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 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
|
// 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 <string>
#include "base/check.h"
#include "base/containers/contains.h"
#include "base/containers/flat_set.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::OneofDescriptor;
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::compiler::cpp::UnderscoresToCamelCase;
using google::protobuf::io::Printer;
using google::protobuf::io::ZeroCopyOutputStream;
struct ProtoExtrasGeneratorOptions {
bool generate_to_value_serialization = false;
bool generate_stream_operator = false;
bool generate_equality = false;
bool protobuf_full_support = false;
};
bool GetAllClassNames(const Descriptor& message,
base::flat_set<std::string>& class_names) {
class_names.insert(ClassName(&message));
for (int i = 0; i < message.nested_type_count(); i++) {
if (!GetAllClassNames(*message.nested_type(i), class_names)) {
return false;
}
}
return true;
}
void FieldToMapKeyFunction(const FieldDescriptor* field, Printer* printer) {
using enum FieldDescriptor::Type;
// From:
// - https://protobuf.dev/programming-guides/proto3/#maps
// - https://protobuf.dev/programming-guides/proto2/#maps
// > `key_type` can be any integral or string type (so, any scalar type except
// > for floating point types and bytes). Note that neither enum nor proto
// > messages are valid for `key_type`. The `value_type` can be any type
// except > another map.
auto conversion_function = [&]() -> std::string {
switch (field->type()) {
case TYPE_STRING:
return "static_cast<std::string>";
case TYPE_INT32:
case TYPE_INT64:
case TYPE_UINT64:
case TYPE_UINT32:
case TYPE_FIXED64:
case TYPE_FIXED32:
case TYPE_SFIXED64:
case TYPE_SFIXED32:
case TYPE_SINT64:
case TYPE_SINT32:
return "base::NumberToString";
case TYPE_BOOL:
case TYPE_BYTES:
case TYPE_ENUM:
case TYPE_DOUBLE:
case TYPE_FLOAT:
case TYPE_MESSAGE:
case TYPE_GROUP:
NOTREACHED() << "Invalid protobuf map key type.";
}
NOTREACHED();
};
printer->Print(conversion_function());
}
void FieldToValueFunction(const FieldDescriptor* field, Printer* printer) {
using enum FieldDescriptor::Type;
auto conversion_function = [&]() -> std::string {
switch (field->type()) {
case TYPE_DOUBLE:
case TYPE_FLOAT:
return "static_cast<double>";
case TYPE_INT32:
case TYPE_INT64:
case TYPE_UINT64:
case TYPE_UINT32:
case TYPE_FIXED64:
case TYPE_FIXED32:
case TYPE_SFIXED64:
case TYPE_SFIXED32:
case TYPE_SINT64:
case TYPE_SINT32:
return "::proto_extras::ToNumericTypeForValue";
case TYPE_BOOL:
return "static_cast<bool>";
case TYPE_STRING:
return "static_cast<std::string>";
case TYPE_BYTES:
return "base::Base64Encode";
case TYPE_ENUM:
return base::StrCat({QualifiedClassName(field->enum_type()), "_Name"});
case TYPE_MESSAGE:
case TYPE_GROUP:
// The Serialize function for the message is in the namespace of the
// nested message itself.
return base::StrCat({Namespace(field->message_type()), "::Serialize"});
}
NOTREACHED();
};
printer->Print(conversion_function());
}
void CreateToValueSerializationDefinitions(
const Descriptor& message,
Printer* printer,
const ProtoExtrasGeneratorOptions& options) {
printer->Emit(
{{"message_type", ClassName(&message)},
{"serialize_fields",
[&]() {
for (int j = 0; j < message.field_count(); j++) {
const FieldDescriptor* field = message.field(j);
std::string field_name = FieldName(message.field(j));
auto field_to_value = [&]() {
FieldToValueFunction(field, printer);
};
if (field->is_map()) {
const FieldDescriptor* map_value =
field->message_type()->map_value();
const FieldDescriptor* map_key = field->message_type()->map_key();
printer->Emit(
{{"field_name", field_name},
{"map_key_to_value",
[&] { FieldToMapKeyFunction(map_key, printer); }},
{"map_value_to_value",
[&] { FieldToValueFunction(map_value, printer); }}},
R"(
if (!message.$field_name$().empty()) {
base::DictValue map_dict;
for (const auto& [key, value] : message.$field_name$()) {
map_dict.Set($map_key_to_value$(key), $map_value_to_value$(value));
}
dict.Set("$field_name$", std::move(map_dict));
}
)");
} else if (field->is_repeated()) {
printer->Emit({{"field_name", field_name},
{"field_to_value", field_to_value}},
R"(
if (!message.$field_name$().empty()) {
base::ListValue list;
for (const auto& value : message.$field_name$()) {
list.Append($field_to_value$(value));
}
dict.Set("$field_name$", std::move(list));
}
)");
} else if (field->has_presence()) {
printer->Emit({{"field_name", field_name},
{"field_to_value", field_to_value}},
R"(
if (message.has_$field_name$()) {
dict.Set("$field_name$", $field_to_value$(message.$field_name$()));
}
)");
} else if (field->type() == FieldDescriptor::Type::TYPE_STRING ||
field->type() == FieldDescriptor::Type::TYPE_BYTES) {
printer->Emit({{"field_name", field_name},
{"field_to_value", field_to_value}},
R"(
if (!message.$field_name$().empty()) {
dict.Set("$field_name$", $field_to_value$(message.$field_name$()));
}
)");
} else {
printer->Emit({{"field_name", field_name},
{"field_to_value", field_to_value}},
R"(
dict.Set("$field_name$", $field_to_value$(message.$field_name$()));
)");
}
}
}}},
R"(
base::DictValue Serialize(const $message_type$& message) {
base::DictValue dict;
::proto_extras::SerializeUnknownFields(message, dict);
$serialize_fields$
return dict;
}
void MaybeSerialize(const std::optional<$message_type$>& opt_message,
std::string_view name,
base::DictValue& output_dictionary) {
if (!opt_message.has_value()) {
return;
}
output_dictionary.Set(name, Serialize(*opt_message));
}
)");
}
void CreateOstreamDefinition(const Descriptor& message,
Printer* printer,
const ProtoExtrasGeneratorOptions& options) {
std::string message_type = ClassName(&message);
printer->Emit({{"message_type", message_type}},
R"(
std::ostream& operator<<(std::ostream& out, const $message_type$& message) {
// This relies on Serialize() from *.to_value.h.
return out << Serialize(message).DebugString();
}
)");
}
void CreateEqualityOperatorDefinition(
const Descriptor& message,
Printer* printer,
const ProtoExtrasGeneratorOptions& options) {
std::string message_type = ClassName(&message);
printer->Emit(
{{"message_type", message_type},
{"compare_fields",
[&]() {
// If protobuf_full_support is enabled, use MessageDifferencerEquals
// to compare the messages as the messages should be full Message
// types.
if (options.protobuf_full_support) {
printer->Print(
"if (!::proto_extras::MessageDifferencerEquals(lhs, rhs)) "
"return false;\n");
return;
}
printer->Print(
"if (lhs.unknown_fields() != rhs.unknown_fields()) return "
"false;\n");
// Compare oneof fields using a switch statement.
for (int i = 0; i < message.oneof_decl_count(); ++i) {
const OneofDescriptor* oneof = message.oneof_decl(i);
printer->Emit(
{{"oneof_name", oneof->name()},
{"message_type", message_type},
{"captital_oneof_name", base::ToUpperASCII(oneof->name())},
{"body",
[&]() {
for (int j = 0; j < oneof->field_count(); ++j) {
const FieldDescriptor* field = oneof->field(j);
std::string field_name = FieldName(field);
std::string case_name = UnderscoresToCamelCase(
field->lowercase_name(), /*cap_next_letter=*/true);
printer->Emit(
{
{"message_type", message_type},
{"case_name", case_name},
{"field_name", field_name},
},
R"(
case $message_type$::k$case_name$:
if (lhs.$field_name$() != rhs.$field_name$()) return false;
break;
)");
}
}}},
R"(
if (lhs.$oneof_name$_case() != rhs.$oneof_name$_case()) return false;
switch (lhs.$oneof_name$_case()) {
$body$
case $message_type$::$captital_oneof_name$_NOT_SET:
break;
}
)");
}
// Compare non-oneof fields.
for (int j = 0; j < message.field_count(); j++) {
const FieldDescriptor* field = message.field(j);
// Skip fields that are part of a oneof, as they are handled above.
if (field->containing_oneof()) {
continue;
}
std::string field_name = FieldName(field);
if (field->is_map()) {
printer->Emit({{"field_name", field_name}},
R"(
if (lhs.$field_name$().size() != rhs.$field_name$().size()) return false;
for (const auto& [key, value] : lhs.$field_name$()) {
auto it = rhs.$field_name$().find(key);
if (it == rhs.$field_name$().end()) return false;
if (value != it->second) return false;
}
)");
} else if (field->is_repeated()) {
printer->Emit({{"field_name", field_name}},
R"(
if (lhs.$field_name$().size() != rhs.$field_name$().size()) return false;
for (int i = 0; i < lhs.$field_name$().size(); ++i) {
if (lhs.$field_name$()[i] != rhs.$field_name$()[i]) return false;
}
)");
} else if (field->has_presence()) {
printer->Emit({{"field_name", field_name}},
R"(
if (lhs.has_$field_name$() != rhs.has_$field_name$()) return false;
if (lhs.has_$field_name$() && lhs.$field_name$() != rhs.$field_name$()) return false;
)");
} else {
printer->Emit({{"field_name", field_name}},
R"(
if (lhs.$field_name$() != rhs.$field_name$()) return false;
)");
}
}
}}},
R"(
bool operator==(const $message_type$& lhs, const $message_type$& rhs) {
if (&lhs == &rhs) return true;
$compare_fields$
return true;
}
bool operator!=(const $message_type$& lhs, const $message_type$& rhs) {
return !(lhs == rhs);
}
)");
}
// 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 ProtoExtrasGenerator : public google::protobuf::compiler::CodeGenerator {
public:
ProtoExtrasGenerator() = default;
~ProtoExtrasGenerator() override = default;
bool Generate(const FileDescriptor* file,
const std::string& command_line_options,
GeneratorContext* context,
std::string* error) const override {
CHECK(file);
ProtoExtrasGeneratorOptions generator_options{
.generate_to_value_serialization = base::Contains(
command_line_options, "generate_to_value_serialization"),
.generate_stream_operator =
base::Contains(command_line_options, "generate_stream_operator"),
.generate_equality =
base::Contains(command_line_options, "generate_equality"),
.protobuf_full_support =
base::Contains(command_line_options, "protobuf_full_support"),
};
// The current design of this library assumes that only one of the
// serialization options is enabled.
CHECK(generator_options.generate_to_value_serialization ^
generator_options.generate_equality ^
generator_options.generate_stream_operator);
base::FilePath proto_file_path = base::FilePath::FromASCII(file->name());
base::FilePath::StringType file_suffix;
if (generator_options.generate_to_value_serialization) {
file_suffix = FILE_PATH_LITERAL(".to_value");
} else if (generator_options.generate_stream_operator) {
file_suffix = FILE_PATH_LITERAL(".ostream");
} else {
CHECK(generator_options.generate_equality);
file_suffix = FILE_PATH_LITERAL(".equal");
}
base::FilePath h_file_path =
proto_file_path.ReplaceExtension(file_suffix + FILE_PATH_LITERAL(".h"));
base::FilePath cc_file_path = proto_file_path.ReplaceExtension(
file_suffix + FILE_PATH_LITERAL(".cc"));
const std::unique_ptr<ZeroCopyOutputStream> h_stream(
context->Open(h_file_path.AsUTF8Unsafe()));
const std::unique_ptr<ZeroCopyOutputStream> cc_stream(
context->Open(cc_file_path.AsUTF8Unsafe()));
Printer h_printer(h_stream.get(), Printer::Options{'$', nullptr});
Printer cc_printer(cc_stream.get(), Printer::Options{'$', nullptr});
std::string include_guard =
base::ToUpperASCII(h_file_path.AsUTF8Unsafe()) + "_";
CHECK(base::ReplaceChars(include_guard, ".-/\\", "_", &include_guard));
auto forward_declarations = [&]() {
if (generator_options.generate_to_value_serialization) {
NamespaceOpener ns("base", &h_printer);
h_printer.Print("class DictValue;\n");
}
NamespaceOpener ns(Namespace(file), &h_printer);
base::flat_set<std::string> forward_declarations;
for (int i = 0; i < file->message_type_count(); i++) {
GetAllClassNames(*file->message_type(i), forward_declarations);
}
for (const auto& forward_declaration : forward_declarations) {
h_printer.Print("class $class$;\n", "class", forward_declaration);
}
};
h_printer.Emit(
{
{"include_guard", include_guard},
{"proto_file_path", proto_file_path.AsUTF8Unsafe()},
{"includes",
[&] {
if (generator_options.generate_stream_operator) {
h_printer.Print("#include <iosfwd>\n\n");
}
if (generator_options.generate_to_value_serialization) {
h_printer.Print(
"#include <optional>\n#include <string_view>\n\n");
}
}},
{"forward_declarations", forward_declarations},
{"function_declarations",
[&] {
NamespaceOpener ns(Namespace(file), &h_printer);
for (int i = 0; i < file->message_type_count(); i++) {
PrintFunctionDeclarations(*file->message_type(i), &h_printer,
error, generator_options);
}
}},
},
R"(// Generated by the proto_extras plugin. DO NOT EDIT!
// source: $proto_file_path$
#ifndef $include_guard$
#define $include_guard$
$includes$
$forward_declarations$
$function_declarations$
#endif // $include_guard$
)");
// Determine the #includes for the implementation file.
base::flat_set<std::string> impl_system_includes;
base::flat_set<std::string> impl_user_includes = {
proto_file_path.ReplaceExtension(FILE_PATH_LITERAL("pb.h"))
.AsUTF8Unsafe(),
};
if (generator_options.generate_stream_operator) {
impl_system_includes.insert("<ostream>");
impl_user_includes.insert(
proto_file_path.ReplaceExtension(FILE_PATH_LITERAL("to_value.h"))
.AsUTF8Unsafe());
impl_user_includes.insert("base/values.h");
}
if (generator_options.generate_to_value_serialization) {
impl_user_includes.insert("base/base64.h");
impl_user_includes.insert("base/strings/string_number_conversions.h");
impl_user_includes.insert("base/values.h");
impl_user_includes.insert("components/proto_extras/proto_extras_lib.h");
}
for (int i = 0; i < file->dependency_count(); i++) {
base::FilePath dependency_proto_file_path =
base::FilePath::FromASCII(file->dependency(i)->name());
bool needs_pb_h = generator_options.generate_to_value_serialization ||
generator_options.generate_equality;
if (needs_pb_h) {
impl_user_includes.insert(
dependency_proto_file_path
.ReplaceExtension(FILE_PATH_LITERAL("pb.h"))
.AsUTF8Unsafe());
}
if (generator_options.generate_to_value_serialization) {
impl_user_includes.insert(
dependency_proto_file_path
.ReplaceExtension(FILE_PATH_LITERAL("to_value.h"))
.AsUTF8Unsafe());
} else if (generator_options.generate_equality) {
impl_user_includes.insert(
dependency_proto_file_path
.ReplaceExtension(FILE_PATH_LITERAL("equal.h"))
.AsUTF8Unsafe());
}
}
if (generator_options.protobuf_full_support) {
impl_user_includes.insert(
"components/proto_extras/protobuf_full_support.h");
}
cc_printer.Emit(
{
{"proto_file_path", proto_file_path.AsUTF8Unsafe()},
{"header_file_path", h_file_path.AsUTF8Unsafe()},
{"system_includes",
[&] {
for (const auto& include : impl_system_includes) {
cc_printer.Print("#include $f$\n", "f", include);
}
}},
{"user_includes",
[&] {
for (const auto& include : impl_user_includes) {
cc_printer.Print("#include \"$f$\"\n", "f", include);
}
}},
{"function_definitions",
[&] {
NamespaceOpener ns(Namespace(file), &cc_printer);
for (int i = 0; i < file->message_type_count(); i++) {
PrintFunctionDefinitions(*file->message_type(i), &cc_printer,
error, generator_options);
}
}},
},
R"(// Generated by the proto_extras plugin. DO NOT EDIT!
// source: $proto_file_path$
#include "$header_file_path$"
$system_includes$
$user_includes$
$function_definitions$
)");
return true;
}
bool PrintFunctionDeclaration(
const Descriptor& message,
Printer* printer,
std::string* error,
const ProtoExtrasGeneratorOptions& options) const {
if (IsSyntheticMapEntry(message)) {
return true;
}
std::string message_type = ClassName(&message);
if (options.generate_to_value_serialization) {
printer->Print("base::DictValue Serialize(const $m$& message);", "m",
message_type);
printer->Print(
R"(
void MaybeSerialize(const std::optional<$m$>& opt_message,
std::string_view output_dictionary_field_name,
base::DictValue& output_dictionary);
)", "m", message_type);
}
if (options.generate_stream_operator) {
printer->Print(
"std::ostream& operator<<(std::ostream& out, const "
"$m$& message);\n",
"m", message_type);
}
if (options.generate_equality) {
printer->Print("bool operator==(const $m$& lhs, const $m$& rhs);\n", "m",
message_type);
}
return true;
}
bool PrintFunctionDefinition(
const Descriptor& message,
Printer* printer,
std::string* error,
const ProtoExtrasGeneratorOptions& options) const {
if (IsSyntheticMapEntry(message)) {
return true;
}
if (options.generate_to_value_serialization) {
CreateToValueSerializationDefinitions(message, printer, options);
}
if (options.generate_stream_operator) {
CreateOstreamDefinition(message, printer, options);
}
if (options.generate_equality) {
CreateEqualityOperatorDefinition(message, printer, options);
}
return true;
}
bool PrintFunctionDeclarations(
const Descriptor& message,
Printer* printer,
std::string* error,
const ProtoExtrasGeneratorOptions& options) const {
if (!PrintFunctionDeclaration(message, printer, error, options)) {
return false;
}
for (int i = 0; i < message.nested_type_count(); i++) {
if (!PrintFunctionDeclarations(*message.nested_type(i), printer, error,
options)) {
return false;
}
}
return true;
}
bool PrintFunctionDefinitions(
const Descriptor& message,
Printer* printer,
std::string* error,
const ProtoExtrasGeneratorOptions& options) const {
if (!PrintFunctionDefinition(message, printer, error, options)) {
return false;
}
for (int i = 0; i < message.nested_type_count(); i++) {
if (!PrintFunctionDefinitions(*message.nested_type(i), printer, error,
options)) {
return false;
}
}
return true;
}
};
} // namespace
int main(int argc, char** argv) {
ProtoExtrasGenerator generator;
return google::protobuf::compiler::PluginMain(argc, argv, &generator);
}
|