parse_tree.cpp 7.3 KB

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