tree_and_subtrees.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_PARSE_TREE_AND_SUBTREES_H_
  5. #define CARBON_TOOLCHAIN_PARSE_TREE_AND_SUBTREES_H_
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "toolchain/base/fixed_size_value_store.h"
  8. #include "toolchain/lex/token_index.h"
  9. #include "toolchain/parse/tree.h"
  10. namespace Carbon::Parse {
  11. // Calculates and stores subtree data for a parse tree. Supports APIs that
  12. // require subtree knowledge.
  13. //
  14. // This requires a complete tree.
  15. class TreeAndSubtrees {
  16. public:
  17. class SiblingIterator;
  18. explicit TreeAndSubtrees(const Lex::TokenizedBuffer& tokens,
  19. const Tree& tree);
  20. // The following `Extract*` function provide an alternative way of accessing
  21. // the nodes of a tree. It is intended to be more convenient and type-safe,
  22. // but slower and can't be used on nodes that are marked as having an error.
  23. // It is appropriate for uses that are less performance sensitive, like
  24. // diagnostics. Example usage:
  25. // ```
  26. // auto file = tree->ExtractFile();
  27. // for (AnyDeclId decl_id : file.decls) {
  28. // // `decl_id` is convertible to a `NodeId`.
  29. // if (std::optional<FunctionDecl> fn_decl =
  30. // tree->ExtractAs<FunctionDecl>(decl_id)) {
  31. // // fn_decl->params is a `TuplePatternId` (which extends `NodeId`)
  32. // // that is guaranteed to reference a `TuplePattern`.
  33. // std::optional<TuplePattern> params = tree->Extract(fn_decl->params);
  34. // // `params` has a value unless there was an error in that node.
  35. // } else if (auto class_def = tree->ExtractAs<ClassDefinition>(decl_id)) {
  36. // // ...
  37. // }
  38. // }
  39. // ```
  40. // Extract a `File` object representing the parse tree for the whole file.
  41. // #include "toolchain/parse/typed_nodes.h" to get the definition of `File`
  42. // and the types representing its children nodes. This is implemented in
  43. // extract.cpp.
  44. auto ExtractFile() const -> File;
  45. // Converts this node_id to a typed node of a specified type, if it is a valid
  46. // node of that kind.
  47. template <typename T>
  48. auto ExtractAs(NodeId node_id) const -> std::optional<T>;
  49. // Converts to a typed node, if it is not an error.
  50. template <typename IdT>
  51. auto Extract(IdT id) const
  52. -> std::optional<typename NodeForId<IdT>::TypedNode>;
  53. // Verifies that each node in the tree can be successfully extracted.
  54. //
  55. // This is fairly slow, and is primarily intended to be used as a debugging
  56. // aid. This doesn't directly CHECK so that it can be used within a debugger.
  57. auto Verify() const -> ErrorOr<Success>;
  58. // Prints the parse tree in postorder format. See also use PrintPreorder.
  59. //
  60. // Output represents each node as a YAML record. A node is formatted as:
  61. // ```
  62. // {kind: 'foo', text: '...'}
  63. // ```
  64. //
  65. // The top level is formatted as an array of these nodes.
  66. // ```
  67. // [
  68. // {kind: 'foo', text: '...'},
  69. // {kind: 'foo', text: '...'},
  70. // ...
  71. // ]
  72. // ```
  73. //
  74. // Nodes are indented in order to indicate depth. For example, a node with two
  75. // children, one of them with an error:
  76. // ```
  77. // {kind: 'bar', text: '...', has_error: yes},
  78. // {kind: 'baz', text: '...'}
  79. // {kind: 'foo', text: '...', subtree_size: 2}
  80. // ```
  81. //
  82. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  83. // on the command line. The format is also reasonably amenable to other
  84. // line-oriented shell tools from `grep` to `awk`.
  85. auto Print(llvm::raw_ostream& output) const -> void;
  86. // Prints the parse tree in preorder. The format is YAML, and similar to
  87. // Print. However, nodes are marked as children with postorder (storage)
  88. // index. For example, a node with two children, one of them with an error:
  89. // ```
  90. // {node_index: 2, kind: 'foo', text: '...', subtree_size: 2, children: [
  91. // {node_index: 0, kind: 'bar', text: '...', has_error: yes},
  92. // {node_index: 1, kind: 'baz', text: '...'}]}
  93. // ```
  94. auto PrintPreorder(llvm::raw_ostream& output) const -> void;
  95. // Collects memory usage of members.
  96. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  97. -> void;
  98. // Returns the range of tokens in the node's subtree.
  99. auto GetSubtreeTokenRange(NodeId node_id) const -> Lex::InclusiveTokenRange;
  100. // Converts the node to a diagnostic location, covering either the full
  101. // subtree or only the token.
  102. auto NodeToDiagnosticLoc(NodeId node_id, bool token_only) const
  103. -> Diagnostics::ConvertedLoc;
  104. // Returns an iterable range over the parse tree node and all of its
  105. // descendants in depth-first postorder.
  106. auto postorder(NodeId n) const
  107. -> llvm::iterator_range<Tree::PostorderIterator>;
  108. // Returns an iterable range over the direct children of a node in the parse
  109. // tree. This is a forward range, but is constant time to increment. The order
  110. // of children is the same as would be found in a reverse postorder traversal.
  111. auto children(NodeId n) const -> llvm::iterator_range<SiblingIterator>;
  112. // Returns an iterable range over the roots of the parse tree. This is a
  113. // forward range, but is constant time to increment. The order of roots is the
  114. // same as would be found in a reverse postorder traversal.
  115. auto roots() const -> llvm::iterator_range<SiblingIterator>;
  116. auto tree() const -> const Tree& { return *tree_; }
  117. private:
  118. friend class TypedNodesTestPeer;
  119. // Extract a node of type `T` from a sibling range. This is expected to
  120. // consume the complete sibling range. Malformed tree errors are written
  121. // to `*trace`, if `trace != nullptr`. This is implemented in extract.cpp.
  122. template <typename T>
  123. auto TryExtractNodeFromChildren(
  124. NodeId node_id, llvm::iterator_range<SiblingIterator> children,
  125. ErrorBuilder* trace) const -> std::optional<T>;
  126. // Extract a node of type `T` from a sibling range. This is expected to
  127. // consume the complete sibling range. Malformed tree errors are fatal.
  128. template <typename T>
  129. auto ExtractNodeFromChildren(
  130. NodeId node_id, llvm::iterator_range<SiblingIterator> children) const
  131. -> T;
  132. // Like ExtractAs(), but malformed tree errors are not fatal. Should only be
  133. // used by `Verify()` or by tests.
  134. template <typename T>
  135. auto VerifyExtractAs(NodeId node_id, ErrorBuilder* trace) const
  136. -> std::optional<T>;
  137. // Wrapper around `VerifyExtractAs` to dispatch based on a runtime node kind.
  138. // Returns true if extraction was successful.
  139. auto VerifyExtract(NodeId node_id, NodeKind kind, ErrorBuilder* trace) const
  140. -> bool;
  141. // Prints a single node for Print(). Returns true when preorder and there are
  142. // children.
  143. auto PrintNode(llvm::raw_ostream& output, NodeId n, int depth,
  144. bool preorder) const -> bool;
  145. // The associated tokens.
  146. const Lex::TokenizedBuffer* tokens_;
  147. // The associated tree.
  148. const Tree* tree_;
  149. // For each node in the tree, the size of the node's subtree. This is the
  150. // number of nodes (and thus tokens) that are covered by the node (and its
  151. // descendents) in the parse tree. It's one for nodes with no children.
  152. //
  153. // During a *reverse* postorder (RPO) traversal of the parse tree, this can
  154. // also be thought of as the offset to the next non-descendant node. When the
  155. // node is not the first child of its parent (which is the last child visited
  156. // in RPO), that is the offset to the next sibling. When the node *is* the
  157. // first child of its parent, this will be an offset to the node's parent's
  158. // next sibling, or if it the parent is also a first child, the grandparent's
  159. // next sibling, and so on.
  160. using SubtreeSizeStore = FixedSizeValueStore<NodeId, int32_t>;
  161. SubtreeSizeStore subtree_sizes_;
  162. };
  163. // A standard signature for a callback to support lazy construction.
  164. using GetTreeAndSubtreesFn = llvm::function_ref<auto()->const TreeAndSubtrees&>;
  165. // A forward iterator across the siblings at a particular level in the parse
  166. // tree. It produces `Tree::NodeId` objects which are opaque handles and must
  167. // be used in conjunction with the `Tree` itself.
  168. //
  169. // While this is a forward iterator and may not have good locality within the
  170. // `Tree` data structure, it is still constant time to increment and
  171. // suitable for algorithms relying on that property.
  172. //
  173. // The siblings are discovered through a reverse postorder (RPO) tree traversal
  174. // (which is made constant time through cached distance information), and so the
  175. // relative order of siblings matches their RPO order.
  176. class TreeAndSubtrees::SiblingIterator
  177. : public llvm::iterator_facade_base<SiblingIterator,
  178. std::forward_iterator_tag, NodeId, int,
  179. const NodeId*, NodeId>,
  180. public Printable<SiblingIterator> {
  181. public:
  182. explicit SiblingIterator() = delete;
  183. friend auto operator==(const SiblingIterator& lhs, const SiblingIterator& rhs)
  184. -> bool {
  185. return lhs.node_ == rhs.node_;
  186. }
  187. auto operator*() const -> NodeId { return node_; }
  188. using iterator_facade_base::operator++;
  189. auto operator++() -> SiblingIterator& {
  190. node_.index -= tree_->subtree_sizes_.Get(node_);
  191. return *this;
  192. }
  193. // Prints the underlying node index.
  194. auto Print(llvm::raw_ostream& output) const -> void;
  195. private:
  196. friend class TreeAndSubtrees;
  197. explicit SiblingIterator(const TreeAndSubtrees& tree, NodeId node)
  198. : tree_(&tree), node_(node) {}
  199. const TreeAndSubtrees* tree_;
  200. NodeId node_;
  201. };
  202. template <typename T>
  203. auto TreeAndSubtrees::ExtractNodeFromChildren(
  204. NodeId node_id, llvm::iterator_range<SiblingIterator> children) const -> T {
  205. auto result = TryExtractNodeFromChildren<T>(node_id, children, nullptr);
  206. if (!result.has_value()) {
  207. // On error try again, this time capturing a trace.
  208. ErrorBuilder trace;
  209. TryExtractNodeFromChildren<T>(node_id, children, &trace);
  210. CARBON_FATAL("Malformed parse node:\n{0}",
  211. static_cast<Error>(trace).message());
  212. }
  213. return *result;
  214. }
  215. template <typename T>
  216. auto TreeAndSubtrees::ExtractAs(NodeId node_id) const -> std::optional<T> {
  217. static_assert(HasKindMember<T>, "Not a parse node type");
  218. if (!tree_->IsValid<T>(node_id)) {
  219. return std::nullopt;
  220. }
  221. return ExtractNodeFromChildren<T>(node_id, children(node_id));
  222. }
  223. template <typename T>
  224. auto TreeAndSubtrees::VerifyExtractAs(NodeId node_id, ErrorBuilder* trace) const
  225. -> std::optional<T> {
  226. static_assert(HasKindMember<T>, "Not a parse node type");
  227. if (!tree_->IsValid<T>(node_id)) {
  228. if (trace) {
  229. *trace << "VerifyExtractAs error: wrong kind "
  230. << tree_->node_kind(node_id) << ", expected " << T::Kind << "\n";
  231. }
  232. return std::nullopt;
  233. }
  234. return TryExtractNodeFromChildren<T>(node_id, children(node_id), trace);
  235. }
  236. template <typename IdT>
  237. auto TreeAndSubtrees::Extract(IdT id) const
  238. -> std::optional<typename NodeForId<IdT>::TypedNode> {
  239. if (!tree_->IsValid(id)) {
  240. return std::nullopt;
  241. }
  242. using T = typename NodeForId<IdT>::TypedNode;
  243. return ExtractNodeFromChildren<T>(id, children(id));
  244. }
  245. } // namespace Carbon::Parse
  246. #endif // CARBON_TOOLCHAIN_PARSE_TREE_AND_SUBTREES_H_