File: proto_test_extras_plugin.cc

package info (click to toggle)
chromium 140.0.7339.127-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,192,880 kB
  • sloc: cpp: 35,093,808; ansic: 7,161,670; javascript: 4,199,694; python: 1,441,797; asm: 949,904; xml: 747,503; pascal: 187,748; perl: 88,691; sh: 88,248; objc: 79,953; sql: 52,714; cs: 44,599; fortran: 24,137; makefile: 22,114; tcl: 15,277; php: 13,980; yacc: 9,000; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (351 lines) | stat: -rw-r--r-- 12,776 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>
#include <string>

#include "base/check.h"
#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/notreached.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/protobuf/src/google/protobuf/compiler/code_generator.h"
#include "third_party/protobuf/src/google/protobuf/compiler/cpp/helpers.h"
#include "third_party/protobuf/src/google/protobuf/compiler/cpp/names.h"
#include "third_party/protobuf/src/google/protobuf/compiler/importer.h"
#include "third_party/protobuf/src/google/protobuf/compiler/plugin.h"
#include "third_party/protobuf/src/google/protobuf/descriptor.h"
#include "third_party/protobuf/src/google/protobuf/io/printer.h"

namespace {

using google::protobuf::Descriptor;
using google::protobuf::FieldDescriptor;
using google::protobuf::FileDescriptor;
using google::protobuf::compiler::GeneratorContext;
using google::protobuf::compiler::cpp::ClassName;
using google::protobuf::compiler::cpp::FieldName;
using google::protobuf::compiler::cpp::Namespace;
using google::protobuf::compiler::cpp::NamespaceOpener;
using google::protobuf::compiler::cpp::QualifiedClassName;
using google::protobuf::io::Printer;
using google::protobuf::io::ZeroCopyOutputStream;

// Returns if the descriptor is for a synthetic 'map entry' message type,
// which is internally created by the protobuf library to support map fields.
// Map fields are instead handled explicitly in the generation via the
// `is_map()` case.
bool IsSyntheticMapEntry(const Descriptor& message) {
  return message.map_key() != nullptr;
}

class ProtoGmockGenerator : public google::protobuf::compiler::CodeGenerator {
 public:
  ProtoGmockGenerator() = default;
  ~ProtoGmockGenerator() override = default;

  bool Generate(const FileDescriptor* file,
                const std::string& options,  // Options from build system
                GeneratorContext* context,
                std::string* error) const override {
    CHECK(file);

    base::FilePath proto_file_path = base::FilePath::FromASCII(file->name());

    base::FilePath h_file_path =
        proto_file_path.ReplaceExtension(FILE_PATH_LITERAL("test.h"));
    const std::unique_ptr<ZeroCopyOutputStream> h_stream(
        context->Open(h_file_path.AsUTF8Unsafe()));
    Printer h_printer(h_stream.get(), Printer::Options{'$', nullptr});

    std::string include_guard =
        base::ToUpperASCII(h_file_path.AsUTF8Unsafe()) + "_";
    CHECK(base::ReplaceChars(include_guard, ".-/\\", "_", &include_guard));

    std::set<std::string> includes = {
        "testing/gmock/include/gmock/gmock.h",
        proto_file_path.ReplaceExtension(FILE_PATH_LITERAL("pb.h"))
            .AsUTF8Unsafe(),
        "components/proto_extras/proto_matchers.h"};
    for (int i = 0; i < file->dependency_count(); i++) {
      base::FilePath dependency_proto_file_path =
          base::FilePath::FromASCII(file->dependency(i)->name());
      includes.insert(dependency_proto_file_path
                          .ReplaceExtension(FILE_PATH_LITERAL("test.h"))
                          .AsUTF8Unsafe());
    }

    h_printer.Emit(
        {{"include_guard", include_guard},
         {"proto_file_path", proto_file_path.AsUTF8Unsafe()},
         {"includes",
          [&] {
            for (const auto& include : includes) {
              h_printer.Print("#include \"$f$\"\n", "f", include);
            }
          }},
         {"matchers",
          [&] {
            NamespaceOpener ns(Namespace(file), &h_printer);
            for (int i = 0; i < file->message_type_count(); i++) {
              PrintMatchersRecursive(*file->message_type(i), &h_printer);
            }
          }},
         {"print_to_declarations",
          [&] {
            NamespaceOpener ns(Namespace(file), &h_printer);
            for (int i = 0; i < file->message_type_count(); i++) {
              PrintToDeclarationRecursive(*file->message_type(i), &h_printer);
            }
          }}},
        R"(// Generated by the proto_test_extras plugin.  DO NOT EDIT!
// source: $proto_file_path$

#ifndef $include_guard$
#define $include_guard$

#include <iosfwd>

$includes$

$matchers$

$print_to_declarations$

#endif  // $include_guard$
)");

    base::FilePath cc_file_path =
        proto_file_path.ReplaceExtension(FILE_PATH_LITERAL("test.cc"));
    const std::unique_ptr<ZeroCopyOutputStream> cc_stream(
        context->Open(cc_file_path.AsUTF8Unsafe()));
    Printer cc_printer(cc_stream.get(), Printer::Options{'$', nullptr});
    cc_printer.Emit(
        {{"proto_file_path", proto_file_path.AsUTF8Unsafe()},
         {"header",
          proto_file_path.ReplaceExtension(FILE_PATH_LITERAL("test.h"))
              .AsUTF8Unsafe()},
         {"to_value_header",
          proto_file_path.ReplaceExtension(FILE_PATH_LITERAL("to_value.h"))
              .AsUTF8Unsafe()},
         {"print_to_definitions",
          [&] {
            NamespaceOpener ns(Namespace(file), &cc_printer);
            for (int i = 0; i < file->message_type_count(); i++) {
              PrintToDefinitionRecursive(*file->message_type(i), &cc_printer);
            }
          }}},
        R"(// Generated by the proto_test_extras plugin. DO NOT EDIT!
// source: $proto_file_path$

#include "$header$"

#include <ostream>

#include "base/values.h"
#include "$to_value_header$"

$print_to_definitions$

)");

    return true;
  }

