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 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. if (vlog_stream) {
  44. tree.Print(*vlog_stream);
  45. }
  46. CARBON_FATAL() << "Invalid tree returned by Parse(): " << verify.error();
  47. }
  48. return tree;
  49. }
  50. auto Tree::postorder() const -> llvm::iterator_range<PostorderIterator> {
  51. return {PostorderIterator(NodeId(0)),
  52. PostorderIterator(NodeId(node_impls_.size()))};
  53. }
  54. auto Tree::postorder(NodeId n) const
  55. -> 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(NodeId(start_index)),
  62. PostorderIterator(NodeId(end_index))};
  63. }
  64. auto Tree::children(NodeId 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, NodeId(n.index - 1)),
  68. SiblingIterator(*this, NodeId(end_index))};
  69. }
  70. auto Tree::roots() const -> llvm::iterator_range<SiblingIterator> {
  71. return {
  72. SiblingIterator(*this, NodeId(static_cast<int>(node_impls_.size()) - 1)),
  73. SiblingIterator(*this, NodeId(-1))};
  74. }
  75. auto Tree::node_has_error(NodeId n) const -> bool {
  76. CARBON_CHECK(n.is_valid());
  77. return node_impls_[n.index].has_error;
  78. }
  79. auto Tree::node_kind(NodeId n) const -> NodeKind {
  80. CARBON_CHECK(n.is_valid());
  81. return node_impls_[n.index].kind;
  82. }
  83. auto Tree::node_token(NodeId n) const -> Lex::TokenIndex {
  84. CARBON_CHECK(n.is_valid());
  85. return node_impls_[n.index].token;
  86. }
  87. auto Tree::node_subtree_size(NodeId n) const -> int32_t {
  88. CARBON_CHECK(n.is_valid());
  89. return node_impls_[n.index].subtree_size;
  90. }
  91. auto Tree::PrintNode(llvm::raw_ostream& output, NodeId n, int depth,
  92. bool preorder) const -> bool {
  93. const auto& n_impl = node_impls_[n.index];
  94. output.indent(2 * (depth + 2));
  95. output << "{";
  96. // If children are being added, include node_index in order to disambiguate
  97. // nodes.
  98. if (preorder) {
  99. output << "node_index: " << n << ", ";
  100. }
  101. output << "kind: '" << n_impl.kind << "', text: '"
  102. << tokens_->GetTokenText(n_impl.token) << "'";
  103. if (n_impl.has_error) {
  104. output << ", has_error: yes";
  105. }
  106. if (n_impl.subtree_size > 1) {
  107. output << ", subtree_size: " << n_impl.subtree_size;
  108. if (preorder) {
  109. output << ", children: [\n";
  110. return true;
  111. }
  112. }
  113. output << "}";
  114. return false;
  115. }
  116. auto Tree::Print(llvm::raw_ostream& output) const -> void {
  117. output << "- filename: " << tokens_->source().filename() << "\n"
  118. << " parse_tree: [\n";
  119. // Walk the tree just to calculate depths for each node.
  120. llvm::SmallVector<int> indents;
  121. indents.append(size(), 0);
  122. llvm::SmallVector<std::pair<NodeId, int>, 16> node_stack;
  123. for (NodeId n : roots()) {
  124. node_stack.push_back({n, 0});
  125. }
  126. while (!node_stack.empty()) {
  127. NodeId n = NodeId::Invalid;
  128. int depth;
  129. std::tie(n, depth) = node_stack.pop_back_val();
  130. for (NodeId sibling_n : children(n)) {
  131. indents[sibling_n.index] = depth + 1;
  132. node_stack.push_back({sibling_n, depth + 1});
  133. }
  134. }
  135. for (NodeId n : postorder()) {
  136. PrintNode(output, n, indents[n.index], /*preorder=*/false);
  137. output << ",\n";
  138. }
  139. output << " ]\n";
  140. }
  141. auto Tree::Print(llvm::raw_ostream& output, bool preorder) const -> void {
  142. if (!preorder) {
  143. Print(output);
  144. return;
  145. }
  146. output << "- filename: " << tokens_->source().filename() << "\n"
  147. << " parse_tree: [\n";
  148. // The parse tree is stored in postorder. The preorder can be constructed
  149. // by reversing the order of each level of siblings within an RPO. The
  150. // sibling iterators are directly built around RPO and so can be used with a
  151. // stack to produce preorder.
  152. // The roots, like siblings, are in RPO (so reversed), but we add them in
  153. // order here because we'll pop off the stack effectively reversing then.
  154. llvm::SmallVector<std::pair<NodeId, int>, 16> node_stack;
  155. for (NodeId n : roots()) {
  156. node_stack.push_back({n, 0});
  157. }
  158. while (!node_stack.empty()) {
  159. NodeId n = NodeId::Invalid;
  160. int depth;
  161. std::tie(n, depth) = node_stack.pop_back_val();
  162. if (PrintNode(output, n, depth, /*preorder=*/true)) {
  163. // Has children, so we descend. We append the children in order here as
  164. // well because they will get reversed when popped off the stack.
  165. for (NodeId sibling_n : children(n)) {
  166. node_stack.push_back({sibling_n, depth + 1});
  167. }
  168. continue;
  169. }
  170. int next_depth = node_stack.empty() ? 0 : node_stack.back().second;
  171. CARBON_CHECK(next_depth <= depth) << "Cannot have the next depth increase!";
  172. for (int close_children_count : llvm::seq(0, depth - next_depth)) {
  173. (void)close_children_count;
  174. output << "]}";
  175. }
  176. // We always end with a comma and a new line as we'll move to the next
  177. // node at whatever the current level ends up being.
  178. output << " ,\n";
  179. }
  180. output << " ]\n";
  181. }
  182. auto Tree::Verify() const -> ErrorOr<Success> {
  183. llvm::SmallVector<NodeId> nodes;
  184. // Traverse the tree in postorder.
  185. for (NodeId n : postorder()) {
  186. const auto& n_impl = node_impls_[n.index];
  187. if (n_impl.has_error && !has_errors_) {
  188. return Error(llvm::formatv(
  189. "NodeId #{0} has errors, but the tree is not marked as having any.",
  190. n.index));
  191. }
  192. if (n_impl.kind == NodeKind::Placeholder) {
  193. return Error(llvm::formatv(
  194. "Node #{0} is a placeholder node that wasn't replaced.", 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("NodeId #{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. "NodeId #{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. "NodeId #{0} is a {1} with subtree_size of {2}, but calculated {3}.",
  226. n, 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("NodeId #{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