parse_tree.h 13 KB

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