parse.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 "common/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, ParseOptions options) -> Tree {
  16. auto* consumer =
  17. options.consumer ? options.consumer : &Diagnostics::ConsoleConsumer();
  18. // Delegate to the parser.
  19. Tree tree(tokens);
  20. Context context(&tree, &tokens, consumer, options.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(StateKind::DeclScopeLoopAsNonClass);
  26. while (!context.state_stack().empty()) {
  27. switch (context.state_stack().back().kind) {
  28. #define CARBON_PARSE_STATE(Name) \
  29. case StateKind::Name: \
  30. Handle##Name(context); \
  31. break;
  32. #include "toolchain/parse/state.def"
  33. }
  34. }
  35. context.AddLeafNode(NodeKind::FileEnd, *context.position());
  36. // Mark the tree as potentially having errors if there were errors coming in
  37. // from the tokenized buffer or we diagnosed new errors.
  38. tree.set_has_errors(tokens.has_errors() || context.has_errors());
  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