parse.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 syntax_error_code = yy::parser(parsed_input, context)();
  25. if (syntax_error_code != 0) {
  26. return syntax_error_code;
  27. }
  28. if (parsed_input == std::nullopt) {
  29. std::cerr << "Internal error: parser validated syntax yet didn't produce "
  30. "an AST.\n";
  31. exit(1);
  32. }
  33. return *parsed_input;
  34. }
  35. } // namespace Carbon