parse.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 "executable_semantics/syntax/parse.h"
  5. #include "common/check.h"
  6. #include "executable_semantics/common/error.h"
  7. #include "executable_semantics/common/tracing_flag.h"
  8. #include "executable_semantics/syntax/lexer.h"
  9. #include "executable_semantics/syntax/parse_and_lex_context.h"
  10. #include "executable_semantics/syntax/parser.h"
  11. namespace Carbon {
  12. auto Parse(Ptr<Arena> arena, const std::string& input_file_name)
  13. -> std::variant<AST, SyntaxErrorCode> {
  14. FILE* input_file = fopen(input_file_name.c_str(), "r");
  15. if (input_file == nullptr) {
  16. FATAL_PROGRAM_ERROR_NO_LINE() << "Error opening '" << input_file_name
  17. << "': " << std::strerror(errno);
  18. }
  19. // Prepare the lexer.
  20. yyscan_t scanner;
  21. yylex_init(&scanner);
  22. yyset_in(input_file, scanner);
  23. // Prepare other parser arguments.
  24. std::optional<AST> ast = std::nullopt;
  25. ParseAndLexContext context(arena->New<std::string>(input_file_name));
  26. // Do the parse.
  27. auto parser = Parser(arena, scanner, context, &ast);
  28. if (tracing_output) {
  29. parser.set_debug_level(1);
  30. }
  31. auto syntax_error_code = parser();
  32. // Clean up the lexer.
  33. fclose(input_file);
  34. yylex_destroy(scanner);
  35. // Return an error if appropriate.
  36. if (syntax_error_code != 0) {
  37. return syntax_error_code;
  38. }
  39. // Return parse results.
  40. CHECK(ast != std::nullopt)
  41. << "parser validated syntax yet didn't produce an AST.";
  42. return *ast;
  43. }
  44. } // namespace Carbon