parse_tree.cpp 8.2 KB

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