parse.cpp 1.6 KB

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