parse.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 "common/check.h"
  5. #include "toolchain/base/pretty_stack_trace_function.h"
  6. #include "toolchain/parse/context.h"
  7. #include "toolchain/parse/node_kind.h"
  8. #include "toolchain/parse/typed_nodes.h"
  9. namespace Carbon::Parse {
  10. auto HandleInvalid(Context& context) -> void {
  11. CARBON_FATAL() << "The Invalid state shouldn't be on the stack: "
  12. << context.PopState();
  13. }
  14. auto Parse(Lex::TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  15. llvm::raw_ostream* vlog_stream) -> Tree {
  16. Lex::TokenLocationTranslator translator(&tokens);
  17. Lex::TokenDiagnosticEmitter emitter(translator, consumer);
  18. // Delegate to the parser.
  19. Tree tree(tokens);
  20. Context context(tree, tokens, emitter, vlog_stream);
  21. PrettyStackTraceFunction context_dumper(
  22. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  23. context.AddLeafNode(NodeKind::FileStart,
  24. context.ConsumeChecked(Lex::TokenKind::FileStart));
  25. context.PushState(State::DeclScopeLoop);
  26. while (!context.state_stack().empty()) {
  27. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  28. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  29. switch (context.state_stack().back().state) {
  30. #define CARBON_PARSE_STATE(Name) \
  31. case State::Name: \
  32. Handle##Name(context); \
  33. break;
  34. #include "toolchain/parse/state.def"
  35. }
  36. }
  37. context.AddLeafNode(NodeKind::FileEnd, *context.position());
  38. if (auto verify = tree.Verify(); !verify.ok()) {
  39. // TODO: This is temporarily printing to stderr directly during development.
  40. // If we can, restrict this to a subtree with the error and add it to the
  41. // stack trace (such as with PrettyStackTraceFunction). Otherwise, switch
  42. // back to vlog_stream prior to broader distribution so that end users are
  43. // hopefully comfortable copy-pasting stderr when there are bugs in tree
  44. // construction.
  45. tree.Print(llvm::errs());
  46. CARBON_FATAL() << "Invalid tree returned by Parse(): " << verify.error();
  47. }
  48. return tree;
  49. }
  50. } // namespace Carbon::Parse