tree.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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/base/value_store.h"
  14. #include "toolchain/lex/tokenized_buffer.h"
  15. #include "toolchain/parse/node_ids.h"
  16. #include "toolchain/parse/node_kind.h"
  17. #include "toolchain/parse/typed_nodes.h"
  18. namespace Carbon::Parse {
  19. struct DeferredDefinition;
  20. // The index of a `DeferredDefinition` within the parse tree.
  21. struct DeferredDefinitionIndex : public IndexBase<DeferredDefinitionIndex> {
  22. static constexpr llvm::StringLiteral Label = "deferred_def";
  23. using IndexBase::IndexBase;
  24. };
  25. // A function whose definition is deferred because it is defined inline in a
  26. // class or similar scope.
  27. //
  28. // Such functions are type-checked out of order, with their bodies checked after
  29. // the enclosing declaration is complete. Some additional information is tracked
  30. // for these functions in the parse tree to support this reordering.
  31. struct DeferredDefinition {
  32. // The node that starts the function definition.
  33. FunctionDefinitionStartId start_id;
  34. // The function definition node.
  35. FunctionDefinitionId definition_id = NodeId::None;
  36. // The index of the next method that is not nested within this one.
  37. DeferredDefinitionIndex next_definition_index = DeferredDefinitionIndex::None;
  38. };
  39. // Defined in typed_nodes.h. Include that to call `Tree::ExtractFile()`.
  40. struct File;
  41. // A tree of parsed tokens based on the language grammar.
  42. //
  43. // This is a purely syntactic parse tree without any semantics yet attached. It
  44. // is based on the token stream and the grammar of the language without even
  45. // name lookup.
  46. //
  47. // The tree is designed to make depth-first traversal especially efficient, with
  48. // postorder and reverse postorder (RPO, a topological order) not even requiring
  49. // extra state.
  50. //
  51. // The nodes of the tree follow a flyweight pattern and are handles into the
  52. // tree. The tree itself must be available to query for information about those
  53. // nodes.
  54. //
  55. // Nodes also have a precise one-to-one correspondence to tokens from the parsed
  56. // token stream. Each node can be thought of as the tree-position of a
  57. // particular token from the stream.
  58. //
  59. // The tree is immutable once built, but is designed to support reasonably
  60. // efficient patterns that build a new tree with a specific transformation
  61. // applied.
  62. class Tree : public Printable<Tree> {
  63. public:
  64. class PostorderIterator;
  65. // Names in packaging, whether the file's packaging or an import. Links back
  66. // to the node for diagnostics.
  67. struct PackagingNames {
  68. AnyPackagingDeclId node_id = AnyPackagingDeclId::None;
  69. PackageNameId package_id = PackageNameId::None;
  70. // TODO: Move LibraryNameId to Base and use it here.
  71. StringLiteralValueId library_id = StringLiteralValueId::None;
  72. InlineImportBodyId inline_body_id = InlineImportBodyId::None;
  73. // Whether an import is exported. This is on the file's packaging
  74. // declaration even though it doesn't apply, for consistency in structure.
  75. bool is_export = false;
  76. };
  77. // The file's packaging.
  78. struct PackagingDecl {
  79. PackagingNames names;
  80. bool is_impl;
  81. };
  82. // Wires up the reference to the tokenized buffer. The `Parse` function should
  83. // be used to actually parse the tokens into a tree.
  84. explicit Tree(Lex::TokenizedBuffer& tokens_arg) : tokens_(&tokens_arg) {
  85. // If the tree is valid, there will be one node per token, so reserve once.
  86. node_impls_.reserve(tokens_->expected_max_parse_tree_size());
  87. }
  88. auto has_errors() const -> bool { return has_errors_; }
  89. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  90. // Returns the number of nodes in this parse tree.
  91. auto size() const -> int { return node_impls_.size(); }
  92. // Returns an iterable range over the parse tree nodes in depth-first
  93. // postorder.
  94. auto postorder() const -> llvm::iterator_range<PostorderIterator>;
  95. // Tests whether a particular node contains an error and may not match the
  96. // full expected structure of the grammar.
  97. auto node_has_error(NodeId n) const -> bool {
  98. CARBON_DCHECK(n.has_value());
  99. return node_impls_[n.index].has_error();
  100. }
  101. // Returns the kind of the given parse tree node.
  102. auto node_kind(NodeId n) const -> NodeKind {
  103. CARBON_DCHECK(n.has_value());
  104. return node_impls_[n.index].kind();
  105. }
  106. // Returns the token the given parse tree node models.
  107. auto node_token(NodeId n) const -> Lex::TokenIndex;
  108. // Returns whether this node is a valid node of the specified type.
  109. template <typename T>
  110. auto IsValid(NodeId node_id) const -> bool {
  111. return node_kind(node_id) == T::Kind && !node_has_error(node_id);
  112. }
  113. template <typename IdT>
  114. auto IsValid(IdT id) const -> bool {
  115. using T = typename NodeForId<IdT>::TypedNode;
  116. CARBON_DCHECK(node_kind(id) == T::Kind);
  117. return !node_has_error(id);
  118. }
  119. // Converts `n` to a constrained node id `T` if the `node_kind(n)` matches
  120. // the constraint on `T`.
  121. template <typename T>
  122. auto TryAs(NodeId n) const -> std::optional<T> {
  123. CARBON_DCHECK(n.has_value());
  124. if (ConvertTo<T>::AllowedFor(node_kind(n))) {
  125. return T::UnsafeMake(n);
  126. } else {
  127. return std::nullopt;
  128. }
  129. }
  130. // Converts to `n` to a constrained node id `T`. Checks that the
  131. // `node_kind(n)` matches the constraint on `T`.
  132. template <typename T>
  133. auto As(NodeId n) const -> T {
  134. CARBON_DCHECK(n.has_value());
  135. CARBON_DCHECK(ConvertTo<T>::AllowedFor(node_kind(n)),
  136. "cannot convert {0} to {1}", node_kind(n), typeid(T).name());
  137. return T::UnsafeMake(n);
  138. }
  139. auto packaging_decl() const -> const std::optional<PackagingDecl>& {
  140. return packaging_decl_;
  141. }
  142. auto imports() const -> llvm::ArrayRef<PackagingNames> { return imports_; }
  143. auto deferred_definitions() const
  144. -> const ValueStore<DeferredDefinitionIndex, DeferredDefinition>& {
  145. return deferred_definitions_;
  146. }
  147. // Builds TreeAndSubtrees to print the tree.
  148. auto Print(llvm::raw_ostream& output) const -> void;
  149. // Collects memory usage of members.
  150. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  151. -> void;
  152. // Verifies the parse tree structure. Checks invariants of the parse tree
  153. // structure and returns verification errors.
  154. //
  155. // In opt builds, this does some minimal checking. In debug builds, it'll
  156. // build a TreeAndSubtrees and run further verification. This doesn't directly
  157. // CHECK so that it can be used within a debugger.
  158. auto Verify() const -> ErrorOr<Success>;
  159. auto tokens() const -> const Lex::TokenizedBuffer& { return *tokens_; }
  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. class NodeImpl {
  168. public:
  169. explicit NodeImpl(NodeKind kind, bool has_error, Lex::TokenIndex token)
  170. : kind_(kind), has_error_(has_error), token_index_(token.index) {
  171. CARBON_DCHECK(token.index >= 0, "Unexpected token for node: {0}", token);
  172. }
  173. auto kind() const -> NodeKind { return kind_; }
  174. auto set_kind(NodeKind kind) -> void { kind_ = kind; }
  175. auto has_error() const -> bool { return has_error_; }
  176. auto token() const -> Lex::TokenIndex {
  177. return Lex::TokenIndex(token_index_);
  178. }
  179. private:
  180. // The kind of this node. Note that this is only a single byte.
  181. NodeKind kind_;
  182. static_assert(sizeof(kind_) == 1, "TokenKind must pack to 8 bits");
  183. // Whether this node is or contains a parse error.
  184. //
  185. // When this is true, this node and its children may not have the expected
  186. // grammatical production structure. Prior to reasoning about any specific
  187. // subtree structure, this flag must be checked.
  188. //
  189. // Not every node in the path from the root to an error will have this field
  190. // set to true. However, any node structure that fails to conform to the
  191. // expected grammatical production will be contained within a subtree with
  192. // this flag set. Whether parents of that subtree also have it set is
  193. // optional (and will depend on the particular parse implementation
  194. // strategy). The goal is that you can rely on grammar-based structural
  195. // invariants *until* you encounter a node with this set.
  196. bool has_error_ : 1;
  197. // The token root of this node.
  198. unsigned token_index_ : Lex::TokenIndex::Bits;
  199. };
  200. static_assert(sizeof(NodeImpl) == 4,
  201. "Unexpected size of node implementation!");
  202. // Sets the kind of a node. This is intended to allow putting the tree into a
  203. // state where verification can fail, in order to make the failure path of
  204. // `Verify` testable.
  205. auto SetNodeKindForTesting(NodeId node_id, NodeKind kind) -> void {
  206. node_impls_[node_id.index].set_kind(kind);
  207. }
  208. // Depth-first postorder sequence of node implementation data.
  209. llvm::SmallVector<NodeImpl> node_impls_;
  210. Lex::TokenizedBuffer* tokens_;
  211. // True if any lowering-blocking issues were encountered while parsing. Trees
  212. // are expected to still be structurally valid for checking.
  213. //
  214. // This doesn't indicate how much of the tree is structurally accurate with
  215. // respect to the grammar. That can be identified by looking at
  216. // `node_has_error` (see above for details). This simply indicates that some
  217. // errors were encountered somewhere. A key implication is that when this is
  218. // true we do *not* enforce the expected 1:1 mapping between tokens and parsed
  219. // nodes, because some tokens may have been skipped.
  220. bool has_errors_ = false;
  221. std::optional<PackagingDecl> packaging_decl_;
  222. llvm::SmallVector<PackagingNames> imports_;
  223. ValueStore<DeferredDefinitionIndex, DeferredDefinition> deferred_definitions_;
  224. };
  225. // A random-access iterator to the depth-first postorder sequence of parse nodes
  226. // in the parse tree. It produces `Tree::NodeId` objects which are opaque
  227. // handles and must be used in conjunction with the `Tree` itself.
  228. class Tree::PostorderIterator
  229. : public llvm::iterator_facade_base<PostorderIterator,
  230. std::random_access_iterator_tag, NodeId,
  231. int, const NodeId*, NodeId>,
  232. public Printable<Tree::PostorderIterator> {
  233. public:
  234. // Returns an iterable range between the two parse tree nodes, in depth-first
  235. // postorder. The range is inclusive of the bounds: [begin, end].
  236. static auto MakeRange(NodeId begin, NodeId end)
  237. -> llvm::iterator_range<PostorderIterator>;
  238. // Prefer using the `postorder` range calls, but direct construction is
  239. // allowed if needed.
  240. explicit PostorderIterator(NodeId n) : node_(n) {}
  241. PostorderIterator() = delete;
  242. friend auto operator==(const PostorderIterator& lhs,
  243. const PostorderIterator& rhs) -> bool {
  244. return lhs.node_ == rhs.node_;
  245. }
  246. // While we don't want users to directly leverage the index of `NodeId` for
  247. // ordering, when we're explicitly walking in postorder, that becomes
  248. // reasonable so add the ordering here and reach down for the index
  249. // explicitly.
  250. friend auto operator<=>(const PostorderIterator& lhs,
  251. const PostorderIterator& rhs)
  252. -> std::strong_ordering {
  253. return lhs.node_.index <=> rhs.node_.index;
  254. }
  255. auto operator*() const -> NodeId { return node_; }
  256. friend auto operator-(const PostorderIterator& lhs,
  257. const PostorderIterator& rhs) -> int {
  258. return lhs.node_.index - rhs.node_.index;
  259. }
  260. auto operator+=(int offset) -> PostorderIterator& {
  261. node_.index += offset;
  262. return *this;
  263. }
  264. auto operator-=(int offset) -> PostorderIterator& {
  265. node_.index -= offset;
  266. return *this;
  267. }
  268. // Prints the underlying node index.
  269. auto Print(llvm::raw_ostream& output) const -> void;
  270. private:
  271. friend class Tree;
  272. NodeId node_;
  273. };
  274. template <const NodeKind& K>
  275. struct Tree::ConvertTo<NodeIdForKind<K>> {
  276. static auto AllowedFor(NodeKind kind) -> bool { return kind == K; }
  277. };
  278. template <NodeCategory::RawEnumType C>
  279. struct Tree::ConvertTo<NodeIdInCategory<C>> {
  280. static auto AllowedFor(NodeKind kind) -> bool {
  281. return kind.category().HasAnyOf(C);
  282. }
  283. };
  284. template <typename... T>
  285. struct Tree::ConvertTo<NodeIdOneOf<T...>> {
  286. static auto AllowedFor(NodeKind kind) -> bool {
  287. return ((kind == T::Kind) || ...);
  288. }
  289. };
  290. } // namespace Carbon::Parse
  291. #endif // CARBON_TOOLCHAIN_PARSE_TREE_H_