parse_tree.cpp 9.6 KB

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