proto_to_carbon_test.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 "common/fuzzing/proto_to_carbon.h"
  5. #include <gmock/gmock.h>
  6. #include <gtest/gtest.h>
  7. #include "explorer/fuzzing/ast_to_proto.h"
  8. #include "explorer/syntax/parse.h"
  9. namespace Carbon::Testing {
  10. namespace {
  11. static std::vector<llvm::StringRef>* carbon_files = nullptr;
  12. // Returns a string representation of `ast`.
  13. auto AstToString(const AST& ast) -> std::string {
  14. std::string s;
  15. llvm::raw_string_ostream out(s);
  16. out << "package " << ast.package.package << (ast.is_api ? "api" : "impl")
  17. << ";\n";
  18. for (auto* declaration : ast.declarations) {
  19. out << *declaration << "\n";
  20. }
  21. return s;
  22. }
  23. TEST(ProtoToCarbonTest, Roundtrip) {
  24. int parsed_ok_count = 0;
  25. for (const llvm::StringRef f : *carbon_files) {
  26. Carbon::Arena arena;
  27. const ErrorOr<AST> ast = Carbon::Parse(&arena, f, /*trace=*/false);
  28. if (ast.ok()) {
  29. ++parsed_ok_count;
  30. const std::string source_from_proto = ProtoToCarbon(AstToProto(*ast));
  31. SCOPED_TRACE(testing::Message()
  32. << "Carbon file: " << f << ", source from proto:\n"
  33. << source_from_proto);
  34. const ErrorOr<AST> ast_from_proto = Carbon::ParseFromString(
  35. &arena, f, source_from_proto, /*trace=*/false);
  36. if (ast_from_proto.ok()) {
  37. EXPECT_EQ(AstToString(*ast), AstToString(*ast_from_proto));
  38. } else {
  39. ADD_FAILURE() << "Parse error " << ast_from_proto.error().message();
  40. }
  41. }
  42. }
  43. // Makes sure files were actually processed.
  44. EXPECT_GT(parsed_ok_count, 0);
  45. }
  46. } // namespace
  47. } // namespace Carbon::Testing
  48. auto main(int argc, char** argv) -> int {
  49. ::testing::InitGoogleTest(&argc, argv);
  50. Carbon::Testing::carbon_files =
  51. new std::vector<llvm::StringRef>(&argv[1], &argv[argc]);
  52. return RUN_ALL_TESTS();
  53. }