tree.cpp 9.6 KB

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