tree.cpp 11 KB

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