parse_tree.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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/parser/parse_tree.h"
  5. #include <cstdlib>
  6. #include "common/check.h"
  7. #include "llvm/ADT/ArrayRef.h"
  8. #include "llvm/ADT/Optional.h"
  9. #include "llvm/ADT/Sequence.h"
  10. #include "llvm/ADT/SmallSet.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/iterator.h"
  13. #include "llvm/Support/raw_ostream.h"
  14. #include "toolchain/lexer/token_kind.h"
  15. #include "toolchain/parser/parse_node_kind.h"
  16. #include "toolchain/parser/parser2.h"
  17. #include "toolchain/parser/parser_impl.h"
  18. namespace Carbon {
  19. auto ParseTree::Parse(TokenizedBuffer& tokens, DiagnosticConsumer& consumer)
  20. -> ParseTree {
  21. TokenizedBuffer::TokenLocationTranslator translator(
  22. tokens, /*last_line_lexed_to_column=*/nullptr);
  23. TokenDiagnosticEmitter emitter(translator, consumer);
  24. // Delegate to the parser.
  25. // TODO: Edit this to swap between Parser and Parser2. This is manual in order
  26. // to avoid test duplication.
  27. return Parser::Parse(tokens, emitter);
  28. }
  29. auto ParseTree::postorder() const -> llvm::iterator_range<PostorderIterator> {
  30. return {PostorderIterator(Node(0)),
  31. PostorderIterator(Node(node_impls_.size()))};
  32. }
  33. auto ParseTree::postorder(Node n) const
  34. -> llvm::iterator_range<PostorderIterator> {
  35. CARBON_CHECK(n.is_valid());
  36. // The postorder ends after this node, the root, and begins at the start of
  37. // its subtree.
  38. int end_index = n.index_ + 1;
  39. int start_index = end_index - node_impls_[n.index_].subtree_size;
  40. return {PostorderIterator(Node(start_index)),
  41. PostorderIterator(Node(end_index))};
  42. }
  43. auto ParseTree::children(Node n) const
  44. -> llvm::iterator_range<SiblingIterator> {
  45. CARBON_CHECK(n.is_valid());
  46. int end_index = n.index_ - node_impls_[n.index_].subtree_size;
  47. return {SiblingIterator(*this, Node(n.index_ - 1)),
  48. SiblingIterator(*this, Node(end_index))};
  49. }
  50. auto ParseTree::roots() const -> llvm::iterator_range<SiblingIterator> {
  51. return {
  52. SiblingIterator(*this, Node(static_cast<int>(node_impls_.size()) - 1)),
  53. SiblingIterator(*this, Node(-1))};
  54. }
  55. auto ParseTree::node_has_error(Node n) const -> bool {
  56. CARBON_CHECK(n.is_valid());
  57. return node_impls_[n.index_].has_error;
  58. }
  59. auto ParseTree::node_kind(Node n) const -> ParseNodeKind {
  60. CARBON_CHECK(n.is_valid());
  61. return node_impls_[n.index_].kind;
  62. }
  63. auto ParseTree::node_token(Node n) const -> TokenizedBuffer::Token {
  64. CARBON_CHECK(n.is_valid());
  65. return node_impls_[n.index_].token;
  66. }
  67. auto ParseTree::node_subtree_size(Node n) const -> int32_t {
  68. CARBON_CHECK(n.is_valid());
  69. return node_impls_[n.index_].subtree_size;
  70. }
  71. auto ParseTree::GetNodeText(Node n) const -> llvm::StringRef {
  72. CARBON_CHECK(n.is_valid());
  73. return tokens_->GetTokenText(node_impls_[n.index_].token);
  74. }
  75. auto ParseTree::Print(llvm::raw_ostream& output) const -> void {
  76. output << "[\n";
  77. // The parse tree is stored in postorder, but the most natural order to
  78. // visualize is preorder. This is a tree, so the preorder can be constructed
  79. // by reversing the order of each level of siblings within an RPO. The sibling
  80. // iterators are directly built around RPO and so can be used with a stack to
  81. // produce preorder.
  82. // The roots, like siblings, are in RPO (so reversed), but we add them in
  83. // order here because we'll pop off the stack effectively reversing then.
  84. llvm::SmallVector<std::pair<Node, int>, 16> node_stack;
  85. for (Node n : roots()) {
  86. node_stack.push_back({n, 0});
  87. }
  88. while (!node_stack.empty()) {
  89. Node n;
  90. int depth;
  91. std::tie(n, depth) = node_stack.pop_back_val();
  92. const auto& n_impl = node_impls_[n.index()];
  93. for (int unused_indent : llvm::seq(0, depth)) {
  94. (void)unused_indent;
  95. output << " ";
  96. }
  97. output << "{node_index: " << n.index_ << ", kind: '" << n_impl.kind.name()
  98. << "', text: '" << tokens_->GetTokenText(n_impl.token) << "'";
  99. if (n_impl.has_error) {
  100. output << ", has_error: yes";
  101. }
  102. if (n_impl.subtree_size > 1) {
  103. output << ", subtree_size: " << n_impl.subtree_size;
  104. // Has children, so we descend.
  105. output << ", children: [\n";
  106. // We append the children in order here as well because they will get
  107. // reversed when popped off the stack.
  108. for (Node sibling_n : children(n)) {
  109. node_stack.push_back({sibling_n, depth + 1});
  110. }
  111. continue;
  112. }
  113. // This node is finished, so close it up.
  114. CARBON_CHECK(n_impl.subtree_size == 1)
  115. << "Subtree size must always be a positive integer!";
  116. output << "}";
  117. int next_depth = node_stack.empty() ? 0 : node_stack.back().second;
  118. CARBON_CHECK(next_depth <= depth) << "Cannot have the next depth increase!";
  119. for (int close_children_count : llvm::seq(0, depth - next_depth)) {
  120. (void)close_children_count;
  121. output << "]}";
  122. }
  123. // We always end with a comma and a new line as we'll move to the next node
  124. // at whatever the current level ends up being.
  125. output << ",\n";
  126. }
  127. output << "]\n";
  128. }
  129. auto ParseTree::Verify() const -> bool {
  130. // Verify basic tree structure invariants.
  131. llvm::SmallVector<ParseTree::Node, 16> ancestors;
  132. for (Node n : llvm::reverse(postorder())) {
  133. const auto& n_impl = node_impls_[n.index()];
  134. if (n_impl.has_error && !has_errors_) {
  135. llvm::errs()
  136. << "Node #" << n.index()
  137. << " has errors, but the tree is not marked as having any.\n";
  138. return false;
  139. }
  140. if (n_impl.subtree_size > 1) {
  141. if (!ancestors.empty()) {
  142. auto parent_n = ancestors.back();
  143. const auto& parent_n_impl = node_impls_[parent_n.index()];
  144. int end_index = n.index() - n_impl.subtree_size;
  145. int parent_end_index = parent_n.index() - parent_n_impl.subtree_size;
  146. if (parent_end_index > end_index) {
  147. llvm::errs() << "Node #" << n.index() << " has a subtree size of "
  148. << n_impl.subtree_size
  149. << " which extends beyond its parent's (node #"
  150. << parent_n.index() << ") subtree (size "
  151. << parent_n_impl.subtree_size << ")\n";
  152. return false;
  153. }
  154. }
  155. // Has children, so we descend.
  156. ancestors.push_back(n);
  157. continue;
  158. }
  159. if (n_impl.subtree_size < 1) {
  160. llvm::errs() << "Node #" << n.index()
  161. << " has an invalid subtree size of " << n_impl.subtree_size
  162. << "!\n";
  163. return false;
  164. }
  165. // We're going to pop off some levels of the tree. Check each ancestor to
  166. // make sure the offsets are correct.
  167. int next_index = n.index() - 1;
  168. while (!ancestors.empty()) {
  169. ParseTree::Node parent_n = ancestors.back();
  170. if ((parent_n.index() - node_impls_[parent_n.index()].subtree_size) !=
  171. next_index) {
  172. break;
  173. }
  174. ancestors.pop_back();
  175. }
  176. }
  177. if (!ancestors.empty()) {
  178. llvm::errs()
  179. << "Finished walking the parse tree and there are still ancestors:\n";
  180. for (Node ancestor_n : ancestors) {
  181. llvm::errs() << " Node #" << ancestor_n.index() << "\n";
  182. }
  183. return false;
  184. }
  185. return true;
  186. }
  187. auto ParseTree::Node::Print(llvm::raw_ostream& output) const -> void {
  188. output << index();
  189. }
  190. auto ParseTree::PostorderIterator::Print(llvm::raw_ostream& output) const
  191. -> void {
  192. output << node_.index();
  193. }
  194. auto ParseTree::SiblingIterator::Print(llvm::raw_ostream& output) const
  195. -> void {
  196. output << node_.index();
  197. }
  198. } // namespace Carbon