tree.cpp 9.4 KB

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