parse_tree.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 has_errors() 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 node_has_error(Node n) const -> bool;
  76. // Returns the kind of the given parse tree node.
  77. [[nodiscard]] auto node_kind(Node n) const -> ParseNodeKind;
  78. // Returns the token the given parse tree node models.
  79. [[nodiscard]] auto node_token(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 index() const -> int { return index_; }
  224. // Prints the node index.
  225. auto Print(llvm::raw_ostream& output) const -> void;
  226. // Returns true if the node is valid; in other words, it was not default
  227. // initialized.
  228. auto is_valid() -> bool { return index_ != InvalidValue; }
  229. private:
  230. friend ParseTree;
  231. friend Parser;
  232. friend PostorderIterator;
  233. friend SiblingIterator;
  234. // Value for uninitialized nodes.
  235. static constexpr int InvalidValue = -1;
  236. // Constructs a node with a specific index into the parse tree's postorder
  237. // sequence of node implementations.
  238. explicit Node(int index) : index_(index) {}
  239. // The index of this node's implementation in the postorder sequence.
  240. int32_t index_ = InvalidValue;
  241. };
  242. // A random-access iterator to the depth-first postorder sequence of parse nodes
  243. // in the parse tree. It produces `ParseTree::Node` objects which are opaque
  244. // handles and must be used in conjunction with the `ParseTree` itself.
  245. class ParseTree::PostorderIterator
  246. : public llvm::iterator_facade_base<PostorderIterator,
  247. std::random_access_iterator_tag, Node,
  248. int, Node*, Node> {
  249. public:
  250. // Default construction is only provided to satisfy iterator requirements. It
  251. // produces an unusable iterator, and you must assign a valid iterator to it
  252. // before performing any operations.
  253. PostorderIterator() = default;
  254. auto operator==(const PostorderIterator& rhs) const -> bool {
  255. return node_ == rhs.node_;
  256. }
  257. auto operator<(const PostorderIterator& rhs) const -> bool {
  258. return node_ < rhs.node_;
  259. }
  260. auto operator*() const -> Node { return node_; }
  261. auto operator-(const PostorderIterator& rhs) const -> int {
  262. return node_.index_ - rhs.node_.index_;
  263. }
  264. auto operator+=(int offset) -> PostorderIterator& {
  265. node_.index_ += offset;
  266. return *this;
  267. }
  268. auto operator-=(int offset) -> PostorderIterator& {
  269. node_.index_ -= offset;
  270. return *this;
  271. }
  272. // Prints the underlying node index.
  273. auto Print(llvm::raw_ostream& output) const -> void;
  274. private:
  275. friend class ParseTree;
  276. explicit PostorderIterator(Node n) : node_(n) {}
  277. Node node_;
  278. };
  279. // A forward iterator across the silbings at a particular level in the parse
  280. // tree. It produces `ParseTree::Node` objects which are opaque handles and must
  281. // be used in conjunction with the `ParseTree` itself.
  282. //
  283. // While this is a forward iterator and may not have good locality within the
  284. // `ParseTree` data structure, it is still constant time to increment and
  285. // suitable for algorithms relying on that property.
  286. //
  287. // The siblings are discovered through a reverse postorder (RPO) tree traversal
  288. // (which is made constant time through cached distance information), and so the
  289. // relative order of siblings matches their RPO order.
  290. class ParseTree::SiblingIterator
  291. : public llvm::iterator_facade_base<
  292. SiblingIterator, std::forward_iterator_tag, Node, int, Node*, Node> {
  293. public:
  294. SiblingIterator() = default;
  295. auto operator==(const SiblingIterator& rhs) const -> bool {
  296. return node_ == rhs.node_;
  297. }
  298. auto operator<(const SiblingIterator& rhs) const -> bool {
  299. // Note that child iterators walk in reverse compared to the postorder
  300. // index.
  301. return node_ > rhs.node_;
  302. }
  303. auto operator*() const -> Node { return node_; }
  304. using iterator_facade_base::operator++;
  305. auto operator++() -> SiblingIterator& {
  306. node_.index_ -= std::abs(tree_->node_impls_[node_.index_].subtree_size);
  307. return *this;
  308. }
  309. // Prints the underlying node index.
  310. auto Print(llvm::raw_ostream& output) const -> void;
  311. private:
  312. friend class ParseTree;
  313. explicit SiblingIterator(const ParseTree& tree_arg, Node n)
  314. : tree_(&tree_arg), node_(n) {}
  315. const ParseTree* tree_;
  316. Node node_;
  317. };
  318. } // namespace Carbon
  319. #endif // TOOLCHAIN_PARSER_PARSE_TREE_H_