parse_tree.cpp 10 KB

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