tree.cpp 10 KB

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