tree.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. // See the other Print comments.
  91. auto Print(llvm::raw_ostream& output) const -> void;
  92. // Prints a description of the parse tree to the provided `raw_ostream`.
  93. //
  94. // The tree may be printed in either preorder or postorder. Output represents
  95. // each node as a YAML record; in preorder, children are nested.
  96. //
  97. // In both, a node is formatted as:
  98. // ```
  99. // {kind: 'foo', text: '...'}
  100. // ```
  101. //
  102. // The top level is formatted as an array of these nodes.
  103. // ```
  104. // [
  105. // {kind: 'foo', text: '...'},
  106. // {kind: 'foo', text: '...'},
  107. // ...
  108. // ]
  109. // ```
  110. //
  111. // In postorder, nodes are indented in order to indicate depth. For example, a
  112. // node with two children, one of them with an error:
  113. // ```
  114. // {kind: 'bar', text: '...', has_error: yes},
  115. // {kind: 'baz', text: '...'}
  116. // {kind: 'foo', text: '...', subtree_size: 2}
  117. // ```
  118. //
  119. // In preorder, nodes are marked as children with postorder (storage) index.
  120. // For example, a node with two children, one of them with an error:
  121. // ```
  122. // {node_index: 2, kind: 'foo', text: '...', subtree_size: 2, children: [
  123. // {node_index: 0, kind: 'bar', text: '...', has_error: yes},
  124. // {node_index: 1, kind: 'baz', text: '...'}]}
  125. // ```
  126. //
  127. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  128. // on the command line. The format is also reasonably amenable to other
  129. // line-oriented shell tools from `grep` to `awk`.
  130. auto Print(llvm::raw_ostream& output, bool preorder) const -> void;
  131. // Verifies the parse tree structure. Checks invariants of the parse tree
  132. // structure and returns verification errors.
  133. //
  134. // This is primarily intended to be used as a
  135. // debugging aid. This routine doesn't directly CHECK so that it can be used
  136. // within a debugger.
  137. [[nodiscard]] auto Verify() const -> ErrorOr<Success>;
  138. private:
  139. friend class Context;
  140. // The in-memory representation of data used for a particular node in the
  141. // tree.
  142. struct NodeImpl {
  143. explicit NodeImpl(NodeKind kind, bool has_error, Lex::Token token,
  144. int subtree_size)
  145. : kind(kind),
  146. has_error(has_error),
  147. token(token),
  148. subtree_size(subtree_size) {}
  149. // The kind of this node. Note that this is only a single byte.
  150. NodeKind kind;
  151. // We have 3 bytes of padding here that we can pack flags or other compact
  152. // data into.
  153. // Whether this node is or contains a parse error.
  154. //
  155. // When this is true, this node and its children may not have the expected
  156. // grammatical production structure. Prior to reasoning about any specific
  157. // subtree structure, this flag must be checked.
  158. //
  159. // Not every node in the path from the root to an error will have this field
  160. // set to true. However, any node structure that fails to conform to the
  161. // expected grammatical production will be contained within a subtree with
  162. // this flag set. Whether parents of that subtree also have it set is
  163. // optional (and will depend on the particular parse implementation
  164. // strategy). The goal is that you can rely on grammar-based structural
  165. // invariants *until* you encounter a node with this set.
  166. bool has_error = false;
  167. // The token root of this node.
  168. Lex::Token token;
  169. // The size of this node's subtree of the parse tree. This is the number of
  170. // nodes (and thus tokens) that are covered by this node (and its
  171. // descendents) in the parse tree.
  172. //
  173. // During a *reverse* postorder (RPO) traversal of the parse tree, this can
  174. // also be thought of as the offset to the next non-descendant node. When
  175. // this node is not the first child of its parent (which is the last child
  176. // visited in RPO), that is the offset to the next sibling. When this node
  177. // *is* the first child of its parent, this will be an offset to the node's
  178. // parent's next sibling, or if it the parent is also a first child, the
  179. // grandparent's next sibling, and so on.
  180. //
  181. // This field should always be a positive integer as at least this node is
  182. // part of its subtree.
  183. int32_t subtree_size;
  184. };
  185. static_assert(sizeof(NodeImpl) == 12,
  186. "Unexpected size of node implementation!");
  187. // Wires up the reference to the tokenized buffer. The `Parse` function should
  188. // be used to actually parse the tokens into a tree.
  189. explicit Tree(Lex::TokenizedBuffer& tokens_arg) : tokens_(&tokens_arg) {
  190. // If the tree is valid, there will be one node per token, so reserve once.
  191. node_impls_.reserve(tokens_->expected_parse_tree_size());
  192. }
  193. // Prints a single node for Print(). Returns true when preorder and there are
  194. // children.
  195. auto PrintNode(llvm::raw_ostream& output, Node n, int depth,
  196. bool preorder) const -> bool;
  197. // Depth-first postorder sequence of node implementation data.
  198. llvm::SmallVector<NodeImpl> node_impls_;
  199. Lex::TokenizedBuffer* tokens_;
  200. // Indicates if any errors were encountered while parsing.
  201. //
  202. // This doesn't indicate how much of the tree is structurally accurate with
  203. // respect to the grammar. That can be identified by looking at the `HasError`
  204. // flag for a given node (see above for details). This simply indicates that
  205. // some errors were encountered somewhere. A key implication is that when this
  206. // is true we do *not* have the expected 1:1 mapping between tokens and parsed
  207. // nodes as some tokens may have been skipped.
  208. bool has_errors_ = false;
  209. };
  210. // A random-access iterator to the depth-first postorder sequence of parse nodes
  211. // in the parse tree. It produces `Tree::Node` objects which are opaque
  212. // handles and must be used in conjunction with the `Tree` itself.
  213. class Tree::PostorderIterator
  214. : public llvm::iterator_facade_base<PostorderIterator,
  215. std::random_access_iterator_tag, Node,
  216. int, Node*, Node>,
  217. public Printable<Tree::PostorderIterator> {
  218. public:
  219. PostorderIterator() = delete;
  220. auto operator==(const PostorderIterator& rhs) const -> bool {
  221. return node_ == rhs.node_;
  222. }
  223. auto operator<(const PostorderIterator& rhs) const -> bool {
  224. return node_ < rhs.node_;
  225. }
  226. auto operator*() const -> Node { return node_; }
  227. auto operator-(const PostorderIterator& rhs) const -> int {
  228. return node_.index - rhs.node_.index;
  229. }
  230. auto operator+=(int offset) -> PostorderIterator& {
  231. node_.index += offset;
  232. return *this;
  233. }
  234. auto operator-=(int offset) -> PostorderIterator& {
  235. node_.index -= offset;
  236. return *this;
  237. }
  238. // Prints the underlying node index.
  239. auto Print(llvm::raw_ostream& output) const -> void;
  240. private:
  241. friend class Tree;
  242. explicit PostorderIterator(Node n) : node_(n) {}
  243. Node node_;
  244. };
  245. // A forward iterator across the siblings at a particular level in the parse
  246. // tree. It produces `Tree::Node` objects which are opaque handles and must
  247. // be used in conjunction with the `Tree` itself.
  248. //
  249. // While this is a forward iterator and may not have good locality within the
  250. // `Tree` data structure, it is still constant time to increment and
  251. // suitable for algorithms relying on that property.
  252. //
  253. // The siblings are discovered through a reverse postorder (RPO) tree traversal
  254. // (which is made constant time through cached distance information), and so the
  255. // relative order of siblings matches their RPO order.
  256. class Tree::SiblingIterator
  257. : public llvm::iterator_facade_base<
  258. SiblingIterator, std::forward_iterator_tag, Node, int, Node*, Node>,
  259. public Printable<Tree::SiblingIterator> {
  260. public:
  261. explicit SiblingIterator() = delete;
  262. auto operator==(const SiblingIterator& rhs) const -> bool {
  263. return node_ == rhs.node_;
  264. }
  265. auto operator<(const SiblingIterator& rhs) const -> bool {
  266. // Note that child iterators walk in reverse compared to the postorder
  267. // index.
  268. return node_ > rhs.node_;
  269. }
  270. auto operator*() const -> Node { return node_; }
  271. using iterator_facade_base::operator++;
  272. auto operator++() -> SiblingIterator& {
  273. node_.index -= std::abs(tree_->node_impls_[node_.index].subtree_size);
  274. return *this;
  275. }
  276. // Prints the underlying node index.
  277. auto Print(llvm::raw_ostream& output) const -> void;
  278. private:
  279. friend class Tree;
  280. explicit SiblingIterator(const Tree& tree_arg, Node n)
  281. : tree_(&tree_arg), node_(n) {}
  282. const Tree* tree_;
  283. Node node_;
  284. };
  285. } // namespace Carbon::Parse
  286. #endif // CARBON_TOOLCHAIN_PARSE_TREE_H_