tree.h 20 KB

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