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 "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, Diagnostics::Consumer& consumer,
  16. llvm::raw_ostream* vlog_stream) -> Tree {
  17. // Delegate to the parser.
  18. Tree tree(tokens);
  19. Context context(&tree, &tokens, &consumer, vlog_stream);
  20. PrettyStackTraceFunction context_dumper(
  21. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  22. context.AddLeafNode(NodeKind::FileStart,
  23. context.ConsumeChecked(Lex::TokenKind::FileStart));
  24. context.PushState(StateKind::DeclScopeLoopAsNonClass);
  25. while (!context.state_stack().empty()) {
  26. switch (context.state_stack().back().kind) {
  27. #define CARBON_PARSE_STATE(Name) \
  28. case StateKind::Name: \
  29. Handle##Name(context); \
  30. break;
  31. #include "toolchain/parse/state.def"
  32. }
  33. }
  34. context.AddLeafNode(NodeKind::FileEnd, *context.position());
  35. // Mark the tree as potentially having errors if there were errors coming in
  36. // from the tokenized buffer or we diagnosed new errors.
  37. tree.set_has_errors(tokens.has_errors() || context.has_errors());
  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(): {0}", verify.error());
  47. }
  48. return tree;
  49. }
  50. } // namespace Carbon::Parse