tree.cpp 9.7 KB

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