tree.h 13 KB

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