tree.cpp 11 KB

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