tree.h 18 KB

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