tree.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 HandleInvalid(Context& context) -> void {
  15. CARBON_FATAL() << "The Invalid state shouldn't be on the stack: "
  16. << context.PopState();
  17. }
  18. auto Tree::Parse(Lex::TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  19. llvm::raw_ostream* vlog_stream) -> Tree {
  20. Lex::TokenLocationTranslator translator(&tokens);
  21. Lex::TokenDiagnosticEmitter emitter(translator, consumer);
  22. // Delegate to the parser.
  23. Tree tree(tokens);
  24. Context context(tree, tokens, emitter, vlog_stream);
  25. PrettyStackTraceFunction context_dumper(
  26. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  27. context.AddLeafNode(NodeKind::FileStart,
  28. context.ConsumeChecked(Lex::TokenKind::FileStart));
  29. context.PushState(State::DeclScopeLoop);
  30. while (!context.state_stack().empty()) {
  31. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  32. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  33. switch (context.state_stack().back().state) {
  34. #define CARBON_PARSE_STATE(Name) \
  35. case State::Name: \
  36. Handle##Name(context); \
  37. break;
  38. #include "toolchain/parse/state.def"
  39. }
  40. }
  41. context.AddLeafNode(NodeKind::FileEnd, *context.position());
  42. if (auto verify = tree.Verify(); !verify.ok()) {
  43. // TODO: This is temporarily printing to stderr directly during development.
  44. // If we can, restrict this to a subtree with the error and add it to the
  45. // stack trace (such as with PrettyStackTraceFunction). Otherwise, switch
  46. // back to vlog_stream prior to broader distribution so that end users are
  47. // hopefully comfortable copy-pasting stderr when there are bugs in tree
  48. // construction.
  49. tree.Print(llvm::errs());
  50. CARBON_FATAL() << "Invalid tree returned by Parse(): " << verify.error();
  51. }
  52. return tree;
  53. }
  54. auto Tree::postorder() const -> llvm::iterator_range<PostorderIterator> {
  55. return {PostorderIterator(NodeId(0)),
  56. PostorderIterator(NodeId(node_impls_.size()))};
  57. }
  58. auto Tree::postorder(NodeId n) const
  59. -> llvm::iterator_range<PostorderIterator> {
  60. CARBON_CHECK(n.is_valid());
  61. // The postorder ends after this node, the root, and begins at the start of
  62. // its subtree.
  63. int end_index = n.index + 1;
  64. int start_index = end_index - node_impls_[n.index].subtree_size;
  65. return {PostorderIterator(NodeId(start_index)),
  66. PostorderIterator(NodeId(end_index))};
  67. }
  68. auto Tree::children(NodeId n) const -> llvm::iterator_range<SiblingIterator> {
  69. CARBON_CHECK(n.is_valid());
  70. int end_index = n.index - node_impls_[n.index].subtree_size;
  71. return {SiblingIterator(*this, NodeId(n.index - 1)),
  72. SiblingIterator(*this, NodeId(end_index))};
  73. }
  74. auto Tree::roots() const -> llvm::iterator_range<SiblingIterator> {
  75. return {
  76. SiblingIterator(*this, NodeId(static_cast<int>(node_impls_.size()) - 1)),
  77. SiblingIterator(*this, NodeId(-1))};
  78. }
  79. auto Tree::node_has_error(NodeId n) const -> bool {
  80. CARBON_CHECK(n.is_valid());
  81. return node_impls_[n.index].has_error;
  82. }
  83. auto Tree::node_kind(NodeId n) const -> NodeKind {
  84. CARBON_CHECK(n.is_valid());
  85. return node_impls_[n.index].kind;
  86. }
  87. auto Tree::node_token(NodeId n) const -> Lex::TokenIndex {
  88. CARBON_CHECK(n.is_valid());
  89. return node_impls_[n.index].token;
  90. }
  91. auto Tree::node_subtree_size(NodeId n) const -> int32_t {
  92. CARBON_CHECK(n.is_valid());
  93. return node_impls_[n.index].subtree_size;
  94. }
  95. auto Tree::PrintNode(llvm::raw_ostream& output, NodeId 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_->source().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<NodeId, int>, 16> node_stack;
  127. for (NodeId n : roots()) {
  128. node_stack.push_back({n, 0});
  129. }
  130. while (!node_stack.empty()) {
  131. NodeId n = NodeId::Invalid;
  132. int depth;
  133. std::tie(n, depth) = node_stack.pop_back_val();
  134. for (NodeId sibling_n : children(n)) {
  135. indents[sibling_n.index] = depth + 1;
  136. node_stack.push_back({sibling_n, depth + 1});
  137. }
  138. }
  139. for (NodeId 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_->source().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<NodeId, int>, 16> node_stack;
  159. for (NodeId n : roots()) {
  160. node_stack.push_back({n, 0});
  161. }
  162. while (!node_stack.empty()) {
  163. NodeId n = NodeId::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 (NodeId 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<NodeId> nodes;
  188. // Traverse the tree in postorder.
  189. for (NodeId 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. "NodeId #{0} has errors, but the tree is not marked as having any.",
  194. n.index));
  195. }
  196. if (n_impl.kind == NodeKind::Placeholder) {
  197. return Error(llvm::formatv(
  198. "Node #{0} is a placeholder node that wasn't replaced.", n.index));
  199. }
  200. int subtree_size = 1;
  201. if (n_impl.kind.has_bracket()) {
  202. while (true) {
  203. if (nodes.empty()) {
  204. return Error(
  205. llvm::formatv("NodeId #{0} is a {1} with bracket {2}, but didn't "
  206. "find the bracket.",
  207. n, n_impl.kind, n_impl.kind.bracket()));
  208. }
  209. auto child_impl = node_impls_[nodes.pop_back_val().index];
  210. subtree_size += child_impl.subtree_size;
  211. if (n_impl.kind.bracket() == child_impl.kind) {
  212. break;
  213. }
  214. }
  215. } else {
  216. for (int i : llvm::seq(n_impl.kind.child_count())) {
  217. if (nodes.empty()) {
  218. return Error(llvm::formatv(
  219. "NodeId #{0} is a {1} with child_count {2}, but only had {3} "
  220. "nodes to consume.",
  221. n, n_impl.kind, n_impl.kind.child_count(), i));
  222. }
  223. auto child_impl = node_impls_[nodes.pop_back_val().index];
  224. subtree_size += child_impl.subtree_size;
  225. }
  226. }
  227. if (n_impl.subtree_size != subtree_size) {
  228. return Error(llvm::formatv(
  229. "NodeId #{0} is a {1} with subtree_size of {2}, but calculated {3}.",
  230. n, n_impl.kind, n_impl.subtree_size, subtree_size));
  231. }
  232. nodes.push_back(n);
  233. }
  234. // Remaining nodes should all be roots in the tree; make sure they line up.
  235. CARBON_CHECK(nodes.back().index ==
  236. static_cast<int32_t>(node_impls_.size()) - 1)
  237. << nodes.back() << " " << node_impls_.size() - 1;
  238. int prev_index = -1;
  239. for (const auto& n : nodes) {
  240. const auto& n_impl = node_impls_[n.index];
  241. if (n.index - n_impl.subtree_size != prev_index) {
  242. return Error(
  243. llvm::formatv("NodeId #{0} is a root {1} with subtree_size {2}, but "
  244. "previous root was at #{3}.",
  245. n, n_impl.kind, n_impl.subtree_size, prev_index));
  246. }
  247. prev_index = n.index;
  248. }
  249. if (!has_errors_ && static_cast<int32_t>(node_impls_.size()) !=
  250. tokens_->expected_parse_tree_size()) {
  251. return Error(
  252. llvm::formatv("Tree has {0} nodes and no errors, but "
  253. "Lex::TokenizedBuffer expected {1} nodes for {2} tokens.",
  254. node_impls_.size(), tokens_->expected_parse_tree_size(),
  255. tokens_->size()));
  256. }
  257. return Success();
  258. }
  259. auto Tree::PostorderIterator::Print(llvm::raw_ostream& output) const -> void {
  260. output << node_;
  261. }
  262. auto Tree::SiblingIterator::Print(llvm::raw_ostream& output) const -> void {
  263. output << node_;
  264. }
  265. } // namespace Carbon::Parse