  std::string UniqueMatcherName(const Descriptor& message) const {
    return base::StrCat({"Equals", ClassName(&message)});
  }

  std::string QualifiedMatcher(const Descriptor& message) const {
    return base::StrCat({Namespace(&message), "::", "Equals",
                         ClassName(&message), "<", QualifiedClassName(&message),
                         ">"});
  }

  void PrintFieldMatcher(const FieldDescriptor& field,
                         const std::string& message_class_name,
                         Printer* printer) const {
    std::string field_accessor = FieldName(&field);

    if (field.is_map()) {
      std::string maybe_nested_matcher;
      if (field.message_type()->map_value()->type() ==
              FieldDescriptor::Type::TYPE_MESSAGE ||
          field.message_type()->map_value()->type() ==
              FieldDescriptor::Type::TYPE_GROUP) {
        maybe_nested_matcher =
            ", &" + QualifiedMatcher(
                        *field.message_type()->map_value()->message_type());
      }
      printer->Emit({{"message_class_name", message_class_name},
                     {"field_accessor", field_accessor},
                     {"maybe_nested_matcher", maybe_nested_matcher}},
                    R"(::proto_extras::HasMapField(
    "$field_accessor$",
    &$message_class_name$::$field_accessor$,
    expected$maybe_nested_matcher$))");
      return;
    }
    if (field.is_repeated()) {
      std::string maybe_nested_matcher;
      if (field.type() == FieldDescriptor::Type::TYPE_MESSAGE ||
          field.type() == FieldDescriptor::Type::TYPE_GROUP) {
        maybe_nested_matcher = ", &" + QualifiedMatcher(*field.message_type());
      }
      std::string resolve_field_function;
      if (field.type() == FieldDescriptor::Type::TYPE_MESSAGE ||
          field.type() == FieldDescriptor::Type::TYPE_GROUP) {
        resolve_field_function = "::proto_extras::ResolveRepeatedPtrField";
      } else {
        resolve_field_function = "::proto_extras::ResolveRepeatedField";
      }
      printer->Emit(
          {
              {"message_class_name", message_class_name},
              {"field_accessor", field_accessor},
              {"resolve_field_function", resolve_field_function},
              {"maybe_nested_matcher", maybe_nested_matcher},
          },
          R"(::proto_extras::HasRepeatedField(
    "$field_accessor$",
    $resolve_field_function$(&$message_class_name$::$field_accessor$),
    expected$maybe_nested_matcher$))");
    } else if (field.has_presence()) {
      std::string matcher;
      if (field.type() == FieldDescriptor::Type::TYPE_MESSAGE ||
          field.type() == FieldDescriptor::Type::TYPE_GROUP) {
        matcher = QualifiedMatcher(*field.message_type());
      } else {
        matcher = "testing::Eq";
      }
      printer->Emit(
          {
              {"field_accessor", field_accessor},
              {"message_class_name", message_class_name},
              {"matcher", matcher},
          },
          R"(::proto_extras::HasOptionalField(
    "$field_accessor$",
    &$message_class_name$::has_$field_accessor$,
    &$message_class_name$::$field_accessor$,
    expected.has_$field_accessor$(),
    $matcher$(expected.$field_accessor$())))");
    } else {
      printer->Emit(
          {{"message_class_name", message_class_name},
           {"field_accessor", field_accessor},
           {"value_matcher",
            [&] {
              if (field.type() == FieldDescriptor::Type::TYPE_MESSAGE ||
                  field.type() == FieldDescriptor::Type::TYPE_GROUP) {
                printer->Emit({{"nested_matcher",
                                QualifiedMatcher(*field.message_type())},
                               {"field_accessor", field_accessor}},
                              "$nested_matcher$(expected.$field_accessor$())");
              } else {
                printer->Print("testing::Eq(expected.$field_accessor$())",
                               "field_accessor", field_accessor);
              }
            }}},
          R"(testing::Property(
    "$field_accessor$",
    &$message_class_name$::$field_accessor$,
    $value_matcher$))");
    }
  }

  void PrintMatcher(const Descriptor& message, Printer* printer) const {
    std::string message_class_name = ClassName(&message);
    std::string matcher_name = UniqueMatcherName(message);

    printer->Emit(
        {{"message_type", message_class_name}, {"matcher_name", matcher_name}},
        R"(
MATCHER_P($matcher_name$, expected, "") {
  return testing::ExplainMatchResult(
      testing::AllOf()");
    {
      auto unindent = printer->WithIndent(10);
      if (message.field_count() == 0) {
        printer->Print("testing::IsTrue()");
      } else {
        for (int i = 0; i < message.field_count(); ++i) {
          const FieldDescriptor& field = *message.field(i);
          PrintFieldMatcher(field, message_class_name, printer);
          if (i < message.field_count() - 1) {
            printer->Print(",\n");
          } else {
            printer->Print("\n");
          }
        }
      }
    }

    printer->Print(R"(
      ), arg, result_listener);
}
)");
  }

  void PrintMatchersRecursive(const Descriptor& message,
                              Printer* printer) const {
    if (IsSyntheticMapEntry(message)) {
      return;
    }
    // Nested types need to be printed before the parent message so that the
    // parent can reference them.
    for (int i = 0; i < message.nested_type_count(); i++) {
      PrintMatchersRecursive(*message.nested_type(i), printer);
    }
    PrintMatcher(message, printer);
  }

  void PrintToDeclaration(const Descriptor& message, Printer* printer) const {
    std::string message_class_name = ClassName(&message);
    printer->Emit({{"message_type", message_class_name}},
                  R"(
void PrintTo(const $message_type$& msg, std::ostream* os);)");
  }

  void PrintToDefinition(const Descriptor& message, Printer* printer) const {
    std::string message_class_name = ClassName(&message);
    printer->Emit({{"message_type", message_class_name}},
                  R"(
void PrintTo(const $message_type$& msg, std::ostream* os) {
  *os << Serialize(msg).DebugString();
})");
  }

  void PrintToDeclarationRecursive(const Descriptor& message,
                                   Printer* printer) const {
    if (IsSyntheticMapEntry(message)) {
      return;
    }
    PrintToDeclaration(message, printer);
    for (int i = 0; i < message.nested_type_count(); i++) {
      PrintToDeclarationRecursive(*message.nested_type(i), printer);
    }
  }

  void PrintToDefinitionRecursive(const Descriptor& message,
                                  Printer* printer) const {
    if (IsSyntheticMapEntry(message)) {
      return;
    }
    PrintToDefinition(message, printer);
    for (int i = 0; i < message.nested_type_count(); i++) {
      PrintToDefinitionRecursive(*message.nested_type(i), printer);
    }
  }
};
}  // namespace

int main(int argc, char** argv) {
  ProtoGmockGenerator generator;
  return google::protobuf::compiler::PluginMain(argc, argv, &generator);
}