parse.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. namespace Carbon::Parse {
  9. // Declare handlers for each parse state.
  10. #define CARBON_PARSE_STATE(Name) auto Handle##Name(Context& context) -> void;
  11. #include "toolchain/parse/state.def"
  12. auto HandleInvalid(Context& context) -> void {
  13. CARBON_FATAL() << "The Invalid state shouldn't be on the stack: "
  14. << context.PopState();
  15. }
  16. auto Parse(Lex::TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  17. llvm::raw_ostream* vlog_stream) -> Tree {
  18. Lex::TokenLocationTranslator translator(&tokens);
  19. Lex::TokenDiagnosticEmitter emitter(translator, consumer);
  20. // Delegate to the parser.
  21. Tree tree(tokens);
  22. Context context(tree, tokens, emitter, vlog_stream);
  23. PrettyStackTraceFunction context_dumper(
  24. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  25. context.AddLeafNode(NodeKind::FileStart,
  26. context.ConsumeChecked(Lex::TokenKind::FileStart));
  27. context.PushState(State::DeclScopeLoop);
  28. while (!context.state_stack().empty()) {
  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