parse.cpp 2.1 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 "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: "
  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. Lex::TokenDiagnosticEmitter emitter(converter, consumer);
  19. // Delegate to the parser.
  20. Tree tree(tokens);
  21. Context context(tree, tokens, emitter, vlog_stream);
  22. PrettyStackTraceFunction context_dumper(
  23. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  24. context.AddLeafNode(NodeKind::FileStart,
  25. context.ConsumeChecked(Lex::TokenKind::FileStart));
  26. context.PushState(State::DeclScopeLoop);
  27. while (!context.state_stack().empty()) {
  28. switch (context.state_stack().back().state) {
  29. #define CARBON_PARSE_STATE(Name) \
  30. case State::Name: \
  31. Handle##Name(context); \
  32. break;
  33. #include "toolchain/parse/state.def"
  34. }
  35. }
  36. context.AddLeafNode(NodeKind::FileEnd, *context.position());
  37. if (auto verify = tree.Verify(); !verify.ok()) {
  38. // TODO: This is temporarily printing to stderr directly during development.
  39. // If we can, restrict this to a subtree with the error and add it to the
  40. // stack trace (such as with PrettyStackTraceFunction). Otherwise, switch
  41. // back to vlog_stream prior to broader distribution so that end users are
  42. // hopefully comfortable copy-pasting stderr when there are bugs in tree
  43. // construction.
  44. tree.Print(llvm::errs());
  45. CARBON_FATAL() << "Invalid tree returned by Parse(): " << verify.error();
  46. }
  47. return tree;
  48. }
  49. } // namespace Carbon::Parse