tree.h 18 KB

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