tree_and_subtrees.h 10 KB

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