parse_tree.h 13 KB

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