tree.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. #include "toolchain/parse/typed_nodes.h"
  14. namespace Carbon::Parse {
  15. auto HandleInvalid(Context& context) -> void {
  16. CARBON_FATAL() << "The Invalid state shouldn't be on the stack: "
  17. << context.PopState();
  18. }
  19. auto Tree::Parse(Lex::TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  20. llvm::raw_ostream* vlog_stream) -> Tree {
  21. Lex::TokenLocationTranslator translator(&tokens);
  22. Lex::TokenDiagnosticEmitter emitter(translator, consumer);
  23. // Delegate to the parser.
  24. Tree tree(tokens);
  25. Context context(tree, tokens, emitter, vlog_stream);
  26. PrettyStackTraceFunction context_dumper(
  27. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  28. context.AddLeafNode(NodeKind::FileStart,
  29. context.ConsumeChecked(Lex::TokenKind::FileStart));
  30. context.PushState(State::DeclScopeLoop);
  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. // TODO: This is temporarily printing to stderr directly during development.
  45. // If we can, restrict this to a subtree with the error and add it to the
  46. // stack trace (such as with PrettyStackTraceFunction). Otherwise, switch
  47. // back to vlog_stream prior to broader distribution so that end users are
  48. // hopefully comfortable copy-pasting stderr when there are bugs in tree
  49. // construction.
  50. tree.Print(llvm::errs());
  51. CARBON_FATAL() << "Invalid tree returned by Parse(): " << verify.error();
  52. }
  53. return tree;
  54. }
  55. auto Tree::postorder() const -> llvm::iterator_range<PostorderIterator> {
  56. return {PostorderIterator(NodeId(0)),
  57. PostorderIterator(NodeId(node_impls_.size()))};
  58. }
  59. auto Tree::postorder(NodeId n) const
  60. -> llvm::iterator_range<PostorderIterator> {
  61. CARBON_CHECK(n.is_valid());
  62. // The postorder ends after this node, the root, and begins at the start of
  63. // its subtree.
  64. int end_index = n.index + 1;
  65. int start_index = end_index - node_impls_[n.index].subtree_size;
  66. return {PostorderIterator(NodeId(start_index)),
  67. PostorderIterator(NodeId(end_index))};
  68. }
  69. auto Tree::children(NodeId n) const -> llvm::iterator_range<SiblingIterator> {
  70. CARBON_CHECK(n.is_valid());
  71. int end_index = n.index - node_impls_[n.index].subtree_size;
  72. return {SiblingIterator(*this, NodeId(n.index - 1)),
  73. SiblingIterator(*this, NodeId(end_index))};
  74. }
  75. auto Tree::roots() const -> llvm::iterator_range<SiblingIterator> {
  76. return {
  77. SiblingIterator(*this, NodeId(static_cast<int>(node_impls_.size()) - 1)),
  78. SiblingIterator(*this, NodeId(-1))};
  79. }
  80. auto Tree::node_has_error(NodeId n) const -> bool {
  81. CARBON_CHECK(n.is_valid());
  82. return node_impls_[n.index].has_error;
  83. }
  84. auto Tree::node_kind(NodeId n) const -> NodeKind {
  85. CARBON_CHECK(n.is_valid());
  86. return node_impls_[n.index].kind;
  87. }
  88. auto Tree::node_token(NodeId n) const -> Lex::TokenIndex {
  89. CARBON_CHECK(n.is_valid());
  90. return node_impls_[n.index].token;
  91. }
  92. auto Tree::node_subtree_size(NodeId n) const -> int32_t {
  93. CARBON_CHECK(n.is_valid());
  94. return node_impls_[n.index].subtree_size;
  95. }
  96. auto Tree::PrintNode(llvm::raw_ostream& output, NodeId n, int depth,
  97. bool preorder) const -> bool {
  98. const auto& n_impl = node_impls_[n.index];
  99. output.indent(2 * (depth + 2));
  100. output << "{";
  101. // If children are being added, include node_index in order to disambiguate
  102. // nodes.
  103. if (preorder) {
  104. output << "node_index: " << n << ", ";
  105. }
  106. output << "kind: '" << n_impl.kind << "', text: '"
  107. << tokens_->GetTokenText(n_impl.token) << "'";
  108. if (n_impl.has_error) {
  109. output << ", has_error: yes";
  110. }
  111. if (n_impl.subtree_size > 1) {
  112. output << ", subtree_size: " << n_impl.subtree_size;
  113. if (preorder) {
  114. output << ", children: [\n";
  115. return true;
  116. }
  117. }
  118. output << "}";
  119. return false;
  120. }
  121. auto Tree::Print(llvm::raw_ostream& output) const -> void {
  122. output << "- filename: " << tokens_->source().filename() << "\n"
  123. << " parse_tree: [\n";
  124. // Walk the tree just to calculate depths for each node.
  125. llvm::SmallVector<int> indents;
  126. indents.append(size(), 0);
  127. llvm::SmallVector<std::pair<NodeId, int>, 16> node_stack;
  128. for (NodeId n : roots()) {
  129. node_stack.push_back({n, 0});
  130. }
  131. while (!node_stack.empty()) {
  132. NodeId n = NodeId::Invalid;
  133. int depth;
  134. std::tie(n, depth) = node_stack.pop_back_val();
  135. for (NodeId sibling_n : children(n)) {
  136. indents[sibling_n.index] = depth + 1;
  137. node_stack.push_back({sibling_n, depth + 1});
  138. }
  139. }
  140. for (NodeId n : postorder()) {
  141. PrintNode(output, n, indents[n.index], /*preorder=*/false);
  142. output << ",\n";
  143. }
  144. output << " ]\n";
  145. }
  146. auto Tree::Print(llvm::raw_ostream& output, bool preorder) const -> void {
  147. if (!preorder) {
  148. Print(output);
  149. return;
  150. }
  151. output << "- filename: " << tokens_->source().filename() << "\n"
  152. << " parse_tree: [\n";
  153. // The parse tree is stored in postorder. The preorder can be constructed
  154. // by reversing the order of each level of siblings within an RPO. The
  155. // sibling iterators are directly built around RPO and so can be used with a
  156. // stack to produce preorder.
  157. // The roots, like siblings, are in RPO (so reversed), but we add them in
  158. // order here because we'll pop off the stack effectively reversing then.
  159. llvm::SmallVector<std::pair<NodeId, int>, 16> node_stack;
  160. for (NodeId n : roots()) {
  161. node_stack.push_back({n, 0});
  162. }
  163. while (!node_stack.empty()) {
  164. NodeId n = NodeId::Invalid;
  165. int depth;
  166. std::tie(n, depth) = node_stack.pop_back_val();
  167. if (PrintNode(output, n, depth, /*preorder=*/true)) {
  168. // Has children, so we descend. We append the children in order here as
  169. // well because they will get reversed when popped off the stack.
  170. for (NodeId sibling_n : children(n)) {
  171. node_stack.push_back({sibling_n, depth + 1});
  172. }
  173. continue;
  174. }
  175. int next_depth = node_stack.empty() ? 0 : node_stack.back().second;
  176. CARBON_CHECK(next_depth <= depth) << "Cannot have the next depth increase!";
  177. for (int close_children_count : llvm::seq(0, depth - next_depth)) {
  178. (void)close_children_count;
  179. output << "]}";
  180. }
  181. // We always end with a comma and a new line as we'll move to the next
  182. // node at whatever the current level ends up being.
  183. output << " ,\n";
  184. }
  185. output << " ]\n";
  186. }
  187. static auto TestExtract(const Tree* tree, NodeId node_id, NodeKind kind,
  188. ErrorBuilder* trace) -> bool {
  189. switch (kind) {
  190. #define CARBON_PARSE_NODE_KIND(Name) \
  191. case NodeKind::Name: \
  192. return tree->VerifyExtractAs<Name>(node_id, trace).has_value();
  193. #include "toolchain/parse/node_kind.def"
  194. }
  195. }
  196. auto Tree::Verify() const -> ErrorOr<Success> {
  197. llvm::SmallVector<NodeId> nodes;
  198. // Traverse the tree in postorder.
  199. for (NodeId n : postorder()) {
  200. const auto& n_impl = node_impls_[n.index];
  201. if (n_impl.has_error && !has_errors_) {
  202. return Error(llvm::formatv(
  203. "NodeId #{0} has errors, but the tree is not marked as having any.",
  204. n.index));
  205. }
  206. if (n_impl.kind == NodeKind::Placeholder) {
  207. return Error(llvm::formatv(
  208. "Node #{0} is a placeholder node that wasn't replaced.", n.index));
  209. }
  210. // Should extract successfully if node not marked as having an error.
  211. // Without this code, a 10 mloc test case of lex & parse takes
  212. // 4.129 s ± 0.041 s. With this additional verification, it takes
  213. // 5.768 s ± 0.036 s.
  214. if (!n_impl.has_error && !TestExtract(this, n, n_impl.kind, nullptr)) {
  215. ErrorBuilder trace;
  216. trace << llvm::formatv(
  217. "NodeId #{0} couldn't be extracted as a {1}. Trace:\n", n,
  218. n_impl.kind);
  219. TestExtract(this, n, n_impl.kind, &trace);
  220. return trace;
  221. }
  222. int subtree_size = 1;
  223. if (n_impl.kind.has_bracket()) {
  224. while (true) {
  225. if (nodes.empty()) {
  226. return Error(
  227. llvm::formatv("NodeId #{0} is a {1} with bracket {2}, but didn't "
  228. "find the bracket.",
  229. n, n_impl.kind, n_impl.kind.bracket()));
  230. }
  231. auto child_impl = node_impls_[nodes.pop_back_val().index];
  232. subtree_size += child_impl.subtree_size;
  233. if (n_impl.kind.bracket() == child_impl.kind) {
  234. break;
  235. }
  236. }
  237. } else {
  238. for (int i : llvm::seq(n_impl.kind.child_count())) {
  239. if (nodes.empty()) {
  240. return Error(llvm::formatv(
  241. "NodeId #{0} is a {1} with child_count {2}, but only had {3} "
  242. "nodes to consume.",
  243. n, n_impl.kind, n_impl.kind.child_count(), i));
  244. }
  245. auto child_impl = node_impls_[nodes.pop_back_val().index];
  246. subtree_size += child_impl.subtree_size;
  247. }
  248. }
  249. if (n_impl.subtree_size != subtree_size) {
  250. return Error(llvm::formatv(
  251. "NodeId #{0} is a {1} with subtree_size of {2}, but calculated {3}.",
  252. n, n_impl.kind, n_impl.subtree_size, subtree_size));
  253. }
  254. nodes.push_back(n);
  255. }
  256. // Remaining nodes should all be roots in the tree; make sure they line up.
  257. CARBON_CHECK(nodes.back().index ==
  258. static_cast<int32_t>(node_impls_.size()) - 1)
  259. << nodes.back() << " " << node_impls_.size() - 1;
  260. int prev_index = -1;
  261. for (const auto& n : nodes) {
  262. const auto& n_impl = node_impls_[n.index];
  263. if (n.index - n_impl.subtree_size != prev_index) {
  264. return Error(
  265. llvm::formatv("NodeId #{0} is a root {1} with subtree_size {2}, but "
  266. "previous root was at #{3}.",
  267. n, n_impl.kind, n_impl.subtree_size, prev_index));
  268. }
  269. prev_index = n.index;
  270. }
  271. // Validate the roots, ensures Tree::ExtractFile() doesn't CHECK-fail.
  272. if (!TryExtractNodeFromChildren<File>(roots(), nullptr)) {
  273. ErrorBuilder trace;
  274. trace << "Roots of tree couldn't be extracted as a `File`. Trace:\n";
  275. TryExtractNodeFromChildren<File>(roots(), &trace);
  276. return trace;
  277. }
  278. if (!has_errors_ && static_cast<int32_t>(node_impls_.size()) !=
  279. tokens_->expected_parse_tree_size()) {
  280. return Error(
  281. llvm::formatv("Tree has {0} nodes and no errors, but "
  282. "Lex::TokenizedBuffer expected {1} nodes for {2} tokens.",
  283. node_impls_.size(), tokens_->expected_parse_tree_size(),
  284. tokens_->size()));
  285. }
  286. return Success();
  287. }
  288. auto Tree::PostorderIterator::Print(llvm::raw_ostream& output) const -> void {
  289. output << node_;
  290. }
  291. auto Tree::SiblingIterator::Print(llvm::raw_ostream& output) const -> void {
  292. output << node_;
  293. }
  294. } // namespace Carbon::Parse