parse_tree.cpp 9.7 KB

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