tree.h 21 KB

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