tree.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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/check.h"
  8. #include "common/error.h"
  9. #include "common/ostream.h"
  10. #include "llvm/ADT/SmallVector.h"
  11. #include "llvm/ADT/iterator.h"
  12. #include "llvm/ADT/iterator_range.h"
  13. #include "toolchain/diagnostics/diagnostic_emitter.h"
  14. #include "toolchain/lex/tokenized_buffer.h"
  15. #include "toolchain/parse/node_ids.h"
  16. #include "toolchain/parse/node_kind.h"
  17. namespace Carbon::Parse {
  18. // Defined in typed_nodes.h. Include that to call `Tree::ExtractFile()`.
  19. struct File;
  20. // A tree of parsed tokens based on the language grammar.
  21. //
  22. // This is a purely syntactic parse tree without any semantics yet attached. It
  23. // is based on the token stream and the grammar of the language without even
  24. // name lookup.
  25. //
  26. // The tree is designed to make depth-first traversal especially efficient, with
  27. // postorder and reverse postorder (RPO, a topological order) not even requiring
  28. // extra state.
  29. //
  30. // The nodes of the tree follow a flyweight pattern and are handles into the
  31. // tree. The tree itself must be available to query for information about those
  32. // nodes.
  33. //
  34. // Nodes also have a precise one-to-one correspondence to tokens from the parsed
  35. // token stream. Each node can be thought of as the tree-position of a
  36. // particular token from the stream.
  37. //
  38. // The tree is immutable once built, but is designed to support reasonably
  39. // efficient patterns that build a new tree with a specific transformation
  40. // applied.
  41. class Tree : public Printable<Tree> {
  42. public:
  43. class PostorderIterator;
  44. class SiblingIterator;
  45. // For PackagingDirective.
  46. enum class ApiOrImpl : uint8_t {
  47. Api,
  48. Impl,
  49. };
  50. // Names in packaging, whether the file's packaging or an import. Links back
  51. // to the node for diagnostics.
  52. struct PackagingNames {
  53. NodeId node;
  54. IdentifierId package_id = IdentifierId::Invalid;
  55. StringLiteralValueId library_id = StringLiteralValueId::Invalid;
  56. };
  57. // The file's packaging.
  58. struct PackagingDirective {
  59. PackagingNames names;
  60. ApiOrImpl api_or_impl;
  61. };
  62. // Wires up the reference to the tokenized buffer. The `Parse` function should
  63. // be used to actually parse the tokens into a tree.
  64. explicit Tree(Lex::TokenizedBuffer& tokens_arg) : tokens_(&tokens_arg) {
  65. // If the tree is valid, there will be one node per token, so reserve once.
  66. node_impls_.reserve(tokens_->expected_parse_tree_size());
  67. }
  68. // Tests whether there are any errors in the parse tree.
  69. auto has_errors() const -> bool { return has_errors_; }
  70. // Returns the number of nodes in this parse tree.
  71. auto size() const -> int { return node_impls_.size(); }
  72. // Returns an iterable range over the parse tree nodes in depth-first
  73. // postorder.
  74. auto postorder() const -> llvm::iterator_range<PostorderIterator>;
  75. // Returns an iterable range over the parse tree node and all of its
  76. // descendants in depth-first postorder.
  77. auto postorder(NodeId n) const -> llvm::iterator_range<PostorderIterator>;
  78. // Returns an iterable range over the direct children of a node in the parse
  79. // tree. This is a forward range, but is constant time to increment. The order
  80. // of children is the same as would be found in a reverse postorder traversal.
  81. auto children(NodeId n) const -> llvm::iterator_range<SiblingIterator>;
  82. // Returns an iterable range over the roots of the parse tree. This is a
  83. // forward range, but is constant time to increment. The order of roots is the
  84. // same as would be found in a reverse postorder traversal.
  85. auto roots() const -> llvm::iterator_range<SiblingIterator>;
  86. // Tests whether a particular node contains an error and may not match the
  87. // full expected structure of the grammar.
  88. auto node_has_error(NodeId n) const -> bool;
  89. // Returns the kind of the given parse tree node.
  90. auto node_kind(NodeId n) const -> NodeKind;
  91. // Returns the token the given parse tree node models.
  92. auto node_token(NodeId n) const -> Lex::TokenIndex;
  93. auto node_subtree_size(NodeId n) const -> int32_t;
  94. // Returns whether this node is a valid node of the specified type.
  95. template <typename T>
  96. auto IsValid(NodeId node_id) const -> bool {
  97. return node_kind(node_id) == T::Kind && !node_has_error(node_id);
  98. }
  99. template <typename IdT>
  100. auto IsValid(IdT id) const -> bool {
  101. using T = typename NodeForId<IdT>::TypedNode;
  102. CARBON_DCHECK(node_kind(id) == T::Kind);
  103. return !node_has_error(id);
  104. }
  105. auto packaging_directive() const -> const std::optional<PackagingDirective>& {
  106. return packaging_directive_;
  107. }
  108. auto imports() const -> llvm::ArrayRef<PackagingNames> { return imports_; }
  109. // See the other Print comments.
  110. auto Print(llvm::raw_ostream& output) const -> void;
  111. // Prints a description of the parse tree to the provided `raw_ostream`.
  112. //
  113. // The tree may be printed in either preorder or postorder. Output represents
  114. // each node as a YAML record; in preorder, children are nested.
  115. //
  116. // In both, a node is formatted as:
  117. // ```
  118. // {kind: 'foo', text: '...'}
  119. // ```
  120. //
  121. // The top level is formatted as an array of these nodes.
  122. // ```
  123. // [
  124. // {kind: 'foo', text: '...'},
  125. // {kind: 'foo', text: '...'},
  126. // ...
  127. // ]
  128. // ```
  129. //
  130. // In postorder, nodes are indented in order to indicate depth. For example, a
  131. // node with two children, one of them with an error:
  132. // ```
  133. // {kind: 'bar', text: '...', has_error: yes},
  134. // {kind: 'baz', text: '...'}
  135. // {kind: 'foo', text: '...', subtree_size: 2}
  136. // ```
  137. //
  138. // In preorder, nodes are marked as children with postorder (storage) index.
  139. // For example, a node with two children, one of them with an error:
  140. // ```
  141. // {node_index: 2, kind: 'foo', text: '...', subtree_size: 2, children: [
  142. // {node_index: 0, kind: 'bar', text: '...', has_error: yes},
  143. // {node_index: 1, kind: 'baz', text: '...'}]}
  144. // ```
  145. //
  146. // This can be parsed as YAML using tools like `python-yq` combined with `jq`
  147. // on the command line. The format is also reasonably amenable to other
  148. // line-oriented shell tools from `grep` to `awk`.
  149. auto Print(llvm::raw_ostream& output, bool preorder) const -> void;
  150. // The following `Extract*` function provide an alternative way of accessing
  151. // the nodes of a tree. It is intended to be more convenient and type-safe,
  152. // but slower and can't be used on nodes that are marked as having an error.
  153. // It is appropriate for uses that are less performance sensitive, like
  154. // diagnostics. Example usage:
  155. // ```
  156. // auto file = tree->ExtractFile();
  157. // for (AnyDeclId decl_id : file.decls) {
  158. // // `decl_id` is convertible to a `NodeId`.
  159. // if (std::optional<FunctionDecl> fn_decl =
  160. // tree->ExtractAs<FunctionDecl>(decl_id)) {
  161. // // fn_decl->params is a `TuplePatternId` (which extends `NodeId`)
  162. // // that is guaranteed to reference a `TuplePattern`.
  163. // std::optional<TuplePattern> params = tree->Extract(fn_decl->params);
  164. // // `params` has a value unless there was an error in that node.
  165. // } else if (auto class_def = tree->ExtractAs<ClassDefinition>(decl_id)) {
  166. // // ...
  167. // }
  168. // }
  169. // ```
  170. // Extract a `File` object representing the parse tree for the whole file.
  171. // #include "toolchain/parse/typed_nodes.h" to get the definition of `File`
  172. // and the types representing its children nodes.
  173. auto ExtractFile() const -> File;
  174. // Converts this node_id to a typed node of a specified type, if it is a valid
  175. // node of that kind.
  176. template <typename T>
  177. auto ExtractAs(NodeId node_id) const -> std::optional<T>;
  178. // Converts to a typed node, if it is not an error.
  179. template <typename IdT>
  180. auto Extract(IdT id) const
  181. -> std::optional<typename NodeForId<IdT>::TypedNode>;
  182. // Verifies the parse tree structure. Checks invariants of the parse tree
  183. // structure and returns verification errors.
  184. //
  185. // This is fairly slow, and is primarily intended to be used as a debugging
  186. // aid. This routine doesn't directly CHECK so that it can be used within a
  187. // debugger.
  188. auto Verify() const -> ErrorOr<Success>;
  189. // Like ExtractAs(), but malformed tree errors are not fatal. Should only be
  190. // used by `Verify()`.
  191. template <typename T>
  192. auto VerifyExtractAs(NodeId node_id, ErrorBuilder* trace) const
  193. -> std::optional<T>;
  194. private:
  195. friend class Context;
  196. // The in-memory representation of data used for a particular node in the
  197. // tree.
  198. struct NodeImpl {
  199. explicit NodeImpl(NodeKind kind, bool has_error, Lex::TokenIndex token,
  200. int subtree_size)
  201. : kind(kind),
  202. has_error(has_error),
  203. token(token),
  204. subtree_size(subtree_size) {}
  205. // The kind of this node. Note that this is only a single byte.
  206. NodeKind kind;
  207. // We have 3 bytes of padding here that we can pack flags or other compact
  208. // data into.
  209. // Whether this node is or contains a parse error.
  210. //
  211. // When this is true, this node and its children may not have the expected
  212. // grammatical production structure. Prior to reasoning about any specific
  213. // subtree structure, this flag must be checked.
  214. //
  215. // Not every node in the path from the root to an error will have this field
  216. // set to true. However, any node structure that fails to conform to the
  217. // expected grammatical production will be contained within a subtree with
  218. // this flag set. Whether parents of that subtree also have it set is
  219. // optional (and will depend on the particular parse implementation
  220. // strategy). The goal is that you can rely on grammar-based structural
  221. // invariants *until* you encounter a node with this set.
  222. bool has_error = false;
  223. // The token root of this node.
  224. Lex::TokenIndex token;
  225. // The size of this node's subtree of the parse tree. This is the number of
  226. // nodes (and thus tokens) that are covered by this node (and its
  227. // descendents) in the parse tree.
  228. //
  229. // During a *reverse* postorder (RPO) traversal of the parse tree, this can
  230. // also be thought of as the offset to the next non-descendant node. When
  231. // this node is not the first child of its parent (which is the last child
  232. // visited in RPO), that is the offset to the next sibling. When this node
  233. // *is* the first child of its parent, this will be an offset to the node's
  234. // parent's next sibling, or if it the parent is also a first child, the
  235. // grandparent's next sibling, and so on.
  236. //
  237. // This field should always be a positive integer as at least this node is
  238. // part of its subtree.
  239. int32_t subtree_size;
  240. };
  241. static_assert(sizeof(NodeImpl) == 12,
  242. "Unexpected size of node implementation!");
  243. // Prints a single node for Print(). Returns true when preorder and there are
  244. // children.
  245. auto PrintNode(llvm::raw_ostream& output, NodeId n, int depth,
  246. bool preorder) const -> bool;
  247. // Extract a node of type `T` from a sibling range. This is expected to
  248. // consume the complete sibling range. Malformed tree errors are written
  249. // to `*trace`, if `trace != nullptr`.
  250. template <typename T>
  251. auto TryExtractNodeFromChildren(
  252. llvm::iterator_range<Tree::SiblingIterator> children,
  253. ErrorBuilder* trace) const -> std::optional<T>;
  254. // Extract a node of type `T` from a sibling range. This is expected to
  255. // consume the complete sibling range. Malformed tree errors are fatal.
  256. template <typename T>
  257. auto ExtractNodeFromChildren(
  258. llvm::iterator_range<Tree::SiblingIterator> children) const -> T;
  259. // Depth-first postorder sequence of node implementation data.
  260. llvm::SmallVector<NodeImpl> node_impls_;
  261. Lex::TokenizedBuffer* tokens_;
  262. // Indicates if any errors were encountered while parsing.
  263. //
  264. // This doesn't indicate how much of the tree is structurally accurate with
  265. // respect to the grammar. That can be identified by looking at the `HasError`
  266. // flag for a given node (see above for details). This simply indicates that
  267. // some errors were encountered somewhere. A key implication is that when this
  268. // is true we do *not* have the expected 1:1 mapping between tokens and parsed
  269. // nodes as some tokens may have been skipped.
  270. bool has_errors_ = false;
  271. std::optional<PackagingDirective> packaging_directive_;
  272. llvm::SmallVector<PackagingNames> imports_;
  273. };
  274. // A random-access iterator to the depth-first postorder sequence of parse nodes
  275. // in the parse tree. It produces `Tree::NodeId` objects which are opaque
  276. // handles and must be used in conjunction with the `Tree` itself.
  277. class Tree::PostorderIterator
  278. : public llvm::iterator_facade_base<PostorderIterator,
  279. std::random_access_iterator_tag, NodeId,
  280. int, const NodeId*, NodeId>,
  281. public Printable<Tree::PostorderIterator> {
  282. public:
  283. PostorderIterator() = delete;
  284. auto operator==(const PostorderIterator& rhs) const -> bool {
  285. return node_ == rhs.node_;
  286. }
  287. auto operator<(const PostorderIterator& rhs) const -> bool {
  288. return node_.index < rhs.node_.index;
  289. }
  290. auto operator*() const -> NodeId { return node_; }
  291. auto operator-(const PostorderIterator& rhs) const -> int {
  292. return node_.index - rhs.node_.index;
  293. }
  294. auto operator+=(int offset) -> PostorderIterator& {
  295. node_.index += offset;
  296. return *this;
  297. }
  298. auto operator-=(int offset) -> PostorderIterator& {
  299. node_.index -= offset;
  300. return *this;
  301. }
  302. // Prints the underlying node index.
  303. auto Print(llvm::raw_ostream& output) const -> void;
  304. private:
  305. friend class Tree;
  306. explicit PostorderIterator(NodeId n) : node_(n) {}
  307. NodeId node_;
  308. };
  309. // A forward iterator across the siblings at a particular level in the parse
  310. // tree. It produces `Tree::NodeId` objects which are opaque handles and must
  311. // be used in conjunction with the `Tree` itself.
  312. //
  313. // While this is a forward iterator and may not have good locality within the
  314. // `Tree` data structure, it is still constant time to increment and
  315. // suitable for algorithms relying on that property.
  316. //
  317. // The siblings are discovered through a reverse postorder (RPO) tree traversal
  318. // (which is made constant time through cached distance information), and so the
  319. // relative order of siblings matches their RPO order.
  320. class Tree::SiblingIterator
  321. : public llvm::iterator_facade_base<SiblingIterator,
  322. std::forward_iterator_tag, NodeId, int,
  323. const NodeId*, NodeId>,
  324. public Printable<Tree::SiblingIterator> {
  325. public:
  326. explicit SiblingIterator() = delete;
  327. auto operator==(const SiblingIterator& rhs) const -> bool {
  328. return node_ == rhs.node_;
  329. }
  330. auto operator*() const -> NodeId { return node_; }
  331. using iterator_facade_base::operator++;
  332. auto operator++() -> SiblingIterator& {
  333. node_.index -= std::abs(tree_->node_impls_[node_.index].subtree_size);
  334. return *this;
  335. }
  336. // Prints the underlying node index.
  337. auto Print(llvm::raw_ostream& output) const -> void;
  338. private:
  339. friend class Tree;
  340. explicit SiblingIterator(const Tree& tree_arg, NodeId n)
  341. : tree_(&tree_arg), node_(n) {}
  342. const Tree* tree_;
  343. NodeId node_;
  344. };
  345. template <typename T>
  346. auto Tree::ExtractNodeFromChildren(
  347. llvm::iterator_range<Tree::SiblingIterator> children) const -> T {
  348. auto result = TryExtractNodeFromChildren<T>(children, nullptr);
  349. if (!result.has_value()) {
  350. // On error try again, this time capturing a trace.
  351. ErrorBuilder trace;
  352. TryExtractNodeFromChildren<T>(children, &trace);
  353. CARBON_FATAL() << "Malformed parse node:\n" << Error(trace).message();
  354. }
  355. return *result;
  356. }
  357. template <typename T>
  358. auto Tree::ExtractAs(NodeId node_id) const -> std::optional<T> {
  359. static_assert(HasKindMember<T>, "Not a parse node type");
  360. if (!IsValid<T>(node_id)) {
  361. return std::nullopt;
  362. }
  363. return ExtractNodeFromChildren<T>(children(node_id));
  364. }
  365. template <typename T>
  366. auto Tree::VerifyExtractAs(NodeId node_id, ErrorBuilder* trace) const
  367. -> std::optional<T> {
  368. static_assert(HasKindMember<T>, "Not a parse node type");
  369. if (!IsValid<T>(node_id)) {
  370. return std::nullopt;
  371. }
  372. return TryExtractNodeFromChildren<T>(children(node_id), trace);
  373. }
  374. template <typename IdT>
  375. auto Tree::Extract(IdT id) const
  376. -> std::optional<typename NodeForId<IdT>::TypedNode> {
  377. if (!IsValid(id)) {
  378. return std::nullopt;
  379. }
  380. using T = typename NodeForId<IdT>::TypedNode;
  381. return ExtractNodeFromChildren<T>(children(id));
  382. }
  383. } // namespace Carbon::Parse
  384. #endif // CARBON_TOOLCHAIN_PARSE_TREE_H_