tree_and_subtrees.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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_and_subtrees.h"
  5. #include <tuple>
  6. #include <utility>
  7. #include "toolchain/base/fixed_size_value_store.h"
  8. #include "toolchain/lex/token_index.h"
  9. namespace Carbon::Parse {
  10. TreeAndSubtrees::TreeAndSubtrees(const Lex::TokenizedBuffer& tokens,
  11. const Tree& tree)
  12. : tokens_(&tokens),
  13. tree_(&tree),
  14. subtree_sizes_(
  15. SubtreeSizeStore::MakeForOverwriteWithExplicitSize(tree_->size())) {
  16. // A stack of nodes which haven't yet been used as children.
  17. llvm::SmallVector<NodeId> size_stack;
  18. for (auto n : tree.postorder()) {
  19. // Nodes always include themselves.
  20. int32_t size = 1;
  21. auto kind = tree.node_kind(n);
  22. if (kind.has_child_count()) {
  23. // When the child count is set, remove the specific number from the stack.
  24. CARBON_CHECK(
  25. static_cast<int32_t>(size_stack.size()) >= kind.child_count(),
  26. "Need {0} children for {1}, have {2} available", kind.child_count(),
  27. kind, size_stack.size());
  28. for (auto i : llvm::seq(kind.child_count())) {
  29. auto child = size_stack.pop_back_val();
  30. CARBON_CHECK(static_cast<size_t>(child.index) < subtree_sizes_.size());
  31. size += subtree_sizes_.Get(child);
  32. if (kind.has_bracket() && i == kind.child_count() - 1) {
  33. CARBON_CHECK(kind.bracket() == tree.node_kind(child),
  34. "Node {0} with child count {1} needs bracket {2}, found "
  35. "wrong bracket {3}",
  36. kind, kind.child_count(), kind.bracket(),
  37. tree.node_kind(child));
  38. }
  39. }
  40. } else {
  41. while (true) {
  42. CARBON_CHECK(!size_stack.empty(), "Node {0} is missing bracket {1}",
  43. kind, kind.bracket());
  44. auto child = size_stack.pop_back_val();
  45. size += subtree_sizes_.Get(child);
  46. if (kind.bracket() == tree.node_kind(child)) {
  47. break;
  48. }
  49. }
  50. }
  51. size_stack.push_back(n);
  52. subtree_sizes_.Set(n, size);
  53. }
  54. // Remaining nodes should all be roots in the tree; make sure they line up.
  55. CARBON_CHECK(
  56. size_stack.back().index == static_cast<int32_t>(tree_->size()) - 1,
  57. "{0} {1}", size_stack.back(), tree_->size() - 1);
  58. int prev_index = -1;
  59. for (const auto& n : size_stack) {
  60. CARBON_CHECK(n.index - subtree_sizes_.Get(n) == prev_index,
  61. "NodeId {0} is a root {1} with subtree_size {2}, but previous "
  62. "root was at {3}.",
  63. n, tree_->node_kind(n), subtree_sizes_.Get(n), prev_index);
  64. prev_index = n.index;
  65. }
  66. }
  67. auto TreeAndSubtrees::VerifyExtract(NodeId node_id, NodeKind kind,
  68. ErrorBuilder* trace) const -> bool {
  69. switch (kind) {
  70. #define CARBON_PARSE_NODE_KIND(Name) \
  71. case NodeKind::Name: \
  72. return VerifyExtractAs<Name>(node_id, trace).has_value();
  73. #include "toolchain/parse/node_kind.def"
  74. }
  75. }
  76. auto TreeAndSubtrees::Verify() const -> ErrorOr<Success> {
  77. // Validate that each node extracts successfully when not marked as having an
  78. // error.
  79. //
  80. // Without this code, a 10 mloc test case of lex & parse takes 4.129 s ± 0.041
  81. // s. With this additional verification, it takes 5.768 s ± 0.036 s.
  82. for (NodeId n : tree_->postorder()) {
  83. if (tree_->node_has_error(n)) {
  84. continue;
  85. }
  86. auto node_kind = tree_->node_kind(n);
  87. if (!VerifyExtract(n, node_kind, nullptr)) {
  88. ErrorBuilder trace;
  89. trace << llvm::formatv(
  90. "NodeId #{0} couldn't be extracted as a {1}. Trace:\n", n, node_kind);
  91. VerifyExtract(n, node_kind, &trace);
  92. return trace;
  93. }
  94. }
  95. // Validate the roots. Also ensures Tree::ExtractFile() doesn't error.
  96. if (!TryExtractNodeFromChildren<File>(NodeId::None, roots(), nullptr)) {
  97. ErrorBuilder trace;
  98. trace << "Roots of tree couldn't be extracted as a `File`. Trace:\n";
  99. TryExtractNodeFromChildren<File>(NodeId::None, roots(), &trace);
  100. return trace;
  101. }
  102. return Success();
  103. }
  104. auto TreeAndSubtrees::postorder(NodeId n) const
  105. -> llvm::iterator_range<Tree::PostorderIterator> {
  106. // The postorder ends after this node, the root, and begins at the begin of
  107. // its subtree.
  108. int begin_index = n.index - subtree_sizes_.Get(n) + 1;
  109. return Tree::PostorderIterator::MakeRange(NodeId(begin_index), n);
  110. }
  111. auto TreeAndSubtrees::children(NodeId n) const
  112. -> llvm::iterator_range<SiblingIterator> {
  113. CARBON_CHECK(n.has_value());
  114. int end_index = n.index - subtree_sizes_.Get(n);
  115. return llvm::iterator_range<SiblingIterator>(
  116. SiblingIterator(*this, NodeId(n.index - 1)),
  117. SiblingIterator(*this, NodeId(end_index)));
  118. }
  119. auto TreeAndSubtrees::roots() const -> llvm::iterator_range<SiblingIterator> {
  120. return llvm::iterator_range<SiblingIterator>(
  121. SiblingIterator(*this,
  122. NodeId(static_cast<int>(subtree_sizes_.size()) - 1)),
  123. SiblingIterator(*this, NodeId(-1)));
  124. }
  125. auto TreeAndSubtrees::PrintNode(llvm::raw_ostream& output, NodeId n, int depth,
  126. bool preorder) const -> bool {
  127. output.indent(2 * (depth + 2));
  128. output << "{";
  129. // If children are being added, include node_index in order to disambiguate
  130. // nodes.
  131. if (preorder) {
  132. output << "node_index: " << n.index << ", ";
  133. }
  134. output << "kind: '" << tree_->node_kind(n) << "', text: '"
  135. << tokens_->GetTokenText(tree_->node_token(n)) << "'";
  136. if (tree_->node_has_error(n)) {
  137. output << ", has_error: yes";
  138. }
  139. if (subtree_sizes_.Get(n) > 1) {
  140. output << ", subtree_size: " << subtree_sizes_.Get(n);
  141. if (preorder) {
  142. output << ", children: [\n";
  143. return true;
  144. }
  145. }
  146. output << "}";
  147. return false;
  148. }
  149. auto TreeAndSubtrees::Print(llvm::raw_ostream& output) const -> void {
  150. output << "- filename: " << tokens_->source().filename() << "\n"
  151. << " parse_tree: [\n";
  152. // Walk the tree in reverse, just to calculate depths for each node.
  153. llvm::SmallVector<int> depths(tree_->size(), 0);
  154. for (auto [n, depth] :
  155. llvm::reverse(llvm::zip_equal(tree_->postorder(), depths))) {
  156. for (auto child : children(n)) {
  157. depths[child.index] = depth + 1;
  158. }
  159. }
  160. for (auto [n, depth] : llvm::zip_equal(tree_->postorder(), depths)) {
  161. PrintNode(output, n, depth, /*preorder=*/false);
  162. output << ",\n";
  163. }
  164. output << " ]\n";
  165. }
  166. auto TreeAndSubtrees::PrintPreorder(llvm::raw_ostream& output) const -> void {
  167. output << "- filename: " << tokens_->source().filename() << "\n"
  168. << " parse_tree: [\n";
  169. // The parse tree is stored in postorder. The preorder can be constructed
  170. // by reversing the order of each level of siblings within an RPO. The
  171. // sibling iterators are directly built around RPO and so can be used with a
  172. // stack to produce preorder.
  173. // The roots, like siblings, are in RPO (so reversed), but we add them in
  174. // order here because we'll pop off the stack effectively reversing then.
  175. llvm::SmallVector<std::pair<NodeId, int>, 16> node_stack;
  176. for (NodeId n : roots()) {
  177. node_stack.push_back({n, 0});
  178. }
  179. while (!node_stack.empty()) {
  180. NodeId n = NodeId::None;
  181. int depth;
  182. std::tie(n, depth) = node_stack.pop_back_val();
  183. if (PrintNode(output, n, depth, /*preorder=*/true)) {
  184. // Has children, so we descend. We append the children in order here as
  185. // well because they will get reversed when popped off the stack.
  186. for (NodeId sibling_n : children(n)) {
  187. node_stack.push_back({sibling_n, depth + 1});
  188. }
  189. continue;
  190. }
  191. int next_depth = node_stack.empty() ? 0 : node_stack.back().second;
  192. CARBON_CHECK(next_depth <= depth, "Cannot have the next depth increase!");
  193. for ([[maybe_unused]] auto _ : llvm::seq(depth - next_depth)) {
  194. output << "]}";
  195. }
  196. // We always end with a comma and a new line as we'll move to the next
  197. // node at whatever the current level ends up being.
  198. output << ",\n";
  199. }
  200. output << " ]\n";
  201. }
  202. auto TreeAndSubtrees::CollectMemUsage(MemUsage& mem_usage,
  203. llvm::StringRef label) const -> void {
  204. mem_usage.Collect(MemUsage::ConcatLabel(label, "subtree_sizes_"),
  205. subtree_sizes_);
  206. }
  207. auto TreeAndSubtrees::GetSubtreeTokenRange(NodeId node_id) const
  208. -> Lex::InclusiveTokenRange {
  209. Lex::InclusiveTokenRange range = {.begin = tree_->node_token(node_id),
  210. .end = Lex::TokenIndex::None};
  211. range.end = range.begin;
  212. for (NodeId desc : postorder(node_id)) {
  213. Lex::TokenIndex desc_token = tree_->node_token(desc);
  214. if (!desc_token.has_value()) {
  215. continue;
  216. }
  217. if (desc_token < range.begin) {
  218. range.begin = desc_token;
  219. } else if (desc_token > range.end) {
  220. range.end = desc_token;
  221. }
  222. }
  223. return range;
  224. }
  225. auto TreeAndSubtrees::NodeToDiagnosticLoc(NodeId node_id, bool token_only) const
  226. -> Diagnostics::ConvertedLoc {
  227. // Support the invalid token as a way to emit only the filename, when there
  228. // is no line association.
  229. if (!node_id.has_value()) {
  230. return {{.filename = tree_->tokens().source().filename()}, -1};
  231. }
  232. if (token_only) {
  233. return tree_->tokens().TokenToDiagnosticLoc(tree_->node_token(node_id));
  234. }
  235. // Construct a location that encompasses all tokens that descend from this
  236. // node (including the root).
  237. Lex::InclusiveTokenRange token_range = GetSubtreeTokenRange(node_id);
  238. auto begin_loc = tree_->tokens().TokenToDiagnosticLoc(token_range.begin);
  239. if (token_range.begin == token_range.end) {
  240. return begin_loc;
  241. }
  242. auto end_loc = tree_->tokens().TokenToDiagnosticLoc(token_range.end);
  243. begin_loc.last_byte_offset = end_loc.last_byte_offset;
  244. // For multiline locations we simply return the rest of the line for now
  245. // since true multiline locations are not yet supported.
  246. if (begin_loc.loc.line_number != end_loc.loc.line_number) {
  247. begin_loc.loc.length =
  248. begin_loc.loc.line.size() - begin_loc.loc.column_number + 1;
  249. } else {
  250. if (begin_loc.loc.column_number != end_loc.loc.column_number) {
  251. begin_loc.loc.length = end_loc.loc.column_number + end_loc.loc.length -
  252. begin_loc.loc.column_number;
  253. }
  254. }
  255. return begin_loc;
  256. }
  257. auto TreeAndSubtrees::SiblingIterator::Print(llvm::raw_ostream& output) const
  258. -> void {
  259. output << node_;
  260. }
  261. } // namespace Carbon::Parse