parse.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. // Returns an abstract representation of the program contained in the
  13. // well-formed input file, or if the file was malformed, a description of the
  14. // problem.
  15. auto Parse(const std::string& input_file_name)
  16. -> std::variant<AST, SyntaxErrorCode> {
  17. FILE* input_file = fopen(input_file_name.c_str(), "r");
  18. if (input_file == nullptr) {
  19. FATAL_PROGRAM_ERROR_NO_LINE() << "Error opening '" << input_file_name
  20. << "': " << std::strerror(errno);
  21. }
  22. // Prepare the lexer.
  23. yyscan_t scanner;
  24. yylex_init(&scanner);
  25. yyset_in(input_file, scanner);
  26. // Prepare other parser arguments.
  27. std::optional<AST> parsed_input = std::nullopt;
  28. ParseAndLexContext context(input_file_name);
  29. // Do the parse.
  30. auto parser = Parser(parsed_input, scanner, context);
  31. if (tracing_output) {
  32. parser.set_debug_level(1);
  33. }
  34. auto syntax_error_code = parser();
  35. // Clean up the lexer.
  36. fclose(input_file);
  37. yylex_destroy(scanner);
  38. // Return an error if appropriate.
  39. if (syntax_error_code != 0) {
  40. return syntax_error_code;
  41. }
  42. // Return parse results.
  43. CHECK(parsed_input != std::nullopt)
  44. << "parser validated syntax yet didn't produce an AST.";
  45. return *parsed_input;
  46. }
  47. } // namespace Carbon