parse_tree.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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/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. [[nodiscard]] auto node_subtree_size(Node n) const -> int32_t;
  81. // Returns the text backing the token for the given node.
  82. //
  83. // This is a convenience method for chaining from a node through its token to
  84. // the underlying source text.
  85. [[nodiscard]] auto GetNodeText(Node n) const -> llvm::StringRef;
  86. // See the other Print comments.
  87. auto Print(llvm::raw_ostream& output) const -> void;
  88. // Prints a description of the parse tree to the provided `raw_ostream`.
  89. //
  90. // The tree may be printed in either preorder or postorder. Output represents
  91. // each node as a YAML record; in preorder, children are nested.
  92. //
  93. // In both, a node is formatted as:
  94. // ```
  95. // {kind: 'foo', text: '...'}
  96. // ```
  97. //
  98. // The top level is formatted as an array of these nodes.
  99. // ```
  100. // [
  101. // {kind: 'foo', text: '...'},
  102. // {kind: 'foo', text: '...'},
  103. // ...
  104. // ]
  105. // ```
  106. //
  107. // In postorder, nodes are indented in order to indicate depth. For example, a
  108. // node with two children, one of them with an error:
  109. // ```
  110. // {kind: 'bar', text: '...', has_error: yes},
  111. // {kind: 'baz', text: '...'}
  112. // {kind: 'foo', text: '...', subtree_size: 2}
  113. // ```
  114. //
  115. // In preorder, nodes are marked as children with postorder (storage) index.
  116. // For example, a node with two children, one of them with an error:
  117. // ```
  118. // {node_index: 2, kind: 'foo', text: '...', subtree_size: 2, children: [
  119. // {node_index: 0, kind: 'bar', text: '...', has_error: yes},
  120. // {node_index: 1, kind: 'baz', text: '...'}]}
  121. // ```
  122. //
  123. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  124. // on the command line. The format is also reasonably amenable to other
  125. // line-oriented shell tools from `grep` to `awk`.
  126. auto Print(llvm::raw_ostream& output, bool preorder) const -> void;
  127. // Verifies the parse tree structure.
  128. //
  129. // This tries to check any invariants of the parse tree structure and write
  130. // out information about it to stderr. Returns false if anything fails to
  131. // verify. This is primarily intended to be used as a debugging aid. A typical
  132. // usage is to `assert` on the result. This routine doesn't directly assert so
  133. // that it can be used even when asserts are disabled or within a debugger.
  134. [[nodiscard]] auto Verify() const -> bool;
  135. private:
  136. class Parser;
  137. friend Parser;
  138. friend class Parser2;
  139. // The in-memory representation of data used for a particular node in the
  140. // tree.
  141. struct NodeImpl {
  142. explicit NodeImpl(ParseNodeKind k, TokenizedBuffer::Token t,
  143. int subtree_size_arg)
  144. : kind(k), token(t), subtree_size(subtree_size_arg) {}
  145. // TODO: Parser2 only uses this construct. Can remove the other if we
  146. // switch.
  147. NodeImpl(ParseNodeKind kind, bool has_error, TokenizedBuffer::Token token,
  148. int subtree_size)
  149. : kind(kind),
  150. has_error(has_error),
  151. token(token),
  152. subtree_size(subtree_size) {}
  153. // The kind of this node. Note that this is only a single byte.
  154. ParseNodeKind kind;
  155. // We have 3 bytes of padding here that we can pack flags or other compact
  156. // data into.
  157. // Whether this node is or contains a parse error.
  158. //
  159. // When this is true, this node and its children may not have the expected
  160. // grammatical production structure. Prior to reasoning about any specific
  161. // subtree structure, this flag must be checked.
  162. //
  163. // Not every node in the path from the root to an error will have this field
  164. // set to true. However, any node structure that fails to conform to the
  165. // expected grammatical production will be contained within a subtree with
  166. // this flag set. Whether parents of that subtree also have it set is
  167. // optional (and will depend on the particular parse implementation
  168. // strategy). The goal is that you can rely on grammar-based structural
  169. // invariants *until* you encounter a node with this set.
  170. bool has_error = false;
  171. // The token root of this node.
  172. TokenizedBuffer::Token token;
  173. // The size of this node's subtree of the parse tree. This is the number of
  174. // nodes (and thus tokens) that are covered by this node (and its
  175. // descendents) in the parse tree.
  176. //
  177. // During a *reverse* postorder (RPO) traversal of the parse tree, this can
  178. // also be thought of as the offset to the next non-descendant node. When
  179. // this node is not the first child of its parent (which is the last child
  180. // visited in RPO), that is the offset to the next sibling. When this node
  181. // *is* the first child of its parent, this will be an offset to the node's
  182. // parent's next sibling, or if it the parent is also a first child, the
  183. // grandparent's next sibling, and so on.
  184. //
  185. // This field should always be a positive integer as at least this node is
  186. // part of its subtree.
  187. int32_t subtree_size;
  188. };
  189. static_assert(sizeof(NodeImpl) == 12,
  190. "Unexpected size of node implementation!");
  191. // Wires up the reference to the tokenized buffer. The global `parse` routine
  192. // should be used to actually parse the tokens into a tree.
  193. explicit ParseTree(TokenizedBuffer& tokens_arg) : tokens_(&tokens_arg) {}
  194. // Prints a single node for Print(). Returns true when preorder and there are
  195. // children.
  196. auto PrintNode(llvm::raw_ostream& output, Node n, int depth,
  197. bool preorder) const -> bool;
  198. // Depth-first postorder sequence of node implementation data.
  199. llvm::SmallVector<NodeImpl, 0> node_impls_;
  200. TokenizedBuffer* tokens_;
  201. // Indicates if any errors were encountered while parsing.
  202. //
  203. // This doesn't indicate how much of the tree is structurally accurate with
  204. // respect to the grammar. That can be identified by looking at the `HasError`
  205. // flag for a given node (see above for details). This simply indicates that
  206. // some errors were encountered somewhere. A key implication is that when this
  207. // is true we do *not* have the expected 1:1 mapping between tokens and parsed
  208. // nodes as some tokens may have been skipped.
  209. bool has_errors_ = false;
  210. };
  211. // A lightweight handle representing a node in the tree.
  212. //
  213. // Objects of this type are small and cheap to copy and store. They don't
  214. // contain any of the information about the node, and serve as a handle that
  215. // can be used with the underlying tree to query for detailed information.
  216. //
  217. // That said, nodes can be compared and are part of a depth-first pre-order
  218. // sequence across all nodes in the parse tree.
  219. class ParseTree::Node {
  220. public:
  221. // Node handles are default constructable, but such a node cannot be used
  222. // for anything. It just allows it to be initialized later through
  223. // assignment. Any other operation on a default constructed node is an
  224. // error.
  225. Node() = default;
  226. friend auto operator==(Node lhs, Node rhs) -> bool {
  227. return lhs.index_ == rhs.index_;
  228. }
  229. friend auto operator!=(Node lhs, Node rhs) -> bool {
  230. return lhs.index_ != rhs.index_;
  231. }
  232. friend auto operator<(Node lhs, Node rhs) -> bool {
  233. return lhs.index_ < rhs.index_;
  234. }
  235. friend auto operator<=(Node lhs, Node rhs) -> bool {
  236. return lhs.index_ <= rhs.index_;
  237. }
  238. friend auto operator>(Node lhs, Node rhs) -> bool {
  239. return lhs.index_ > rhs.index_;
  240. }
  241. friend auto operator>=(Node lhs, Node rhs) -> bool {
  242. return lhs.index_ >= rhs.index_;
  243. }
  244. // Returns an opaque integer identifier of the node in the tree. Clients
  245. // should not expect any particular semantics from this value.
  246. //
  247. // TODO: Maybe we can switch to stream operator overloads?
  248. [[nodiscard]] auto index() const -> int { return index_; }
  249. // Prints the node index.
  250. auto Print(llvm::raw_ostream& output) const -> void;
  251. // Returns true if the node is valid; in other words, it was not default
  252. // initialized.
  253. auto is_valid() -> bool { return index_ != InvalidValue; }
  254. private:
  255. friend ParseTree;
  256. friend Parser;
  257. friend PostorderIterator;
  258. friend SiblingIterator;
  259. // Value for uninitialized nodes.
  260. static constexpr int InvalidValue = -1;
  261. // Constructs a node with a specific index into the parse tree's postorder
  262. // sequence of node implementations.
  263. explicit Node(int index) : index_(index) {}
  264. // The index of this node's implementation in the postorder sequence.
  265. int32_t index_ = InvalidValue;
  266. };
  267. // A random-access iterator to the depth-first postorder sequence of parse nodes
  268. // in the parse tree. It produces `ParseTree::Node` objects which are opaque
  269. // handles and must be used in conjunction with the `ParseTree` itself.
  270. class ParseTree::PostorderIterator
  271. : public llvm::iterator_facade_base<PostorderIterator,
  272. std::random_access_iterator_tag, Node,
  273. int, Node*, Node> {
  274. public:
  275. // Default construction is only provided to satisfy iterator requirements. It
  276. // produces an unusable iterator, and you must assign a valid iterator to it
  277. // before performing any operations.
  278. PostorderIterator() = default;
  279. auto operator==(const PostorderIterator& rhs) const -> bool {
  280. return node_ == rhs.node_;
  281. }
  282. auto operator<(const PostorderIterator& rhs) const -> bool {
  283. return node_ < rhs.node_;
  284. }
  285. auto operator*() const -> Node { return node_; }
  286. auto operator-(const PostorderIterator& rhs) const -> int {
  287. return node_.index_ - rhs.node_.index_;
  288. }
  289. auto operator+=(int offset) -> PostorderIterator& {
  290. node_.index_ += offset;
  291. return *this;
  292. }
  293. auto operator-=(int offset) -> PostorderIterator& {
  294. node_.index_ -= offset;
  295. return *this;
  296. }
  297. // Prints the underlying node index.
  298. auto Print(llvm::raw_ostream& output) const -> void;
  299. private:
  300. friend class ParseTree;
  301. explicit PostorderIterator(Node n) : node_(n) {}
  302. Node node_;
  303. };
  304. // A forward iterator across the siblings at a particular level in the parse
  305. // tree. It produces `ParseTree::Node` objects which are opaque handles and must
  306. // be used in conjunction with the `ParseTree` itself.
  307. //
  308. // While this is a forward iterator and may not have good locality within the
  309. // `ParseTree` data structure, it is still constant time to increment and
  310. // suitable for algorithms relying on that property.
  311. //
  312. // The siblings are discovered through a reverse postorder (RPO) tree traversal
  313. // (which is made constant time through cached distance information), and so the
  314. // relative order of siblings matches their RPO order.
  315. class ParseTree::SiblingIterator
  316. : public llvm::iterator_facade_base<
  317. SiblingIterator, std::forward_iterator_tag, Node, int, Node*, Node> {
  318. public:
  319. SiblingIterator() = default;
  320. auto operator==(const SiblingIterator& rhs) const -> bool {
  321. return node_ == rhs.node_;
  322. }
  323. auto operator<(const SiblingIterator& rhs) const -> bool {
  324. // Note that child iterators walk in reverse compared to the postorder
  325. // index.
  326. return node_ > rhs.node_;
  327. }
  328. auto operator*() const -> Node { return node_; }
  329. using iterator_facade_base::operator++;
  330. auto operator++() -> SiblingIterator& {
  331. node_.index_ -= std::abs(tree_->node_impls_[node_.index_].subtree_size);
  332. return *this;
  333. }
  334. // Prints the underlying node index.
  335. auto Print(llvm::raw_ostream& output) const -> void;
  336. private:
  337. friend class ParseTree;
  338. explicit SiblingIterator(const ParseTree& tree_arg, Node n)
  339. : tree_(&tree_arg), node_(n) {}
  340. const ParseTree* tree_;
  341. Node node_;
  342. };
  343. } // namespace Carbon
  344. #endif // CARBON_TOOLCHAIN_PARSER_PARSE_TREE_H_