tree.h 13 KB

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