parse_tree.h 14 KB

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