tree_and_subtrees.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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] : llvm::reverse(llvm::zip(tree_->postorder(), depths))) {
  155. for (auto child : children(n)) {
  156. depths[child.index] = depth + 1;
  157. }
  158. }
  159. for (auto [n, depth] : llvm::zip(tree_->postorder(), depths)) {
  160. PrintNode(output, n, depth, /*preorder=*/false);
  161. output << ",\n";
  162. }
  163. output << " ]\n";
  164. }
  165. auto TreeAndSubtrees::PrintPreorder(llvm::raw_ostream& output) const -> void {
  166. output << "- filename: " << tokens_->source().filename() << "\n"
  167. << " parse_tree: [\n";
  168. // The parse tree is stored in postorder. The preorder can be constructed
  169. // by reversing the order of each level of siblings within an RPO. The
  170. // sibling iterators are directly built around RPO and so can be used with a
  171. // stack to produce preorder.
  172. // The roots, like siblings, are in RPO (so reversed), but we add them in
  173. // order here because we'll pop off the stack effectively reversing then.
  174. llvm::SmallVector<std::pair<NodeId, int>, 16> node_stack;
  175. for (NodeId n : roots()) {
  176. node_stack.push_back({n, 0});
  177. }
  178. while (!node_stack.empty()) {
  179. NodeId n = NodeId::None;
  180. int depth;
  181. std::tie(n, depth) = node_stack.pop_back_val();
  182. if (PrintNode(output, n, depth, /*preorder=*/true)) {
  183. // Has children, so we descend. We append the children in order here as
  184. // well because they will get reversed when popped off the stack.
  185. for (NodeId sibling_n : children(n)) {
  186. node_stack.push_back({sibling_n, depth + 1});
  187. }
  188. continue;
  189. }
  190. int next_depth = node_stack.empty() ? 0 : node_stack.back().second;
  191. CARBON_CHECK(next_depth <= depth, "Cannot have the next depth increase!");
  192. for ([[maybe_unused]] auto _ : llvm::seq(depth - next_depth)) {
  193. output << "]}";
  194. }
  195. // We always end with a comma and a new line as we'll move to the next
  196. // node at whatever the current level ends up being.
  197. output << ",\n";
  198. }
  199. output << " ]\n";
  200. }
  201. auto TreeAndSubtrees::CollectMemUsage(MemUsage& mem_usage,
  202. llvm::StringRef label) const -> void {
  203. mem_usage.Collect(MemUsage::ConcatLabel(label, "subtree_sizes_"),
  204. subtree_sizes_);
  205. }
  206. auto TreeAndSubtrees::GetSubtreeTokenRange(NodeId node_id) const
  207. -> Lex::InclusiveTokenRange {
  208. Lex::InclusiveTokenRange range = {.begin = tree_->node_token(node_id),
  209. .end = Lex::TokenIndex::None};
  210. range.end = range.begin;
  211. for (NodeId desc : postorder(node_id)) {
  212. Lex::TokenIndex desc_token = tree_->node_token(desc);
  213. if (!desc_token.has_value()) {
  214. continue;
  215. }
  216. if (desc_token < range.begin) {
  217. range.begin = desc_token;
  218. } else if (desc_token > range.end) {
  219. range.end = desc_token;
  220. }
  221. }
  222. return range;
  223. }
  224. auto TreeAndSubtrees::NodeToDiagnosticLoc(NodeId node_id, bool token_only) const
  225. -> Diagnostics::ConvertedLoc {
  226. // Support the invalid token as a way to emit only the filename, when there
  227. // is no line association.
  228. if (!node_id.has_value()) {
  229. return {{.filename = tree_->tokens().source().filename()}, -1};
  230. }
  231. if (token_only) {
  232. return tree_->tokens().TokenToDiagnosticLoc(tree_->node_token(node_id));
  233. }
  234. // Construct a location that encompasses all tokens that descend from this
  235. // node (including the root).
  236. Lex::InclusiveTokenRange token_range = GetSubtreeTokenRange(node_id);
  237. auto begin_loc = tree_->tokens().TokenToDiagnosticLoc(token_range.begin);
  238. if (token_range.begin == token_range.end) {
  239. return begin_loc;
  240. }
  241. auto end_loc = tree_->tokens().TokenToDiagnosticLoc(token_range.end);
  242. begin_loc.last_byte_offset = end_loc.last_byte_offset;
  243. // For multiline locations we simply return the rest of the line for now
  244. // since true multiline locations are not yet supported.
  245. if (begin_loc.loc.line_number != end_loc.loc.line_number) {
  246. begin_loc.loc.length =
  247. begin_loc.loc.line.size() - begin_loc.loc.column_number + 1;
  248. } else {
  249. if (begin_loc.loc.column_number != end_loc.loc.column_number) {
  250. begin_loc.loc.length = end_loc.loc.column_number + end_loc.loc.length -
  251. begin_loc.loc.column_number;
  252. }
  253. }
  254. return begin_loc;
  255. }
  256. auto TreeAndSubtrees::SiblingIterator::Print(llvm::raw_ostream& output) const
  257. -> void {
  258. output << node_;
  259. }
  260. } // namespace Carbon::Parse