tree.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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_H_
  5. #define CARBON_TOOLCHAIN_PARSE_TREE_H_
  6. #include <iterator>
  7. #include "common/error.h"
  8. #include "common/ostream.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/ADT/iterator.h"
  12. #include "llvm/ADT/iterator_range.h"
  13. #include "toolchain/diagnostics/diagnostic_emitter.h"
  14. #include "toolchain/lex/tokenized_buffer.h"
  15. #include "toolchain/parse/node_kind.h"
  16. namespace Carbon::Parse {
  17. // A lightweight handle representing a node in the tree.
  18. //
  19. // Objects of this type are small and cheap to copy and store. They don't
  20. // contain any of the information about the node, and serve as a handle that
  21. // can be used with the underlying tree to query for detailed information.
  22. //
  23. // That said, nodes can be compared and are part of a depth-first pre-order
  24. // sequence across all nodes in the parse tree.
  25. struct Node : public ComparableIndexBase {
  26. // An explicitly invalid instance.
  27. static const Node Invalid;
  28. using ComparableIndexBase::ComparableIndexBase;
  29. };
  30. constexpr Node Node::Invalid = Node(Node::InvalidIndex);
  31. // A tree of parsed tokens based on the language grammar.
  32. //
  33. // This is a purely syntactic parse tree without any semantics yet attached. It
  34. // is based on the token stream and the grammar of the language without even
  35. // name lookup.
  36. //
  37. // The tree is designed to make depth-first traversal especially efficient, with
  38. // postorder and reverse postorder (RPO, a topological order) not even requiring
  39. // extra state.
  40. //
  41. // The nodes of the tree follow a flyweight pattern and are handles into the
  42. // tree. The tree itself must be available to query for information about those
  43. // nodes.
  44. //
  45. // Nodes also have a precise one-to-one correspondence to tokens from the parsed
  46. // token stream. Each node can be thought of as the tree-position of a
  47. // particular token from the stream.
  48. //
  49. // The tree is immutable once built, but is designed to support reasonably
  50. // efficient patterns that build a new tree with a specific transformation
  51. // applied.
  52. class Tree : public Printable<Tree> {
  53. public:
  54. class PostorderIterator;
  55. class SiblingIterator;
  56. // Parses the token buffer into a `Tree`.
  57. //
  58. // This is the factory function which is used to build parse trees.
  59. static auto Parse(Lex::TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  60. llvm::raw_ostream* vlog_stream) -> Tree;
  61. // Tests whether there are any errors in the parse tree.
  62. [[nodiscard]] auto has_errors() const -> bool { return has_errors_; }
  63. // Returns the number of nodes in this parse tree.
  64. [[nodiscard]] auto size() const -> int { return node_impls_.size(); }
  65. // Returns an iterable range over the parse tree nodes in depth-first
  66. // postorder.
  67. [[nodiscard]] auto postorder() const
  68. -> llvm::iterator_range<PostorderIterator>;
  69. // Returns an iterable range over the parse tree node and all of its
  70. // descendants in depth-first postorder.
  71. [[nodiscard]] auto postorder(Node n) const
  72. -> llvm::iterator_range<PostorderIterator>;
  73. // Returns an iterable range over the direct children of a node in the parse
  74. // tree. This is a forward range, but is constant time to increment. The order
  75. // of children is the same as would be found in a reverse postorder traversal.
  76. [[nodiscard]] auto children(Node n) const
  77. -> llvm::iterator_range<SiblingIterator>;
  78. // Returns an iterable range over the roots of the parse tree. This is a
  79. // forward range, but is constant time to increment. The order of roots is the
  80. // same as would be found in a reverse postorder traversal.
  81. [[nodiscard]] auto roots() const -> llvm::iterator_range<SiblingIterator>;
  82. // Tests whether a particular node contains an error and may not match the
  83. // full expected structure of the grammar.
  84. [[nodiscard]] auto node_has_error(Node n) const -> bool;
  85. // Returns the kind of the given parse tree node.
  86. [[nodiscard]] auto node_kind(Node n) const -> NodeKind;
  87. // Returns the token the given parse tree node models.
  88. [[nodiscard]] auto node_token(Node n) const -> Lex::Token;
  89. [[nodiscard]] auto node_subtree_size(Node n) const -> int32_t;
  90. // Returns the text backing the token for the given node.
  91. //
  92. // This is a convenience method for chaining from a node through its token to
  93. // the underlying source text.
  94. [[nodiscard]] auto GetNodeText(Node n) const -> llvm::StringRef;
  95. // See the other Print comments.
  96. auto Print(llvm::raw_ostream& output) const -> void;
  97. // Prints a description of the parse tree to the provided `raw_ostream`.
  98. //
  99. // The tree may be printed in either preorder or postorder. Output represents
  100. // each node as a YAML record; in preorder, children are nested.
  101. //
  102. // In both, a node is formatted as:
  103. // ```
  104. // {kind: 'foo', text: '...'}
  105. // ```
  106. //
  107. // The top level is formatted as an array of these nodes.
  108. // ```
  109. // [
  110. // {kind: 'foo', text: '...'},
  111. // {kind: 'foo', text: '...'},
  112. // ...
  113. // ]
  114. // ```
  115. //
  116. // In postorder, nodes are indented in order to indicate depth. For example, a
  117. // node with two children, one of them with an error:
  118. // ```
  119. // {kind: 'bar', text: '...', has_error: yes},
  120. // {kind: 'baz', text: '...'}
  121. // {kind: 'foo', text: '...', subtree_size: 2}
  122. // ```
  123. //
  124. // In preorder, nodes are marked as children with postorder (storage) index.
  125. // For example, a node with two children, one of them with an error:
  126. // ```
  127. // {node_index: 2, kind: 'foo', text: '...', subtree_size: 2, children: [
  128. // {node_index: 0, kind: 'bar', text: '...', has_error: yes},
  129. // {node_index: 1, kind: 'baz', text: '...'}]}
  130. // ```
  131. //
  132. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  133. // on the command line. The format is also reasonably amenable to other
  134. // line-oriented shell tools from `grep` to `awk`.
  135. auto Print(llvm::raw_ostream& output, bool preorder) const -> void;
  136. // Verifies the parse tree structure. Checks invariants of the parse tree
  137. // structure and returns verification errors.
  138. //
  139. // This is primarily intended to be used as a
  140. // debugging aid. This routine doesn't directly CHECK so that it can be used
  141. // within a debugger.
  142. [[nodiscard]] auto Verify() const -> ErrorOr<Success>;
  143. private:
  144. friend class Context;
  145. // The in-memory representation of data used for a particular node in the
  146. // tree.
  147. struct NodeImpl {
  148. explicit NodeImpl(NodeKind kind, bool has_error, Lex::Token token,
  149. int subtree_size)
  150. : kind(kind),
  151. has_error(has_error),
  152. token(token),
  153. subtree_size(subtree_size) {}
  154. // The kind of this node. Note that this is only a single byte.
  155. NodeKind kind;
  156. // We have 3 bytes of padding here that we can pack flags or other compact
  157. // data into.
  158. // Whether this node is or contains a parse error.
  159. //
  160. // When this is true, this node and its children may not have the expected
  161. // grammatical production structure. Prior to reasoning about any specific
  162. // subtree structure, this flag must be checked.
  163. //
  164. // Not every node in the path from the root to an error will have this field
  165. // set to true. However, any node structure that fails to conform to the
  166. // expected grammatical production will be contained within a subtree with
  167. // this flag set. Whether parents of that subtree also have it set is
  168. // optional (and will depend on the particular parse implementation
  169. // strategy). The goal is that you can rely on grammar-based structural
  170. // invariants *until* you encounter a node with this set.
  171. bool has_error = false;
  172. // The token root of this node.
  173. Lex::Token token;
  174. // The size of this node's subtree of the parse tree. This is the number of
  175. // nodes (and thus tokens) that are covered by this node (and its
  176. // descendents) in the parse tree.
  177. //
  178. // During a *reverse* postorder (RPO) traversal of the parse tree, this can
  179. // also be thought of as the offset to the next non-descendant node. When
  180. // this node is not the first child of its parent (which is the last child
  181. // visited in RPO), that is the offset to the next sibling. When this node
  182. // *is* the first child of its parent, this will be an offset to the node's
  183. // parent's next sibling, or if it the parent is also a first child, the
  184. // grandparent's next sibling, and so on.
  185. //
  186. // This field should always be a positive integer as at least this node is
  187. // part of its subtree.
  188. int32_t subtree_size;
  189. };
  190. static_assert(sizeof(NodeImpl) == 12,
  191. "Unexpected size of node implementation!");
  192. // Wires up the reference to the tokenized buffer. The `Parse` function should
  193. // be used to actually parse the tokens into a tree.
  194. explicit Tree(Lex::TokenizedBuffer& tokens_arg) : tokens_(&tokens_arg) {
  195. // If the tree is valid, there will be one node per token, so reserve once.
  196. node_impls_.reserve(tokens_->expected_parse_tree_size());
  197. }
  198. // Prints a single node for Print(). Returns true when preorder and there are
  199. // children.
  200. auto PrintNode(llvm::raw_ostream& output, Node n, int depth,
  201. bool preorder) const -> bool;
  202. // Depth-first postorder sequence of node implementation data.
  203. llvm::SmallVector<NodeImpl> node_impls_;
  204. Lex::TokenizedBuffer* tokens_;
  205. // Indicates if any errors were encountered while parsing.
  206. //
  207. // This doesn't indicate how much of the tree is structurally accurate with
  208. // respect to the grammar. That can be identified by looking at the `HasError`
  209. // flag for a given node (see above for details). This simply indicates that
  210. // some errors were encountered somewhere. A key implication is that when this
  211. // is true we do *not* have the expected 1:1 mapping between tokens and parsed
  212. // nodes as some tokens may have been skipped.
  213. bool has_errors_ = false;
  214. };
  215. // A random-access iterator to the depth-first postorder sequence of parse nodes
  216. // in the parse tree. It produces `Tree::Node` objects which are opaque
  217. // handles and must be used in conjunction with the `Tree` itself.
  218. class Tree::PostorderIterator
  219. : public llvm::iterator_facade_base<PostorderIterator,
  220. std::random_access_iterator_tag, Node,
  221. int, Node*, Node>,
  222. public Printable<Tree::PostorderIterator> {
  223. public:
  224. PostorderIterator() = delete;
  225. auto operator==(const PostorderIterator& rhs) const -> bool {
  226. return node_ == rhs.node_;
  227. }
  228. auto operator<(const PostorderIterator& rhs) const -> bool {
  229. return node_ < rhs.node_;
  230. }
  231. auto operator*() const -> Node { return node_; }
  232. auto operator-(const PostorderIterator& rhs) const -> int {
  233. return node_.index - rhs.node_.index;
  234. }
  235. auto operator+=(int offset) -> PostorderIterator& {
  236. node_.index += offset;
  237. return *this;
  238. }
  239. auto operator-=(int offset) -> PostorderIterator& {
  240. node_.index -= offset;
  241. return *this;
  242. }
  243. // Prints the underlying node index.
  244. auto Print(llvm::raw_ostream& output) const -> void;
  245. private:
  246. friend class Tree;
  247. explicit PostorderIterator(Node n) : node_(n) {}
  248. Node node_;
  249. };
  250. // A forward iterator across the siblings at a particular level in the parse
  251. // tree. It produces `Tree::Node` objects which are opaque handles and must
  252. // be used in conjunction with the `Tree` itself.
  253. //
  254. // While this is a forward iterator and may not have good locality within the
  255. // `Tree` data structure, it is still constant time to increment and
  256. // suitable for algorithms relying on that property.
  257. //
  258. // The siblings are discovered through a reverse postorder (RPO) tree traversal
  259. // (which is made constant time through cached distance information), and so the
  260. // relative order of siblings matches their RPO order.
  261. class Tree::SiblingIterator
  262. : public llvm::iterator_facade_base<
  263. SiblingIterator, std::forward_iterator_tag, Node, int, Node*, Node>,
  264. public Printable<Tree::SiblingIterator> {
  265. public:
  266. explicit SiblingIterator() = delete;
  267. auto operator==(const SiblingIterator& rhs) const -> bool {
  268. return node_ == rhs.node_;
  269. }
  270. auto operator<(const SiblingIterator& rhs) const -> bool {
  271. // Note that child iterators walk in reverse compared to the postorder
  272. // index.
  273. return node_ > rhs.node_;
  274. }
  275. auto operator*() const -> Node { return node_; }
  276. using iterator_facade_base::operator++;
  277. auto operator++() -> SiblingIterator& {
  278. node_.index -= std::abs(tree_->node_impls_[node_.index].subtree_size);
  279. return *this;
  280. }
  281. // Prints the underlying node index.
  282. auto Print(llvm::raw_ostream& output) const -> void;
  283. private:
  284. friend class Tree;
  285. explicit SiblingIterator(const Tree& tree_arg, Node n)
  286. : tree_(&tree_arg), node_(n) {}
  287. const Tree* tree_;
  288. Node node_;
  289. };
  290. } // namespace Carbon::Parse
  291. #endif // CARBON_TOOLCHAIN_PARSE_TREE_H_