tree_and_subtrees.cpp 10 KB

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