parse.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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/parse/parse.h"
  5. #include "common/check.h"
  6. #include "toolchain/base/pretty_stack_trace_function.h"
  7. #include "toolchain/parse/context.h"
  8. #include "toolchain/parse/handle.h"
  9. #include "toolchain/parse/node_kind.h"
  10. namespace Carbon::Parse {
  11. auto HandleInvalid(Context& context) -> void {
  12. CARBON_FATAL("The Invalid state shouldn't be on the stack: {0}",
  13. context.PopState());
  14. }
  15. auto Parse(Lex::TokenizedBuffer& tokens, DiagnosticConsumer& consumer,
  16. llvm::raw_ostream* vlog_stream) -> Tree {
  17. Lex::TokenDiagnosticConverter converter(&tokens);
  18. ErrorTrackingDiagnosticConsumer err_tracker(consumer);
  19. Lex::TokenDiagnosticEmitter emitter(converter, err_tracker);
  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. tree.set_has_errors(err_tracker.seen_error());
  39. if (auto verify = tree.Verify(); !verify.ok()) {
  40. // TODO: This is temporarily printing to stderr directly during development.
  41. // If we can, restrict this to a subtree with the error and add it to the
  42. // stack trace (such as with PrettyStackTraceFunction). Otherwise, switch
  43. // back to vlog_stream prior to broader distribution so that end users are
  44. // hopefully comfortable copy-pasting stderr when there are bugs in tree
  45. // construction.
  46. tree.Print(llvm::errs());
  47. CARBON_FATAL("Invalid tree returned by Parse(): {0}", verify.error());
  48. }
  49. return tree;
  50. }
  51. } // namespace Carbon::Parse