tree_and_subtrees.cpp 10 KB

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