tree.h 12 KB

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