parse_tree.cpp 7.0 KB

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