parse_tree.cpp 9.5 KB

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