tree.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. // Names in packaging, whether the file's packaging or an import. Links back
  70. // to the node for diagnostics.
  71. struct PackagingNames {
  72. ImportDeclId node_id;
  73. IdentifierId package_id = IdentifierId::Invalid;
  74. StringLiteralValueId library_id = StringLiteralValueId::Invalid;
  75. // Whether an import is exported. This is on the file's packaging
  76. // declaration even though it doesn't apply, for consistency in structure.
  77. bool is_export = false;
  78. };
  79. // The file's packaging.
  80. struct PackagingDecl {
  81. PackagingNames names;
  82. bool is_impl;
  83. };
  84. // Wires up the reference to the tokenized buffer. The `Parse` function should
  85. // be used to actually parse the tokens into a tree.
  86. explicit Tree(Lex::TokenizedBuffer& tokens_arg) : tokens_(&tokens_arg) {
  87. // If the tree is valid, there will be one node per token, so reserve once.
  88. node_impls_.reserve(tokens_->expected_max_parse_tree_size());
  89. }
  90. auto has_errors() const -> bool { return has_errors_; }
  91. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  92. // Returns the number of nodes in this parse tree.
  93. auto size() const -> int { return node_impls_.size(); }
  94. // Returns an iterable range over the parse tree nodes in depth-first
  95. // postorder.
  96. auto postorder() const -> llvm::iterator_range<PostorderIterator>;
  97. // Tests whether a particular node contains an error and may not match the
  98. // full expected structure of the grammar.
  99. auto node_has_error(NodeId n) const -> bool {
  100. CARBON_DCHECK(n.is_valid());
  101. return node_impls_[n.index].has_error;
  102. }
  103. // Returns the kind of the given parse tree node.
  104. auto node_kind(NodeId n) const -> NodeKind {
  105. CARBON_DCHECK(n.is_valid());
  106. return node_impls_[n.index].kind;
  107. }
  108. // Returns the token the given parse tree node models.
  109. auto node_token(NodeId n) const -> Lex::TokenIndex;
  110. // Returns whether this node is a valid node of the specified type.
  111. template <typename T>
  112. auto IsValid(NodeId node_id) const -> bool {
  113. return node_kind(node_id) == T::Kind && !node_has_error(node_id);
  114. }
  115. template <typename IdT>
  116. auto IsValid(IdT id) const -> bool {
  117. using T = typename NodeForId<IdT>::TypedNode;
  118. CARBON_DCHECK(node_kind(id) == T::Kind);
  119. return !node_has_error(id);
  120. }
  121. // Converts `n` to a constrained node id `T` if the `node_kind(n)` matches
  122. // the constraint on `T`.
  123. template <typename T>
  124. auto TryAs(NodeId n) const -> std::optional<T> {
  125. CARBON_DCHECK(n.is_valid());
  126. if (ConvertTo<T>::AllowedFor(node_kind(n))) {
  127. return T(n);
  128. } else {
  129. return std::nullopt;
  130. }
  131. }
  132. // Converts to `n` to a constrained node id `T`. Checks that the
  133. // `node_kind(n)` matches the constraint on `T`.
  134. template <typename T>
  135. auto As(NodeId n) const -> T {
  136. CARBON_DCHECK(n.is_valid());
  137. CARBON_CHECK(ConvertTo<T>::AllowedFor(node_kind(n)));
  138. return T(n);
  139. }
  140. auto packaging_decl() const -> const std::optional<PackagingDecl>& {
  141. return packaging_decl_;
  142. }
  143. auto imports() const -> llvm::ArrayRef<PackagingNames> { return imports_; }
  144. auto deferred_definitions() const
  145. -> const ValueStore<DeferredDefinitionIndex>& {
  146. return deferred_definitions_;
  147. }
  148. // Builds TreeAndSubtrees to print the tree.
  149. auto Print(llvm::raw_ostream& output) const -> void;
  150. // Collects memory usage of members.
  151. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  152. -> void;
  153. // Verifies the parse tree structure. Checks invariants of the parse tree
  154. // structure and returns verification errors.
  155. //
  156. // In opt builds, this does some minimal checking. In debug builds, it'll
  157. // build a TreeAndSubtrees and run further verification. This doesn't directly
  158. // CHECK so that it can be used within a debugger.
  159. auto Verify() const -> ErrorOr<Success>;
  160. private:
  161. friend class Context;
  162. friend class TypedNodesTestPeer;
  163. template <typename T>
  164. struct ConvertTo;
  165. // The in-memory representation of data used for a particular node in the
  166. // tree.
  167. struct NodeImpl {
  168. explicit NodeImpl(NodeKind kind, bool has_error, Lex::TokenIndex token)
  169. : kind(kind), has_error(has_error), token(token) {}
  170. // The kind of this node. Note that this is only a single byte.
  171. NodeKind kind;
  172. // We have 3 bytes of padding here that we can pack flags or other compact
  173. // data into.
  174. // Whether this node is or contains a parse error.
  175. //
  176. // When this is true, this node and its children may not have the expected
  177. // grammatical production structure. Prior to reasoning about any specific
  178. // subtree structure, this flag must be checked.
  179. //
  180. // Not every node in the path from the root to an error will have this field
  181. // set to true. However, any node structure that fails to conform to the
  182. // expected grammatical production will be contained within a subtree with
  183. // this flag set. Whether parents of that subtree also have it set is
  184. // optional (and will depend on the particular parse implementation
  185. // strategy). The goal is that you can rely on grammar-based structural
  186. // invariants *until* you encounter a node with this set.
  187. bool has_error = false;
  188. // The token root of this node.
  189. Lex::TokenIndex token;
  190. };
  191. static_assert(sizeof(NodeImpl) == 8,
  192. "Unexpected size of node implementation!");
  193. // Sets the kind of a node. This is intended to allow putting the tree into a
  194. // state where verification can fail, in order to make the failure path of
  195. // `Verify` testable.
  196. auto SetNodeKindForTesting(NodeId node_id, NodeKind kind) -> void {
  197. node_impls_[node_id.index].kind = kind;
  198. }
  199. // Depth-first postorder sequence of node implementation data.
  200. llvm::SmallVector<NodeImpl> node_impls_;
  201. Lex::TokenizedBuffer* tokens_;
  202. // True if any lowering-blocking issues were encountered while parsing. Trees
  203. // are expected to still be structurally valid for checking.
  204. //
  205. // This doesn't indicate how much of the tree is structurally accurate with
  206. // respect to the grammar. That can be identified by looking at
  207. // `node_has_error` (see above for details). This simply indicates that some
  208. // errors were encountered somewhere. A key implication is that when this is
  209. // true we do *not* enforce the expected 1:1 mapping between tokens and parsed
  210. // nodes, because some tokens may have been skipped.
  211. bool has_errors_ = false;
  212. std::optional<PackagingDecl> packaging_decl_;
  213. llvm::SmallVector<PackagingNames> imports_;
  214. ValueStore<DeferredDefinitionIndex> deferred_definitions_;
  215. };
  216. // A random-access iterator to the depth-first postorder sequence of parse nodes
  217. // in the parse tree. It produces `Tree::NodeId` objects which are opaque
  218. // handles and must be used in conjunction with the `Tree` itself.
  219. class Tree::PostorderIterator
  220. : public llvm::iterator_facade_base<PostorderIterator,
  221. std::random_access_iterator_tag, NodeId,
  222. int, const NodeId*, NodeId>,
  223. public Printable<Tree::PostorderIterator> {
  224. public:
  225. // Returns an iterable range between the two parse tree nodes, in depth-first
  226. // postorder. The range is inclusive of the bounds: [begin, end].
  227. static auto MakeRange(NodeId begin, NodeId end)
  228. -> llvm::iterator_range<PostorderIterator>;
  229. // Prefer using the `postorder` range calls, but direct construction is
  230. // allowed if needed.
  231. explicit PostorderIterator(NodeId n) : node_(n) {}
  232. PostorderIterator() = delete;
  233. auto operator==(const PostorderIterator& rhs) const -> bool {
  234. return node_ == rhs.node_;
  235. }
  236. // While we don't want users to directly leverage the index of `NodeId` for
  237. // ordering, when we're explicitly walking in postorder, that becomes
  238. // reasonable so add the ordering here and reach down for the index
  239. // explicitly.
  240. auto operator<=>(const PostorderIterator& rhs) const -> std::strong_ordering {
  241. return node_.index <=> rhs.node_.index;
  242. }
  243. auto operator*() const -> NodeId { return node_; }
  244. auto operator-(const PostorderIterator& rhs) const -> int {
  245. return node_.index - rhs.node_.index;
  246. }
  247. auto operator+=(int offset) -> PostorderIterator& {
  248. node_.index += offset;
  249. return *this;
  250. }
  251. auto operator-=(int offset) -> PostorderIterator& {
  252. node_.index -= offset;
  253. return *this;
  254. }
  255. // Prints the underlying node index.
  256. auto Print(llvm::raw_ostream& output) const -> void;
  257. private:
  258. friend class Tree;
  259. NodeId node_;
  260. };
  261. template <const NodeKind& K>
  262. struct Tree::ConvertTo<NodeIdForKind<K>> {
  263. static auto AllowedFor(NodeKind kind) -> bool { return kind == K; }
  264. };
  265. template <NodeCategory::RawEnumType C>
  266. struct Tree::ConvertTo<NodeIdInCategory<C>> {
  267. static auto AllowedFor(NodeKind kind) -> bool {
  268. return kind.category().HasAnyOf(C);
  269. }
  270. };
  271. template <typename... T>
  272. struct Tree::ConvertTo<NodeIdOneOf<T...>> {
  273. static auto AllowedFor(NodeKind kind) -> bool {
  274. return ((kind == T::Kind) || ...);
  275. }
  276. };
  277. } // namespace Carbon::Parse
  278. #endif // CARBON_TOOLCHAIN_PARSE_TREE_H_