parse.cpp 1.4 KB

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