parse_tree.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 <optional>
  7. #include "common/check.h"
  8. #include "common/error.h"
  9. #include "llvm/ADT/Sequence.h"
  10. #include "llvm/ADT/SmallVector.h"
  11. #include "toolchain/lexer/tokenized_buffer.h"
  12. #include "toolchain/parser/parse_node_kind.h"
  13. #include "toolchain/parser/parser.h"
  14. namespace Carbon {
  15. auto ParseTree::Parse(TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  16. llvm::raw_ostream* vlog_stream) -> ParseTree {
  17. TokenizedBuffer::TokenLocationTranslator translator(
  18. &tokens, /*last_line_lexed_to_column=*/nullptr);
  19. TokenDiagnosticEmitter emitter(translator, consumer);
  20. // Delegate to the parser.
  21. auto tree = Parser::Parse(tokens, emitter, vlog_stream);
  22. if (auto verify = tree.Verify(); !verify.ok()) {
  23. if (vlog_stream) {
  24. tree.Print(*vlog_stream);
  25. }
  26. CARBON_FATAL() << "Invalid tree returned by Parse(): " << verify.error();
  27. }
  28. return tree;
  29. }
  30. auto ParseTree::postorder() const -> llvm::iterator_range<PostorderIterator> {
  31. return {PostorderIterator(Node(0)),
  32. PostorderIterator(Node(node_impls_.size()))};
  33. }
  34. auto ParseTree::postorder(Node n) const
  35. -> llvm::iterator_range<PostorderIterator> {
  36. CARBON_CHECK(n.is_valid());
  37. // The postorder ends after this node, the root, and begins at the start of
  38. // its subtree.
  39. int end_index = n.index + 1;
  40. int start_index = end_index - node_impls_[n.index].subtree_size;
  41. return {PostorderIterator(Node(start_index)),
  42. PostorderIterator(Node(end_index))};
  43. }
  44. auto ParseTree::children(Node n) const
  45. -> llvm::iterator_range<SiblingIterator> {
  46. CARBON_CHECK(n.is_valid());
  47. int end_index = n.index - node_impls_[n.index].subtree_size;
  48. return {SiblingIterator(*this, Node(n.index - 1)),
  49. SiblingIterator(*this, Node(end_index))};
  50. }
  51. auto ParseTree::roots() const -> llvm::iterator_range<SiblingIterator> {
  52. return {
  53. SiblingIterator(*this, Node(static_cast<int>(node_impls_.size()) - 1)),
  54. SiblingIterator(*this, Node(-1))};
  55. }
  56. auto ParseTree::node_has_error(Node n) const -> bool {
  57. CARBON_CHECK(n.is_valid());
  58. return node_impls_[n.index].has_error;
  59. }
  60. auto ParseTree::node_kind(Node n) const -> ParseNodeKind {
  61. CARBON_CHECK(n.is_valid());
  62. return node_impls_[n.index].kind;
  63. }
  64. auto ParseTree::node_token(Node n) const -> TokenizedBuffer::Token {
  65. CARBON_CHECK(n.is_valid());
  66. return node_impls_[n.index].token;
  67. }
  68. auto ParseTree::node_subtree_size(Node n) const -> int32_t {
  69. CARBON_CHECK(n.is_valid());
  70. return node_impls_[n.index].subtree_size;
  71. }
  72. auto ParseTree::GetNodeText(Node n) const -> llvm::StringRef {
  73. CARBON_CHECK(n.is_valid());
  74. return tokens_->GetTokenText(node_impls_[n.index].token);
  75. }
  76. auto ParseTree::PrintNode(llvm::raw_ostream& output, Node n, int depth,
  77. bool preorder) const -> bool {
  78. const auto& n_impl = node_impls_[n.index];
  79. output.indent(2 * depth);
  80. output << "{";
  81. // If children are being added, include node_index in order to disambiguate
  82. // nodes.
  83. if (preorder) {
  84. output << "node_index: " << n << ", ";
  85. }
  86. output << "kind: '" << n_impl.kind << "', text: '"
  87. << tokens_->GetTokenText(n_impl.token) << "'";
  88. if (n_impl.has_error) {
  89. output << ", has_error: yes";
  90. }
  91. if (n_impl.subtree_size > 1) {
  92. output << ", subtree_size: " << n_impl.subtree_size;
  93. if (preorder) {
  94. output << ", children: [\n";
  95. return true;
  96. }
  97. }
  98. output << "}";
  99. return false;
  100. }
  101. auto ParseTree::Print(llvm::raw_ostream& output) const -> void {
  102. // Walk the tree just to calculate depths for each node.
  103. llvm::SmallVector<int> indents;
  104. indents.append(size(), 0);
  105. llvm::SmallVector<std::pair<Node, int>, 16> node_stack;
  106. for (Node n : roots()) {
  107. node_stack.push_back({n, 0});
  108. }
  109. while (!node_stack.empty()) {
  110. Node n = Node::Invalid;
  111. int depth;
  112. std::tie(n, depth) = node_stack.pop_back_val();
  113. for (Node sibling_n : children(n)) {
  114. indents[sibling_n.index] = depth + 1;
  115. node_stack.push_back({sibling_n, depth + 1});
  116. }
  117. }
  118. output << "[\n";
  119. for (Node n : postorder()) {
  120. PrintNode(output, n, indents[n.index], /*preorder=*/false);
  121. output << ",\n";
  122. }
  123. output << "]\n";
  124. }
  125. auto ParseTree::Print(llvm::raw_ostream& output, bool preorder) const -> void {
  126. if (!preorder) {
  127. Print(output);
  128. return;
  129. }
  130. output << "[\n";
  131. // The parse tree is stored in postorder. The preorder can be constructed
  132. // by reversing the order of each level of siblings within an RPO. The
  133. // sibling iterators are directly built around RPO and so can be used with a
  134. // stack to produce preorder.
  135. // The roots, like siblings, are in RPO (so reversed), but we add them in
  136. // order here because we'll pop off the stack effectively reversing then.
  137. llvm::SmallVector<std::pair<Node, int>, 16> node_stack;
  138. for (Node n : roots()) {
  139. node_stack.push_back({n, 0});
  140. }
  141. while (!node_stack.empty()) {
  142. Node n = Node::Invalid;
  143. int depth;
  144. std::tie(n, depth) = node_stack.pop_back_val();
  145. if (PrintNode(output, n, depth, /*preorder=*/true)) {
  146. // Has children, so we descend. We append the children in order here as
  147. // well because they will get reversed when popped off the stack.
  148. for (Node sibling_n : children(n)) {
  149. node_stack.push_back({sibling_n, depth + 1});
  150. }
  151. continue;
  152. }
  153. int next_depth = node_stack.empty() ? 0 : node_stack.back().second;
  154. CARBON_CHECK(next_depth <= depth) << "Cannot have the next depth increase!";
  155. for (int close_children_count : llvm::seq(0, depth - next_depth)) {
  156. (void)close_children_count;
  157. output << "]}";
  158. }
  159. // We always end with a comma and a new line as we'll move to the next
  160. // node at whatever the current level ends up being.
  161. output << ",\n";
  162. }
  163. output << "]\n";
  164. }
  165. auto ParseTree::Verify() const -> ErrorOr<Success> {
  166. llvm::SmallVector<ParseTree::Node> nodes;
  167. // Traverse the tree in postorder.
  168. for (Node n : postorder()) {
  169. const auto& n_impl = node_impls_[n.index];
  170. if (n_impl.has_error && !has_errors_) {
  171. return Error(llvm::formatv(
  172. "Node #{0} has errors, but the tree is not marked as having any.",
  173. n.index));
  174. }
  175. int subtree_size = 1;
  176. if (n_impl.kind.has_bracket()) {
  177. while (true) {
  178. if (nodes.empty()) {
  179. return Error(
  180. llvm::formatv("Node #{0} is a {1} with bracket {2}, but didn't "
  181. "find the bracket.",
  182. n, n_impl.kind, n_impl.kind.bracket()));
  183. }
  184. auto child_impl = node_impls_[nodes.pop_back_val().index];
  185. subtree_size += child_impl.subtree_size;
  186. if (n_impl.kind.bracket() == child_impl.kind) {
  187. break;
  188. }
  189. }
  190. } else {
  191. for (int i = 0; i < n_impl.kind.child_count(); ++i) {
  192. if (nodes.empty()) {
  193. return Error(llvm::formatv(
  194. "Node #{0} is a {1} with child_count {2}, but only had {3} "
  195. "nodes to consume.",
  196. n, n_impl.kind, n_impl.kind.child_count(), i));
  197. }
  198. auto child_impl = node_impls_[nodes.pop_back_val().index];
  199. subtree_size += child_impl.subtree_size;
  200. }
  201. }
  202. if (n_impl.subtree_size != subtree_size) {
  203. return Error(llvm::formatv(
  204. "Node #{0} is a {1} with subtree_size of {2}, but calculated {3}.", n,
  205. n_impl.kind, n_impl.subtree_size, subtree_size));
  206. }
  207. nodes.push_back(n);
  208. }
  209. // Remaining nodes should all be roots in the tree; make sure they line up.
  210. CARBON_CHECK(nodes.back().index ==
  211. static_cast<int32_t>(node_impls_.size()) - 1)
  212. << nodes.back() << " " << node_impls_.size() - 1;
  213. int prev_index = -1;
  214. for (const auto& n : nodes) {
  215. const auto& n_impl = node_impls_[n.index];
  216. if (n.index - n_impl.subtree_size != prev_index) {
  217. return Error(
  218. llvm::formatv("Node #{0} is a root {1} with subtree_size {2}, but "
  219. "previous root was at #{3}.",
  220. n, n_impl.kind, n_impl.subtree_size, prev_index));
  221. }
  222. prev_index = n.index;
  223. }
  224. if (!has_errors_ &&
  225. static_cast<int32_t>(node_impls_.size()) != tokens_->size()) {
  226. return Error(
  227. llvm::formatv("ParseTree has {0} nodes and no errors, but "
  228. "TokenizedBuffer has {1} tokens.",
  229. node_impls_.size(), tokens_->size()));
  230. }
  231. return Success();
  232. }
  233. auto ParseTree::PostorderIterator::Print(llvm::raw_ostream& output) const
  234. -> void {
  235. output << node_;
  236. }
  237. auto ParseTree::SiblingIterator::Print(llvm::raw_ostream& output) const
  238. -> void {
  239. output << node_;
  240. }
  241. } // namespace Carbon