tree_and_subtrees.h 11 KB

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