tree.h 13 KB

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