tree_and_subtrees.h 11 KB

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