tree.h 19 KB

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