tree.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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_PARSE_TREE_H_
  5. #define CARBON_TOOLCHAIN_PARSE_TREE_H_
  6. #include <iterator>
  7. #include "common/error.h"
  8. #include "common/ostream.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/ADT/iterator.h"
  11. #include "llvm/ADT/iterator_range.h"
  12. #include "toolchain/diagnostics/diagnostic_emitter.h"
  13. #include "toolchain/lex/tokenized_buffer.h"
  14. #include "toolchain/parse/node_kind.h"
  15. namespace Carbon::Parse {
  16. // A lightweight handle representing a node in the tree.
  17. //
  18. // Objects of this type are small and cheap to copy and store. They don't
  19. // contain any of the information about the node, and serve as a handle that
  20. // can be used with the underlying tree to query for detailed information.
  21. //
  22. // That said, nodes can be compared and are part of a depth-first pre-order
  23. // sequence across all nodes in the parse tree.
  24. struct Node : public ComparableIndexBase {
  25. // An explicitly invalid instance.
  26. static const Node Invalid;
  27. using ComparableIndexBase::ComparableIndexBase;
  28. };
  29. constexpr Node Node::Invalid = Node(Node::InvalidIndex);
  30. // A tree of parsed tokens based on the language grammar.
  31. //
  32. // This is a purely syntactic parse tree without any semantics yet attached. It
  33. // is based on the token stream and the grammar of the language without even
  34. // name lookup.
  35. //
  36. // The tree is designed to make depth-first traversal especially efficient, with
  37. // postorder and reverse postorder (RPO, a topological order) not even requiring
  38. // extra state.
  39. //
  40. // The nodes of the tree follow a flyweight pattern and are handles into the
  41. // tree. The tree itself must be available to query for information about those
  42. // nodes.
  43. //
  44. // Nodes also have a precise one-to-one correspondence to tokens from the parsed
  45. // token stream. Each node can be thought of as the tree-position of a
  46. // particular token from the stream.
  47. //
  48. // The tree is immutable once built, but is designed to support reasonably
  49. // efficient patterns that build a new tree with a specific transformation
  50. // applied.
  51. class Tree : public Printable<Tree> {
  52. public:
  53. class PostorderIterator;
  54. class SiblingIterator;
  55. // For PackagingDirective.
  56. enum class ApiOrImpl : uint8_t {
  57. Api,
  58. Impl,
  59. };
  60. // Names in packaging, whether the file's packaging or an import. Links back
  61. // to the node for diagnostics.
  62. struct PackagingNames {
  63. Node node;
  64. IdentifierId package_id = IdentifierId::Invalid;
  65. StringLiteralId library_id = StringLiteralId::Invalid;
  66. };
  67. // The file's packaging.
  68. struct PackagingDirective {
  69. PackagingNames names;
  70. ApiOrImpl api_or_impl;
  71. };
  72. // Parses the token buffer into a `Tree`.
  73. //
  74. // This is the factory function which is used to build parse trees.
  75. static auto Parse(Lex::TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  76. llvm::raw_ostream* vlog_stream) -> Tree;
  77. // Tests whether there are any errors in the parse tree.
  78. auto has_errors() const -> bool { return has_errors_; }
  79. // Returns the number of nodes in this parse tree.
  80. auto size() const -> int { return node_impls_.size(); }
  81. // Returns an iterable range over the parse tree nodes in depth-first
  82. // postorder.
  83. auto postorder() const -> llvm::iterator_range<PostorderIterator>;
  84. // Returns an iterable range over the parse tree node and all of its
  85. // descendants in depth-first postorder.
  86. auto postorder(Node n) const -> llvm::iterator_range<PostorderIterator>;
  87. // Returns an iterable range over the direct children of a node in the parse
  88. // tree. This is a forward range, but is constant time to increment. The order
  89. // of children is the same as would be found in a reverse postorder traversal.
  90. auto children(Node n) const -> llvm::iterator_range<SiblingIterator>;
  91. // Returns an iterable range over the roots of the parse tree. This is a
  92. // forward range, but is constant time to increment. The order of roots is the
  93. // same as would be found in a reverse postorder traversal.
  94. auto roots() const -> llvm::iterator_range<SiblingIterator>;
  95. // Tests whether a particular node contains an error and may not match the
  96. // full expected structure of the grammar.
  97. auto node_has_error(Node n) const -> bool;
  98. // Returns the kind of the given parse tree node.
  99. auto node_kind(Node n) const -> NodeKind;
  100. // Returns the token the given parse tree node models.
  101. auto node_token(Node n) const -> Lex::Token;
  102. auto node_subtree_size(Node n) const -> int32_t;
  103. auto packaging_directive() const -> const std::optional<PackagingDirective>& {
  104. return packaging_directive_;
  105. }
  106. auto imports() const -> llvm::ArrayRef<PackagingNames> { return imports_; }
  107. // See the other Print comments.
  108. auto Print(llvm::raw_ostream& output) const -> void;
  109. // Prints a description of the parse tree to the provided `raw_ostream`.
  110. //
  111. // The tree may be printed in either preorder or postorder. Output represents
  112. // each node as a YAML record; in preorder, children are nested.
  113. //
  114. // In both, a node is formatted as:
  115. // ```
  116. // {kind: 'foo', text: '...'}
  117. // ```
  118. //
  119. // The top level is formatted as an array of these nodes.
  120. // ```
  121. // [
  122. // {kind: 'foo', text: '...'},
  123. // {kind: 'foo', text: '...'},
  124. // ...
  125. // ]
  126. // ```
  127. //
  128. // In postorder, nodes are indented in order to indicate depth. For example, a
  129. // node with two children, one of them with an error:
  130. // ```
  131. // {kind: 'bar', text: '...', has_error: yes},
  132. // {kind: 'baz', text: '...'}
  133. // {kind: 'foo', text: '...', subtree_size: 2}
  134. // ```
  135. //
  136. // In preorder, nodes are marked as children with postorder (storage) index.
  137. // For example, a node with two children, one of them with an error:
  138. // ```
  139. // {node_index: 2, kind: 'foo', text: '...', subtree_size: 2, children: [
  140. // {node_index: 0, kind: 'bar', text: '...', has_error: yes},
  141. // {node_index: 1, kind: 'baz', text: '...'}]}
  142. // ```
  143. //
  144. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  145. // on the command line. The format is also reasonably amenable to other
  146. // line-oriented shell tools from `grep` to `awk`.
  147. auto Print(llvm::raw_ostream& output, bool preorder) const -> void;
  148. // Verifies the parse tree structure. Checks invariants of the parse tree
  149. // structure and returns verification errors.
  150. //
  151. // This is primarily intended to be used as a
  152. // debugging aid. This routine doesn't directly CHECK so that it can be used
  153. // within a debugger.
  154. auto Verify() const -> ErrorOr<Success>;
  155. private:
  156. friend class Context;
  157. // The in-memory representation of data used for a particular node in the
  158. // tree.
  159. struct NodeImpl {
  160. explicit NodeImpl(NodeKind kind, bool has_error, Lex::Token token,
  161. int subtree_size)
  162. : kind(kind),
  163. has_error(has_error),
  164. token(token),
  165. subtree_size(subtree_size) {}
  166. // The kind of this node. Note that this is only a single byte.
  167. NodeKind kind;
  168. // We have 3 bytes of padding here that we can pack flags or other compact
  169. // data into.
  170. // Whether this node is or contains a parse error.
  171. //
  172. // When this is true, this node and its children may not have the expected
  173. // grammatical production structure. Prior to reasoning about any specific
  174. // subtree structure, this flag must be checked.
  175. //
  176. // Not every node in the path from the root to an error will have this field
  177. // set to true. However, any node structure that fails to conform to the
  178. // expected grammatical production will be contained within a subtree with
  179. // this flag set. Whether parents of that subtree also have it set is
  180. // optional (and will depend on the particular parse implementation
  181. // strategy). The goal is that you can rely on grammar-based structural
  182. // invariants *until* you encounter a node with this set.
  183. bool has_error = false;
  184. // The token root of this node.
  185. Lex::Token token;
  186. // The size of this node's subtree of the parse tree. This is the number of
  187. // nodes (and thus tokens) that are covered by this node (and its
  188. // descendents) in the parse tree.
  189. //
  190. // During a *reverse* postorder (RPO) traversal of the parse tree, this can
  191. // also be thought of as the offset to the next non-descendant node. When
  192. // this node is not the first child of its parent (which is the last child
  193. // visited in RPO), that is the offset to the next sibling. When this node
  194. // *is* the first child of its parent, this will be an offset to the node's
  195. // parent's next sibling, or if it the parent is also a first child, the
  196. // grandparent's next sibling, and so on.
  197. //
  198. // This field should always be a positive integer as at least this node is
  199. // part of its subtree.
  200. int32_t subtree_size;
  201. };
  202. static_assert(sizeof(NodeImpl) == 12,
  203. "Unexpected size of node implementation!");
  204. // Wires up the reference to the tokenized buffer. The `Parse` function should
  205. // be used to actually parse the tokens into a tree.
  206. explicit Tree(Lex::TokenizedBuffer& tokens_arg) : tokens_(&tokens_arg) {
  207. // If the tree is valid, there will be one node per token, so reserve once.
  208. node_impls_.reserve(tokens_->expected_parse_tree_size());
  209. }
  210. // Prints a single node for Print(). Returns true when preorder and there are
  211. // children.
  212. auto PrintNode(llvm::raw_ostream& output, Node n, int depth,
  213. bool preorder) const -> bool;
  214. // Depth-first postorder sequence of node implementation data.
  215. llvm::SmallVector<NodeImpl> node_impls_;
  216. Lex::TokenizedBuffer* tokens_;
  217. // Indicates if any errors were encountered while parsing.
  218. //
  219. // This doesn't indicate how much of the tree is structurally accurate with
  220. // respect to the grammar. That can be identified by looking at the `HasError`
  221. // flag for a given node (see above for details). This simply indicates that
  222. // some errors were encountered somewhere. A key implication is that when this
  223. // is true we do *not* have the expected 1:1 mapping between tokens and parsed
  224. // nodes as some tokens may have been skipped.
  225. bool has_errors_ = false;
  226. std::optional<PackagingDirective> packaging_directive_;
  227. llvm::SmallVector<PackagingNames> imports_;
  228. };
  229. // A random-access iterator to the depth-first postorder sequence of parse nodes
  230. // in the parse tree. It produces `Tree::Node` objects which are opaque
  231. // handles and must be used in conjunction with the `Tree` itself.
  232. class Tree::PostorderIterator
  233. : public llvm::iterator_facade_base<PostorderIterator,
  234. std::random_access_iterator_tag, Node,
  235. int, Node*, Node>,
  236. public Printable<Tree::PostorderIterator> {
  237. public:
  238. PostorderIterator() = delete;
  239. auto operator==(const PostorderIterator& rhs) const -> bool {
  240. return node_ == rhs.node_;
  241. }
  242. auto operator<(const PostorderIterator& rhs) const -> bool {
  243. return node_ < rhs.node_;
  244. }
  245. auto operator*() const -> Node { return node_; }
  246. auto operator-(const PostorderIterator& rhs) const -> int {
  247. return node_.index - rhs.node_.index;
  248. }
  249. auto operator+=(int offset) -> PostorderIterator& {
  250. node_.index += offset;
  251. return *this;
  252. }
  253. auto operator-=(int offset) -> PostorderIterator& {
  254. node_.index -= offset;
  255. return *this;
  256. }
  257. // Prints the underlying node index.
  258. auto Print(llvm::raw_ostream& output) const -> void;
  259. private:
  260. friend class Tree;
  261. explicit PostorderIterator(Node n) : node_(n) {}
  262. Node node_;
  263. };
  264. // A forward iterator across the siblings at a particular level in the parse
  265. // tree. It produces `Tree::Node` objects which are opaque handles and must
  266. // be used in conjunction with the `Tree` itself.
  267. //
  268. // While this is a forward iterator and may not have good locality within the
  269. // `Tree` 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 Tree::SiblingIterator
  276. : public llvm::iterator_facade_base<
  277. SiblingIterator, std::forward_iterator_tag, Node, int, Node*, Node>,
  278. public Printable<Tree::SiblingIterator> {
  279. public:
  280. explicit SiblingIterator() = delete;
  281. auto operator==(const SiblingIterator& rhs) const -> bool {
  282. return node_ == rhs.node_;
  283. }
  284. auto operator<(const SiblingIterator& rhs) const -> bool {
  285. // Note that child iterators walk in reverse compared to the postorder
  286. // index.
  287. return node_ > rhs.node_;
  288. }
  289. auto operator*() const -> Node { return node_; }
  290. using iterator_facade_base::operator++;
  291. auto operator++() -> SiblingIterator& {
  292. node_.index -= std::abs(tree_->node_impls_[node_.index].subtree_size);
  293. return *this;
  294. }
  295. // Prints the underlying node index.
  296. auto Print(llvm::raw_ostream& output) const -> void;
  297. private:
  298. friend class Tree;
  299. explicit SiblingIterator(const Tree& tree_arg, Node n)
  300. : tree_(&tree_arg), node_(n) {}
  301. const Tree* tree_;
  302. Node node_;
  303. };
  304. } // namespace Carbon::Parse
  305. #endif // CARBON_TOOLCHAIN_PARSE_TREE_H_