From e936433fa639fc6ac7199d0d0e87cae9d3e7f900 Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Fri, 7 Oct 2022 11:00:37 -0400 Subject: [PATCH] [ObjC] Run clang-format on the ObjC Generator impl files. --- .../protobuf/compiler/objectivec/enum.cc | 44 +- .../compiler/objectivec/enum_field.cc | 16 +- .../protobuf/compiler/objectivec/extension.cc | 9 +- .../protobuf/compiler/objectivec/field.cc | 38 +- .../protobuf/compiler/objectivec/file.cc | 68 +-- .../protobuf/compiler/objectivec/generator.cc | 33 +- .../protobuf/compiler/objectivec/helpers.cc | 24 +- .../compiler/objectivec/import_writer.cc | 80 ++-- .../compiler/objectivec/line_consumer.cc | 26 +- .../objectivec/line_consumer_unittest.cc | 92 ++-- .../protobuf/compiler/objectivec/map_field.cc | 26 +- .../protobuf/compiler/objectivec/message.cc | 75 ++- .../compiler/objectivec/message_field.cc | 27 +- .../protobuf/compiler/objectivec/names.cc | 426 ++++++++++++------ .../compiler/objectivec/names_unittest.cc | 3 +- .../protobuf/compiler/objectivec/oneof.cc | 22 +- .../compiler/objectivec/primitive_field.cc | 2 +- .../objectivec/text_format_decode_data.cc | 27 +- .../text_format_decode_data_unittest.cc | 1 - 19 files changed, 580 insertions(+), 459 deletions(-) diff --git a/src/google/protobuf/compiler/objectivec/enum.cc b/src/google/protobuf/compiler/objectivec/enum.cc index 3b81df8d63..af3e3353cd 100644 --- a/src/google/protobuf/compiler/objectivec/enum.cc +++ b/src/google/protobuf/compiler/objectivec/enum.cc @@ -36,8 +36,8 @@ #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/text_format_decode_data.h" #include "google/protobuf/io/printer.h" @@ -58,8 +58,7 @@ std::string SafelyPrintIntToCode(int v) { } // namespace EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor) - : descriptor_(descriptor), - name_(EnumName(descriptor_)) { + : descriptor_(descriptor), name_(EnumName(descriptor_)) { // Track the names for the enum values, and if an alias overlaps a base // value, skip making a name for it. Likewise if two alias overlap, the // first one wins. @@ -121,10 +120,11 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) { // doesn't have to bother with the `enum_extensibility` attribute, as the // default will be what is needed. - printer->Print("$comments$typedef$deprecated_attribute$ GPB_ENUM($name$) {\n", - "comments", enum_comments, - "deprecated_attribute", GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()), - "name", name_); + printer->Print( + "$comments$typedef$deprecated_attribute$ GPB_ENUM($name$) {\n", + "comments", enum_comments, "deprecated_attribute", + GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()), "name", + name_); printer->Indent(); if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { @@ -141,7 +141,8 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) { "name", name_); } for (int i = 0; i < all_values_.size(); i++) { - if (alias_values_to_skip_.find(all_values_[i]) != alias_values_to_skip_.end()) { + if (alias_values_to_skip_.find(all_values_[i]) != + alias_values_to_skip_.end()) { continue; } if (all_values_[i]->GetSourceLocation(&location)) { @@ -154,11 +155,10 @@ void EnumGenerator::GenerateHeader(io::Printer* printer) { } } - printer->Print( - "$name$$deprecated_attribute$ = $value$,\n", - "name", EnumValueName(all_values_[i]), - "deprecated_attribute", GetOptionalDeprecatedAttribute(all_values_[i]), - "value", SafelyPrintIntToCode(all_values_[i]->number())); + printer->Print("$name$$deprecated_attribute$ = $value$,\n", "name", + EnumValueName(all_values_[i]), "deprecated_attribute", + GetOptionalDeprecatedAttribute(all_values_[i]), "value", + SafelyPrintIntToCode(all_values_[i]->number())); } printer->Outdent(); printer->Print( @@ -211,18 +211,17 @@ void EnumGenerator::GenerateSource(io::Printer* printer) { "name", name_); static const int kBytesPerLine = 40; // allow for escaping - printer->Print( - " static const char *valueNames ="); + printer->Print(" static const char *valueNames ="); for (int i = 0; i < text_blob.size(); i += kBytesPerLine) { printer->Print( - "\n \"$data$\"", - "data", EscapeTrigraphs(absl::CEscape(text_blob.substr(i, kBytesPerLine)))); + "\n \"$data$\"", "data", + EscapeTrigraphs(absl::CEscape(text_blob.substr(i, kBytesPerLine)))); } printer->Print( ";\n" " static const int32_t values[] = {\n"); for (int i = 0; i < all_values_.size(); i++) { - printer->Print(" $name$,\n", "name", EnumValueName(all_values_[i])); + printer->Print(" $name$,\n", "name", EnumValueName(all_values_[i])); } printer->Print(" };\n"); @@ -249,8 +248,8 @@ void EnumGenerator::GenerateSource(io::Printer* printer) { " enumVerifier:$name$_IsValidValue\n" " extraTextFormatInfo:extraTextFormatInfo];\n", // clang-format on - "name", name_, - "extraTextFormatInfo", absl::CEscape(text_format_decode_data.Data())); + "name", name_, "extraTextFormatInfo", + absl::CEscape(text_format_decode_data.Data())); } // clang-format off printer->Print( @@ -271,9 +270,8 @@ void EnumGenerator::GenerateSource(io::Printer* printer) { "name", name_); for (int i = 0; i < base_values_.size(); i++) { - printer->Print( - " case $name$:\n", - "name", EnumValueName(base_values_[i])); + printer->Print(" case $name$:\n", "name", + EnumValueName(base_values_[i])); } // clang-format off diff --git a/src/google/protobuf/compiler/objectivec/enum_field.cc b/src/google/protobuf/compiler/objectivec/enum_field.cc index c779a5e0d4..c08cbde970 100644 --- a/src/google/protobuf/compiler/objectivec/enum_field.cc +++ b/src/google/protobuf/compiler/objectivec/enum_field.cc @@ -28,12 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#include "google/protobuf/compiler/objectivec/enum_field.h" + #include #include -#include "google/protobuf/compiler/objectivec/enum_field.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" namespace google { @@ -119,10 +120,9 @@ void EnumFieldGenerator::GenerateCFunctionImplementations( } void EnumFieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls, - bool include_external_types) const { - SingleFieldGenerator::DetermineForwardDeclarations( - fwd_decls, include_external_types); + std::set* fwd_decls, bool include_external_types) const { + SingleFieldGenerator::DetermineForwardDeclarations(fwd_decls, + include_external_types); // If it is an enum defined in a different file (and not a WKT), then we'll // need a forward declaration for it. When it is in our file, all the enums // are output before the message, so it will be declared before it is needed. @@ -146,8 +146,8 @@ RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {} void RepeatedEnumFieldGenerator::FinishInitialization(void) { RepeatedFieldGenerator::FinishInitialization(); - variables_["array_comment"] = - "// |" + variables_["name"] + "| contains |" + variables_["storage_type"] + "|\n"; + variables_["array_comment"] = "// |" + variables_["name"] + "| contains |" + + variables_["storage_type"] + "|\n"; } } // namespace objectivec diff --git a/src/google/protobuf/compiler/objectivec/extension.cc b/src/google/protobuf/compiler/objectivec/extension.cc index 768b4f1063..d23cf5c126 100644 --- a/src/google/protobuf/compiler/objectivec/extension.cc +++ b/src/google/protobuf/compiler/objectivec/extension.cc @@ -33,8 +33,8 @@ #include #include "absl/strings/str_cat.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/printer.h" @@ -52,7 +52,7 @@ ExtensionGenerator::ExtensionGenerator(const std::string& root_class_name, // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some // error cases, so it seems to be ok to use as a back door for errors. std::cerr << "error: Extension is a map<>!" - << " That used to be blocked by the compiler." << std::endl; + << " That used to be blocked by the compiler." << std::endl; std::cerr.flush(); abort(); } @@ -76,7 +76,8 @@ void ExtensionGenerator::GenerateMembersHeader(io::Printer* printer) { } // Unlike normal message fields, check if the file for the extension was // deprecated. - vars["deprecated_attribute"] = GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()); + vars["deprecated_attribute"] = + GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()); // clang-format off printer->Print( vars, @@ -120,7 +121,7 @@ void ExtensionGenerator::GenerateStaticVariablesInitialization( if (objc_type == OBJECTIVECTYPE_ENUM) { vars["enum_desc_func_name"] = - EnumName(descriptor_->enum_type()) + "_EnumDescriptor"; + EnumName(descriptor_->enum_type()) + "_EnumDescriptor"; } else { vars["enum_desc_func_name"] = "NULL"; } diff --git a/src/google/protobuf/compiler/objectivec/field.cc b/src/google/protobuf/compiler/objectivec/field.cc index a5fe4e97c9..94663be507 100644 --- a/src/google/protobuf/compiler/objectivec/field.cc +++ b/src/google/protobuf/compiler/objectivec/field.cc @@ -34,10 +34,10 @@ #include "absl/strings/str_cat.h" #include "google/protobuf/compiler/objectivec/enum_field.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" #include "google/protobuf/compiler/objectivec/map_field.h" #include "google/protobuf/compiler/objectivec/message_field.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/primitive_field.h" #include "google/protobuf/io/printer.h" @@ -78,7 +78,8 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor, classname + "_FieldNumber_" + capitalized_name; (*variables)["field_number"] = absl::StrCat(descriptor->number()); (*variables)["field_type"] = GetCapitalizedType(descriptor); - (*variables)["deprecated_attribute"] = GetOptionalDeprecatedAttribute(descriptor); + (*variables)["deprecated_attribute"] = + GetOptionalDeprecatedAttribute(descriptor); std::vector field_flags; if (descriptor->is_repeated()) field_flags.push_back("GPBFieldRepeated"); if (descriptor->is_required()) field_flags.push_back("GPBFieldRequired"); @@ -109,8 +110,8 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor, (*variables)["dataTypeSpecific_name"] = "clazz"; (*variables)["dataTypeSpecific_value"] = "Nil"; - (*variables)["storage_offset_value"] = - "(uint32_t)offsetof(" + classname + "__storage_, " + camel_case_name + ")"; + (*variables)["storage_offset_value"] = "(uint32_t)offsetof(" + classname + + "__storage_, " + camel_case_name + ")"; (*variables)["storage_offset_comment"] = ""; // Clear some common things so they can be set just when needed. @@ -213,13 +214,10 @@ FieldGenerator::FieldGenerator(const FieldDescriptor* descriptor) FieldGenerator::~FieldGenerator() {} void FieldGenerator::GenerateFieldNumberConstant(io::Printer* printer) const { - printer->Print( - variables_, - "$field_number_name$ = $field_number$,\n"); + printer->Print(variables_, "$field_number_name$ = $field_number$,\n"); } -void FieldGenerator::GenerateCFunctionDeclarations( - io::Printer* printer) const { +void FieldGenerator::GenerateCFunctionDeclarations(io::Printer* printer) const { // Nothing } @@ -229,8 +227,7 @@ void FieldGenerator::GenerateCFunctionImplementations( } void FieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls, - bool include_external_types) const { + std::set* fwd_decls, bool include_external_types) const { // Nothing } @@ -239,8 +236,8 @@ void FieldGenerator::DetermineObjectiveCClassDefinitions( // Nothing } -void FieldGenerator::GenerateFieldDescription( - io::Printer* printer, bool include_default) const { +void FieldGenerator::GenerateFieldDescription(io::Printer* printer, + bool include_default) const { // Printed in the same order as the structure decl. if (include_default) { // clang-format off @@ -282,14 +279,13 @@ void FieldGenerator::SetNoHasBit(void) { variables_["has_index"] = "GPBNoHasBit"; } -int FieldGenerator::ExtraRuntimeHasBitsNeeded(void) const { - return 0; -} +int FieldGenerator::ExtraRuntimeHasBitsNeeded(void) const { return 0; } void FieldGenerator::SetExtraRuntimeHasBitsBase(int index_base) { // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some // error cases, so it seems to be ok to use as a back door for errors. - std::cerr << "Error: should have overridden SetExtraRuntimeHasBitsBase()." << std::endl; + std::cerr << "Error: should have overridden SetExtraRuntimeHasBitsBase()." + << std::endl; std::cerr.flush(); abort(); } @@ -379,7 +375,6 @@ void ObjCObjFieldGenerator::GenerateFieldStorageDeclaration( void ObjCObjFieldGenerator::GeneratePropertyDeclaration( io::Printer* printer) const { - // Differs from SingleFieldGenerator::GeneratePropertyDeclaration() in that // it uses pointers and deals with Objective C's rules around storage name // conventions (init*, new*, etc.) @@ -402,7 +397,8 @@ void ObjCObjFieldGenerator::GeneratePropertyDeclaration( // If property name starts with init we need to annotate it to get past ARC. // http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227 printer->Print(variables_, - "- ($property_type$ *)$name$ GPB_METHOD_FAMILY_NONE$deprecated_attribute$;\n"); + "- ($property_type$ *)$name$ " + "GPB_METHOD_FAMILY_NONE$deprecated_attribute$;\n"); } printer->Print("\n"); } @@ -435,7 +431,6 @@ void RepeatedFieldGenerator::GeneratePropertyImplementation( void RepeatedFieldGenerator::GeneratePropertyDeclaration( io::Printer* printer) const { - // Repeated fields don't need the has* properties, but they do expose a // *Count (to check without autocreation). So for the field property we need // the same logic as ObjCObjFieldGenerator::GeneratePropertyDeclaration() for @@ -472,8 +467,7 @@ FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor) extension_generators_(descriptor->extension_count()) { // Construct all the FieldGenerators. for (int i = 0; i < descriptor->field_count(); i++) { - field_generators_[i].reset( - FieldGenerator::Make(descriptor->field(i))); + field_generators_[i].reset(FieldGenerator::Make(descriptor->field(i))); } for (int i = 0; i < descriptor->extension_count(); i++) { extension_generators_[i].reset( diff --git a/src/google/protobuf/compiler/objectivec/file.cc b/src/google/protobuf/compiler/objectivec/file.cc index 291696f7f9..2fe4ccd04e 100644 --- a/src/google/protobuf/compiler/objectivec/file.cc +++ b/src/google/protobuf/compiler/objectivec/file.cc @@ -34,14 +34,14 @@ #include #include -#include "google/protobuf/compiler/code_generator.h" #include "absl/strings/str_cat.h" +#include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/compiler/objectivec/enum.h" #include "google/protobuf/compiler/objectivec/extension.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" #include "google/protobuf/compiler/objectivec/import_writer.h" #include "google/protobuf/compiler/objectivec/message.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some @@ -137,7 +137,7 @@ struct FileDescriptorsOrderedByName { } // namespace -FileGenerator::CommonState::CommonState() { } +FileGenerator::CommonState::CommonState() {} const FileGenerator::CommonState::MinDepsEntry& FileGenerator::CommonState::CollectMinimalFileDepsContainingExtensionsInternal( @@ -156,20 +156,24 @@ FileGenerator::CommonState::CollectMinimalFileDepsContainingExtensionsInternal( CollectMinimalFileDepsContainingExtensionsInternal(dep); // Everything the dep covered, this file will also cover. - covered_deps_collector.insert(dep_info.covered_deps.begin(), dep_info.covered_deps.end()); + covered_deps_collector.insert(dep_info.covered_deps.begin(), + dep_info.covered_deps.end()); // Prune everything from the dep's covered list in case another dep lists it // as a min dep. to_prune.insert(dep_info.covered_deps.begin(), dep_info.covered_deps.end()); // Does the dep have any extensions... if (dep_info.has_extensions) { - // Yes -> Add this file, prune its min_deps and add them to the covered deps. + // Yes -> Add this file, prune its min_deps and add them to the covered + // deps. min_deps_collector.insert(dep); to_prune.insert(dep_info.min_deps.begin(), dep_info.min_deps.end()); - covered_deps_collector.insert(dep_info.min_deps.begin(), dep_info.min_deps.end()); + covered_deps_collector.insert(dep_info.min_deps.begin(), + dep_info.min_deps.end()); } else { // No -> Just use its min_deps. - min_deps_collector.insert(dep_info.min_deps.begin(), dep_info.min_deps.end()); + min_deps_collector.insert(dep_info.min_deps.begin(), + dep_info.min_deps.end()); } } @@ -178,22 +182,25 @@ FileGenerator::CommonState::CollectMinimalFileDepsContainingExtensionsInternal( // Fast path: if nothing to prune or there was only one dep, the prune work is // a waste, skip it. if (to_prune.empty() || file->dependency_count() == 1) { - return deps_info_cache_.insert( - {file, {file_has_exts, min_deps_collector, covered_deps_collector}}).first->second; + return deps_info_cache_ + .insert( + {file, {file_has_exts, min_deps_collector, covered_deps_collector}}) + .first->second; } std::unordered_set min_deps; std::copy_if(min_deps_collector.begin(), min_deps_collector.end(), std::inserter(min_deps, min_deps.end()), - [&](const FileDescriptor* value){ - return to_prune.find(value) == to_prune.end(); - }); - return deps_info_cache_.insert( - {file, {file_has_exts, min_deps, covered_deps_collector}}).first->second; + [&](const FileDescriptor* value) { + return to_prune.find(value) == to_prune.end(); + }); + return deps_info_cache_ + .insert({file, {file_has_exts, min_deps, covered_deps_collector}}) + .first->second; } -// Collect the deps of the given file that contain extensions. This can be used to -// create the chain of roots that need to be wired together. +// Collect the deps of the given file that contain extensions. This can be used +// to create the chain of roots that need to be wired together. // // NOTE: If any changes are made to this and the supporting functions, you will // need to manually validate what the generated code is for the test files: @@ -205,7 +212,7 @@ const std::vector FileGenerator::CommonState::CollectMinimalFileDepsContainingExtensions( const FileDescriptor* file) { std::unordered_set min_deps = - CollectMinimalFileDepsContainingExtensionsInternal(file).min_deps; + CollectMinimalFileDepsContainingExtensionsInternal(file).min_deps; // Sort the list since pointer order isn't stable across runs. std::vector result(min_deps.begin(), min_deps.end()); std::sort(result.begin(), result.end(), FileDescriptorsOrderedByName()); @@ -275,7 +282,8 @@ void FileGenerator::GenerateHeader(io::Printer* printer) { // The bundled protos (WKTs) don't use of forward declarations. bool headers_use_forward_declarations = - generation_options_.headers_use_forward_declarations && !is_bundled_proto_; + generation_options_.headers_use_forward_declarations && + !is_bundled_proto_; { ImportWriter import_writer( @@ -409,11 +417,12 @@ void FileGenerator::GenerateSource(io::Printer* printer) { } std::vector deps_with_extensions = - common_state_.CollectMinimalFileDepsContainingExtensions(file_); + common_state_.CollectMinimalFileDepsContainingExtensions(file_); // The bundled protos (WKTs) don't use of forward declarations. bool headers_use_forward_declarations = - generation_options_.headers_use_forward_declarations && !is_bundled_proto_; + generation_options_.headers_use_forward_declarations && + !is_bundled_proto_; { ImportWriter import_writer( @@ -434,7 +443,7 @@ void FileGenerator::GenerateSource(io::Printer* printer) { public_import_names.insert(file_->public_dependency(i)->name()); } for (int i = 0; i < file_->dependency_count(); i++) { - const FileDescriptor *dep = file_->dependency(i); + const FileDescriptor* dep = file_->dependency(i); bool public_import = (public_import_names.count(dep->name()) != 0); if (!public_import) { import_writer.AddFile(dep, header_extension); @@ -499,8 +508,7 @@ void FileGenerator::GenerateSource(io::Printer* printer) { "#pragma clang diagnostic ignored \"-Wdollar-in-identifier-extension\"\n"); // clang-format on } - printer->Print( - "\n"); + printer->Print("\n"); if (!fwd_decls.empty()) { // clang-format off printer->Print( @@ -544,8 +552,7 @@ void FileGenerator::GenerateSource(io::Printer* printer) { printer->Indent(); if (file_contains_extensions) { - printer->Print( - "static GPBExtensionDescription descriptions[] = {\n"); + printer->Print("static GPBExtensionDescription descriptions[] = {\n"); printer->Indent(); for (const auto& generator : extension_generators_) { generator->GenerateStaticVariablesInitialization(printer); @@ -710,14 +717,13 @@ void FileGenerator::PrintFileRuntimePreamble( import_prefix += "/"; } for (const auto& header : headers_to_import) { - printer->Print( - "#import \"$import_prefix$$header$\"\n", - "import_prefix", import_prefix, - "header", header); + printer->Print("#import \"$import_prefix$$header$\"\n", "import_prefix", + import_prefix, "header", header); } } else { - ImportWriter::PrintRuntimeImports( - printer, headers_to_import, generation_options_.runtime_import_prefix, true); + ImportWriter::PrintRuntimeImports(printer, headers_to_import, + generation_options_.runtime_import_prefix, + true); } printer->Print("\n"); diff --git a/src/google/protobuf/compiler/objectivec/generator.cc b/src/google/protobuf/compiler/objectivec/generator.cc index 8267d2c827..1b963683ae 100644 --- a/src/google/protobuf/compiler/objectivec/generator.cc +++ b/src/google/protobuf/compiler/objectivec/generator.cc @@ -39,8 +39,8 @@ #include "absl/strings/str_split.h" #include "absl/strings/strip.h" #include "google/protobuf/compiler/objectivec/file.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream.h" @@ -75,9 +75,7 @@ ObjectiveCGenerator::ObjectiveCGenerator() {} ObjectiveCGenerator::~ObjectiveCGenerator() {} -bool ObjectiveCGenerator::HasGenerateAll() const { - return true; -} +bool ObjectiveCGenerator::HasGenerateAll() const { return true; } bool ObjectiveCGenerator::Generate(const FileDescriptor* file, const std::string& parameter, @@ -97,7 +95,8 @@ bool ObjectiveCGenerator::GenerateAll( // options along with their values. If the option appears multiple times, only // the last value will be considered. // - // e.g. protoc ... --objc_opt=expected_prefixes=file.txt,generate_for_named_framework=MyFramework + // e.g. protoc ... + // --objc_opt=expected_prefixes=file.txt,generate_for_named_framework=MyFramework Options validation_options; GenerationOptions generation_options; @@ -127,8 +126,8 @@ bool ObjectiveCGenerator::GenerateAll( // A semicolon delimited string that lists the paths of .proto files to // exclude from the package prefix validations (expected_prefixes_path). // This is provided as an "out", to skip some files being checked. - for (absl::string_view split_piece : absl::StrSplit( - options[i].second, ";", absl::SkipEmpty())) { + for (absl::string_view split_piece : + absl::StrSplit(options[i].second, ";", absl::SkipEmpty())) { validation_options.expected_prefixes_suppressions.push_back( std::string(split_piece)); } @@ -142,7 +141,8 @@ bool ObjectiveCGenerator::GenerateAll( // Default is "no". if (!StringToBool(options[i].second, &validation_options.prefixes_must_be_registered)) { - *error = "error: Unknown value for prefixes_must_be_registered: " + options[i].second; + *error = "error: Unknown value for prefixes_must_be_registered: " + + options[i].second; return false; } } else if (options[i].first == "require_prefixes") { @@ -154,7 +154,8 @@ bool ObjectiveCGenerator::GenerateAll( // Default is "no". if (!StringToBool(options[i].second, &validation_options.require_prefixes)) { - *error = "error: Unknown value for require_prefixes: " + options[i].second; + *error = + "error: Unknown value for require_prefixes: " + options[i].second; return false; } } else if (options[i].first == "generate_for_named_framework") { @@ -167,7 +168,8 @@ bool ObjectiveCGenerator::GenerateAll( // the "default" framework name used for everything that wasn't mapped by // the mapping file. generation_options.generate_for_named_framework = options[i].second; - } else if (options[i].first == "named_framework_to_proto_path_mappings_path") { + } else if (options[i].first == + "named_framework_to_proto_path_mappings_path") { // Path to find a file containing the list of framework names and proto // files. The generator uses this to decide if a proto file // referenced should use a framework style import vs. a user level import @@ -188,7 +190,8 @@ bool ObjectiveCGenerator::GenerateAll( // mappings file, it will use the default framework name if one was passed // with generate_for_named_framework, or the relative path to it's include // path otherwise. - generation_options.named_framework_to_proto_path_mappings_path = options[i].second; + generation_options.named_framework_to_proto_path_mappings_path = + options[i].second; } else if (options[i].first == "runtime_import_prefix") { // Path to use as a prefix on #imports of runtime provided headers in the // generated files. When integrating ObjC protos into a build system, @@ -198,8 +201,9 @@ bool ObjectiveCGenerator::GenerateAll( std::string(absl::StripSuffix(options[i].second, "/")); } else if (options[i].first == "package_to_prefix_mappings_path") { // Path to use for when loading the objc class prefix mappings to use. - // The `objc_class_prefix` file option is always honored first if one is present. - // This option also has precedent over the use_package_as_prefix option. + // The `objc_class_prefix` file option is always honored first if one is + // present. This option also has precedent over the use_package_as_prefix + // option. // // The format of the file is: // - An entry is a line of "package=prefix". @@ -243,7 +247,8 @@ bool ObjectiveCGenerator::GenerateAll( } else if (options[i].first == "headers_use_forward_declarations") { if (!StringToBool(options[i].second, &generation_options.headers_use_forward_declarations)) { - *error = "error: Unknown value for headers_use_forward_declarations: " + options[i].second; + *error = "error: Unknown value for headers_use_forward_declarations: " + + options[i].second; return false; } } else { diff --git a/src/google/protobuf/compiler/objectivec/helpers.cc b/src/google/protobuf/compiler/objectivec/helpers.cc index 3fbfcabfde..1de95f07db 100644 --- a/src/google/protobuf/compiler/objectivec/helpers.cc +++ b/src/google/protobuf/compiler/objectivec/helpers.cc @@ -28,16 +28,17 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include "google/protobuf/compiler/code_generator.h" -#include "google/protobuf/stubs/strutil.h" +#include "google/protobuf/compiler/objectivec/helpers.h" + #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" -#include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream_impl.h" +#include "google/protobuf/stubs/strutil.h" // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some // error cases, so it seems to be ok to use as a back door for errors. @@ -54,7 +55,7 @@ std::string EscapeTrigraphs(absl::string_view to_escape) { namespace { std::string GetZeroEnumNameForFlagType(const FlagType flag_type) { - switch(flag_type) { + switch (flag_type) { case FLAGTYPE_DESCRIPTOR_INITIALIZATION: return "GPBDescriptorInitializationFlag_None"; case FLAGTYPE_EXTENSION: @@ -68,7 +69,7 @@ std::string GetZeroEnumNameForFlagType(const FlagType flag_type) { } std::string GetEnumNameForFlagType(const FlagType flag_type) { - switch(flag_type) { + switch (flag_type) { case FLAGTYPE_DESCRIPTOR_INITIALIZATION: return "GPBDescriptorInitializationFlags"; case FLAGTYPE_EXTENSION: @@ -81,8 +82,7 @@ std::string GetEnumNameForFlagType(const FlagType flag_type) { } } -std::string HandleExtremeFloatingPoint(std::string val, - bool add_float_suffix) { +std::string HandleExtremeFloatingPoint(std::string val, bool add_float_suffix) { if (val == "nan") { return "NAN"; } else if (val == "inf") { @@ -201,7 +201,7 @@ std::string GPBGenericValueFieldName(const FieldDescriptor* field) { // Returns the field within the GPBGenericValue union to use for the given // field. if (field->is_repeated()) { - return "valueMessage"; + return "valueMessage"; } switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: @@ -236,7 +236,6 @@ std::string GPBGenericValueFieldName(const FieldDescriptor* field) { return std::string(); } - std::string DefaultValue(const FieldDescriptor* field) { // Repeated fields don't have defaults. if (field->is_repeated()) { @@ -335,10 +334,10 @@ std::string ObjCClassDeclaration(const std::string& class_name) { } std::string BuildCommentsString(const SourceLocation& location, - bool prefer_single_line) { + bool prefer_single_line) { const std::string& comments = location.leading_comments.empty() - ? location.trailing_comments - : location.leading_comments; + ? location.trailing_comments + : location.leading_comments; std::vector lines; lines = absl::StrSplit(comments, "\n", absl::AllowEmpty()); while (!lines.empty() && lines.back().empty()) { @@ -387,7 +386,6 @@ std::string BuildCommentsString(const SourceLocation& location, return final_comments; } - } // namespace objectivec } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/objectivec/import_writer.cc b/src/google/protobuf/compiler/objectivec/import_writer.cc index f36ef781ec..a0291b05a9 100644 --- a/src/google/protobuf/compiler/objectivec/import_writer.cc +++ b/src/google/protobuf/compiler/objectivec/import_writer.cc @@ -29,10 +29,11 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "google/protobuf/compiler/objectivec/import_writer.h" + +#include "absl/strings/ascii.h" #include "google/protobuf/compiler/objectivec/line_consumer.h" #include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" -#include "absl/strings/ascii.h" // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some // error cases, so it seems to be ok to use as a back door for errors. @@ -46,17 +47,19 @@ namespace { class ProtoFrameworkCollector : public LineConsumer { public: - ProtoFrameworkCollector(std::map* inout_proto_file_to_framework_name) + ProtoFrameworkCollector( + std::map* inout_proto_file_to_framework_name) : map_(inout_proto_file_to_framework_name) {} - virtual bool ConsumeLine(const absl::string_view& line, std::string* out_error) override; + virtual bool ConsumeLine(const absl::string_view& line, + std::string* out_error) override; private: std::map* map_; }; -bool ProtoFrameworkCollector::ConsumeLine( - const absl::string_view& line, std::string* out_error) { +bool ProtoFrameworkCollector::ConsumeLine(const absl::string_view& line, + std::string* out_error) { int offset = line.find(':'); if (offset == absl::string_view::npos) { *out_error = @@ -64,8 +67,10 @@ bool ProtoFrameworkCollector::ConsumeLine( std::string(line) + "'."; return false; } - absl::string_view framework_name = absl::StripAsciiWhitespace(line.substr(0, offset)); - absl::string_view proto_file_list = absl::StripAsciiWhitespace(line.substr(offset + 1)); + absl::string_view framework_name = + absl::StripAsciiWhitespace(line.substr(0, offset)); + absl::string_view proto_file_list = + absl::StripAsciiWhitespace(line.substr(offset + 1)); int start = 0; while (start < proto_file_list.length()) { @@ -74,16 +79,17 @@ bool ProtoFrameworkCollector::ConsumeLine( offset = proto_file_list.length(); } - absl::string_view proto_file = - absl::StripAsciiWhitespace(proto_file_list.substr(start, offset - start)); + absl::string_view proto_file = absl::StripAsciiWhitespace( + proto_file_list.substr(start, offset - start)); if (!proto_file.empty()) { std::map::iterator existing_entry = map_->find(std::string(proto_file)); if (existing_entry != map_->end()) { std::cerr << "warning: duplicate proto file reference, replacing " "framework entry for '" - << std::string(proto_file) << "' with '" << std::string(framework_name) - << "' (was '" << existing_entry->second << "')." << std::endl; + << std::string(proto_file) << "' with '" + << std::string(framework_name) << "' (was '" + << existing_entry->second << "')." << std::endl; std::cerr.flush(); } @@ -141,15 +147,14 @@ void ImportWriter::AddFile(const FileDescriptor* file, proto_file_to_framework_name_.find(file->name()); if (proto_lookup != proto_file_to_framework_name_.end()) { other_framework_imports_.push_back( - proto_lookup->second + "/" + - FilePathBasename(file) + header_extension); + proto_lookup->second + "/" + FilePathBasename(file) + header_extension); return; } if (!generate_for_named_framework_.empty()) { - other_framework_imports_.push_back( - generate_for_named_framework_ + "/" + - FilePathBasename(file) + header_extension); + other_framework_imports_.push_back(generate_for_named_framework_ + "/" + + FilePathBasename(file) + + header_extension); return; } @@ -172,9 +177,7 @@ void ImportWriter::Print(io::Printer* printer) const { for (std::vector::const_iterator iter = other_framework_imports_.begin(); iter != other_framework_imports_.end(); ++iter) { - printer->Print( - "#import <$header$>\n", - "header", *iter); + printer->Print("#import <$header$>\n", "header", *iter); } add_blank_line = true; @@ -187,9 +190,7 @@ void ImportWriter::Print(io::Printer* printer) const { for (std::vector::const_iterator iter = other_imports_.begin(); iter != other_imports_.end(); ++iter) { - printer->Print( - "#import \"$header$\"\n", - "header", *iter); + printer->Print("#import \"$header$\"\n", "header", *iter); } } } @@ -200,10 +201,8 @@ void ImportWriter::PrintRuntimeImports( // Given an override, use that. if (!runtime_import_prefix.empty()) { for (const auto& header : header_to_import) { - printer->Print( - " #import \"$import_prefix$/$header$\"\n", - "import_prefix", runtime_import_prefix, - "header", header); + printer->Print(" #import \"$import_prefix$/$header$\"\n", "import_prefix", + runtime_import_prefix, "header", header); } return; } @@ -224,24 +223,16 @@ void ImportWriter::PrintRuntimeImports( "cpp_symbol", cpp_symbol); } - printer->Print( - "#if $cpp_symbol$\n", - "cpp_symbol", cpp_symbol); + printer->Print("#if $cpp_symbol$\n", "cpp_symbol", cpp_symbol); for (const auto& header : header_to_import) { - printer->Print( - " #import <$framework_name$/$header$>\n", - "framework_name", framework_name, - "header", header); + printer->Print(" #import <$framework_name$/$header$>\n", "framework_name", + framework_name, "header", header); } - printer->Print( - "#else\n"); + printer->Print("#else\n"); for (const auto& header : header_to_import) { - printer->Print( - " #import \"$header$\"\n", - "header", header); + printer->Print(" #import \"$header$\"\n", "header", header); } - printer->Print( - "#endif\n"); + printer->Print("#endif\n"); } void ImportWriter::ParseFrameworkMappings() { @@ -252,10 +243,11 @@ void ImportWriter::ParseFrameworkMappings() { ProtoFrameworkCollector collector(&proto_file_to_framework_name_); std::string parse_error; - if (!ParseSimpleFile(named_framework_to_proto_path_mappings_path_, - &collector, &parse_error)) { - std::cerr << "error parsing " << named_framework_to_proto_path_mappings_path_ - << " : " << parse_error << std::endl; + if (!ParseSimpleFile(named_framework_to_proto_path_mappings_path_, &collector, + &parse_error)) { + std::cerr << "error parsing " + << named_framework_to_proto_path_mappings_path_ << " : " + << parse_error << std::endl; std::cerr.flush(); } } diff --git a/src/google/protobuf/compiler/objectivec/line_consumer.cc b/src/google/protobuf/compiler/objectivec/line_consumer.cc index 2026c2826d..b668875a42 100644 --- a/src/google/protobuf/compiler/objectivec/line_consumer.cc +++ b/src/google/protobuf/compiler/objectivec/line_consumer.cc @@ -61,16 +61,14 @@ namespace objectivec { namespace posix { #ifdef _WIN32 using google::protobuf::io::win32::open; -#else // !_WIN32 +#else // !_WIN32 using ::open; #endif // _WIN32 } // namespace posix namespace { -bool ascii_isnewline(char c) { - return c == '\n' || c == '\r'; -} +bool ascii_isnewline(char c) { return c == '\n' || c == '\r'; } bool ReadLine(absl::string_view* input, absl::string_view* line) { for (int len = 0; len < input->size(); ++len) { @@ -149,7 +147,8 @@ bool Parser::Finish(std::string* out_error) { if (!leftover_.empty() && !ParseChunk("\n", out_error)) { return false; } - // This really should never fail if ParseChunk succeeded, but check to be sure. + // This really should never fail if ParseChunk succeeded, but check to be + // sure. if (!leftover_.empty()) { *out_error = "ParseSimple Internal error: finished with pending data."; return false; @@ -157,8 +156,10 @@ bool Parser::Finish(std::string* out_error) { return true; } -std::string FullErrorString(const std::string& name, int line_num, const std::string& msg) { - return std::string("error: ") + name + " Line " + absl::StrCat(line_num) + ", " + msg; +std::string FullErrorString(const std::string& name, int line_num, + const std::string& msg) { + return std::string("error: ") + name + " Line " + absl::StrCat(line_num) + + ", " + msg; } } // namespace @@ -186,8 +187,7 @@ bool ParseSimpleFile(const std::string& path, LineConsumer* line_consumer, bool ParseSimpleStream(io::ZeroCopyInputStream& input_stream, const std::string& stream_name, - LineConsumer* line_consumer, - std::string* out_error) { + LineConsumer* line_consumer, std::string* out_error) { std::string local_error; Parser parser(line_consumer); const void* buf; @@ -197,9 +197,11 @@ bool ParseSimpleStream(io::ZeroCopyInputStream& input_stream, continue; } - if (!parser.ParseChunk(absl::string_view(static_cast(buf), buf_len), - &local_error)) { - *out_error = FullErrorString(stream_name, parser.last_line(), local_error); + if (!parser.ParseChunk( + absl::string_view(static_cast(buf), buf_len), + &local_error)) { + *out_error = + FullErrorString(stream_name, parser.last_line(), local_error); return false; } } diff --git a/src/google/protobuf/compiler/objectivec/line_consumer_unittest.cc b/src/google/protobuf/compiler/objectivec/line_consumer_unittest.cc index 2513b6f4fe..ff8ff87d2d 100644 --- a/src/google/protobuf/compiler/objectivec/line_consumer_unittest.cc +++ b/src/google/protobuf/compiler/objectivec/line_consumer_unittest.cc @@ -29,11 +29,12 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "google/protobuf/compiler/objectivec/line_consumer.h" -#include "google/protobuf/io/zero_copy_stream_impl_lite.h" -#include "absl/strings/str_cat.h" #include +#include "absl/strings/str_cat.h" +#include "google/protobuf/io/zero_copy_stream_impl_lite.h" + namespace google { namespace protobuf { namespace compiler { @@ -43,11 +44,12 @@ namespace { class TestLineCollector : public LineConsumer { public: explicit TestLineCollector(std::vector* inout_lines, - const std::string* reject_line = nullptr, - bool skip_msg = false) - : lines_(inout_lines), reject_(reject_line), skip_msg_(skip_msg) {} + const std::string* reject_line = nullptr, + bool skip_msg = false) + : lines_(inout_lines), reject_(reject_line), skip_msg_(skip_msg) {} - bool ConsumeLine(const absl::string_view& line, std::string* out_error) override { + bool ConsumeLine(const absl::string_view& line, + std::string* out_error) override { if (reject_ && *reject_ == line) { if (!skip_msg_) { *out_error = std::string("Rejected '") + *reject_ + "'"; @@ -71,19 +73,20 @@ const int kBlockSizeCount = ABSL_ARRAYSIZE(kBlockSizes); TEST(ObjCHelper, ParseSimple_BasicsSuccess) { const std::vector>> tests = { - {"", {}}, - {"a", {"a"}}, - {"a c", {"a c"}}, - {" a c ", {"a c"}}, - {"\ta c ", {"a c"}}, - {"abc\n", {"abc"}}, - {"abc\nd f", {"abc", "d f"}}, - {"\n abc \n def \n\n", {"abc", "def"}}, + {"", {}}, + {"a", {"a"}}, + {"a c", {"a c"}}, + {" a c ", {"a c"}}, + {"\ta c ", {"a c"}}, + {"abc\n", {"abc"}}, + {"abc\nd f", {"abc", "d f"}}, + {"\n abc \n def \n\n", {"abc", "def"}}, }; for (const auto& test : tests) { for (int i = 0; i < kBlockSizeCount; i++) { - io::ArrayInputStream input(test.first.data(), test.first.size(), kBlockSizes[i]); + io::ArrayInputStream input(test.first.data(), test.first.size(), + kBlockSizes[i]); std::string err_str; std::vector lines; TestLineCollector collector(&lines); @@ -96,22 +99,23 @@ TEST(ObjCHelper, ParseSimple_BasicsSuccess) { TEST(ObjCHelper, ParseSimple_DropsComments) { const std::vector>> tests = { - {"# nothing", {}}, - {"#", {}}, - {"##", {}}, - {"\n# nothing\n", {}}, - {"a # same line", {"a"}}, - {"a # same line\n", {"a"}}, - {"a\n# line\nc", {"a", "c"}}, - {"# n o t # h i n g #", {}}, - {"## n o # t h i n g #", {}}, - {"a# n o t # h i n g #", {"a"}}, - {"a\n## n o # t h i n g #", {"a"}}, + {"# nothing", {}}, + {"#", {}}, + {"##", {}}, + {"\n# nothing\n", {}}, + {"a # same line", {"a"}}, + {"a # same line\n", {"a"}}, + {"a\n# line\nc", {"a", "c"}}, + {"# n o t # h i n g #", {}}, + {"## n o # t h i n g #", {}}, + {"a# n o t # h i n g #", {"a"}}, + {"a\n## n o # t h i n g #", {"a"}}, }; for (const auto& test : tests) { for (int i = 0; i < kBlockSizeCount; i++) { - io::ArrayInputStream input(test.first.data(), test.first.size(), kBlockSizes[i]); + io::ArrayInputStream input(test.first.data(), test.first.size(), + kBlockSizes[i]); std::string err_str; std::vector lines; TestLineCollector collector(&lines); @@ -124,21 +128,22 @@ TEST(ObjCHelper, ParseSimple_DropsComments) { TEST(ObjCHelper, ParseSimple_RejectLines) { const std::vector> tests = { - std::make_tuple("a\nb\nc", "a", 1), - std::make_tuple("a\nb\nc", "b", 2), - std::make_tuple("a\nb\nc", "c", 3), - std::make_tuple("a\nb\nc\n", "c", 3), + std::make_tuple("a\nb\nc", "a", 1), + std::make_tuple("a\nb\nc", "b", 2), + std::make_tuple("a\nb\nc", "c", 3), + std::make_tuple("a\nb\nc\n", "c", 3), }; for (const auto& test : tests) { for (int i = 0; i < kBlockSizeCount; i++) { - io::ArrayInputStream input(std::get<0>(test).data(), std::get<0>(test).size(), - kBlockSizes[i]); + io::ArrayInputStream input(std::get<0>(test).data(), + std::get<0>(test).size(), kBlockSizes[i]); std::string err_str; TestLineCollector collector(nullptr, &std::get<1>(test)); EXPECT_FALSE(ParseSimpleStream(input, "dummy", &collector, &err_str)); std::string expected_err = - absl::StrCat("error: dummy Line ", std::get<2>(test), ", Rejected '", std::get<1>(test), "'"); + absl::StrCat("error: dummy Line ", std::get<2>(test), ", Rejected '", + std::get<1>(test), "'"); EXPECT_EQ(err_str, expected_err); } } @@ -146,22 +151,23 @@ TEST(ObjCHelper, ParseSimple_RejectLines) { TEST(ObjCHelper, ParseSimple_RejectLinesNoMessage) { const std::vector> tests = { - std::make_tuple("a\nb\nc", "a", 1), - std::make_tuple("a\nb\nc", "b", 2), - std::make_tuple("a\nb\nc", "c", 3), - std::make_tuple("a\nb\nc\n", "c", 3), + std::make_tuple("a\nb\nc", "a", 1), + std::make_tuple("a\nb\nc", "b", 2), + std::make_tuple("a\nb\nc", "c", 3), + std::make_tuple("a\nb\nc\n", "c", 3), }; for (const auto& test : tests) { for (int i = 0; i < kBlockSizeCount; i++) { - io::ArrayInputStream input(std::get<0>(test).data(), std::get<0>(test).size(), - kBlockSizes[i]); + io::ArrayInputStream input(std::get<0>(test).data(), + std::get<0>(test).size(), kBlockSizes[i]); std::string err_str; - TestLineCollector collector(nullptr, &std::get<1>(test), true /* skip msg */); + TestLineCollector collector(nullptr, &std::get<1>(test), + true /* skip msg */); EXPECT_FALSE(ParseSimpleStream(input, "dummy", &collector, &err_str)); std::string expected_err = - absl::StrCat("error: dummy Line ", std::get<2>(test), - ", ConsumeLine failed without setting an error."); + absl::StrCat("error: dummy Line ", std::get<2>(test), + ", ConsumeLine failed without setting an error."); EXPECT_EQ(err_str, expected_err); } } diff --git a/src/google/protobuf/compiler/objectivec/map_field.cc b/src/google/protobuf/compiler/objectivec/map_field.cc index e11794a77e..0c6acb3929 100644 --- a/src/google/protobuf/compiler/objectivec/map_field.cc +++ b/src/google/protobuf/compiler/objectivec/map_field.cc @@ -28,12 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#include "google/protobuf/compiler/objectivec/map_field.h" + #include #include -#include "google/protobuf/compiler/objectivec/map_field.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" namespace google { @@ -84,8 +85,7 @@ const char* MapEntryTypeName(const FieldDescriptor* descriptor, bool isKey) { MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor) : RepeatedFieldGenerator(descriptor) { - const FieldDescriptor* key_descriptor = - descriptor->message_type()->map_key(); + const FieldDescriptor* key_descriptor = descriptor->message_type()->map_key(); const FieldDescriptor* value_descriptor = descriptor->message_type()->map_value(); value_field_generator_.reset(FieldGenerator::Make(value_descriptor)); @@ -135,8 +135,8 @@ MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor) variables_["array_storage_type"] = class_name; if (value_is_object_type) { variables_["array_property_type"] = - class_name + "<" + - value_field_generator_->variable("storage_type") + "*>"; + class_name + "<" + value_field_generator_->variable("storage_type") + + "*>"; } } @@ -156,15 +156,15 @@ void MapFieldGenerator::FinishInitialization(void) { descriptor_->message_type()->map_value(); if (GetObjectiveCType(value_descriptor) == OBJECTIVECTYPE_ENUM) { variables_["array_comment"] = - "// |" + variables_["name"] + "| values are |" + value_field_generator_->variable("storage_type") + "|\n"; + "// |" + variables_["name"] + "| values are |" + + value_field_generator_->variable("storage_type") + "|\n"; } } void MapFieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls, - bool include_external_types) const { - RepeatedFieldGenerator::DetermineForwardDeclarations( - fwd_decls, include_external_types); + std::set* fwd_decls, bool include_external_types) const { + RepeatedFieldGenerator::DetermineForwardDeclarations(fwd_decls, + include_external_types); const FieldDescriptor* value_descriptor = descriptor_->message_type()->map_value(); // Within a file there is no requirement on the order of the messages, so @@ -186,8 +186,8 @@ void MapFieldGenerator::DetermineObjectiveCClassDefinitions( const FieldDescriptor* value_descriptor = descriptor_->message_type()->map_value(); if (GetObjectiveCType(value_descriptor) == OBJECTIVECTYPE_MESSAGE) { - fwd_decls->insert(ObjCClassDeclaration( - value_field_generator_->variable("storage_type"))); + fwd_decls->insert( + ObjCClassDeclaration(value_field_generator_->variable("storage_type"))); } } diff --git a/src/google/protobuf/compiler/objectivec/message.cc b/src/google/protobuf/compiler/objectivec/message.cc index 05bc5b3199..a68aa60a28 100644 --- a/src/google/protobuf/compiler/objectivec/message.cc +++ b/src/google/protobuf/compiler/objectivec/message.cc @@ -38,8 +38,8 @@ #include "absl/strings/str_cat.h" #include "google/protobuf/compiler/objectivec/enum.h" #include "google/protobuf/compiler/objectivec/extension.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/text_format_decode_data.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/printer.h" @@ -152,11 +152,12 @@ struct ExtensionRangeOrdering { // and return it. const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { const FieldDescriptor** fields = - new const FieldDescriptor* [descriptor->field_count()]; + new const FieldDescriptor*[descriptor->field_count()]; for (int i = 0; i < descriptor->field_count(); i++) { fields[i] = descriptor->field(i); } - std::sort(fields, fields + descriptor->field_count(), FieldOrderingByNumber()); + std::sort(fields, fields + descriptor->field_count(), + FieldOrderingByNumber()); return fields; } @@ -164,12 +165,12 @@ const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { // array and return it. const FieldDescriptor** SortFieldsByStorageSize(const Descriptor* descriptor) { const FieldDescriptor** fields = - new const FieldDescriptor* [descriptor->field_count()]; + new const FieldDescriptor*[descriptor->field_count()]; for (int i = 0; i < descriptor->field_count(); i++) { fields[i] = descriptor->field(i); } std::sort(fields, fields + descriptor->field_count(), - FieldOrderingByStorageSize()); + FieldOrderingByStorageSize()); return fields; } @@ -200,8 +201,7 @@ MessageGenerator::MessageGenerator(const std::string& root_classname, for (int i = 0; i < descriptor_->nested_type_count(); i++) { MessageGenerator* generator = - new MessageGenerator(root_classname_, - descriptor_->nested_type(i)); + new MessageGenerator(root_classname_, descriptor_->nested_type(i)); nested_message_generators_.emplace_back(generator); } } @@ -220,8 +220,7 @@ void MessageGenerator::GenerateStaticVariablesInitialization( } void MessageGenerator::DetermineForwardDeclarations( - std::set* fwd_decls, - bool include_external_types) { + std::set* fwd_decls, bool include_external_types) { if (!IsMapEntryMessage(descriptor_)) { for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* fieldDescriptor = descriptor_->field(i); @@ -315,8 +314,8 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { std::unique_ptr sorted_fields( SortFieldsByNumber(descriptor_)); - printer->Print("typedef GPB_ENUM($classname$_FieldNumber) {\n", - "classname", class_name_); + printer->Print("typedef GPB_ENUM($classname$_FieldNumber) {\n", "classname", + class_name_); printer->Indent(); for (int i = 0; i < descriptor_->field_count(); i++) { @@ -344,8 +343,7 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { // clang-format off "$comments$$deprecated_attribute$GPB_FINAL @interface $classname$ : GPBMessage\n\n", // clang-format on - "classname", class_name_, - "deprecated_attribute", deprecated_attribute_, + "classname", class_name_, "deprecated_attribute", deprecated_attribute_, "comments", message_comments); std::vector seen_oneofs(oneof_generators_.size(), 0); @@ -378,8 +376,8 @@ void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { } if (descriptor_->extension_count() > 0) { - printer->Print("@interface $classname$ (DynamicMethods)\n\n", - "classname", class_name_); + printer->Print("@interface $classname$ (DynamicMethods)\n\n", "classname", + class_name_); for (const auto& generator : extension_generators_) { generator->GenerateMembersHeader(printer); } @@ -410,8 +408,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { // clang-format on } - printer->Print("@implementation $classname$\n\n", - "classname", class_name_); + printer->Print("@implementation $classname$\n\n", "classname", class_name_); for (const auto& generator : oneof_generators_) { generator->GeneratePropertyImplementation(printer); @@ -434,7 +431,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { } std::sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); + ExtensionRangeOrdering()); // Assign has bits: // 1. FieldGeneratorMap::CalculateHasBits() loops through the fields seeing @@ -465,8 +462,8 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { "typedef struct $classname$__storage_ {\n" " uint32_t _has_storage_[$sizeof_has_storage$];\n", // clang-format on - "classname", class_name_, - "sizeof_has_storage", absl::StrCat(sizeof_has_storage)); + "classname", class_name_, "sizeof_has_storage", + absl::StrCat(sizeof_has_storage)); printer->Indent(); for (int i = 0; i < descriptor_->field_count(); i++) { @@ -477,7 +474,6 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { printer->Print("} $classname$__storage_;\n\n", "classname", class_name_); - // clang-format off printer->Print( "// This method is threadsafe because it is initially called\n" @@ -499,23 +495,21 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { if (has_fields) { printer->Indent(); printer->Indent(); - printer->Print( - "static $field_description_type$ fields[] = {\n", - "field_description_type", field_description_type); + printer->Print("static $field_description_type$ fields[] = {\n", + "field_description_type", field_description_type); printer->Indent(); for (int i = 0; i < descriptor_->field_count(); ++i) { const FieldGenerator& field_generator = field_generators_.get(sorted_fields[i]); field_generator.GenerateFieldDescription(printer, need_defaults); if (field_generator.needs_textformat_name_support()) { - text_format_decode_data.AddString(sorted_fields[i]->number(), - field_generator.generated_objc_name(), - field_generator.raw_field_name()); + text_format_decode_data.AddString( + sorted_fields[i]->number(), field_generator.generated_objc_name(), + field_generator.raw_field_name()); } } printer->Outdent(); - printer->Print( - "};\n"); + printer->Print("};\n"); printer->Outdent(); printer->Outdent(); } @@ -540,8 +534,8 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { if (descriptor_->options().message_set_wire_format()) { init_flags.push_back("GPBDescriptorInitializationFlag_WireFormat"); } - vars["init_flags"] = BuildFlagsString(FLAGTYPE_DESCRIPTOR_INITIALIZATION, - init_flags); + vars["init_flags"] = + BuildFlagsString(FLAGTYPE_DESCRIPTOR_INITIALIZATION, init_flags); // clang-format off printer->Print( @@ -556,8 +550,7 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { " flags:$init_flags$];\n"); // clang-format on if (!oneof_generators_.empty()) { - printer->Print( - " static const char *oneofs[] = {\n"); + printer->Print(" static const char *oneofs[] = {\n"); for (const auto& generator : oneof_generators_) { printer->Print(" \"$name$\",\n", "name", generator->DescriptorName()); @@ -580,10 +573,9 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { // clang-format on static const int kBytesPerLine = 40; // allow for escaping for (int i = 0; i < text_format_data_str.size(); i += kBytesPerLine) { - printer->Print( - "\n \"$data$\"", - "data", EscapeTrigraphs( - absl::CEscape(text_format_data_str.substr(i, kBytesPerLine)))); + printer->Print("\n \"$data$\"", "data", + EscapeTrigraphs(absl::CEscape( + text_format_data_str.substr(i, kBytesPerLine)))); } // clang-format off printer->Print( @@ -593,12 +585,11 @@ void MessageGenerator::GenerateSource(io::Printer* printer) { // clang-format on } if (!sorted_extensions.empty()) { - printer->Print( - " static const GPBExtensionRange ranges[] = {\n"); + printer->Print(" static const GPBExtensionRange ranges[] = {\n"); for (int i = 0; i < sorted_extensions.size(); i++) { - printer->Print(" { .start = $start$, .end = $end$ },\n", - "start", absl::StrCat(sorted_extensions[i]->start), - "end", absl::StrCat(sorted_extensions[i]->end)); + printer->Print(" { .start = $start$, .end = $end$ },\n", "start", + absl::StrCat(sorted_extensions[i]->start), "end", + absl::StrCat(sorted_extensions[i]->end)); } // clang-format off printer->Print( diff --git a/src/google/protobuf/compiler/objectivec/message_field.cc b/src/google/protobuf/compiler/objectivec/message_field.cc index b9dd6c02fb..62e6281547 100644 --- a/src/google/protobuf/compiler/objectivec/message_field.cc +++ b/src/google/protobuf/compiler/objectivec/message_field.cc @@ -28,12 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#include "google/protobuf/compiler/objectivec/message_field.h" + #include #include -#include "google/protobuf/compiler/objectivec/message_field.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" namespace google { @@ -66,15 +67,14 @@ MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor) MessageFieldGenerator::~MessageFieldGenerator() {} void MessageFieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls, - bool include_external_types) const { - ObjCObjFieldGenerator::DetermineForwardDeclarations( - fwd_decls, include_external_types); + std::set* fwd_decls, bool include_external_types) const { + ObjCObjFieldGenerator::DetermineForwardDeclarations(fwd_decls, + include_external_types); // Within a file there is no requirement on the order of the messages, so // local references need a forward declaration. External files (not WKTs), // need one when requested. - if ((include_external_types && - !IsProtobufLibraryBundledProtoFile(descriptor_->message_type()->file())) || + if ((include_external_types && !IsProtobufLibraryBundledProtoFile( + descriptor_->message_type()->file())) || descriptor_->file() == descriptor_->message_type()->file()) { // Class name is already in "storage_type". fwd_decls->insert("@class " + variable("storage_type")); @@ -98,15 +98,14 @@ RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {} void RepeatedMessageFieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls, - bool include_external_types) const { - RepeatedFieldGenerator::DetermineForwardDeclarations( - fwd_decls, include_external_types); + std::set* fwd_decls, bool include_external_types) const { + RepeatedFieldGenerator::DetermineForwardDeclarations(fwd_decls, + include_external_types); // Within a file there is no requirement on the order of the messages, so // local references need a forward declaration. External files (not WKTs), // need one when requested. - if ((include_external_types && - !IsProtobufLibraryBundledProtoFile(descriptor_->message_type()->file())) || + if ((include_external_types && !IsProtobufLibraryBundledProtoFile( + descriptor_->message_type()->file())) || descriptor_->file() == descriptor_->message_type()->file()) { // Class name is already in "storage_type". fwd_decls->insert("@class " + variable("storage_type")); diff --git a/src/google/protobuf/compiler/objectivec/names.cc b/src/google/protobuf/compiler/objectivec/names.cc index 84fb4dd17d..e9cd9a338f 100644 --- a/src/google/protobuf/compiler/objectivec/names.cc +++ b/src/google/protobuf/compiler/objectivec/names.cc @@ -28,6 +28,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#include "google/protobuf/compiler/objectivec/names.h" + #include #include #include @@ -35,11 +37,10 @@ #include #include -#include "google/protobuf/compiler/code_generator.h" #include "absl/strings/ascii.h" #include "absl/strings/str_split.h" +#include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/compiler/objectivec/line_consumer.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/nsobject_methods.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/zero_copy_stream_impl.h" @@ -67,7 +68,8 @@ class SimpleLineCollector : public LineConsumer { explicit SimpleLineCollector(std::unordered_set* inout_set) : set_(inout_set) {} - virtual bool ConsumeLine(const absl::string_view& line, std::string* out_error) override { + virtual bool ConsumeLine(const absl::string_view& line, + std::string* out_error) override { set_->insert(std::string(line)); return true; } @@ -78,11 +80,13 @@ class SimpleLineCollector : public LineConsumer { class PackageToPrefixesCollector : public LineConsumer { public: - PackageToPrefixesCollector(const std::string &usage, - std::map* inout_package_to_prefix_map) + PackageToPrefixesCollector( + const std::string& usage, + std::map* inout_package_to_prefix_map) : usage_(usage), prefix_map_(inout_package_to_prefix_map) {} - virtual bool ConsumeLine(const absl::string_view& line, std::string* out_error) override; + virtual bool ConsumeLine(const absl::string_view& line, + std::string* out_error) override; private: const std::string usage_; @@ -93,7 +97,9 @@ class PrefixModeStorage { public: PrefixModeStorage(); - std::string package_to_prefix_mappings_path() const { return package_to_prefix_mappings_path_; } + std::string package_to_prefix_mappings_path() const { + return package_to_prefix_mappings_path_; + } void set_package_to_prefix_mappings_path(const std::string& path) { package_to_prefix_mappings_path_ = path; package_to_prefix_map_.clear(); @@ -115,7 +121,9 @@ class PrefixModeStorage { // When using a proto package as the prefix, this should be added as the // prefix in front of it. const std::string& forced_package_prefix() const { return forced_prefix_; } - void set_forced_package_prefix(const std::string& prefix) { forced_prefix_ = prefix; } + void set_forced_package_prefix(const std::string& prefix) { + forced_prefix_ = prefix; + } private: bool use_package_name_; @@ -132,7 +140,8 @@ PrefixModeStorage::PrefixModeStorage() { use_package_name_ = BoolFromEnvVar("GPB_OBJC_USE_PACKAGE_AS_PREFIX", false); - const char* exception_path = getenv("GPB_OBJC_PACKAGE_PREFIX_EXCEPTIONS_PATH"); + const char* exception_path = + getenv("GPB_OBJC_PACKAGE_PREFIX_EXCEPTIONS_PATH"); if (exception_path) { exception_path_ = exception_path; } @@ -143,21 +152,25 @@ PrefixModeStorage::PrefixModeStorage() { } } -std::string PrefixModeStorage::prefix_from_proto_package_mappings(const FileDescriptor* file) { +std::string PrefixModeStorage::prefix_from_proto_package_mappings( + const FileDescriptor* file) { if (!file) { return ""; } - if (package_to_prefix_map_.empty() && !package_to_prefix_mappings_path_.empty()) { + if (package_to_prefix_map_.empty() && + !package_to_prefix_mappings_path_.empty()) { std::string error_str; - // Re use the same collector as we use for expected_prefixes_path since the file - // format is the same. - PackageToPrefixesCollector collector("Package to prefixes", &package_to_prefix_map_); - if (!ParseSimpleFile(package_to_prefix_mappings_path_, &collector, &error_str)) { + // Re use the same collector as we use for expected_prefixes_path since the + // file format is the same. + PackageToPrefixesCollector collector("Package to prefixes", + &package_to_prefix_map_); + if (!ParseSimpleFile(package_to_prefix_mappings_path_, &collector, + &error_str)) { if (error_str.empty()) { - error_str = std::string("protoc:0: warning: Failed to parse") - + std::string(" prefix to proto package mappings file: ") - + package_to_prefix_mappings_path_; + error_str = std::string("protoc:0: warning: Failed to parse") + + std::string(" prefix to proto package mappings file: ") + + package_to_prefix_mappings_path_; } std::cerr << error_str << std::endl; std::cerr.flush(); @@ -169,7 +182,8 @@ std::string PrefixModeStorage::prefix_from_proto_package_mappings(const FileDesc // For files without packages, the can be registered as "no_package:PATH", // allowing the expected prefixes file. static const std::string no_package_prefix("no_package:"); - const std::string lookup_key = package.empty() ? no_package_prefix + file->name() : package; + const std::string lookup_key = + package.empty() ? no_package_prefix + file->name() : package; std::map::const_iterator prefix_lookup = package_to_prefix_map_.find(lookup_key); @@ -187,9 +201,9 @@ bool PrefixModeStorage::is_package_exempted(const std::string& package) { SimpleLineCollector collector(&exceptions_); if (!ParseSimpleFile(exception_path_, &collector, &error_str)) { if (error_str.empty()) { - error_str = std::string("protoc:0: warning: Failed to parse") - + std::string(" package prefix exceptions file: ") - + exception_path_; + error_str = std::string("protoc:0: warning: Failed to parse") + + std::string(" package prefix exceptions file: ") + + exception_path_; } std::cerr << error_str << std::endl; std::cerr.flush(); @@ -320,8 +334,7 @@ std::string UnderscoresToCamelCase(const std::string& input, } result += value; } - if ((result.length() != 0) && - !first_capitalized && + if ((result.length() != 0) && !first_capitalized && !first_segment_forces_upper) { result[0] = absl::ascii_tolower(result[0]); } @@ -329,72 +342,193 @@ std::string UnderscoresToCamelCase(const std::string& input, } const char* const kReservedWordList[] = { - // Note NSObject Methods: - // These are brought in from nsobject_methods.h that is generated - // using method_dump.sh. See kNSObjectMethods below. - - // Objective C "keywords" that aren't in C - // From - // http://stackoverflow.com/questions/1873630/reserved-keywords-in-objective-c - // with some others added on. - "id", "_cmd", "super", "in", "out", "inout", "bycopy", "byref", "oneway", - "self", "instancetype", "nullable", "nonnull", "nil", "Nil", - "YES", "NO", "weak", - - // C/C++ keywords (Incl C++ 0x11) - // From http://en.cppreference.com/w/cpp/keywords - "and", "and_eq", "alignas", "alignof", "asm", "auto", "bitand", "bitor", - "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", - "compl", "const", "constexpr", "const_cast", "continue", "decltype", - "default", "delete", "double", "dynamic_cast", "else", "enum", "explicit", - "export", "extern ", "false", "float", "for", "friend", "goto", "if", - "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not", - "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", - "public", "register", "reinterpret_cast", "return", "short", "signed", - "sizeof", "static", "static_assert", "static_cast", "struct", "switch", - "template", "this", "thread_local", "throw", "true", "try", "typedef", - "typeid", "typename", "union", "unsigned", "using", "virtual", "void", - "volatile", "wchar_t", "while", "xor", "xor_eq", - - // C99 keywords - // From - // http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fkeyw.htm - "restrict", - - // GCC/Clang extension - "typeof", - - // Not a keyword, but will break you - "NULL", - - // C88+ specs call for these to be macros, so depending on what they are - // defined to be it can lead to odd errors for some Xcode/SDK versions. - "stdin", "stdout", "stderr", - - // Objective-C Runtime typedefs - // From - "Category", "Ivar", "Method", "Protocol", - - // GPBMessage Methods - // Only need to add instance methods that may conflict with - // method declared in protos. The main cases are methods - // that take no arguments, or setFoo:/hasFoo: type methods. - "clear", "data", "delimitedData", "descriptor", "extensionRegistry", - "extensionsCurrentlySet", "initialized", "isInitialized", "serializedSize", - "sortedExtensionsInUse", "unknownFields", - - // MacTypes.h names - "Fixed", "Fract", "Size", "LogicalAddress", "PhysicalAddress", "ByteCount", - "ByteOffset", "Duration", "AbsoluteTime", "OptionBits", "ItemCount", - "PBVersion", "ScriptCode", "LangCode", "RegionCode", "OSType", - "ProcessSerialNumber", "Point", "Rect", "FixedPoint", "FixedRect", "Style", - "StyleParameter", "StyleField", "TimeScale", "TimeBase", "TimeRecord", + // Note NSObject Methods: + // These are brought in from nsobject_methods.h that is generated + // using method_dump.sh. See kNSObjectMethods below. + + // Objective C "keywords" that aren't in C + // From + // http://stackoverflow.com/questions/1873630/reserved-keywords-in-objective-c + // with some others added on. + "id", + "_cmd", + "super", + "in", + "out", + "inout", + "bycopy", + "byref", + "oneway", + "self", + "instancetype", + "nullable", + "nonnull", + "nil", + "Nil", + "YES", + "NO", + "weak", + + // C/C++ keywords (Incl C++ 0x11) + // From http://en.cppreference.com/w/cpp/keywords + "and", + "and_eq", + "alignas", + "alignof", + "asm", + "auto", + "bitand", + "bitor", + "bool", + "break", + "case", + "catch", + "char", + "char16_t", + "char32_t", + "class", + "compl", + "const", + "constexpr", + "const_cast", + "continue", + "decltype", + "default", + "delete", + "double", + "dynamic_cast", + "else", + "enum", + "explicit", + "export", + "extern ", + "false", + "float", + "for", + "friend", + "goto", + "if", + "inline", + "int", + "long", + "mutable", + "namespace", + "new", + "noexcept", + "not", + "not_eq", + "nullptr", + "operator", + "or", + "or_eq", + "private", + "protected", + "public", + "register", + "reinterpret_cast", + "return", + "short", + "signed", + "sizeof", + "static", + "static_assert", + "static_cast", + "struct", + "switch", + "template", + "this", + "thread_local", + "throw", + "true", + "try", + "typedef", + "typeid", + "typename", + "union", + "unsigned", + "using", + "virtual", + "void", + "volatile", + "wchar_t", + "while", + "xor", + "xor_eq", + + // C99 keywords + // From + // http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fkeyw.htm + "restrict", + + // GCC/Clang extension + "typeof", + + // Not a keyword, but will break you + "NULL", + + // C88+ specs call for these to be macros, so depending on what they are + // defined to be it can lead to odd errors for some Xcode/SDK versions. + "stdin", + "stdout", + "stderr", + + // Objective-C Runtime typedefs + // From + "Category", + "Ivar", + "Method", + "Protocol", + + // GPBMessage Methods + // Only need to add instance methods that may conflict with + // method declared in protos. The main cases are methods + // that take no arguments, or setFoo:/hasFoo: type methods. + "clear", + "data", + "delimitedData", + "descriptor", + "extensionRegistry", + "extensionsCurrentlySet", + "initialized", + "isInitialized", + "serializedSize", + "sortedExtensionsInUse", + "unknownFields", + + // MacTypes.h names + "Fixed", + "Fract", + "Size", + "LogicalAddress", + "PhysicalAddress", + "ByteCount", + "ByteOffset", + "Duration", + "AbsoluteTime", + "OptionBits", + "ItemCount", + "PBVersion", + "ScriptCode", + "LangCode", + "RegionCode", + "OSType", + "ProcessSerialNumber", + "Point", + "Rect", + "FixedPoint", + "FixedRect", + "Style", + "StyleParameter", + "StyleField", + "TimeScale", + "TimeBase", + "TimeRecord", }; // returns true is input starts with __ or _[A-Z] which are reserved identifiers -// in C/ C++. All calls should go through UnderscoresToCamelCase before getting here -// but this verifies and allows for future expansion if we decide to redefine what a -// reserved C identifier is (for example the GNU list +// in C/ C++. All calls should go through UnderscoresToCamelCase before getting +// here but this verifies and allows for future expansion if we decide to +// redefine what a reserved C identifier is (for example the GNU list // https://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html ) bool IsReservedCIdentifier(const std::string& input) { if (input.length() > 2) { @@ -422,7 +556,8 @@ std::string SanitizeNameForObjC(const std::string& prefix, // b) Isn't equivalent to the prefix or // c) Has the prefix, but the letter after the prefix is lowercase if (absl::StartsWith(input, prefix)) { - if (input.length() == prefix.length() || !absl::ascii_isupper(input[prefix.length()])) { + if (input.length() == prefix.length() || + !absl::ascii_isupper(input[prefix.length()])) { sanitized = prefix + input; } else { sanitized = input; @@ -469,8 +604,7 @@ void PathSplit(const std::string& path, std::string* directory, } bool IsSpecialNamePrefix(const std::string& name, - const std::string* special_names, - size_t count) { + const std::string* special_names, size_t count) { for (size_t i = 0; i < count; ++i) { const size_t length = special_names[i].length(); if (name.compare(0, length, special_names[i]) == 0) { @@ -503,8 +637,8 @@ bool IsRetainedName(const std::string& name) { // http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html static const std::string retained_names[] = {"new", "alloc", "copy", "mutableCopy"}; - return IsSpecialNamePrefix(name, retained_names, - sizeof(retained_names) / sizeof(retained_names[0])); + return IsSpecialNamePrefix( + name, retained_names, sizeof(retained_names) / sizeof(retained_names[0])); } bool IsInitName(const std::string& name) { @@ -557,8 +691,10 @@ std::string FileClassPrefix(const FileDescriptor* file) { return file->options().objc_class_prefix(); } - // If package prefix is specified in an prefix to proto mappings file then use that. - std::string objc_class_prefix = g_prefix_mode.prefix_from_proto_package_mappings(file); + // If package prefix is specified in an prefix to proto mappings file then use + // that. + std::string objc_class_prefix = + g_prefix_mode.prefix_from_proto_package_mappings(file); if (!objc_class_prefix.empty()) { return objc_class_prefix; } @@ -577,7 +713,8 @@ std::string FileClassPrefix(const FileDescriptor* file) { // camelcase each one and then join them with underscores, and add an // underscore at the end. std::string result; - const std::vector segments = absl::StrSplit(file->package(), ".", absl::SkipEmpty()); + const std::vector segments = + absl::StrSplit(file->package(), ".", absl::SkipEmpty()); for (const auto& segment : segments) { const std::string part = UnderscoresToCamelCase(segment, true); if (part.empty()) { @@ -780,7 +917,8 @@ std::string OneofNameCapitalized(const OneofDescriptor* descriptor) { return result; } -std::string UnCamelCaseFieldName(const std::string& name, const FieldDescriptor* field) { +std::string UnCamelCaseFieldName(const std::string& name, + const FieldDescriptor* field) { absl::string_view worker(name); if (absl::EndsWith(worker, "_p")) { worker = absl::StripSuffix(worker, "_p"); @@ -850,15 +988,18 @@ bool IsProtobufLibraryBundledProtoFile(const FileDescriptor* file) { namespace { -bool PackageToPrefixesCollector::ConsumeLine( - const absl::string_view& line, std::string* out_error) { +bool PackageToPrefixesCollector::ConsumeLine(const absl::string_view& line, + std::string* out_error) { int offset = line.find('='); if (offset == absl::string_view::npos) { - *out_error = usage_ + " file line without equal sign: '" + absl::StrCat(line) + "'."; + *out_error = + usage_ + " file line without equal sign: '" + absl::StrCat(line) + "'."; return false; } - absl::string_view package = absl::StripAsciiWhitespace(line.substr(0, offset)); - absl::string_view prefix = absl::StripAsciiWhitespace(line.substr(offset + 1)); + absl::string_view package = + absl::StripAsciiWhitespace(line.substr(0, offset)); + absl::string_view prefix = + absl::StripAsciiWhitespace(line.substr(offset + 1)); MaybeUnQuote(&prefix); // Don't really worry about error checking the package/prefix for // being valid. Assume the file is validated when it is created/edited. @@ -874,8 +1015,7 @@ bool LoadExpectedPackagePrefixes(const std::string& expected_prefixes_path, } PackageToPrefixesCollector collector("Expected prefixes", prefix_map); - return ParseSimpleFile( - expected_prefixes_path, &collector, out_error); + return ParseSimpleFile(expected_prefixes_path, &collector, out_error); } bool ValidateObjCClassPrefix( @@ -929,9 +1069,9 @@ bool ValidateObjCClassPrefix( // If there was no prefix option, we're done at this point. if (!has_prefix) { if (require_prefixes) { - *out_error = - "error: '" + file->name() + "' does not have a required 'option" + - " objc_class_prefix'."; + *out_error = "error: '" + file->name() + + "' does not have a required 'option" + + " objc_class_prefix'."; return false; } return true; @@ -958,9 +1098,9 @@ bool ValidateObjCClassPrefix( // package (overlap is allowed, but it has to be listed as an expected // overlap). if (!other_package_for_prefix.empty()) { - *out_error = - "error: Found 'option objc_class_prefix = \"" + prefix + - "\";' in '" + file->name() + "'; that prefix is already used for "; + *out_error = "error: Found 'option objc_class_prefix = \"" + prefix + + "\";' in '" + file->name() + + "'; that prefix is already used for "; if (absl::StartsWith(other_package_for_prefix, no_package_prefix)) { absl::StrAppend( out_error, "file '", @@ -976,26 +1116,24 @@ bool ValidateObjCClassPrefix( expected_prefixes_path, ")."); return false; // Only report first usage of the prefix. } - } // !prefix.empty() && have_expected_prefix_file + } // !prefix.empty() && have_expected_prefix_file // Check: Warning - Make sure the prefix is is a reasonable value according // to Apple's rules (the checks above implicitly whitelist anything that // doesn't meet these rules). if (!prefix.empty() && !absl::ascii_isupper(prefix[0])) { - std::cerr - << "protoc:0: warning: Invalid 'option objc_class_prefix = \"" - << prefix << "\";' in '" << file->name() << "';" - << " it should start with a capital letter." << std::endl; + std::cerr << "protoc:0: warning: Invalid 'option objc_class_prefix = \"" + << prefix << "\";' in '" << file->name() << "';" + << " it should start with a capital letter." << std::endl; std::cerr.flush(); } if (!prefix.empty() && prefix.length() < 3) { // Apple reserves 2 character prefixes for themselves. They do use some // 3 character prefixes, but they haven't updated the rules/docs. - std::cerr - << "protoc:0: warning: Invalid 'option objc_class_prefix = \"" - << prefix << "\";' in '" << file->name() << "';" - << " Apple recommends they should be at least 3 characters long." - << std::endl; + std::cerr << "protoc:0: warning: Invalid 'option objc_class_prefix = \"" + << prefix << "\";' in '" << file->name() << "';" + << " Apple recommends they should be at least 3 characters long." + << std::endl; std::cerr.flush(); } @@ -1004,19 +1142,19 @@ bool ValidateObjCClassPrefix( if (have_expected_prefix_file) { if (prefixes_must_be_registered) { *out_error = - "error: '" + file->name() + "' has 'option objc_class_prefix = \"" + - prefix + "\";', but it is not registered. Add '" + lookup_key + " = " + - (prefix.empty() ? "\"\"" : prefix) + - "' to the expected prefixes file (" + expected_prefixes_path + ")."; + "error: '" + file->name() + "' has 'option objc_class_prefix = \"" + + prefix + "\";', but it is not registered. Add '" + lookup_key + + " = " + (prefix.empty() ? "\"\"" : prefix) + + "' to the expected prefixes file (" + expected_prefixes_path + ")."; return false; } std::cerr - << "protoc:0: warning: Found unexpected 'option objc_class_prefix = \"" - << prefix << "\";' in '" << file->name() << "'; consider adding '" - << lookup_key << " = " << (prefix.empty() ? "\"\"" : prefix) - << "' to the expected prefixes file (" << expected_prefixes_path - << ")." << std::endl; + << "protoc:0: warning: Found unexpected 'option objc_class_prefix = \"" + << prefix << "\";' in '" << file->name() << "'; consider adding '" + << lookup_key << " = " << (prefix.empty() ? "\"\"" : prefix) + << "' to the expected prefixes file (" << expected_prefixes_path << ")." + << std::endl; std::cerr.flush(); } @@ -1033,7 +1171,8 @@ Options::Options() { if (file_path) { expected_prefixes_path = file_path; } - const char* suppressions = getenv("GPB_OBJC_EXPECTED_PACKAGE_PREFIXES_SUPPRESSIONS"); + const char* suppressions = + getenv("GPB_OBJC_EXPECTED_PACKAGE_PREFIXES_SUPPRESSIONS"); if (suppressions) { expected_prefixes_suppressions = absl::StrSplit(suppressions, ";", absl::SkipEmpty()); @@ -1045,9 +1184,9 @@ Options::Options() { bool ValidateObjCClassPrefixes(const std::vector& files, std::string* out_error) { - // Options's ctor load from the environment. - Options options; - return ValidateObjCClassPrefixes(files, options, out_error); + // Options's ctor load from the environment. + Options options; + return ValidateObjCClassPrefixes(files, options, out_error); } bool ValidateObjCClassPrefixes(const std::vector& files, @@ -1062,28 +1201,25 @@ bool ValidateObjCClassPrefixes(const std::vector& files, // Load the expected package prefixes, if available, to validate against. std::map expected_package_prefixes; if (!LoadExpectedPackagePrefixes(generation_options.expected_prefixes_path, - &expected_package_prefixes, - out_error)) { + &expected_package_prefixes, out_error)) { return false; } for (int i = 0; i < files.size(); i++) { bool should_skip = - (std::find(generation_options.expected_prefixes_suppressions.begin(), - generation_options.expected_prefixes_suppressions.end(), - files[i]->name()) - != generation_options.expected_prefixes_suppressions.end()); + (std::find(generation_options.expected_prefixes_suppressions.begin(), + generation_options.expected_prefixes_suppressions.end(), + files[i]->name()) != + generation_options.expected_prefixes_suppressions.end()); if (should_skip) { continue; } - bool is_valid = - ValidateObjCClassPrefix(files[i], - generation_options.expected_prefixes_path, - expected_package_prefixes, - generation_options.prefixes_must_be_registered, - generation_options.require_prefixes, - out_error); + bool is_valid = ValidateObjCClassPrefix( + files[i], generation_options.expected_prefixes_path, + expected_package_prefixes, + generation_options.prefixes_must_be_registered, + generation_options.require_prefixes, out_error); if (!is_valid) { return false; } diff --git a/src/google/protobuf/compiler/objectivec/names_unittest.cc b/src/google/protobuf/compiler/objectivec/names_unittest.cc index 0aac79497c..8063049913 100644 --- a/src/google/protobuf/compiler/objectivec/names_unittest.cc +++ b/src/google/protobuf/compiler/objectivec/names_unittest.cc @@ -29,10 +29,11 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "google/protobuf/compiler/objectivec/names.h" -#include "google/protobuf/io/zero_copy_stream_impl_lite.h" #include +#include "google/protobuf/io/zero_copy_stream_impl_lite.h" + namespace google { namespace protobuf { namespace compiler { diff --git a/src/google/protobuf/compiler/objectivec/oneof.cc b/src/google/protobuf/compiler/objectivec/oneof.cc index dd15932b7a..6fd934a83e 100644 --- a/src/google/protobuf/compiler/objectivec/oneof.cc +++ b/src/google/protobuf/compiler/objectivec/oneof.cc @@ -34,8 +34,8 @@ #include #include "absl/strings/str_cat.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" namespace google { @@ -71,22 +71,16 @@ void OneofGenerator::SetOneofIndexBase(int index_base) { } void OneofGenerator::GenerateCaseEnum(io::Printer* printer) { - printer->Print( - variables_, - "typedef GPB_ENUM($enum_name$) {\n"); + printer->Print(variables_, "typedef GPB_ENUM($enum_name$) {\n"); printer->Indent(); - printer->Print( - variables_, - "$enum_name$_GPBUnsetOneOfCase = 0,\n"); + printer->Print(variables_, "$enum_name$_GPBUnsetOneOfCase = 0,\n"); std::string enum_name = variables_["enum_name"]; for (int j = 0; j < descriptor_->field_count(); j++) { const FieldDescriptor* field = descriptor_->field(j); std::string field_name = FieldNameCapitalized(field); - printer->Print( - "$enum_name$_$field_name$ = $field_number$,\n", - "enum_name", enum_name, - "field_name", field_name, - "field_number", absl::StrCat(field->number())); + printer->Print("$enum_name$_$field_name$ = $field_number$,\n", "enum_name", + enum_name, "field_name", field_name, "field_number", + absl::StrCat(field->number())); } printer->Outdent(); // clang-format off @@ -119,9 +113,7 @@ void OneofGenerator::GenerateClearFunctionDeclaration(io::Printer* printer) { } void OneofGenerator::GeneratePropertyImplementation(io::Printer* printer) { - printer->Print( - variables_, - "@dynamic $name$OneOfCase;\n"); + printer->Print(variables_, "@dynamic $name$OneOfCase;\n"); } void OneofGenerator::GenerateClearFunctionImplementation(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/objectivec/primitive_field.cc b/src/google/protobuf/compiler/objectivec/primitive_field.cc index 739d1ce334..b6a44d2dea 100644 --- a/src/google/protobuf/compiler/objectivec/primitive_field.cc +++ b/src/google/protobuf/compiler/objectivec/primitive_field.cc @@ -34,8 +34,8 @@ #include #include "absl/strings/str_cat.h" -#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/compiler/objectivec/helpers.h" +#include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/printer.h" namespace google { diff --git a/src/google/protobuf/compiler/objectivec/text_format_decode_data.cc b/src/google/protobuf/compiler/objectivec/text_format_decode_data.cc index dac343e34a..b262dd7518 100644 --- a/src/google/protobuf/compiler/objectivec/text_format_decode_data.cc +++ b/src/google/protobuf/compiler/objectivec/text_format_decode_data.cc @@ -28,17 +28,18 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include "google/protobuf/compiler/code_generator.h" -#include "google/protobuf/stubs/strutil.h" +#include "google/protobuf/compiler/objectivec/text_format_decode_data.h" + #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" -#include "google/protobuf/compiler/objectivec/text_format_decode_data.h" +#include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/compiler/objectivec/names.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream_impl.h" +#include "google/protobuf/stubs/strutil.h" // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some // error cases, so it seems to be ok to use as a back door for errors. @@ -167,9 +168,9 @@ std::string DirectDecodeString(const std::string& str) { } // namespace -TextFormatDecodeData::TextFormatDecodeData() { } +TextFormatDecodeData::TextFormatDecodeData() {} -TextFormatDecodeData::~TextFormatDecodeData() { } +TextFormatDecodeData::~TextFormatDecodeData() {} void TextFormatDecodeData::AddString(int32_t key, const std::string& input_for_decode, @@ -178,8 +179,8 @@ void TextFormatDecodeData::AddString(int32_t key, i != entries_.end(); ++i) { if (i->first == key) { std::cerr << "error: duplicate key (" << key - << ") making TextFormat data, input: \"" << input_for_decode - << "\", desired: \"" << desired_output << "\"." << std::endl; + << ") making TextFormat data, input: \"" << input_for_decode + << "\", desired: \"" << desired_output << "\"." << std::endl; std::cerr.flush(); abort(); } @@ -214,16 +215,17 @@ std::string TextFormatDecodeData::DecodeDataForString( const std::string& input_for_decode, const std::string& desired_output) { if (input_for_decode.empty() || desired_output.empty()) { std::cerr << "error: got empty string for making TextFormat data, input: \"" - << input_for_decode << "\", desired: \"" << desired_output << "\"." - << std::endl; + << input_for_decode << "\", desired: \"" << desired_output + << "\"." << std::endl; std::cerr.flush(); abort(); } if ((input_for_decode.find('\0') != std::string::npos) || (desired_output.find('\0') != std::string::npos)) { - std::cerr << "error: got a null char in a string for making TextFormat data," - << " input: \"" << absl::CEscape(input_for_decode) << "\", desired: \"" - << absl::CEscape(desired_output) << "\"." << std::endl; + std::cerr + << "error: got a null char in a string for making TextFormat data," + << " input: \"" << absl::CEscape(input_for_decode) << "\", desired: \"" + << absl::CEscape(desired_output) << "\"." << std::endl; std::cerr.flush(); abort(); } @@ -260,7 +262,6 @@ std::string TextFormatDecodeData::DecodeDataForString( return builder.Finish() + (char)'\0'; } - } // namespace objectivec } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/objectivec/text_format_decode_data_unittest.cc b/src/google/protobuf/compiler/objectivec/text_format_decode_data_unittest.cc index ad1308ad9d..6cec537d4b 100644 --- a/src/google/protobuf/compiler/objectivec/text_format_decode_data_unittest.cc +++ b/src/google/protobuf/compiler/objectivec/text_format_decode_data_unittest.cc @@ -212,7 +212,6 @@ TEST(ObjCHelper, TextFormatDecodeData_ByteCodes) { EXPECT_EQ(expected, decode_data.Data()); } - // Death tests do not work on Windows as of yet. #ifdef PROTOBUF_HAS_DEATH_TEST TEST(ObjCHelperDeathTest, TextFormatDecodeData_Failures) {