Automated rollback of commit 47e7983055.

PiperOrigin-RevId: 503007139
pull/11589/head
Mike Kruskal 2 years ago committed by Copybara-Service
parent 6fcc5228c7
commit 08b97c3120
  1. 40
      src/google/protobuf/compiler/java/context.cc
  2. 6
      src/google/protobuf/compiler/java/enum_field.cc
  3. 4
      src/google/protobuf/compiler/java/enum_field_lite.cc
  4. 10
      src/google/protobuf/compiler/java/extension.cc
  5. 27
      src/google/protobuf/compiler/java/field.cc
  6. 24
      src/google/protobuf/compiler/java/file.cc
  7. 58
      src/google/protobuf/compiler/java/generator.cc
  8. 136
      src/google/protobuf/compiler/java/helpers.cc
  9. 23
      src/google/protobuf/compiler/java/helpers.h
  10. 9
      src/google/protobuf/compiler/java/kotlin_generator.cc
  11. 20
      src/google/protobuf/compiler/java/map_field.cc
  12. 11
      src/google/protobuf/compiler/java/map_field_lite.cc
  13. 4
      src/google/protobuf/compiler/java/message_field.cc
  14. 4
      src/google/protobuf/compiler/java/message_field_lite.cc
  15. 60
      src/google/protobuf/compiler/java/name_resolver.cc
  16. 10
      src/google/protobuf/compiler/java/name_resolver.h
  17. 6
      src/google/protobuf/compiler/java/names.cc
  18. 4
      src/google/protobuf/compiler/java/names.h
  19. 31
      src/google/protobuf/compiler/java/plugin_unittest.cc
  20. 24
      src/google/protobuf/compiler/java/primitive_field.cc
  21. 22
      src/google/protobuf/compiler/java/primitive_field_lite.cc
  22. 8
      src/google/protobuf/compiler/java/shared_code_generator.cc
  23. 29
      src/google/protobuf/compiler/java/string_field.cc
  24. 10
      src/google/protobuf/compiler/java/string_field_lite.cc
  25. 45
      src/google/protobuf/descriptor.cc
  26. 2
      src/google/protobuf/extension_set_unittest.cc
  27. 5
      src/google/protobuf/test_util2.h
  28. 9
      src/google/protobuf/text_format.cc

