tree_and_subtrees.cpp 10 KB

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