ast_to_proto_main.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // To convert a Carbon file to a text proto:
  5. // `ast_to_proto <file.carbon>`
  6. #include <google/protobuf/text_format.h>
  7. #include <fstream>
  8. #include <iostream>
  9. #include <sstream>
  10. #include "common/bazel_working_dir.h"
  11. #include "common/error.h"
  12. #include "explorer/ast/ast.h"
  13. #include "explorer/base/arena.h"
  14. #include "explorer/fuzzing/ast_to_proto.h"
  15. #include "explorer/syntax/parse.h"
  16. #include "testing/fuzzing/carbon.pb.h"
  17. namespace Carbon::Testing {
  18. auto Main(int argc, char** argv) -> ErrorOr<Success> {
  19. SetWorkingDirForBazel();
  20. if (argc != 2) {
  21. return Error("Syntax: ast_to_proto <file.carbon>");
  22. }
  23. if (!std::filesystem::is_regular_file(argv[1])) {
  24. return Error("Argument must be a file.");
  25. }
  26. Arena arena;
  27. const ErrorOr<AST> ast =
  28. Parse(*llvm::vfs::getRealFileSystem(), &arena, argv[1], FileKind::Main,
  29. /*parser_debug=*/false);
  30. if (!ast.ok()) {
  31. return ErrorBuilder() << "Parsing failed: " << ast.error().message();
  32. }
  33. Fuzzing::Carbon carbon_proto = AstToProto(*ast);
  34. std::string proto_string;
  35. google::protobuf::TextFormat::Printer p;
  36. if (!p.PrintToString(carbon_proto, &proto_string)) {
  37. return Error("Failed to convert to text proto");
  38. }
  39. std::cout << proto_string;
  40. return Success();
  41. }
  42. } // namespace Carbon::Testing
  43. auto main(int argc, char** argv) -> int {
  44. auto err = Carbon::Testing::Main(argc, argv);
  45. if (!err.ok()) {
  46. std::cerr << err.error().message() << "\n";
  47. return EXIT_FAILURE;
  48. }
  49. return EXIT_SUCCESS;
  50. }