@ -30,12 +30,8 @@
#include "google/protobuf/compiler/java/context.h" #include "google/protobuf/compiler/java/context.h"
#include <string>
#include "google/protobuf/stubs/logging.h" #include "google/protobuf/stubs/logging.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/strings/strip.h"
#include "google/protobuf/compiler/java/field.h" #include "google/protobuf/compiler/java/field.h"
#include "google/protobuf/compiler/java/helpers.h" #include "google/protobuf/compiler/java/helpers.h"
#include "google/protobuf/compiler/java/name_resolver.h" #include "google/protobuf/compiler/java/name_resolver.h"
@ -58,17 +54,11 @@ ClassNameResolver* Context::GetNameResolver() const {
} }
namespace { namespace {
bool EqualWithSuffix(absl::string_view name1, absl::string_view suffix,
absl::string_view name2) {
if (!absl::ConsumeSuffix(&name2, suffix)) return false;
return name1 == name2;
}
// Whether two fields have conflicting accessors (assuming name1 and name2 // Whether two fields have conflicting accessors (assuming name1 and name2
// are different). name1 and name2 are field1 and field2's camel-case name // are different). name1 and name2 are field1 and field2's camel-case name
// respectively. // respectively.
bool IsConflicting(const FieldDescriptor* field1, absl::string_view name1, bool IsConflicting(const FieldDescriptor* field1, const std::string& name1,
const FieldDescriptor* field2, absl::string_view name2, const FieldDescriptor* field2, const std::string& name2,
std::string* info) { std::string* info) {
if (field1->is_repeated()) { if (field1->is_repeated()) {
if (field2->is_repeated()) { if (field2->is_repeated()) {
@ -76,18 +66,16 @@ bool IsConflicting(const FieldDescriptor* field1, absl::string_view name1,
return false; return false;
} else { } else {
// field1 is repeated, and field2 is not. // field1 is repeated, and field2 is not.
if (EqualWithSuffix(name1, "Count", name2)) { if (name1 + "Count" == name2) {
*info = absl::StrCat("both repeated field \"", field1->name(), *info = "both repeated field \"" + field1->name() + "\" and singular " +
"\" and singular ", "field \"", field2->name(), "field \"" + field2->name() + "\" generate the method \"" +
"\" generate the method \"", "get", name1, "get" + name1 + "Count()\"";
"Count()\"");
return true; return true;
} }
if (EqualWithSuffix(name1, "List", name2)) { if (name1 + "List" == name2) {
*info = *info = "both repeated field \"" + field1->name() + "\" and singular " +
absl::StrCat("both repeated field \"", field1->name(), "field \"" + field2->name() + "\" generate the method \"" +
"\" and singular ", "field \"", field2->name(), "get" + name1 + "List()\"";
"\" generate the method \"", "get", name1, "List()\"");
return true; return true;
} }
// Well, there are obviously many more conflicting cases, but it probably // Well, there are obviously many more conflicting cases, but it probably
@ -150,8 +138,8 @@ void Context::InitializeFieldGeneratorInfoForFields(
if (name == other_name) { if (name == other_name) {
is_conflict[i] = is_conflict[j] = true; is_conflict[i] = is_conflict[j] = true;
conflict_reason[i] = conflict_reason[j] = conflict_reason[i] = conflict_reason[j] =
absl::StrCat("capitalized name of field \"", field->name(), "capitalized name of field \"" + field->name() +
"\" conflicts with field \"", other->name(), "\""); "\" conflicts with field \"" + other->name() + "\"";
} else if (IsConflicting(field, name, other, other_name, } else if (IsConflicting(field, name, other, other_name,
&conflict_reason[j])) { &conflict_reason[j])) {
is_conflict[i] = is_conflict[j] = true; is_conflict[i] = is_conflict[j] = true;
@ -172,8 +160,8 @@ void Context::InitializeFieldGeneratorInfoForFields(
// For fields conflicting with some other fields, we append the field // For fields conflicting with some other fields, we append the field
// number to their field names in generated code to avoid conflicts. // number to their field names in generated code to avoid conflicts.
if (is_conflict[i]) { if (is_conflict[i]) {
absl::StrAppend(&info.name, field->number()); info.name += absl::StrCat(field->number());
absl::StrAppend(&info.capitalized_name, field->number()); info.capitalized_name += absl::StrCat(field->number());
info.disambiguated_reason = conflict_reason[i]; info.disambiguated_reason = conflict_reason[i];
} }
field_generator_info_map_[field] = info; field_generator_info_map_[field] = info;

@ -93,7 +93,7 @@ void SetEnumVariables(
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
// Note that these have a trailing ";". // Note that these have a trailing ";".
(*variables)["set_has_field_bit_message"] = (*variables)["set_has_field_bit_message"] =
absl::StrCat(GenerateSetBit(messageBitIndex), ";"); GenerateSetBit(messageBitIndex) + ";";
(*variables)["set_has_field_bit_to_local"] = (*variables)["set_has_field_bit_to_local"] =
GenerateSetBitToLocal(messageBitIndex); GenerateSetBitToLocal(messageBitIndex);
(*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
@ -114,9 +114,9 @@ void SetEnumVariables(
// Note that these have a trailing ";". // Note that these have a trailing ";".
(*variables)["set_has_field_bit_builder"] = (*variables)["set_has_field_bit_builder"] =
absl::StrCat(GenerateSetBit(builderBitIndex), ";"); GenerateSetBit(builderBitIndex) + ";";
(*variables)["clear_has_field_bit_builder"] = (*variables)["clear_has_field_bit_builder"] =
absl::StrCat(GenerateClearBit(builderBitIndex), ";"); GenerateClearBit(builderBitIndex) + ";";
(*variables)["get_has_field_bit_from_local"] = (*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex); GenerateGetBitFromLocal(builderBitIndex);

@ -109,9 +109,9 @@ void SetEnumVariables(
// Note that these have a trailing ";". // Note that these have a trailing ";".
(*variables)["set_has_field_bit_message"] = (*variables)["set_has_field_bit_message"] =
absl::StrCat(GenerateSetBit(messageBitIndex), ";"); GenerateSetBit(messageBitIndex) + ";";
(*variables)["clear_has_field_bit_message"] = (*variables)["clear_has_field_bit_message"] =
absl::StrCat(GenerateClearBit(messageBitIndex), ";"); GenerateClearBit(messageBitIndex) + ";";
(*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
} else { } else {

@ -83,7 +83,7 @@ void ExtensionGenerator::InitTemplateVars(
? "" ? ""
: DefaultValue(descriptor, immutable, name_resolver, : DefaultValue(descriptor, immutable, name_resolver,
context->options()); context->options());
vars["type_constant"] = std::string(FieldTypeName(GetType(descriptor))); vars["type_constant"] = FieldTypeName(GetType(descriptor));
vars["packed"] = descriptor->is_packed() ? "true" : "false"; vars["packed"] = descriptor->is_packed() ? "true" : "false";
vars["enum_map"] = "null"; vars["enum_map"] = "null";
vars["prototype"] = "null"; vars["prototype"] = "null";
@ -94,12 +94,12 @@ void ExtensionGenerator::InitTemplateVars(
case JAVATYPE_MESSAGE: case JAVATYPE_MESSAGE:
singular_type = singular_type =
name_resolver->GetClassName(descriptor->message_type(), immutable); name_resolver->GetClassName(descriptor->message_type(), immutable);
vars["prototype"] = absl::StrCat(singular_type, ".getDefaultInstance()"); vars["prototype"] = singular_type + ".getDefaultInstance()";
break; break;
case JAVATYPE_ENUM: case JAVATYPE_ENUM:
singular_type = singular_type =
name_resolver->GetClassName(descriptor->enum_type(), immutable); name_resolver->GetClassName(descriptor->enum_type(), immutable);
vars["enum_map"] = absl::StrCat(singular_type, ".internalGetValueMap()"); vars["enum_map"] = singular_type + ".internalGetValueMap()";
break; break;
case JAVATYPE_STRING: case JAVATYPE_STRING:
singular_type = "java.lang.String"; singular_type = "java.lang.String";
@ -108,11 +108,11 @@ void ExtensionGenerator::InitTemplateVars(
singular_type = immutable ? "com.google.protobuf.ByteString" : "byte[]"; singular_type = immutable ? "com.google.protobuf.ByteString" : "byte[]";
break; break;
default: default:
singular_type = std::string(BoxedPrimitiveTypeName(java_type)); singular_type = BoxedPrimitiveTypeName(java_type);
break; break;
} }
vars["type"] = descriptor->is_repeated() vars["type"] = descriptor->is_repeated()
? absl::StrCat("java.util.List<", singular_type, ">") ? "java.util.List<" + singular_type + ">"
: singular_type; : singular_type;
vars["singular_type"] = singular_type; vars["singular_type"] = singular_type;
} }

@ -259,26 +259,24 @@ void SetCommonFieldVariables(
// empty string. // empty string.
(*variables)["{"] = ""; (*variables)["{"] = "";
(*variables)["}"] = ""; (*variables)["}"] = "";
(*variables)["kt_name"] = IsForbiddenKotlin(info->name) (*variables)["kt_name"] =
? absl::StrCat(info->name, "_") IsForbiddenKotlin(info->name) ? info->name + "_" : info->name;
: info->name; (*variables)["kt_capitalized_name"] = IsForbiddenKotlin(info->name)
(*variables)["kt_capitalized_name"] = ? info->capitalized_name + "_"
IsForbiddenKotlin(info->name) ? absl::StrCat(info->capitalized_name, "_") : info->capitalized_name;
: info->capitalized_name;
if (!descriptor->is_repeated()) { if (!descriptor->is_repeated()) {
(*variables)["annotation_field_type"] = (*variables)["annotation_field_type"] = FieldTypeName(descriptor->type());
std::string(FieldTypeName(descriptor->type()));
} else if (GetJavaType(descriptor) == JAVATYPE_MESSAGE && } else if (GetJavaType(descriptor) == JAVATYPE_MESSAGE &&
IsMapEntry(descriptor->message_type())) { IsMapEntry(descriptor->message_type())) {
(*variables)["annotation_field_type"] = (*variables)["annotation_field_type"] =
absl::StrCat(FieldTypeName(descriptor->type()), "MAP"); std::string(FieldTypeName(descriptor->type())) + "MAP";
} else { } else {
(*variables)["annotation_field_type"] = (*variables)["annotation_field_type"] =
absl::StrCat(FieldTypeName(descriptor->type()), "_LIST"); std::string(FieldTypeName(descriptor->type())) + "_LIST";
if (descriptor->is_packed()) { if (descriptor->is_packed()) {
variables->insert( variables->insert(
{"annotation_field_type", {"annotation_field_type",
absl::StrCat(FieldTypeName(descriptor->type()), "_LIST_PACKED")}); absl::StrCat((*variables)["annotation_field_type"], "_PACKED")});
} }
} }
} }
@ -292,11 +290,10 @@ void SetCommonOneofVariables(
absl::StrCat(descriptor->containing_oneof()->index()); absl::StrCat(descriptor->containing_oneof()->index());
(*variables)["oneof_stored_type"] = GetOneofStoredType(descriptor); (*variables)["oneof_stored_type"] = GetOneofStoredType(descriptor);
(*variables)["set_oneof_case_message"] = (*variables)["set_oneof_case_message"] =
absl::StrCat(info->name, "Case_ = ", descriptor->number()); info->name + "Case_ = " + absl::StrCat(descriptor->number());
(*variables)["clear_oneof_case_message"] = (*variables)["clear_oneof_case_message"] = info->name + "Case_ = 0";
absl::StrCat(info->name, "Case_ = 0");
(*variables)["has_oneof_case_message"] = (*variables)["has_oneof_case_message"] =
absl::StrCat(info->name, "Case_ == ", descriptor->number()); info->name + "Case_ == " + absl::StrCat(descriptor->number());
} }
void PrintExtraFieldInfo( void PrintExtraFieldInfo(

@ -273,8 +273,7 @@ void FileGenerator::Generate(io::Printer* printer) {
"package", java_package_); "package", java_package_);
} }
PrintGeneratedAnnotation( PrintGeneratedAnnotation(
printer, '$', printer, '$', options_.annotate_code ? classname_ + ".java.pb.meta" : "",
options_.annotate_code ? absl::StrCat(classname_, ".java.pb.meta") : "",
options_); options_);
if (!options_.opensource_runtime) { if (!options_.opensource_runtime) {
@ -553,14 +552,12 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(
for (const FieldDescriptor* field : extensions) { for (const FieldDescriptor* field : extensions) {
std::string scope; std::string scope;
if (field->extension_scope() != NULL) { if (field->extension_scope() != NULL) {
scope = absl::StrCat( scope = name_resolver_->GetMutableClassName(field->extension_scope()) +
name_resolver_->GetMutableClassName(field->extension_scope()), ".getDescriptor()";
".getDescriptor()");
} else { } else {
scope = scope = FileJavaPackage(field->file(), true, options_) + "." +
absl::StrCat(FileJavaPackage(field->file(), true, options_), ".", name_resolver_->GetDescriptorClassName(field->file()) +
name_resolver_->GetDescriptorClassName(field->file()), ".descriptor";
".descriptor");
} }
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
printer->Print( printer->Print(
@ -609,9 +606,9 @@ static void GenerateSibling(
GeneratorClass* generator, GeneratorClass* generator,
void (GeneratorClass::*pfn)(io::Printer* printer)) { void (GeneratorClass::*pfn)(io::Printer* printer)) {
std::string filename = std::string filename =
absl::StrCat(package_dir, descriptor->name(), name_suffix, ".java"); package_dir + descriptor->name() + name_suffix + ".java";
file_list->push_back(filename); file_list->push_back(filename);
std::string info_full_path = absl::StrCat(filename, ".pb.meta"); std::string info_full_path = filename + ".pb.meta";
GeneratedCodeInfo annotations; GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector( io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations); &annotations);
@ -720,10 +717,9 @@ void FileGenerator::GenerateKotlinSiblings(
auto open_file = [context](const std::string& filename) { auto open_file = [context](const std::string& filename) {
return std::unique_ptr<io::ZeroCopyOutputStream>(context->Open(filename)); return std::unique_ptr<io::ZeroCopyOutputStream>(context->Open(filename));
}; };
std::string filename = std::string filename = package_dir + descriptor->name() + "Kt.kt";
absl::StrCat(package_dir, descriptor->name(), "Kt.kt");
file_list->push_back(filename); file_list->push_back(filename);
std::string info_full_path = absl::StrCat(filename, ".pb.meta"); std::string info_full_path = filename + ".pb.meta";
GeneratedCodeInfo annotations; GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector( io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations); &annotations);

@ -34,9 +34,6 @@
#include "google/protobuf/compiler/java/generator.h" #include "google/protobuf/compiler/java/generator.h"
#include <utility>
#include <vector>
#include <memory> #include <memory>
@ -75,25 +72,25 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
file_options.opensource_runtime = opensource_runtime_; file_options.opensource_runtime = opensource_runtime_;
for (auto& option : options) { for (int i = 0; i < options.size(); i++) {
if (option.first == "output_list_file") { if (options[i].first == "output_list_file") {
file_options.output_list_file = option.second; file_options.output_list_file = options[i].second;
} else if (option.first == "immutable") { } else if (options[i].first == "immutable") {
file_options.generate_immutable_code = true; file_options.generate_immutable_code = true;
} else if (option.first == "mutable") { } else if (options[i].first == "mutable") {
file_options.generate_mutable_code = true; file_options.generate_mutable_code = true;
} else if (option.first == "shared") { } else if (options[i].first == "shared") {
file_options.generate_shared_code = true; file_options.generate_shared_code = true;
} else if (option.first == "lite") { } else if (options[i].first == "lite") {
// Note: Java Lite does not guarantee API/ABI stability. We may choose to // Note: Java Lite does not guarantee API/ABI stability. We may choose to
// break existing API in order to boost performance / reduce code size. // break existing API in order to boost performance / reduce code size.
file_options.enforce_lite = true; file_options.enforce_lite = true;
} else if (option.first == "annotate_code") { } else if (options[i].first == "annotate_code") {
file_options.annotate_code = true; file_options.annotate_code = true;
} else if (option.first == "annotation_list_file") { } else if (options[i].first == "annotation_list_file") {
file_options.annotation_list_file = option.second; file_options.annotation_list_file = options[i].second;
} else { } else {
*error = absl::StrCat("Unknown generator option: ", option.first); *error = "Unknown generator option: " + options[i].first;
return false; return false;
} }
} }
@ -118,31 +115,35 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
std::vector<std::string> all_annotations; std::vector<std::string> all_annotations;
std::vector<std::unique_ptr<FileGenerator>> file_generators; std::vector<FileGenerator*> file_generators;
if (file_options.generate_immutable_code) { if (file_options.generate_immutable_code) {
file_generators.emplace_back( file_generators.push_back(new FileGenerator(file, file_options,
std::make_unique<FileGenerator>(file, file_options, /* immutable = */ true));
/* immutable = */ true));
} }
if (file_options.generate_mutable_code) { if (file_options.generate_mutable_code) {
file_generators.emplace_back( file_generators.push_back(new FileGenerator(file, file_options,
std::make_unique<FileGenerator>(file, file_options, /* mutable = */ false));
/* mutable = */ false));
} }
for (auto& file_generator : file_generators) { for (int i = 0; i < file_generators.size(); ++i) {
if (!file_generator->Validate(error)) { if (!file_generators[i]->Validate(error)) {
for (int j = 0; j < file_generators.size(); ++j) {
delete file_generators[j];
}
return false; return false;
} }
} }
for (auto& file_generator : file_generators) { for (int i = 0; i < file_generators.size(); ++i) {
FileGenerator* file_generator = file_generators[i];
std::string package_dir = JavaPackageToDir(file_generator->java_package()); std::string package_dir = JavaPackageToDir(file_generator->java_package());
std::string java_filename = std::string java_filename = package_dir;
absl::StrCat(package_dir, file_generator->classname(), ".java"); java_filename += file_generator->classname();
java_filename += ".java";
all_files.push_back(java_filename); all_files.push_back(java_filename);
std::string info_full_path = absl::StrCat(java_filename, ".pb.meta"); std::string info_full_path = java_filename + ".pb.meta";
if (file_options.annotate_code) { if (file_options.annotate_code) {
all_annotations.push_back(info_full_path); all_annotations.push_back(info_full_path);
} }
@ -171,6 +172,9 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
} }
for (int i = 0; i < file_generators.size(); ++i) {
delete file_generators[i];
}
file_generators.clear(); file_generators.clear();
// Generate output list if requested. // Generate output list if requested.

@ -72,7 +72,7 @@ const char kThinSeparator[] =
"// -------------------------------------------------------------------\n"; "// -------------------------------------------------------------------\n";
void PrintGeneratedAnnotation(io::Printer* printer, char delimiter, void PrintGeneratedAnnotation(io::Printer* printer, char delimiter,
absl::string_view annotation_file, const std::string& annotation_file,
Options options) { Options options) {
if (annotation_file.empty()) { if (annotation_file.empty()) {
return; return;
@ -89,8 +89,7 @@ void PrintGeneratedAnnotation(io::Printer* printer, char delimiter,
void PrintEnumVerifierLogic( void PrintEnumVerifierLogic(
io::Printer* printer, const FieldDescriptor* descriptor, io::Printer* printer, const FieldDescriptor* descriptor,
const absl::flat_hash_map<absl::string_view, std::string>& variables, const absl::flat_hash_map<absl::string_view, std::string>& variables,
absl::string_view var_name, absl::string_view terminating_string, const char* var_name, const char* terminating_string, bool enforce_lite) {
bool enforce_lite) {
std::string enum_verifier_string = std::string enum_verifier_string =
enforce_lite ? absl::StrCat(var_name, ".internalGetVerifier()") enforce_lite ? absl::StrCat(var_name, ".internalGetVerifier()")
: absl::StrCat( : absl::StrCat(
@ -102,11 +101,12 @@ void PrintEnumVerifierLogic(
".forNumber(number) != null;\n" ".forNumber(number) != null;\n"
" }\n" " }\n"
" }"); " }");
printer->Print(variables, printer->Print(
absl::StrCat(enum_verifier_string, terminating_string)); variables,
absl::StrCat(enum_verifier_string, terminating_string).c_str());
} }
std::string UnderscoresToCamelCase(absl::string_view input, std::string UnderscoresToCamelCase(const std::string& input,
bool cap_next_letter) { bool cap_next_letter) {
GOOGLE_ABSL_CHECK(!input.empty()); GOOGLE_ABSL_CHECK(!input.empty());
std::string result; std::string result;
@ -143,7 +143,7 @@ std::string UnderscoresToCamelCase(absl::string_view input,
return result; return result;
} }
std::string ToCamelCase(absl::string_view input, bool lower_first) { std::string ToCamelCase(const std::string& input, bool lower_first) {
bool capitalize_next = !lower_first; bool capitalize_next = !lower_first;
std::string result; std::string result;
result.reserve(input.size()); result.reserve(input.size());
@ -185,26 +185,25 @@ bool IsForbiddenKotlin(absl::string_view field_name) {
std::string EscapeKotlinKeywords(std::string name) { std::string EscapeKotlinKeywords(std::string name) {
std::vector<std::string> escaped_packages; std::vector<std::string> escaped_packages;
std::vector<std::string> packages = absl::StrSplit(name, "."); // NOLINT std::vector<std::string> packages = absl::StrSplit(name, "."); // NOLINT
for (absl::string_view package : packages) { for (const std::string& package : packages) {
if (IsForbiddenKotlin(package)) { if (IsForbiddenKotlin(package)) {
escaped_packages.push_back(absl::StrCat("`", package, "`")); escaped_packages.push_back("`" + package + "`");
} else { } else {
escaped_packages.emplace_back(package); escaped_packages.push_back(package);
} }
} }
return absl::StrJoin(escaped_packages, "."); return absl::StrJoin(escaped_packages, ".");
} }
std::string UniqueFileScopeIdentifier(const Descriptor* descriptor) { std::string UniqueFileScopeIdentifier(const Descriptor* descriptor) {
return absl::StrCat( return "static_" + absl::StrReplaceAll(descriptor->full_name(), {{".", "_"}});
"static_", absl::StrReplaceAll(descriptor->full_name(), {{".", "_"}}));
} }
std::string CamelCaseFieldName(const FieldDescriptor* field) { std::string CamelCaseFieldName(const FieldDescriptor* field) {
std::string fieldName = UnderscoresToCamelCase(field); std::string fieldName = UnderscoresToCamelCase(field);
if ('0' <= fieldName[0] && fieldName[0] <= '9') { if ('0' <= fieldName[0] && fieldName[0] <= '9') {
return absl::StrCat("_", fieldName); return '_' + fieldName;
} }
return fieldName; return fieldName;
} }
@ -215,28 +214,31 @@ std::string FileClassName(const FileDescriptor* file, bool immutable) {
std::string JavaPackageToDir(std::string package_name) { std::string JavaPackageToDir(std::string package_name) {
std::string package_dir = absl::StrReplaceAll(package_name, {{".", "/"}}); std::string package_dir = absl::StrReplaceAll(package_name, {{".", "/"}});
if (!package_dir.empty()) absl::StrAppend(&package_dir, "/"); if (!package_dir.empty()) package_dir += "/";
return package_dir; return package_dir;
} }
std::string ExtraMessageInterfaces(const Descriptor* descriptor) { std::string ExtraMessageInterfaces(const Descriptor* descriptor) {
return absl::StrCat("// @@protoc_insertion_point(message_implements:", std::string interfaces = "// @@protoc_insertion_point(message_implements:" +
descriptor->full_name(), ")"); descriptor->full_name() + ")";
return interfaces;
} }
std::string ExtraBuilderInterfaces(const Descriptor* descriptor) { std::string ExtraBuilderInterfaces(const Descriptor* descriptor) {
return absl::StrCat("// @@protoc_insertion_point(builder_implements:", std::string interfaces = "// @@protoc_insertion_point(builder_implements:" +
descriptor->full_name(), ")"); descriptor->full_name() + ")";
return interfaces;
} }
std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor) { std::string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor) {
return absl::StrCat("// @@protoc_insertion_point(interface_extends:", std::string interfaces = "// @@protoc_insertion_point(interface_extends:" +
descriptor->full_name(), ")"); descriptor->full_name() + ")";
return interfaces;
} }
std::string FieldConstantName(const FieldDescriptor* field) { std::string FieldConstantName(const FieldDescriptor* field) {
std::string name = absl::StrCat(field->name(), "_FIELD_NUMBER"); std::string name = field->name() + "_FIELD_NUMBER";
absl::AsciiStrToUpper(&name); absl::AsciiStrToUpper(&name);
return name; return name;
} }
@ -291,7 +293,7 @@ JavaType GetJavaType(const FieldDescriptor* field) {
return JAVATYPE_INT; return JAVATYPE_INT;
} }
absl::string_view PrimitiveTypeName(JavaType type) { const char* PrimitiveTypeName(JavaType type) {
switch (type) { switch (type) {
case JAVATYPE_INT: case JAVATYPE_INT:
return "int"; return "int";
@ -308,23 +310,23 @@ absl::string_view PrimitiveTypeName(JavaType type) {
case JAVATYPE_BYTES: case JAVATYPE_BYTES:
return "com.google.protobuf.ByteString"; return "com.google.protobuf.ByteString";
case JAVATYPE_ENUM: case JAVATYPE_ENUM:
return {}; return NULL;
case JAVATYPE_MESSAGE: case JAVATYPE_MESSAGE:
return {}; return NULL;
// No default because we want the compiler to complain if any new // No default because we want the compiler to complain if any new
// JavaTypes are added. // JavaTypes are added.
} }
GOOGLE_ABSL_LOG(FATAL) << "Can't get here."; GOOGLE_ABSL_LOG(FATAL) << "Can't get here.";
return {}; return NULL;
} }
absl::string_view PrimitiveTypeName(const FieldDescriptor* descriptor) { const char* PrimitiveTypeName(const FieldDescriptor* descriptor) {
return PrimitiveTypeName(GetJavaType(descriptor)); return PrimitiveTypeName(GetJavaType(descriptor));
} }
absl::string_view BoxedPrimitiveTypeName(JavaType type) { const char* BoxedPrimitiveTypeName(JavaType type) {
switch (type) { switch (type) {
case JAVATYPE_INT: case JAVATYPE_INT:
return "java.lang.Integer"; return "java.lang.Integer";
@ -341,23 +343,23 @@ absl::string_view BoxedPrimitiveTypeName(JavaType type) {
case JAVATYPE_BYTES: case JAVATYPE_BYTES:
return "com.google.protobuf.ByteString"; return "com.google.protobuf.ByteString";
case JAVATYPE_ENUM: case JAVATYPE_ENUM:
return {}; return NULL;
case JAVATYPE_MESSAGE: case JAVATYPE_MESSAGE:
return {}; return NULL;
// No default because we want the compiler to complain if any new // No default because we want the compiler to complain if any new
// JavaTypes are added. // JavaTypes are added.
} }
GOOGLE_ABSL_LOG(FATAL) << "Can't get here."; GOOGLE_ABSL_LOG(FATAL) << "Can't get here.";
return {}; return NULL;
} }
absl::string_view BoxedPrimitiveTypeName(const FieldDescriptor* descriptor) { const char* BoxedPrimitiveTypeName(const FieldDescriptor* descriptor) {
return BoxedPrimitiveTypeName(GetJavaType(descriptor)); return BoxedPrimitiveTypeName(GetJavaType(descriptor));
} }
absl::string_view KotlinTypeName(JavaType type) { const char* KotlinTypeName(JavaType type) {
switch (type) { switch (type) {
case JAVATYPE_INT: case JAVATYPE_INT:
return "kotlin.Int"; return "kotlin.Int";
@ -374,16 +376,16 @@ absl::string_view KotlinTypeName(JavaType type) {
case JAVATYPE_BYTES: case JAVATYPE_BYTES:
return "com.google.protobuf.ByteString"; return "com.google.protobuf.ByteString";
case JAVATYPE_ENUM: case JAVATYPE_ENUM:
return {}; return NULL;
case JAVATYPE_MESSAGE: case JAVATYPE_MESSAGE:
return {}; return NULL;
// No default because we want the compiler to complain if any new // No default because we want the compiler to complain if any new
// JavaTypes are added. // JavaTypes are added.
} }
GOOGLE_ABSL_LOG(FATAL) << "Can't get here."; GOOGLE_ABSL_LOG(FATAL) << "Can't get here.";
return {}; return NULL;
} }
std::string GetOneofStoredType(const FieldDescriptor* field) { std::string GetOneofStoredType(const FieldDescriptor* field) {
@ -394,11 +396,11 @@ std::string GetOneofStoredType(const FieldDescriptor* field) {
case JAVATYPE_MESSAGE: case JAVATYPE_MESSAGE:
return ClassNameResolver().GetClassName(field->message_type(), true); return ClassNameResolver().GetClassName(field->message_type(), true);
default: default:
return std::string(BoxedPrimitiveTypeName(javaType)); return BoxedPrimitiveTypeName(javaType);
} }
} }
absl::string_view FieldTypeName(FieldDescriptor::Type field_type) { const char* FieldTypeName(FieldDescriptor::Type field_type) {
switch (field_type) { switch (field_type) {
case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_INT32:
return "INT32"; return "INT32";
@ -442,10 +444,10 @@ absl::string_view FieldTypeName(FieldDescriptor::Type field_type) {
} }
GOOGLE_ABSL_LOG(FATAL) << "Can't get here."; GOOGLE_ABSL_LOG(FATAL) << "Can't get here.";
return {}; return NULL;
} }
bool AllAscii(absl::string_view text) { bool AllAscii(const std::string& text) {
for (int i = 0; i < text.size(); i++) { for (int i = 0; i < text.size(); i++) {
if ((text[i] & 0x80) != 0) { if ((text[i] & 0x80) != 0) {
return false; return false;
@ -465,7 +467,7 @@ std::string DefaultValue(const FieldDescriptor* field, bool immutable,
// Need to print as a signed int since Java has no unsigned. // Need to print as a signed int since Java has no unsigned.
return absl::StrCat(static_cast<int32_t>(field->default_value_uint32())); return absl::StrCat(static_cast<int32_t>(field->default_value_uint32()));
case FieldDescriptor::CPPTYPE_INT64: case FieldDescriptor::CPPTYPE_INT64:
return absl::StrCat(field->default_value_int64(), "L"); return absl::StrCat(field->default_value_int64()) + "L";
case FieldDescriptor::CPPTYPE_UINT64: case FieldDescriptor::CPPTYPE_UINT64:
return absl::StrCat(static_cast<int64_t>(field->default_value_uint64())) + return absl::StrCat(static_cast<int64_t>(field->default_value_uint64())) +
"L"; "L";
@ -478,7 +480,7 @@ std::string DefaultValue(const FieldDescriptor* field, bool immutable,
} else if (value != value) { } else if (value != value) {
return "Double.NaN"; return "Double.NaN";
} else { } else {
return absl::StrCat(io::SimpleDtoa(value), "D"); return io::SimpleDtoa(value) + "D";
} }
} }
case FieldDescriptor::CPPTYPE_FLOAT: { case FieldDescriptor::CPPTYPE_FLOAT: {
@ -490,7 +492,7 @@ std::string DefaultValue(const FieldDescriptor* field, bool immutable,
} else if (value != value) { } else if (value != value) {
return "Float.NaN"; return "Float.NaN";
} else { } else {
return absl::StrCat(io::SimpleFtoa(value), "F"); return io::SimpleFtoa(value) + "F";
} }
} }
case FieldDescriptor::CPPTYPE_BOOL: case FieldDescriptor::CPPTYPE_BOOL:
@ -508,8 +510,7 @@ std::string DefaultValue(const FieldDescriptor* field, bool immutable,
} else { } else {
if (AllAscii(field->default_value_string())) { if (AllAscii(field->default_value_string())) {
// All chars are ASCII. In this case CEscape() works fine. // All chars are ASCII. In this case CEscape() works fine.
return absl::StrCat( return "\"" + absl::CEscape(field->default_value_string()) + "\"";
"\"", absl::CEscape(field->default_value_string()), "\"");
} else { } else {
// See comments in Internal.java for gory details. // See comments in Internal.java for gory details.
return absl::Substitute( return absl::Substitute(
@ -519,14 +520,12 @@ std::string DefaultValue(const FieldDescriptor* field, bool immutable,
} }
case FieldDescriptor::CPPTYPE_ENUM: case FieldDescriptor::CPPTYPE_ENUM:
return absl::StrCat( return name_resolver->GetClassName(field->enum_type(), immutable) + "." +
name_resolver->GetClassName(field->enum_type(), immutable), ".", field->default_value_enum()->name();
field->default_value_enum()->name());
case FieldDescriptor::CPPTYPE_MESSAGE: case FieldDescriptor::CPPTYPE_MESSAGE:
return absl::StrCat( return name_resolver->GetClassName(field->message_type(), immutable) +
name_resolver->GetClassName(field->message_type(), immutable), ".getDefaultInstance()";
".getDefaultInstance()");
// No default because we want the compiler to complain if any new // No default because we want the compiler to complain if any new
// types are added. // types are added.
@ -573,7 +572,7 @@ bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field) {
field->default_value_string() != ""; field->default_value_string() != "";
} }
constexpr absl::string_view bit_masks[] = { const char* bit_masks[] = {
"0x00000001", "0x00000002", "0x00000004", "0x00000008", "0x00000001", "0x00000002", "0x00000004", "0x00000008",
"0x00000010", "0x00000020", "0x00000040", "0x00000080", "0x00000010", "0x00000020", "0x00000040", "0x00000080",
@ -588,7 +587,10 @@ constexpr absl::string_view bit_masks[] = {
}; };
std::string GetBitFieldName(int index) { std::string GetBitFieldName(int index) {
return absl::StrCat("bitField", index, "_"); std::string varName = "bitField";
varName += absl::StrCat(index);
varName += "_";
return varName;
} }
std::string GetBitFieldNameForBit(int bitIndex) { std::string GetBitFieldNameForBit(int bitIndex) {
@ -597,19 +599,22 @@ std::string GetBitFieldNameForBit(int bitIndex) {
namespace { namespace {
std::string GenerateGetBitInternal(absl::string_view prefix, int bitIndex) { std::string GenerateGetBitInternal(const std::string& prefix, int bitIndex) {
std::string varName = absl::StrCat(prefix, GetBitFieldNameForBit(bitIndex)); std::string varName = prefix + GetBitFieldNameForBit(bitIndex);
int bitInVarIndex = bitIndex % 32; int bitInVarIndex = bitIndex % 32;
return absl::StrCat("((", varName, " & ", bit_masks[bitInVarIndex], std::string mask = bit_masks[bitInVarIndex];
") != 0)"); std::string result = "((" + varName + " & " + mask + ") != 0)";
return result;
} }
std::string GenerateSetBitInternal(absl::string_view prefix, int bitIndex) { std::string GenerateSetBitInternal(const std::string& prefix, int bitIndex) {
std::string varName = absl::StrCat(prefix, GetBitFieldNameForBit(bitIndex)); std::string varName = prefix + GetBitFieldNameForBit(bitIndex);
int bitInVarIndex = bitIndex % 32; int bitInVarIndex = bitIndex % 32;
return absl::StrCat(varName, " |= ", bit_masks[bitInVarIndex]); std::string mask = bit_masks[bitInVarIndex];
std::string result = varName + " |= " + mask;
return result;
} }
} // namespace } // namespace
@ -626,8 +631,9 @@ std::string GenerateClearBit(int bitIndex) {
std::string varName = GetBitFieldNameForBit(bitIndex); std::string varName = GetBitFieldNameForBit(bitIndex);
int bitInVarIndex = bitIndex % 32; int bitInVarIndex = bitIndex % 32;
return absl::StrCat(varName, " = (", varName, " & ~", std::string mask = bit_masks[bitInVarIndex];
bit_masks[bitInVarIndex], ")"); std::string result = varName + " = (" + varName + " & ~" + mask + ")";
return result;
} }
std::string GenerateGetBitFromLocal(int bitIndex) { std::string GenerateGetBitFromLocal(int bitIndex) {
@ -675,8 +681,8 @@ bool IsReferenceType(JavaType type) {
return false; return false;
} }
absl::string_view GetCapitalizedType(const FieldDescriptor* field, const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable,
bool immutable, Options options) { Options options) {
switch (GetType(field)) { switch (GetType(field)) {
case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_INT32:
return "Int32"; return "Int32";
@ -721,7 +727,7 @@ absl::string_view GetCapitalizedType(const FieldDescriptor* field,
} }
GOOGLE_ABSL_LOG(FATAL) << "Can't get here."; GOOGLE_ABSL_LOG(FATAL) << "Can't get here.";
return {}; return NULL;
} }
// For encodings with fixed sizes, returns that size in bytes. Otherwise // For encodings with fixed sizes, returns that size in bytes. Otherwise

@ -69,7 +69,7 @@ bool IsForbiddenKotlin(absl::string_view field_name);
// annotation_file should be generated from the filename of the source file // annotation_file should be generated from the filename of the source file
// being annotated (which in turn must be a Java identifier plus ".java"). // being annotated (which in turn must be a Java identifier plus ".java").
void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$', void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$',
absl::string_view annotation_file = "", const std::string& annotation_file = "",
Options options = {}); Options options = {});
// If a GeneratedMessageLite contains non-lite enums, then its verifier // If a GeneratedMessageLite contains non-lite enums, then its verifier
@ -77,12 +77,11 @@ void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$',
void PrintEnumVerifierLogic( void PrintEnumVerifierLogic(
io::Printer* printer, const FieldDescriptor* descriptor, io::Printer* printer, const FieldDescriptor* descriptor,
const absl::flat_hash_map<absl::string_view, std::string>& variables, const absl::flat_hash_map<absl::string_view, std::string>& variables,
absl::string_view var_name, absl::string_view terminating_string, const char* var_name, const char* terminating_string, bool enforce_lite);
bool enforce_lite);
// Converts a name to camel-case. If cap_first_letter is true, capitalize the // Converts a name to camel-case. If cap_first_letter is true, capitalize the
// first letter. // first letter.
std::string ToCamelCase(absl::string_view input, bool lower_first); std::string ToCamelCase(const std::string& input, bool lower_first);
// Similar to UnderscoresToCamelCase, but guarantees that the result is a // Similar to UnderscoresToCamelCase, but guarantees that the result is a
// complete Java identifier by adding a _ if needed. // complete Java identifier by adding a _ if needed.
@ -185,8 +184,8 @@ inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) {
// (e.g.) be "OrBuilder" for some generated interfaces. // (e.g.) be "OrBuilder" for some generated interfaces.
template <typename Descriptor> template <typename Descriptor>
std::string AnnotationFileName(const Descriptor* descriptor, std::string AnnotationFileName(const Descriptor* descriptor,
absl::string_view suffix) { const std::string& suffix) {
return absl::StrCat(descriptor->name(), suffix, ".java.pb.meta"); return descriptor->name() + suffix + ".java.pb.meta";
} }
// Get the unqualified name that should be used for a field's field // Get the unqualified name that should be used for a field's field
@ -212,21 +211,21 @@ enum JavaType {
JavaType GetJavaType(const FieldDescriptor* field); JavaType GetJavaType(const FieldDescriptor* field);
absl::string_view PrimitiveTypeName(JavaType type); const char* PrimitiveTypeName(JavaType type);
// Get the fully-qualified class name for a boxed primitive type, e.g. // Get the fully-qualified class name for a boxed primitive type, e.g.
// "java.lang.Integer" for JAVATYPE_INT. Returns NULL for enum and message // "java.lang.Integer" for JAVATYPE_INT. Returns NULL for enum and message
// types. // types.
absl::string_view BoxedPrimitiveTypeName(JavaType type); const char* BoxedPrimitiveTypeName(JavaType type);
// Kotlin source does not distinguish between primitives and non-primitives, // Kotlin source does not distinguish between primitives and non-primitives,
// but does use Kotlin-specific qualified types for them. // but does use Kotlin-specific qualified types for them.
absl::string_view KotlinTypeName(JavaType type); const char* KotlinTypeName(JavaType type);
// Get the name of the java enum constant representing this type. E.g., // Get the name of the java enum constant representing this type. E.g.,
// "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full // "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full
// name is "com.google.protobuf.WireFormat.FieldType.INT32". // name is "com.google.protobuf.WireFormat.FieldType.INT32".
absl::string_view FieldTypeName(const FieldDescriptor::Type field_type); const char* FieldTypeName(const FieldDescriptor::Type field_type);
class ClassNameResolver; class ClassNameResolver;
std::string DefaultValue(const FieldDescriptor* field, bool immutable, std::string DefaultValue(const FieldDescriptor* field, bool immutable,
@ -314,8 +313,8 @@ bool IsReferenceType(JavaType type);
// Returns the capitalized name for calling relative functions in // Returns the capitalized name for calling relative functions in
// CodedInputStream // CodedInputStream
absl::string_view GetCapitalizedType(const FieldDescriptor* field, const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable,
bool immutable, Options options); Options options);
// For encodings with fixed sizes, returns that size in bytes. Otherwise // For encodings with fixed sizes, returns that size in bytes. Otherwise
// returns -1. // returns -1.

@ -78,7 +78,7 @@ bool KotlinGenerator::Generate(const FileDescriptor* file,
} else if (option.first == "annotation_list_file") { } else if (option.first == "annotation_list_file") {
file_options.annotation_list_file = option.second; file_options.annotation_list_file = option.second;
} else { } else {
*error = absl::StrCat("Unknown generator option: ", option.first); *error = "Unknown generator option: " + option.first;
return false; return false;
} }
} }
@ -101,10 +101,11 @@ bool KotlinGenerator::Generate(const FileDescriptor* file,
return std::unique_ptr<io::ZeroCopyOutputStream>(context->Open(filename)); return std::unique_ptr<io::ZeroCopyOutputStream>(context->Open(filename));
}; };
std::string package_dir = JavaPackageToDir(file_generator->java_package()); std::string package_dir = JavaPackageToDir(file_generator->java_package());
std::string kotlin_filename = std::string kotlin_filename = package_dir;
absl::StrCat(package_dir, file_generator->GetKotlinClassname(), ".kt"); kotlin_filename += file_generator->GetKotlinClassname();
kotlin_filename += ".kt";
all_files.push_back(kotlin_filename); all_files.push_back(kotlin_filename);
std::string info_full_path = absl::StrCat(kotlin_filename, ".pb.meta"); std::string info_full_path = kotlin_filename + ".pb.meta";
if (file_options.annotate_code) { if (file_options.annotate_code) {
all_annotations.push_back(info_full_path); all_annotations.push_back(info_full_path);
} }

@ -68,8 +68,8 @@ std::string TypeName(const FieldDescriptor* field,
} else if (GetJavaType(field) == JAVATYPE_ENUM) { } else if (GetJavaType(field) == JAVATYPE_ENUM) {
return name_resolver->GetImmutableClassName(field->enum_type()); return name_resolver->GetImmutableClassName(field->enum_type());
} else { } else {
return std::string(boxed ? BoxedPrimitiveTypeName(GetJavaType(field)) return boxed ? BoxedPrimitiveTypeName(GetJavaType(field))
: PrimitiveTypeName(GetJavaType(field))); : PrimitiveTypeName(GetJavaType(field));
} }
} }
@ -80,13 +80,13 @@ std::string KotlinTypeName(const FieldDescriptor* field,
} else if (GetJavaType(field) == JAVATYPE_ENUM) { } else if (GetJavaType(field) == JAVATYPE_ENUM) {
return name_resolver->GetImmutableClassName(field->enum_type()); return name_resolver->GetImmutableClassName(field->enum_type());
} else { } else {
return std::string(KotlinTypeName(GetJavaType(field))); return KotlinTypeName(GetJavaType(field));
} }
} }
std::string WireType(const FieldDescriptor* field) { std::string WireType(const FieldDescriptor* field) {
return absl::StrCat("com.google.protobuf.WireFormat.FieldType.", return "com.google.protobuf.WireFormat.FieldType." +
FieldTypeName(field->type())); std::string(FieldTypeName(field->type()));
} }
void SetMessageVariables( void SetMessageVariables(
@ -190,18 +190,18 @@ void SetMessageVariables(
{"default_entry", absl::StrCat((*variables)["capitalized_name"], {"default_entry", absl::StrCat((*variables)["capitalized_name"],
"DefaultEntryHolder.defaultEntry")}); "DefaultEntryHolder.defaultEntry")});
variables->insert({"map_field_parameter", (*variables)["default_entry"]}); variables->insert({"map_field_parameter", (*variables)["default_entry"]});
(*variables)["descriptor"] = absl::StrCat( (*variables)["descriptor"] =
name_resolver->GetImmutableClassName(descriptor->file()), ".internal_", name_resolver->GetImmutableClassName(descriptor->file()) + ".internal_" +
UniqueFileScopeIdentifier(descriptor->message_type()), "_descriptor, "); UniqueFileScopeIdentifier(descriptor->message_type()) + "_descriptor, ";
(*variables)["ver"] = GeneratedCodeVersionSuffix(); (*variables)["ver"] = GeneratedCodeVersionSuffix();
(*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex); (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
(*variables)["get_has_field_bit_from_local"] = (*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex); GenerateGetBitFromLocal(builderBitIndex);
(*variables)["set_has_field_bit_builder"] = (*variables)["set_has_field_bit_builder"] =
absl::StrCat(GenerateSetBit(builderBitIndex), ";"); GenerateSetBit(builderBitIndex) + ";";
(*variables)["clear_has_field_bit_builder"] = (*variables)["clear_has_field_bit_builder"] =
absl::StrCat(GenerateClearBit(builderBitIndex), ";"); GenerateClearBit(builderBitIndex) + ";";
} }
} // namespace } // namespace

@ -31,7 +31,6 @@
#include "google/protobuf/compiler/java/map_field_lite.h" #include "google/protobuf/compiler/java/map_field_lite.h"
#include <cstdint> #include <cstdint>
#include <string>
#include "google/protobuf/compiler/java/context.h" #include "google/protobuf/compiler/java/context.h"
#include "google/protobuf/compiler/java/doc_comment.h" #include "google/protobuf/compiler/java/doc_comment.h"
@ -70,8 +69,8 @@ std::string TypeName(const FieldDescriptor* field,
} else if (GetJavaType(field) == JAVATYPE_ENUM) { } else if (GetJavaType(field) == JAVATYPE_ENUM) {
return name_resolver->GetImmutableClassName(field->enum_type()); return name_resolver->GetImmutableClassName(field->enum_type());
} else { } else {
return std::string(boxed ? BoxedPrimitiveTypeName(GetJavaType(field)) return boxed ? BoxedPrimitiveTypeName(GetJavaType(field))
: PrimitiveTypeName(GetJavaType(field))); : PrimitiveTypeName(GetJavaType(field));
} }
} }
@ -82,13 +81,13 @@ std::string KotlinTypeName(const FieldDescriptor* field,
} else if (GetJavaType(field) == JAVATYPE_ENUM) { } else if (GetJavaType(field) == JAVATYPE_ENUM) {
return name_resolver->GetImmutableClassName(field->enum_type()); return name_resolver->GetImmutableClassName(field->enum_type());
} else { } else {
return std::string(KotlinTypeName(GetJavaType(field))); return KotlinTypeName(GetJavaType(field));
} }
} }
std::string WireType(const FieldDescriptor* field) { std::string WireType(const FieldDescriptor* field) {
return absl::StrCat("com.google.protobuf.WireFormat.FieldType.", return "com.google.protobuf.WireFormat.FieldType." +
FieldTypeName(field->type())); std::string(FieldTypeName(field->type()));
} }
void SetMessageVariables( void SetMessageVariables(

@ -111,9 +111,9 @@ void SetMessageVariables(
(*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex); (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
(*variables)["set_has_field_bit_builder"] = (*variables)["set_has_field_bit_builder"] =
absl::StrCat(GenerateSetBit(builderBitIndex), ";"); GenerateSetBit(builderBitIndex) + ";";
(*variables)["clear_has_field_bit_builder"] = (*variables)["clear_has_field_bit_builder"] =
absl::StrCat(GenerateClearBit(builderBitIndex), ";"); GenerateClearBit(builderBitIndex) + ";";
(*variables)["get_has_field_bit_from_local"] = (*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex); GenerateGetBitFromLocal(builderBitIndex);
} }

@ -88,9 +88,9 @@ void SetMessageVariables(
// Note that these have a trailing ";". // Note that these have a trailing ";".
(*variables)["set_has_field_bit_message"] = (*variables)["set_has_field_bit_message"] =
absl::StrCat(GenerateSetBit(messageBitIndex), ";"); GenerateSetBit(messageBitIndex) + ";";
(*variables)["clear_has_field_bit_message"] = (*variables)["clear_has_field_bit_message"] =
absl::StrCat(GenerateClearBit(messageBitIndex), ";"); GenerateClearBit(messageBitIndex) + ";";
(*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
} else { } else {

@ -59,8 +59,8 @@ const char* kOuterClassNameSuffix = "OuterClass";
// Full name : foo.Bar.Baz // Full name : foo.Bar.Baz
// Package name: foo // Package name: foo
// After strip : Bar.Baz // After strip : Bar.Baz
absl::string_view StripPackageName(absl::string_view full_name, std::string StripPackageName(const std::string& full_name,
const FileDescriptor* file) { const FileDescriptor* file) {
if (file->package().empty()) { if (file->package().empty()) {
return full_name; return full_name;
} else { } else {
@ -72,8 +72,7 @@ absl::string_view StripPackageName(absl::string_view full_name,
// Get the name of a message's Java class without package name prefix. // Get the name of a message's Java class without package name prefix.
std::string ClassNameWithoutPackage(const Descriptor* descriptor, std::string ClassNameWithoutPackage(const Descriptor* descriptor,
bool immutable) { bool immutable) {
return std::string( return StripPackageName(descriptor->full_name(), descriptor->file());
StripPackageName(descriptor->full_name(), descriptor->file()));
} }
std::string ClassNameWithoutPackageKotlin(const Descriptor* descriptor) { std::string ClassNameWithoutPackageKotlin(const Descriptor* descriptor) {
@ -81,7 +80,7 @@ std::string ClassNameWithoutPackageKotlin(const Descriptor* descriptor) {
const Descriptor* temp = descriptor->containing_type(); const Descriptor* temp = descriptor->containing_type();
while (temp) { while (temp) {
result = absl::StrCat(temp->name(), "Kt.", result); result = temp->name() + "Kt." + result;
temp = temp->containing_type(); temp = temp->containing_type();
} }
return result; return result;
@ -95,23 +94,23 @@ std::string ClassNameWithoutPackage(const EnumDescriptor* descriptor,
if (message_descriptor == NULL) { if (message_descriptor == NULL) {
return descriptor->name(); return descriptor->name();
} else { } else {
return absl::StrCat(ClassNameWithoutPackage(message_descriptor, immutable), return ClassNameWithoutPackage(message_descriptor, immutable) + "." +
".", descriptor->name()); descriptor->name();
} }
} }
// Get the name of a service's Java class without package name prefix. // Get the name of a service's Java class without package name prefix.
std::string ClassNameWithoutPackage(const ServiceDescriptor* descriptor, std::string ClassNameWithoutPackage(const ServiceDescriptor* descriptor,
bool immutable) { bool immutable) {
absl::string_view full_name = std::string full_name =
StripPackageName(descriptor->full_name(), descriptor->file()); StripPackageName(descriptor->full_name(), descriptor->file());
// We don't allow nested service definitions. // We don't allow nested service definitions.
GOOGLE_ABSL_CHECK(!absl::StrContains(full_name, '.')); GOOGLE_ABSL_CHECK(full_name.find('.') == std::string::npos);
return std::string(full_name); return full_name;
} }
// Return true if a and b are equals (case insensitive). // Return true if a and b are equals (case insensitive).
NameEquality CheckNameEquality(absl::string_view a, absl::string_view b) { NameEquality CheckNameEquality(const std::string& a, const std::string& b) {
if (absl::AsciiStrToUpper(a) == absl::AsciiStrToUpper(b)) { if (absl::AsciiStrToUpper(a) == absl::AsciiStrToUpper(b)) {
if (a == b) { if (a == b) {
return NameEquality::EXACT_EQUAL; return NameEquality::EXACT_EQUAL;
@ -123,7 +122,7 @@ NameEquality CheckNameEquality(absl::string_view a, absl::string_view b) {
// Check whether a given message or its nested types has the given class name. // Check whether a given message or its nested types has the given class name.
bool MessageHasConflictingClassName(const Descriptor* message, bool MessageHasConflictingClassName(const Descriptor* message,
absl::string_view classname, const std::string& classname,
NameEquality equality_mode) { NameEquality equality_mode) {
if (CheckNameEquality(message->name(), classname) == equality_mode) { if (CheckNameEquality(message->name(), classname) == equality_mode) {
return true; return true;
@ -182,18 +181,18 @@ std::string ClassNameResolver::GetFileClassName(const FileDescriptor* file,
std::string ClassNameResolver::GetFileClassName(const FileDescriptor* file, std::string ClassNameResolver::GetFileClassName(const FileDescriptor* file,
bool immutable, bool kotlin) { bool immutable, bool kotlin) {
if (kotlin) { if (kotlin) {
return absl::StrCat(GetFileImmutableClassName(file), "Kt"); return GetFileImmutableClassName(file) + "Kt";
} else if (immutable) { } else if (immutable) {
return GetFileImmutableClassName(file); return GetFileImmutableClassName(file);
} else { } else {
return absl::StrCat("Mutable", GetFileImmutableClassName(file)); return "Mutable" + GetFileImmutableClassName(file);
} }
} }
// Check whether there is any type defined in the proto file that has // Check whether there is any type defined in the proto file that has
// the given class name. // the given class name.
bool ClassNameResolver::HasConflictingClassName(const FileDescriptor* file, bool ClassNameResolver::HasConflictingClassName(const FileDescriptor* file,
absl::string_view classname, const std::string& classname,
NameEquality equality_mode) { NameEquality equality_mode) {
for (int i = 0; i < file->enum_type_count(); i++) { for (int i = 0; i < file->enum_type_count(); i++) {
if (CheckNameEquality(file->enum_type(i)->name(), classname) == if (CheckNameEquality(file->enum_type(i)->name(), classname) ==
@ -221,7 +220,7 @@ std::string ClassNameResolver::GetDescriptorClassName(
if (options_.opensource_runtime) { if (options_.opensource_runtime) {
return GetFileImmutableClassName(file); return GetFileImmutableClassName(file);
} else { } else {
return absl::StrCat(GetFileImmutableClassName(file), "InternalDescriptors"); return GetFileImmutableClassName(file) + "InternalDescriptors";
} }
} }
@ -241,14 +240,14 @@ std::string ClassNameResolver::GetClassName(const FileDescriptor* descriptor,
// Get the full name of a Java class by prepending the Java package name // Get the full name of a Java class by prepending the Java package name
// or outer class name. // or outer class name.
std::string ClassNameResolver::GetClassFullName( std::string ClassNameResolver::GetClassFullName(
absl::string_view name_without_package, const FileDescriptor* file, const std::string& name_without_package, const FileDescriptor* file,
bool immutable, bool is_own_file) { bool immutable, bool is_own_file) {
return GetClassFullName(name_without_package, file, immutable, is_own_file, return GetClassFullName(name_without_package, file, immutable, is_own_file,
false); false);
} }
std::string ClassNameResolver::GetClassFullName( std::string ClassNameResolver::GetClassFullName(
absl::string_view name_without_package, const FileDescriptor* file, const std::string& name_without_package, const FileDescriptor* file,
bool immutable, bool is_own_file, bool kotlin) { bool immutable, bool is_own_file, bool kotlin) {
std::string result; std::string result;
if (is_own_file) { if (is_own_file) {
@ -257,10 +256,10 @@ std::string ClassNameResolver::GetClassFullName(
result = GetClassName(file, immutable, kotlin); result = GetClassName(file, immutable, kotlin);
} }
if (!result.empty()) { if (!result.empty()) {
absl::StrAppend(&result, "."); result += '.';
} }
absl::StrAppend(&result, name_without_package); result += name_without_package;
if (kotlin) absl::StrAppend(&result, "Kt"); if (kotlin) result += "Kt";
return result; return result;
} }
@ -302,13 +301,13 @@ std::string ClassNameResolver::GetClassName(const ServiceDescriptor* descriptor,
// Get the Java Class style full name of a message. // Get the Java Class style full name of a message.
std::string ClassNameResolver::GetJavaClassFullName( std::string ClassNameResolver::GetJavaClassFullName(
absl::string_view name_without_package, const FileDescriptor* file, const std::string& name_without_package, const FileDescriptor* file,
bool immutable) { bool immutable) {
return GetJavaClassFullName(name_without_package, file, immutable, false); return GetJavaClassFullName(name_without_package, file, immutable, false);
} }
std::string ClassNameResolver::GetJavaClassFullName( std::string ClassNameResolver::GetJavaClassFullName(
absl::string_view name_without_package, const FileDescriptor* file, const std::string& name_without_package, const FileDescriptor* file,
bool immutable, bool kotlin) { bool immutable, bool kotlin) {
std::string result; std::string result;
if (MultipleJavaFiles(file, immutable)) { if (MultipleJavaFiles(file, immutable)) {
@ -329,15 +328,14 @@ std::string ClassNameResolver::GetExtensionIdentifierName(
std::string ClassNameResolver::GetExtensionIdentifierName( std::string ClassNameResolver::GetExtensionIdentifierName(
const FieldDescriptor* descriptor, bool immutable, bool kotlin) { const FieldDescriptor* descriptor, bool immutable, bool kotlin) {
return absl::StrCat( return GetClassName(descriptor->containing_type(), immutable, kotlin) + "." +
GetClassName(descriptor->containing_type(), immutable, kotlin), ".", descriptor->name();
descriptor->name());
} }
std::string ClassNameResolver::GetKotlinFactoryName( std::string ClassNameResolver::GetKotlinFactoryName(
const Descriptor* descriptor) { const Descriptor* descriptor) {
std::string name = ToCamelCase(descriptor->name(), /* lower_first = */ true); std::string name = ToCamelCase(descriptor->name(), /* lower_first = */ true);
return IsForbiddenKotlin(name) ? absl::StrCat(name, "_") : name; return IsForbiddenKotlin(name) ? name + "_" : name;
} }
std::string ClassNameResolver::GetJavaImmutableClassName( std::string ClassNameResolver::GetJavaImmutableClassName(
@ -372,14 +370,14 @@ std::string ClassNameResolver::GetJavaMutableClassName(
std::string ClassNameResolver::GetDowngradedFileClassName( std::string ClassNameResolver::GetDowngradedFileClassName(
const FileDescriptor* file) { const FileDescriptor* file) {
return absl::StrCat("Downgraded", GetFileClassName(file, false)); return "Downgraded" + GetFileClassName(file, false);
} }
std::string ClassNameResolver::GetDowngradedClassName( std::string ClassNameResolver::GetDowngradedClassName(
const Descriptor* descriptor) { const Descriptor* descriptor) {
return absl::StrCat(FileJavaPackage(descriptor->file(), true, options_), ".", return FileJavaPackage(descriptor->file(), true, options_) + "." +
GetDowngradedFileClassName(descriptor->file()), ".", GetDowngradedFileClassName(descriptor->file()) + "." +
ClassNameWithoutPackage(descriptor, false)); ClassNameWithoutPackage(descriptor, false);
} }
} // namespace java } // namespace java

@ -78,7 +78,7 @@ class ClassNameResolver {
// Check whether there is any type defined in the proto file that has // Check whether there is any type defined in the proto file that has
// the given class name. // the given class name.
bool HasConflictingClassName(const FileDescriptor* file, bool HasConflictingClassName(const FileDescriptor* file,
absl::string_view classname, const std::string& classname,
NameEquality equality_mode); NameEquality equality_mode);
// Gets the name of the outer class that holds descriptor information. // Gets the name of the outer class that holds descriptor information.
@ -132,10 +132,10 @@ class ClassNameResolver {
// Get the full name of a Java class by prepending the Java package name // Get the full name of a Java class by prepending the Java package name
// or outer class name. // or outer class name.
std::string GetClassFullName(absl::string_view name_without_package, std::string GetClassFullName(const std::string& name_without_package,
const FileDescriptor* file, bool immutable, const FileDescriptor* file, bool immutable,
bool is_own_file); bool is_own_file);
std::string GetClassFullName(absl::string_view name_without_package, std::string GetClassFullName(const std::string& name_without_package,
const FileDescriptor* file, bool immutable, const FileDescriptor* file, bool immutable,
bool is_own_file, bool kotlin); bool is_own_file, bool kotlin);
@ -143,9 +143,9 @@ class ClassNameResolver {
private: private:
// Get the Java Class style full name of a message. // Get the Java Class style full name of a message.
std::string GetJavaClassFullName(absl::string_view name_without_package, std::string GetJavaClassFullName(const std::string& name_without_package,
const FileDescriptor* file, bool immutable); const FileDescriptor* file, bool immutable);
std::string GetJavaClassFullName(absl::string_view name_without_package, std::string GetJavaClassFullName(const std::string& name_without_package,
const FileDescriptor* file, bool immutable, const FileDescriptor* file, bool immutable,
bool kotlin); bool kotlin);
// Caches the result to provide better performance. // Caches the result to provide better performance.

@ -74,7 +74,7 @@ bool IsReservedName(absl::string_view name) {
return kReservedNames.contains(name); return kReservedNames.contains(name);
} }
bool IsForbidden(absl::string_view field_name) { bool IsForbidden(const std::string& field_name) {
// Names that should be avoided (in UpperCamelCase format). // Names that should be avoided (in UpperCamelCase format).
// Using them will cause the compiler to generate accessors whose names // Using them will cause the compiler to generate accessors whose names
// collide with methods defined in base classes. // collide with methods defined in base classes.
@ -113,7 +113,7 @@ std::string FieldName(const FieldDescriptor* field) {
if (IsForbidden(field_name)) { if (IsForbidden(field_name)) {
// Append a trailing "#" to indicate that the name should be decorated to // Append a trailing "#" to indicate that the name should be decorated to
// avoid collision with other names. // avoid collision with other names.
absl::StrAppend(&field_name, "#"); field_name += "#";
} }
return field_name; return field_name;
} }
@ -180,7 +180,7 @@ std::string UnderscoresToCamelCase(const MethodDescriptor* method) {
std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field) { std::string UnderscoresToCamelCaseCheckReserved(const FieldDescriptor* field) {
std::string name = UnderscoresToCamelCase(field); std::string name = UnderscoresToCamelCase(field);
if (IsReservedName(name)) { if (IsReservedName(name)) {
absl::StrAppend(&name, "_"); return name + "_";
} }
return name; return name;
} }

@ -103,8 +103,8 @@ std::string CapitalizedFieldName(const FieldDescriptor* descriptor);
// Returns: // Returns:
// Converts a name to camel-case. If cap_first_letter is true, capitalize the // Converts a name to camel-case. If cap_first_letter is true, capitalize the
// first letter. // first letter.
std::string UnderscoresToCamelCase(absl::string_view input, std::string UnderscoresToCamelCase(const std::string& name,
bool cap_next_letter); bool cap_first_letter);
// Requires: // Requires:
// field != NULL // field != NULL
// Returns: // Returns:

@ -81,17 +81,16 @@ class TestGenerator : public CodeGenerator {
// not verify that they are correctly-placed; that would require actually // not verify that they are correctly-placed; that would require actually
// compiling the output which is a bit more than I care to do for this test. // compiling the output which is a bit more than I care to do for this test.
TEST(JavaPluginTest, PluginTest) { TEST(JavaPluginTest, PluginTest) {
GOOGLE_ABSL_CHECK_OK( GOOGLE_ABSL_CHECK_OK(File::SetContents(TestTempDir() + "/test.proto",
File::SetContents(absl::StrCat(TestTempDir(), "/test.proto"), "syntax = \"proto2\";\n"
"syntax = \"proto2\";\n" "package foo;\n"
"package foo;\n" "option java_package = \"\";\n"
"option java_package = \"\";\n" "option java_outer_classname = \"Test\";\n"
"option java_outer_classname = \"Test\";\n" "message Bar {\n"
"message Bar {\n" " message Baz {}\n"
" message Baz {}\n" "}\n"
"}\n" "enum Qux { BLAH = 1; }\n",
"enum Qux { BLAH = 1; }\n", true));
true));
CommandLineInterface cli; CommandLineInterface cli;
cli.SetInputsAreProtoPathRelative(true); cli.SetInputsAreProtoPathRelative(true);
@ -101,9 +100,9 @@ TEST(JavaPluginTest, PluginTest) {
cli.RegisterGenerator("--java_out", &java_generator, ""); cli.RegisterGenerator("--java_out", &java_generator, "");
cli.RegisterGenerator("--test_out", &test_generator, ""); cli.RegisterGenerator("--test_out", &test_generator, "");
std::string proto_path = absl::StrCat("-I", TestTempDir()); std::string proto_path = "-I" + TestTempDir();
std::string java_out = absl::StrCat("--java_out=", TestTempDir()); std::string java_out = "--java_out=" + TestTempDir();
std::string test_out = absl::StrCat("--test_out=", TestTempDir()); std::string test_out = "--test_out=" + TestTempDir();
const char* argv[] = {"protoc", proto_path.c_str(), java_out.c_str(), const char* argv[] = {"protoc", proto_path.c_str(), java_out.c_str(),
test_out.c_str(), "test.proto"}; test_out.c_str(), "test.proto"};
@ -114,8 +113,8 @@ TEST(JavaPluginTest, PluginTest) {
// expect // expect
std::string output; std::string output;
GOOGLE_ABSL_CHECK_OK(File::GetContents(absl::StrCat(TestTempDir(), "/Test.java"), GOOGLE_ABSL_CHECK_OK(File::GetContents(TestTempDir() + "/Test.java", &output,
&output, true)); true));
std::vector<std::string> lines = absl::StrSplit(output, "\n"); std::vector<std::string> lines = absl::StrSplit(output, "\n");
bool found_generated_annotation = false; bool found_generated_annotation = false;
bool found_do_not_edit = false; bool found_do_not_edit = false;

@ -64,9 +64,9 @@ void SetPrimitiveVariables(
SetCommonFieldVariables(descriptor, info, variables); SetCommonFieldVariables(descriptor, info, variables);
JavaType javaType = GetJavaType(descriptor); JavaType javaType = GetJavaType(descriptor);
(*variables)["type"] = std::string(PrimitiveTypeName(javaType)); (*variables)["type"] = PrimitiveTypeName(javaType);
(*variables)["boxed_type"] = std::string(BoxedPrimitiveTypeName(javaType)); (*variables)["boxed_type"] = BoxedPrimitiveTypeName(javaType);
(*variables)["kt_type"] = std::string(KotlinTypeName(javaType)); (*variables)["kt_type"] = KotlinTypeName(javaType);
variables->insert({"field_type", (*variables)["type"]}); variables->insert({"field_type", (*variables)["type"]});
std::string name = (*variables)["name"]; std::string name = (*variables)["name"];
@ -112,10 +112,10 @@ void SetPrimitiveVariables(
(*variables)["default_init"] = (*variables)["default_init"] =
IsDefaultValueJavaDefault(descriptor) IsDefaultValueJavaDefault(descriptor)
? "" ? ""
: absl::StrCat("= ", ImmutableDefaultValue(descriptor, name_resolver, : ("= " + ImmutableDefaultValue(descriptor, name_resolver,
context->options())); context->options()));
(*variables)["capitalized_type"] = std::string(GetCapitalizedType( (*variables)["capitalized_type"] = GetCapitalizedType(
descriptor, /* immutable = */ true, context->options())); descriptor, /* immutable = */ true, context->options());
(*variables)["tag"] = (*variables)["tag"] =
absl::StrCat(static_cast<int32_t>(WireFormat::MakeTag(descriptor))); absl::StrCat(static_cast<int32_t>(WireFormat::MakeTag(descriptor)));
(*variables)["tag_size"] = absl::StrCat( (*variables)["tag_size"] = absl::StrCat(
@ -146,7 +146,7 @@ void SetPrimitiveVariables(
(*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
// Note that these have a trailing ";". // Note that these have a trailing ";".
(*variables)["set_has_field_bit_to_local"] = (*variables)["set_has_field_bit_to_local"] =
absl::StrCat(GenerateSetBitToLocal(messageBitIndex), ";"); GenerateSetBitToLocal(messageBitIndex) + ";";
(*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
} else { } else {
(*variables)["set_has_field_bit_to_local"] = ""; (*variables)["set_has_field_bit_to_local"] = "";
@ -182,9 +182,9 @@ void SetPrimitiveVariables(
(*variables)["get_has_field_bit_from_local"] = (*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex); GenerateGetBitFromLocal(builderBitIndex);
(*variables)["set_has_field_bit_builder"] = (*variables)["set_has_field_bit_builder"] =
absl::StrCat(GenerateSetBit(builderBitIndex), ";"); GenerateSetBit(builderBitIndex) + ";";
(*variables)["clear_has_field_bit_builder"] = (*variables)["clear_has_field_bit_builder"] =
absl::StrCat(GenerateClearBit(builderBitIndex), ";"); GenerateClearBit(builderBitIndex) + ";";
} }
} // namespace } // namespace
@ -506,7 +506,7 @@ void ImmutablePrimitiveFieldGenerator::GenerateHashCode(
} }
std::string ImmutablePrimitiveFieldGenerator::GetBoxedType() const { std::string ImmutablePrimitiveFieldGenerator::GetBoxedType() const {
return std::string(BoxedPrimitiveTypeName(GetJavaType(descriptor_))); return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
} }
// =================================================================== // ===================================================================
@ -1069,7 +1069,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateHashCode(
} }
std::string RepeatedImmutablePrimitiveFieldGenerator::GetBoxedType() const { std::string RepeatedImmutablePrimitiveFieldGenerator::GetBoxedType() const {
return std::string(BoxedPrimitiveTypeName(GetJavaType(descriptor_))); return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
} }
} // namespace java } // namespace java

@ -70,14 +70,14 @@ void SetPrimitiveVariables(
Context* context) { Context* context) {
SetCommonFieldVariables(descriptor, info, variables); SetCommonFieldVariables(descriptor, info, variables);
JavaType javaType = GetJavaType(descriptor); JavaType javaType = GetJavaType(descriptor);
(*variables)["type"] = std::string(PrimitiveTypeName(javaType)); (*variables)["type"] = PrimitiveTypeName(javaType);
(*variables)["boxed_type"] = std::string(BoxedPrimitiveTypeName(javaType)); (*variables)["boxed_type"] = BoxedPrimitiveTypeName(javaType);
(*variables)["kt_type"] = std::string(KotlinTypeName(javaType)); (*variables)["kt_type"] = KotlinTypeName(javaType);
variables->insert({"field_type", (*variables)["type"]}); variables->insert({"field_type", (*variables)["type"]});
(*variables)["default"] = (*variables)["default"] =
ImmutableDefaultValue(descriptor, name_resolver, context->options()); ImmutableDefaultValue(descriptor, name_resolver, context->options());
(*variables)["capitalized_type"] = std::string(GetCapitalizedType( (*variables)["capitalized_type"] = GetCapitalizedType(
descriptor, /* immutable = */ true, context->options())); descriptor, /* immutable = */ true, context->options());
(*variables)["tag"] = (*variables)["tag"] =
absl::StrCat(static_cast<int32_t>(WireFormat::MakeTag(descriptor))); absl::StrCat(static_cast<int32_t>(WireFormat::MakeTag(descriptor)));
(*variables)["tag_size"] = absl::StrCat( (*variables)["tag_size"] = absl::StrCat(
@ -126,7 +126,7 @@ void SetPrimitiveVariables(
if (javaType == JAVATYPE_BYTES) { if (javaType == JAVATYPE_BYTES) {
(*variables)["bytes_default"] = (*variables)["bytes_default"] =
absl::StrCat(absl::AsciiStrToUpper(name), "_DEFAULT_VALUE"); absl::AsciiStrToUpper(name) + "_DEFAULT_VALUE";
} }
if (IsReferenceType(javaType)) { if (IsReferenceType(javaType)) {
@ -157,9 +157,9 @@ void SetPrimitiveVariables(
// Note that these have a trailing ";". // Note that these have a trailing ";".
(*variables)["set_has_field_bit_message"] = (*variables)["set_has_field_bit_message"] =
absl::StrCat(GenerateSetBit(messageBitIndex), ";"); GenerateSetBit(messageBitIndex) + ";";
(*variables)["clear_has_field_bit_message"] = (*variables)["clear_has_field_bit_message"] =
absl::StrCat(GenerateClearBit(messageBitIndex), ";"); GenerateClearBit(messageBitIndex) + ";";
(*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
} else { } else {
@ -182,7 +182,7 @@ void SetPrimitiveVariables(
default: default:
variables->insert( variables->insert(
{"is_field_present_message", {"is_field_present_message",
absl::StrCat(name, "_ != ", (*variables)["default"])}); absl::StrCat(name, "_ != " + (*variables)["default"])});
break; break;
} }
} }
@ -394,7 +394,7 @@ void ImmutablePrimitiveFieldLiteGenerator::GenerateInitializationCode(
} }
std::string ImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const { std::string ImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const {
return std::string(BoxedPrimitiveTypeName(GetJavaType(descriptor_))); return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
} }
// =================================================================== // ===================================================================
@ -796,7 +796,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateInitializationCode(
} }
std::string RepeatedImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const { std::string RepeatedImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const {
return std::string(BoxedPrimitiveTypeName(GetJavaType(descriptor_))); return BoxedPrimitiveTypeName(GetJavaType(descriptor_));
} }
} // namespace java } // namespace java

@ -66,7 +66,7 @@ void SharedCodeGenerator::Generate(
if (HasDescriptorMethods(file_, options_.enforce_lite)) { if (HasDescriptorMethods(file_, options_.enforce_lite)) {
// Generate descriptors. // Generate descriptors.
std::string classname = name_resolver_->GetDescriptorClassName(file_); std::string classname = name_resolver_->GetDescriptorClassName(file_);
std::string filename = absl::StrCat(package_dir, classname, ".java"); std::string filename = package_dir + classname + ".java";
file_list->push_back(filename); file_list->push_back(filename);
std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename)); std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GeneratedCodeInfo annotations; GeneratedCodeInfo annotations;
@ -75,8 +75,8 @@ void SharedCodeGenerator::Generate(
std::unique_ptr<io::Printer> printer( std::unique_ptr<io::Printer> printer(
new io::Printer(output.get(), '$', new io::Printer(output.get(), '$',
options_.annotate_code ? &annotation_collector : NULL)); options_.annotate_code ? &annotation_collector : NULL));
std::string info_relative_path = absl::StrCat(classname, ".java.pb.meta"); std::string info_relative_path = classname + ".java.pb.meta";
std::string info_full_path = absl::StrCat(filename, ".pb.meta"); std::string info_full_path = filename + ".pb.meta";
printer->Print( printer->Print(
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n" "// source: $filename$\n"
@ -177,7 +177,7 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
if (package.empty()) { if (package.empty()) {
full_name = classname; full_name = classname;
} else { } else {
full_name = absl::StrCat(package, ".", classname); full_name = package + "." + classname;
} }
dependencies.push_back(std::make_pair(filename, full_name)); dependencies.push_back(std::make_pair(filename, full_name));
} }

@ -69,9 +69,9 @@ void SetPrimitiveVariables(
(*variables)["default"] = (*variables)["default"] =
ImmutableDefaultValue(descriptor, name_resolver, context->options()); ImmutableDefaultValue(descriptor, name_resolver, context->options());
(*variables)["default_init"] = absl::StrCat( (*variables)["default_init"] =
"= ", "= " +
ImmutableDefaultValue(descriptor, name_resolver, context->options())); ImmutableDefaultValue(descriptor, name_resolver, context->options());
(*variables)["capitalized_type"] = "String"; (*variables)["capitalized_type"] = "String";
(*variables)["tag"] = (*variables)["tag"] =
absl::StrCat(static_cast<int32_t>(WireFormat::MakeTag(descriptor))); absl::StrCat(static_cast<int32_t>(WireFormat::MakeTag(descriptor)));
@ -79,15 +79,14 @@ void SetPrimitiveVariables(
WireFormat::TagSize(descriptor->number(), GetType(descriptor))); WireFormat::TagSize(descriptor->number(), GetType(descriptor)));
(*variables)["null_check"] = (*variables)["null_check"] =
"if (value == null) { throw new NullPointerException(); }"; "if (value == null) { throw new NullPointerException(); }";
(*variables)["isStringEmpty"] = (*variables)["isStringEmpty"] = "com.google.protobuf.GeneratedMessage" +
absl::StrCat("com.google.protobuf.GeneratedMessage", GeneratedCodeVersionSuffix() +
GeneratedCodeVersionSuffix(), ".isStringEmpty"); ".isStringEmpty";
(*variables)["writeString"] = (*variables)["writeString"] = "com.google.protobuf.GeneratedMessage" +
absl::StrCat("com.google.protobuf.GeneratedMessage", GeneratedCodeVersionSuffix() + ".writeString";
GeneratedCodeVersionSuffix(), ".writeString"); (*variables)["computeStringSize"] = "com.google.protobuf.GeneratedMessage" +
(*variables)["computeStringSize"] = GeneratedCodeVersionSuffix() +
absl::StrCat("com.google.protobuf.GeneratedMessage", ".computeStringSize";
GeneratedCodeVersionSuffix(), ".computeStringSize");
// TODO(birdo): Add @deprecated javadoc when generating javadoc is supported // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported
// by the proto compiler // by the proto compiler
@ -109,7 +108,7 @@ void SetPrimitiveVariables(
// Note that these have a trailing ";". // Note that these have a trailing ";".
(*variables)["set_has_field_bit_message"] = (*variables)["set_has_field_bit_message"] =
absl::StrCat(GenerateSetBit(messageBitIndex), ";"); GenerateSetBit(messageBitIndex) + ";";
(*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
} else { } else {
@ -131,9 +130,9 @@ void SetPrimitiveVariables(
(*variables)["get_has_field_bit_from_local"] = (*variables)["get_has_field_bit_from_local"] =
GenerateGetBitFromLocal(builderBitIndex); GenerateGetBitFromLocal(builderBitIndex);
(*variables)["set_has_field_bit_builder"] = (*variables)["set_has_field_bit_builder"] =
absl::StrCat(GenerateSetBit(builderBitIndex), ";"); GenerateSetBit(builderBitIndex) + ";";
(*variables)["clear_has_field_bit_builder"] = (*variables)["clear_has_field_bit_builder"] =
absl::StrCat(GenerateClearBit(builderBitIndex), ";"); GenerateClearBit(builderBitIndex) + ";";
} }
} // namespace } // namespace

@ -69,9 +69,9 @@ void SetPrimitiveVariables(
(*variables)["default"] = (*variables)["default"] =
ImmutableDefaultValue(descriptor, name_resolver, context->options()); ImmutableDefaultValue(descriptor, name_resolver, context->options());
(*variables)["default_init"] = absl::StrCat( (*variables)["default_init"] =
"= ", "= " +
ImmutableDefaultValue(descriptor, name_resolver, context->options())); ImmutableDefaultValue(descriptor, name_resolver, context->options());
(*variables)["capitalized_type"] = "java.lang.String"; (*variables)["capitalized_type"] = "java.lang.String";
(*variables)["tag"] = (*variables)["tag"] =
absl::StrCat(static_cast<int32_t>(WireFormat::MakeTag(descriptor))); absl::StrCat(static_cast<int32_t>(WireFormat::MakeTag(descriptor)));
@ -109,9 +109,9 @@ void SetPrimitiveVariables(
// Note that these have a trailing ";". // Note that these have a trailing ";".
(*variables)["set_has_field_bit_message"] = (*variables)["set_has_field_bit_message"] =
absl::StrCat(GenerateSetBit(messageBitIndex), ";"); GenerateSetBit(messageBitIndex) + ";";
(*variables)["clear_has_field_bit_message"] = (*variables)["clear_has_field_bit_message"] =
absl::StrCat(GenerateClearBit(messageBitIndex), ";"); GenerateClearBit(messageBitIndex) + ";";
(*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
} else { } else {

@ -6909,13 +6909,14 @@ void DescriptorBuilder::ValidateFileOptions(FileDescriptor* file,
if (!IsLite(file)) { if (!IsLite(file)) {
for (int i = 0; i < file->dependency_count(); i++) { for (int i = 0; i < file->dependency_count(); i++) {
if (IsLite(file->dependency(i))) { if (IsLite(file->dependency(i))) {
AddError( AddError(file->dependency(i)->name(), proto,
file->dependency(i)->name(), proto, DescriptorPool::ErrorCollector::IMPORT,
DescriptorPool::ErrorCollector::IMPORT, absl::StrCat("Files that do not use optimize_for = "
absl::StrCat("Files that do not use optimize_for = LITE_RUNTIME " "LITE_RUNTIME cannot import "
"cannot import files which do use this option. This " "files which do use this option. This file is "
"file is not lite, but it imports \"", "not lite, but it "
file->dependency(i)->name(), "\" which is.")); "imports \"",
file->dependency(i)->name(), "\" which is."));
break; break;
} }
} }
@ -7447,7 +7448,8 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
} }
if (uninterpreted_option_->name(0).name_part() == "uninterpreted_option") { if (uninterpreted_option_->name(0).name_part() == "uninterpreted_option") {
return AddNameError( return AddNameError(
"Option must not use reserved name \"uninterpreted_option\"."); "Option must not use reserved name "
"\"uninterpreted_option\".");
} }
const Descriptor* options_descriptor = nullptr; const Descriptor* options_descriptor = nullptr;
@ -7939,7 +7941,8 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
uint64_t value; uint64_t value;
if (!uninterpreted_option_->has_identifier_value()) { if (!uninterpreted_option_->has_identifier_value()) {
return AddValueError( return AddValueError(
absl::StrCat("Value must be identifier for boolean option \"", absl::StrCat("Value must be identifier for boolean option "
"\"",
option_field->full_name(), "\".")); option_field->full_name(), "\"."));
} }
if (uninterpreted_option_->identifier_value() == "true") { if (uninterpreted_option_->identifier_value() == "true") {
@ -7947,9 +7950,10 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
} else if (uninterpreted_option_->identifier_value() == "false") { } else if (uninterpreted_option_->identifier_value() == "false") {
value = 0; value = 0;
} else { } else {
return AddValueError(absl::StrCat( return AddValueError(
"Value must be \"true\" or \"false\" for boolean option \"", absl::StrCat("Value must be \"true\" or \"false\" for boolean "
option_field->full_name(), "\".")); "option \"",
option_field->full_name(), "\"."));
} }
unknown_fields->AddVarint(option_field->number(), value); unknown_fields->AddVarint(option_field->number(), value);
break; break;
@ -7957,7 +7961,8 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
case FieldDescriptor::CPPTYPE_ENUM: { case FieldDescriptor::CPPTYPE_ENUM: {
if (!uninterpreted_option_->has_identifier_value()) { if (!uninterpreted_option_->has_identifier_value()) {
return AddValueError( return AddValueError(
absl::StrCat("Value must be identifier for enum-valued option \"", absl::StrCat("Value must be identifier for enum-valued option "
"\"",
option_field->full_name(), "\".")); option_field->full_name(), "\"."));
} }
const EnumDescriptor* enum_type = option_field->enum_type(); const EnumDescriptor* enum_type = option_field->enum_type();
@ -7999,7 +8004,9 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
return AddValueError( return AddValueError(
absl::StrCat("Enum type \"", option_field->enum_type()->full_name(), absl::StrCat("Enum type \"", option_field->enum_type()->full_name(),
"\" has no value named \"", value_name, "\" has no value named \"", value_name,
"\" for option \"", option_field->full_name(), "\".")); "\" for "
"option \"",
option_field->full_name(), "\"."));
} else { } else {
// Sign-extension is not a problem, since we cast directly from int32_t // Sign-extension is not a problem, since we cast directly from int32_t
// to uint64_t, without first going through uint32_t. // to uint64_t, without first going through uint32_t.
@ -8013,7 +8020,8 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
case FieldDescriptor::CPPTYPE_STRING: case FieldDescriptor::CPPTYPE_STRING:
if (!uninterpreted_option_->has_string_value()) { if (!uninterpreted_option_->has_string_value()) {
return AddValueError( return AddValueError(
absl::StrCat("Value must be quoted string for string option \"", absl::StrCat("Value must be quoted string for string option "
"\"",
option_field->full_name(), "\".")); option_field->full_name(), "\"."));
} }
// The string has already been unquoted and unescaped by the parser. // The string has already been unquoted and unescaped by the parser.
@ -8107,11 +8115,12 @@ bool DescriptorBuilder::OptionInterpreter::SetAggregateOption(
if (!uninterpreted_option_->has_aggregate_value()) { if (!uninterpreted_option_->has_aggregate_value()) {
return AddValueError( return AddValueError(
absl::StrCat("Option \"", option_field->full_name(), absl::StrCat("Option \"", option_field->full_name(),
"\" is a message. " "\" is a message. To set the entire message, use "
"To set the entire message, use syntax like \"", "syntax like \"",
option_field->name(), option_field->name(),
" = { <proto text format> }\". " " = { <proto text format> }\". "
"To set fields within it, use syntax like \"", "To set fields within it, use "
"syntax like \"",
option_field->name(), ".foo = value\".")); option_field->name(), ".foo = value\"."));
} }

@ -1072,7 +1072,7 @@ TEST(ExtensionSetTest, RepeatedFields) {
.MutableRepeatedExtension(unittest::repeated_string_extension) .MutableRepeatedExtension(unittest::repeated_string_extension)
->end(); ->end();
string_iter != string_end; ++string_iter) { string_iter != string_end; ++string_iter) {
string_iter->append("test"); absl::StrAppend(&*string_iter, "test");
} }
RepeatedPtrField<std::string>::const_iterator string_const_iter; RepeatedPtrField<std::string>::const_iterator string_const_iter;
RepeatedPtrField<std::string>::const_iterator string_const_end; RepeatedPtrField<std::string>::const_iterator string_const_end;

@ -61,8 +61,9 @@ inline std::string TranslatePathToOpensource(absl::string_view google3_path) {
} }
inline std::string MaybeTranslatePath(absl::string_view google3_path) { inline std::string MaybeTranslatePath(absl::string_view google3_path) {
return TranslatePathToOpensource(google3_path); std::string path(google3_path);
return std::string(google3_path); path = TranslatePathToOpensource(path);
return path;
} }
inline std::string TestSourceDir() { inline std::string TestSourceDir() {

@ -910,12 +910,15 @@ class TextFormat::Parser::ParserImpl {
return true; return true;
} else if (!allow_unknown_enum_) { } else if (!allow_unknown_enum_) {
ReportError(absl::StrCat("Unknown enumeration value of \"", value, ReportError(absl::StrCat("Unknown enumeration value of \"", value,
"\" for field \"", field->name(), "\".")); "\" for "
"field \"",
field->name(), "\"."));
return false; return false;
} else { } else {
ReportWarning(absl::StrCat("Unknown enumeration value of \"", value, ReportWarning(absl::StrCat("Unknown enumeration value of \"", value,
"\" for field \"", field->name(), "\" for "
"\".")); "field \"",
field->name(), "\"."));
return true; return true;
} }
} }

Loading…
Cancel
Save