tree.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. #include "toolchain/parse/tree.h"
  5. #include "common/check.h"
  6. #include "common/error.h"
  7. #include "llvm/ADT/Sequence.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/base/pretty_stack_trace_function.h"
  10. #include "toolchain/lex/tokenized_buffer.h"
  11. #include "toolchain/parse/context.h"
  12. #include "toolchain/parse/node_kind.h"
  13. namespace Carbon::Parse {
  14. auto Tree::Parse(Lex::TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  15. llvm::raw_ostream* vlog_stream) -> Tree {
  16. Lex::TokenLocationTranslator translator(&tokens);
  17. Lex::TokenDiagnosticEmitter emitter(translator, consumer);
  18. // Delegate to the parser.
  19. Tree tree(tokens);
  20. Context context(tree, tokens, emitter, vlog_stream);
  21. PrettyStackTraceFunction context_dumper(
  22. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  23. context.AddLeafNode(NodeKind::FileStart,
  24. context.ConsumeChecked(Lex::TokenKind::StartOfFile));
  25. context.PushState(State::DeclarationScopeLoop);
  26. // The package should always be the first token, if it's present. Any other
  27. // use is invalid.
  28. if (context.PositionIs(Lex::TokenKind::Package)) {
  29. context.PushState(State::Package);
  30. }
  31. while (!context.state_stack().empty()) {
  32. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  33. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  34. switch (context.state_stack().back().state) {
  35. #define CARBON_PARSE_STATE(Name) \
  36. case State::Name: \
  37. Handle##Name(context); \
  38. break;
  39. #include "toolchain/parse/state.def"
  40. }
  41. }
  42. context.AddLeafNode(NodeKind::FileEnd, *context.position());
  43. if (auto verify = tree.Verify(); !verify.ok()) {
  44. if (vlog_stream) {
  45. tree.Print(*vlog_stream);
  46. }
  47. CARBON_FATAL() << "Invalid tree returned by Parse(): " << verify.error();
  48. }
  49. return tree;
  50. }
  51. auto Tree::postorder() const -> llvm::iterator_range<PostorderIterator> {
  52. return {PostorderIterator(Node(0)),
  53. PostorderIterator(Node(node_impls_.size()))};
  54. }
  55. auto Tree::postorder(Node n) const -> llvm::iterator_range<PostorderIterator> {
  56. CARBON_CHECK(n.is_valid());
  57. // The postorder ends after this node, the root, and begins at the start of
  58. // its subtree.
  59. int end_index = n.index + 1;
  60. int start_index = end_index - node_impls_[n.index].subtree_size;
  61. return {PostorderIterator(Node(start_index)),
  62. PostorderIterator(Node(end_index))};
  63. }
  64. auto Tree::children(Node n) const -> llvm::iterator_range<SiblingIterator> {
  65. CARBON_CHECK(n.is_valid());
  66. int end_index = n.index - node_impls_[n.index].subtree_size;
  67. return {SiblingIterator(*this, Node(n.index - 1)),
  68. SiblingIterator(*this, Node(end_index))};
  69. }
  70. auto Tree::roots() const -> llvm::iterator_range<SiblingIterator> {
  71. return {
  72. SiblingIterator(*this, Node(static_cast<int>(node_impls_.size()) - 1)),
  73. SiblingIterator(*this, Node(-1))};
  74. }
  75. auto Tree::node_has_error(Node n) const -> bool {
  76. CARBON_CHECK(n.is_valid());
  77. return node_impls_[n.index].has_error;
  78. }
  79. auto Tree::node_kind(Node n) const -> NodeKind {
  80. CARBON_CHECK(n.is_valid());
  81. return node_impls_[n.index].kind;
  82. }
  83. auto Tree::node_token(Node n) const -> Lex::Token {
  84. CARBON_CHECK(n.is_valid());
  85. return node_impls_[n.index].token;
  86. }
  87. auto Tree::node_subtree_size(Node n) const -> int32_t {
  88. CARBON_CHECK(n.is_valid());
  89. return node_impls_[n.index].subtree_size;
  90. }
  91. auto Tree::GetNodeText(Node n) const -> llvm::StringRef {
  92. CARBON_CHECK(n.is_valid());
  93. return tokens_->GetTokenText(node_impls_[n.index].token);
  94. }
  95. auto Tree::PrintNode(llvm::raw_ostream& output, Node n, int depth,
  96. bool preorder) const -> bool {
  97. const auto& n_impl = node_impls_[n.index];
  98. output.indent(2 * (depth + 2));
  99. output << "{";
  100. // If children are being added, include node_index in order to disambiguate
  101. // nodes.
  102. if (preorder) {
  103. output << "node_index: " << n << ", ";
  104. }
  105. output << "kind: '" << n_impl.kind << "', text: '"
  106. << tokens_->GetTokenText(n_impl.token) << "'";
  107. if (n_impl.has_error) {
  108. output << ", has_error: yes";
  109. }
  110. if (n_impl.subtree_size > 1) {
  111. output << ", subtree_size: " << n_impl.subtree_size;
  112. if (preorder) {
  113. output << ", children: [\n";
  114. return true;
  115. }
  116. }
  117. output << "}";
  118. return false;
  119. }
  120. auto Tree::Print(llvm::raw_ostream& output) const -> void {
  121. output << "- filename: " << tokens_->filename() << "\n"
  122. << " parse_tree: [\n";
  123. // Walk the tree just to calculate depths for each node.
  124. llvm::SmallVector<int> indents;
  125. indents.append(size(), 0);
  126. llvm::SmallVector<std::pair<Node, int>, 16> node_stack;
  127. for (Node n : roots()) {
  128. node_stack.push_back({n, 0});
  129. }
  130. while (!node_stack.empty()) {
  131. Node n = Node::Invalid;
  132. int depth;
  133. std::tie(n, depth) = node_stack.pop_back_val();
  134. for (Node sibling_n : children(n)) {
  135. indents[sibling_n.index] = depth + 1;
  136. node_stack.push_back({sibling_n, depth + 1});
  137. }
  138. }
  139. for (Node n : postorder()) {
  140. PrintNode(output, n, indents[n.index], /*preorder=*/false);
  141. output << ",\n";
  142. }
  143. output << " ]\n";
  144. }
  145. auto Tree::Print(llvm::raw_ostream& output, bool preorder) const -> void {
  146. if (!preorder) {
  147. Print(output);
  148. return;
  149. }
  150. output << "- filename: " << tokens_->filename() << "\n"
  151. << " parse_tree: [\n";
  152. // The parse tree is stored in postorder. The preorder can be constructed
  153. // by reversing the order of each level of siblings within an RPO. The
  154. // sibling iterators are directly built around RPO and so can be used with a
  155. // stack to produce preorder.
  156. // The roots, like siblings, are in RPO (so reversed), but we add them in
  157. // order here because we'll pop off the stack effectively reversing then.
  158. llvm::SmallVector<std::pair<Node, int>, 16> node_stack;
  159. for (Node n : roots()) {
  160. node_stack.push_back({n, 0});
  161. }
  162. while (!node_stack.empty()) {
  163. Node n = Node::Invalid;
  164. int depth;
  165. std::tie(n, depth) = node_stack.pop_back_val();
  166. if (PrintNode(output, n, depth, /*preorder=*/true)) {
  167. // Has children, so we descend. We append the children in order here as
  168. // well because they will get reversed when popped off the stack.
  169. for (Node sibling_n : children(n)) {
  170. node_stack.push_back({sibling_n, depth + 1});
  171. }
  172. continue;
  173. }
  174. int next_depth = node_stack.empty() ? 0 : node_stack.back().second;
  175. CARBON_CHECK(next_depth <= depth) << "Cannot have the next depth increase!";
  176. for (int close_children_count : llvm::seq(0, depth - next_depth)) {
  177. (void)close_children_count;
  178. output << "]}";
  179. }
  180. // We always end with a comma and a new line as we'll move to the next
  181. // node at whatever the current level ends up being.
  182. output << " ,\n";
  183. }
  184. output << " ]\n";
  185. }
  186. auto Tree::Verify() const -> ErrorOr<Success> {
  187. llvm::SmallVector<Node> nodes;
  188. // Traverse the tree in postorder.
  189. for (Node n : postorder()) {
  190. const auto& n_impl = node_impls_[n.index];
  191. if (n_impl.has_error && !has_errors_) {
  192. return Error(llvm::formatv(
  193. "Node #{0} has errors, but the tree is not marked as having any.",
  194. n.index));
  195. }
  196. int subtree_size = 1;
  197. if (n_impl.kind.has_bracket()) {
  198. while (true) {
  199. if (nodes.empty()) {
  200. return Error(
  201. llvm::formatv("Node #{0} is a {1} with bracket {2}, but didn't "
  202. "find the bracket.",
  203. n, n_impl.kind, n_impl.kind.bracket()));
  204. }
  205. auto child_impl = node_impls_[nodes.pop_back_val().index];
  206. subtree_size += child_impl.subtree_size;
  207. if (n_impl.kind.bracket() == child_impl.kind) {
  208. break;
  209. }
  210. }
  211. } else {
  212. for (int i : llvm::seq(n_impl.kind.child_count())) {
  213. if (nodes.empty()) {
  214. return Error(llvm::formatv(
  215. "Node #{0} is a {1} with child_count {2}, but only had {3} "
  216. "nodes to consume.",
  217. n, n_impl.kind, n_impl.kind.child_count(), i));
  218. }
  219. auto child_impl = node_impls_[nodes.pop_back_val().index];
  220. subtree_size += child_impl.subtree_size;
  221. }
  222. }
  223. if (n_impl.subtree_size != subtree_size) {
  224. return Error(llvm::formatv(
  225. "Node #{0} is a {1} with subtree_size of {2}, but calculated {3}.", n,
  226. n_impl.kind, n_impl.subtree_size, subtree_size));
  227. }
  228. nodes.push_back(n);
  229. }
  230. // Remaining nodes should all be roots in the tree; make sure they line up.
  231. CARBON_CHECK(nodes.back().index ==
  232. static_cast<int32_t>(node_impls_.size()) - 1)
  233. << nodes.back() << " " << node_impls_.size() - 1;
  234. int prev_index = -1;
  235. for (const auto& n : nodes) {
  236. const auto& n_impl = node_impls_[n.index];
  237. if (n.index - n_impl.subtree_size != prev_index) {
  238. return Error(
  239. llvm::formatv("Node #{0} is a root {1} with subtree_size {2}, but "
  240. "previous root was at #{3}.",
  241. n, n_impl.kind, n_impl.subtree_size, prev_index));
  242. }
  243. prev_index = n.index;
  244. }
  245. if (!has_errors_ && static_cast<int32_t>(node_impls_.size()) !=
  246. tokens_->expected_parse_tree_size()) {
  247. return Error(
  248. llvm::formatv("Tree has {0} nodes and no errors, but "
  249. "Lex::TokenizedBuffer expected {1} nodes for {2} tokens.",
  250. node_impls_.size(), tokens_->expected_parse_tree_size(),
  251. tokens_->size()));
  252. }
  253. return Success();
  254. }
  255. auto Tree::PostorderIterator::Print(llvm::raw_ostream& output) const -> void {
  256. output << node_;
  257. }
  258. auto Tree::SiblingIterator::Print(llvm::raw_ostream& output) const -> void {
  259. output << node_;
  260. }
  261. } // namespace Carbon::Parse