ast_to_proto_main.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 "common/fuzzing/carbon.pb.h"
  13. #include "explorer/ast/ast.h"
  14. #include "explorer/common/arena.h"
  15. #include "explorer/fuzzing/ast_to_proto.h"
  16. #include "explorer/syntax/parse.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. // Read the input file.
  27. std::ifstream proto_file(argv[1]);
  28. std::stringstream buffer;
  29. buffer << proto_file.rdbuf();
  30. proto_file.close();
  31. Arena arena;
  32. const ErrorOr<AST> ast = Parse(&arena, argv[1],
  33. /*parser_debug=*/false);
  34. if (!ast.ok()) {
  35. return ErrorBuilder() << "Parsing failed: " << ast.error().message();
  36. }
  37. Fuzzing::Carbon carbon_proto = AstToProto(*ast);
  38. std::string proto_string;
  39. google::protobuf::TextFormat::Printer p;
  40. if (!p.PrintToString(carbon_proto, &proto_string)) {
  41. return Error("Failed to convert to text proto");
  42. }
  43. std::cout << proto_string;
  44. return Success();
  45. }
  46. } // namespace Carbon::Testing
  47. auto main(int argc, char** argv) -> int {
  48. auto err = Carbon::Testing::Main(argc, argv);
  49. if (!err.ok()) {
  50. std::cerr << err.error().message() << "\n";
  51. return EXIT_FAILURE;
  52. }
  53. return EXIT_SUCCESS;
  54. }