parse_tree.h 14 KB

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