tree.cpp 9.5 KB

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