tree_and_subtrees.cpp 10 KB

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