parse.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 <iostream>
  6. #include "executable_semantics/syntax/parse_and_lex_context.h"
  7. #include "executable_semantics/syntax/parser.h"
  8. #include "executable_semantics/tracing_flag.h"
  9. extern FILE* yyin;
  10. namespace Carbon {
  11. // Returns an abstract representation of the program contained in the
  12. // well-formed input file, or if the file was malformed, a description of the
  13. // problem.
  14. auto parse(const std::string& input_file_name)
  15. -> std::variant<AST, SyntaxErrorCode> {
  16. yyin = fopen(input_file_name.c_str(), "r");
  17. if (yyin == nullptr) {
  18. std::cerr << "Error opening '" << input_file_name
  19. << "': " << std::strerror(errno) << std::endl;
  20. exit(1);
  21. }
  22. std::optional<AST> parsed_input = std::nullopt;
  23. ParseAndLexContext context(input_file_name);
  24. auto parser = yy::parser(parsed_input, context);
  25. if (tracing_output) {
  26. parser.set_debug_level(1);
  27. }
  28. auto syntax_error_code = parser();
  29. if (syntax_error_code != 0) {
  30. return syntax_error_code;
  31. }
  32. if (parsed_input == std::nullopt) {
  33. std::cerr << "Internal error: parser validated syntax yet didn't produce "
  34. "an AST.\n";
  35. exit(1);
  36. }
  37. return *parsed_input;
  38. }
  39. } // namespace Carbon