From 34ba95bb71946936e087986f5fe7eea7d96c7016 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Fri, 26 Aug 2022 16:36:36 -0400 Subject: [PATCH 01/64] json_name and default pseudo-options have source code info consistent with options --- src/google/protobuf/compiler/parser.cc | 40 +++++++++++++++---- src/google/protobuf/compiler/parser.h | 4 ++ .../protobuf/compiler/parser_unittest.cc | 7 ++-- 3 files changed, 40 insertions(+), 11 deletions(-) diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index f220fad8be..2ab823981e 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -408,6 +408,11 @@ Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent) { Init(parent, parent.source_code_info_); } +Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent, + SourceCodeInfo* source_code_info) { + Init(parent, source_code_info); +} + Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent, int path1, SourceCodeInfo* source_code_info) { @@ -1237,13 +1242,22 @@ bool Parser::ParseDefaultAssignment( field->clear_default_value(); } + LocationRecorder location(field_location, + FieldDescriptorProto::kDefaultValueFieldNumber); + DO(Consume("default")); DO(Consume("=")); - LocationRecorder location(field_location, - FieldDescriptorProto::kDefaultValueFieldNumber); - location.RecordLegacyLocation(field, - DescriptorPool::ErrorCollector::DEFAULT_VALUE); + // We don't need to create separate spans in source code info for name and value, + // since there's no way to represent them distinctly in a location path. But we will + // want a separate recorder for the value, just to have more precise location info + // in error messages. So we let it create a location in no_op, so it doesn't add a + // span to the file descriptor. + SourceCodeInfo no_op; + LocationRecorder value_location(location, &no_op); + value_location.RecordLegacyLocation( + field, DescriptorPool::ErrorCollector::DEFAULT_VALUE); + std::string* default_value = field->mutable_default_value(); if (!field->has_type()) { @@ -1377,13 +1391,23 @@ bool Parser::ParseJsonName(FieldDescriptorProto* field, LocationRecorder location(field_location, FieldDescriptorProto::kJsonNameFieldNumber); - location.RecordLegacyLocation(field, - DescriptorPool::ErrorCollector::OPTION_NAME); - DO(Consume("json_name")); + // We don't need to create separate spans in source code info for name and value, + // since there's no way to represent them distinctly in a location path. But we will + // want a separate recorder for them, just to have more precise location info + // in error messages. So we let them create a location in no_op, so they don't + // add a span to the file descriptor. + SourceCodeInfo no_op; + { + LocationRecorder name_location(location, &no_op); + name_location.RecordLegacyLocation( + field, DescriptorPool::ErrorCollector::OPTION_NAME); + + DO(Consume("json_name")); + } DO(Consume("=")); - LocationRecorder value_location(location); + LocationRecorder value_location(location, &no_op); value_location.RecordLegacyLocation( field, DescriptorPool::ErrorCollector::OPTION_VALUE); diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index d4eb76302c..8b05d0e4ad 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -237,6 +237,10 @@ class PROTOBUF_EXPORT Parser { LocationRecorder(const LocationRecorder& parent, int path1, int path2); // Creates a recorder that generates locations into given source code info. + LocationRecorder(const LocationRecorder& parent, + SourceCodeInfo* source_code_info); + // Creates a recorder that generates locations into given source code info + // and calls AddPath() one time. LocationRecorder(const LocationRecorder& parent, int path1, SourceCodeInfo* source_code_info); diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 55ed7acb6f..a164d7d54a 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -3415,18 +3415,19 @@ TEST_F(SourceInfoTest, FieldOptions) { EXPECT_TRUE( Parse("message Foo {" " optional int32 bar = 1 " - "$a$[default=$b$123$c$,$d$opt1=123$e$," - "$f$opt2='hi'$g$]$h$;" + "$a$[$b$default=123$c$, $d$opt1=123$e$, " + "$f$opt2='hi'$g$, $h$json_name='barBar'$i$]$j$;" "}\n")); const FieldDescriptorProto& field = file_.message_type(0).field(0); const UninterpretedOption& option1 = field.options().uninterpreted_option(0); const UninterpretedOption& option2 = field.options().uninterpreted_option(1); - EXPECT_TRUE(HasSpan('a', 'h', field.options())); + EXPECT_TRUE(HasSpan('a', 'j', field.options())); EXPECT_TRUE(HasSpan('b', 'c', field, "default_value")); EXPECT_TRUE(HasSpan('d', 'e', option1)); EXPECT_TRUE(HasSpan('f', 'g', option2)); + EXPECT_TRUE(HasSpan('h', 'i', field, "json_name")); // Ignore these. EXPECT_TRUE(HasSpan(file_)); From 40847c7ee5848f41c505a1ece1f27ec4a687837b Mon Sep 17 00:00:00 2001 From: Mike Kruskal <62662355+mkruskal-google@users.noreply.github.com> Date: Tue, 30 Aug 2022 09:39:21 -0400 Subject: [PATCH 02/64] Fix Kokoro tests to work on Monterey machines (#10473) * Disabling broken mac php tests * Fix ruby permissions after Monterey upgrade * Install m4 via Homebrew * Adding ruby/python fixes to presubmits * Adding homebrew prefix command * More fixes for objc, python, and benchmark build * Properly disabling C++ benchmark warning * Use python 2 for testing * Splitting venv and python 2 * Setup tox-pyenv * Silencing more warnings * Cleanup * Upgrade python tests to 3.7 on mac * Switch to python 2 by default (googletest requires it) * Remove venv for python tests, use python 3.7 * Disable all compiler warnings for benchmark builds * Enable benchmark LTO to silence warnings * Fix locale issues in cocoapods * Remove benchmark build from C++ tests * Removing deprecated use_bazel command Removing python 3.6 mac build, since Monterey doesn't support it --- benchmarks/Makefile.am | 4 +-- kokoro/macos/prepare_build_macos_rc | 35 +++++++++++-------- kokoro/macos/ruby31/build.sh | 3 ++ .../release/python/macos/build_artifacts.sh | 1 - kokoro/release/ruby/macos/build_artifacts.sh | 3 -- kokoro/release/ruby/macos/ruby/ruby_build.sh | 1 - .../ruby/macos/ruby/ruby_build_environment.sh | 4 +++ tests.sh | 11 ------ 8 files changed, 29 insertions(+), 33 deletions(-) diff --git a/benchmarks/Makefile.am b/benchmarks/Makefile.am index 3ab35e37ca..ed5797880d 100644 --- a/benchmarks/Makefile.am +++ b/benchmarks/Makefile.am @@ -91,8 +91,8 @@ $(benchmarks_protoc_outputs_proto2_header): protoc_middleman2 initialize_submodule: oldpwd=`pwd` - cd $(top_srcdir) && git submodule update --init -r third_party/benchmark && \ - cd third_party/benchmark && cmake -DCMAKE_BUILD_TYPE=Release && make + cd $(top_srcdir) && git submodule update --init -r third_party/benchmark && cd third_party/benchmark \ + && cmake -DCMAKE_BUILD_TYPE=Release && make cd $$oldpwd touch initialize_submodule diff --git a/kokoro/macos/prepare_build_macos_rc b/kokoro/macos/prepare_build_macos_rc index 8e0a87edbb..75b50c09f9 100755 --- a/kokoro/macos/prepare_build_macos_rc +++ b/kokoro/macos/prepare_build_macos_rc @@ -4,14 +4,15 @@ set -eux +export HOMEBREW_PREFIX=$(brew --prefix) + ## # Select Xcode version -# Remember to update the Xcode version when Xcode_11.3.app is not available. -# If xcode is not available, it will probably encounter the failure for -# "autom4te: need GNU m4 1.4 or later: /usr/bin/m4" -# go/kokoro/userdocs/macos/selecting_xcode.md for more information. -export DEVELOPER_DIR=/Applications/Xcode_11.3.app/Contents/Developer +## +# Select Xcode version +export DEVELOPER_DIR=/Applications/Xcode_13.3.1.app/Contents/Developer +sudo xcode-select -s "${DEVELOPER_DIR}" ## # Select C/C++ compilers @@ -19,22 +20,26 @@ export DEVELOPER_DIR=/Applications/Xcode_11.3.app/Contents/Developer export CC=gcc export CXX=g++ +## +# Install Python 2 by default + +eval "$(pyenv init -)" +pyenv install -v -s 2.7.18 && pyenv global 2.7.18 + ## # Install Tox if [[ "${KOKORO_INSTALL_TOX:-}" == "yes" ]] ; then - sudo python3 -m pip install --upgrade pip tox + pyenv install -v -s 3.7.13 + pyenv global 3.7.13 + sudo python -m pip install --upgrade pip tox tox-pyenv fi ## -# Install RVM - +# Setup RVM if [[ "${KOKORO_INSTALL_RVM:-}" == "yes" ]] ; then - curl -sSL https://rvm.io/mpapis.asc | gpg --import - - curl -sSL https://rvm.io/pkuczynski.asc | gpg --import - - - # Old OpenSSL versions cannot handle the SSL certificate used by - # https://get.rvm.io, so as a workaround we download RVM directly from - # GitHub. See this issue for details: https://github.com/rvm/rvm/issues/5133 - curl -sSL https://raw.githubusercontent.com/rvm/rvm/master/binscripts/rvm-installer | bash -s master --ruby + git config --global --add safe.directory $HOMEBREW_PREFIX/Library/Taps/homebrew/homebrew-cask + git config --global --add safe.directory $HOMEBREW_PREFIX/Library/Taps/homebrew/homebrew-core + git config --global --add safe.directory $HOMEBREW_PREFIX/Library/Taps/homebrew/homebrew-services + sudo chown -R $(whoami) $HOME/.rvm/ fi diff --git a/kokoro/macos/ruby31/build.sh b/kokoro/macos/ruby31/build.sh index 1b5a5a5a60..3cf61f60f6 100644 --- a/kokoro/macos/ruby31/build.sh +++ b/kokoro/macos/ruby31/build.sh @@ -5,6 +5,9 @@ # Change to repo root cd $(dirname $0)/../../.. +# Fix locale issues in Monterey. +export LC_ALL=en_US.UTF-8 + # Prepare worker environment to run tests KOKORO_INSTALL_RVM=yes source kokoro/macos/prepare_build_macos_rc diff --git a/kokoro/release/python/macos/build_artifacts.sh b/kokoro/release/python/macos/build_artifacts.sh index aeb4242a6b..a72ee6733f 100755 --- a/kokoro/release/python/macos/build_artifacts.sh +++ b/kokoro/release/python/macos/build_artifacts.sh @@ -58,7 +58,6 @@ build_artifact_version() { } export MB_PYTHON_OSX_VER=10.9 -build_artifact_version 3.6 build_artifact_version 3.7 build_artifact_version 3.8 build_artifact_version 3.9 diff --git a/kokoro/release/ruby/macos/build_artifacts.sh b/kokoro/release/ruby/macos/build_artifacts.sh index c68b63cc43..a109d45b61 100755 --- a/kokoro/release/ruby/macos/build_artifacts.sh +++ b/kokoro/release/ruby/macos/build_artifacts.sh @@ -12,8 +12,5 @@ export ARTIFACT_DIR=$(pwd)/artifacts # ruby environment bash kokoro/release/ruby/macos/ruby/ruby_build_environment.sh -gem install rubygems-update -update_rubygems - # build artifacts bash kokoro/release/ruby/macos/ruby/ruby_build.sh diff --git a/kokoro/release/ruby/macos/ruby/ruby_build.sh b/kokoro/release/ruby/macos/ruby/ruby_build.sh index 55773b21a9..bbfc631197 100755 --- a/kokoro/release/ruby/macos/ruby/ruby_build.sh +++ b/kokoro/release/ruby/macos/ruby/ruby_build.sh @@ -3,7 +3,6 @@ set -ex # Build protoc -use_bazel.sh 5.1.1 bazel build //:protoc export PROTOC=$PWD/bazel-bin/protoc diff --git a/kokoro/release/ruby/macos/ruby/ruby_build_environment.sh b/kokoro/release/ruby/macos/ruby/ruby_build_environment.sh index 2a9cb1687b..29066427f2 100755 --- a/kokoro/release/ruby/macos/ruby/ruby_build_environment.sh +++ b/kokoro/release/ruby/macos/ruby/ruby_build_environment.sh @@ -2,6 +2,10 @@ set -ex +# Fix permissions +sudo chown -R $(whoami) $HOME/.rvm/ +sudo chown -R $(whoami) /Library/Ruby/ + set +ex # rvm script is very verbose and exits with errorcode curl -sSL https://rvm.io/mpapis.asc | gpg --import - diff --git a/tests.sh b/tests.sh index e82265c895..180b870210 100755 --- a/tests.sh +++ b/tests.sh @@ -23,17 +23,6 @@ build_cpp() { internal_build_cpp make check -j$(nproc) || (cat src/test-suite.log; false) cd conformance && make test_cpp && cd .. - - # The benchmark code depends on cmake, so test if it is installed before - # trying to do the build. - if [[ $(type cmake 2>/dev/null) ]]; then - # Verify benchmarking code can build successfully. - cd benchmarks && make cpp-benchmark && cd .. - else - echo "" - echo "WARNING: Skipping validation of the benchmarking code, cmake isn't installed." - echo "" - fi } build_cpp_tcmalloc() { From aafacb09c75d521b11500970827214f2247dd4aa Mon Sep 17 00:00:00 2001 From: Mike Kruskal <62662355+mkruskal-google@users.noreply.github.com> Date: Wed, 7 Sep 2022 09:59:22 -0700 Subject: [PATCH 03/64] Remove broken use_bazel.sh (#10511) --- kokoro/release/python/macos/config.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/kokoro/release/python/macos/config.sh b/kokoro/release/python/macos/config.sh index 91e62d6c79..74e65691cb 100644 --- a/kokoro/release/python/macos/config.sh +++ b/kokoro/release/python/macos/config.sh @@ -26,7 +26,6 @@ function pre_build { pushd protobuf # Build protoc and protobuf libraries - use_bazel.sh 5.1.1 bazel build //:protoc export PROTOC=$PWD/bazel-bin/protoc mkdir src/.libs From ea2f20498e2853a58875f247b06edcb567ccd86b Mon Sep 17 00:00:00 2001 From: Mike Kruskal <62662355+mkruskal-google@users.noreply.github.com> Date: Thu, 8 Sep 2022 10:57:01 -0700 Subject: [PATCH 04/64] Uninstall system protobuf to prevent version conflicts (#10522) --- kokoro/macos/prepare_build_macos_rc | 4 ++++ kokoro/release/python/macos/build_artifacts.sh | 3 +++ 2 files changed, 7 insertions(+) diff --git a/kokoro/macos/prepare_build_macos_rc b/kokoro/macos/prepare_build_macos_rc index 75b50c09f9..8f99f105fa 100755 --- a/kokoro/macos/prepare_build_macos_rc +++ b/kokoro/macos/prepare_build_macos_rc @@ -6,6 +6,10 @@ set -eux export HOMEBREW_PREFIX=$(brew --prefix) +## +# Remove any pre-existing protobuf installation. +brew uninstall protobuf + ## # Select Xcode version diff --git a/kokoro/release/python/macos/build_artifacts.sh b/kokoro/release/python/macos/build_artifacts.sh index a72ee6733f..296bd9aef3 100755 --- a/kokoro/release/python/macos/build_artifacts.sh +++ b/kokoro/release/python/macos/build_artifacts.sh @@ -2,6 +2,9 @@ set -ex +# Remove any pre-existing protobuf installation. +brew uninstall protobuf + # change to repo root pushd $(dirname $0)/../../../.. From fc1dbc6fac87d6c6307d055e50bc5a57c8143e4e Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Wed, 7 Sep 2022 18:25:00 +0100 Subject: [PATCH 05/64] Fix 32-bit floating point JSON parsing of maximal values for C# Fixes #10509. --- .../src/Google.Protobuf.Test/JsonParserTest.cs | 10 ++++++++-- csharp/src/Google.Protobuf/JsonParser.cs | 16 ++++++---------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs index b5d6c0bbe3..c03b326c08 100644 --- a/csharp/src/Google.Protobuf.Test/JsonParserTest.cs +++ b/csharp/src/Google.Protobuf.Test/JsonParserTest.cs @@ -576,6 +576,10 @@ namespace Google.Protobuf [TestCase("-3.402823e38", -3.402823e38f)] [TestCase("1.5e1", 15f)] [TestCase("15e-1", 1.5f)] + [TestCase("3.4028235e38", float.MaxValue)] + [TestCase("-3.4028235e38", float.MinValue)] + [TestCase("3.4028235e+38", float.MaxValue)] + [TestCase("-3.4028235e+38", float.MinValue)] public void NumberToFloat_Valid(string jsonValue, float expectedParsedValue) { string json = "{ \"singleFloat\": " + jsonValue + "}"; @@ -584,8 +588,10 @@ namespace Google.Protobuf } [Test] - [TestCase("3.402824e38", typeof(InvalidProtocolBufferException))] - [TestCase("-3.402824e38", typeof(InvalidProtocolBufferException))] + [TestCase("3.4028236e38", typeof(InvalidProtocolBufferException))] + [TestCase("-3.4028236e38", typeof(InvalidProtocolBufferException))] + [TestCase("3.4028236e+38", typeof(InvalidProtocolBufferException))] + [TestCase("-3.4028236e+38", typeof(InvalidProtocolBufferException))] [TestCase("1,0", typeof(InvalidJsonException))] [TestCase("1.0.0", typeof(InvalidJsonException))] [TestCase("+1", typeof(InvalidJsonException))] diff --git a/csharp/src/Google.Protobuf/JsonParser.cs b/csharp/src/Google.Protobuf/JsonParser.cs index 3575e2529e..6cb98d6e24 100644 --- a/csharp/src/Google.Protobuf/JsonParser.cs +++ b/csharp/src/Google.Protobuf/JsonParser.cs @@ -642,19 +642,15 @@ namespace Google.Protobuf { return float.NaN; } - if (value > float.MaxValue || value < float.MinValue) + float converted = (float) value; + // If the value is out of range of float, the cast representation will be infinite. + // If the original value was infinite as well, that's fine - we'll return the 32-bit + // version (with the correct sign). + if (float.IsInfinity(converted) && !double.IsInfinity(value)) { - if (double.IsPositiveInfinity(value)) - { - return float.PositiveInfinity; - } - if (double.IsNegativeInfinity(value)) - { - return float.NegativeInfinity; - } throw new InvalidProtocolBufferException($"Value out of range: {value}"); } - return (float) value; + return converted; case FieldType.Enum: CheckInteger(value); // Just return it as an int, and let the CLR convert it. From cd0ee8f45d0d749a1e4deb9847e53efb62c04d7b Mon Sep 17 00:00:00 2001 From: Deanna Garcia Date: Tue, 13 Sep 2022 16:38:34 +0000 Subject: [PATCH 06/64] Apply patch --- src/google/protobuf/extension_set_inl.h | 27 +++-- src/google/protobuf/wire_format.cc | 26 +++-- src/google/protobuf/wire_format_lite.h | 27 +++-- src/google/protobuf/wire_format_unittest.inc | 104 +++++++++++++++++-- 4 files changed, 149 insertions(+), 35 deletions(-) diff --git a/src/google/protobuf/extension_set_inl.h b/src/google/protobuf/extension_set_inl.h index 95936cc243..e4e711721d 100644 --- a/src/google/protobuf/extension_set_inl.h +++ b/src/google/protobuf/extension_set_inl.h @@ -206,16 +206,21 @@ const char* ExtensionSet::ParseMessageSetItemTmpl( const char* ptr, const Msg* extendee, internal::InternalMetadata* metadata, internal::ParseContext* ctx) { std::string payload; - uint32_t type_id = 0; - bool payload_read = false; + uint32_t type_id; + enum class State { kNoTag, kHasType, kHasPayload, kDone }; + State state = State::kNoTag; + while (!ctx->Done(&ptr)) { uint32_t tag = static_cast(*ptr++); if (tag == WireFormatLite::kMessageSetTypeIdTag) { uint64_t tmp; ptr = ParseBigVarint(ptr, &tmp); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); - type_id = tmp; - if (payload_read) { + if (state == State::kNoTag) { + type_id = tmp; + state = State::kHasType; + } else if (state == State::kHasPayload) { + type_id = tmp; ExtensionInfo extension; bool was_packed_on_wire; if (!FindExtension(2, type_id, extendee, ctx, &extension, @@ -241,20 +246,24 @@ const char* ExtensionSet::ParseMessageSetItemTmpl( GOOGLE_PROTOBUF_PARSER_ASSERT(value->_InternalParse(p, &tmp_ctx) && tmp_ctx.EndedAtLimit()); } - type_id = 0; + state = State::kDone; } } else if (tag == WireFormatLite::kMessageSetMessageTag) { - if (type_id != 0) { + if (state == State::kHasType) { ptr = ParseFieldMaybeLazily(static_cast(type_id) * 8 + 2, ptr, extendee, metadata, ctx); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); - type_id = 0; + state = State::kDone; } else { + std::string tmp; int32_t size = ReadSize(&ptr); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); - ptr = ctx->ReadString(ptr, size, &payload); + ptr = ctx->ReadString(ptr, size, &tmp); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); - payload_read = true; + if (state == State::kNoTag) { + payload = std::move(tmp); + state = State::kHasPayload; + } } } else { ptr = ReadTag(ptr - 1, &tag); diff --git a/src/google/protobuf/wire_format.cc b/src/google/protobuf/wire_format.cc index e44c6ebeee..6fe63c86ce 100644 --- a/src/google/protobuf/wire_format.cc +++ b/src/google/protobuf/wire_format.cc @@ -657,9 +657,11 @@ struct WireFormat::MessageSetParser { const char* _InternalParse(const char* ptr, internal::ParseContext* ctx) { // Parse a MessageSetItem auto metadata = reflection->MutableInternalMetadata(msg); + enum class State { kNoTag, kHasType, kHasPayload, kDone }; + State state = State::kNoTag; + std::string payload; uint32_t type_id = 0; - bool payload_read = false; while (!ctx->Done(&ptr)) { // We use 64 bit tags in order to allow typeid's that span the whole // range of 32 bit numbers. @@ -668,8 +670,11 @@ struct WireFormat::MessageSetParser { uint64_t tmp; ptr = ParseBigVarint(ptr, &tmp); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); - type_id = tmp; - if (payload_read) { + if (state == State::kNoTag) { + type_id = tmp; + state = State::kHasType; + } else if (state == State::kHasPayload) { + type_id = tmp; const FieldDescriptor* field; if (ctx->data().pool == nullptr) { field = reflection->FindKnownExtensionByNumber(type_id); @@ -696,17 +701,17 @@ struct WireFormat::MessageSetParser { GOOGLE_PROTOBUF_PARSER_ASSERT(value->_InternalParse(p, &tmp_ctx) && tmp_ctx.EndedAtLimit()); } - type_id = 0; + state = State::kDone; } continue; } else if (tag == WireFormatLite::kMessageSetMessageTag) { - if (type_id == 0) { + if (state == State::kNoTag) { int32_t size = ReadSize(&ptr); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ptr = ctx->ReadString(ptr, size, &payload); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); - payload_read = true; - } else { + state = State::kHasPayload; + } else if (state == State::kHasType) { // We're now parsing the payload const FieldDescriptor* field = nullptr; if (descriptor->IsExtensionNumber(type_id)) { @@ -720,7 +725,12 @@ struct WireFormat::MessageSetParser { ptr = WireFormat::_InternalParseAndMergeField( msg, ptr, ctx, static_cast(type_id) * 8 + 2, reflection, field); - type_id = 0; + state = State::kDone; + } else { + int32_t size = ReadSize(&ptr); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); + ptr = ctx->Skip(ptr, size); + GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); } } else { // An unknown field in MessageSetItem. diff --git a/src/google/protobuf/wire_format_lite.h b/src/google/protobuf/wire_format_lite.h index a7e64bf1e4..80d396156f 100644 --- a/src/google/protobuf/wire_format_lite.h +++ b/src/google/protobuf/wire_format_lite.h @@ -1831,6 +1831,9 @@ bool ParseMessageSetItemImpl(io::CodedInputStream* input, MS ms) { // we can parse it later. std::string message_data; + enum class State { kNoTag, kHasType, kHasPayload, kDone }; + State state = State::kNoTag; + while (true) { const uint32_t tag = input->ReadTagNoLastTag(); if (tag == 0) return false; @@ -1839,26 +1842,34 @@ bool ParseMessageSetItemImpl(io::CodedInputStream* input, MS ms) { case WireFormatLite::kMessageSetTypeIdTag: { uint32_t type_id; if (!input->ReadVarint32(&type_id)) return false; - last_type_id = type_id; - - if (!message_data.empty()) { + if (state == State::kNoTag) { + last_type_id = type_id; + state = State::kHasType; + } else if (state == State::kHasPayload) { // We saw some message data before the type_id. Have to parse it // now. io::CodedInputStream sub_input( reinterpret_cast(message_data.data()), static_cast(message_data.size())); sub_input.SetRecursionLimit(input->RecursionBudget()); - if (!ms.ParseField(last_type_id, &sub_input)) { + if (!ms.ParseField(type_id, &sub_input)) { return false; } message_data.clear(); + state = State::kDone; } break; } case WireFormatLite::kMessageSetMessageTag: { - if (last_type_id == 0) { + if (state == State::kHasType) { + // Already saw type_id, so we can parse this directly. + if (!ms.ParseField(last_type_id, input)) { + return false; + } + state = State::kDone; + } else if (state == State::kNoTag) { // We haven't seen a type_id yet. Append this data to message_data. uint32_t length; if (!input->ReadVarint32(&length)) return false; @@ -1869,11 +1880,9 @@ bool ParseMessageSetItemImpl(io::CodedInputStream* input, MS ms) { auto ptr = reinterpret_cast(&message_data[0]); ptr = io::CodedOutputStream::WriteVarint32ToArray(length, ptr); if (!input->ReadRaw(ptr, length)) return false; + state = State::kHasPayload; } else { - // Already saw type_id, so we can parse this directly. - if (!ms.ParseField(last_type_id, input)) { - return false; - } + if (!ms.SkipField(tag, input)) return false; } break; diff --git a/src/google/protobuf/wire_format_unittest.inc b/src/google/protobuf/wire_format_unittest.inc index d583ddde19..0e3869cbef 100644 --- a/src/google/protobuf/wire_format_unittest.inc +++ b/src/google/protobuf/wire_format_unittest.inc @@ -581,28 +581,54 @@ TEST(WireFormatTest, ParseMessageSet) { EXPECT_EQ(message_set.DebugString(), dynamic_message_set.DebugString()); } -TEST(WireFormatTest, ParseMessageSetWithReverseTagOrder) { +namespace { +std::string BuildMessageSetItemStart() { std::string data; { - UNITTEST::TestMessageSetExtension1 message; - message.set_i(123); - // Build a MessageSet manually with its message content put before its - // type_id. io::StringOutputStream output_stream(&data); io::CodedOutputStream coded_output(&output_stream); coded_output.WriteTag(WireFormatLite::kMessageSetItemStartTag); + } + return data; +} +std::string BuildMessageSetItemEnd() { + std::string data; + { + io::StringOutputStream output_stream(&data); + io::CodedOutputStream coded_output(&output_stream); + coded_output.WriteTag(WireFormatLite::kMessageSetItemEndTag); + } + return data; +} +std::string BuildMessageSetTestExtension1(int value = 123) { + std::string data; + { + UNITTEST::TestMessageSetExtension1 message; + message.set_i(value); + io::StringOutputStream output_stream(&data); + io::CodedOutputStream coded_output(&output_stream); // Write the message content first. WireFormatLite::WriteTag(WireFormatLite::kMessageSetMessageNumber, WireFormatLite::WIRETYPE_LENGTH_DELIMITED, &coded_output); coded_output.WriteVarint32(message.ByteSizeLong()); message.SerializeWithCachedSizes(&coded_output); - // Write the type id. - uint32_t type_id = message.GetDescriptor()->extension(0)->number(); + } + return data; +} +std::string BuildMessageSetItemTypeId(int extension_number) { + std::string data; + { + io::StringOutputStream output_stream(&data); + io::CodedOutputStream coded_output(&output_stream); WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber, - type_id, &coded_output); - coded_output.WriteTag(WireFormatLite::kMessageSetItemEndTag); + extension_number, &coded_output); } + return data; +} +void ValidateTestMessageSet(const std::string& test_case, + const std::string& data) { + SCOPED_TRACE(test_case); { PROTO2_WIREFORMAT_UNITTEST::TestMessageSet message_set; ASSERT_TRUE(message_set.ParseFromString(data)); @@ -612,6 +638,11 @@ TEST(WireFormatTest, ParseMessageSetWithReverseTagOrder) { .GetExtension( UNITTEST::TestMessageSetExtension1::message_set_extension) .i()); + + // Make sure it does not contain anything else. + message_set.ClearExtension( + UNITTEST::TestMessageSetExtension1::message_set_extension); + EXPECT_EQ(message_set.SerializeAsString(), ""); } { // Test parse the message via Reflection. @@ -627,6 +658,61 @@ TEST(WireFormatTest, ParseMessageSetWithReverseTagOrder) { UNITTEST::TestMessageSetExtension1::message_set_extension) .i()); } + { + // Test parse the message via DynamicMessage. + DynamicMessageFactory factory; + std::unique_ptr msg( + factory + .GetPrototype( + PROTO2_WIREFORMAT_UNITTEST::TestMessageSet::descriptor()) + ->New()); + msg->ParseFromString(data); + auto* reflection = msg->GetReflection(); + std::vector fields; + reflection->ListFields(*msg, &fields); + ASSERT_EQ(fields.size(), 1); + const auto& sub = reflection->GetMessage(*msg, fields[0]); + reflection = sub.GetReflection(); + EXPECT_EQ(123, reflection->GetInt32( + sub, sub.GetDescriptor()->FindFieldByName("i"))); + } +} +} // namespace + +TEST(WireFormatTest, ParseMessageSetWithAnyTagOrder) { + std::string start = BuildMessageSetItemStart(); + std::string end = BuildMessageSetItemEnd(); + std::string id = BuildMessageSetItemTypeId( + UNITTEST::TestMessageSetExtension1::descriptor()->extension(0)->number()); + std::string message = BuildMessageSetTestExtension1(); + + ValidateTestMessageSet("id + message", start + id + message + end); + ValidateTestMessageSet("message + id", start + message + id + end); +} + +TEST(WireFormatTest, ParseMessageSetWithDuplicateTags) { + std::string start = BuildMessageSetItemStart(); + std::string end = BuildMessageSetItemEnd(); + std::string id = BuildMessageSetItemTypeId( + UNITTEST::TestMessageSetExtension1::descriptor()->extension(0)->number()); + std::string other_id = BuildMessageSetItemTypeId(123456); + std::string message = BuildMessageSetTestExtension1(); + std::string other_message = BuildMessageSetTestExtension1(321); + + // Double id + ValidateTestMessageSet("id + other_id + message", + start + id + other_id + message + end); + ValidateTestMessageSet("id + message + other_id", + start + id + message + other_id + end); + ValidateTestMessageSet("message + id + other_id", + start + message + id + other_id + end); + // Double message + ValidateTestMessageSet("id + message + other_message", + start + id + message + other_message + end); + ValidateTestMessageSet("message + id + other_message", + start + message + id + other_message + end); + ValidateTestMessageSet("message + other_message + id", + start + message + other_message + id + end); } void SerializeReverseOrder( From 24487dd1045c7f3d64a21f38a3f0c06cc4cf2edb Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Tue, 13 Sep 2022 13:50:08 -0700 Subject: [PATCH 07/64] Updating version.json and repo version numbers to: 21.6 --- Protobuf-C++.podspec | 2 +- Protobuf.podspec | 2 +- configure.ac | 2 +- csharp/Google.Protobuf.Tools.nuspec | 2 +- .../Google.Protobuf/Google.Protobuf.csproj | 2 +- java/README.md | 6 ++--- java/bom/pom.xml | 2 +- java/core/pom.xml | 2 +- java/kotlin-lite/pom.xml | 2 +- java/kotlin/pom.xml | 2 +- java/lite.md | 2 +- java/lite/pom.xml | 2 +- java/pom.xml | 2 +- java/util/pom.xml | 2 +- php/ext/google/protobuf/package.xml | 23 +++++++++++++++---- php/ext/google/protobuf/protobuf.h | 2 +- protobuf_version.bzl | 6 ++--- protoc-artifacts/pom.xml | 2 +- python/google/protobuf/__init__.py | 2 +- ruby/google-protobuf.gemspec | 2 +- ruby/pom.xml | 4 ++-- src/Makefile.am | 2 +- src/google/protobuf/any.pb.h | 2 +- src/google/protobuf/api.pb.h | 2 +- src/google/protobuf/compiler/plugin.pb.h | 2 +- src/google/protobuf/descriptor.pb.h | 2 +- src/google/protobuf/duration.pb.h | 2 +- src/google/protobuf/empty.pb.h | 2 +- src/google/protobuf/field_mask.pb.h | 2 +- src/google/protobuf/port_def.inc | 2 +- src/google/protobuf/source_context.pb.h | 2 +- src/google/protobuf/struct.pb.h | 2 +- src/google/protobuf/stubs/common.h | 2 +- src/google/protobuf/timestamp.pb.h | 2 +- src/google/protobuf/type.pb.h | 2 +- src/google/protobuf/wrappers.pb.h | 2 +- version.json | 20 ++++++++-------- 37 files changed, 69 insertions(+), 54 deletions(-) diff --git a/Protobuf-C++.podspec b/Protobuf-C++.podspec index 2043adbdec..8ab70d04ac 100644 --- a/Protobuf-C++.podspec +++ b/Protobuf-C++.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'Protobuf-C++' - s.version = '3.21.5' + s.version = '3.21.6' s.summary = 'Protocol Buffers v3 runtime library for C++.' s.homepage = 'https://github.com/google/protobuf' s.license = 'BSD-3-Clause' diff --git a/Protobuf.podspec b/Protobuf.podspec index eb87a8f81a..b3e843485e 100644 --- a/Protobuf.podspec +++ b/Protobuf.podspec @@ -5,7 +5,7 @@ # dependent projects use the :git notation to refer to the library. Pod::Spec.new do |s| s.name = 'Protobuf' - s.version = '3.21.5' + s.version = '3.21.6' s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.' s.homepage = 'https://github.com/protocolbuffers/protobuf' s.license = 'BSD-3-Clause' diff --git a/configure.ac b/configure.ac index 375a79d93a..c42fbc21ba 100644 --- a/configure.ac +++ b/configure.ac @@ -17,7 +17,7 @@ AC_PREREQ(2.59) # In the SVN trunk, the version should always be the next anticipated release # version with the "-pre" suffix. (We used to use "-SNAPSHOT" but this pushed # the size of one file name in the dist tarfile over the 99-char limit.) -AC_INIT([Protocol Buffers],[3.21.5],[protobuf@googlegroups.com],[protobuf]) +AC_INIT([Protocol Buffers],[3.21.6],[protobuf@googlegroups.com],[protobuf]) AM_MAINTAINER_MODE([enable]) diff --git a/csharp/Google.Protobuf.Tools.nuspec b/csharp/Google.Protobuf.Tools.nuspec index 5b71f9f040..096d0a47c1 100644 --- a/csharp/Google.Protobuf.Tools.nuspec +++ b/csharp/Google.Protobuf.Tools.nuspec @@ -5,7 +5,7 @@ Google Protocol Buffers tools Tools for Protocol Buffers - Google's data interchange format. See project site for more info. - 3.21.5 + 3.21.6 Google Inc. protobuf-packages https://github.com/protocolbuffers/protobuf/blob/main/LICENSE diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.csproj b/csharp/src/Google.Protobuf/Google.Protobuf.csproj index 35248481f2..33db8a8e0b 100644 --- a/csharp/src/Google.Protobuf/Google.Protobuf.csproj +++ b/csharp/src/Google.Protobuf/Google.Protobuf.csproj @@ -4,7 +4,7 @@ C# runtime library for Protocol Buffers - Google's data interchange format. Copyright 2015, Google Inc. Google Protocol Buffers - 3.21.5 + 3.21.6 7.2 Google Inc. diff --git a/java/README.md b/java/README.md index 3a022f0929..6a23c0d9e8 100644 --- a/java/README.md +++ b/java/README.md @@ -23,7 +23,7 @@ If you are using Maven, use the following: com.google.protobuf protobuf-java - 3.21.5 + 3.21.6 ``` @@ -37,7 +37,7 @@ protobuf-java-util package: com.google.protobuf protobuf-java-util - 3.21.5 + 3.21.6 ``` @@ -45,7 +45,7 @@ protobuf-java-util package: If you are using Gradle, add the following to your `build.gradle` file's dependencies: ``` - implementation 'com.google.protobuf:protobuf-java:3.21.5' + implementation 'com.google.protobuf:protobuf-java:3.21.6' ``` Again, be sure to check that the version number matches (or is newer than) the version number of protoc that you are using. diff --git a/java/bom/pom.xml b/java/bom/pom.xml index 4504729f9c..1196d3685c 100644 --- a/java/bom/pom.xml +++ b/java/bom/pom.xml @@ -4,7 +4,7 @@ com.google.protobuf protobuf-bom - 3.21.5 + 3.21.6 pom Protocol Buffers [BOM] diff --git a/java/core/pom.xml b/java/core/pom.xml index 9315004516..7e5e8df1d7 100644 --- a/java/core/pom.xml +++ b/java/core/pom.xml @@ -4,7 +4,7 @@ com.google.protobuf protobuf-parent - 3.21.5 + 3.21.6 protobuf-java diff --git a/java/kotlin-lite/pom.xml b/java/kotlin-lite/pom.xml index 03f28f5901..52bc1b3675 100644 --- a/java/kotlin-lite/pom.xml +++ b/java/kotlin-lite/pom.xml @@ -4,7 +4,7 @@ com.google.protobuf protobuf-parent - 3.21.5 + 3.21.6 protobuf-kotlin-lite diff --git a/java/kotlin/pom.xml b/java/kotlin/pom.xml index f2d034e9c8..ee949ddb4b 100644 --- a/java/kotlin/pom.xml +++ b/java/kotlin/pom.xml @@ -4,7 +4,7 @@ com.google.protobuf protobuf-parent - 3.21.5 + 3.21.6 protobuf-kotlin diff --git a/java/lite.md b/java/lite.md index 2445ec3a88..6f003ed543 100644 --- a/java/lite.md +++ b/java/lite.md @@ -29,7 +29,7 @@ protobuf Java Lite runtime. If you are using Maven, include the following: com.google.protobuf protobuf-javalite - 3.21.5 + 3.21.6 ``` diff --git a/java/lite/pom.xml b/java/lite/pom.xml index c5ef4abc0d..ba65f5cbf4 100644 --- a/java/lite/pom.xml +++ b/java/lite/pom.xml @@ -4,7 +4,7 @@ com.google.protobuf protobuf-parent - 3.21.5 + 3.21.6 protobuf-javalite diff --git a/java/pom.xml b/java/pom.xml index c086992432..6f1059f8d9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -4,7 +4,7 @@ com.google.protobuf protobuf-parent - 3.21.5 + 3.21.6 pom Protocol Buffers [Parent] diff --git a/java/util/pom.xml b/java/util/pom.xml index 987163247d..0f02bb84df 100644 --- a/java/util/pom.xml +++ b/java/util/pom.xml @@ -4,7 +4,7 @@ com.google.protobuf protobuf-parent - 3.21.5 + 3.21.6 protobuf-java-util diff --git a/php/ext/google/protobuf/package.xml b/php/ext/google/protobuf/package.xml index ccf1d414fd..4f0b8b4277 100644 --- a/php/ext/google/protobuf/package.xml +++ b/php/ext/google/protobuf/package.xml @@ -10,11 +10,11 @@ protobuf-packages@google.com yes - 2022-08-09 - + 2022-09-13 + - 3.21.5 - 3.21.5 + 3.21.6 + 3.21.6 stable @@ -1403,5 +1403,20 @@ G A release. + + + 3.21.6 + 3.21.6 + + + stable + stable + + 2022-09-13 + + BSD-3-Clause + + + diff --git a/php/ext/google/protobuf/protobuf.h b/php/ext/google/protobuf/protobuf.h index 836bb8b74e..4f14ab526a 100644 --- a/php/ext/google/protobuf/protobuf.h +++ b/php/ext/google/protobuf/protobuf.h @@ -127,7 +127,7 @@ ZEND_BEGIN_ARG_INFO_EX(arginfo_setter, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() -#define PHP_PROTOBUF_VERSION "3.21.5" +#define PHP_PROTOBUF_VERSION "3.21.6" // ptr -> PHP object cache. This is a weak map that caches lazily-created // wrapper objects around upb types: diff --git a/protobuf_version.bzl b/protobuf_version.bzl index 253aaac46d..fdd9b5fe57 100644 --- a/protobuf_version.bzl +++ b/protobuf_version.bzl @@ -1,3 +1,3 @@ -PROTOC_VERSION = '21.5' -PROTOBUF_JAVA_VERSION = '3.21.5' -PROTOBUF_PYTHON_VERSION = '4.21.5' +PROTOC_VERSION = '21.6' +PROTOBUF_JAVA_VERSION = '3.21.6' +PROTOBUF_PYTHON_VERSION = '4.21.6' diff --git a/protoc-artifacts/pom.xml b/protoc-artifacts/pom.xml index bdbf3fc334..8e81909771 100644 --- a/protoc-artifacts/pom.xml +++ b/protoc-artifacts/pom.xml @@ -8,7 +8,7 @@ com.google.protobuf protoc - 3.21.5 + 3.21.6 pom Protobuf Compiler diff --git a/python/google/protobuf/__init__.py b/python/google/protobuf/__init__.py index 4d288e20d0..9ba2b78c85 100644 --- a/python/google/protobuf/__init__.py +++ b/python/google/protobuf/__init__.py @@ -30,4 +30,4 @@ # Copyright 2007 Google Inc. All Rights Reserved. -__version__ = '4.21.5' +__version__ = '4.21.6' diff --git a/ruby/google-protobuf.gemspec b/ruby/google-protobuf.gemspec index 3d776fecea..9dc373ca3b 100644 --- a/ruby/google-protobuf.gemspec +++ b/ruby/google-protobuf.gemspec @@ -1,6 +1,6 @@ Gem::Specification.new do |s| s.name = "google-protobuf" - s.version = "3.21.5" + s.version = "3.21.6" git_tag = "v#{s.version.to_s.sub('.rc.', '-rc')}" # Converts X.Y.Z.rc.N to vX.Y.Z-rcN, used for the git tag s.licenses = ["BSD-3-Clause"] s.summary = "Protocol Buffers" diff --git a/ruby/pom.xml b/ruby/pom.xml index d56c99d785..4e07f84022 100644 --- a/ruby/pom.xml +++ b/ruby/pom.xml @@ -9,7 +9,7 @@ com.google.protobuf.jruby protobuf-jruby - 3.21.5 + 3.21.6 Protocol Buffer JRuby native extension Protocol Buffers are a way of encoding structured data in an efficient yet @@ -76,7 +76,7 @@ com.google.protobuf protobuf-java-util - 3.21.5 + 3.21.6 org.jruby diff --git a/src/Makefile.am b/src/Makefile.am index e6a7dc7fdd..3a6ecdc42e 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -18,7 +18,7 @@ else PTHREAD_DEF = endif -PROTOBUF_VERSION = 32:5:0 +PROTOBUF_VERSION = 32:6:0 if GCC # Turn on all warnings except for sign comparison (we ignore sign comparison diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h index 41ee5c2a90..ac51c9bcac 100644 --- a/src/google/protobuf/any.pb.h +++ b/src/google/protobuf/any.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h index 31c09b5c5f..348bac8882 100644 --- a/src/google/protobuf/api.pb.h +++ b/src/google/protobuf/api.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h index f2cff45738..97bf2f02b5 100644 --- a/src/google/protobuf/compiler/plugin.pb.h +++ b/src/google/protobuf/compiler/plugin.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h index 4129d0d2d5..2d9c790f57 100644 --- a/src/google/protobuf/descriptor.pb.h +++ b/src/google/protobuf/descriptor.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h index 83e780e2b3..c4a94c5394 100644 --- a/src/google/protobuf/duration.pb.h +++ b/src/google/protobuf/duration.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h index ca821f91a8..00a4481544 100644 --- a/src/google/protobuf/empty.pb.h +++ b/src/google/protobuf/empty.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h index ff9424f0f4..ecc6edee9a 100644 --- a/src/google/protobuf/field_mask.pb.h +++ b/src/google/protobuf/field_mask.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/port_def.inc b/src/google/protobuf/port_def.inc index e4b07537fb..8943a4454f 100644 --- a/src/google/protobuf/port_def.inc +++ b/src/google/protobuf/port_def.inc @@ -178,7 +178,7 @@ #ifdef PROTOBUF_VERSION #error PROTOBUF_VERSION was previously defined #endif -#define PROTOBUF_VERSION 3021005 +#define PROTOBUF_VERSION 3021006 #ifdef PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC #error PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC was previously defined diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h index 784fe1cdf3..e9c41bdea7 100644 --- a/src/google/protobuf/source_context.pb.h +++ b/src/google/protobuf/source_context.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h index cf7416c121..ac2d9716dd 100644 --- a/src/google/protobuf/struct.pb.h +++ b/src/google/protobuf/struct.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h index 427df67d4f..ebb1ca0e67 100644 --- a/src/google/protobuf/stubs/common.h +++ b/src/google/protobuf/stubs/common.h @@ -82,7 +82,7 @@ namespace internal { // The current version, represented as a single integer to make comparison // easier: major * 10^6 + minor * 10^3 + micro -#define GOOGLE_PROTOBUF_VERSION 3021005 +#define GOOGLE_PROTOBUF_VERSION 3021006 // A suffix string for alpha, beta or rc releases. Empty for stable releases. #define GOOGLE_PROTOBUF_VERSION_SUFFIX "" diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h index 14efcf185f..6633822791 100644 --- a/src/google/protobuf/timestamp.pb.h +++ b/src/google/protobuf/timestamp.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h index 19247b337c..0f11e6cd1b 100644 --- a/src/google/protobuf/type.pb.h +++ b/src/google/protobuf/type.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h index 1766742722..cc42a8ba5c 100644 --- a/src/google/protobuf/wrappers.pb.h +++ b/src/google/protobuf/wrappers.pb.h @@ -13,7 +13,7 @@ #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. diff --git a/version.json b/version.json index 25df6c1044..eed0a2a14b 100644 --- a/version.json +++ b/version.json @@ -1,17 +1,17 @@ { "21.x": { - "protoc_version": "21.6-dev", + "protoc_version": "21.6", "lts": false, - "date": "2022-08-09", + "date": "2022-09-13", "languages": { - "cpp": "3.21.6-dev", - "csharp": "3.21.6-dev", - "java": "3.21.6-dev", - "javascript": "3.21.6-dev", - "objectivec": "3.21.6-dev", - "php": "3.21.6-dev", - "python": "4.21.6-dev", - "ruby": "3.21.6-dev" + "cpp": "3.21.6", + "csharp": "3.21.6", + "java": "3.21.6", + "javascript": "3.21.6", + "objectivec": "3.21.6", + "php": "3.21.6", + "python": "4.21.6", + "ruby": "3.21.6" } } } \ No newline at end of file From aa8c73d845339c8e477df4a9ca5731ffc7c023c8 Mon Sep 17 00:00:00 2001 From: Deanna Garcia Date: Tue, 13 Sep 2022 21:21:48 +0000 Subject: [PATCH 08/64] Updating changelog --- CHANGES.txt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGES.txt b/CHANGES.txt index 264c72853b..4be9411211 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,8 @@ +2022-09-13 version 21.6 (C++/Java/Python/PHP/Objective-C/C#/Ruby) + +C++ +* Reduce memory consumption of MessageSet parsing + 2022-08-09 version 21.5 (C++/Java/Python/PHP/Objective-C/C#/Ruby) PHP From de7597e577320e3737b7585b0f9740adff423a4f Mon Sep 17 00:00:00 2001 From: zhangskz <89936743+zhangskz@users.noreply.github.com> Date: Wed, 27 Jul 2022 19:53:14 +0000 Subject: [PATCH 09/64] Update python/release.sh to handle delay between twine upload and pip install (#10324) --- python/release.sh | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/python/release.sh b/python/release.sh index 15a70db31f..87fcf8cfee 100755 --- a/python/release.sh +++ b/python/release.sh @@ -19,11 +19,24 @@ function run_install_test() { chmod +x test-venv/bin/protoc source test-venv/bin/activate - pip install -i ${PYPI} protobuf==${VERSION} --no-cache-dir + (pip install -i ${PYPI} protobuf==${VERSION} --no-cache-dir) || (retry_pip_install ${PYPI} ${VERSION}) deactivate rm -fr test-venv } +function retry_pip_install() { + local PYPI=$1 + local VERSION=$2 + + read -p "pip install failed, possibly due to delay between upload and availability on pip. Retry? [y/n]" -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + exit 1 + fi + + (pip install -i ${PYPI} protobuf==${VERSION} --no-cache-dir) || (retry_pip_install ${PYPI} ${VERSION}) +} + [ $# -lt 1 ] && { echo "Usage: $0 VERSION [" @@ -86,13 +99,16 @@ python3 setup.py test python3 setup.py sdist twine upload --skip-existing -r testpypi -u protobuf-wheel-test dist/* -# Test locally with different python versions. +# Sleep to allow time for distribution to be available on pip. +sleep 5m + +# Test locally. run_install_test ${TESTING_VERSION} python3 https://test.pypi.org/simple # Deploy egg/wheel packages to testing PyPI and test again. python3 setup.py clean build bdist_wheel twine upload --skip-existing -r testpypi -u protobuf-wheel-test dist/* - +sleep 5m run_install_test ${TESTING_VERSION} python3 https://test.pypi.org/simple echo "All install tests have passed using testing PyPI." From b1924e1de96f1e7bc617fe8b4dd52a29be6edaa2 Mon Sep 17 00:00:00 2001 From: Deanna Garcia Date: Wed, 14 Sep 2022 21:40:15 +0000 Subject: [PATCH 10/64] Update version.json to: 21.7-dev --- version.json | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/version.json b/version.json index eed0a2a14b..ade50a1b8a 100644 --- a/version.json +++ b/version.json @@ -1,17 +1,17 @@ { "21.x": { - "protoc_version": "21.6", + "protoc_version": "21.7-dev", "lts": false, - "date": "2022-09-13", + "date": "2022-09-14", "languages": { - "cpp": "3.21.6", - "csharp": "3.21.6", - "java": "3.21.6", - "javascript": "3.21.6", - "objectivec": "3.21.6", - "php": "3.21.6", - "python": "4.21.6", - "ruby": "3.21.6" + "cpp": "3.21.7-dev", + "csharp": "3.21.7-dev", + "java": "3.21.7-dev", + "javascript": "3.21.7-dev", + "objectivec": "3.21.7-dev", + "php": "3.21.7-dev", + "python": "4.21.7-dev", + "ruby": "3.21.7-dev" } } } \ No newline at end of file From c23d0b87c50cb9655c230d637c5430f25d76cbe4 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 14 Sep 2022 14:04:12 -0400 Subject: [PATCH 11/64] add check for custom JSON name conflicts - also, include check for default JSON name conflicts even in proto2 files (but only warn) - if custom JSON name conflicts with other default name, only a warning in proto2 --- src/google/protobuf/descriptor.cc | 116 +++++++++++++++++++++--------- 1 file changed, 81 insertions(+), 35 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index ddebcf6184..43d7492b9b 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -3847,8 +3847,6 @@ class DescriptorBuilder { internal::FlatAllocator& alloc); void BuildOneof(const OneofDescriptorProto& proto, Descriptor* parent, OneofDescriptor* result, internal::FlatAllocator& alloc); - void CheckEnumValueUniqueness(const EnumDescriptorProto& proto, - const EnumDescriptor* result); void BuildEnum(const EnumDescriptorProto& proto, const Descriptor* parent, EnumDescriptor* result, internal::FlatAllocator& alloc); void BuildEnumValue(const EnumValueDescriptorProto& proto, @@ -3860,6 +3858,14 @@ class DescriptorBuilder { const ServiceDescriptor* parent, MethodDescriptor* result, internal::FlatAllocator& alloc); + void CheckFieldJSONNameUniqueness(const DescriptorProto& proto, + const Descriptor* result); + void CheckFieldJSONNameUniqueness(std::string message_name, + const DescriptorProto& message, + bool is_proto2, bool use_custom_names); + void CheckEnumValueUniqueness(const EnumDescriptorProto& proto, + const EnumDescriptor* result); + void LogUnusedDependency(const FileDescriptorProto& proto, const FileDescriptor* result); @@ -5415,7 +5421,10 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, } } + CheckFieldJSONNameUniqueness(proto, result); + // Check that fields aren't using reserved names or numbers and that they + // aren't using extension numbers. for (int i = 0; i < result->field_count(); i++) { const FieldDescriptor* field = result->field(i); for (int j = 0; j < result->extension_range_count(); j++) { @@ -5480,6 +5489,75 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, } } +std::string GetJSONName(const FieldDescriptorProto& field, bool use_custom, bool* was_custom) { + if (use_custom && field.has_json_name()) { + *was_custom = true; + return field.json_name(); + } + *was_custom = false; + return ToJsonName(field.name()); +} + +void DescriptorBuilder::CheckFieldJSONNameUniqueness( + const DescriptorProto& proto, const Descriptor* result) { + bool is_proto2 = result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2; + std::string message_name = result->full_name(); + // two passes: one looking only at default JSON names, and one that considers custom JSON names + CheckFieldJSONNameUniqueness(message_name, proto, is_proto2, false); + CheckFieldJSONNameUniqueness(message_name, proto, is_proto2, true); +} + +struct JSONNameDetails { + const FieldDescriptorProto* field; + std::string orig_name; + bool is_custom; +}; + +void DescriptorBuilder::CheckFieldJSONNameUniqueness( + std::string message_name,const DescriptorProto& message, bool is_proto2, bool use_custom_names) { + + std::map name_to_field; + for (int i = 0; i < message.field_size(); ++i) { + bool is_custom; + std::string name = GetJSONName(message.field(i), use_custom_names, &is_custom); + std::string lowercase_name = absl::AsciiStrToLower(name); + auto existing = name_to_field.find(lowercase_name); + if (existing != name_to_field.end()) { + auto match = existing->second; + if (use_custom_names && !is_custom && !match.is_custom) { + // if this pass is considering custom JSON names, but neither of the + // names involved in the conflict are custom, don't bother with a message. + // That will have been reported from other pass (non-custom JSON names). + continue; + } + std::string this_type = is_custom ? "custom" : "default"; + std::string existing_type = match.is_custom ? "custom" : "default"; + // If the matched name differs (which it can only differ in case), include it + // in the error message, for maximum clarity to user. + std::string name_suffix = name == match.orig_name ? "" : " (\"" + match.orig_name + "\")"; + std::string error_message = + "The " + this_type + " JSON name of field \"" + message.field(i).name() + + "\" (\"" + name + "\") conflicts with the " + existing_type + " JSON name of field \"" + + match.field->name() + "\"" + name_suffix + "."; + + bool involves_default = !is_custom || !match.is_custom; + if (is_proto2 && involves_default) { + AddWarning(message_name, message.field(i), + DescriptorPool::ErrorCollector::NAME, error_message); + } else { + if (involves_default) { + error_message += " This is not allowed in proto3."; + } + AddError(message_name, message.field(i), + DescriptorPool::ErrorCollector::NAME, error_message); + } + } else { + struct JSONNameDetails details = { &message.field(i), name, is_custom }; + name_to_field[lowercase_name] = details; + } + } +} + void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, Descriptor* parent, FieldDescriptor* result, @@ -5913,6 +5991,7 @@ void DescriptorBuilder::CheckEnumValueUniqueness( AddWarning(value->full_name(), proto.value(i), DescriptorPool::ErrorCollector::NAME, error_message); } else { + error_message += " This is not allowed in proto3."; AddError(value->full_name(), proto.value(i), DescriptorPool::ErrorCollector::NAME, error_message); } @@ -6779,20 +6858,6 @@ void DescriptorBuilder::ValidateProto3(FileDescriptor* file, } } -static std::string ToLowercaseWithoutUnderscores(const std::string& name) { - std::string result; - for (char character : name) { - if (character != '_') { - if (character >= 'A' && character <= 'Z') { - result.push_back(character - 'A' + 'a'); - } else { - result.push_back(character); - } - } - } - return result; -} - void DescriptorBuilder::ValidateProto3Message(Descriptor* message, const DescriptorProto& proto) { for (int i = 0; i < message->nested_type_count(); ++i) { @@ -6817,25 +6882,6 @@ void DescriptorBuilder::ValidateProto3Message(Descriptor* message, AddError(message->full_name(), proto, DescriptorPool::ErrorCollector::NAME, "MessageSet is not supported in proto3."); } - - // In proto3, we reject field names if they conflict in camelCase. - // Note that we currently enforce a stricter rule: Field names must be - // unique after being converted to lowercase with underscores removed. - std::map name_to_field; - for (int i = 0; i < message->field_count(); ++i) { - std::string lowercase_name = - ToLowercaseWithoutUnderscores(message->field(i)->name()); - if (name_to_field.find(lowercase_name) != name_to_field.end()) { - AddError(message->full_name(), proto.field(i), - DescriptorPool::ErrorCollector::NAME, - "The JSON camel-case name of field \"" + - message->field(i)->name() + "\" conflicts with field \"" + - name_to_field[lowercase_name]->name() + "\". This is not " + - "allowed in proto3."); - } else { - name_to_field[lowercase_name] = message->field(i); - } - } } void DescriptorBuilder::ValidateProto3Field(FieldDescriptor* field, From cbd5c84b6b8b07e01ee63ade2c4c2f76dfd3ee2c Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 14 Sep 2022 18:06:31 -0400 Subject: [PATCH 12/64] update existing test expectations and add new tests --- .../protobuf/compiler/parser_unittest.cc | 84 ++++++++++++++++++- src/google/protobuf/descriptor.cc | 5 +- src/google/protobuf/descriptor_unittest.cc | 35 ++++---- 3 files changed, 100 insertions(+), 24 deletions(-) diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 3b32451916..568a699727 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -1977,8 +1977,88 @@ TEST_F(ParserValidationErrorTest, Proto3JsonConflictError) { " uint32 foo = 1;\n" " uint32 Foo = 2;\n" "}\n", - "3:9: The JSON camel-case name of field \"Foo\" conflicts with field " - "\"foo\". This is not allowed in proto3.\n"); + "3:9: The default JSON name of field \"Foo\" (\"Foo\") conflicts " + "with the default JSON name of field \"foo\" (\"foo\"). " + "This is not allowed in proto3.\n"); +} + +TEST_F(ParserValidationErrorTest, Proto2JsonConflictError) { + // conflicts with default JSON names are not errors in proto2 + ExpectParsesTo( + "syntax = 'proto2';\n" + "message TestMessage {\n" + " optional uint32 foo = 1;\n" + " optional uint32 Foo = 2;\n" + "}\n", + + "syntax: 'proto2'" + "message_type {" + " name: 'TestMessage'" + " field {" + " label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'foo' number: 1" + " }" + " field {" + " label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'Foo' number: 2" + " }" + "}" + ); +} + +TEST_F(ParserValidationErrorTest, Proto3CustomJsonConflictWithDefaultError) { + ExpectHasValidationErrors( + "syntax = 'proto3';\n" + "message TestMessage {\n" + " uint32 foo = 1 [json_name='bar'];\n" + " uint32 bar = 2;\n" + "}\n", + "3:9: The default JSON name of field \"bar\" (\"bar\") conflicts " + "with the custom JSON name of field \"foo\". " + "This is not allowed in proto3.\n"); +} + +TEST_F(ParserValidationErrorTest, Proto2CustomJsonConflictWithDefaultError) { + // conflicts with default JSON names are not errors in proto2 + ExpectParsesTo( + "syntax = 'proto2';\n" + "message TestMessage {\n" + " optional uint32 foo = 1 [json_name='bar'];\n" + " optional uint32 bar = 2;\n" + "}\n", + + "syntax: 'proto2'" + "message_type {" + " name: 'TestMessage'" + " field {" + " label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'foo' number: 1 json_name: 'bar'" + " }" + " field {" + " label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'bar' number: 2" + " }" + "}" + ); +} + +TEST_F(ParserValidationErrorTest, Proto3CustomJsonConflictError) { + ExpectHasValidationErrors( + "syntax = 'proto3';\n" + "message TestMessage {\n" + " uint32 foo = 1 [json_name='baz'];\n" + " uint32 bar = 2 [json_name='baz'];\n" + "}\n", + "3:9: The custom JSON name of field \"bar\" (\"baz\") conflicts " + "with the custom JSON name of field \"foo\".\n"); +} + +TEST_F(ParserValidationErrorTest, Proto2CustomJsonConflictError) { + ExpectHasValidationErrors( + "syntax = 'proto2';\n" + "message TestMessage {\n" + " optional uint32 foo = 1 [json_name='baz'];\n" + " optional uint32 bar = 2 [json_name='baz'];\n" + "}\n", + // fails in proto2 also: can't explicitly configure bad custom JSON names + "3:18: The custom JSON name of field \"bar\" (\"baz\") conflicts " + "with the custom JSON name of field \"foo\".\n"); } TEST_F(ParserValidationErrorTest, EnumNameError) { diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 43d7492b9b..ad5eb8db2c 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -5982,9 +5982,8 @@ void DescriptorBuilder::CheckEnumValueUniqueness( "Enum name " + value->name() + " has the same name as " + values[stripped]->name() + " if you ignore case and strip out the enum name prefix (if any). " - "This is error-prone and can lead to undefined behavior. " - "Please avoid doing this. If you are using allow_alias, please " - "assign the same numeric value to both enums."; + "(If you are using allow_alias, please assign the same numeric " + "value to both enums.)"; // There are proto2 enums out there with conflicting names, so to preserve // compatibility we issue only a warning for proto2. if (result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2) { diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index a2900454f6..cc05addf97 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -6411,9 +6411,8 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWithDifferentCasing) { "}", "foo.proto: bar: NAME: Enum name bar has the same name as BAR " "if you ignore case and strip out the enum name prefix (if any). " - "This is error-prone and can lead to undefined behavior. " - "Please avoid doing this. If you are using allow_alias, please assign " - "the same numeric value to both enums.\n"); + "(If you are using allow_alias, please assign the same numeric " + "value to both enums.) This is not allowed in proto3.\n"); // Not an error because both enums are mapped to the same value. BuildFile( @@ -6439,9 +6438,8 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { "}", "foo.proto: BAZ: NAME: Enum name BAZ has the same name as FOO_ENUM_BAZ " "if you ignore case and strip out the enum name prefix (if any). " - "This is error-prone and can lead to undefined behavior. " - "Please avoid doing this. If you are using allow_alias, please assign " - "the same numeric value to both enums.\n"); + "(If you are using allow_alias, please assign the same numeric value " + "to both enums.) This is not allowed in proto3.\n"); BuildFileWithErrors( "syntax: 'proto3'" @@ -6453,9 +6451,8 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { "}", "foo.proto: BAZ: NAME: Enum name BAZ has the same name as FOOENUM_BAZ " "if you ignore case and strip out the enum name prefix (if any). " - "This is error-prone and can lead to undefined behavior. " - "Please avoid doing this. If you are using allow_alias, please assign " - "the same numeric value to both enums.\n"); + "(If you are using allow_alias, please assign the same numeric value " + "to both enums.) This is not allowed in proto3.\n"); BuildFileWithErrors( "syntax: 'proto3'" @@ -6467,9 +6464,8 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { "}", "foo.proto: BAR__BAZ: NAME: Enum name BAR__BAZ has the same name as " "FOO_ENUM_BAR_BAZ if you ignore case and strip out the enum name prefix " - "(if any). This is error-prone and can lead to undefined behavior. " - "Please avoid doing this. If you are using allow_alias, please assign " - "the same numeric value to both enums.\n"); + "(if any). (If you are using allow_alias, please assign the same numeric " + "value to both enums.) This is not allowed in proto3.\n"); BuildFileWithErrors( "syntax: 'proto3'" @@ -6481,9 +6477,8 @@ TEST_F(ValidationErrorTest, EnumValuesConflictWhenPrefixesStripped) { "}", "foo.proto: BAR_BAZ: NAME: Enum name BAR_BAZ has the same name as " "FOO_ENUM__BAR_BAZ if you ignore case and strip out the enum name prefix " - "(if any). This is error-prone and can lead to undefined behavior. " - "Please avoid doing this. If you are using allow_alias, please assign " - "the same numeric value to both enums.\n"); + "(if any). (If you are using allow_alias, please assign the same numeric " + "value to both enums.) This is not allowed in proto3.\n"); // This isn't an error because the underscore will cause the PascalCase to // differ by case (BarBaz vs. Barbaz). @@ -6828,8 +6823,9 @@ TEST_F(ValidationErrorTest, ValidateProto3JsonName) { " field { name:'name' number:1 label:LABEL_OPTIONAL type:TYPE_INT32 }" " field { name:'Name' number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" "}", - "foo.proto: Foo: NAME: The JSON camel-case name of field \"Name\" " - "conflicts with field \"name\". This is not allowed in proto3.\n"); + "foo.proto: Foo: NAME: The default JSON name of field \"Name\" (\"Name\") " + "conflicts with the default JSON name of field \"name\" (\"name\"). This is " + "not allowed in proto3.\n"); // Underscores are ignored. BuildFileWithErrors( "name: 'foo.proto' " @@ -6839,8 +6835,9 @@ TEST_F(ValidationErrorTest, ValidateProto3JsonName) { " field { name:'ab' number:1 label:LABEL_OPTIONAL type:TYPE_INT32 }" " field { name:'_a__b_' number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" "}", - "foo.proto: Foo: NAME: The JSON camel-case name of field \"_a__b_\" " - "conflicts with field \"ab\". This is not allowed in proto3.\n"); + "foo.proto: Foo: NAME: The default JSON name of field \"_a__b_\" (\"AB\") " + "conflicts with the default JSON name of field \"ab\" (\"ab\"). This is not " + "allowed in proto3.\n"); } From 2270d3f93ce3040380fa470807ce60db28c1339f Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Tue, 13 Sep 2022 16:17:10 -0400 Subject: [PATCH 13/64] allow excessively large int literal values (that would otherwise overflow uint64 or underflow int64) to be used as float/double values --- src/google/protobuf/compiler/parser.cc | 43 +++++++++++++++++--------- src/google/protobuf/compiler/parser.h | 3 ++ 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index 4cae1a1187..e5f42c4506 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -288,6 +288,16 @@ bool Parser::ConsumeInteger64(uint64_t max_value, uint64_t* output, } } +bool Parser::TryConsumeInteger64(uint64_t max_value, uint64_t* output) { + if (LookingAtType(io::Tokenizer::TYPE_INTEGER) && + io::Tokenizer::ParseInteger(input_->current().text, max_value, + output)) { + input_->Next(); + return true; + } + return false; +} + bool Parser::ConsumeNumber(double* output, const char* error) { if (LookingAtType(io::Tokenizer::TYPE_FLOAT)) { *output = io::Tokenizer::ParseFloat(input_->current().text); @@ -296,13 +306,14 @@ bool Parser::ConsumeNumber(double* output, const char* error) { } else if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { // Also accept integers. uint64_t value = 0; - if (!io::Tokenizer::ParseInteger(input_->current().text, + if (io::Tokenizer::ParseInteger(input_->current().text, std::numeric_limits::max(), &value)) { - AddError("Integer out of range."); - // We still return true because we did, in fact, parse a number. + *output = value; + } else { + // out of int range, treat as double literal + *output = io::Tokenizer::ParseFloat(input_->current().text); } - *output = value; input_->Next(); return true; } else if (LookingAt("inf")) { @@ -1551,18 +1562,20 @@ bool Parser::ParseOption(Message* options, is_negative ? static_cast(std::numeric_limits::max()) + 1 : std::numeric_limits::max(); - DO(ConsumeInteger64(max_value, &value, "Expected integer.")); - if (is_negative) { - value_location.AddPath( - UninterpretedOption::kNegativeIntValueFieldNumber); - uninterpreted_option->set_negative_int_value( - static_cast(0 - value)); - } else { - value_location.AddPath( - UninterpretedOption::kPositiveIntValueFieldNumber); - uninterpreted_option->set_positive_int_value(value); + if (TryConsumeInteger64(max_value, &value)) { + if (is_negative) { + value_location.AddPath( + UninterpretedOption::kNegativeIntValueFieldNumber); + uninterpreted_option->set_negative_int_value( + static_cast(0 - value)); + } else { + value_location.AddPath( + UninterpretedOption::kPositiveIntValueFieldNumber); + uninterpreted_option->set_positive_int_value(value); + } + break; } - break; + // value too large for an integer; fall through below to treat as floating point } case io::Tokenizer::TYPE_FLOAT: { diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index ccd3e5a5f7..a5649fd587 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -180,6 +180,9 @@ class PROTOBUF_EXPORT Parser { // is greater than max_value, an error will be reported. bool ConsumeInteger64(uint64_t max_value, uint64_t* output, const char* error); + // Try to consume a 64-bit integer and store its value in "output". No + // error is reported on failure, allowing caller to consume token another way. + bool TryConsumeInteger64(uint64_t max_value, uint64_t* output); // Consume a number and store its value in "output". This will accept // tokens of either INTEGER or FLOAT type. bool ConsumeNumber(double* output, const char* error); From 87f24e47595ef5e382949346e50a81150d35c230 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Tue, 13 Sep 2022 16:32:48 -0400 Subject: [PATCH 14/64] add allowed ranges to error messages --- src/google/protobuf/descriptor.cc | 18 ++++++++---------- src/google/protobuf/descriptor_unittest.cc | 16 ++++++++-------- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index ddebcf6184..0e43bc3af6 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -7683,7 +7683,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > static_cast(std::numeric_limits::max())) { - return AddValueError("Value out of range for int32 option \"" + + return AddValueError("Value out of range, -2,147,483,648 to 2,147,483,647, for int32 option \"" + option_field->full_name() + "\"."); } else { SetInt32(option_field->number(), @@ -7693,7 +7693,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( } else if (uninterpreted_option_->has_negative_int_value()) { if (uninterpreted_option_->negative_int_value() < static_cast(std::numeric_limits::min())) { - return AddValueError("Value out of range for int32 option \"" + + return AddValueError("Value out of range, -2,147,483,648 to 2,147,483,647, for int32 option \"" + option_field->full_name() + "\"."); } else { SetInt32(option_field->number(), @@ -7701,7 +7701,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( option_field->type(), unknown_fields); } } else { - return AddValueError("Value must be integer for int32 option \"" + + return AddValueError("Value must be integer, from -2,147,483,648 to 2,147,483,647, for int32 option \"" + option_field->full_name() + "\"."); } break; @@ -7710,7 +7710,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > static_cast(std::numeric_limits::max())) { - return AddValueError("Value out of range for int64 option \"" + + return AddValueError("Value out of range, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, for int64 option \"" + option_field->full_name() + "\"."); } else { SetInt64(option_field->number(), @@ -7722,7 +7722,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( uninterpreted_option_->negative_int_value(), option_field->type(), unknown_fields); } else { - return AddValueError("Value must be integer for int64 option \"" + + return AddValueError("Value must be integer, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, for int64 option \"" + option_field->full_name() + "\"."); } break; @@ -7731,7 +7731,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > std::numeric_limits::max()) { - return AddValueError("Value out of range for uint32 option \"" + + return AddValueError("Value out of range, 0 to 4,294,967,295, for uint32 option \"" + option_field->name() + "\"."); } else { SetUInt32(option_field->number(), @@ -7740,8 +7740,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( } } else { return AddValueError( - "Value must be non-negative integer for uint32 " - "option \"" + + "Value must be integer, from 0 to 4,294,967,295, for uint32 option \"" + option_field->full_name() + "\"."); } break; @@ -7753,8 +7752,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( option_field->type(), unknown_fields); } else { return AddValueError( - "Value must be non-negative integer for uint64 " - "option \"" + + "Value must be integer, from 0 to 18,446,744,073,709,551,615, for uint64 option \"" + option_field->full_name() + "\"."); } break; diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index a2900454f6..33d4299fb6 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -5557,7 +5557,7 @@ TEST_F(ValidationErrorTest, Int32OptionValueOutOfPositiveRange) { " positive_int_value: 0x80000000 } " "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " + "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -2,147,483,648 to 2,147,483,647, " "for int32 option \"foo\".\n"); } @@ -5574,7 +5574,7 @@ TEST_F(ValidationErrorTest, Int32OptionValueOutOfNegativeRange) { " negative_int_value: -0x80000001 } " "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " + "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -2,147,483,648 to 2,147,483,647, " "for int32 option \"foo\".\n"); } @@ -5590,7 +5590,7 @@ TEST_F(ValidationErrorTest, Int32OptionValueIsNotPositiveInt) { " is_extension: true } " " string_value: \"5\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer " + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from -2,147,483,648 to 2,147,483,647, " "for int32 option \"foo\".\n"); } @@ -5608,7 +5608,7 @@ TEST_F(ValidationErrorTest, Int64OptionValueOutOfRange) { "} " "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " + "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, " "for int64 option \"foo\".\n"); } @@ -5624,7 +5624,7 @@ TEST_F(ValidationErrorTest, Int64OptionValueIsNotPositiveInt) { " is_extension: true } " " identifier_value: \"5\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer " + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, " "for int64 option \"foo\".\n"); } @@ -5640,7 +5640,7 @@ TEST_F(ValidationErrorTest, UInt32OptionValueOutOfRange) { " is_extension: true } " " positive_int_value: 0x100000000 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " + "foo.proto: foo.proto: OPTION_VALUE: Value out of range, 0 to 4,294,967,295, " "for uint32 option \"foo\".\n"); } @@ -5656,7 +5656,7 @@ TEST_F(ValidationErrorTest, UInt32OptionValueIsNotPositiveInt) { " is_extension: true } " " double_value: -5.6 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be non-negative integer " + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from 0 to 4,294,967,295, " "for uint32 option \"foo\".\n"); } @@ -5672,7 +5672,7 @@ TEST_F(ValidationErrorTest, UInt64OptionValueIsNotPositiveInt) { " is_extension: true } " " negative_int_value: -5 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be non-negative integer " + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from 0 to 18,446,744,073,709,551,615, " "for uint64 option \"foo\".\n"); } From 4e54ec20d12aaf6868638ceaab4d1c8c17f4d4e8 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 14 Sep 2022 15:16:51 -0400 Subject: [PATCH 15/64] change format of int range in error message; use macro to make DRY --- src/google/protobuf/descriptor.cc | 35 +++++++++++----------- src/google/protobuf/descriptor_unittest.cc | 16 +++++----- 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 0e43bc3af6..cd40584b37 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -58,6 +58,7 @@ #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" #include "google/protobuf/stubs/stringprintf.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" @@ -7675,6 +7676,14 @@ bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( return true; } +#define VALUE_OUT_OF_RANGE(T, NAME) absl::StrFormat( \ + "Value out of range, %d to %d, for " #T " option \"%s\".", \ + std::numeric_limits::min(), std::numeric_limits::max(), NAME) + +#define VALUE_MUST_BE_INT(T, NAME) absl::StrFormat( \ + "Value must be integer, from %d to %d, for " #T " option \"%s\".", \ + std::numeric_limits::min(), std::numeric_limits::max(), NAME) + bool DescriptorBuilder::OptionInterpreter::SetOptionValue( const FieldDescriptor* option_field, UnknownFieldSet* unknown_fields) { // We switch on the CppType to validate. @@ -7683,8 +7692,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > static_cast(std::numeric_limits::max())) { - return AddValueError("Value out of range, -2,147,483,648 to 2,147,483,647, for int32 option \"" + - option_field->full_name() + "\"."); + return AddValueError(VALUE_OUT_OF_RANGE(int32, option_field->full_name())); } else { SetInt32(option_field->number(), uninterpreted_option_->positive_int_value(), @@ -7693,16 +7701,14 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( } else if (uninterpreted_option_->has_negative_int_value()) { if (uninterpreted_option_->negative_int_value() < static_cast(std::numeric_limits::min())) { - return AddValueError("Value out of range, -2,147,483,648 to 2,147,483,647, for int32 option \"" + - option_field->full_name() + "\"."); + return AddValueError(VALUE_OUT_OF_RANGE(int32, option_field->full_name())); } else { SetInt32(option_field->number(), uninterpreted_option_->negative_int_value(), option_field->type(), unknown_fields); } } else { - return AddValueError("Value must be integer, from -2,147,483,648 to 2,147,483,647, for int32 option \"" + - option_field->full_name() + "\"."); + return AddValueError(VALUE_MUST_BE_INT(int32, option_field->full_name())); } break; @@ -7710,8 +7716,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > static_cast(std::numeric_limits::max())) { - return AddValueError("Value out of range, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, for int64 option \"" + - option_field->full_name() + "\"."); + return AddValueError(VALUE_OUT_OF_RANGE(int64, option_field->full_name())); } else { SetInt64(option_field->number(), uninterpreted_option_->positive_int_value(), @@ -7722,8 +7727,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( uninterpreted_option_->negative_int_value(), option_field->type(), unknown_fields); } else { - return AddValueError("Value must be integer, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, for int64 option \"" + - option_field->full_name() + "\"."); + return AddValueError(VALUE_MUST_BE_INT(int64, option_field->full_name())); } break; @@ -7731,17 +7735,14 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > std::numeric_limits::max()) { - return AddValueError("Value out of range, 0 to 4,294,967,295, for uint32 option \"" + - option_field->name() + "\"."); + return AddValueError(VALUE_OUT_OF_RANGE(uint32, option_field->full_name())); } else { SetUInt32(option_field->number(), uninterpreted_option_->positive_int_value(), option_field->type(), unknown_fields); } } else { - return AddValueError( - "Value must be integer, from 0 to 4,294,967,295, for uint32 option \"" + - option_field->full_name() + "\"."); + return AddValueError(VALUE_MUST_BE_INT(uint32, option_field->full_name())); } break; @@ -7751,9 +7752,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( uninterpreted_option_->positive_int_value(), option_field->type(), unknown_fields); } else { - return AddValueError( - "Value must be integer, from 0 to 18,446,744,073,709,551,615, for uint64 option \"" + - option_field->full_name() + "\"."); + return AddValueError(VALUE_MUST_BE_INT(uint64, option_field->full_name())); } break; diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index 33d4299fb6..8079a26895 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -5557,7 +5557,7 @@ TEST_F(ValidationErrorTest, Int32OptionValueOutOfPositiveRange) { " positive_int_value: 0x80000000 } " "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -2,147,483,648 to 2,147,483,647, " + "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -2147483648 to 2147483647, " "for int32 option \"foo\".\n"); } @@ -5574,7 +5574,7 @@ TEST_F(ValidationErrorTest, Int32OptionValueOutOfNegativeRange) { " negative_int_value: -0x80000001 } " "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -2,147,483,648 to 2,147,483,647, " + "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -2147483648 to 2147483647, " "for int32 option \"foo\".\n"); } @@ -5590,7 +5590,7 @@ TEST_F(ValidationErrorTest, Int32OptionValueIsNotPositiveInt) { " is_extension: true } " " string_value: \"5\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from -2,147,483,648 to 2,147,483,647, " + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from -2147483648 to 2147483647, " "for int32 option \"foo\".\n"); } @@ -5608,7 +5608,7 @@ TEST_F(ValidationErrorTest, Int64OptionValueOutOfRange) { "} " "}", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, " + "foo.proto: foo.proto: OPTION_VALUE: Value out of range, -9223372036854775808 to 9223372036854775807, " "for int64 option \"foo\".\n"); } @@ -5624,7 +5624,7 @@ TEST_F(ValidationErrorTest, Int64OptionValueIsNotPositiveInt) { " is_extension: true } " " identifier_value: \"5\" } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, " + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from -9223372036854775808 to 9223372036854775807, " "for int64 option \"foo\".\n"); } @@ -5640,7 +5640,7 @@ TEST_F(ValidationErrorTest, UInt32OptionValueOutOfRange) { " is_extension: true } " " positive_int_value: 0x100000000 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value out of range, 0 to 4,294,967,295, " + "foo.proto: foo.proto: OPTION_VALUE: Value out of range, 0 to 4294967295, " "for uint32 option \"foo\".\n"); } @@ -5656,7 +5656,7 @@ TEST_F(ValidationErrorTest, UInt32OptionValueIsNotPositiveInt) { " is_extension: true } " " double_value: -5.6 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from 0 to 4,294,967,295, " + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from 0 to 4294967295, " "for uint32 option \"foo\".\n"); } @@ -5672,7 +5672,7 @@ TEST_F(ValidationErrorTest, UInt64OptionValueIsNotPositiveInt) { " is_extension: true } " " negative_int_value: -5 } }", - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from 0 to 18,446,744,073,709,551,615, " + "foo.proto: foo.proto: OPTION_VALUE: Value must be integer, from 0 to 18446744073709551615, " "for uint64 option \"foo\".\n"); } From 35dd193f4787983a69911cb5f0afd6a7763b820a Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 14 Sep 2022 16:25:14 -0400 Subject: [PATCH 16/64] add test to verify parsing of extremely large decimal integers to double values --- .../protobuf/compiler/parser_unittest.cc | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 3b32451916..7685371c14 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -592,6 +592,56 @@ TEST_F(ParseMessageTest, FieldOptions) { "}"); } +TEST_F(ParseMessageTest, FieldOptionsSupportLargeDecimalLiteral) { + // decimal integer literal > uint64 max + ExpectParsesTo( + "import \"google/protobuf/descriptor.proto\";\n" + "extend google.protobuf.FieldOptions {\n" + " optional double f = 10101;\n" + "}\n" + "message TestMessage {\n" + " optional double a = 1 [default = 18446744073709551616];\n" + " optional double b = 2 [default = -18446744073709551616];\n" + " optional double c = 3 [(f) = 18446744073709551616];\n" + " optional double d = 4 [(f) = -18446744073709551616];\n" + "}\n", + + "dependency: \"google/protobuf/descriptor.proto\"" + "extension {" + " name: \"f\" label: LABEL_OPTIONAL type: TYPE_DOUBLE number: 10101" + " extendee: \"google.protobuf.FieldOptions\"" + "}" + "message_type {" + " name: \"TestMessage\"" + " field {" + " name: \"a\" label: LABEL_OPTIONAL type: TYPE_DOUBLE number: 1" + " default_value: \"1.8446744073709552e+19\"" + " }" + " field {" + " name: \"b\" label: LABEL_OPTIONAL type: TYPE_DOUBLE number: 2" + " default_value: \"-1.8446744073709552e+19\"" + " }" + " field {" + " name: \"c\" label: LABEL_OPTIONAL type: TYPE_DOUBLE number: 3" + " options{" + " uninterpreted_option{" + " name{ name_part: \"f\" is_extension: true }" + " double_value: 1.8446744073709552e+19" + " }" + " }" + " }" + " field {" + " name: \"d\" label: LABEL_OPTIONAL type: TYPE_DOUBLE number: 4" + " options{" + " uninterpreted_option{" + " name{ name_part: \"f\" is_extension: true }" + " double_value: -1.8446744073709552e+19" + " }" + " }" + " }" + "}"); +} + TEST_F(ParseMessageTest, Oneof) { ExpectParsesTo( "message TestMessage {\n" From 4c69337faab5cd7a6bd040dbae841e21873004c0 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 14 Sep 2022 20:11:19 -0400 Subject: [PATCH 17/64] use template instead of macro --- src/google/protobuf/descriptor.cc | 36 +++++++++++++++++++------------ 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index cd40584b37..b2841ce6ef 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -7676,13 +7676,21 @@ bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( return true; } -#define VALUE_OUT_OF_RANGE(T, NAME) absl::StrFormat( \ - "Value out of range, %d to %d, for " #T " option \"%s\".", \ - std::numeric_limits::min(), std::numeric_limits::max(), NAME) +template std::string ValueOutOfRange( + std::string type_name, std::string option_name) { + return absl::StrFormat( + "Value out of range, %d to %d, for %s option \"%s\".", \ + std::numeric_limits::min(), std::numeric_limits::max(), + type_name, option_name); +} -#define VALUE_MUST_BE_INT(T, NAME) absl::StrFormat( \ - "Value must be integer, from %d to %d, for " #T " option \"%s\".", \ - std::numeric_limits::min(), std::numeric_limits::max(), NAME) +template std::string ValueMustBeInt( + std::string type_name, std::string option_name) { + return absl::StrFormat( + "Value must be integer, from %d to %d, for %s option \"%s\".", \ + std::numeric_limits::min(), std::numeric_limits::max(), + type_name, option_name); +} bool DescriptorBuilder::OptionInterpreter::SetOptionValue( const FieldDescriptor* option_field, UnknownFieldSet* unknown_fields) { @@ -7692,7 +7700,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > static_cast(std::numeric_limits::max())) { - return AddValueError(VALUE_OUT_OF_RANGE(int32, option_field->full_name())); + return AddValueError(ValueOutOfRange("int32", option_field->full_name())); } else { SetInt32(option_field->number(), uninterpreted_option_->positive_int_value(), @@ -7701,14 +7709,14 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( } else if (uninterpreted_option_->has_negative_int_value()) { if (uninterpreted_option_->negative_int_value() < static_cast(std::numeric_limits::min())) { - return AddValueError(VALUE_OUT_OF_RANGE(int32, option_field->full_name())); + return AddValueError(ValueOutOfRange("int32", option_field->full_name())); } else { SetInt32(option_field->number(), uninterpreted_option_->negative_int_value(), option_field->type(), unknown_fields); } } else { - return AddValueError(VALUE_MUST_BE_INT(int32, option_field->full_name())); + return AddValueError(ValueMustBeInt("int32", option_field->full_name())); } break; @@ -7716,7 +7724,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > static_cast(std::numeric_limits::max())) { - return AddValueError(VALUE_OUT_OF_RANGE(int64, option_field->full_name())); + return AddValueError(ValueOutOfRange("int64", option_field->full_name())); } else { SetInt64(option_field->number(), uninterpreted_option_->positive_int_value(), @@ -7727,7 +7735,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( uninterpreted_option_->negative_int_value(), option_field->type(), unknown_fields); } else { - return AddValueError(VALUE_MUST_BE_INT(int64, option_field->full_name())); + return AddValueError(ValueMustBeInt("int64", option_field->full_name())); } break; @@ -7735,14 +7743,14 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > std::numeric_limits::max()) { - return AddValueError(VALUE_OUT_OF_RANGE(uint32, option_field->full_name())); + return AddValueError(ValueOutOfRange("uint32", option_field->full_name())); } else { SetUInt32(option_field->number(), uninterpreted_option_->positive_int_value(), option_field->type(), unknown_fields); } } else { - return AddValueError(VALUE_MUST_BE_INT(uint32, option_field->full_name())); + return AddValueError(ValueMustBeInt("uint32", option_field->full_name())); } break; @@ -7752,7 +7760,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( uninterpreted_option_->positive_int_value(), option_field->type(), unknown_fields); } else { - return AddValueError(VALUE_MUST_BE_INT(uint64, option_field->full_name())); + return AddValueError(ValueMustBeInt("uint64", option_field->full_name())); } break; From 7702355b9cc9ab7a1fcc851ecaac372debbc25f6 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Thu, 15 Sep 2022 09:44:15 -0400 Subject: [PATCH 18/64] address latest review comments --- src/google/protobuf/descriptor.cc | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index b2841ce6ef..ffc8cd628e 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -7677,7 +7677,7 @@ bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( } template std::string ValueOutOfRange( - std::string type_name, std::string option_name) { + absl::string_view type_name, absl::string_view option_name) { return absl::StrFormat( "Value out of range, %d to %d, for %s option \"%s\".", \ std::numeric_limits::min(), std::numeric_limits::max(), @@ -7685,7 +7685,7 @@ template std::string ValueOutOfRange( } template std::string ValueMustBeInt( - std::string type_name, std::string option_name) { + absl::string_view type_name, absl::string_view option_name) { return absl::StrFormat( "Value must be integer, from %d to %d, for %s option \"%s\".", \ std::numeric_limits::min(), std::numeric_limits::max(), @@ -7724,7 +7724,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > static_cast(std::numeric_limits::max())) { - return AddValueError(ValueOutOfRange("int64", option_field->full_name())); + return AddValueError(ValueOutOfRange("int64", option_field->full_name())); } else { SetInt64(option_field->number(), uninterpreted_option_->positive_int_value(), @@ -7735,7 +7735,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( uninterpreted_option_->negative_int_value(), option_field->type(), unknown_fields); } else { - return AddValueError(ValueMustBeInt("int64", option_field->full_name())); + return AddValueError(ValueMustBeInt("int64", option_field->full_name())); } break; @@ -7743,14 +7743,14 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( if (uninterpreted_option_->has_positive_int_value()) { if (uninterpreted_option_->positive_int_value() > std::numeric_limits::max()) { - return AddValueError(ValueOutOfRange("uint32", option_field->full_name())); + return AddValueError(ValueOutOfRange("uint32", option_field->full_name())); } else { SetUInt32(option_field->number(), uninterpreted_option_->positive_int_value(), option_field->type(), unknown_fields); } } else { - return AddValueError(ValueMustBeInt("uint32", option_field->full_name())); + return AddValueError(ValueMustBeInt("uint32", option_field->full_name())); } break; @@ -7760,7 +7760,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( uninterpreted_option_->positive_int_value(), option_field->type(), unknown_fields); } else { - return AddValueError(ValueMustBeInt("uint64", option_field->full_name())); + return AddValueError(ValueMustBeInt("uint64", option_field->full_name())); } break; From 1eb29b8257a3c3e9e40cbcb16b968df7538ab61c Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Thu, 15 Sep 2022 10:26:45 -0400 Subject: [PATCH 19/64] validate reserved names are identifiers --- src/google/protobuf/compiler/parser.cc | 39 ++++++++++++------- src/google/protobuf/compiler/parser.h | 1 + .../protobuf/compiler/parser_unittest.cc | 17 ++++++++ 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index 4cae1a1187..8158b9724e 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -51,6 +51,7 @@ #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/tokenizer.h" @@ -1728,11 +1729,23 @@ bool Parser::ParseReserved(DescriptorProto* message, } } +bool Parser::ParseReservedName(std::string* name, const char* error_message) { + // capture position of token + int line = input_->current().line; + int col = input_->current().column; + DO(ConsumeString(name, error_message)); + if (!io::Tokenizer::IsIdentifier(*name)) { + AddError(line, col, absl::StrFormat("Reserved name \"%s\" is not a valid identifier.", *name)); + return false; + } + return true; +} + bool Parser::ParseReservedNames(DescriptorProto* message, const LocationRecorder& parent_location) { do { LocationRecorder location(parent_location, message->reserved_name_size()); - DO(ConsumeString(message->add_reserved_name(), "Expected field name.")); + DO(ParseReservedName(message->add_reserved_name(), "Expected field name.")); } while (TryConsume(",")); DO(ConsumeEndOfDeclaration(";", &parent_location)); return true; @@ -1787,42 +1800,42 @@ bool Parser::ParseReservedNumbers(DescriptorProto* message, return true; } -bool Parser::ParseReserved(EnumDescriptorProto* message, - const LocationRecorder& message_location) { +bool Parser::ParseReserved(EnumDescriptorProto* proto, + const LocationRecorder& enum_location) { io::Tokenizer::Token start_token = input_->current(); // Parse the declaration. DO(Consume("reserved")); if (LookingAtType(io::Tokenizer::TYPE_STRING)) { - LocationRecorder location(message_location, + LocationRecorder location(enum_location, EnumDescriptorProto::kReservedNameFieldNumber); location.StartAt(start_token); - return ParseReservedNames(message, location); + return ParseReservedNames(proto, location); } else { - LocationRecorder location(message_location, + LocationRecorder location(enum_location, EnumDescriptorProto::kReservedRangeFieldNumber); location.StartAt(start_token); - return ParseReservedNumbers(message, location); + return ParseReservedNumbers(proto, location); } } -bool Parser::ParseReservedNames(EnumDescriptorProto* message, +bool Parser::ParseReservedNames(EnumDescriptorProto* proto, const LocationRecorder& parent_location) { do { - LocationRecorder location(parent_location, message->reserved_name_size()); - DO(ConsumeString(message->add_reserved_name(), "Expected enum value.")); + LocationRecorder location(parent_location, proto->reserved_name_size()); + DO(ParseReservedName(proto->add_reserved_name(), "Expected enum value.")); } while (TryConsume(",")); DO(ConsumeEndOfDeclaration(";", &parent_location)); return true; } -bool Parser::ParseReservedNumbers(EnumDescriptorProto* message, +bool Parser::ParseReservedNumbers(EnumDescriptorProto* proto, const LocationRecorder& parent_location) { bool first = true; do { - LocationRecorder location(parent_location, message->reserved_range_size()); + LocationRecorder location(parent_location, proto->reserved_range_size()); EnumDescriptorProto::EnumReservedRange* range = - message->add_reserved_range(); + proto->add_reserved_range(); int start, end; io::Tokenizer::Token start_token; { diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index ccd3e5a5f7..b7dfec6e25 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -394,6 +394,7 @@ class PROTOBUF_EXPORT Parser { const LocationRecorder& message_location); bool ParseReservedNames(DescriptorProto* message, const LocationRecorder& parent_location); + bool ParseReservedName(std::string* name, const char* error_message); bool ParseReservedNumbers(DescriptorProto* message, const LocationRecorder& parent_location); bool ParseReserved(EnumDescriptorProto* message, diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 3b32451916..c6dae84494 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -1675,6 +1675,15 @@ TEST_F(ParseErrorTest, EnumReservedMissingQuotes) { "2:11: Expected enum value or number range.\n"); } +TEST_F(ParseErrorTest, EnumReservedInvalidIdentifier) { + ExpectHasErrors( + "enum TestEnum {\n" + " FOO = 1;\n" + " reserved \"foo bar\";\n" + "}\n", + "2:11: Reserved name \"foo bar\" is not a valid identifier.\n"); +} + // ------------------------------------------------------------------- // Reserved field number errors @@ -1702,6 +1711,14 @@ TEST_F(ParseErrorTest, ReservedMissingQuotes) { "1:11: Expected field name or number range.\n"); } +TEST_F(ParseErrorTest, ReservedInvalidIdentifier) { + ExpectHasErrors( + "message Foo {\n" + " reserved \"foo bar\";\n" + "}\n", + "1:11: Reserved name \"foo bar\" is not a valid identifier.\n"); +} + TEST_F(ParseErrorTest, ReservedNegativeNumber) { ExpectHasErrors( "message Foo {\n" From 0bc90b189cb6d6f6f66f263dcd0afc84daf12e0d Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Thu, 15 Sep 2022 10:36:26 -0400 Subject: [PATCH 20/64] put helpers into anon namespace --- src/google/protobuf/descriptor.cc | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index ffc8cd628e..81412ffc6c 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -7676,6 +7676,9 @@ bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( return true; } +namespace { +// Helpers for method below + template std::string ValueOutOfRange( absl::string_view type_name, absl::string_view option_name) { return absl::StrFormat( @@ -7692,6 +7695,8 @@ template std::string ValueMustBeInt( type_name, option_name); } +} // namespace + bool DescriptorBuilder::OptionInterpreter::SetOptionValue( const FieldDescriptor* option_field, UnknownFieldSet* unknown_fields) { // We switch on the CppType to validate. From 9b64c403f6e8a7d03ce53521ad629eec23301d96 Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Thu, 15 Sep 2022 10:36:44 -0400 Subject: [PATCH 21/64] [ObjC] Clean up includes. - Sort things. - Remove the duplicate (not sure if some automation went wrong at some point). --- .../compiler/objectivec/objectivec_enum.cc | 14 ++++------- .../objectivec/objectivec_extension.cc | 12 ++++------ .../compiler/objectivec/objectivec_field.cc | 14 ++++------- .../compiler/objectivec/objectivec_file.cc | 23 ++++++++----------- .../objectivec/objectivec_generator.cc | 15 +++++------- .../compiler/objectivec/objectivec_helpers.cc | 12 +++++----- .../objectivec/objectivec_map_field.h | 1 + .../compiler/objectivec/objectivec_message.cc | 20 +++++++--------- .../objectivec/objectivec_message_field.h | 1 + .../compiler/objectivec/objectivec_oneof.cc | 12 ++++------ .../compiler/objectivec/objectivec_oneof.h | 3 ++- .../objectivec/objectivec_primitive_field.cc | 12 ++++------ 12 files changed, 56 insertions(+), 83 deletions(-) diff --git a/src/google/protobuf/compiler/objectivec/objectivec_enum.cc b/src/google/protobuf/compiler/objectivec/objectivec_enum.cc index 7e1283b841..28ef44cace 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_enum.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_enum.cc @@ -28,22 +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 #include #include -#include "google/protobuf/compiler/objectivec/objectivec_enum.h" -#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" -#include "google/protobuf/io/printer.h" -#include "google/protobuf/stubs/strutil.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" #include "absl/strings/str_replace.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" #include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" -#include // std::find() +#include "google/protobuf/compiler/objectivec/objectivec_enum.h" +#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" +#include "google/protobuf/io/printer.h" +#include "google/protobuf/stubs/strutil.h" namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc index c70766a6ef..3c20a13ad2 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc @@ -30,19 +30,15 @@ #include -#include "google/protobuf/compiler/objectivec/objectivec_extension.h" -#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" -#include "google/protobuf/descriptor.pb.h" -#include "google/protobuf/stubs/strutil.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" #include "absl/strings/str_replace.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" #include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" +#include "google/protobuf/compiler/objectivec/objectivec_extension.h" +#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" +#include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/printer.h" +#include "google/protobuf/stubs/strutil.h" namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_field.cc index f11cbde086..4397231c58 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_field.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_field.cc @@ -30,22 +30,18 @@ #include +#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/objectivec_enum_field.h" #include "google/protobuf/compiler/objectivec/objectivec_field.h" #include "google/protobuf/compiler/objectivec/objectivec_helpers.h" -#include "google/protobuf/compiler/objectivec/objectivec_enum_field.h" #include "google/protobuf/compiler/objectivec/objectivec_map_field.h" #include "google/protobuf/compiler/objectivec/objectivec_message_field.h" #include "google/protobuf/compiler/objectivec/objectivec_primitive_field.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/stubs/strutil.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc index a420c2c69b..72caa47d4f 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc @@ -28,27 +28,24 @@ // (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/objectivec_file.h" +#include +#include +#include + +#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/code_generator.h" #include "google/protobuf/compiler/objectivec/objectivec_enum.h" #include "google/protobuf/compiler/objectivec/objectivec_extension.h" +#include "google/protobuf/compiler/objectivec/objectivec_file.h" #include "google/protobuf/compiler/objectivec/objectivec_helpers.h" #include "google/protobuf/compiler/objectivec/objectivec_message.h" -#include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/stubs/stl_util.h" #include "google/protobuf/stubs/strutil.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" -#include // std::find() -#include -#include // 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. diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc index e2efe29b20..9c7acabc63 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc @@ -32,20 +32,17 @@ #include #include #include -#include "google/protobuf/compiler/objectivec/objectivec_generator.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/objectivec_file.h" +#include "google/protobuf/compiler/objectivec/objectivec_generator.h" #include "google/protobuf/compiler/objectivec/objectivec_helpers.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/stubs/strutil.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc index 1dbff83749..87a5685a4d 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc @@ -41,21 +41,21 @@ #include #include +#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/code_generator.h" #include "google/protobuf/compiler/objectivec/objectivec_helpers.h" #include "google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/coded_stream.h" +#include "google/protobuf/io/io_win32.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream_impl.h" -#include "google/protobuf/io/io_win32.h" #include "google/protobuf/port.h" #include "google/protobuf/stubs/common.h" #include "google/protobuf/stubs/strutil.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" -#include "absl/strings/str_replace.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. @@ -199,7 +199,7 @@ std::string PrefixModeStorage::prefix_from_proto_package_mappings(const FileDesc if (prefix_lookup != package_to_prefix_map_.end()) { return prefix_lookup->second; - } + } return ""; } diff --git a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h index c16e818e2e..20c538e3bb 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_map_field.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_map_field.h @@ -33,6 +33,7 @@ #include #include + #include "google/protobuf/compiler/objectivec/objectivec_field.h" namespace google { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message.cc b/src/google/protobuf/compiler/objectivec/objectivec_message.cc index 945d095b7e..dd3eacb1d1 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_message.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_message.cc @@ -32,24 +32,20 @@ #include #include -#include "google/protobuf/compiler/objectivec/objectivec_message.h" -#include "google/protobuf/compiler/objectivec/objectivec_enum.h" -#include "google/protobuf/compiler/objectivec/objectivec_extension.h" -#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" -#include "google/protobuf/stubs/stl_util.h" -#include "google/protobuf/stubs/strutil.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" #include "absl/strings/str_replace.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" #include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" -#include "google/protobuf/io/printer.h" +#include "google/protobuf/compiler/objectivec/objectivec_enum.h" +#include "google/protobuf/compiler/objectivec/objectivec_extension.h" +#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" +#include "google/protobuf/compiler/objectivec/objectivec_message.h" +#include "google/protobuf/descriptor.pb.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/descriptor.pb.h" +#include "google/protobuf/stubs/stl_util.h" +#include "google/protobuf/stubs/strutil.h" namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_message_field.h b/src/google/protobuf/compiler/objectivec/objectivec_message_field.h index 12e191eed2..19f23a29e7 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_message_field.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_message_field.h @@ -33,6 +33,7 @@ #include #include + #include "google/protobuf/compiler/objectivec/objectivec_field.h" namespace google { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc b/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc index 269cd52660..dc218dff9f 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc @@ -31,18 +31,14 @@ #include #include -#include "google/protobuf/compiler/objectivec/objectivec_oneof.h" -#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" -#include "google/protobuf/io/printer.h" -#include "google/protobuf/stubs/strutil.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" #include "absl/strings/str_replace.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" #include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" +#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" +#include "google/protobuf/compiler/objectivec/objectivec_oneof.h" +#include "google/protobuf/io/printer.h" +#include "google/protobuf/stubs/strutil.h" namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_oneof.h b/src/google/protobuf/compiler/objectivec/objectivec_oneof.h index 27e9c2a423..c89cdd91b4 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_oneof.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_oneof.h @@ -31,9 +31,10 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ONEOF_H__ #define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ONEOF_H__ -#include #include +#include #include + #include "google/protobuf/descriptor.h" #include "google/protobuf/io/printer.h" diff --git a/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc b/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc index 2c30d6bac5..824bdbfa8b 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc @@ -31,18 +31,14 @@ #include #include -#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" -#include "google/protobuf/compiler/objectivec/objectivec_primitive_field.h" -#include "google/protobuf/io/printer.h" -#include "google/protobuf/stubs/strutil.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" -#include "absl/strings/str_split.h" #include "absl/strings/str_replace.h" -#include "absl/strings/ascii.h" -#include "absl/strings/escaping.h" #include "absl/strings/str_split.h" -#include "absl/strings/str_replace.h" +#include "google/protobuf/compiler/objectivec/objectivec_helpers.h" +#include "google/protobuf/compiler/objectivec/objectivec_primitive_field.h" +#include "google/protobuf/io/printer.h" +#include "google/protobuf/stubs/strutil.h" namespace google { namespace protobuf { From f82be688318afe5f46ea877a576a208d70d83d9d Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Thu, 15 Sep 2022 11:26:13 -0400 Subject: [PATCH 22/64] avoid possible exception; error if octal or hex literal that is too large --- src/google/protobuf/compiler/parser.cc | 11 ++++++++--- .../protobuf/compiler/parser_unittest.cc | 16 ++++++++++++++++ src/google/protobuf/io/tokenizer.cc | 19 ++++++++++++------- src/google/protobuf/io/tokenizer.h | 4 ++++ 4 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index e5f42c4506..4381307624 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -310,9 +310,14 @@ bool Parser::ConsumeNumber(double* output, const char* error) { std::numeric_limits::max(), &value)) { *output = value; - } else { - // out of int range, treat as double literal - *output = io::Tokenizer::ParseFloat(input_->current().text); + } else if (input_->current().text[0] == '0') { + // octal or hexadecimal; don't bother parsing as float + AddError("Integer out of range."); + // We still return true because we did, in fact, parse a number. + } else if (!io::Tokenizer::TryParseFloat(input_->current().text, output)) { + // out of int range, and not valid float? 🤷 + AddError("Integer out of range."); + // We still return true because we did, in fact, parse a number. } input_->Next(); return true; diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 7685371c14..39d5b60744 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -1941,6 +1941,22 @@ TEST_F(ParserValidationErrorTest, FieldDefaultValueError) { "2:32: Enum type \"Baz\" has no value named \"NO_SUCH_VALUE\".\n"); } +TEST_F(ParserValidationErrorTest, FieldDefaultIntegerOutOfRange) { + ExpectHasErrors( + "message Foo {\n" + " optional double bar = 1 [default = 0x10000000000000000];\n" + "}\n", + "1:37: Integer out of range.\n"); +} + +TEST_F(ParserValidationErrorTest, FieldOptionOutOfRange) { + ExpectHasErrors( + "message Foo {\n" + " optional double bar = 1 [foo = 0x10000000000000000];\n" + "}\n", + "1:33: Integer out of range.\n"); +} + TEST_F(ParserValidationErrorTest, FileOptionNameError) { ExpectHasValidationErrors( "option foo = 5;", diff --git a/src/google/protobuf/io/tokenizer.cc b/src/google/protobuf/io/tokenizer.cc index 7bc0820dd8..127fb5a402 100644 --- a/src/google/protobuf/io/tokenizer.cc +++ b/src/google/protobuf/io/tokenizer.cc @@ -1002,9 +1002,19 @@ bool Tokenizer::ParseInteger(const std::string& text, uint64_t max_value, } double Tokenizer::ParseFloat(const std::string& text) { + double result; + GOOGLE_LOG_IF(DFATAL, + !TryParseFloat(text, &result)) + << " Tokenizer::ParseFloat() passed text that could not have been" + " tokenized as a float: " + << absl::CEscape(text); + return result; +} + +bool Tokenizer::TryParseFloat(const std::string& text, double* result) { const char* start = text.c_str(); char* end; - double result = NoLocaleStrtod(start, &end); + *result = NoLocaleStrtod(start, &end); // "1e" is not a valid float, but if the tokenizer reads it, it will // report an error but still return it as a valid token. We need to @@ -1020,12 +1030,7 @@ double Tokenizer::ParseFloat(const std::string& text) { ++end; } - GOOGLE_LOG_IF(DFATAL, - static_cast(end - start) != text.size() || *start == '-') - << " Tokenizer::ParseFloat() passed text that could not have been" - " tokenized as a float: " - << absl::CEscape(text); - return result; + return static_cast(end - start) == text.size() && *start != '-'; } // Helper to append a Unicode code point to a string as UTF8, without bringing diff --git a/src/google/protobuf/io/tokenizer.h b/src/google/protobuf/io/tokenizer.h index cab1faf917..73877ccc24 100644 --- a/src/google/protobuf/io/tokenizer.h +++ b/src/google/protobuf/io/tokenizer.h @@ -214,6 +214,10 @@ class PROTOBUF_EXPORT Tokenizer { // result is undefined (possibly an assert failure). static double ParseFloat(const std::string& text); + // Parses given text as if it were a TYPE_FLOAT token. Returns false if the + // given text is not actually a valid float literal. + static bool TryParseFloat(const std::string& text, double* result); + // Parses a TYPE_STRING token. This never fails, so long as the text actually // comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the // result is undefined (possibly an assert failure). From b67bd3309b8a92a279fc43653d3a7d4a698ea11c Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Thu, 15 Sep 2022 10:05:11 -0400 Subject: [PATCH 23/64] [ObjC] Add helper for IsCreateName for the CF Create Rule. Also add tests for all of the Is*Name helpers. --- .../compiler/objectivec/objectivec_helpers.cc | 49 +++++++++-- .../compiler/objectivec/objectivec_helpers.h | 4 + .../objectivec/objectivec_helpers_unittest.cc | 84 +++++++++++++++++++ 3 files changed, 129 insertions(+), 8 deletions(-) diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc index 87a5685a4d..f4a36936c0 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc @@ -513,13 +513,14 @@ void PathSplit(const std::string& path, std::string* directory, } } -bool IsSpecialName(const std::string& name, const std::string* special_names, - size_t count) { +bool IsSpecialNamePrefix(const std::string& name, + const std::string* special_names, + size_t count) { for (size_t i = 0; i < count; ++i) { - size_t length = special_names[i].length(); + const size_t length = special_names[i].length(); if (name.compare(0, length, special_names[i]) == 0) { if (name.length() > length) { - // If name is longer than the retained_name[i] that it matches + // If name is longer than the special_names[i] that it matches // the next character must be not lower case (newton vs newTon vs // new_ton). return !absl::ascii_islower(name[length]); @@ -589,14 +590,46 @@ 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 IsSpecialName(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) { static const std::string init_names[] = {"init"}; - return IsSpecialName(name, init_names, - sizeof(init_names) / sizeof(init_names[0])); + return IsSpecialNamePrefix(name, init_names, + sizeof(init_names) / sizeof(init_names[0])); +} + +bool IsCreateName(const std::string& name) { + // List of segments from + // https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-103029 + static const std::string create_names[] = {"Create", "Copy"}; + const size_t count = sizeof(create_names) / sizeof(create_names[0]); + + for (size_t i = 0; i < count; ++i) { + const size_t length = create_names[i].length(); + size_t pos = name.find(create_names[i]); + if (pos != std::string::npos) { + // The above docs don't actually call out anything about the characters + // before the special words. So it's not clear if something like + // "FOOCreate" would or would not match the "The Create Rule", but by not + // checking, and claiming it does match, then callers will annotate with + // `cf_returns_not_retained` which will ensure things work as desired. + // + // The footnote here is the docs do have a passing reference to "NoCopy", + // but again, not looking for that and just returning `true` will cause + // callers to annotate the api as not being a Create Rule function. + + // If name is longer than the create_names[i] that it matches the next + // character must be not lower case (Copyright vs CopyFoo vs Copy_Foo). + if (name.length() > pos + length) { + return !absl::ascii_islower(name[pos + length]); + } else { + return true; + } + } + } + return false; } std::string BaseFileName(const FileDescriptor* file) { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h index 9cee305080..79a9643c17 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h @@ -92,6 +92,10 @@ bool PROTOC_EXPORT IsRetainedName(const std::string& name); // handling under ARC. bool PROTOC_EXPORT IsInitName(const std::string& name); +// Returns true if the name requires a cf_returns_not_retained attribute applied +// to it. +bool PROTOC_EXPORT IsCreateName(const std::string& name); + // Gets the objc_class_prefix or the prefix made from the proto package. std::string PROTOC_EXPORT FileClassPrefix(const FileDescriptor* file); diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc index 7ad11f04cb..0ae2451464 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc @@ -369,6 +369,90 @@ TEST(ObjCHelper, ParseSimple_RejectLinesNoMessage) { } } +TEST(ObjCHelper, IsRetainedName) { + EXPECT_TRUE(IsRetainedName("new")); + EXPECT_TRUE(IsRetainedName("alloc")); + EXPECT_TRUE(IsRetainedName("copy")); + EXPECT_TRUE(IsRetainedName("mutableCopy")); + EXPECT_TRUE(IsRetainedName("newFoo")); + EXPECT_TRUE(IsRetainedName("allocFoo")); + EXPECT_TRUE(IsRetainedName("copyFoo")); + EXPECT_TRUE(IsRetainedName("mutableCopyFoo")); + EXPECT_TRUE(IsRetainedName("new_foo")); + EXPECT_TRUE(IsRetainedName("alloc_foo")); + EXPECT_TRUE(IsRetainedName("copy_foo")); + EXPECT_TRUE(IsRetainedName("mutableCopy_foo")); + + EXPECT_FALSE(IsRetainedName("")); + EXPECT_FALSE(IsRetainedName("ne")); + EXPECT_FALSE(IsRetainedName("all")); + EXPECT_FALSE(IsRetainedName("co")); + EXPECT_FALSE(IsRetainedName("mutable")); + EXPECT_FALSE(IsRetainedName("New")); + EXPECT_FALSE(IsRetainedName("Alloc")); + EXPECT_FALSE(IsRetainedName("Copy")); + EXPECT_FALSE(IsRetainedName("MutableCopy")); + EXPECT_FALSE(IsRetainedName("newer")); + EXPECT_FALSE(IsRetainedName("alloced")); + EXPECT_FALSE(IsRetainedName("copying")); + EXPECT_FALSE(IsRetainedName("mutableCopying")); + + EXPECT_FALSE(IsRetainedName("init")); + EXPECT_FALSE(IsRetainedName("Create")); + EXPECT_FALSE(IsRetainedName("Copy")); +} + +TEST(ObjCHelper, IsInitName) { + EXPECT_TRUE(IsInitName("init")); + EXPECT_TRUE(IsInitName("initFoo")); + EXPECT_TRUE(IsInitName("init_foo")); + + EXPECT_FALSE(IsInitName("")); + EXPECT_FALSE(IsInitName("in")); + EXPECT_FALSE(IsInitName("Init")); + EXPECT_FALSE(IsInitName("inIt")); + EXPECT_FALSE(IsInitName("initial")); + EXPECT_FALSE(IsInitName("initiAl")); + EXPECT_FALSE(IsInitName("fooInit")); + EXPECT_FALSE(IsInitName("foo_init")); + + EXPECT_FALSE(IsInitName("new")); + EXPECT_FALSE(IsInitName("alloc")); + EXPECT_FALSE(IsInitName("copy")); + EXPECT_FALSE(IsInitName("mutableCopy")); + EXPECT_FALSE(IsInitName("Create")); + EXPECT_FALSE(IsInitName("Copy")); +} + +TEST(ObjCHelper, IsCreateName) { + EXPECT_TRUE(IsCreateName("Create")); + EXPECT_TRUE(IsCreateName("Copy")); + EXPECT_TRUE(IsCreateName("CreateFoo")); + EXPECT_TRUE(IsCreateName("CopyFoo")); + EXPECT_TRUE(IsCreateName("Create_foo")); + EXPECT_TRUE(IsCreateName("Copy_foo")); + EXPECT_TRUE(IsCreateName("ReCreate")); + EXPECT_TRUE(IsCreateName("ReCopy")); + EXPECT_TRUE(IsCreateName("FOOCreate")); + EXPECT_TRUE(IsCreateName("FOOCopy")); + EXPECT_TRUE(IsCreateName("CreateWithCopy")); + + EXPECT_FALSE(IsCreateName("")); + EXPECT_FALSE(IsCreateName("Crea")); + EXPECT_FALSE(IsCreateName("Co")); + EXPECT_FALSE(IsCreateName("create")); + EXPECT_FALSE(IsCreateName("recreate")); + EXPECT_FALSE(IsCreateName("recopy")); + EXPECT_FALSE(IsCreateName("ReCreated")); + EXPECT_FALSE(IsCreateName("ReCopying")); + + EXPECT_FALSE(IsCreateName("init")); + EXPECT_FALSE(IsCreateName("new")); + EXPECT_FALSE(IsCreateName("alloc")); + EXPECT_FALSE(IsCreateName("copy")); + EXPECT_TRUE(IsCreateName("mutableCopy")); +} + // TODO(thomasvl): Should probably add some unittests for all the special cases // of name mangling (class name, field name, enum names). Rather than doing // this with an ObjC test in the objectivec directory, we should be able to From 3c01924679c4a96b7fb8ded2b0333c7c8dc1c3cb Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Wed, 14 Sep 2022 09:55:55 -0400 Subject: [PATCH 24/64] [ObjC] Move generation options out to their own file. This will make it easier to pass the option down in the future to the other parts (message, enum, extension, etc. generators) as needed. --- src/file_lists.cmake | 1 + .../protobuf/compiler/objectivec/BUILD.bazel | 1 + .../compiler/objectivec/objectivec_file.h | 12 +--- .../objectivec/objectivec_generator.cc | 2 +- .../compiler/objectivec/objectivec_options.h | 56 +++++++++++++++++++ 5 files changed, 60 insertions(+), 12 deletions(-) create mode 100644 src/google/protobuf/compiler/objectivec/objectivec_options.h diff --git a/src/file_lists.cmake b/src/file_lists.cmake index 0d6a9f850e..be3d61ee14 100644 --- a/src/file_lists.cmake +++ b/src/file_lists.cmake @@ -456,6 +456,7 @@ set(libprotoc_hdrs ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_message_field.h ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_oneof.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_options.h ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/php/php_generator.h ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/plugin.h diff --git a/src/google/protobuf/compiler/objectivec/BUILD.bazel b/src/google/protobuf/compiler/objectivec/BUILD.bazel index defcf29183..ee2ef1f0e0 100644 --- a/src/google/protobuf/compiler/objectivec/BUILD.bazel +++ b/src/google/protobuf/compiler/objectivec/BUILD.bazel @@ -35,6 +35,7 @@ cc_library( "objectivec_message_field.h", "objectivec_nsobject_methods.h", "objectivec_oneof.h", + "objectivec_options.h", "objectivec_primitive_field.h", ], copts = COPTS, diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.h b/src/google/protobuf/compiler/objectivec/objectivec_file.h index 842ddff154..5063611923 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_file.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_file.h @@ -35,6 +35,7 @@ #include #include #include +#include "google/protobuf/compiler/objectivec/objectivec_options.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/io/printer.h" @@ -49,17 +50,6 @@ class MessageGenerator; class FileGenerator { public: - struct GenerationOptions { - GenerationOptions() - // TODO(thomasvl): Eventually flip this default to false for better - // interop with Swift if proto usages span modules made from ObjC sources. - : headers_use_forward_declarations(true) {} - std::string generate_for_named_framework; - std::string named_framework_to_proto_path_mappings_path; - std::string runtime_import_prefix; - bool headers_use_forward_declarations; - }; - // Wrapper for some common state that is shared between file generations to // improve performance when more than one file is generated at a time. struct CommonState { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc index 9c7acabc63..225a7d207e 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc @@ -100,7 +100,7 @@ bool ObjectiveCGenerator::GenerateAll( // e.g. protoc ... --objc_opt=expected_prefixes=file.txt,generate_for_named_framework=MyFramework Options validation_options; - FileGenerator::GenerationOptions generation_options; + GenerationOptions generation_options; std::vector > options; ParseGeneratorParameter(parameter, &options); diff --git a/src/google/protobuf/compiler/objectivec/objectivec_options.h b/src/google/protobuf/compiler/objectivec/objectivec_options.h new file mode 100644 index 0000000000..07b90b3d69 --- /dev/null +++ b/src/google/protobuf/compiler/objectivec/objectivec_options.h @@ -0,0 +1,56 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_OPTIONS_H__ +#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_OPTIONS_H__ + +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace objectivec { + +// Generation options, documented within objectivec_generator.cc. +struct GenerationOptions { + std::string generate_for_named_framework; + std::string named_framework_to_proto_path_mappings_path; + std::string runtime_import_prefix; + // TODO(thomasvl): Eventually flip this default to false for better interop + // with Swift if proto usages span modules made from ObjC sources. + bool headers_use_forward_declarations = true; +}; + +} // namespace objectivec +} // namespace compiler +} // namespace protobuf +} // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_OPTIONS_H__ From d6acffba7bf67e8f928acf1cc676056919ad19e3 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Thu, 15 Sep 2022 13:37:59 -0400 Subject: [PATCH 25/64] use normal conditional --- src/google/protobuf/io/tokenizer.cc | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/google/protobuf/io/tokenizer.cc b/src/google/protobuf/io/tokenizer.cc index 127fb5a402..d14c5a1926 100644 --- a/src/google/protobuf/io/tokenizer.cc +++ b/src/google/protobuf/io/tokenizer.cc @@ -1003,11 +1003,12 @@ bool Tokenizer::ParseInteger(const std::string& text, uint64_t max_value, double Tokenizer::ParseFloat(const std::string& text) { double result; - GOOGLE_LOG_IF(DFATAL, - !TryParseFloat(text, &result)) - << " Tokenizer::ParseFloat() passed text that could not have been" - " tokenized as a float: " - << absl::CEscape(text); + if (!TryParseFloat(text, &result)) { + LOG(DFATAL) + << " Tokenizer::ParseFloat() passed text that could not have been" + " tokenized as a float: " + << absl::CEscape(text); + } return result; } From 0362a1204f269161fe20e53ff1184440bdeeb792 Mon Sep 17 00:00:00 2001 From: Joshua Humphries Date: Thu, 15 Sep 2022 14:01:43 -0400 Subject: [PATCH 26/64] initialize var to avoid undefined return val --- src/google/protobuf/io/tokenizer.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/google/protobuf/io/tokenizer.cc b/src/google/protobuf/io/tokenizer.cc index d14c5a1926..d7f100dbbd 100644 --- a/src/google/protobuf/io/tokenizer.cc +++ b/src/google/protobuf/io/tokenizer.cc @@ -1002,7 +1002,7 @@ bool Tokenizer::ParseInteger(const std::string& text, uint64_t max_value, } double Tokenizer::ParseFloat(const std::string& text) { - double result; + double result = 0; if (!TryParseFloat(text, &result)) { LOG(DFATAL) << " Tokenizer::ParseFloat() passed text that could not have been" From 7c57fb08e6e27bc72a4bfdf0832d4737ed0ab3bb Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Thu, 15 Sep 2022 14:26:23 -0400 Subject: [PATCH 27/64] JSON -> Json --- src/google/protobuf/descriptor.cc | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index ad5eb8db2c..308381982f 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -3858,9 +3858,9 @@ class DescriptorBuilder { const ServiceDescriptor* parent, MethodDescriptor* result, internal::FlatAllocator& alloc); - void CheckFieldJSONNameUniqueness(const DescriptorProto& proto, + void CheckFieldJsonNameUniqueness(const DescriptorProto& proto, const Descriptor* result); - void CheckFieldJSONNameUniqueness(std::string message_name, + void CheckFieldJsonNameUniqueness(std::string message_name, const DescriptorProto& message, bool is_proto2, bool use_custom_names); void CheckEnumValueUniqueness(const EnumDescriptorProto& proto, @@ -5421,7 +5421,7 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, } } - CheckFieldJSONNameUniqueness(proto, result); + CheckFieldJsonNameUniqueness(proto, result); // Check that fields aren't using reserved names or numbers and that they // aren't using extension numbers. @@ -5489,7 +5489,7 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, } } -std::string GetJSONName(const FieldDescriptorProto& field, bool use_custom, bool* was_custom) { +std::string GetJsonName(const FieldDescriptorProto& field, bool use_custom, bool* was_custom) { if (use_custom && field.has_json_name()) { *was_custom = true; return field.json_name(); @@ -5498,28 +5498,28 @@ std::string GetJSONName(const FieldDescriptorProto& field, bool use_custom, bool return ToJsonName(field.name()); } -void DescriptorBuilder::CheckFieldJSONNameUniqueness( +void DescriptorBuilder::CheckFieldJsonNameUniqueness( const DescriptorProto& proto, const Descriptor* result) { bool is_proto2 = result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2; std::string message_name = result->full_name(); // two passes: one looking only at default JSON names, and one that considers custom JSON names - CheckFieldJSONNameUniqueness(message_name, proto, is_proto2, false); - CheckFieldJSONNameUniqueness(message_name, proto, is_proto2, true); + CheckFieldJsonNameUniqueness(message_name, proto, is_proto2, false); + CheckFieldJsonNameUniqueness(message_name, proto, is_proto2, true); } -struct JSONNameDetails { +struct JsonNameDetails { const FieldDescriptorProto* field; std::string orig_name; bool is_custom; }; -void DescriptorBuilder::CheckFieldJSONNameUniqueness( +void DescriptorBuilder::CheckFieldJsonNameUniqueness( std::string message_name,const DescriptorProto& message, bool is_proto2, bool use_custom_names) { - std::map name_to_field; + std::map name_to_field; for (int i = 0; i < message.field_size(); ++i) { bool is_custom; - std::string name = GetJSONName(message.field(i), use_custom_names, &is_custom); + std::string name = GetJsonName(message.field(i), use_custom_names, &is_custom); std::string lowercase_name = absl::AsciiStrToLower(name); auto existing = name_to_field.find(lowercase_name); if (existing != name_to_field.end()) { @@ -5552,7 +5552,7 @@ void DescriptorBuilder::CheckFieldJSONNameUniqueness( DescriptorPool::ErrorCollector::NAME, error_message); } } else { - struct JSONNameDetails details = { &message.field(i), name, is_custom }; + JsonNameDetails details = { &message.field(i), name, is_custom }; name_to_field[lowercase_name] = details; } } From 16627c5f41c46c78fc35b4b8d8c43ff6597c382e Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Thu, 15 Sep 2022 15:04:20 -0400 Subject: [PATCH 28/64] address review feedback wrt absl string functions also moves helpers into anonymous namespace --- src/google/protobuf/descriptor.cc | 73 +++++++++++++++++-------------- 1 file changed, 40 insertions(+), 33 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 308381982f..3bdbf5c6ef 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -58,6 +58,7 @@ #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" #include "google/protobuf/stubs/stringprintf.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" @@ -5489,15 +5490,6 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, } } -std::string GetJsonName(const FieldDescriptorProto& field, bool use_custom, bool* was_custom) { - if (use_custom && field.has_json_name()) { - *was_custom = true; - return field.json_name(); - } - *was_custom = false; - return ToJsonName(field.name()); -} - void DescriptorBuilder::CheckFieldJsonNameUniqueness( const DescriptorProto& proto, const Descriptor* result) { bool is_proto2 = result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2; @@ -5507,52 +5499,68 @@ void DescriptorBuilder::CheckFieldJsonNameUniqueness( CheckFieldJsonNameUniqueness(message_name, proto, is_proto2, true); } +namespace { +// Helpers for function below + +std::string GetJsonName(const FieldDescriptorProto& field, bool use_custom, bool* was_custom) { + if (use_custom && field.has_json_name()) { + *was_custom = true; + return field.json_name(); + } + *was_custom = false; + return ToJsonName(field.name()); +} + struct JsonNameDetails { const FieldDescriptorProto* field; std::string orig_name; bool is_custom; }; +} // namespace + void DescriptorBuilder::CheckFieldJsonNameUniqueness( std::string message_name,const DescriptorProto& message, bool is_proto2, bool use_custom_names) { - std::map name_to_field; - for (int i = 0; i < message.field_size(); ++i) { + absl::flat_hash_map name_to_field; + for (const FieldDescriptorProto& field : message.field()) { bool is_custom; - std::string name = GetJsonName(message.field(i), use_custom_names, &is_custom); + std::string name = GetJsonName(field, use_custom_names, &is_custom); std::string lowercase_name = absl::AsciiStrToLower(name); auto existing = name_to_field.find(lowercase_name); if (existing != name_to_field.end()) { - auto match = existing->second; + JsonNameDetails& match = existing->second; if (use_custom_names && !is_custom && !match.is_custom) { // if this pass is considering custom JSON names, but neither of the // names involved in the conflict are custom, don't bother with a message. // That will have been reported from other pass (non-custom JSON names). continue; } - std::string this_type = is_custom ? "custom" : "default"; - std::string existing_type = match.is_custom ? "custom" : "default"; + absl::string_view this_type = is_custom ? "custom" : "default"; + absl::string_view existing_type = match.is_custom ? "custom" : "default"; // If the matched name differs (which it can only differ in case), include it // in the error message, for maximum clarity to user. - std::string name_suffix = name == match.orig_name ? "" : " (\"" + match.orig_name + "\")"; - std::string error_message = - "The " + this_type + " JSON name of field \"" + message.field(i).name() + - "\" (\"" + name + "\") conflicts with the " + existing_type + " JSON name of field \"" + - match.field->name() + "\"" + name_suffix + "."; + absl::string_view name_suffix = ""; + if (name != match.orig_name) { + name_suffix = absl::StrCat(" (\"", match.orig_name, "\")"); + } + std::string error_message = absl::StrFormat( + "The %s JSON name of field \"%s\" (\"%s\") conflicts with the %s JSON name of field \"%s\"%s.", + this_type, field.name(), name, existing_type, match.field->name(), name_suffix); bool involves_default = !is_custom || !match.is_custom; if (is_proto2 && involves_default) { - AddWarning(message_name, message.field(i), + AddWarning(message_name, field, DescriptorPool::ErrorCollector::NAME, error_message); } else { if (involves_default) { - error_message += " This is not allowed in proto3."; + absl::StrAppend(&error_message, " This is not allowed in proto3."); } - AddError(message_name, message.field(i), + AddError(message_name, field, DescriptorPool::ErrorCollector::NAME, error_message); } } else { - JsonNameDetails details = { &message.field(i), name, is_custom }; + JsonNameDetails details = { &field, name, is_custom }; name_to_field[lowercase_name] = details; } } @@ -5961,12 +5969,12 @@ void DescriptorBuilder::CheckEnumValueUniqueness( // NAME_TYPE_LAST_NAME = 2, // } PrefixRemover remover(result->name()); - std::map values; + absl::flat_hash_map values; for (int i = 0; i < result->value_count(); i++) { const EnumValueDescriptor* value = result->value(i); std::string stripped = EnumValueToPascalCase(remover.MaybeRemove(value->name())); - std::pair::iterator, bool> + std::pair::iterator, bool> insert_result = values.insert(std::make_pair(stripped, value)); bool inserted = insert_result.second; @@ -5978,19 +5986,18 @@ void DescriptorBuilder::CheckEnumValueUniqueness( // stripping should de-dup the labels in this case). if (!inserted && insert_result.first->second->name() != value->name() && insert_result.first->second->number() != value->number()) { - std::string error_message = - "Enum name " + value->name() + " has the same name as " + - values[stripped]->name() + - " if you ignore case and strip out the enum name prefix (if any). " - "(If you are using allow_alias, please assign the same numeric " - "value to both enums.)"; + std::string error_message = absl::StrFormat( + "Enum name %s has the same name as %s if you ignore case and strip " + "out the enum name prefix (if any). (If you are using allow_alias, " + "please assign the same numeric value to both enums.)", + value->name(), values[stripped]->name()); // There are proto2 enums out there with conflicting names, so to preserve // compatibility we issue only a warning for proto2. if (result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2) { AddWarning(value->full_name(), proto.value(i), DescriptorPool::ErrorCollector::NAME, error_message); } else { - error_message += " This is not allowed in proto3."; + absl::StrAppend(&error_message, " This is not allowed in proto3."); AddError(value->full_name(), proto.value(i), DescriptorPool::ErrorCollector::NAME, error_message); } From d86340e37d0591d8e3ac237315d9fb8120b365f1 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Thu, 15 Sep 2022 15:09:18 -0400 Subject: [PATCH 29/64] apply clang-format changes; change really long pair type to auto --- src/google/protobuf/descriptor.cc | 39 +++++++++++++++++-------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 3bdbf5c6ef..393be38294 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -5494,7 +5494,8 @@ void DescriptorBuilder::CheckFieldJsonNameUniqueness( const DescriptorProto& proto, const Descriptor* result) { bool is_proto2 = result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2; std::string message_name = result->full_name(); - // two passes: one looking only at default JSON names, and one that considers custom JSON names + // two passes: one looking only at default JSON names, and one that considers + // custom JSON names CheckFieldJsonNameUniqueness(message_name, proto, is_proto2, false); CheckFieldJsonNameUniqueness(message_name, proto, is_proto2, true); } @@ -5502,7 +5503,8 @@ void DescriptorBuilder::CheckFieldJsonNameUniqueness( namespace { // Helpers for function below -std::string GetJsonName(const FieldDescriptorProto& field, bool use_custom, bool* was_custom) { +std::string GetJsonName(const FieldDescriptorProto& field, bool use_custom, + bool* was_custom) { if (use_custom && field.has_json_name()) { *was_custom = true; return field.json_name(); @@ -5520,7 +5522,8 @@ struct JsonNameDetails { } // namespace void DescriptorBuilder::CheckFieldJsonNameUniqueness( - std::string message_name,const DescriptorProto& message, bool is_proto2, bool use_custom_names) { + std::string message_name, const DescriptorProto& message, bool is_proto2, + bool use_custom_names) { absl::flat_hash_map name_to_field; for (const FieldDescriptorProto& field : message.field()) { @@ -5532,35 +5535,38 @@ void DescriptorBuilder::CheckFieldJsonNameUniqueness( JsonNameDetails& match = existing->second; if (use_custom_names && !is_custom && !match.is_custom) { // if this pass is considering custom JSON names, but neither of the - // names involved in the conflict are custom, don't bother with a message. - // That will have been reported from other pass (non-custom JSON names). + // names involved in the conflict are custom, don't bother with a + // message. That will have been reported from other pass (non-custom + // JSON names). continue; } absl::string_view this_type = is_custom ? "custom" : "default"; absl::string_view existing_type = match.is_custom ? "custom" : "default"; - // If the matched name differs (which it can only differ in case), include it - // in the error message, for maximum clarity to user. + // If the matched name differs (which it can only differ in case), include + // it in the error message, for maximum clarity to user. absl::string_view name_suffix = ""; if (name != match.orig_name) { name_suffix = absl::StrCat(" (\"", match.orig_name, "\")"); } - std::string error_message = absl::StrFormat( - "The %s JSON name of field \"%s\" (\"%s\") conflicts with the %s JSON name of field \"%s\"%s.", - this_type, field.name(), name, existing_type, match.field->name(), name_suffix); + std::string error_message = + absl::StrFormat("The %s JSON name of field \"%s\" (\"%s\") conflicts " + "with the %s JSON name of field \"%s\"%s.", + this_type, field.name(), name, existing_type, + match.field->name(), name_suffix); bool involves_default = !is_custom || !match.is_custom; if (is_proto2 && involves_default) { - AddWarning(message_name, field, - DescriptorPool::ErrorCollector::NAME, error_message); + AddWarning(message_name, field, DescriptorPool::ErrorCollector::NAME, + error_message); } else { if (involves_default) { absl::StrAppend(&error_message, " This is not allowed in proto3."); } - AddError(message_name, field, - DescriptorPool::ErrorCollector::NAME, error_message); + AddError(message_name, field, DescriptorPool::ErrorCollector::NAME, + error_message); } } else { - JsonNameDetails details = { &field, name, is_custom }; + JsonNameDetails details = {&field, name, is_custom}; name_to_field[lowercase_name] = details; } } @@ -5974,8 +5980,7 @@ void DescriptorBuilder::CheckEnumValueUniqueness( const EnumValueDescriptor* value = result->value(i); std::string stripped = EnumValueToPascalCase(remover.MaybeRemove(value->name())); - std::pair::iterator, bool> - insert_result = values.insert(std::make_pair(stripped, value)); + auto insert_result = values.insert(std::make_pair(stripped, value)); bool inserted = insert_result.second; // We don't throw the error if the two conflicting symbols are identical, or From 7e745c4910630f49b243c7f8d1db2050bdb4ff01 Mon Sep 17 00:00:00 2001 From: Joshua Humphries Date: Thu, 15 Sep 2022 15:24:48 -0400 Subject: [PATCH 30/64] oops, fix name: LOG -> GOOGLE_LOG --- src/google/protobuf/io/tokenizer.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/google/protobuf/io/tokenizer.cc b/src/google/protobuf/io/tokenizer.cc index d7f100dbbd..4fcf81b3dc 100644 --- a/src/google/protobuf/io/tokenizer.cc +++ b/src/google/protobuf/io/tokenizer.cc @@ -1004,7 +1004,7 @@ bool Tokenizer::ParseInteger(const std::string& text, uint64_t max_value, double Tokenizer::ParseFloat(const std::string& text) { double result = 0; if (!TryParseFloat(text, &result)) { - LOG(DFATAL) + GOOGLE_LOG(DFATAL) << " Tokenizer::ParseFloat() passed text that could not have been" " tokenized as a float: " << absl::CEscape(text); From e293b5cc43f3416706c61e8c839e6e9ab4d0e853 Mon Sep 17 00:00:00 2001 From: Joshua Humphries Date: Thu, 15 Sep 2022 15:27:38 -0400 Subject: [PATCH 31/64] clarify comment --- src/google/protobuf/compiler/parser.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index 8158b9724e..e053eca7e5 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -1730,7 +1730,8 @@ bool Parser::ParseReserved(DescriptorProto* message, } bool Parser::ParseReservedName(std::string* name, const char* error_message) { - // capture position of token + // Capture the position of the token, in case we have to report an + // error after it is consumed. int line = input_->current().line; int col = input_->current().column; DO(ConsumeString(name, error_message)); From b6a3f6eb98ab0fc96d6ff7d66d4b77dc12cbb827 Mon Sep 17 00:00:00 2001 From: Deanna Garcia Date: Fri, 16 Sep 2022 17:55:33 +0000 Subject: [PATCH 32/64] Add public modifier --- .../protobuf/compiler/java/enum_field.cc | 22 +++++----- .../protobuf/compiler/java/enum_field_lite.cc | 22 +++++----- .../protobuf/compiler/java/map_field.cc | 12 +++--- .../protobuf/compiler/java/map_field_lite.cc | 14 +++---- src/google/protobuf/compiler/java/message.cc | 38 +++++++++--------- .../protobuf/compiler/java/message_field.cc | 24 +++++------ .../compiler/java/message_field_lite.cc | 24 +++++------ .../protobuf/compiler/java/message_lite.cc | 40 +++++++++---------- .../protobuf/compiler/java/primitive_field.cc | 22 +++++----- .../compiler/java/primitive_field_lite.cc | 22 +++++----- .../protobuf/compiler/java/string_field.cc | 22 +++++----- .../compiler/java/string_field_lite.cc | 22 +++++----- 12 files changed, 142 insertions(+), 142 deletions(-) diff --git a/src/google/protobuf/compiler/java/enum_field.cc b/src/google/protobuf/compiler/java/enum_field.cc index ea74d8bc6f..ab799f026c 100644 --- a/src/google/protobuf/compiler/java/enum_field.cc +++ b/src/google/protobuf/compiler/java/enum_field.cc @@ -276,7 +276,7 @@ void ImmutableEnumFieldGenerator::GenerateKotlinDslMembers( io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$ var $kt_name$: $kt_type$\n" + "$kt_deprecation$public var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -299,7 +299,7 @@ void ImmutableEnumFieldGenerator::GenerateKotlinDslMembers( WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "fun ${$clear$kt_capitalized_name$$}$() {\n" + "public fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -308,7 +308,7 @@ void ImmutableEnumFieldGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -1085,12 +1085,12 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$public val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -1103,7 +1103,7 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -1115,7 +1115,7 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -1126,7 +1126,7 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -1139,7 +1139,7 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -1151,7 +1151,7 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "operator fun com.google.protobuf.kotlin.DslList" + "public operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -1162,7 +1162,7 @@ void RepeatedImmutableEnumFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" diff --git a/src/google/protobuf/compiler/java/enum_field_lite.cc b/src/google/protobuf/compiler/java/enum_field_lite.cc index 713f805f98..c221a33368 100644 --- a/src/google/protobuf/compiler/java/enum_field_lite.cc +++ b/src/google/protobuf/compiler/java/enum_field_lite.cc @@ -311,7 +311,7 @@ void ImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$var $kt_name$: $kt_type$\n" + "$kt_deprecation$public var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -334,7 +334,7 @@ void ImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "fun ${$clear$kt_capitalized_name$$}$() {\n" + "public fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -343,7 +343,7 @@ void ImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -870,12 +870,12 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$ public val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -888,7 +888,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -900,7 +900,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -911,7 +911,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -924,7 +924,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -936,7 +936,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "operator fun com.google.protobuf.kotlin.DslList" + "public operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -947,7 +947,7 @@ void RepeatedImmutableEnumFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" diff --git a/src/google/protobuf/compiler/java/map_field.cc b/src/google/protobuf/compiler/java/map_field.cc index 66d7fbb9c5..d741ca472e 100644 --- a/src/google/protobuf/compiler/java/map_field.cc +++ b/src/google/protobuf/compiler/java/map_field.cc @@ -727,13 +727,13 @@ void ImmutableMapFieldGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print( variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$ public val $kt_name$: " "com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -746,7 +746,7 @@ void ImmutableMapFieldGenerator::GenerateKotlinDslMembers( printer->Print( variables_, "@JvmName(\"put$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslMap" + "public fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .put(key: $kt_key_type$, value: $kt_value_type$) {\n" " $kt_dsl_builder$.${$put$capitalized_name$$}$(key, value)\n" @@ -758,7 +758,7 @@ void ImmutableMapFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"set$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslMap" + "public inline operator fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .set(key: $kt_key_type$, value: $kt_value_type$) {\n" " put(key, value)\n" @@ -769,7 +769,7 @@ void ImmutableMapFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"remove$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslMap" + "public fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .remove(key: $kt_key_type$) {\n" " $kt_dsl_builder$.${$remove$capitalized_name$$}$(key)\n" @@ -780,7 +780,7 @@ void ImmutableMapFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"putAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslMap" + "public fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .putAll(map: kotlin.collections.Map<$kt_key_type$, $kt_value_type$>) " "{\n" diff --git a/src/google/protobuf/compiler/java/map_field_lite.cc b/src/google/protobuf/compiler/java/map_field_lite.cc index e116d1ebb6..471bbdaab9 100644 --- a/src/google/protobuf/compiler/java/map_field_lite.cc +++ b/src/google/protobuf/compiler/java/map_field_lite.cc @@ -871,13 +871,13 @@ void ImmutableMapFieldLiteGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print( variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$ public val $kt_name$: " "com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -890,7 +890,7 @@ void ImmutableMapFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print( variables_, "@JvmName(\"put$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslMap" + "public fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .put(key: $kt_key_type$, value: $kt_value_type$) {\n" " $kt_dsl_builder$.${$put$capitalized_name$$}$(key, value)\n" @@ -902,7 +902,7 @@ void ImmutableMapFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"set$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslMap" + "public inline operator fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .set(key: $kt_key_type$, value: $kt_value_type$) {\n" " put(key, value)\n" @@ -913,7 +913,7 @@ void ImmutableMapFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"remove$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslMap" + "public fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .remove(key: $kt_key_type$) {\n" " $kt_dsl_builder$.${$remove$capitalized_name$$}$(key)\n" @@ -924,7 +924,7 @@ void ImmutableMapFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"putAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslMap" + "public fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .putAll(map: kotlin.collections.Map<$kt_key_type$, $kt_value_type$>) " "{\n" @@ -936,7 +936,7 @@ void ImmutableMapFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslMap" + "public fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" diff --git a/src/google/protobuf/compiler/java/message.cc b/src/google/protobuf/compiler/java/message.cc index 52768bb477..55f486e3ee 100644 --- a/src/google/protobuf/compiler/java/message.cc +++ b/src/google/protobuf/compiler/java/message.cc @@ -1409,10 +1409,10 @@ void ImmutableMessageGenerator::GenerateKotlinDsl(io::Printer* printer) const { "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" "@com.google.protobuf.kotlin.ProtoDslMarker\n"); printer->Print( - "class Dsl private constructor(\n" + "public class Dsl private constructor(\n" " private val _builder: $message$.Builder\n" ") {\n" - " companion object {\n" + " public companion object {\n" " @kotlin.jvm.JvmSynthetic\n" " @kotlin.PublishedApi\n" " internal fun _create(builder: $message$.Builder): Dsl = " @@ -1435,10 +1435,10 @@ void ImmutableMessageGenerator::GenerateKotlinDsl(io::Printer* printer) const { for (auto oneof : oneofs_) { printer->Print( - "val $oneof_name$Case: $message$.$oneof_capitalized_name$Case\n" + "public val $oneof_name$Case: $message$.$oneof_capitalized_name$Case\n" " @JvmName(\"get$oneof_capitalized_name$Case\")\n" " get() = _builder.get$oneof_capitalized_name$Case()\n\n" - "fun clear$oneof_capitalized_name$() {\n" + "public fun clear$oneof_capitalized_name$() {\n" " _builder.clear$oneof_capitalized_name$()\n" "}\n", "oneof_name", context_->GetOneofGeneratorInfo(oneof)->name, @@ -1466,7 +1466,7 @@ void ImmutableMessageGenerator::GenerateKotlinMembers( } printer->Print( - "inline fun $camelcase_name$(block: $message_kt$.Dsl.() -> " + "public inline fun $camelcase_name$(block: $message_kt$.Dsl.() -> " "kotlin.Unit): " "$message$ " "=\n" @@ -1480,7 +1480,7 @@ void ImmutableMessageGenerator::GenerateKotlinMembers( EscapeKotlinKeywords(name_resolver_->GetClassName(descriptor_, true))); WriteMessageDocComment(printer, descriptor_, /* kdoc */ true); - printer->Print("object $name$Kt {\n", "name", descriptor_->name()); + printer->Print("public object $name$Kt {\n", "name", descriptor_->name()); printer->Indent(); GenerateKotlinDsl(printer); for (int i = 0; i < descriptor_->nested_type_count(); i++) { @@ -1501,7 +1501,7 @@ void ImmutableMessageGenerator::GenerateTopLevelKotlinMembers( } printer->Print( - "inline fun $message$.copy(block: $message_kt$.Dsl.() -> " + "public inline fun $message$.copy(block: $message_kt$.Dsl.() -> " "kotlin.Unit): $message$ =\n" " $message_kt$.Dsl._create(this.toBuilder()).apply { block() " "}._build()\n\n", @@ -1546,7 +1546,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@Suppress(\"UNCHECKED_CAST\")\n" "@kotlin.jvm.JvmSynthetic\n" - "operator fun get(extension: " + "public operator fun get(extension: " "com.google.protobuf.ExtensionLite<$message$, T>): T {\n" " return if (extension.isRepeated) {\n" " get(extension as com.google.protobuf.ExtensionLite<$message$, " @@ -1562,7 +1562,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" "@kotlin.jvm.JvmName(\"-getRepeatedExtension\")\n" - "operator fun get(\n" + "public operator fun get(\n" " extension: com.google.protobuf.ExtensionLite<$message$, List>\n" "): com.google.protobuf.kotlin.ExtensionList {\n" " return com.google.protobuf.kotlin.ExtensionList(extension, " @@ -1572,7 +1572,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "operator fun contains(extension: " + "public operator fun contains(extension: " "com.google.protobuf.ExtensionLite<$message$, *>): " "Boolean {\n" " return _builder.hasExtension(extension)\n" @@ -1581,7 +1581,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "fun clear(extension: " + "public fun clear(extension: " "com.google.protobuf.ExtensionLite<$message$, *>) " "{\n" " _builder.clearExtension(extension)\n" @@ -1601,7 +1601,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun > set(\n" + "public inline operator fun > set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" ") {\n" @@ -1612,7 +1612,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun set(\n" + "public inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, " "com.google.protobuf.ByteString>,\n" " value: com.google.protobuf.ByteString\n" @@ -1634,7 +1634,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "fun com.google.protobuf.kotlin.ExtensionList com.google.protobuf.kotlin.ExtensionList.add(value: E) {\n" " _builder.addExtension(this.extension, value)\n" "}\n\n", @@ -1643,7 +1643,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun " + "public inline operator fun " "com.google.protobuf.kotlin.ExtensionList.plusAssign" "(value: E) {\n" @@ -1653,7 +1653,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "fun com.google.protobuf.kotlin.ExtensionList com.google.protobuf.kotlin.ExtensionList.addAll(values: Iterable) {\n" " for (value in values) {\n" " add(value)\n" @@ -1664,7 +1664,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun " + "public inline operator fun " "com.google.protobuf.kotlin.ExtensionList.plusAssign(values: " "Iterable) {\n" @@ -1674,7 +1674,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "operator fun " + "public operator fun " "com.google.protobuf.kotlin.ExtensionList.set(index: Int, value: " "E) {\n" @@ -1685,7 +1685,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline fun com.google.protobuf.kotlin.ExtensionList<*, " + "public inline fun com.google.protobuf.kotlin.ExtensionList<*, " "$message$>.clear() {\n" " clear(extension)\n" "}\n\n", diff --git a/src/google/protobuf/compiler/java/message_field.cc b/src/google/protobuf/compiler/java/message_field.cc index 32da1b74eb..c51c71a020 100644 --- a/src/google/protobuf/compiler/java/message_field.cc +++ b/src/google/protobuf/compiler/java/message_field.cc @@ -426,7 +426,7 @@ void ImmutableMessageFieldGenerator::GenerateKotlinDslMembers( io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$var $kt_name$: $kt_type$\n" + "$kt_deprecation$public var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -437,7 +437,7 @@ void ImmutableMessageFieldGenerator::GenerateKotlinDslMembers( WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "fun ${$clear$kt_capitalized_name$$}$() {\n" + "public fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -445,7 +445,7 @@ void ImmutableMessageFieldGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); @@ -455,7 +455,7 @@ void ImmutableMessageFieldGenerator::GenerateKotlinDslMembers( void ImmutableMessageFieldGenerator::GenerateKotlinOrNull(io::Printer* printer) const { if (descriptor_->has_optional_keyword()) { printer->Print(variables_, - "val $classname$Kt.Dsl.$name$OrNull: $kt_type$?\n" + "public val $classname$Kt.Dsl.$name$OrNull: $kt_type$?\n" " get() = $kt_dsl_builder$.$name$OrNull\n"); } } @@ -1425,12 +1425,12 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$ public val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -1443,7 +1443,7 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -1455,7 +1455,7 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -1466,7 +1466,7 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -1479,7 +1479,7 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -1491,7 +1491,7 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "operator fun com.google.protobuf.kotlin.DslList" + "public operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -1502,7 +1502,7 @@ void RepeatedImmutableMessageFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" diff --git a/src/google/protobuf/compiler/java/message_field_lite.cc b/src/google/protobuf/compiler/java/message_field_lite.cc index ad685eb26d..5a05939c95 100644 --- a/src/google/protobuf/compiler/java/message_field_lite.cc +++ b/src/google/protobuf/compiler/java/message_field_lite.cc @@ -293,7 +293,7 @@ void ImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$var $kt_name$: $kt_type$\n" + "$kt_deprecation$public var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -304,7 +304,7 @@ void ImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "fun ${$clear$kt_capitalized_name$$}$() {\n" + "public fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -312,7 +312,7 @@ void ImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); GenerateKotlinOrNull(printer); @@ -321,7 +321,7 @@ void ImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( void ImmutableMessageFieldLiteGenerator::GenerateKotlinOrNull(io::Printer* printer) const { if (descriptor_->has_optional_keyword()) { printer->Print(variables_, - "val $classname$Kt.Dsl.$name$OrNull: $kt_type$?\n" + "public val $classname$Kt.Dsl.$name$OrNull: $kt_type$?\n" " get() = $kt_dsl_builder$.$name$OrNull\n"); } } @@ -819,12 +819,12 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$ public val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -837,7 +837,7 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -849,7 +849,7 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -860,7 +860,7 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -873,7 +873,7 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -885,7 +885,7 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "operator fun com.google.protobuf.kotlin.DslList" + "public operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -896,7 +896,7 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" diff --git a/src/google/protobuf/compiler/java/message_lite.cc b/src/google/protobuf/compiler/java/message_lite.cc index fc98ef5009..504e072bee 100644 --- a/src/google/protobuf/compiler/java/message_lite.cc +++ b/src/google/protobuf/compiler/java/message_lite.cc @@ -746,10 +746,10 @@ void ImmutableMessageLiteGenerator::GenerateKotlinDsl( "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" "@com.google.protobuf.kotlin.ProtoDslMarker\n"); printer->Print( - "class Dsl private constructor(\n" + "public class Dsl private constructor(\n" " private val _builder: $message$.Builder\n" ") {\n" - " companion object {\n" + " public companion object {\n" " @kotlin.jvm.JvmSynthetic\n" " @kotlin.PublishedApi\n" " internal fun _create(builder: $message$.Builder): Dsl = " @@ -772,10 +772,10 @@ void ImmutableMessageLiteGenerator::GenerateKotlinDsl( for (auto oneof : oneofs_) { printer->Print( - "val $oneof_name$Case: $message$.$oneof_capitalized_name$Case\n" + "public val $oneof_name$Case: $message$.$oneof_capitalized_name$Case\n" " @JvmName(\"get$oneof_capitalized_name$Case\")\n" " get() = _builder.get$oneof_capitalized_name$Case()\n\n" - "fun clear$oneof_capitalized_name$() {\n" + "public fun clear$oneof_capitalized_name$() {\n" " _builder.clear$oneof_capitalized_name$()\n" "}\n", "oneof_name", context_->GetOneofGeneratorInfo(oneof)->name, @@ -802,7 +802,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinMembers( printer->Print("@com.google.errorprone.annotations.CheckReturnValue\n"); } printer->Print( - "inline fun $camelcase_name$(block: $message_kt$.Dsl.() -> " + "public inline fun $camelcase_name$(block: $message_kt$.Dsl.() -> " "kotlin.Unit): $message$ =\n" " $message_kt$.Dsl._create($message$.newBuilder()).apply { block() " "}._build()\n", @@ -814,7 +814,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinMembers( EscapeKotlinKeywords(name_resolver_->GetClassName(descriptor_, true))); WriteMessageDocComment(printer, descriptor_, /* kdoc */ true); - printer->Print("object $name$Kt {\n", "name", descriptor_->name()); + printer->Print("public object $name$Kt {\n", "name", descriptor_->name()); printer->Indent(); GenerateKotlinDsl(printer); for (int i = 0; i < descriptor_->nested_type_count(); i++) { @@ -832,7 +832,7 @@ void ImmutableMessageLiteGenerator::GenerateTopLevelKotlinMembers( printer->Print("@com.google.errorprone.annotations.CheckReturnValue\n"); } printer->Print( - "inline fun $message$.copy(block: $message_kt$.Dsl.() -> " + "public inline fun $message$.copy(block: $message_kt$.Dsl.() -> " "kotlin.Unit): $message$ =\n" " $message_kt$.Dsl._create(this.toBuilder()).apply { block() " "}._build()\n\n", @@ -879,7 +879,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@Suppress(\"UNCHECKED_CAST\")\n" "@kotlin.jvm.JvmSynthetic\n" - "operator fun get(extension: " + "public operator fun get(extension: " "com.google.protobuf.ExtensionLite<$message$, T>): T {\n" " return if (extension.isRepeated) {\n" " get(extension as com.google.protobuf.ExtensionLite<$message$, " @@ -895,7 +895,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" "@kotlin.jvm.JvmName(\"-getRepeatedExtension\")\n" - "operator fun get(\n" + "public operator fun get(\n" " extension: com.google.protobuf.ExtensionLite<$message$, List>\n" "): com.google.protobuf.kotlin.ExtensionList {\n" " return com.google.protobuf.kotlin.ExtensionList(extension, " @@ -905,7 +905,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "operator fun contains(extension: " + "public operator fun contains(extension: " "com.google.protobuf.ExtensionLite<$message$, *>): " "Boolean {\n" " return _builder.hasExtension(extension)\n" @@ -914,7 +914,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "fun clear(extension: " + "public fun clear(extension: " "com.google.protobuf.ExtensionLite<$message$, *>) " "{\n" " _builder.clearExtension(extension)\n" @@ -934,7 +934,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun > set(\n" + "public inline operator fun > set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" ") {\n" @@ -945,7 +945,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun set(\n" + "public inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, " "com.google.protobuf.ByteString>,\n" " value: com.google.protobuf.ByteString\n" @@ -957,7 +957,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun set(\n" + "public inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" ") {\n" @@ -967,7 +967,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "fun com.google.protobuf.kotlin.ExtensionList com.google.protobuf.kotlin.ExtensionList.add(value: E) {\n" " _builder.addExtension(this.extension, value)\n" "}\n\n", @@ -976,7 +976,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun " + "public inline operator fun " "com.google.protobuf.kotlin.ExtensionList.plusAssign" "(value: E) {\n" @@ -986,7 +986,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "fun com.google.protobuf.kotlin.ExtensionList com.google.protobuf.kotlin.ExtensionList.addAll(values: Iterable) {\n" " for (value in values) {\n" " add(value)\n" @@ -997,7 +997,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun " + "public inline operator fun " "com.google.protobuf.kotlin.ExtensionList.plusAssign(values: " "Iterable) {\n" @@ -1007,7 +1007,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "operator fun " + "public operator fun " "com.google.protobuf.kotlin.ExtensionList.set(index: Int, value: " "E) {\n" @@ -1018,7 +1018,7 @@ void ImmutableMessageLiteGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline fun com.google.protobuf.kotlin.ExtensionList<*, " + "public inline fun com.google.protobuf.kotlin.ExtensionList<*, " "$message$>.clear() {\n" " clear(extension)\n" "}\n\n", diff --git a/src/google/protobuf/compiler/java/primitive_field.cc b/src/google/protobuf/compiler/java/primitive_field.cc index 3706ef164f..aae9b324d7 100644 --- a/src/google/protobuf/compiler/java/primitive_field.cc +++ b/src/google/protobuf/compiler/java/primitive_field.cc @@ -324,7 +324,7 @@ void ImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$var $kt_name$: $kt_type$\n" + "$kt_deprecation$public var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -335,7 +335,7 @@ void ImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "fun ${$clear$kt_capitalized_name$$}$() {\n" + "public fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -344,7 +344,7 @@ void ImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -854,12 +854,12 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$ public val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -872,7 +872,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -884,7 +884,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -895,7 +895,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -908,7 +908,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -920,7 +920,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "operator fun com.google.protobuf.kotlin.DslList" + "public operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -931,7 +931,7 @@ void RepeatedImmutablePrimitiveFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" diff --git a/src/google/protobuf/compiler/java/primitive_field_lite.cc b/src/google/protobuf/compiler/java/primitive_field_lite.cc index 28066bb6b2..b7ff8912c3 100644 --- a/src/google/protobuf/compiler/java/primitive_field_lite.cc +++ b/src/google/protobuf/compiler/java/primitive_field_lite.cc @@ -344,7 +344,7 @@ void ImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$var $kt_name$: $kt_type$\n" + "$kt_deprecation$public var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -355,7 +355,7 @@ void ImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "fun ${$clear$kt_capitalized_name$$}$() {\n" + "public fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -364,7 +364,7 @@ void ImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -691,12 +691,12 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$ public val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -709,7 +709,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -721,7 +721,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -732,7 +732,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -745,7 +745,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -757,7 +757,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "operator fun com.google.protobuf.kotlin.DslList" + "public operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -768,7 +768,7 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" diff --git a/src/google/protobuf/compiler/java/string_field.cc b/src/google/protobuf/compiler/java/string_field.cc index d8b5d4ef6f..a40d473149 100644 --- a/src/google/protobuf/compiler/java/string_field.cc +++ b/src/google/protobuf/compiler/java/string_field.cc @@ -383,7 +383,7 @@ void ImmutableStringFieldGenerator::GenerateKotlinDslMembers( io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$var $kt_name$: kotlin.String\n" + "$kt_deprecation$public var $kt_name$: kotlin.String\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -394,7 +394,7 @@ void ImmutableStringFieldGenerator::GenerateKotlinDslMembers( WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "fun ${$clear$kt_capitalized_name$$}$() {\n" + "public fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -403,7 +403,7 @@ void ImmutableStringFieldGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -968,14 +968,14 @@ void RepeatedImmutableStringFieldGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); // property for List WriteFieldAccessorDocComment(printer, descriptor_, LIST_GETTER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$public val $kt_name$: " "com.google.protobuf.kotlin.DslList" "\n" " @kotlin.jvm.JvmSynthetic\n" @@ -989,7 +989,7 @@ void RepeatedImmutableStringFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "." "add(value: kotlin.String) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -1002,7 +1002,7 @@ void RepeatedImmutableStringFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "." "plusAssign(value: kotlin.String) {\n" " add(value)\n" @@ -1015,7 +1015,7 @@ void RepeatedImmutableStringFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "." "addAll(values: kotlin.collections.Iterable) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -1029,7 +1029,7 @@ void RepeatedImmutableStringFieldGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "." "plusAssign(values: kotlin.collections.Iterable) {\n" " addAll(values)\n" @@ -1042,7 +1042,7 @@ void RepeatedImmutableStringFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "operator fun com.google.protobuf.kotlin.DslList" + "public operator fun com.google.protobuf.kotlin.DslList" "." "set(index: kotlin.Int, value: kotlin.String) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -1053,7 +1053,7 @@ void RepeatedImmutableStringFieldGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" diff --git a/src/google/protobuf/compiler/java/string_field_lite.cc b/src/google/protobuf/compiler/java/string_field_lite.cc index 2551d395cc..73e849917a 100644 --- a/src/google/protobuf/compiler/java/string_field_lite.cc +++ b/src/google/protobuf/compiler/java/string_field_lite.cc @@ -342,7 +342,7 @@ void ImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_, /* kdoc */ true); printer->Print(variables_, - "$kt_deprecation$var $kt_name$: kotlin.String\n" + "$kt_deprecation$public var $kt_name$: kotlin.String\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -353,7 +353,7 @@ void ImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false, /* kdoc */ true); printer->Print(variables_, - "fun ${$clear$kt_capitalized_name$$}$() {\n" + "public fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -362,7 +362,7 @@ void ImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -788,7 +788,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); // property for List @@ -796,7 +796,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( /* builder */ false, /* kdoc */ true); printer->Print( variables_, - "$kt_deprecation$ val $kt_name$: " + "$kt_deprecation$public val $kt_name$: " "com.google.protobuf.kotlin.DslList" "\n" "@kotlin.OptIn" @@ -811,7 +811,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "." "add(value: kotlin.String) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -824,7 +824,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "." "plusAssign(value: kotlin.String) {\n" " add(value)\n" @@ -837,7 +837,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "." "addAll(values: kotlin.collections.Iterable) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -851,7 +851,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun com.google.protobuf.kotlin.DslList" + "public inline operator fun com.google.protobuf.kotlin.DslList" "." "plusAssign(values: kotlin.collections.Iterable) {\n" " addAll(values)\n" @@ -864,7 +864,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "operator fun com.google.protobuf.kotlin.DslList" + "public operator fun com.google.protobuf.kotlin.DslList" "." "set(index: kotlin.Int, value: kotlin.String) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -875,7 +875,7 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateKotlinDslMembers( printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslList" + "public fun com.google.protobuf.kotlin.DslList" "." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" From 47a3ccf75666cd588d1c9b69beef3660e4d0bbc3 Mon Sep 17 00:00:00 2001 From: Deanna Garcia Date: Fri, 16 Sep 2022 17:59:00 +0000 Subject: [PATCH 33/64] Add missing public --- src/google/protobuf/compiler/java/map_field.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/google/protobuf/compiler/java/map_field.cc b/src/google/protobuf/compiler/java/map_field.cc index d741ca472e..0a59a32e35 100644 --- a/src/google/protobuf/compiler/java/map_field.cc +++ b/src/google/protobuf/compiler/java/map_field.cc @@ -792,7 +792,7 @@ void ImmutableMapFieldGenerator::GenerateKotlinDslMembers( variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"clear$kt_capitalized_name$\")\n" - "fun com.google.protobuf.kotlin.DslMap" + "public fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" From 42ce332a5f4cd471c2f35e07fb9fea6251e20cbb Mon Sep 17 00:00:00 2001 From: Deanna Garcia Date: Fri, 16 Sep 2022 18:07:52 +0000 Subject: [PATCH 34/64] Add missing modifier --- src/google/protobuf/compiler/java/message.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/google/protobuf/compiler/java/message.cc b/src/google/protobuf/compiler/java/message.cc index 55f486e3ee..af64911e97 100644 --- a/src/google/protobuf/compiler/java/message.cc +++ b/src/google/protobuf/compiler/java/message.cc @@ -1624,7 +1624,7 @@ void ImmutableMessageGenerator::GenerateKotlinExtensions( printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "inline operator fun set(\n" + "public inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" ") {\n" From 2202cc8d3302c2a7bf9624bc1fda63e7a5557a6d Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Fri, 16 Sep 2022 12:39:56 -0400 Subject: [PATCH 35/64] Add clang-format for some things are well formatted already. The sources haven't yet been reformatted, there are lots of Print() calls that end up worse, but those should probably get revisit to Emit() instead. --- .../protobuf/compiler/objectivec/objectivec_generator.h | 2 ++ .../protobuf/compiler/objectivec/objectivec_helpers.h | 2 ++ .../compiler/objectivec/objectivec_helpers_unittest.cc | 8 ++++++++ 3 files changed, 12 insertions(+) diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.h b/src/google/protobuf/compiler/objectivec/objectivec_generator.h index f863fc8686..acd9ce895f 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_generator.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.h @@ -37,7 +37,9 @@ #include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/descriptor.h" +// clang-format off #include "google/protobuf/port_def.inc" +// clang-format on namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h index 79a9643c17..a0a8d5b6e8 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers.h +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers.h @@ -40,7 +40,9 @@ #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/zero_copy_stream.h" +// clang-format off #include "google/protobuf/port_def.inc" +// clang-format on namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc b/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc index 0ae2451464..e6d0a7c613 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc @@ -101,10 +101,12 @@ TEST(ObjCHelper, TextFormatDecodeData_DecodeDataForString_ByteCodes) { // Long name so multiple decode ops are needed. + // clang-format off input_for_decode = "longFieldNameIsLooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong1000"; desired_output_for_decode = "long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1000"; + // clang-format on expected = std::string("\x04\xA5\xA4\xA2\xBF\x1F\x0E\x84\x0", 9); result = TextFormatDecodeData::DecodeDataForString(input_for_decode, desired_output_for_decode); @@ -154,11 +156,13 @@ TEST(ObjCHelper, TextFormatDecodeData_RawStrings) { EXPECT_EQ(4, decode_data.num_entries()); uint8_t expected_data[] = { + // clang-format off 0x4, 0x1, 0x0, 'z', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'J', 0x0, 0x3, 0x0, 'a', 'b', 'c', 'd', 'e', 'z', 'g', 'h', 'I', 'J', 0x0, 0x2, 0x0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 0x0, 0x4, 0x0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'J', 'z', 0x0, + // clang-format on }; std::string expected((const char*)expected_data, sizeof(expected_data)); @@ -172,12 +176,15 @@ TEST(ObjCHelper, TextFormatDecodeData_ByteCodes) { decode_data.AddString(3, "abcdefghIJ", "_AbcdefghIJ"); decode_data.AddString(2, "abcdefghIJ", "Abcd_EfghIJ"); decode_data.AddString(4, "abcdefghIJ", "ABCD__EfghI_j"); + // clang-format off decode_data.AddString(1000, "longFieldNameIsLooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong1000", "long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1000"); + // clang-format on EXPECT_EQ(5, decode_data.num_entries()); + // clang-format off uint8_t expected_data[] = { 0x5, // All as is (00 op) @@ -196,6 +203,7 @@ TEST(ObjCHelper, TextFormatDecodeData_ByteCodes) { // underscore, as is + 3 (00 op) 0xE8, 0x07, 0x04, 0xA5, 0xA4, 0xA2, 0xBF, 0x1F, 0x0E, 0x84, 0x0, }; + // clang-format on std::string expected((const char*)expected_data, sizeof(expected_data)); EXPECT_EQ(expected, decode_data.Data()); From 805812ec90ea06a1c81b1915bbdf6419c00a7f1a Mon Sep 17 00:00:00 2001 From: Adam Cozzette Date: Fri, 16 Sep 2022 15:11:30 -0700 Subject: [PATCH 36/64] Auto-generate CMake file lists in GitHub action (#10592) This GitHub action will run after each pull request merge and will auto-update the file lists in in src/file_lists.cmake. The action will run as our bot account. I realized that if a bug somehow made the file generation non-idempotent, this could trigger an infinite loop of commits, so I put in an extra safeguard against that. If the previous commit was by "Protobuf Team Bot", the GitHub action will revert any local changes to ensure that no new commit will be made. --- .github/workflows/generated_cmake.yml | 30 +++++++++++--------- cmake/push_auto_update.sh | 41 +++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 13 deletions(-) create mode 100755 cmake/push_auto_update.sh diff --git a/.github/workflows/generated_cmake.yml b/.github/workflows/generated_cmake.yml index 91dcd4f1e7..b63f16c0cc 100644 --- a/.github/workflows/generated_cmake.yml +++ b/.github/workflows/generated_cmake.yml @@ -1,8 +1,13 @@ -name: Generated CMake File Lists +name: Generate CMake File Lists on: - - push - - pull_request + push: + branches: + - main + - '[0-9]+.x' + # The 21.x branch predates support for auto-generation of the CMake file + # lists, so we make sure to exclude it. + - '!21.x' jobs: cmake: @@ -12,13 +17,12 @@ jobs: fail-fast: false # Don't cancel all jobs if one fails. steps: - - uses: actions/checkout@v2 - - name: Set up Bazel read-only caching - run: echo "BAZEL_CACHE_AUTH=--remote_upload_local_results=false" >> $GITHUB_ENV - - name: Generate CMake files - run: cd ${{ github.workspace }} && bazel build //pkg:gen_src_file_lists --test_output=errors $BAZEL_CACHE $BAZEL_CACHE_AUTH - - name: Compare to Golden file - run: diff -du bazel-bin/pkg/src_file_lists.cmake src/file_lists.cmake - - name: Report - run: echo "::error file=cmake/update_file_lists.sh::CMake files are stale, please run cmake/update_file_lists.sh" - if: failure() + - uses: actions/checkout@v3 + with: + # Note: this token has an expiration date, so if the workflow starts + # failing then you may need to generate a fresh token. + token: ${{ secrets.BOT_ACCESS_TOKEN }} + - name: Configure name and email address in Git + run: cd ${{ github.workspace }} && git config user.name "Protobuf Team Bot" && git config user.email "protobuf-team-bot@google.com" + - name: Commit and push update + run: cd ${{ github.workspace }} && ./cmake/push_auto_update.sh diff --git a/cmake/push_auto_update.sh b/cmake/push_auto_update.sh new file mode 100755 index 0000000000..abae4f4c0c --- /dev/null +++ b/cmake/push_auto_update.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +# This script updates the CMake file lists (i.e. src/file_lists.cmake), commits +# the resulting change, and pushes it. This does not do anything useful when +# run manually, but should be run by our GitHub action instead. + +set -ex + +# Exit early if the previous commit was made by the bot. This reduces the risk +# of a bug causing an infinite loop of auto-generated commits. +if (git log -1 --pretty=format:'%an' | grep -q "Protobuf Team Bot"); then + echo "Previous commit was authored by bot" + exit 0 +fi + +$(dirname -- "$0")/update_file_lists.sh + +# Try to determine the most recent pull request number. +title=$(git log -1 --pretty='%s') +pr_from_merge=$(echo "$title" | sed -n 's/^Merge pull request #\([0-9]\+\).*/\1/p') +pr_from_squash=$(echo "$title" | sed -n 's/^.*(#\([0-9]\+\))$/\1/p') + +pr="" +if [ ! -z "$pr_from_merge" ]; then + pr="$pr_from_merge" +elif [ ! -z "$pr_from_squash" ]; then + pr="$pr_from_squash" +fi + +if [ ! -z "$pr" ]; then + commit_message="Auto-generate CMake file lists after PR #$pr" +else + # If we are unable to determine the pull request number, we fall back on this + # default commit message. Typically this should not occur, but could happen + # if a pull request was merged via a rebase. + commit_message="Auto-generate CMake file lists" +fi + +git add -A +git diff --staged --quiet || git commit -am "$commit_message" +git push From 6be96e7a20801e70ef8f2a964e73eb47d09cd815 Mon Sep 17 00:00:00 2001 From: Adam Cozzette Date: Fri, 16 Sep 2022 15:20:52 -0700 Subject: [PATCH 37/64] Run CMake file auto-generation only on the main protobuf repo (#10611) This workflow will otherwise fail on forks, so let's make sure to do it only on the main repo where we need it. --- .github/workflows/generated_cmake.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/generated_cmake.yml b/.github/workflows/generated_cmake.yml index b63f16c0cc..640bd137ec 100644 --- a/.github/workflows/generated_cmake.yml +++ b/.github/workflows/generated_cmake.yml @@ -11,6 +11,7 @@ on: jobs: cmake: + if: github.repository == 'protocolbuffers/protobuf' runs-on: ubuntu-latest strategy: From 975ed9f7045a32c5abf3014cb62fe61f9a9201bb Mon Sep 17 00:00:00 2001 From: Adam Cozzette Date: Fri, 16 Sep 2022 15:55:16 -0700 Subject: [PATCH 38/64] Make slight change to ordering in src/file_lists.cmake (#10612) This change does not directly do anything useful, but the goal is to confirm that the GitHub action for auto-generating file_lists.cmake will quickly rewrite the file in its canonical form. --- src/file_lists.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/file_lists.cmake b/src/file_lists.cmake index be3d61ee14..0b15b8cc1c 100644 --- a/src/file_lists.cmake +++ b/src/file_lists.cmake @@ -11,8 +11,8 @@ endif() # //pkg:protobuf set(libprotobuf_srcs - ${protobuf_SOURCE_DIR}/src/google/protobuf/any.pb.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/api.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/any.pb.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/duration.pb.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/empty.pb.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/field_mask.pb.cc From fe9db54cedabf8ccb09c241c2477d7953d777844 Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Fri, 16 Sep 2022 22:55:52 +0000 Subject: [PATCH 39/64] Auto-generate CMake file lists after PR #10612 --- src/file_lists.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/file_lists.cmake b/src/file_lists.cmake index 0b15b8cc1c..be3d61ee14 100644 --- a/src/file_lists.cmake +++ b/src/file_lists.cmake @@ -11,8 +11,8 @@ endif() # //pkg:protobuf set(libprotobuf_srcs - ${protobuf_SOURCE_DIR}/src/google/protobuf/api.pb.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/any.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/api.pb.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/duration.pb.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/empty.pb.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/field_mask.pb.cc From e18aa2eda7835007c805c07cb3c4025aebda7b94 Mon Sep 17 00:00:00 2001 From: Mike Kruskal <62662355+mkruskal-google@users.noreply.github.com> Date: Fri, 16 Sep 2022 18:56:59 -0700 Subject: [PATCH 40/64] Fix broken examples build (#10614) * Add .bazelrc for examples repo * Include examples in some of our basic tests --- examples/.bazelrc | 1 + kokoro/linux/bazel/common.cfg | 2 +- kokoro/linux/cmake/build.sh | 2 +- kokoro/windows/bazel/build.bat | 2 +- kokoro/windows/cmake/build.bat | 1 + 5 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 examples/.bazelrc diff --git a/examples/.bazelrc b/examples/.bazelrc new file mode 100644 index 0000000000..554440cfe3 --- /dev/null +++ b/examples/.bazelrc @@ -0,0 +1 @@ +build --cxxopt=-std=c++14 --host_cxxopt=-std=c++14 diff --git a/kokoro/linux/bazel/common.cfg b/kokoro/linux/bazel/common.cfg index 6d35d8bbaa..cd41cb2cb8 100644 --- a/kokoro/linux/bazel/common.cfg +++ b/kokoro/linux/bazel/common.cfg @@ -6,7 +6,7 @@ timeout_mins: 15 env_vars { key: "BAZEL_TARGETS" - value: "//src/..." + value: "//src/... @com_google_protobuf_examples//..." } action { diff --git a/kokoro/linux/cmake/build.sh b/kokoro/linux/cmake/build.sh index 523253da25..ee06d95cf9 100755 --- a/kokoro/linux/cmake/build.sh +++ b/kokoro/linux/cmake/build.sh @@ -19,7 +19,7 @@ docker run \ --cidfile $tmpfile \ -v $GIT_REPO_ROOT:/workspace \ $CONTAINER_IMAGE \ - /test.sh -Dprotobuf_BUILD_CONFORMANCE=ON + /test.sh -Dprotobuf_BUILD_CONFORMANCE=ON -Dprotobuf_BUILD_EXAMPLES=ON # Save logs for Kokoro docker cp \ diff --git a/kokoro/windows/bazel/build.bat b/kokoro/windows/bazel/build.bat index 0b2ba9fc13..55fba16579 100644 --- a/kokoro/windows/bazel/build.bat +++ b/kokoro/windows/bazel/build.bat @@ -24,7 +24,7 @@ bazel %BAZEL_STARTUP% build //:protoc //:protobuf //:protobuf_lite %BAZEL_FLAGS% @rem TODO(b/241484899) Enable conformance tests on windows. bazel %BAZEL_STARTUP% test %BAZEL_FLAGS% ^ --test_tag_filters=-conformance --build_tag_filters=-conformance ^ - //src/... || goto :error + //src/... @com_google_protobuf_examples//... || goto :error goto :EOF diff --git a/kokoro/windows/cmake/build.bat b/kokoro/windows/cmake/build.bat index 29d012ba1c..49c89d3c84 100644 --- a/kokoro/windows/cmake/build.bat +++ b/kokoro/windows/cmake/build.bat @@ -13,6 +13,7 @@ cd build cmake .. ^ -G "Visual Studio 15 2017" -A x64 ^ + -Dprotobuf_BUILD_EXAMPLES=ON ^ -Dprotobuf_BUILD_CONFORMANCE=OFF ^ -Dprotobuf_WITH_ZLIB=OFF ^ -Dprotobuf_TEST_XML_OUTDIR=%KOKORO_ARTIFACTS_DIR%\logs\ || goto :error From f191ab0f35432c76fff0763509a4cc6439183d49 Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Thu, 15 Sep 2022 14:40:15 -0400 Subject: [PATCH 41/64] Provide a protocol for GPBExtensionRegistry's lookup support. This allows some to use an alternative registry if they have a different implementation. This is really just wiring though the change to use the GPBExtensionRegistry protocol vs the concrete GPBExtensionRegistry through the other apis. --- objectivec/GPBCodedInputStream.h | 4 +-- objectivec/GPBCodedInputStream.m | 6 ++-- .../GPBCodedInputStream_PackagePrivate.h | 4 +-- objectivec/GPBDictionary.m | 4 +-- objectivec/GPBDictionary_PackagePrivate.h | 4 +-- objectivec/GPBExtensionInternals.h | 4 +-- objectivec/GPBExtensionInternals.m | 6 ++-- objectivec/GPBExtensionRegistry.h | 32 +++++++++++-------- objectivec/GPBMessage.h | 14 ++++---- objectivec/GPBMessage.m | 24 +++++++------- objectivec/GPBMessage_PackagePrivate.h | 4 +-- 11 files changed, 56 insertions(+), 50 deletions(-) diff --git a/objectivec/GPBCodedInputStream.h b/objectivec/GPBCodedInputStream.h index 1886ccf61b..73b65581d7 100644 --- a/objectivec/GPBCodedInputStream.h +++ b/objectivec/GPBCodedInputStream.h @@ -31,7 +31,7 @@ #import @class GPBMessage; -@class GPBExtensionRegistry; +@protocol GPBExtensionRegistry; NS_ASSUME_NONNULL_BEGIN @@ -184,7 +184,7 @@ CF_EXTERN_C_END * extensions for message. **/ - (void)readMessage:(GPBMessage *)message - extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry; + extensionRegistry:(nullable id)extensionRegistry; /** * Reads and discards a single field, given its tag value. diff --git a/objectivec/GPBCodedInputStream.m b/objectivec/GPBCodedInputStream.m index c459391e08..25dde75320 100644 --- a/objectivec/GPBCodedInputStream.m +++ b/objectivec/GPBCodedInputStream.m @@ -434,7 +434,7 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, - (void)readGroup:(int32_t)fieldNumber message:(GPBMessage *)message - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + extensionRegistry:(id)extensionRegistry { CheckRecursionLimit(&state_); ++state_.recursionDepth; [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry]; @@ -454,7 +454,7 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, } - (void)readMessage:(GPBMessage *)message - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + extensionRegistry:(id)extensionRegistry { CheckRecursionLimit(&state_); int32_t length = ReadRawVarint32(&state_); size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length); @@ -466,7 +466,7 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, } - (void)readMapEntry:(id)mapDictionary - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + extensionRegistry:(id)extensionRegistry field:(GPBFieldDescriptor *)field parentMessage:(GPBMessage *)parentMessage { CheckRecursionLimit(&state_); diff --git a/objectivec/GPBCodedInputStream_PackagePrivate.h b/objectivec/GPBCodedInputStream_PackagePrivate.h index 43ec6e79b2..cdfb0dcc3f 100644 --- a/objectivec/GPBCodedInputStream_PackagePrivate.h +++ b/objectivec/GPBCodedInputStream_PackagePrivate.h @@ -61,7 +61,7 @@ typedef struct GPBCodedInputStreamState { // support for older data. - (void)readGroup:(int32_t)fieldNumber message:(GPBMessage *)message - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry; + extensionRegistry:(id)extensionRegistry; // Reads a group field value from the stream and merges it into the given // UnknownFieldSet. @@ -70,7 +70,7 @@ typedef struct GPBCodedInputStreamState { // Reads a map entry. - (void)readMapEntry:(id)mapDictionary - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + extensionRegistry:(id)extensionRegistry field:(GPBFieldDescriptor *)field parentMessage:(GPBMessage *)parentMessage; @end diff --git a/objectivec/GPBDictionary.m b/objectivec/GPBDictionary.m index 187a97092f..77642c27f9 100644 --- a/objectivec/GPBDictionary.m +++ b/objectivec/GPBDictionary.m @@ -386,7 +386,7 @@ BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescri static void ReadValue(GPBCodedInputStream *stream, GPBGenericValue *valueToFill, GPBDataType type, - GPBExtensionRegistry *registry, + idregistry, GPBFieldDescriptor *field) { switch (type) { case GPBDataTypeBool: @@ -454,7 +454,7 @@ static void ReadValue(GPBCodedInputStream *stream, void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream, - GPBExtensionRegistry *registry, + idregistry, GPBFieldDescriptor *field, GPBMessage *parentMessage) { GPBDataType keyDataType = field.mapKeyDataType; diff --git a/objectivec/GPBDictionary_PackagePrivate.h b/objectivec/GPBDictionary_PackagePrivate.h index 15e4283264..d494b7ee88 100644 --- a/objectivec/GPBDictionary_PackagePrivate.h +++ b/objectivec/GPBDictionary_PackagePrivate.h @@ -34,7 +34,7 @@ @class GPBCodedInputStream; @class GPBCodedOutputStream; -@class GPBExtensionRegistry; +@protocol GPBExtensionRegistry; @class GPBFieldDescriptor; @protocol GPBDictionaryInternalsProtocol @@ -493,7 +493,7 @@ BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, // Helper to read a map instead. void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream, - GPBExtensionRegistry *registry, + idregistry, GPBFieldDescriptor *field, GPBMessage *parentMessage); diff --git a/objectivec/GPBExtensionInternals.h b/objectivec/GPBExtensionInternals.h index 2b980aefa4..854b57fe89 100644 --- a/objectivec/GPBExtensionInternals.h +++ b/objectivec/GPBExtensionInternals.h @@ -34,12 +34,12 @@ @class GPBCodedInputStream; @class GPBCodedOutputStream; -@class GPBExtensionRegistry; +@protocol GPBExtensionRegistry; void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream, GPBCodedInputStream *input, - GPBExtensionRegistry *extensionRegistry, + idextensionRegistry, GPBMessage *message); size_t GPBComputeExtensionSerializedSizeIncludingTag( diff --git a/objectivec/GPBExtensionInternals.m b/objectivec/GPBExtensionInternals.m index bacec5740a..b74591e0a0 100644 --- a/objectivec/GPBExtensionInternals.m +++ b/objectivec/GPBExtensionInternals.m @@ -40,7 +40,7 @@ static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, GPBCodedInputStream *input, - GPBExtensionRegistry *extensionRegistry, + idextensionRegistry, GPBMessage *existingValue) __attribute__((ns_returns_retained)); @@ -273,7 +273,7 @@ static void WriteArrayIncludingTagsToCodedOutputStream( void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream, GPBCodedInputStream *input, - GPBExtensionRegistry *extensionRegistry, + idextensionRegistry, GPBMessage *message) { GPBExtensionDescription *description = extension->description_; GPBCodedInputStreamState *state = &input->state_; @@ -334,7 +334,7 @@ size_t GPBComputeExtensionSerializedSizeIncludingTag( // Note that this returns a retained value intentionally. static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, GPBCodedInputStream *input, - GPBExtensionRegistry *extensionRegistry, + idextensionRegistry, GPBMessage *existingValue) { GPBExtensionDescription *description = extension->description_; GPBCodedInputStreamState *state = &input->state_; diff --git a/objectivec/GPBExtensionRegistry.h b/objectivec/GPBExtensionRegistry.h index d79632d28b..b1850568d9 100644 --- a/objectivec/GPBExtensionRegistry.h +++ b/objectivec/GPBExtensionRegistry.h @@ -41,6 +41,24 @@ NS_ASSUME_NONNULL_BEGIN * GPBExtensionRegistry in which you have registered any extensions that you * want to be able to parse. Otherwise, those extensions will just be treated * like unknown fields. + **/ +@protocol GPBExtensionRegistry + +/** + * Looks for the extension registered for the given field number on a given + * GPBDescriptor. + * + * @param descriptor The descriptor to look for a registered extension on. + * @param fieldNumber The field number of the extension to look for. + * + * @return The registered GPBExtensionDescriptor or nil if none was found. + **/ +- (nullable GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor + fieldNumber:(NSInteger)fieldNumber; +@end + +/** + * A concrete implementation of `GPBExtensionRegistry`. * * The *Root classes provide `+extensionRegistry` for the extensions defined * in a given file *and* all files it imports. You can also create a @@ -54,7 +72,7 @@ NS_ASSUME_NONNULL_BEGIN * MyMessage *msg = [MyMessage parseData:data extensionRegistry:registry error:&parseError]; * ``` **/ -@interface GPBExtensionRegistry : NSObject +@interface GPBExtensionRegistry : NSObject /** * Adds the given GPBExtensionDescriptor to this registry. @@ -70,18 +88,6 @@ NS_ASSUME_NONNULL_BEGIN **/ - (void)addExtensions:(GPBExtensionRegistry *)registry; -/** - * Looks for the extension registered for the given field number on a given - * GPBDescriptor. - * - * @param descriptor The descriptor to look for a registered extension on. - * @param fieldNumber The field number of the extension to look for. - * - * @return The registered GPBExtensionDescriptor or nil if none was found. - **/ -- (nullable GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor - fieldNumber:(NSInteger)fieldNumber; - @end NS_ASSUME_NONNULL_END diff --git a/objectivec/GPBMessage.h b/objectivec/GPBMessage.h index 01253a4afc..990a796faf 100644 --- a/objectivec/GPBMessage.h +++ b/objectivec/GPBMessage.h @@ -36,7 +36,7 @@ @class GPBCodedInputStream; @class GPBCodedOutputStream; @class GPBExtensionDescriptor; -@class GPBExtensionRegistry; +@protocol GPBExtensionRegistry; @class GPBFieldDescriptor; @class GPBUnknownFieldSet; @@ -147,7 +147,7 @@ CF_EXTERN_C_END * @return A new instance of the generated class. **/ + (nullable instancetype)parseFromData:(NSData *)data - extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry + extensionRegistry:(nullable id)extensionRegistry error:(NSError **)errorPtr; /** @@ -171,7 +171,7 @@ CF_EXTERN_C_END **/ + (nullable instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: - (nullable GPBExtensionRegistry *)extensionRegistry + (nullable id)extensionRegistry error:(NSError **)errorPtr; /** @@ -196,7 +196,7 @@ CF_EXTERN_C_END **/ + (nullable instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: - (nullable GPBExtensionRegistry *)extensionRegistry + (nullable id)extensionRegistry error:(NSError **)errorPtr; /** @@ -239,7 +239,7 @@ CF_EXTERN_C_END * @return An initialized instance of the generated class. **/ - (nullable instancetype)initWithData:(NSData *)data - extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry + extensionRegistry:(nullable id)extensionRegistry error:(NSError **)errorPtr; /** @@ -264,7 +264,7 @@ CF_EXTERN_C_END **/ - (nullable instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: - (nullable GPBExtensionRegistry *)extensionRegistry + (nullable id)extensionRegistry error:(NSError **)errorPtr; /** @@ -278,7 +278,7 @@ CF_EXTERN_C_END * unsuccessful. **/ - (void)mergeFromData:(NSData *)data - extensionRegistry:(nullable GPBExtensionRegistry *)extensionRegistry; + extensionRegistry:(nullable id)extensionRegistry; /** * Merges the fields from another message (of the same type) into this diff --git a/objectivec/GPBMessage.m b/objectivec/GPBMessage.m index ee94dee8ed..b293604608 100644 --- a/objectivec/GPBMessage.m +++ b/objectivec/GPBMessage.m @@ -881,7 +881,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } - (instancetype)initWithData:(NSData *)data - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + extensionRegistry:(id)extensionRegistry error:(NSError **)errorPtr { if ((self = [self init])) { @try { @@ -912,7 +912,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { - (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: - (GPBExtensionRegistry *)extensionRegistry + (id)extensionRegistry error:(NSError **)errorPtr { if ((self = [self init])) { @try { @@ -1973,7 +1973,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { #pragma mark - mergeFrom - (void)mergeFromData:(NSData *)data - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + extensionRegistry:(id)extensionRegistry { GPBCodedInputStream *input = [[GPBCodedInputStream alloc] initWithData:data]; [self mergeFromCodedInputStream:input extensionRegistry:extensionRegistry]; [input checkLastTagWas:0]; @@ -1983,7 +1983,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { #pragma mark - mergeDelimitedFrom - (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + extensionRegistry:(id)extensionRegistry { GPBCodedInputStreamState *state = &input->state_; if (GPBCodedInputStreamIsAtEnd(state)) { return; @@ -2003,7 +2003,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } + (instancetype)parseFromData:(NSData *)data - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + extensionRegistry:(id)extensionRegistry error:(NSError **)errorPtr { return [[[self alloc] initWithData:data extensionRegistry:extensionRegistry @@ -2011,7 +2011,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } + (instancetype)parseFromCodedInputStream:(GPBCodedInputStream *)input - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + extensionRegistry:(id)extensionRegistry error:(NSError **)errorPtr { return [[[self alloc] initWithCodedInputStream:input @@ -2023,7 +2023,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { + (instancetype)parseDelimitedFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: - (GPBExtensionRegistry *)extensionRegistry + (id)extensionRegistry error:(NSError **)errorPtr { GPBMessage *message = [[[self alloc] init] autorelease]; @try { @@ -2065,7 +2065,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } - (void)parseMessageSet:(GPBCodedInputStream *)input - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + extensionRegistry:(id)extensionRegistry { uint32_t typeId = 0; NSData *rawBytes = nil; GPBExtensionDescriptor *extension = nil; @@ -2117,7 +2117,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } - (BOOL)parseUnknownField:(GPBCodedInputStream *)input - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry + extensionRegistry:(id)extensionRegistry tag:(uint32_t)tag { GPBWireFormat wireType = GPBWireFormatGetTagWireType(tag); int32_t fieldNumber = GPBWireFormatGetTagFieldNumber(tag); @@ -2170,7 +2170,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { static void MergeSingleFieldFromCodedInputStream( GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax, - GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) { + GPBCodedInputStream *input, idextensionRegistry) { GPBDataType fieldDataType = GPBGetFieldDataType(field); switch (fieldDataType) { #define CASE_SINGLE_POD(NAME, TYPE, FUNC_TYPE) \ @@ -2306,7 +2306,7 @@ static void MergeRepeatedPackedFieldFromCodedInputStream( static void MergeRepeatedNotPackedFieldFromCodedInputStream( GPBMessage *self, GPBFieldDescriptor *field, GPBFileSyntax syntax, - GPBCodedInputStream *input, GPBExtensionRegistry *extensionRegistry) { + GPBCodedInputStream *input, idextensionRegistry) { GPBCodedInputStreamState *state = &input->state_; id genericArray = GetOrCreateArrayIvarWithField(self, field); switch (GPBGetFieldDataType(field)) { @@ -2371,7 +2371,7 @@ static void MergeRepeatedNotPackedFieldFromCodedInputStream( } - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry { + extensionRegistry:(id)extensionRegistry { GPBDescriptor *descriptor = [self descriptor]; GPBFileSyntax syntax = descriptor.file.syntax; GPBCodedInputStreamState *state = &input->state_; diff --git a/objectivec/GPBMessage_PackagePrivate.h b/objectivec/GPBMessage_PackagePrivate.h index ca10983b3c..a8755a29ce 100644 --- a/objectivec/GPBMessage_PackagePrivate.h +++ b/objectivec/GPBMessage_PackagePrivate.h @@ -78,13 +78,13 @@ typedef struct GPBMessage_Storage *GPBMessage_StoragePtr; // or zero for EOF. // NOTE: This will throw if there is an error while parsing. - (void)mergeFromCodedInputStream:(GPBCodedInputStream *)input - extensionRegistry:(GPBExtensionRegistry *)extensionRegistry; + extensionRegistry:(id)extensionRegistry; // Parses the next delimited message of this type from the input and merges it // with this message. - (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input extensionRegistry: - (GPBExtensionRegistry *)extensionRegistry; + (id)extensionRegistry; - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data; From 01c340d0bb9abb2654554afc732df2c89774ce81 Mon Sep 17 00:00:00 2001 From: Mike Kruskal <62662355+mkruskal-google@users.noreply.github.com> Date: Mon, 19 Sep 2022 09:50:19 -0700 Subject: [PATCH 42/64] Adding full build to 32 bit tests (#10589) * Adding full build to 32 bit tests * Running C++ tests in 32 bit builds * Patching static assert test failure * Test fixes for 32-bit architectures * Cleanup after CMake build * Save protoc before cleanup * Route protoc better --- kokoro/linux/32-bit/test_php.sh | 11 ++++++-- php/generate_descriptor_protos.sh | 4 ++- php/generate_test_protos.sh | 4 ++- .../compiler/cpp/message_size_unittest.cc | 2 +- src/google/protobuf/extension_set_unittest.cc | 6 ++-- .../protobuf/io/zero_copy_stream_unittest.cc | 3 ++ .../protobuf/repeated_field_unittest.cc | 4 +-- src/google/protobuf/util/time_util_test.cc | 28 +++++++++++-------- 8 files changed, 42 insertions(+), 20 deletions(-) diff --git a/kokoro/linux/32-bit/test_php.sh b/kokoro/linux/32-bit/test_php.sh index 3770b84af3..739467b20c 100644 --- a/kokoro/linux/32-bit/test_php.sh +++ b/kokoro/linux/32-bit/test_php.sh @@ -36,9 +36,13 @@ build_php_c() { test_php_c } -cmake . -cmake --build . --target protoc -- -j20 +mkdir build +pushd build +cmake .. +cmake --build . -- -j20 +ctest --verbose --parallel 20 export PROTOC=$(pwd)/protoc +popd build_php 7.0 build_php 7.1 @@ -49,3 +53,6 @@ build_php_c 7.4 build_php_c 7.1-zts build_php_c 7.2-zts build_php_c 7.5-zts + +# Cleanup after CMake build +rm -rf build diff --git a/php/generate_descriptor_protos.sh b/php/generate_descriptor_protos.sh index 1a600abc63..0e5be35e24 100755 --- a/php/generate_descriptor_protos.sh +++ b/php/generate_descriptor_protos.sh @@ -5,7 +5,9 @@ set -e -PROTOC=$(realpath protoc) +if [[ -z "${PROTOC}" ]]; then + PROTOC=$(realpath protoc) +fi if [ ! -f $PROTOC ]; then bazel build -c opt //:protoc PROTOC=$(realpath bazel-bin/protoc) diff --git a/php/generate_test_protos.sh b/php/generate_test_protos.sh index 565c7ec1cd..6d06f959b9 100755 --- a/php/generate_test_protos.sh +++ b/php/generate_test_protos.sh @@ -4,7 +4,9 @@ set -ex cd `dirname $0`/.. -PROTOC=$(pwd)/protoc +if [[ -z "${PROTOC}" ]]; then + PROTOC=$(pwd)/protoc +fi if [ ! -f $PROTOC ]; then bazel build -c opt //:protoc PROTOC=$(pwd)/bazel-bin/protoc diff --git a/src/google/protobuf/compiler/cpp/message_size_unittest.cc b/src/google/protobuf/compiler/cpp/message_size_unittest.cc index a75d77a70c..ed4a90e223 100644 --- a/src/google/protobuf/compiler/cpp/message_size_unittest.cc +++ b/src/google/protobuf/compiler/cpp/message_size_unittest.cc @@ -139,9 +139,9 @@ TEST(GeneratedMessageTest, OneStringSize) { TEST(GeneratedMessageTest, MoreStringSize) { struct MockGenerated : public MockMessageBase { // 16 bytes - int has_bits[1]; // 4 bytes int cached_size; // 4 bytes MockRepeatedPtrField data; // 24 bytes + // + 4 bytes padding }; GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 48); EXPECT_EQ(sizeof(protobuf_unittest::MoreString), sizeof(MockGenerated)); diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc index 8b436bc20c..84da3c5465 100644 --- a/src/google/protobuf/extension_set_unittest.cc +++ b/src/google/protobuf/extension_set_unittest.cc @@ -855,8 +855,10 @@ TEST(ExtensionSetTest, SpaceUsedExcludingSelf) { const size_t old_capacity = \ message->GetRepeatedExtension(unittest::repeated_##type##_extension) \ .Capacity(); \ - EXPECT_GE(old_capacity, \ - (RepeatedFieldLowerClampLimit())); \ + EXPECT_GE( \ + old_capacity, \ + (RepeatedFieldLowerClampLimit())); \ for (int i = 0; i < 16; ++i) { \ message->AddExtension(unittest::repeated_##type##_extension, value); \ } \ diff --git a/src/google/protobuf/io/zero_copy_stream_unittest.cc b/src/google/protobuf/io/zero_copy_stream_unittest.cc index d82354e571..d656da5f13 100644 --- a/src/google/protobuf/io/zero_copy_stream_unittest.cc +++ b/src/google/protobuf/io/zero_copy_stream_unittest.cc @@ -720,6 +720,9 @@ TEST_F(IoTest, StringIo) { // Verifies that outputs up to kint32max can be created. TEST_F(IoTest, LargeOutput) { + // Filter out this test on 32-bit architectures. + if(sizeof(void*) < 8) return; + std::string str; StringOutputStream output(&str); void* unused_data; diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc index eb0b9091cf..3baf6f25bb 100644 --- a/src/google/protobuf/repeated_field_unittest.cc +++ b/src/google/protobuf/repeated_field_unittest.cc @@ -429,14 +429,14 @@ TEST(RepeatedField, ReserveNothing) { TEST(RepeatedField, ReserveLowerClamp) { int clamped_value = internal::CalculateReserveSize(0, 1); - EXPECT_GE(clamped_value, 8 / sizeof(bool)); + EXPECT_GE(clamped_value, sizeof(void*) / sizeof(bool)); EXPECT_EQ((internal::RepeatedFieldLowerClampLimit()), clamped_value); // EXPECT_EQ(clamped_value, (internal::CalculateReserveSize( clamped_value, 2))); clamped_value = internal::CalculateReserveSize(0, 1); - EXPECT_GE(clamped_value, 8 / sizeof(int)); + EXPECT_GE(clamped_value, sizeof(void*) / sizeof(int)); EXPECT_EQ((internal::RepeatedFieldLowerClampLimit()), clamped_value); // EXPECT_EQ(clamped_value, (internal::CalculateReserveSize= sizeof(uint64_t)) { + Timestamp begin, end; + EXPECT_TRUE(TimeUtil::FromString("0001-01-01T00:00:00Z", &begin)); + EXPECT_EQ(TimeUtil::kTimestampMinSeconds, begin.seconds()); + EXPECT_EQ(0, begin.nanos()); + EXPECT_TRUE(TimeUtil::FromString("9999-12-31T23:59:59.999999999Z", &end)); + EXPECT_EQ(TimeUtil::kTimestampMaxSeconds, end.seconds()); + EXPECT_EQ(999999999, end.nanos()); + EXPECT_EQ("0001-01-01T00:00:00Z", TimeUtil::ToString(begin)); + EXPECT_EQ("9999-12-31T23:59:59.999999999Z", TimeUtil::ToString(end)); + } // Test negative timestamps. Timestamp time = TimeUtil::NanosecondsToTimestamp(-1); @@ -94,9 +97,12 @@ TEST(TimeUtilTest, DurationStringFormat) { EXPECT_TRUE(TimeUtil::FromString("0001-01-01T00:00:00Z", &begin)); EXPECT_TRUE(TimeUtil::FromString("9999-12-31T23:59:59.999999999Z", &end)); - EXPECT_EQ("315537897599.999999999s", TimeUtil::ToString(end - begin)); + // These these are out of bounds for 32-bit architectures. + if(sizeof(time_t) >= sizeof(uint64_t)) { + EXPECT_EQ("315537897599.999999999s", TimeUtil::ToString(end - begin)); + EXPECT_EQ("-315537897599.999999999s", TimeUtil::ToString(begin - end)); + } EXPECT_EQ(999999999, (end - begin).nanos()); - EXPECT_EQ("-315537897599.999999999s", TimeUtil::ToString(begin - end)); EXPECT_EQ(-999999999, (begin - end).nanos()); // Generated output should contain 3, 6, or 9 fractional digits. From 81e35132bff7c6752462f4b606af821b80ee7b98 Mon Sep 17 00:00:00 2001 From: Mike Kruskal <62662355+mkruskal-google@users.noreply.github.com> Date: Mon, 19 Sep 2022 11:08:21 -0700 Subject: [PATCH 43/64] Improve CMake installation tests (#10615) * Using glob to remove headers instead of cyclic file_lists * Simplify CMake config and include missing files * Don't remove generated proto headers * Fix broken CMake proto dependencies instead of opting out pb.h files. * Fixing cyclic dependency --- BUILD.bazel | 6 + cmake/conformance.cmake | 17 +- cmake/tests.cmake | 43 +++-- kokoro/windows/cmake/build.bat | 4 +- kokoro/windows/cmake_install/build.bat | 4 +- kokoro/windows/cmake_nmake/build.bat | 4 +- kokoro/windows/cmake_shared/build.bat | 4 +- pkg/BUILD.bazel | 40 +++-- src/file_lists.cmake | 158 ++++--------------- src/google/protobuf/BUILD.bazel | 10 +- src/google/protobuf/compiler/cpp/BUILD.bazel | 1 + 11 files changed, 113 insertions(+), 178 deletions(-) diff --git a/BUILD.bazel b/BUILD.bazel index b63b7bf984..fd9ee70aeb 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -324,6 +324,12 @@ alias( # Test protos ################################################################################ +alias( + name = "lite_test_proto_srcs", + actual = "//src/google/protobuf:lite_test_proto_srcs", # proto_library + visibility = ["//:__subpackages__"], +) + alias( name = "lite_test_protos", actual = "//src/google/protobuf:lite_test_protos", # proto_library diff --git a/cmake/conformance.cmake b/cmake/conformance.cmake index fa5c479bc6..056250ebe9 100644 --- a/cmake/conformance.cmake +++ b/cmake/conformance.cmake @@ -1,6 +1,8 @@ add_custom_command( - OUTPUT ${protobuf_SOURCE_DIR}/conformance/conformance.pb.cc + OUTPUT + ${protobuf_SOURCE_DIR}/conformance/conformance.pb.h + ${protobuf_SOURCE_DIR}/conformance/conformance.pb.cc DEPENDS ${protobuf_PROTOC_EXE} ${protobuf_SOURCE_DIR}/conformance/conformance.proto COMMAND ${protobuf_PROTOC_EXE} ${protobuf_SOURCE_DIR}/conformance/conformance.proto --proto_path=${protobuf_SOURCE_DIR}/conformance @@ -8,8 +10,11 @@ add_custom_command( ) add_custom_command( - OUTPUT ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.cc + OUTPUT + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.cc DEPENDS ${protobuf_PROTOC_EXE} ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.proto ${protobuf_PROTOC_EXE} ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.proto COMMAND ${protobuf_PROTOC_EXE} ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.proto @@ -21,6 +26,7 @@ add_custom_command( add_executable(conformance_test_runner ${protobuf_SOURCE_DIR}/conformance/binary_json_conformance_suite.cc ${protobuf_SOURCE_DIR}/conformance/binary_json_conformance_suite.h + ${protobuf_SOURCE_DIR}/conformance/conformance.pb.h ${protobuf_SOURCE_DIR}/conformance/conformance.pb.cc ${protobuf_SOURCE_DIR}/conformance/conformance_test.cc ${protobuf_SOURCE_DIR}/conformance/conformance_test_runner.cc @@ -29,14 +35,19 @@ add_executable(conformance_test_runner ${protobuf_SOURCE_DIR}/conformance/text_format_conformance_suite.h ${protobuf_SOURCE_DIR}/conformance/third_party/jsoncpp/json.h ${protobuf_SOURCE_DIR}/conformance/third_party/jsoncpp/jsoncpp.cpp + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.h ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.h ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.cc ) add_executable(conformance_cpp + ${protobuf_SOURCE_DIR}/conformance/conformance.pb.h ${protobuf_SOURCE_DIR}/conformance/conformance.pb.cc ${protobuf_SOURCE_DIR}/conformance/conformance_cpp.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.h ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.h ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.cc ) diff --git a/cmake/tests.cmake b/cmake/tests.cmake index a9fdd524ca..530a66ba8b 100644 --- a/cmake/tests.cmake +++ b/cmake/tests.cmake @@ -43,19 +43,20 @@ endif() include(${protobuf_SOURCE_DIR}/src/file_lists.cmake) set(lite_test_protos - ${protobuf_lite_test_protos_proto_srcs} + ${protobuf_lite_test_protos_files} ) set(tests_protos - ${protobuf_test_protos_proto_srcs} + ${protobuf_test_protos_files} ${compiler_test_protos_files} ${util_test_protos_files} ) macro(compile_proto_file filename) - string(REPLACE .proto .pb.cc pb_file ${filename}) + string(REPLACE .proto .pb.h pb_hdr ${filename}) + string(REPLACE .proto .pb.cc pb_src ${filename}) add_custom_command( - OUTPUT ${pb_file} + OUTPUT ${pb_hdr} ${pb_src} DEPENDS ${protobuf_PROTOC_EXE} ${filename} COMMAND ${protobuf_PROTOC_EXE} ${filename} --proto_path=${protobuf_SOURCE_DIR}/src @@ -67,13 +68,13 @@ endmacro(compile_proto_file) set(lite_test_proto_files) foreach(proto_file ${lite_test_protos}) compile_proto_file(${proto_file}) - set(lite_test_proto_files ${lite_test_proto_files} ${pb_file}) + set(lite_test_proto_files ${lite_test_proto_files} ${pb_src} ${pb_hdr}) endforeach(proto_file) set(tests_proto_files) foreach(proto_file ${tests_protos}) compile_proto_file(${proto_file}) - set(tests_proto_files ${tests_proto_files} ${pb_file}) + set(tests_proto_files ${tests_proto_files} ${pb_src} ${pb_hdr}) endforeach(proto_file) add_library(protobuf-lite-test-common STATIC @@ -85,8 +86,8 @@ target_link_libraries(protobuf-lite-test-common set(common_test_files ${test_util_hdrs} ${test_util_srcs} - ${mock_code_generator_srcs} - ${testing_srcs} + ${common_test_hdrs} + ${common_test_srcs} ) add_library(protobuf-test-common STATIC @@ -138,8 +139,8 @@ target_link_libraries(tests protobuf-lite-test-common protobuf-test-common ${pro set(test_plugin_files ${test_plugin_files} - ${mock_code_generator_srcs} - ${testing_srcs} + ${common_test_hdrs} + ${common_test_srcs} ) add_executable(test_plugin ${test_plugin_files}) @@ -172,13 +173,23 @@ add_custom_target(save-installed-headers) add_custom_target(remove-installed-headers) add_custom_target(restore-installed-headers) -# Explicitly skip the bootstrapping headers as it's directly used in tests -set(_installed_hdrs ${libprotobuf_hdrs} ${libprotoc_hdrs}) -list(REMOVE_ITEM _installed_hdrs +file(GLOB_RECURSE _local_hdrs + "${PROJECT_SOURCE_DIR}/src/*.h" + "${PROJECT_SOURCE_DIR}/src/*.inc") + +# Exclude the bootstrapping that are directly used by tests. +set(_exclude_hdrs "${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor.pb.h" "${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/plugin.pb.h") -foreach(_hdr ${_installed_hdrs}) +# Exclude test library headers. +list(APPEND _exclude_hdrs ${test_util_hdrs} ${lite_test_util_hdrs} ${common_test_hdrs} + ${compiler_test_utils_hdrs}) +foreach(_hdr ${_exclude_hdrs}) + list(REMOVE_ITEM _local_hdrs ${_hdr}) +endforeach() + +foreach(_hdr ${_local_hdrs}) string(REPLACE "${protobuf_SOURCE_DIR}/src" "" _file ${_hdr}) set(_tmp_file "${CMAKE_BINARY_DIR}/tmp-install-test/${_file}") add_custom_command(TARGET remove-installed-headers PRE_BUILD @@ -193,6 +204,6 @@ endforeach() add_dependencies(remove-installed-headers save-installed-headers) if(protobuf_REMOVE_INSTALLED_HEADERS) - add_dependencies(protobuf-lite-test-common remove-installed-headers) - add_dependencies(protobuf-test-common remove-installed-headers) + # Make sure we remove all the headers *before* any codegen occurs. + add_dependencies(${protobuf_PROTOC_EXE} remove-installed-headers) endif() diff --git a/kokoro/windows/cmake/build.bat b/kokoro/windows/cmake/build.bat index 49c89d3c84..d24e635d24 100644 --- a/kokoro/windows/cmake/build.bat +++ b/kokoro/windows/cmake/build.bat @@ -6,8 +6,8 @@ call kokoro\windows\prepare_build_win64.bat || goto :error @rem TODO(b/241475022) Use docker to guarantee better stability. @rem TODO(b/241484899) Run conformance tests in windows. -md build -ea 0 -md %KOKORO_ARTIFACTS_DIR%\logs -ea 0 +md build +md %KOKORO_ARTIFACTS_DIR%\logs cd build diff --git a/kokoro/windows/cmake_install/build.bat b/kokoro/windows/cmake_install/build.bat index 5392f9e664..c5878de338 100644 --- a/kokoro/windows/cmake_install/build.bat +++ b/kokoro/windows/cmake_install/build.bat @@ -6,8 +6,8 @@ call kokoro\windows\prepare_build_win64.bat || goto :error @rem TODO(b/241475022) Use docker to guarantee better stability. @rem TODO(b/241484899) Run conformance tests in windows. -md build -ea 0 -md %KOKORO_ARTIFACTS_DIR%\logs -ea 0 +md build +md %KOKORO_ARTIFACTS_DIR%\logs cd build diff --git a/kokoro/windows/cmake_nmake/build.bat b/kokoro/windows/cmake_nmake/build.bat index a0807714fc..7b03678dbc 100644 --- a/kokoro/windows/cmake_nmake/build.bat +++ b/kokoro/windows/cmake_nmake/build.bat @@ -6,8 +6,8 @@ call kokoro\windows\prepare_build_win64.bat || goto :error @rem TODO(b/241475022) Use docker to guarantee better stability. @rem TODO(b/241484899) Run conformance tests in windows. -md build -ea 0 -md %KOKORO_ARTIFACTS_DIR%\logs -ea 0 +md build +md %KOKORO_ARTIFACTS_DIR%\logs cd build diff --git a/kokoro/windows/cmake_shared/build.bat b/kokoro/windows/cmake_shared/build.bat index bcd5244608..d4bb2b16ee 100644 --- a/kokoro/windows/cmake_shared/build.bat +++ b/kokoro/windows/cmake_shared/build.bat @@ -6,8 +6,8 @@ call kokoro\windows\prepare_build_win64.bat || goto :error @rem TODO(b/241475022) Use docker to guarantee better stability. @rem TODO(b/241484899) Run conformance tests in windows. -md build -ea 0 -md %KOKORO_ARTIFACTS_DIR%\logs -ea 0 +md build +md %KOKORO_ARTIFACTS_DIR%\logs cd build diff --git a/pkg/BUILD.bazel b/pkg/BUILD.bazel index 65dc37c0c6..4eda549da5 100644 --- a/pkg/BUILD.bazel +++ b/pkg/BUILD.bazel @@ -314,20 +314,18 @@ gen_file_lists( "//src/google/protobuf:descriptor_proto": "descriptor_proto", "//src/google/protobuf/compiler:plugin_proto": "plugin_proto", # Test libraries: + ":common_test": "common_test", ":lite_test_util": "lite_test_util", ":test_util": "test_util", # Tests and test-only protos: "//src/google/protobuf:full_test_srcs": "protobuf_test", - "//src/google/protobuf:test_protos": "protobuf_test_protos", + "//src/google/protobuf:test_proto_srcs": "protobuf_test_protos", "//src/google/protobuf:lite_test_srcs": "protobuf_lite_test", - "//src/google/protobuf:lite_test_protos": "protobuf_lite_test_protos", + "//src/google/protobuf:lite_test_proto_srcs": "protobuf_lite_test_protos", "//src/google/protobuf/compiler:test_srcs": "compiler_test", - ":compiler_annotation_test_util": "annotation_test_util", - ":compiler_mock_code_generator": "mock_code_generator", "//src/google/protobuf/compiler:test_proto_srcs": "compiler_test_protos", "//src/google/protobuf/compiler:test_plugin_srcs": "test_plugin", "//src/google/protobuf/io:test_srcs": "io_test", - ":testinglib": "testing", "//src/google/protobuf/util:test_srcs": "util_test", "//src/google/protobuf/util:test_proto_srcs": "util_test_protos", "//src/google/protobuf/stubs:test_srcs": "stubs_test", @@ -369,6 +367,7 @@ cc_dist_library( "//src/google/protobuf:protobuf_nowkt", "//src/google/protobuf:arena", "//src/google/protobuf:protobuf_lite", + "//src/google/protobuf:port_def", "//src/google/protobuf/compiler:importer", "//src/google/protobuf/io", "//src/google/protobuf/io:gzip_stream", @@ -384,6 +383,7 @@ cc_dist_library( "//src/google/protobuf/util:json_util", "//src/google/protobuf/util:time_util", "//src/google/protobuf/util:type_resolver_util", + "//src/google/protobuf/util/internal:constants", "//src/google/protobuf/util/internal:datapiece", "//src/google/protobuf/util/internal:default_value", "//src/google/protobuf/util/internal:field_mask_utility", @@ -422,29 +422,27 @@ cc_dist_library( name = "test_util", testonly = 1, tags = ["manual"], - deps = ["//src/google/protobuf:test_util"], -) - -cc_dist_library( - name = "compiler_annotation_test_util", - testonly = 1, - tags = ["manual"], - deps = ["//src/google/protobuf/compiler:annotation_test_util"], + deps = [ + "//src/google/protobuf:test_util", + "//src/google/protobuf:test_util2", + "//src/google/protobuf/util/internal:expecting_objectwriter", + "//src/google/protobuf/util/internal:mock_error_listener", + "//src/google/protobuf/util/internal:type_info_test_helper", + "//src/google/protobuf/compiler:annotation_test_util", + "//src/google/protobuf/compiler/cpp:unittest_lib", + ], ) cc_dist_library( - name = "compiler_mock_code_generator", + name = "common_test", testonly = 1, tags = ["manual"], - deps = ["//src/google/protobuf/compiler:mock_code_generator"], + deps = [ + "//src/google/protobuf/testing", + "//src/google/protobuf/compiler:mock_code_generator", + ], ) -cc_dist_library( - name = "testinglib", - testonly = 1, - tags = ["manual"], - deps = ["//src/google/protobuf/testing"], -) ################################################################################ # Distribution sources diff --git a/src/file_lists.cmake b/src/file_lists.cmake index be3d61ee14..2a76933de4 100644 --- a/src/file_lists.cmake +++ b/src/file_lists.cmake @@ -157,6 +157,8 @@ set(libprotobuf_hdrs ${protobuf_SOURCE_DIR}/src/google/protobuf/metadata_lite.h ${protobuf_SOURCE_DIR}/src/google/protobuf/parse_context.h ${protobuf_SOURCE_DIR}/src/google/protobuf/port.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/port_def.inc + ${protobuf_SOURCE_DIR}/src/google/protobuf/port_undef.inc ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection.h ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_internal.h ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_ops.h @@ -179,6 +181,7 @@ set(libprotobuf_hdrs ${protobuf_SOURCE_DIR}/src/google/protobuf/util/delimited_message_util.h ${protobuf_SOURCE_DIR}/src/google/protobuf/util/field_comparator.h ${protobuf_SOURCE_DIR}/src/google/protobuf/util/field_mask_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/constants.h ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/datapiece.h ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/default_value_objectwriter.h ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/error_listener.h @@ -524,6 +527,20 @@ set(plugin_proto_files ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/plugin_proto-descriptor-set.proto.bin ) +# //pkg:common_test +set(common_test_srcs + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/mock_code_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/file.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/googletest.cc +) + +# //pkg:common_test +set(common_test_hdrs + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/mock_code_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/file.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/googletest.h +) + # //pkg:lite_test_util set(lite_test_util_srcs ${protobuf_SOURCE_DIR}/src/google/protobuf/arena_test_util.cc @@ -542,12 +559,17 @@ set(lite_test_util_hdrs # //pkg:test_util set(test_util_srcs + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/annotation_test_util.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_tester.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/test_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/type_info_test_helper.cc ) # //pkg:test_util set(test_util_hdrs + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/annotation_test_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/unittest.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/unittest.inc ${protobuf_SOURCE_DIR}/src/google/protobuf/map_test.inc ${protobuf_SOURCE_DIR}/src/google/protobuf/map_test_util.h ${protobuf_SOURCE_DIR}/src/google/protobuf/map_test_util.inc @@ -555,7 +577,11 @@ set(test_util_hdrs ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_tester.h ${protobuf_SOURCE_DIR}/src/google/protobuf/test_util.h ${protobuf_SOURCE_DIR}/src/google/protobuf/test_util.inc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_util2.h ${protobuf_SOURCE_DIR}/src/google/protobuf/test_util_lite.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/expecting_objectwriter.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/mock_error_listener.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/type_info_test_helper.h ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format_unittest.inc ) @@ -590,8 +616,8 @@ set(protobuf_test_files ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format_unittest.cc ) -# //src/google/protobuf:test_protos -set(protobuf_test_protos_proto_srcs +# //src/google/protobuf:test_proto_srcs +set(protobuf_test_protos_files ${protobuf_SOURCE_DIR}/src/google/protobuf/any_test.proto ${protobuf_SOURCE_DIR}/src/google/protobuf/map_proto2_unittest.proto ${protobuf_SOURCE_DIR}/src/google/protobuf/map_unittest.proto @@ -623,112 +649,20 @@ set(protobuf_test_protos_proto_srcs ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_well_known_types.proto ) -# //src/google/protobuf:test_protos -set(protobuf_test_protos_srcs - ${protobuf_SOURCE_DIR}/src/google/protobuf/any_test.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/map_proto2_unittest.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/map_unittest.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_arena.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_custom_options.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_drop_unknown_fields.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_embed_optimize_for.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_empty.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_enormous_descriptor.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import_public.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lazy_dependencies.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lazy_dependencies_custom_option.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lazy_dependencies_enum.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lite_imports_nonlite.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_mset.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_mset_wire_format.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_no_field_presence.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_no_generic_services.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_optimize_for.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_preserve_unknown_enum.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_preserve_unknown_enum2.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3_arena.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3_arena_lite.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3_lite.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3_optional.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_well_known_types.proto.pb.cc -) - -# //src/google/protobuf:test_protos -set(protobuf_test_protos_hdrs - ${protobuf_SOURCE_DIR}/src/google/protobuf/any_test.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/map_proto2_unittest.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/map_unittest.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_arena.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_custom_options.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_drop_unknown_fields.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_embed_optimize_for.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_empty.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_enormous_descriptor.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import_public.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lazy_dependencies.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lazy_dependencies_custom_option.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lazy_dependencies_enum.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lite_imports_nonlite.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_mset.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_mset_wire_format.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_no_field_presence.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_no_generic_services.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_optimize_for.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_preserve_unknown_enum.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_preserve_unknown_enum2.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3_arena.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3_arena_lite.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3_lite.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_proto3_optional.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_well_known_types.proto.pb.h -) - -# //src/google/protobuf:test_protos -set(protobuf_test_protos_files - ${protobuf_SOURCE_DIR}/src/google/protobuf/test_protos-descriptor-set.proto.bin -) - # //src/google/protobuf:lite_test_srcs set(protobuf_lite_test_files ${protobuf_SOURCE_DIR}/src/google/protobuf/lite_arena_unittest.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/lite_unittest.cc ) -# //src/google/protobuf:lite_test_protos -set(protobuf_lite_test_protos_proto_srcs +# //src/google/protobuf:lite_test_proto_srcs +set(protobuf_lite_test_protos_files ${protobuf_SOURCE_DIR}/src/google/protobuf/map_lite_unittest.proto ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import_lite.proto ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import_public_lite.proto ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lite.proto ) -# //src/google/protobuf:lite_test_protos -set(protobuf_lite_test_protos_srcs - ${protobuf_SOURCE_DIR}/src/google/protobuf/map_lite_unittest.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import_lite.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import_public_lite.proto.pb.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lite.proto.pb.cc -) - -# //src/google/protobuf:lite_test_protos -set(protobuf_lite_test_protos_hdrs - ${protobuf_SOURCE_DIR}/src/google/protobuf/map_lite_unittest.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import_lite.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_import_public_lite.proto.pb.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/unittest_lite.proto.pb.h -) - -# //src/google/protobuf:lite_test_protos -set(protobuf_lite_test_protos_files - ${protobuf_SOURCE_DIR}/src/google/protobuf/lite_test_protos-descriptor-set.proto.bin -) - # //src/google/protobuf/compiler:test_srcs set(compiler_test_files ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/command_line_interface_unittest.cc @@ -750,26 +684,6 @@ set(compiler_test_files ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc ) -# //pkg:compiler_annotation_test_util -set(annotation_test_util_srcs - ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/annotation_test_util.cc -) - -# //pkg:compiler_annotation_test_util -set(annotation_test_util_hdrs - ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/annotation_test_util.h -) - -# //pkg:compiler_mock_code_generator -set(mock_code_generator_srcs - ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/mock_code_generator.cc -) - -# //pkg:compiler_mock_code_generator -set(mock_code_generator_hdrs - ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/mock_code_generator.h -) - # //src/google/protobuf/compiler:test_proto_srcs set(compiler_test_protos_files ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/test_bad_identifiers.proto @@ -792,18 +706,6 @@ set(io_test_files ${protobuf_SOURCE_DIR}/src/google/protobuf/io/zero_copy_stream_unittest.cc ) -# //pkg:testinglib -set(testing_srcs - ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/file.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/googletest.cc -) - -# //pkg:testinglib -set(testing_hdrs - ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/file.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/googletest.h -) - # //src/google/protobuf/util:test_srcs set(util_test_files ${protobuf_SOURCE_DIR}/src/google/protobuf/util/delimited_message_util_test.cc diff --git a/src/google/protobuf/BUILD.bazel b/src/google/protobuf/BUILD.bazel index 91aaab9e30..8eaa0113e1 100644 --- a/src/google/protobuf/BUILD.bazel +++ b/src/google/protobuf/BUILD.bazel @@ -392,14 +392,20 @@ filegroup( ], ) -proto_library( - name = "lite_test_protos", +filegroup( + name = "lite_test_proto_srcs", srcs = [ "map_lite_unittest.proto", "unittest_import_lite.proto", "unittest_import_public_lite.proto", "unittest_lite.proto", ], + visibility = ["//:__subpackages__"], +) + +proto_library( + name = "lite_test_protos", + srcs = [":lite_test_proto_srcs"], strip_import_prefix = "/src", visibility = ["//:__subpackages__"], deps = [ diff --git a/src/google/protobuf/compiler/cpp/BUILD.bazel b/src/google/protobuf/compiler/cpp/BUILD.bazel index 4a17bc10f0..8d6657d2f4 100644 --- a/src/google/protobuf/compiler/cpp/BUILD.bazel +++ b/src/google/protobuf/compiler/cpp/BUILD.bazel @@ -97,6 +97,7 @@ cc_library( "unittest.inc", ], strip_include_prefix = "/src", + visibility = ["//pkg:__pkg__"], ) cc_test( From 6a28393f089d9f3ab2242d0207ef216dd5171ca2 Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Mon, 19 Sep 2022 12:44:31 -0400 Subject: [PATCH 44/64] Keep the class forward declaration also. Some users might be depended on these, so until everything is flipped to explicit imports, need to still provide the class declaration so the proto isn't a breaking change. --- objectivec/GPBCodedInputStream.h | 1 + objectivec/GPBMessage.h | 1 + 2 files changed, 2 insertions(+) diff --git a/objectivec/GPBCodedInputStream.h b/objectivec/GPBCodedInputStream.h index 73b65581d7..2b95cc9ae2 100644 --- a/objectivec/GPBCodedInputStream.h +++ b/objectivec/GPBCodedInputStream.h @@ -31,6 +31,7 @@ #import @class GPBMessage; +@class GPBExtensionRegistry; @protocol GPBExtensionRegistry; NS_ASSUME_NONNULL_BEGIN diff --git a/objectivec/GPBMessage.h b/objectivec/GPBMessage.h index 990a796faf..ddd5de7c9f 100644 --- a/objectivec/GPBMessage.h +++ b/objectivec/GPBMessage.h @@ -36,6 +36,7 @@ @class GPBCodedInputStream; @class GPBCodedOutputStream; @class GPBExtensionDescriptor; +@class GPBExtensionRegistry; @protocol GPBExtensionRegistry; @class GPBFieldDescriptor; @class GPBUnknownFieldSet; From 99955470e098aa79d6572f057d430f89c75bbc56 Mon Sep 17 00:00:00 2001 From: Ted Pudlik Date: Mon, 19 Sep 2022 19:12:05 +0000 Subject: [PATCH 45/64] Add reserved extension number for Pigweed The extension number will be used for providing custom options to the Pigweed protobuf compiler. Support for this is added in https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/110632. --- docs/options.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/options.md b/docs/options.md index dc19688235..87f7dca50b 100644 --- a/docs/options.md +++ b/docs/options.md @@ -344,3 +344,7 @@ with info about your project (name and website) so we can add an entry for you. 1. mypy-protobuf * Website: https://github.com/nipunn1313/mypy-protobuf * Extension: 1151-1154 + +1. Pigweed protobuf compiler + * Website: https://pigweed.dev/pw_protobuf + * Extension: 1155 From 5392dc1dd4f6542598d8717a84ee2db678c4aeee Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Mon, 19 Sep 2022 16:06:12 -0400 Subject: [PATCH 46/64] [ObjC] Use a real import for GPBExtensionRegistry. The fwd decls can lead to ambiguity for downstream users, so use a full import to avoid the potential issues. --- objectivec/GPBCodedInputStream.h | 4 ++-- objectivec/GPBMessage.h | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/objectivec/GPBCodedInputStream.h b/objectivec/GPBCodedInputStream.h index 2b95cc9ae2..b7e1c7e6ab 100644 --- a/objectivec/GPBCodedInputStream.h +++ b/objectivec/GPBCodedInputStream.h @@ -30,9 +30,9 @@ #import +#import "GPBExtensionRegistry.h" + @class GPBMessage; -@class GPBExtensionRegistry; -@protocol GPBExtensionRegistry; NS_ASSUME_NONNULL_BEGIN diff --git a/objectivec/GPBMessage.h b/objectivec/GPBMessage.h index ddd5de7c9f..f80778bc39 100644 --- a/objectivec/GPBMessage.h +++ b/objectivec/GPBMessage.h @@ -31,13 +31,12 @@ #import #import "GPBBootstrap.h" +#import "GPBExtensionRegistry.h" @class GPBDescriptor; @class GPBCodedInputStream; @class GPBCodedOutputStream; @class GPBExtensionDescriptor; -@class GPBExtensionRegistry; -@protocol GPBExtensionRegistry; @class GPBFieldDescriptor; @class GPBUnknownFieldSet; From 719dc252a33cb0e9afd98f58f2dcd244b8f04e4d Mon Sep 17 00:00:00 2001 From: Mike Kruskal Date: Mon, 19 Sep 2022 14:24:20 -0700 Subject: [PATCH 47/64] Update changelog --- CHANGES.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.txt b/CHANGES.txt index 2dc86330a3..3b0681e3fe 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -22,6 +22,9 @@ * Turns on table-driven parser for reflection based objects. * Save code space by avoiding inlining of large-in-aggregate code-space MessageLite::~MessageLite destructor. * Undefine the macro `linux` when compiling protobuf + * Reduce memory consumption of MessageSet parsing. + * Save code space by avoiding inlining of large-in-aggregate code-space MessageLite::~MessageLite destructor. + * Breaking change: delete Arena::Init Kotlin From d4af9c919fb4a7d72dacedf501443159e2948ace Mon Sep 17 00:00:00 2001 From: Mike Kruskal Date: Mon, 19 Sep 2022 14:28:14 -0700 Subject: [PATCH 48/64] Fixing bad merges, updating generated files --- .github/workflows/codespell.yml | 2 +- .../protobuf/map_for_proto2_lite_test.proto | 3 + src/google/protobuf/any.pb.cc | 114 +++--- src/google/protobuf/any.pb.h | 51 ++- src/google/protobuf/api.pb.cc | 225 ++++++----- src/google/protobuf/api.pb.h | 71 ++-- .../compiler/csharp/csharp_map_field.cc | 2 +- .../objectivec/objectivec_extension.cc | 1 - .../compiler/objectivec/objectivec_file.cc | 1 - .../objectivec/objectivec_generator.cc | 1 - src/google/protobuf/compiler/plugin.pb.h | 15 +- src/google/protobuf/descriptor.pb.h | 15 +- src/google/protobuf/duration.pb.cc | 108 +++--- src/google/protobuf/duration.pb.h | 51 ++- src/google/protobuf/empty.pb.cc | 102 +++-- src/google/protobuf/empty.pb.h | 51 ++- src/google/protobuf/field_mask.pb.cc | 106 +++--- src/google/protobuf/field_mask.pb.h | 51 ++- src/google/protobuf/source_context.pb.cc | 106 +++--- src/google/protobuf/source_context.pb.h | 51 ++- src/google/protobuf/struct.pb.cc | 231 +++++------ src/google/protobuf/struct.pb.h | 75 ++-- src/google/protobuf/timestamp.pb.cc | 108 +++--- src/google/protobuf/timestamp.pb.h | 51 ++- src/google/protobuf/type.pb.cc | 340 +++++++++-------- src/google/protobuf/type.pb.h | 89 +++-- src/google/protobuf/wrappers.pb.cc | 358 +++++++++--------- src/google/protobuf/wrappers.pb.h | 115 +++--- 28 files changed, 1400 insertions(+), 1094 deletions(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 2e5ee80cde..d056ecc454 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -13,4 +13,4 @@ jobs: with: check_filenames: true skip: ./.git,./conformance/third_party,*.snk,*.pb,*.pb.cc,*.pb.h,./src/google/protobuf/testdata,./objectivec/Tests,./python/compatibility_tests/v2.5.0/tests/google/protobuf/internal,./.github/workflows/codespell.yml - ignore_words_list: "alow,alse,ba,cleare,copyable,cloneable,dedup,dur,errorprone,files',fo,fundementals,hel,importd,inout,leapyear,nd,nin,ois,ons,parseable,process',te,testof,ue,unparseable,wasn,wee,gae,keyserver,objext,od,optin,streem,sur,falsy" + ignore_words_list: "alow,alse,ba,chec,cleare,copyable,cloneable,dedup,dur,errorprone,files',fo,fundementals,hel,importd,inout,leapyear,nd,nin,ois,ons,parseable,process',te,testof,ue,unparseable,wasn,wee,gae,keyserver,objext,od,optin,streem,sur,falsy" diff --git a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto index 95ab8c06d4..4ec968819b 100644 --- a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto +++ b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto @@ -125,3 +125,6 @@ message ReservedAsMapFieldWithEnumValue { // null is not a 'reserved word' per se but as a literal needs similar care map null = 10; } +package map_for_proto2_lite_test; +option java_package = "map_lite_test"; +option optimize_for = LITE_RUNTIME; diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc index 2aa32b8423..514da7116a 100644 --- a/src/google/protobuf/any.pb.cc +++ b/src/google/protobuf/any.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto -#include +#include "google/protobuf/any.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,16 +12,15 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; #if defined(__llvm__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wuninitialized" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wuninitialized" #endif // __llvm__ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Any::Any( @@ -32,64 +30,88 @@ PROTOBUF_CONSTEXPR Any::Any( , /*decltype(_impl_._cached_size_)*/{} , /*decltype(_impl_._any_metadata_)*/{&_impl_.type_url_, &_impl_.value_}} {} struct AnyDefaultTypeInternal { - PROTOBUF_CONSTEXPR AnyDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR AnyDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~AnyDefaultTypeInternal() {} union { Any _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 AnyDefaultTypeInternal _Any_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 AnyDefaultTypeInternal _Any_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2fany_2eproto[1]; -static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _impl_.type_url_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _impl_.value_), +static constexpr const ::_pb::EnumDescriptor** + file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2fany_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2fany_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _impl_.type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _impl_.value_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Any)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Any)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_Any_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Any_default_instance_._instance, +}; +const char descriptor_table_protodef_google_2fprotobuf_2fany_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n\031google/protobuf/any.proto\022\017google.prot" + "obuf\"&\n\003Any\022\020\n\010type_url\030\001 \001(\t\022\r\n\005value\030\002" + " \001(\014Bv\n\023com.google.protobufB\010AnyProtoP\001Z" + ",google.golang.org/protobuf/types/known/" + "anypb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownT" + "ypesb\006proto3" }; - -const char descriptor_table_protodef_google_2fprotobuf_2fany_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n\031google/protobuf/any.proto\022\017google.prot" - "obuf\"&\n\003Any\022\020\n\010type_url\030\001 \001(\t\022\r\n\005value\030\002" - " \001(\014Bv\n\023com.google.protobufB\010AnyProtoP\001Z" - ",google.golang.org/protobuf/types/known/" - "anypb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownT" - "ypesb\006proto3" - ; static ::absl::once_flag descriptor_table_google_2fprotobuf_2fany_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto = { - false, false, 212, descriptor_table_protodef_google_2fprotobuf_2fany_2eproto, + false, + false, + 212, + descriptor_table_protodef_google_2fprotobuf_2fany_2eproto, "google/protobuf/any.proto", - &descriptor_table_google_2fprotobuf_2fany_2eproto_once, nullptr, 0, 1, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2fany_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2fany_2eproto, file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto, + &descriptor_table_google_2fprotobuf_2fany_2eproto_once, + nullptr, + 0, + 1, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2fany_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fany_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2fany_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2fany_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2fany_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fany_2eproto(&descriptor_table_google_2fprotobuf_2fany_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fany_2eproto(&descriptor_table_google_2fprotobuf_2fany_2eproto); PROTOBUF_NAMESPACE_OPEN - // =================================================================== bool Any::GetAnyFieldDescriptors( @@ -353,7 +375,6 @@ void Any::InternalSwap(Any* other) { &descriptor_table_google_2fprotobuf_2fany_2eproto_getter, &descriptor_table_google_2fprotobuf_2fany_2eproto_once, file_level_metadata_google_2fprotobuf_2fany_2eproto[0]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -362,9 +383,8 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Any >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::Any >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #if defined(__llvm__) - #pragma clang diagnostic pop +#pragma clang diagnostic pop #endif // __llvm__ #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h index 8075234381..726cff2f30 100644 --- a/src/google/protobuf/any.pb.h +++ b/src/google/protobuf/any.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -31,8 +32,12 @@ #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/unknown_field_set.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -43,19 +48,23 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fany_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2fany_2eproto; PROTOBUF_NAMESPACE_OPEN class Any; struct AnyDefaultTypeInternal; PROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Any* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Any>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Any* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Any>(Arena*); -PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT Any final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ { public: @@ -262,12 +271,17 @@ class PROTOBUF_EXPORT Any final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // Any // string type_url = 1; @@ -371,14 +385,15 @@ inline void Any::set_allocated_value(std::string* value) { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto_2epb_2eh diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc index 080a47e49c..865bf5963b 100644 --- a/src/google/protobuf/api.pb.cc +++ b/src/google/protobuf/api.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto -#include +#include "google/protobuf/api.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,13 +12,12 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Api::Api( ::_pbi::ConstantInitialized): _impl_{ @@ -32,14 +30,15 @@ PROTOBUF_CONSTEXPR Api::Api( , /*decltype(_impl_.syntax_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct ApiDefaultTypeInternal { - PROTOBUF_CONSTEXPR ApiDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR ApiDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~ApiDefaultTypeInternal() {} union { Api _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ApiDefaultTypeInternal _Api_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ApiDefaultTypeInternal _Api_default_instance_; PROTOBUF_CONSTEXPR Method::Method( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.options_)*/{} @@ -51,129 +50,155 @@ PROTOBUF_CONSTEXPR Method::Method( , /*decltype(_impl_.syntax_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct MethodDefaultTypeInternal { - PROTOBUF_CONSTEXPR MethodDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR MethodDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~MethodDefaultTypeInternal() {} union { Method _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 MethodDefaultTypeInternal _Method_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 MethodDefaultTypeInternal _Method_default_instance_; PROTOBUF_CONSTEXPR Mixin::Mixin( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} , /*decltype(_impl_.root_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} , /*decltype(_impl_._cached_size_)*/{}} {} struct MixinDefaultTypeInternal { - PROTOBUF_CONSTEXPR MixinDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR MixinDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~MixinDefaultTypeInternal() {} union { Mixin _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 MixinDefaultTypeInternal _Mixin_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 MixinDefaultTypeInternal _Mixin_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2fapi_2eproto[3]; -static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2fapi_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.methods_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.version_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.source_context_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.mixins_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.syntax_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.request_type_url_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.request_streaming_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.response_type_url_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.response_streaming_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.syntax_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _impl_.name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _impl_.root_), +static constexpr const ::_pb::EnumDescriptor** + file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr; +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2fapi_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.methods_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.version_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.source_context_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.mixins_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.syntax_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.request_type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.request_streaming_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.response_type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.response_streaming_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.syntax_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _impl_.root_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Api)}, - { 15, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Method)}, - { 30, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Mixin)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Api)}, + { 15, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Method)}, + { 30, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Mixin)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_Api_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Method_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Mixin_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Api_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Method_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Mixin_default_instance_._instance, }; - -const char descriptor_table_protodef_google_2fprotobuf_2fapi_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n\031google/protobuf/api.proto\022\017google.prot" - "obuf\032$google/protobuf/source_context.pro" - "to\032\032google/protobuf/type.proto\"\201\002\n\003Api\022\014" - "\n\004name\030\001 \001(\t\022(\n\007methods\030\002 \003(\0132\027.google.p" - "rotobuf.Method\022(\n\007options\030\003 \003(\0132\027.google" - ".protobuf.Option\022\017\n\007version\030\004 \001(\t\0226\n\016sou" - "rce_context\030\005 \001(\0132\036.google.protobuf.Sour" - "ceContext\022&\n\006mixins\030\006 \003(\0132\026.google.proto" - "buf.Mixin\022\'\n\006syntax\030\007 \001(\0162\027.google.proto" - "buf.Syntax\"\325\001\n\006Method\022\014\n\004name\030\001 \001(\t\022\030\n\020r" - "equest_type_url\030\002 \001(\t\022\031\n\021request_streami" - "ng\030\003 \001(\010\022\031\n\021response_type_url\030\004 \001(\t\022\032\n\022r" - "esponse_streaming\030\005 \001(\010\022(\n\007options\030\006 \003(\013" - "2\027.google.protobuf.Option\022\'\n\006syntax\030\007 \001(" - "\0162\027.google.protobuf.Syntax\"#\n\005Mixin\022\014\n\004n" - "ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBv\n\023com.google.pr" - "otobufB\010ApiProtoP\001Z,google.golang.org/pr" - "otobuf/types/known/apipb\242\002\003GPB\252\002\036Google." - "Protobuf.WellKnownTypesb\006proto3" - ; -static const ::_pbi::DescriptorTable* const descriptor_table_google_2fprotobuf_2fapi_2eproto_deps[2] = { - &::descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto, - &::descriptor_table_google_2fprotobuf_2ftype_2eproto, +const char descriptor_table_protodef_google_2fprotobuf_2fapi_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n\031google/protobuf/api.proto\022\017google.prot" + "obuf\032$google/protobuf/source_context.pro" + "to\032\032google/protobuf/type.proto\"\201\002\n\003Api\022\014" + "\n\004name\030\001 \001(\t\022(\n\007methods\030\002 \003(\0132\027.google.p" + "rotobuf.Method\022(\n\007options\030\003 \003(\0132\027.google" + ".protobuf.Option\022\017\n\007version\030\004 \001(\t\0226\n\016sou" + "rce_context\030\005 \001(\0132\036.google.protobuf.Sour" + "ceContext\022&\n\006mixins\030\006 \003(\0132\026.google.proto" + "buf.Mixin\022\'\n\006syntax\030\007 \001(\0162\027.google.proto" + "buf.Syntax\"\325\001\n\006Method\022\014\n\004name\030\001 \001(\t\022\030\n\020r" + "equest_type_url\030\002 \001(\t\022\031\n\021request_streami" + "ng\030\003 \001(\010\022\031\n\021response_type_url\030\004 \001(\t\022\032\n\022r" + "esponse_streaming\030\005 \001(\010\022(\n\007options\030\006 \003(\013" + "2\027.google.protobuf.Option\022\'\n\006syntax\030\007 \001(" + "\0162\027.google.protobuf.Syntax\"#\n\005Mixin\022\014\n\004n" + "ame\030\001 \001(\t\022\014\n\004root\030\002 \001(\tBv\n\023com.google.pr" + "otobufB\010ApiProtoP\001Z,google.golang.org/pr" + "otobuf/types/known/apipb\242\002\003GPB\252\002\036Google." + "Protobuf.WellKnownTypesb\006proto3" +}; +static const ::_pbi::DescriptorTable* const descriptor_table_google_2fprotobuf_2fapi_2eproto_deps[2] = + { + &::descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto, + &::descriptor_table_google_2fprotobuf_2ftype_2eproto, }; static ::absl::once_flag descriptor_table_google_2fprotobuf_2fapi_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2fapi_2eproto = { - false, false, 751, descriptor_table_protodef_google_2fprotobuf_2fapi_2eproto, + false, + false, + 751, + descriptor_table_protodef_google_2fprotobuf_2fapi_2eproto, "google/protobuf/api.proto", - &descriptor_table_google_2fprotobuf_2fapi_2eproto_once, descriptor_table_google_2fprotobuf_2fapi_2eproto_deps, 2, 3, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2fapi_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2fapi_2eproto, file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto, + &descriptor_table_google_2fprotobuf_2fapi_2eproto_once, + descriptor_table_google_2fprotobuf_2fapi_2eproto_deps, + 2, + 3, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2fapi_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fapi_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2fapi_2eproto, file_level_service_descriptors_google_2fprotobuf_2fapi_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2fapi_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2fapi_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fapi_2eproto(&descriptor_table_google_2fprotobuf_2fapi_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fapi_2eproto(&descriptor_table_google_2fprotobuf_2fapi_2eproto); PROTOBUF_NAMESPACE_OPEN - // =================================================================== class Api::_Internal { @@ -613,7 +638,6 @@ void Api::InternalSwap(Api* other) { &descriptor_table_google_2fprotobuf_2fapi_2eproto_getter, &descriptor_table_google_2fprotobuf_2fapi_2eproto_once, file_level_metadata_google_2fprotobuf_2fapi_2eproto[0]); } - // =================================================================== class Method::_Internal { @@ -1040,7 +1064,6 @@ void Method::InternalSwap(Method* other) { &descriptor_table_google_2fprotobuf_2fapi_2eproto_getter, &descriptor_table_google_2fprotobuf_2fapi_2eproto_once, file_level_metadata_google_2fprotobuf_2fapi_2eproto[1]); } - // =================================================================== class Mixin::_Internal { @@ -1293,7 +1316,6 @@ void Mixin::InternalSwap(Mixin* other) { &descriptor_table_google_2fprotobuf_2fapi_2eproto_getter, &descriptor_table_google_2fprotobuf_2fapi_2eproto_once, file_level_metadata_google_2fprotobuf_2fapi_2eproto[2]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -1310,6 +1332,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Mixin >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::Mixin >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h index 726c959345..80fecb6e31 100644 --- a/src/google/protobuf/api.pb.h +++ b/src/google/protobuf/api.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -30,11 +31,15 @@ #include "google/protobuf/repeated_field.h" // IWYU pragma: export #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/unknown_field_set.h" -#include -#include +#include "google/protobuf/source_context.pb.h" +#include "google/protobuf/type.pb.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -45,7 +50,8 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fapi_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fapi_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2fapi_2eproto; PROTOBUF_NAMESPACE_OPEN class Api; struct ApiDefaultTypeInternal; @@ -56,16 +62,21 @@ PROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_; class Mixin; struct MixinDefaultTypeInternal; PROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Api* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Api>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Method* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Method>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Mixin* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Mixin>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Api* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Api>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Method* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Method>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Mixin* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Mixin>(Arena*); -PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT Api final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ { public: @@ -323,8 +334,7 @@ class PROTOBUF_EXPORT Api final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT Method final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ { @@ -561,8 +571,7 @@ class PROTOBUF_EXPORT Method final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT Mixin final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ { @@ -734,12 +743,17 @@ class PROTOBUF_EXPORT Mixin final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // Api // string name = 1; @@ -1420,18 +1434,15 @@ inline void Mixin::set_allocated_root(std::string* root) { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto_2epb_2eh diff --git a/src/google/protobuf/compiler/csharp/csharp_map_field.cc b/src/google/protobuf/compiler/csharp/csharp_map_field.cc index efe87f2a6a..50d8b1d828 100644 --- a/src/google/protobuf/compiler/csharp/csharp_map_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_map_field.cc @@ -88,7 +88,7 @@ void MapFieldGenerator::GenerateMembers(io::Printer* printer) { void MapFieldGenerator::GenerateMergingCode(io::Printer* printer) { printer->Print( variables_, - "$name$_.Add(other.$name$_);\n"); + "$name$_.MergeFrom(other.$name$_);\n"); } void MapFieldGenerator::GenerateParsingCode(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc index 8102df29e8..c97c9feade 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_extension.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_extension.cc @@ -36,7 +36,6 @@ #include "google/protobuf/compiler/objectivec/objectivec_helpers.h" #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/printer.h" -#include "google/protobuf/stubs/strutil.h" namespace google { namespace protobuf { diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc index 496786ee88..84910fff23 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc @@ -38,7 +38,6 @@ #include "absl/strings/str_cat.h" #include "google/protobuf/compiler/objectivec/objectivec_enum.h" #include "google/protobuf/compiler/objectivec/objectivec_extension.h" -#include "google/protobuf/compiler/objectivec/objectivec_file.h" #include "google/protobuf/compiler/objectivec/objectivec_helpers.h" #include "google/protobuf/compiler/objectivec/objectivec_message.h" #include "google/protobuf/io/printer.h" diff --git a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc index ec4071bb79..e5f2fb3d6e 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_generator.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_generator.cc @@ -39,7 +39,6 @@ #include "absl/strings/str_split.h" #include "absl/strings/strip.h" #include "google/protobuf/compiler/objectivec/objectivec_file.h" -#include "google/protobuf/compiler/objectivec/objectivec_generator.h" #include "google/protobuf/compiler/objectivec/objectivec_helpers.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream.h" diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h index 9b8dd81f1c..5abaad9dd3 100644 --- a/src/google/protobuf/compiler/plugin.pb.h +++ b/src/google/protobuf/compiler/plugin.pb.h @@ -10,17 +10,12 @@ #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error "This file was generated by an older version of protoc which is" #error "incompatible with your Protocol Buffer headers. Please" #error "regenerate this file with a newer version of protoc." diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h index 834e9ac799..6c664ab20b 100644 --- a/src/google/protobuf/descriptor.pb.h +++ b/src/google/protobuf/descriptor.pb.h @@ -10,17 +10,12 @@ #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION -#if 3021005 < PROTOBUF_MIN_PROTOC_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION #error "This file was generated by an older version of protoc which is" #error "incompatible with your Protocol Buffer headers. Please" #error "regenerate this file with a newer version of protoc." diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc index b0db698485..18d3e42ad3 100644 --- a/src/google/protobuf/duration.pb.cc +++ b/src/google/protobuf/duration.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto -#include +#include "google/protobuf/duration.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,13 +12,12 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Duration::Duration( ::_pbi::ConstantInitialized): _impl_{ @@ -27,64 +25,88 @@ PROTOBUF_CONSTEXPR Duration::Duration( , /*decltype(_impl_.nanos_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct DurationDefaultTypeInternal { - PROTOBUF_CONSTEXPR DurationDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR DurationDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~DurationDefaultTypeInternal() {} union { Duration _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 DurationDefaultTypeInternal _Duration_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 DurationDefaultTypeInternal _Duration_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2fduration_2eproto[1]; -static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2fduration_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, _impl_.seconds_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, _impl_.nanos_), +static constexpr const ::_pb::EnumDescriptor** + file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr; +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2fduration_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, _impl_.seconds_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, _impl_.nanos_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Duration)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Duration)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_Duration_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Duration_default_instance_._instance, +}; +const char descriptor_table_protodef_google_2fprotobuf_2fduration_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n\036google/protobuf/duration.proto\022\017google" + ".protobuf\"*\n\010Duration\022\017\n\007seconds\030\001 \001(\003\022\r" + "\n\005nanos\030\002 \001(\005B\203\001\n\023com.google.protobufB\rD" + "urationProtoP\001Z1google.golang.org/protob" + "uf/types/known/durationpb\370\001\001\242\002\003GPB\252\002\036Goo" + "gle.Protobuf.WellKnownTypesb\006proto3" }; - -const char descriptor_table_protodef_google_2fprotobuf_2fduration_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n\036google/protobuf/duration.proto\022\017google" - ".protobuf\"*\n\010Duration\022\017\n\007seconds\030\001 \001(\003\022\r" - "\n\005nanos\030\002 \001(\005B\203\001\n\023com.google.protobufB\rD" - "urationProtoP\001Z1google.golang.org/protob" - "uf/types/known/durationpb\370\001\001\242\002\003GPB\252\002\036Goo" - "gle.Protobuf.WellKnownTypesb\006proto3" - ; static ::absl::once_flag descriptor_table_google_2fprotobuf_2fduration_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2fduration_2eproto = { - false, false, 235, descriptor_table_protodef_google_2fprotobuf_2fduration_2eproto, + false, + false, + 235, + descriptor_table_protodef_google_2fprotobuf_2fduration_2eproto, "google/protobuf/duration.proto", - &descriptor_table_google_2fprotobuf_2fduration_2eproto_once, nullptr, 0, 1, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2fduration_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2fduration_2eproto, file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto, + &descriptor_table_google_2fprotobuf_2fduration_2eproto_once, + nullptr, + 0, + 1, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2fduration_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fduration_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2fduration_2eproto, file_level_service_descriptors_google_2fprotobuf_2fduration_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2fduration_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2fduration_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fduration_2eproto(&descriptor_table_google_2fprotobuf_2fduration_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fduration_2eproto(&descriptor_table_google_2fprotobuf_2fduration_2eproto); PROTOBUF_NAMESPACE_OPEN - // =================================================================== class Duration::_Internal { @@ -295,7 +317,6 @@ void Duration::InternalSwap(Duration* other) { &descriptor_table_google_2fprotobuf_2fduration_2eproto_getter, &descriptor_table_google_2fprotobuf_2fduration_2eproto_once, file_level_metadata_google_2fprotobuf_2fduration_2eproto[0]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -304,6 +325,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Duration >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::Duration >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/duration.pb.h b/src/google/protobuf/duration.pb.h index 4fe1e620de..dd8cab0ca1 100644 --- a/src/google/protobuf/duration.pb.h +++ b/src/google/protobuf/duration.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -31,8 +32,12 @@ #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/unknown_field_set.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fduration_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -43,19 +48,23 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fduration_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fduration_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2fduration_2eproto; PROTOBUF_NAMESPACE_OPEN class Duration; struct DurationDefaultTypeInternal; PROTOBUF_EXPORT extern DurationDefaultTypeInternal _Duration_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Duration* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Duration>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Duration* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Duration>(Arena*); -PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT Duration final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Duration) */ { public: @@ -216,12 +225,17 @@ class PROTOBUF_EXPORT Duration final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // Duration // int64 seconds = 1; @@ -265,14 +279,15 @@ inline void Duration::set_nanos(int32_t value) { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fduration_2eproto_2epb_2eh diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc index c3de546339..91ba9f2c87 100644 --- a/src/google/protobuf/empty.pb.cc +++ b/src/google/protobuf/empty.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/empty.proto -#include +#include "google/protobuf/empty.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,72 +12,95 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Empty::Empty( ::_pbi::ConstantInitialized) {} struct EmptyDefaultTypeInternal { - PROTOBUF_CONSTEXPR EmptyDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR EmptyDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~EmptyDefaultTypeInternal() {} union { Empty _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EmptyDefaultTypeInternal _Empty_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EmptyDefaultTypeInternal _Empty_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2fempty_2eproto[1]; -static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2fempty_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Empty, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) +static constexpr const ::_pb::EnumDescriptor** + file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr; +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2fempty_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Empty, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Empty)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Empty)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_Empty_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Empty_default_instance_._instance, +}; +const char descriptor_table_protodef_google_2fprotobuf_2fempty_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n\033google/protobuf/empty.proto\022\017google.pr" + "otobuf\"\007\n\005EmptyB}\n\023com.google.protobufB\n" + "EmptyProtoP\001Z.google.golang.org/protobuf" + "/types/known/emptypb\370\001\001\242\002\003GPB\252\002\036Google.P" + "rotobuf.WellKnownTypesb\006proto3" }; - -const char descriptor_table_protodef_google_2fprotobuf_2fempty_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n\033google/protobuf/empty.proto\022\017google.pr" - "otobuf\"\007\n\005EmptyB}\n\023com.google.protobufB\n" - "EmptyProtoP\001Z.google.golang.org/protobuf" - "/types/known/emptypb\370\001\001\242\002\003GPB\252\002\036Google.P" - "rotobuf.WellKnownTypesb\006proto3" - ; static ::absl::once_flag descriptor_table_google_2fprotobuf_2fempty_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2fempty_2eproto = { - false, false, 190, descriptor_table_protodef_google_2fprotobuf_2fempty_2eproto, + false, + false, + 190, + descriptor_table_protodef_google_2fprotobuf_2fempty_2eproto, "google/protobuf/empty.proto", - &descriptor_table_google_2fprotobuf_2fempty_2eproto_once, nullptr, 0, 1, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2fempty_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2fempty_2eproto, file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto, + &descriptor_table_google_2fprotobuf_2fempty_2eproto_once, + nullptr, + 0, + 1, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2fempty_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fempty_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2fempty_2eproto, file_level_service_descriptors_google_2fprotobuf_2fempty_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2fempty_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2fempty_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fempty_2eproto(&descriptor_table_google_2fprotobuf_2fempty_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fempty_2eproto(&descriptor_table_google_2fprotobuf_2fempty_2eproto); PROTOBUF_NAMESPACE_OPEN - // =================================================================== class Empty::_Internal { @@ -118,7 +140,6 @@ const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Empty::GetClassData() const { &descriptor_table_google_2fprotobuf_2fempty_2eproto_getter, &descriptor_table_google_2fprotobuf_2fempty_2eproto_once, file_level_metadata_google_2fprotobuf_2fempty_2eproto[0]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -127,6 +148,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Empty >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::Empty >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h index bc6bbc695b..e134813f32 100644 --- a/src/google/protobuf/empty.pb.h +++ b/src/google/protobuf/empty.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -32,8 +33,12 @@ #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/unknown_field_set.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fempty_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -44,19 +49,23 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fempty_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fempty_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2fempty_2eproto; PROTOBUF_NAMESPACE_OPEN class Empty; struct EmptyDefaultTypeInternal; PROTOBUF_EXPORT extern EmptyDefaultTypeInternal _Empty_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Empty* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Empty>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Empty* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Empty>(Arena*); -PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT Empty final : public ::PROTOBUF_NAMESPACE_ID::internal::ZeroFieldsBase /* @@protoc_insertion_point(class_definition:google.protobuf.Empty) */ { public: @@ -176,23 +185,29 @@ class PROTOBUF_EXPORT Empty final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // Empty #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fempty_2eproto_2epb_2eh diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc index 66af752693..42dbbd5047 100644 --- a/src/google/protobuf/field_mask.pb.cc +++ b/src/google/protobuf/field_mask.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto -#include +#include "google/protobuf/field_mask.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,76 +12,99 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR FieldMask::FieldMask( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.paths_)*/{} , /*decltype(_impl_._cached_size_)*/{}} {} struct FieldMaskDefaultTypeInternal { - PROTOBUF_CONSTEXPR FieldMaskDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR FieldMaskDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~FieldMaskDefaultTypeInternal() {} union { FieldMask _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FieldMaskDefaultTypeInternal _FieldMask_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FieldMaskDefaultTypeInternal _FieldMask_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto[1]; -static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldMask, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldMask, _impl_.paths_), +static constexpr const ::_pb::EnumDescriptor** + file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr; +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldMask, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldMask, _impl_.paths_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::FieldMask)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::FieldMask)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_FieldMask_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_FieldMask_default_instance_._instance, +}; +const char descriptor_table_protodef_google_2fprotobuf_2ffield_5fmask_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n google/protobuf/field_mask.proto\022\017goog" + "le.protobuf\"\032\n\tFieldMask\022\r\n\005paths\030\001 \003(\tB" + "\205\001\n\023com.google.protobufB\016FieldMaskProtoP" + "\001Z2google.golang.org/protobuf/types/know" + "n/fieldmaskpb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf" + ".WellKnownTypesb\006proto3" }; - -const char descriptor_table_protodef_google_2fprotobuf_2ffield_5fmask_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n google/protobuf/field_mask.proto\022\017goog" - "le.protobuf\"\032\n\tFieldMask\022\r\n\005paths\030\001 \003(\tB" - "\205\001\n\023com.google.protobufB\016FieldMaskProtoP" - "\001Z2google.golang.org/protobuf/types/know" - "n/fieldmaskpb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf" - ".WellKnownTypesb\006proto3" - ; static ::absl::once_flag descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto = { - false, false, 223, descriptor_table_protodef_google_2fprotobuf_2ffield_5fmask_2eproto, + false, + false, + 223, + descriptor_table_protodef_google_2fprotobuf_2ffield_5fmask_2eproto, "google/protobuf/field_mask.proto", - &descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_once, nullptr, 0, 1, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto, file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto, + &descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_once, + nullptr, + 0, + 1, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto, file_level_service_descriptors_google_2fprotobuf_2ffield_5fmask_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2ffield_5fmask_2eproto(&descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2ffield_5fmask_2eproto(&descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto); PROTOBUF_NAMESPACE_OPEN - // =================================================================== class FieldMask::_Internal { @@ -272,7 +294,6 @@ void FieldMask::InternalSwap(FieldMask* other) { &descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_getter, &descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto_once, file_level_metadata_google_2fprotobuf_2ffield_5fmask_2eproto[0]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -281,6 +302,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::FieldMask >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::FieldMask >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h index 3d9c467fcf..0b3e0b714a 100644 --- a/src/google/protobuf/field_mask.pb.h +++ b/src/google/protobuf/field_mask.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -31,8 +32,12 @@ #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/unknown_field_set.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ffield_5fmask_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -43,19 +48,23 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2ffield_5fmask_2eproto; PROTOBUF_NAMESPACE_OPEN class FieldMask; struct FieldMaskDefaultTypeInternal; PROTOBUF_EXPORT extern FieldMaskDefaultTypeInternal _FieldMask_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::FieldMask* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::FieldMask>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::FieldMask* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::FieldMask>(Arena*); -PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT FieldMask final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FieldMask) */ { public: @@ -220,12 +229,17 @@ class PROTOBUF_EXPORT FieldMask final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // FieldMask // repeated string paths = 1; @@ -302,14 +316,15 @@ FieldMask::mutable_paths() { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ffield_5fmask_2eproto_2epb_2eh diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc index e6934f0187..1959701b80 100644 --- a/src/google/protobuf/source_context.pb.cc +++ b/src/google/protobuf/source_context.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/source_context.proto -#include +#include "google/protobuf/source_context.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,76 +12,99 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR SourceContext::SourceContext( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.file_name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} , /*decltype(_impl_._cached_size_)*/{}} {} struct SourceContextDefaultTypeInternal { - PROTOBUF_CONSTEXPR SourceContextDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR SourceContextDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~SourceContextDefaultTypeInternal() {} union { SourceContext _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SourceContextDefaultTypeInternal _SourceContext_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SourceContextDefaultTypeInternal _SourceContext_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto[1]; -static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto = nullptr; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceContext, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceContext, _impl_.file_name_), +static constexpr const ::_pb::EnumDescriptor** + file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto = nullptr; +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceContext, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceContext, _impl_.file_name_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::SourceContext)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::SourceContext)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_._instance, +}; +const char descriptor_table_protodef_google_2fprotobuf_2fsource_5fcontext_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n$google/protobuf/source_context.proto\022\017" + "google.protobuf\"\"\n\rSourceContext\022\021\n\tfile" + "_name\030\001 \001(\tB\212\001\n\023com.google.protobufB\022Sou" + "rceContextProtoP\001Z6google.golang.org/pro" + "tobuf/types/known/sourcecontextpb\242\002\003GPB\252" + "\002\036Google.Protobuf.WellKnownTypesb\006proto3" }; - -const char descriptor_table_protodef_google_2fprotobuf_2fsource_5fcontext_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n$google/protobuf/source_context.proto\022\017" - "google.protobuf\"\"\n\rSourceContext\022\021\n\tfile" - "_name\030\001 \001(\tB\212\001\n\023com.google.protobufB\022Sou" - "rceContextProtoP\001Z6google.golang.org/pro" - "tobuf/types/known/sourcecontextpb\242\002\003GPB\252" - "\002\036Google.Protobuf.WellKnownTypesb\006proto3" - ; static ::absl::once_flag descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto = { - false, false, 240, descriptor_table_protodef_google_2fprotobuf_2fsource_5fcontext_2eproto, + false, + false, + 240, + descriptor_table_protodef_google_2fprotobuf_2fsource_5fcontext_2eproto, "google/protobuf/source_context.proto", - &descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_once, nullptr, 0, 1, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto, file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto, + &descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_once, + nullptr, + 0, + 1, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto, file_level_service_descriptors_google_2fprotobuf_2fsource_5fcontext_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fsource_5fcontext_2eproto(&descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fsource_5fcontext_2eproto(&descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto); PROTOBUF_NAMESPACE_OPEN - // =================================================================== class SourceContext::_Internal { @@ -285,7 +307,6 @@ void SourceContext::InternalSwap(SourceContext* other) { &descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_getter, &descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto_once, file_level_metadata_google_2fprotobuf_2fsource_5fcontext_2eproto[0]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -294,6 +315,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::SourceContext >(Arena* arena return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::SourceContext >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h index ee4e6b22d6..8efcd328ef 100644 --- a/src/google/protobuf/source_context.pb.h +++ b/src/google/protobuf/source_context.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -31,8 +32,12 @@ #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/unknown_field_set.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fsource_5fcontext_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -43,19 +48,23 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto; PROTOBUF_NAMESPACE_OPEN class SourceContext; struct SourceContextDefaultTypeInternal; PROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::SourceContext* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::SourceContext>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::SourceContext* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::SourceContext>(Arena*); -PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT SourceContext final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.SourceContext) */ { public: @@ -210,12 +219,17 @@ class PROTOBUF_EXPORT SourceContext final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // SourceContext // string file_name = 1; @@ -269,14 +283,15 @@ inline void SourceContext::set_allocated_file_name(std::string* file_name) { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fsource_5fcontext_2eproto_2epb_2eh diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc index 42fbd1a2fb..aa53b799b0 100644 --- a/src/google/protobuf/struct.pb.cc +++ b/src/google/protobuf/struct.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/struct.proto -#include +#include "google/protobuf/struct.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,164 +12,190 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse( ::_pbi::ConstantInitialized) {} struct Struct_FieldsEntry_DoNotUseDefaultTypeInternal { - PROTOBUF_CONSTEXPR Struct_FieldsEntry_DoNotUseDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR Struct_FieldsEntry_DoNotUseDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~Struct_FieldsEntry_DoNotUseDefaultTypeInternal() {} union { Struct_FieldsEntry_DoNotUse _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Struct_FieldsEntry_DoNotUseDefaultTypeInternal _Struct_FieldsEntry_DoNotUse_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Struct_FieldsEntry_DoNotUseDefaultTypeInternal _Struct_FieldsEntry_DoNotUse_default_instance_; PROTOBUF_CONSTEXPR Struct::Struct( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.fields_)*/{::_pbi::ConstantInitialized()} , /*decltype(_impl_._cached_size_)*/{}} {} struct StructDefaultTypeInternal { - PROTOBUF_CONSTEXPR StructDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR StructDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~StructDefaultTypeInternal() {} union { Struct _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 StructDefaultTypeInternal _Struct_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 StructDefaultTypeInternal _Struct_default_instance_; PROTOBUF_CONSTEXPR Value::Value( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.kind_)*/{} , /*decltype(_impl_._cached_size_)*/{} , /*decltype(_impl_._oneof_case_)*/{}} {} struct ValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR ValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~ValueDefaultTypeInternal() {} union { Value _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ValueDefaultTypeInternal _Value_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ValueDefaultTypeInternal _Value_default_instance_; PROTOBUF_CONSTEXPR ListValue::ListValue( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.values_)*/{} , /*decltype(_impl_._cached_size_)*/{}} {} struct ListValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR ListValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR ListValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~ListValueDefaultTypeInternal() {} union { ListValue _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ListValueDefaultTypeInternal _ListValue_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ListValueDefaultTypeInternal _ListValue_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2fstruct_2eproto[4]; static const ::_pb::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto[1]; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fstruct_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, _has_bits_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, key_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, value_), - 0, - 1, - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct, _impl_.fields_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _internal_metadata_), - ~0u, // no _extensions_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _impl_._oneof_case_[0]), - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - ::_pbi::kInvalidFieldOffsetTag, - ::_pbi::kInvalidFieldOffsetTag, - ::_pbi::kInvalidFieldOffsetTag, - ::_pbi::kInvalidFieldOffsetTag, - ::_pbi::kInvalidFieldOffsetTag, - ::_pbi::kInvalidFieldOffsetTag, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _impl_.kind_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ListValue, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ListValue, _impl_.values_), +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2fstruct_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, key_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse, value_), + 0, + 1, + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct, _impl_.fields_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _internal_metadata_), + ~0u, // no _extensions_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _impl_._oneof_case_[0]), + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + ::_pbi::kInvalidFieldOffsetTag, + ::_pbi::kInvalidFieldOffsetTag, + ::_pbi::kInvalidFieldOffsetTag, + ::_pbi::kInvalidFieldOffsetTag, + ::_pbi::kInvalidFieldOffsetTag, + ::_pbi::kInvalidFieldOffsetTag, + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _impl_.kind_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ListValue, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ListValue, _impl_.values_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, 10, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse)}, - { 12, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Struct)}, - { 21, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Value)}, - { 36, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::ListValue)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, 10, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse)}, + { 12, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Struct)}, + { 21, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Value)}, + { 36, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::ListValue)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_Struct_FieldsEntry_DoNotUse_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Struct_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Value_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_ListValue_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Struct_FieldsEntry_DoNotUse_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Struct_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Value_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_ListValue_default_instance_._instance, +}; +const char descriptor_table_protodef_google_2fprotobuf_2fstruct_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n\034google/protobuf/struct.proto\022\017google.p" + "rotobuf\"\204\001\n\006Struct\0223\n\006fields\030\001 \003(\0132#.goo" + "gle.protobuf.Struct.FieldsEntry\032E\n\013Field" + "sEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.goo" + "gle.protobuf.Value:\0028\001\"\352\001\n\005Value\0220\n\nnull" + "_value\030\001 \001(\0162\032.google.protobuf.NullValue" + "H\000\022\026\n\014number_value\030\002 \001(\001H\000\022\026\n\014string_val" + "ue\030\003 \001(\tH\000\022\024\n\nbool_value\030\004 \001(\010H\000\022/\n\014stru" + "ct_value\030\005 \001(\0132\027.google.protobuf.StructH" + "\000\0220\n\nlist_value\030\006 \001(\0132\032.google.protobuf." + "ListValueH\000B\006\n\004kind\"3\n\tListValue\022&\n\006valu" + "es\030\001 \003(\0132\026.google.protobuf.Value*\033\n\tNull" + "Value\022\016\n\nNULL_VALUE\020\000B\177\n\023com.google.prot" + "obufB\013StructProtoP\001Z/google.golang.org/p" + "rotobuf/types/known/structpb\370\001\001\242\002\003GPB\252\002\036" + "Google.Protobuf.WellKnownTypesb\006proto3" }; - -const char descriptor_table_protodef_google_2fprotobuf_2fstruct_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n\034google/protobuf/struct.proto\022\017google.p" - "rotobuf\"\204\001\n\006Struct\0223\n\006fields\030\001 \003(\0132#.goo" - "gle.protobuf.Struct.FieldsEntry\032E\n\013Field" - "sEntry\022\013\n\003key\030\001 \001(\t\022%\n\005value\030\002 \001(\0132\026.goo" - "gle.protobuf.Value:\0028\001\"\352\001\n\005Value\0220\n\nnull" - "_value\030\001 \001(\0162\032.google.protobuf.NullValue" - "H\000\022\026\n\014number_value\030\002 \001(\001H\000\022\026\n\014string_val" - "ue\030\003 \001(\tH\000\022\024\n\nbool_value\030\004 \001(\010H\000\022/\n\014stru" - "ct_value\030\005 \001(\0132\027.google.protobuf.StructH" - "\000\0220\n\nlist_value\030\006 \001(\0132\032.google.protobuf." - "ListValueH\000B\006\n\004kind\"3\n\tListValue\022&\n\006valu" - "es\030\001 \003(\0132\026.google.protobuf.Value*\033\n\tNull" - "Value\022\016\n\nNULL_VALUE\020\000B\177\n\023com.google.prot" - "obufB\013StructProtoP\001Z/google.golang.org/p" - "rotobuf/types/known/structpb\370\001\001\242\002\003GPB\252\002\036" - "Google.Protobuf.WellKnownTypesb\006proto3" - ; static ::absl::once_flag descriptor_table_google_2fprotobuf_2fstruct_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2fstruct_2eproto = { - false, false, 638, descriptor_table_protodef_google_2fprotobuf_2fstruct_2eproto, + false, + false, + 638, + descriptor_table_protodef_google_2fprotobuf_2fstruct_2eproto, "google/protobuf/struct.proto", - &descriptor_table_google_2fprotobuf_2fstruct_2eproto_once, nullptr, 0, 4, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2fstruct_2eproto, file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto, + &descriptor_table_google_2fprotobuf_2fstruct_2eproto_once, + nullptr, + 0, + 4, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2fstruct_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fstruct_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2fstruct_2eproto, file_level_service_descriptors_google_2fprotobuf_2fstruct_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2fstruct_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2fstruct_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fstruct_2eproto(&descriptor_table_google_2fprotobuf_2fstruct_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fstruct_2eproto(&descriptor_table_google_2fprotobuf_2fstruct_2eproto); PROTOBUF_NAMESPACE_OPEN const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* NullValue_descriptor() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2fstruct_2eproto); @@ -185,7 +210,6 @@ bool NullValue_IsValid(int value) { } } - // =================================================================== Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse() {} @@ -199,7 +223,6 @@ void Struct_FieldsEntry_DoNotUse::MergeFrom(const Struct_FieldsEntry_DoNotUse& o &descriptor_table_google_2fprotobuf_2fstruct_2eproto_getter, &descriptor_table_google_2fprotobuf_2fstruct_2eproto_once, file_level_metadata_google_2fprotobuf_2fstruct_2eproto[0]); } - // =================================================================== class Struct::_Internal { @@ -414,7 +437,6 @@ void Struct::InternalSwap(Struct* other) { &descriptor_table_google_2fprotobuf_2fstruct_2eproto_getter, &descriptor_table_google_2fprotobuf_2fstruct_2eproto_once, file_level_metadata_google_2fprotobuf_2fstruct_2eproto[1]); } - // =================================================================== class Value::_Internal { @@ -856,7 +878,6 @@ void Value::InternalSwap(Value* other) { &descriptor_table_google_2fprotobuf_2fstruct_2eproto_getter, &descriptor_table_google_2fprotobuf_2fstruct_2eproto_once, file_level_metadata_google_2fprotobuf_2fstruct_2eproto[2]); } - // =================================================================== class ListValue::_Internal { @@ -1041,7 +1062,6 @@ void ListValue::InternalSwap(ListValue* other) { &descriptor_table_google_2fprotobuf_2fstruct_2eproto_getter, &descriptor_table_google_2fprotobuf_2fstruct_2eproto_once, file_level_metadata_google_2fprotobuf_2fstruct_2eproto[3]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -1062,6 +1082,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::ListValue >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::ListValue >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h index e52be9476e..1292783621 100644 --- a/src/google/protobuf/struct.pb.h +++ b/src/google/protobuf/struct.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -35,8 +36,12 @@ #include "google/protobuf/generated_enum_reflection.h" #include "google/protobuf/unknown_field_set.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fstruct_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -47,7 +52,8 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fstruct_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fstruct_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2fstruct_2eproto; PROTOBUF_NAMESPACE_OPEN class ListValue; struct ListValueDefaultTypeInternal; @@ -61,15 +67,17 @@ PROTOBUF_EXPORT extern Struct_FieldsEntry_DoNotUseDefaultTypeInternal _Struct_Fi class Value; struct ValueDefaultTypeInternal; PROTOBUF_EXPORT extern ValueDefaultTypeInternal _Value_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::ListValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::ListValue>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Struct* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Struct>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Value>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::ListValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::ListValue>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Struct* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Struct>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Value>(Arena*); -PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN +PROTOBUF_NAMESPACE_OPEN enum NullValue : int { NULL_VALUE = 0, NullValue_INT_MIN_SENTINEL_DO_NOT_USE_ = std::numeric_limits::min(), @@ -98,8 +106,12 @@ inline bool NullValue_Parse( return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( NullValue_descriptor(), name, value); } + // =================================================================== + +// ------------------------------------------------------------------- + class Struct_FieldsEntry_DoNotUse : public ::PROTOBUF_NAMESPACE_ID::internal::MapEntry fields = 1; @@ -1152,19 +1166,13 @@ ListValue::values() const { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN template <> struct is_proto_enum< ::PROTOBUF_NAMESPACE_ID::NullValue> : ::std::true_type {}; @@ -1178,4 +1186,5 @@ PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fstruct_2eproto_2epb_2eh diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc index 47ecf7250c..a62cdcffde 100644 --- a/src/google/protobuf/timestamp.pb.cc +++ b/src/google/protobuf/timestamp.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto -#include +#include "google/protobuf/timestamp.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,13 +12,12 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Timestamp::Timestamp( ::_pbi::ConstantInitialized): _impl_{ @@ -27,64 +25,88 @@ PROTOBUF_CONSTEXPR Timestamp::Timestamp( , /*decltype(_impl_.nanos_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct TimestampDefaultTypeInternal { - PROTOBUF_CONSTEXPR TimestampDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR TimestampDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~TimestampDefaultTypeInternal() {} union { Timestamp _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TimestampDefaultTypeInternal _Timestamp_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TimestampDefaultTypeInternal _Timestamp_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto[1]; -static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto = nullptr; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ftimestamp_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, _impl_.seconds_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, _impl_.nanos_), +static constexpr const ::_pb::EnumDescriptor** + file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto = nullptr; +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2ftimestamp_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, _impl_.seconds_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, _impl_.nanos_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Timestamp)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Timestamp)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_Timestamp_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Timestamp_default_instance_._instance, +}; +const char descriptor_table_protodef_google_2fprotobuf_2ftimestamp_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n\037google/protobuf/timestamp.proto\022\017googl" + "e.protobuf\"+\n\tTimestamp\022\017\n\007seconds\030\001 \001(\003" + "\022\r\n\005nanos\030\002 \001(\005B\205\001\n\023com.google.protobufB" + "\016TimestampProtoP\001Z2google.golang.org/pro" + "tobuf/types/known/timestamppb\370\001\001\242\002\003GPB\252\002" + "\036Google.Protobuf.WellKnownTypesb\006proto3" }; - -const char descriptor_table_protodef_google_2fprotobuf_2ftimestamp_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n\037google/protobuf/timestamp.proto\022\017googl" - "e.protobuf\"+\n\tTimestamp\022\017\n\007seconds\030\001 \001(\003" - "\022\r\n\005nanos\030\002 \001(\005B\205\001\n\023com.google.protobufB" - "\016TimestampProtoP\001Z2google.golang.org/pro" - "tobuf/types/known/timestamppb\370\001\001\242\002\003GPB\252\002" - "\036Google.Protobuf.WellKnownTypesb\006proto3" - ; static ::absl::once_flag descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2ftimestamp_2eproto = { - false, false, 239, descriptor_table_protodef_google_2fprotobuf_2ftimestamp_2eproto, + false, + false, + 239, + descriptor_table_protodef_google_2fprotobuf_2ftimestamp_2eproto, "google/protobuf/timestamp.proto", - &descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_once, nullptr, 0, 1, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto, file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto, + &descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_once, + nullptr, + 0, + 1, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2ftimestamp_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2ftimestamp_2eproto, file_level_service_descriptors_google_2fprotobuf_2ftimestamp_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2ftimestamp_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2ftimestamp_2eproto(&descriptor_table_google_2fprotobuf_2ftimestamp_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2ftimestamp_2eproto(&descriptor_table_google_2fprotobuf_2ftimestamp_2eproto); PROTOBUF_NAMESPACE_OPEN - // =================================================================== class Timestamp::_Internal { @@ -295,7 +317,6 @@ void Timestamp::InternalSwap(Timestamp* other) { &descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_getter, &descriptor_table_google_2fprotobuf_2ftimestamp_2eproto_once, file_level_metadata_google_2fprotobuf_2ftimestamp_2eproto[0]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -304,6 +325,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Timestamp >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::Timestamp >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/timestamp.pb.h b/src/google/protobuf/timestamp.pb.h index c9fe105f4a..547b1e24f8 100644 --- a/src/google/protobuf/timestamp.pb.h +++ b/src/google/protobuf/timestamp.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -31,8 +32,12 @@ #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/unknown_field_set.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftimestamp_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -43,19 +48,23 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ftimestamp_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftimestamp_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2ftimestamp_2eproto; PROTOBUF_NAMESPACE_OPEN class Timestamp; struct TimestampDefaultTypeInternal; PROTOBUF_EXPORT extern TimestampDefaultTypeInternal _Timestamp_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Timestamp* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Timestamp>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Timestamp* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Timestamp>(Arena*); -PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT Timestamp final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Timestamp) */ { public: @@ -216,12 +225,17 @@ class PROTOBUF_EXPORT Timestamp final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // Timestamp // int64 seconds = 1; @@ -265,14 +279,15 @@ inline void Timestamp::set_nanos(int32_t value) { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftimestamp_2eproto_2epb_2eh diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc index 760823fed8..cdebb41d33 100644 --- a/src/google/protobuf/type.pb.cc +++ b/src/google/protobuf/type.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto -#include +#include "google/protobuf/type.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,13 +12,12 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Type::Type( ::_pbi::ConstantInitialized): _impl_{ @@ -31,14 +29,15 @@ PROTOBUF_CONSTEXPR Type::Type( , /*decltype(_impl_.syntax_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct TypeDefaultTypeInternal { - PROTOBUF_CONSTEXPR TypeDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR TypeDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~TypeDefaultTypeInternal() {} union { Type _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TypeDefaultTypeInternal _Type_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TypeDefaultTypeInternal _Type_default_instance_; PROTOBUF_CONSTEXPR Field::Field( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.options_)*/{} @@ -53,14 +52,15 @@ PROTOBUF_CONSTEXPR Field::Field( , /*decltype(_impl_.packed_)*/false , /*decltype(_impl_._cached_size_)*/{}} {} struct FieldDefaultTypeInternal { - PROTOBUF_CONSTEXPR FieldDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR FieldDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~FieldDefaultTypeInternal() {} union { Field _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FieldDefaultTypeInternal _Field_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FieldDefaultTypeInternal _Field_default_instance_; PROTOBUF_CONSTEXPR Enum::Enum( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.enumvalue_)*/{} @@ -70,14 +70,15 @@ PROTOBUF_CONSTEXPR Enum::Enum( , /*decltype(_impl_.syntax_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct EnumDefaultTypeInternal { - PROTOBUF_CONSTEXPR EnumDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR EnumDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~EnumDefaultTypeInternal() {} union { Enum _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumDefaultTypeInternal _Enum_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumDefaultTypeInternal _Enum_default_instance_; PROTOBUF_CONSTEXPR EnumValue::EnumValue( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.options_)*/{} @@ -85,178 +86,204 @@ PROTOBUF_CONSTEXPR EnumValue::EnumValue( , /*decltype(_impl_.number_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct EnumValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR EnumValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR EnumValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~EnumValueDefaultTypeInternal() {} union { EnumValue _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumValueDefaultTypeInternal _EnumValue_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumValueDefaultTypeInternal _EnumValue_default_instance_; PROTOBUF_CONSTEXPR Option::Option( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} , /*decltype(_impl_.value_)*/nullptr , /*decltype(_impl_._cached_size_)*/{}} {} struct OptionDefaultTypeInternal { - PROTOBUF_CONSTEXPR OptionDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR OptionDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~OptionDefaultTypeInternal() {} union { Option _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 OptionDefaultTypeInternal _Option_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 OptionDefaultTypeInternal _Option_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2ftype_2eproto[5]; static const ::_pb::EnumDescriptor* file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto[3]; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2ftype_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2ftype_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.fields_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.oneofs_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.source_context_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.syntax_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.kind_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.cardinality_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.number_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.type_url_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.oneof_index_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.packed_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.json_name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.default_value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.enumvalue_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.source_context_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.syntax_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.number_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.options_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _impl_.name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _impl_.value_), +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2ftype_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2ftype_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.fields_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.oneofs_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.source_context_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.syntax_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.kind_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.cardinality_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.number_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.oneof_index_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.packed_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.json_name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.default_value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.enumvalue_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.source_context_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.syntax_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.number_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.options_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _impl_.value_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Type)}, - { 14, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Field)}, - { 32, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Enum)}, - { 45, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::EnumValue)}, - { 56, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Option)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Type)}, + { 14, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Field)}, + { 32, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Enum)}, + { 45, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::EnumValue)}, + { 56, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Option)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_Type_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Field_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Enum_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_EnumValue_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Option_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Type_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Field_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Enum_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_EnumValue_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Option_default_instance_._instance, }; - -const char descriptor_table_protodef_google_2fprotobuf_2ftype_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n\032google/protobuf/type.proto\022\017google.pro" - "tobuf\032\031google/protobuf/any.proto\032$google" - "/protobuf/source_context.proto\"\327\001\n\004Type\022" - "\014\n\004name\030\001 \001(\t\022&\n\006fields\030\002 \003(\0132\026.google.p" - "rotobuf.Field\022\016\n\006oneofs\030\003 \003(\t\022(\n\007options" - "\030\004 \003(\0132\027.google.protobuf.Option\0226\n\016sourc" - "e_context\030\005 \001(\0132\036.google.protobuf.Source" - "Context\022\'\n\006syntax\030\006 \001(\0162\027.google.protobu" - "f.Syntax\"\325\005\n\005Field\022)\n\004kind\030\001 \001(\0162\033.googl" - "e.protobuf.Field.Kind\0227\n\013cardinality\030\002 \001" - "(\0162\".google.protobuf.Field.Cardinality\022\016" - "\n\006number\030\003 \001(\005\022\014\n\004name\030\004 \001(\t\022\020\n\010type_url" - "\030\006 \001(\t\022\023\n\013oneof_index\030\007 \001(\005\022\016\n\006packed\030\010 " - "\001(\010\022(\n\007options\030\t \003(\0132\027.google.protobuf.O" - "ption\022\021\n\tjson_name\030\n \001(\t\022\025\n\rdefault_valu" - "e\030\013 \001(\t\"\310\002\n\004Kind\022\020\n\014TYPE_UNKNOWN\020\000\022\017\n\013TY" - "PE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTYPE_INT6" - "4\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT32\020\005\022\020\n\014" - "TYPE_FIXED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022\r\n\tTYPE" - "_BOOL\020\010\022\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_GROUP\020\n" - "\022\020\n\014TYPE_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020\014\022\017\n\013TY" - "PE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYPE_SFIXE" - "D32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_SINT32\020" - "\021\022\017\n\013TYPE_SINT64\020\022\"t\n\013Cardinality\022\027\n\023CAR" - "DINALITY_UNKNOWN\020\000\022\030\n\024CARDINALITY_OPTION" - "AL\020\001\022\030\n\024CARDINALITY_REQUIRED\020\002\022\030\n\024CARDIN" - "ALITY_REPEATED\020\003\"\316\001\n\004Enum\022\014\n\004name\030\001 \001(\t\022" - "-\n\tenumvalue\030\002 \003(\0132\032.google.protobuf.Enu" - "mValue\022(\n\007options\030\003 \003(\0132\027.google.protobu" - "f.Option\0226\n\016source_context\030\004 \001(\0132\036.googl" - "e.protobuf.SourceContext\022\'\n\006syntax\030\005 \001(\016" - "2\027.google.protobuf.Syntax\"S\n\tEnumValue\022\014" - "\n\004name\030\001 \001(\t\022\016\n\006number\030\002 \001(\005\022(\n\007options\030" - "\003 \003(\0132\027.google.protobuf.Option\";\n\006Option" - "\022\014\n\004name\030\001 \001(\t\022#\n\005value\030\002 \001(\0132\024.google.p" - "rotobuf.Any*.\n\006Syntax\022\021\n\rSYNTAX_PROTO2\020\000" - "\022\021\n\rSYNTAX_PROTO3\020\001B{\n\023com.google.protob" - "ufB\tTypeProtoP\001Z-google.golang.org/proto" - "buf/types/known/typepb\370\001\001\242\002\003GPB\252\002\036Google" - ".Protobuf.WellKnownTypesb\006proto3" - ; -static const ::_pbi::DescriptorTable* const descriptor_table_google_2fprotobuf_2ftype_2eproto_deps[2] = { - &::descriptor_table_google_2fprotobuf_2fany_2eproto, - &::descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto, +const char descriptor_table_protodef_google_2fprotobuf_2ftype_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n\032google/protobuf/type.proto\022\017google.pro" + "tobuf\032\031google/protobuf/any.proto\032$google" + "/protobuf/source_context.proto\"\327\001\n\004Type\022" + "\014\n\004name\030\001 \001(\t\022&\n\006fields\030\002 \003(\0132\026.google.p" + "rotobuf.Field\022\016\n\006oneofs\030\003 \003(\t\022(\n\007options" + "\030\004 \003(\0132\027.google.protobuf.Option\0226\n\016sourc" + "e_context\030\005 \001(\0132\036.google.protobuf.Source" + "Context\022\'\n\006syntax\030\006 \001(\0162\027.google.protobu" + "f.Syntax\"\325\005\n\005Field\022)\n\004kind\030\001 \001(\0162\033.googl" + "e.protobuf.Field.Kind\0227\n\013cardinality\030\002 \001" + "(\0162\".google.protobuf.Field.Cardinality\022\016" + "\n\006number\030\003 \001(\005\022\014\n\004name\030\004 \001(\t\022\020\n\010type_url" + "\030\006 \001(\t\022\023\n\013oneof_index\030\007 \001(\005\022\016\n\006packed\030\010 " + "\001(\010\022(\n\007options\030\t \003(\0132\027.google.protobuf.O" + "ption\022\021\n\tjson_name\030\n \001(\t\022\025\n\rdefault_valu" + "e\030\013 \001(\t\"\310\002\n\004Kind\022\020\n\014TYPE_UNKNOWN\020\000\022\017\n\013TY" + "PE_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTYPE_INT6" + "4\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT32\020\005\022\020\n\014" + "TYPE_FIXED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022\r\n\tTYPE" + "_BOOL\020\010\022\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_GROUP\020\n" + "\022\020\n\014TYPE_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020\014\022\017\n\013TY" + "PE_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYPE_SFIXE" + "D32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_SINT32\020" + "\021\022\017\n\013TYPE_SINT64\020\022\"t\n\013Cardinality\022\027\n\023CAR" + "DINALITY_UNKNOWN\020\000\022\030\n\024CARDINALITY_OPTION" + "AL\020\001\022\030\n\024CARDINALITY_REQUIRED\020\002\022\030\n\024CARDIN" + "ALITY_REPEATED\020\003\"\316\001\n\004Enum\022\014\n\004name\030\001 \001(\t\022" + "-\n\tenumvalue\030\002 \003(\0132\032.google.protobuf.Enu" + "mValue\022(\n\007options\030\003 \003(\0132\027.google.protobu" + "f.Option\0226\n\016source_context\030\004 \001(\0132\036.googl" + "e.protobuf.SourceContext\022\'\n\006syntax\030\005 \001(\016" + "2\027.google.protobuf.Syntax\"S\n\tEnumValue\022\014" + "\n\004name\030\001 \001(\t\022\016\n\006number\030\002 \001(\005\022(\n\007options\030" + "\003 \003(\0132\027.google.protobuf.Option\";\n\006Option" + "\022\014\n\004name\030\001 \001(\t\022#\n\005value\030\002 \001(\0132\024.google.p" + "rotobuf.Any*.\n\006Syntax\022\021\n\rSYNTAX_PROTO2\020\000" + "\022\021\n\rSYNTAX_PROTO3\020\001B{\n\023com.google.protob" + "ufB\tTypeProtoP\001Z-google.golang.org/proto" + "buf/types/known/typepb\370\001\001\242\002\003GPB\252\002\036Google" + ".Protobuf.WellKnownTypesb\006proto3" +}; +static const ::_pbi::DescriptorTable* const descriptor_table_google_2fprotobuf_2ftype_2eproto_deps[2] = + { + &::descriptor_table_google_2fprotobuf_2fany_2eproto, + &::descriptor_table_google_2fprotobuf_2fsource_5fcontext_2eproto, }; static ::absl::once_flag descriptor_table_google_2fprotobuf_2ftype_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2ftype_2eproto = { - false, false, 1592, descriptor_table_protodef_google_2fprotobuf_2ftype_2eproto, + false, + false, + 1592, + descriptor_table_protodef_google_2fprotobuf_2ftype_2eproto, "google/protobuf/type.proto", - &descriptor_table_google_2fprotobuf_2ftype_2eproto_once, descriptor_table_google_2fprotobuf_2ftype_2eproto_deps, 2, 5, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2ftype_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2ftype_2eproto, file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto, + &descriptor_table_google_2fprotobuf_2ftype_2eproto_once, + descriptor_table_google_2fprotobuf_2ftype_2eproto_deps, + 2, + 5, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2ftype_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2ftype_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2ftype_2eproto, file_level_service_descriptors_google_2fprotobuf_2ftype_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2ftype_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2ftype_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2ftype_2eproto(&descriptor_table_google_2fprotobuf_2ftype_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2ftype_2eproto(&descriptor_table_google_2fprotobuf_2ftype_2eproto); PROTOBUF_NAMESPACE_OPEN const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* Field_Kind_descriptor() { ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors(&descriptor_table_google_2fprotobuf_2ftype_2eproto); @@ -352,7 +379,6 @@ bool Syntax_IsValid(int value) { } } - // =================================================================== class Type::_Internal { @@ -744,7 +770,6 @@ void Type::InternalSwap(Type* other) { &descriptor_table_google_2fprotobuf_2ftype_2eproto_getter, &descriptor_table_google_2fprotobuf_2ftype_2eproto_once, file_level_metadata_google_2fprotobuf_2ftype_2eproto[0]); } - // =================================================================== class Field::_Internal { @@ -1269,7 +1294,6 @@ void Field::InternalSwap(Field* other) { &descriptor_table_google_2fprotobuf_2ftype_2eproto_getter, &descriptor_table_google_2fprotobuf_2ftype_2eproto_once, file_level_metadata_google_2fprotobuf_2ftype_2eproto[1]); } - // =================================================================== class Enum::_Internal { @@ -1622,7 +1646,6 @@ void Enum::InternalSwap(Enum* other) { &descriptor_table_google_2fprotobuf_2ftype_2eproto_getter, &descriptor_table_google_2fprotobuf_2ftype_2eproto_once, file_level_metadata_google_2fprotobuf_2ftype_2eproto[2]); } - // =================================================================== class EnumValue::_Internal { @@ -1886,7 +1909,6 @@ void EnumValue::InternalSwap(EnumValue* other) { &descriptor_table_google_2fprotobuf_2ftype_2eproto_getter, &descriptor_table_google_2fprotobuf_2ftype_2eproto_once, file_level_metadata_google_2fprotobuf_2ftype_2eproto[3]); } - // =================================================================== class Option::_Internal { @@ -2137,7 +2159,6 @@ void Option::InternalSwap(Option* other) { &descriptor_table_google_2fprotobuf_2ftype_2eproto_getter, &descriptor_table_google_2fprotobuf_2ftype_2eproto_once, file_level_metadata_google_2fprotobuf_2ftype_2eproto[4]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -2162,6 +2183,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Option >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::Option >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h index 34914636d7..66382466b7 100644 --- a/src/google/protobuf/type.pb.h +++ b/src/google/protobuf/type.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -31,11 +32,15 @@ #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/generated_enum_reflection.h" #include "google/protobuf/unknown_field_set.h" -#include -#include +#include "google/protobuf/any.pb.h" +#include "google/protobuf/source_context.pb.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftype_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -46,7 +51,8 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2ftype_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2ftype_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2ftype_2eproto; PROTOBUF_NAMESPACE_OPEN class Enum; struct EnumDefaultTypeInternal; @@ -63,16 +69,19 @@ PROTOBUF_EXPORT extern OptionDefaultTypeInternal _Option_default_instance_; class Type; struct TypeDefaultTypeInternal; PROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Enum* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Enum>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::EnumValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::EnumValue>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Field* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Field>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Option* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Option>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Type* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Type>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Enum* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Enum>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::EnumValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::EnumValue>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Field* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Field>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Option* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Option>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Type* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Type>(Arena*); -PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN +PROTOBUF_NAMESPACE_OPEN enum Field_Kind : int { Field_Kind_TYPE_UNKNOWN = 0, Field_Kind_TYPE_DOUBLE = 1, @@ -179,8 +188,12 @@ inline bool Syntax_Parse( return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( Syntax_descriptor(), name, value); } + // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT Type final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Type) */ { public: @@ -428,8 +441,7 @@ class PROTOBUF_EXPORT Type final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT Field final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Field) */ { @@ -802,8 +814,7 @@ class PROTOBUF_EXPORT Field final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT Enum final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Enum) */ { @@ -1026,8 +1037,7 @@ class PROTOBUF_EXPORT Enum final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT EnumValue final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.EnumValue) */ { @@ -1210,8 +1220,7 @@ class PROTOBUF_EXPORT EnumValue final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT Option final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Option) */ { @@ -1387,12 +1396,17 @@ class PROTOBUF_EXPORT Option final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // Type // string name = 1; @@ -2540,21 +2554,13 @@ inline void Option::set_allocated_value(::PROTOBUF_NAMESPACE_ID::Any* value) { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN template <> struct is_proto_enum< ::PROTOBUF_NAMESPACE_ID::Field_Kind> : ::std::true_type {}; @@ -2578,4 +2584,5 @@ PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2ftype_2eproto_2epb_2eh diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc index cc9048b047..60846db200 100644 --- a/src/google/protobuf/wrappers.pb.cc +++ b/src/google/protobuf/wrappers.pb.cc @@ -1,10 +1,9 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/wrappers.proto -#include +#include "google/protobuf/wrappers.pb.h" #include - #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/extension_set.h" #include "google/protobuf/wire_format_lite.h" @@ -13,274 +12,305 @@ #include "google/protobuf/reflection_ops.h" #include "google/protobuf/wire_format.h" // @@protoc_insertion_point(includes) -#include "google/protobuf/port_def.inc" +// Must be included last. +#include "google/protobuf/port_def.inc" PROTOBUF_PRAGMA_INIT_SEG - namespace _pb = ::PROTOBUF_NAMESPACE_ID; -namespace _pbi = _pb::internal; - +namespace _pbi = ::PROTOBUF_NAMESPACE_ID::internal; PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR DoubleValue::DoubleValue( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct DoubleValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR DoubleValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR DoubleValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~DoubleValueDefaultTypeInternal() {} union { DoubleValue _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 DoubleValueDefaultTypeInternal _DoubleValue_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 DoubleValueDefaultTypeInternal _DoubleValue_default_instance_; PROTOBUF_CONSTEXPR FloatValue::FloatValue( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct FloatValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR FloatValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR FloatValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~FloatValueDefaultTypeInternal() {} union { FloatValue _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FloatValueDefaultTypeInternal _FloatValue_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FloatValueDefaultTypeInternal _FloatValue_default_instance_; PROTOBUF_CONSTEXPR Int64Value::Int64Value( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/int64_t{0} , /*decltype(_impl_._cached_size_)*/{}} {} struct Int64ValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR Int64ValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR Int64ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~Int64ValueDefaultTypeInternal() {} union { Int64Value _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Int64ValueDefaultTypeInternal _Int64Value_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Int64ValueDefaultTypeInternal _Int64Value_default_instance_; PROTOBUF_CONSTEXPR UInt64Value::UInt64Value( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/uint64_t{0u} , /*decltype(_impl_._cached_size_)*/{}} {} struct UInt64ValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR UInt64ValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR UInt64ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~UInt64ValueDefaultTypeInternal() {} union { UInt64Value _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_; PROTOBUF_CONSTEXPR Int32Value::Int32Value( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/0 , /*decltype(_impl_._cached_size_)*/{}} {} struct Int32ValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR Int32ValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR Int32ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~Int32ValueDefaultTypeInternal() {} union { Int32Value _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Int32ValueDefaultTypeInternal _Int32Value_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Int32ValueDefaultTypeInternal _Int32Value_default_instance_; PROTOBUF_CONSTEXPR UInt32Value::UInt32Value( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/0u , /*decltype(_impl_._cached_size_)*/{}} {} struct UInt32ValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR UInt32ValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR UInt32ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~UInt32ValueDefaultTypeInternal() {} union { UInt32Value _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 UInt32ValueDefaultTypeInternal _UInt32Value_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 UInt32ValueDefaultTypeInternal _UInt32Value_default_instance_; PROTOBUF_CONSTEXPR BoolValue::BoolValue( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/false , /*decltype(_impl_._cached_size_)*/{}} {} struct BoolValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR BoolValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR BoolValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~BoolValueDefaultTypeInternal() {} union { BoolValue _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 BoolValueDefaultTypeInternal _BoolValue_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 BoolValueDefaultTypeInternal _BoolValue_default_instance_; PROTOBUF_CONSTEXPR StringValue::StringValue( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} , /*decltype(_impl_._cached_size_)*/{}} {} struct StringValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR StringValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR StringValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~StringValueDefaultTypeInternal() {} union { StringValue _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 StringValueDefaultTypeInternal _StringValue_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 StringValueDefaultTypeInternal _StringValue_default_instance_; PROTOBUF_CONSTEXPR BytesValue::BytesValue( ::_pbi::ConstantInitialized): _impl_{ /*decltype(_impl_.value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} , /*decltype(_impl_._cached_size_)*/{}} {} struct BytesValueDefaultTypeInternal { - PROTOBUF_CONSTEXPR BytesValueDefaultTypeInternal() - : _instance(::_pbi::ConstantInitialized{}) {} + PROTOBUF_CONSTEXPR BytesValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} ~BytesValueDefaultTypeInternal() {} union { BytesValue _instance; }; }; -PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 BytesValueDefaultTypeInternal _BytesValue_default_instance_; + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT + PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 BytesValueDefaultTypeInternal _BytesValue_default_instance_; PROTOBUF_NAMESPACE_CLOSE static ::_pb::Metadata file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[9]; -static constexpr ::_pb::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fwrappers_2eproto = nullptr; -static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fwrappers_2eproto = nullptr; - -const uint32_t TableStruct_google_2fprotobuf_2fwrappers_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DoubleValue, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DoubleValue, _impl_.value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FloatValue, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FloatValue, _impl_.value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int64Value, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int64Value, _impl_.value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt64Value, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt64Value, _impl_.value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int32Value, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int32Value, _impl_.value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt32Value, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt32Value, _impl_.value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BoolValue, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BoolValue, _impl_.value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::StringValue, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::StringValue, _impl_.value_), - ~0u, // no _has_bits_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BytesValue, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - ~0u, // no _inlined_string_donated_ - ~0u, // no _split_ - ~0u, // no sizeof(Split) - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BytesValue, _impl_.value_), +static constexpr const ::_pb::EnumDescriptor** + file_level_enum_descriptors_google_2fprotobuf_2fwrappers_2eproto = nullptr; +static constexpr const ::_pb::ServiceDescriptor** + file_level_service_descriptors_google_2fprotobuf_2fwrappers_2eproto = nullptr; +const uint32_t TableStruct_google_2fprotobuf_2fwrappers_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE( + protodesc_cold) = { + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DoubleValue, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DoubleValue, _impl_.value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FloatValue, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FloatValue, _impl_.value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int64Value, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int64Value, _impl_.value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt64Value, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt64Value, _impl_.value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int32Value, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int32Value, _impl_.value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt32Value, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt32Value, _impl_.value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BoolValue, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BoolValue, _impl_.value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::StringValue, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::StringValue, _impl_.value_), + ~0u, // no _has_bits_ + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BytesValue, _internal_metadata_), + ~0u, // no _extensions_ + ~0u, // no _oneof_case_ + ~0u, // no _weak_field_map_ + ~0u, // no _inlined_string_donated_ + ~0u, // no _split_ + ~0u, // no sizeof(Split) + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BytesValue, _impl_.value_), }; -static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::DoubleValue)}, - { 9, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::FloatValue)}, - { 18, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Int64Value)}, - { 27, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::UInt64Value)}, - { 36, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Int32Value)}, - { 45, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::UInt32Value)}, - { 54, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::BoolValue)}, - { 63, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::StringValue)}, - { 72, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::BytesValue)}, + +static const ::_pbi::MigrationSchema + schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::DoubleValue)}, + { 9, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::FloatValue)}, + { 18, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Int64Value)}, + { 27, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::UInt64Value)}, + { 36, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Int32Value)}, + { 45, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::UInt32Value)}, + { 54, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::BoolValue)}, + { 63, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::StringValue)}, + { 72, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::BytesValue)}, }; static const ::_pb::Message* const file_default_instances[] = { - &::PROTOBUF_NAMESPACE_ID::_DoubleValue_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_FloatValue_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Int64Value_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_UInt64Value_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_Int32Value_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_UInt32Value_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_BoolValue_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_StringValue_default_instance_._instance, - &::PROTOBUF_NAMESPACE_ID::_BytesValue_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_DoubleValue_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_FloatValue_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Int64Value_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_UInt64Value_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_Int32Value_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_UInt32Value_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_BoolValue_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_StringValue_default_instance_._instance, + &::PROTOBUF_NAMESPACE_ID::_BytesValue_default_instance_._instance, +}; +const char descriptor_table_protodef_google_2fprotobuf_2fwrappers_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { + "\n\036google/protobuf/wrappers.proto\022\017google" + ".protobuf\"\034\n\013DoubleValue\022\r\n\005value\030\001 \001(\001\"" + "\033\n\nFloatValue\022\r\n\005value\030\001 \001(\002\"\033\n\nInt64Val" + "ue\022\r\n\005value\030\001 \001(\003\"\034\n\013UInt64Value\022\r\n\005valu" + "e\030\001 \001(\004\"\033\n\nInt32Value\022\r\n\005value\030\001 \001(\005\"\034\n\013" + "UInt32Value\022\r\n\005value\030\001 \001(\r\"\032\n\tBoolValue\022" + "\r\n\005value\030\001 \001(\010\"\034\n\013StringValue\022\r\n\005value\030\001" + " \001(\t\"\033\n\nBytesValue\022\r\n\005value\030\001 \001(\014B\203\001\n\023co" + "m.google.protobufB\rWrappersProtoP\001Z1goog" + "le.golang.org/protobuf/types/known/wrapp" + "erspb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKno" + "wnTypesb\006proto3" }; - -const char descriptor_table_protodef_google_2fprotobuf_2fwrappers_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = - "\n\036google/protobuf/wrappers.proto\022\017google" - ".protobuf\"\034\n\013DoubleValue\022\r\n\005value\030\001 \001(\001\"" - "\033\n\nFloatValue\022\r\n\005value\030\001 \001(\002\"\033\n\nInt64Val" - "ue\022\r\n\005value\030\001 \001(\003\"\034\n\013UInt64Value\022\r\n\005valu" - "e\030\001 \001(\004\"\033\n\nInt32Value\022\r\n\005value\030\001 \001(\005\"\034\n\013" - "UInt32Value\022\r\n\005value\030\001 \001(\r\"\032\n\tBoolValue\022" - "\r\n\005value\030\001 \001(\010\"\034\n\013StringValue\022\r\n\005value\030\001" - " \001(\t\"\033\n\nBytesValue\022\r\n\005value\030\001 \001(\014B\203\001\n\023co" - "m.google.protobufB\rWrappersProtoP\001Z1goog" - "le.golang.org/protobuf/types/known/wrapp" - "erspb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKno" - "wnTypesb\006proto3" - ; static ::absl::once_flag descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once; const ::_pbi::DescriptorTable descriptor_table_google_2fprotobuf_2fwrappers_2eproto = { - false, false, 455, descriptor_table_protodef_google_2fprotobuf_2fwrappers_2eproto, + false, + false, + 455, + descriptor_table_protodef_google_2fprotobuf_2fwrappers_2eproto, "google/protobuf/wrappers.proto", - &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, nullptr, 0, 9, - schemas, file_default_instances, TableStruct_google_2fprotobuf_2fwrappers_2eproto::offsets, - file_level_metadata_google_2fprotobuf_2fwrappers_2eproto, file_level_enum_descriptors_google_2fprotobuf_2fwrappers_2eproto, + &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, + nullptr, + 0, + 9, + schemas, + file_default_instances, + TableStruct_google_2fprotobuf_2fwrappers_2eproto::offsets, + file_level_metadata_google_2fprotobuf_2fwrappers_2eproto, + file_level_enum_descriptors_google_2fprotobuf_2fwrappers_2eproto, file_level_service_descriptors_google_2fprotobuf_2fwrappers_2eproto, }; + +// This function exists to be marked as weak. +// It can significantly speed up compilation by breaking up LLVM's SCC +// in the .pb.cc translation units. Large translation units see a +// reduction of more than 35% of walltime for optimized builds. Without +// the weak attribute all the messages in the file, including all the +// vtables and everything they use become part of the same SCC through +// a cycle like: +// GetMetadata -> descriptor table -> default instances -> +// vtables -> GetMetadata +// By adding a weak function here we break the connection from the +// individual vtables back into the descriptor table. PROTOBUF_ATTRIBUTE_WEAK const ::_pbi::DescriptorTable* descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter() { return &descriptor_table_google_2fprotobuf_2fwrappers_2eproto; } - // Force running AddDescriptors() at dynamic initialization time. -PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fwrappers_2eproto(&descriptor_table_google_2fprotobuf_2fwrappers_2eproto); +PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 +static ::_pbi::AddDescriptorsRunner dynamic_init_dummy_google_2fprotobuf_2fwrappers_2eproto(&descriptor_table_google_2fprotobuf_2fwrappers_2eproto); PROTOBUF_NAMESPACE_OPEN - // =================================================================== class DoubleValue::_Internal { @@ -470,7 +500,6 @@ void DoubleValue::InternalSwap(DoubleValue* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[0]); } - // =================================================================== class FloatValue::_Internal { @@ -660,7 +689,6 @@ void FloatValue::InternalSwap(FloatValue* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[1]); } - // =================================================================== class Int64Value::_Internal { @@ -838,7 +866,6 @@ void Int64Value::InternalSwap(Int64Value* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[2]); } - // =================================================================== class UInt64Value::_Internal { @@ -1016,7 +1043,6 @@ void UInt64Value::InternalSwap(UInt64Value* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[3]); } - // =================================================================== class Int32Value::_Internal { @@ -1194,7 +1220,6 @@ void Int32Value::InternalSwap(Int32Value* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[4]); } - // =================================================================== class UInt32Value::_Internal { @@ -1372,7 +1397,6 @@ void UInt32Value::InternalSwap(UInt32Value* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[5]); } - // =================================================================== class BoolValue::_Internal { @@ -1550,7 +1574,6 @@ void BoolValue::InternalSwap(BoolValue* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[6]); } - // =================================================================== class StringValue::_Internal { @@ -1753,7 +1776,6 @@ void StringValue::InternalSwap(StringValue* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[7]); } - // =================================================================== class BytesValue::_Internal { @@ -1951,7 +1973,6 @@ void BytesValue::InternalSwap(BytesValue* other) { &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_getter, &descriptor_table_google_2fprotobuf_2fwrappers_2eproto_once, file_level_metadata_google_2fprotobuf_2fwrappers_2eproto[8]); } - // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN @@ -1992,6 +2013,5 @@ Arena::CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::BytesValue >(Arena* arena) { return Arena::CreateMessageInternal< ::PROTOBUF_NAMESPACE_ID::BytesValue >(arena); } PROTOBUF_NAMESPACE_CLOSE - // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h index 16ec96e853..a7af36d7d1 100644 --- a/src/google/protobuf/wrappers.pb.h +++ b/src/google/protobuf/wrappers.pb.h @@ -6,19 +6,20 @@ #include #include +#include #include "google/protobuf/port_def.inc" #if PROTOBUF_VERSION < 3021000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif +#error "This file was generated by a newer version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please update" +#error "your headers." +#endif // PROTOBUF_VERSION +#if 3021006 < PROTOBUF_MIN_PROTOC_VERSION +#error "This file was generated by an older version of protoc which is" +#error "incompatible with your Protocol Buffer headers. Please" +#error "regenerate this file with a newer version of protoc." +#endif // PROTOBUF_MIN_PROTOC_VERSION #include "google/protobuf/port_undef.inc" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/arena.h" @@ -31,8 +32,12 @@ #include "google/protobuf/extension_set.h" // IWYU pragma: export #include "google/protobuf/unknown_field_set.h" // @@protoc_insertion_point(includes) + +// Must be included last. #include "google/protobuf/port_def.inc" + #define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fwrappers_2eproto PROTOBUF_EXPORT + PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; @@ -43,7 +48,8 @@ PROTOBUF_NAMESPACE_CLOSE struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fwrappers_2eproto { static const uint32_t offsets[]; }; -PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fwrappers_2eproto; +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable + descriptor_table_google_2fprotobuf_2fwrappers_2eproto; PROTOBUF_NAMESPACE_OPEN class BoolValue; struct BoolValueDefaultTypeInternal; @@ -72,22 +78,33 @@ PROTOBUF_EXPORT extern UInt32ValueDefaultTypeInternal _UInt32Value_default_insta class UInt64Value; struct UInt64ValueDefaultTypeInternal; PROTOBUF_EXPORT extern UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_; +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::BoolValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::BoolValue>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::BytesValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::BytesValue>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::DoubleValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::DoubleValue>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::FloatValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::FloatValue>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Int32Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Int32Value>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Int64Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Int64Value>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::StringValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::StringValue>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::UInt32Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::UInt32Value>(Arena*); +template <> +PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::UInt64Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::UInt64Value>(Arena*); PROTOBUF_NAMESPACE_CLOSE -PROTOBUF_NAMESPACE_OPEN -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::BoolValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::BoolValue>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::BytesValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::BytesValue>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::DoubleValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::DoubleValue>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::FloatValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::FloatValue>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Int32Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Int32Value>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::Int64Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Int64Value>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::StringValue* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::StringValue>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::UInt32Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::UInt32Value>(Arena*); -template<> PROTOBUF_EXPORT ::PROTOBUF_NAMESPACE_ID::UInt64Value* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::UInt64Value>(Arena*); -PROTOBUF_NAMESPACE_CLOSE + PROTOBUF_NAMESPACE_OPEN // =================================================================== + +// ------------------------------------------------------------------- + class PROTOBUF_EXPORT DoubleValue final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.DoubleValue) */ { public: @@ -233,8 +250,7 @@ class PROTOBUF_EXPORT DoubleValue final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT FloatValue final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.FloatValue) */ { @@ -381,8 +397,7 @@ class PROTOBUF_EXPORT FloatValue final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT Int64Value final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int64Value) */ { @@ -529,8 +544,7 @@ class PROTOBUF_EXPORT Int64Value final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT UInt64Value final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt64Value) */ { @@ -677,8 +691,7 @@ class PROTOBUF_EXPORT UInt64Value final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT Int32Value final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Int32Value) */ { @@ -825,8 +838,7 @@ class PROTOBUF_EXPORT Int32Value final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT UInt32Value final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.UInt32Value) */ { @@ -973,8 +985,7 @@ class PROTOBUF_EXPORT UInt32Value final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT BoolValue final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BoolValue) */ { @@ -1121,8 +1132,7 @@ class PROTOBUF_EXPORT BoolValue final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT StringValue final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.StringValue) */ { @@ -1274,8 +1284,7 @@ class PROTOBUF_EXPORT StringValue final : }; union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; -}; -// ------------------------------------------------------------------- +};// ------------------------------------------------------------------- class PROTOBUF_EXPORT BytesValue final : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.BytesValue) */ { @@ -1431,12 +1440,17 @@ class PROTOBUF_EXPORT BytesValue final : // =================================================================== + + // =================================================================== + #ifdef __GNUC__ - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Wstrict-aliasing" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ +// ------------------------------------------------------------------- + // DoubleValue // double value = 1; @@ -1712,30 +1726,15 @@ inline void BytesValue::set_allocated_value(std::string* value) { } #ifdef __GNUC__ - #pragma GCC diagnostic pop +#pragma GCC diagnostic pop #endif // __GNUC__ -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - -// ------------------------------------------------------------------- - // @@protoc_insertion_point(namespace_scope) - PROTOBUF_NAMESPACE_CLOSE + // @@protoc_insertion_point(global_scope) #include "google/protobuf/port_undef.inc" -#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto_2epb_2eh + +#endif // GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fwrappers_2eproto_2epb_2eh From 790f85dad25a033484c2ba90572ca020e62ed43f Mon Sep 17 00:00:00 2001 From: Dennis Shao <67387070+shaod2@users.noreply.github.com> Date: Tue, 20 Sep 2022 15:06:54 -0700 Subject: [PATCH 49/64] Correct the link to example WORKSPACE file --- src/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/README.md b/src/README.md index 3592f4f272..b28b0f0382 100644 --- a/src/README.md +++ b/src/README.md @@ -62,7 +62,7 @@ For more usage information on Bazel, please refer to http://bazel.build. To compile a package that uses Protocol Buffers, you need to setup a Bazel WORKSPACE that's hooked up to the protobuf repository and loads its -dependencies. For an example, see [WORKSPACE](examples/WORKSPACE). +dependencies. For an example, see [WORKSPACE](../examples/WORKSPACE). **Note for Mac users** From 8e74523ff6b5639ec988679634ca800fc927cda0 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 21 Sep 2022 12:33:24 -0400 Subject: [PATCH 50/64] address review feedback --- .../protobuf/compiler/parser_unittest.cc | 126 ++++++++++-------- src/google/protobuf/descriptor.cc | 85 ++++++------ 2 files changed, 113 insertions(+), 98 deletions(-) diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 568a699727..e51b6e3260 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -1972,12 +1972,14 @@ TEST_F(ParserValidationErrorTest, Proto3Default) { TEST_F(ParserValidationErrorTest, Proto3JsonConflictError) { ExpectHasValidationErrors( - "syntax = 'proto3';\n" - "message TestMessage {\n" - " uint32 foo = 1;\n" - " uint32 Foo = 2;\n" - "}\n", - "3:9: The default JSON name of field \"Foo\" (\"Foo\") conflicts " + R"pb( + syntax = 'proto3'; + message TestMessage { + uint32 foo = 1; + uint32 Foo = 2; + } + )pb", + "4:15: The default JSON name of field \"Foo\" (\"Foo\") conflicts " "with the default JSON name of field \"foo\" (\"foo\"). " "This is not allowed in proto3.\n"); } @@ -1985,33 +1987,38 @@ TEST_F(ParserValidationErrorTest, Proto3JsonConflictError) { TEST_F(ParserValidationErrorTest, Proto2JsonConflictError) { // conflicts with default JSON names are not errors in proto2 ExpectParsesTo( - "syntax = 'proto2';\n" - "message TestMessage {\n" - " optional uint32 foo = 1;\n" - " optional uint32 Foo = 2;\n" - "}\n", - - "syntax: 'proto2'" - "message_type {" - " name: 'TestMessage'" - " field {" - " label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'foo' number: 1" - " }" - " field {" - " label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'Foo' number: 2" - " }" - "}" + R"pb( + syntax = "proto2"; + message TestMessage { + optional uint32 foo = 1; + optional uint32 Foo = 2; + } + )pb", + R"pb( + syntax: 'proto2' + message_type { + name: 'TestMessage' + field { + label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'foo' number: 1 + } + field { + label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'Foo' number: 2 + } + } + )pb" ); } TEST_F(ParserValidationErrorTest, Proto3CustomJsonConflictWithDefaultError) { ExpectHasValidationErrors( - "syntax = 'proto3';\n" - "message TestMessage {\n" - " uint32 foo = 1 [json_name='bar'];\n" - " uint32 bar = 2;\n" - "}\n", - "3:9: The default JSON name of field \"bar\" (\"bar\") conflicts " + R"pb( + syntax = 'proto3'; + message TestMessage { + uint32 foo = 1 [json_name='bar']; + uint32 bar = 2; + } + )pb", + "4:15: The default JSON name of field \"bar\" (\"bar\") conflicts " "with the custom JSON name of field \"foo\". " "This is not allowed in proto3.\n"); } @@ -2019,45 +2026,52 @@ TEST_F(ParserValidationErrorTest, Proto3CustomJsonConflictWithDefaultError) { TEST_F(ParserValidationErrorTest, Proto2CustomJsonConflictWithDefaultError) { // conflicts with default JSON names are not errors in proto2 ExpectParsesTo( - "syntax = 'proto2';\n" - "message TestMessage {\n" - " optional uint32 foo = 1 [json_name='bar'];\n" - " optional uint32 bar = 2;\n" - "}\n", - - "syntax: 'proto2'" - "message_type {" - " name: 'TestMessage'" - " field {" - " label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'foo' number: 1 json_name: 'bar'" - " }" - " field {" - " label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'bar' number: 2" - " }" - "}" + R"pb( + syntax = 'proto2'; + message TestMessage { + optional uint32 foo = 1 [json_name='bar']; + optional uint32 bar = 2; + } + )pb", + R"pb( + syntax: 'proto2' + message_type { + name: 'TestMessage' + field { + label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'foo' number: 1 json_name: 'bar' + } + field { + label: LABEL_OPTIONAL type: TYPE_UINT32 name: 'bar' number: 2 + } + } + )pb" ); } TEST_F(ParserValidationErrorTest, Proto3CustomJsonConflictError) { ExpectHasValidationErrors( - "syntax = 'proto3';\n" - "message TestMessage {\n" - " uint32 foo = 1 [json_name='baz'];\n" - " uint32 bar = 2 [json_name='baz'];\n" - "}\n", - "3:9: The custom JSON name of field \"bar\" (\"baz\") conflicts " + R"pb( + syntax = 'proto3'; + message TestMessage { + uint32 foo = 1 [json_name='baz']; + uint32 bar = 2 [json_name='baz']; + } + )pb", + "4:15: The custom JSON name of field \"bar\" (\"baz\") conflicts " "with the custom JSON name of field \"foo\".\n"); } TEST_F(ParserValidationErrorTest, Proto2CustomJsonConflictError) { ExpectHasValidationErrors( - "syntax = 'proto2';\n" - "message TestMessage {\n" - " optional uint32 foo = 1 [json_name='baz'];\n" - " optional uint32 bar = 2 [json_name='baz'];\n" - "}\n", + R"pb( + syntax = 'proto2'; + message TestMessage { + optional uint32 foo = 1 [json_name='baz']; + optional uint32 bar = 2 [json_name='baz']; + } + )pb", // fails in proto2 also: can't explicitly configure bad custom JSON names - "3:18: The custom JSON name of field \"bar\" (\"baz\") conflicts " + "4:24: The custom JSON name of field \"bar\" (\"baz\") conflicts " "with the custom JSON name of field \"foo\".\n"); } diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 393be38294..4dfdc287f5 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -3861,9 +3861,10 @@ class DescriptorBuilder { void CheckFieldJsonNameUniqueness(const DescriptorProto& proto, const Descriptor* result); - void CheckFieldJsonNameUniqueness(std::string message_name, + void CheckFieldJsonNameUniqueness(const std::string& message_name, const DescriptorProto& message, - bool is_proto2, bool use_custom_names); + FileDescriptor::Syntax syntax, + bool use_custom_names); void CheckEnumValueUniqueness(const EnumDescriptorProto& proto, const EnumDescriptor* result); @@ -5492,12 +5493,12 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, void DescriptorBuilder::CheckFieldJsonNameUniqueness( const DescriptorProto& proto, const Descriptor* result) { - bool is_proto2 = result->file()->syntax() == FileDescriptor::SYNTAX_PROTO2; + FileDescriptor::Syntax syntax = result->file()->syntax(); std::string message_name = result->full_name(); // two passes: one looking only at default JSON names, and one that considers // custom JSON names - CheckFieldJsonNameUniqueness(message_name, proto, is_proto2, false); - CheckFieldJsonNameUniqueness(message_name, proto, is_proto2, true); + CheckFieldJsonNameUniqueness(message_name, proto, syntax, false); + CheckFieldJsonNameUniqueness(message_name, proto, syntax, true); } namespace { @@ -5522,8 +5523,8 @@ struct JsonNameDetails { } // namespace void DescriptorBuilder::CheckFieldJsonNameUniqueness( - std::string message_name, const DescriptorProto& message, bool is_proto2, - bool use_custom_names) { + const std::string& message_name, const DescriptorProto& message, + FileDescriptor::Syntax syntax, bool use_custom_names) { absl::flat_hash_map name_to_field; for (const FieldDescriptorProto& field : message.field()) { @@ -5531,43 +5532,43 @@ void DescriptorBuilder::CheckFieldJsonNameUniqueness( std::string name = GetJsonName(field, use_custom_names, &is_custom); std::string lowercase_name = absl::AsciiStrToLower(name); auto existing = name_to_field.find(lowercase_name); - if (existing != name_to_field.end()) { - JsonNameDetails& match = existing->second; - if (use_custom_names && !is_custom && !match.is_custom) { - // if this pass is considering custom JSON names, but neither of the - // names involved in the conflict are custom, don't bother with a - // message. That will have been reported from other pass (non-custom - // JSON names). - continue; - } - absl::string_view this_type = is_custom ? "custom" : "default"; - absl::string_view existing_type = match.is_custom ? "custom" : "default"; - // If the matched name differs (which it can only differ in case), include - // it in the error message, for maximum clarity to user. - absl::string_view name_suffix = ""; - if (name != match.orig_name) { - name_suffix = absl::StrCat(" (\"", match.orig_name, "\")"); - } - std::string error_message = - absl::StrFormat("The %s JSON name of field \"%s\" (\"%s\") conflicts " - "with the %s JSON name of field \"%s\"%s.", - this_type, field.name(), name, existing_type, - match.field->name(), name_suffix); - - bool involves_default = !is_custom || !match.is_custom; - if (is_proto2 && involves_default) { - AddWarning(message_name, field, DescriptorPool::ErrorCollector::NAME, - error_message); - } else { - if (involves_default) { - absl::StrAppend(&error_message, " This is not allowed in proto3."); - } - AddError(message_name, field, DescriptorPool::ErrorCollector::NAME, - error_message); - } - } else { + if (existing == name_to_field.end()) { JsonNameDetails details = {&field, name, is_custom}; name_to_field[lowercase_name] = details; + continue; + } + JsonNameDetails& match = existing->second; + if (use_custom_names && !is_custom && !match.is_custom) { + // if this pass is considering custom JSON names, but neither of the + // names involved in the conflict are custom, don't bother with a + // message. That will have been reported from other pass (non-custom + // JSON names). + continue; + } + absl::string_view this_type = is_custom ? "custom" : "default"; + absl::string_view existing_type = match.is_custom ? "custom" : "default"; + // If the matched name differs (which it can only differ in case), include + // it in the error message, for maximum clarity to user. + absl::string_view name_suffix = ""; + if (name != match.orig_name) { + name_suffix = absl::StrCat(" (\"", match.orig_name, "\")"); + } + std::string error_message = + absl::StrFormat("The %s JSON name of field \"%s\" (\"%s\") conflicts " + "with the %s JSON name of field \"%s\"%s.", + this_type, field.name(), name, existing_type, + match.field->name(), name_suffix); + + bool involves_default = !is_custom || !match.is_custom; + if (syntax == FileDescriptor::SYNTAX_PROTO2 && involves_default) { + AddWarning(message_name, field, DescriptorPool::ErrorCollector::NAME, + error_message); + } else { + if (involves_default) { + absl::StrAppend(&error_message, " This is not allowed in proto3."); + } + AddError(message_name, field, DescriptorPool::ErrorCollector::NAME, + error_message); } } } From c7ba0553f511b00519ade94b976480efb37e85b2 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 21 Sep 2022 12:54:20 -0400 Subject: [PATCH 51/64] return struct instead of using out param --- src/google/protobuf/descriptor.cc | 34 ++++++++++++++----------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 4dfdc287f5..43ea110424 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -5504,22 +5504,20 @@ void DescriptorBuilder::CheckFieldJsonNameUniqueness( namespace { // Helpers for function below -std::string GetJsonName(const FieldDescriptorProto& field, bool use_custom, - bool* was_custom) { - if (use_custom && field.has_json_name()) { - *was_custom = true; - return field.json_name(); - } - *was_custom = false; - return ToJsonName(field.name()); -} - struct JsonNameDetails { const FieldDescriptorProto* field; std::string orig_name; bool is_custom; }; +JsonNameDetails GetJsonNameDetails(const FieldDescriptorProto* field, bool use_custom) { + if (use_custom && field->has_json_name()) { + return {field, field->json_name(), true}; + } + return {field, ToJsonName(field->name()), false}; +} + + } // namespace void DescriptorBuilder::CheckFieldJsonNameUniqueness( @@ -5528,38 +5526,36 @@ void DescriptorBuilder::CheckFieldJsonNameUniqueness( absl::flat_hash_map name_to_field; for (const FieldDescriptorProto& field : message.field()) { - bool is_custom; - std::string name = GetJsonName(field, use_custom_names, &is_custom); - std::string lowercase_name = absl::AsciiStrToLower(name); + JsonNameDetails details = GetJsonNameDetails(&field, use_custom_names); + std::string lowercase_name = absl::AsciiStrToLower(details.orig_name); auto existing = name_to_field.find(lowercase_name); if (existing == name_to_field.end()) { - JsonNameDetails details = {&field, name, is_custom}; name_to_field[lowercase_name] = details; continue; } JsonNameDetails& match = existing->second; - if (use_custom_names && !is_custom && !match.is_custom) { + if (use_custom_names && !details.is_custom && !match.is_custom) { // if this pass is considering custom JSON names, but neither of the // names involved in the conflict are custom, don't bother with a // message. That will have been reported from other pass (non-custom // JSON names). continue; } - absl::string_view this_type = is_custom ? "custom" : "default"; + absl::string_view this_type = details.is_custom ? "custom" : "default"; absl::string_view existing_type = match.is_custom ? "custom" : "default"; // If the matched name differs (which it can only differ in case), include // it in the error message, for maximum clarity to user. absl::string_view name_suffix = ""; - if (name != match.orig_name) { + if (details.orig_name != match.orig_name) { name_suffix = absl::StrCat(" (\"", match.orig_name, "\")"); } std::string error_message = absl::StrFormat("The %s JSON name of field \"%s\" (\"%s\") conflicts " "with the %s JSON name of field \"%s\"%s.", - this_type, field.name(), name, existing_type, + this_type, field.name(), details.orig_name, existing_type, match.field->name(), name_suffix); - bool involves_default = !is_custom || !match.is_custom; + bool involves_default = !details.is_custom || !match.is_custom; if (syntax == FileDescriptor::SYNTAX_PROTO2 && involves_default) { AddWarning(message_name, field, DescriptorPool::ErrorCollector::NAME, error_message); From 072fb8f58a63f36b34b5cb05242903ae71245b2c Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 21 Sep 2022 18:24:59 -0400 Subject: [PATCH 52/64] downgrade to a warning --- src/google/protobuf/compiler/parser.cc | 11 +++--- src/google/protobuf/compiler/parser.h | 3 ++ .../protobuf/compiler/parser_unittest.cc | 36 +++++++++++++------ 3 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index e053eca7e5..b937fa25b9 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -390,13 +390,16 @@ void Parser::AddError(const std::string& error) { AddError(input_->current().line, input_->current().column, error); } -void Parser::AddWarning(const std::string& warning) { +void Parser::AddWarning(int line, int column, const std::string& warning) { if (error_collector_ != nullptr) { - error_collector_->AddWarning(input_->current().line, - input_->current().column, warning); + error_collector_->AddWarning(line, column, warning); } } +void Parser::AddWarning(const std::string& warning) { + AddWarning(input_->current().line, input_->current().column, warning); +} + // ------------------------------------------------------------------- Parser::LocationRecorder::LocationRecorder(Parser* parser) @@ -1736,7 +1739,7 @@ bool Parser::ParseReservedName(std::string* name, const char* error_message) { int col = input_->current().column; DO(ConsumeString(name, error_message)); if (!io::Tokenizer::IsIdentifier(*name)) { - AddError(line, col, absl::StrFormat("Reserved name \"%s\" is not a valid identifier.", *name)); + AddWarning(line, col, absl::StrFormat("Reserved name \"%s\" is not a valid identifier.", *name)); return false; } return true; diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index b7dfec6e25..600fef6adb 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -213,6 +213,9 @@ class PROTOBUF_EXPORT Parser { // of the current token. void AddError(const std::string& error); + // Invokes error_collector_->AddWarning(), if error_collector_ is not NULL. + void AddWarning(int line, int column, const std::string& warning); + // Invokes error_collector_->AddWarning() with the line and column number // of the current token. void AddWarning(const std::string& warning); diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index c6dae84494..9cd34f155c 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -147,6 +147,16 @@ class ParserTest : public testing::Test { EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); } + // Parse the text and expect that the given warnings are reported. + void ExpectHasWarnings(const char* text, const char* expected_warnings) { + SetupParser(text); + FileDescriptorProto file; + parser_->Parse(input_.get(), &file); + EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); + ASSERT_EQ("", error_collector_.text_); + EXPECT_EQ(expected_warnings, error_collector_.warning_); + } + // Same as above but does not expect that the parser parses the complete // input. void ExpectHasEarlyExitErrors(const char* text, const char* expected_errors) { @@ -1676,12 +1686,14 @@ TEST_F(ParseErrorTest, EnumReservedMissingQuotes) { } TEST_F(ParseErrorTest, EnumReservedInvalidIdentifier) { - ExpectHasErrors( - "enum TestEnum {\n" - " FOO = 1;\n" - " reserved \"foo bar\";\n" - "}\n", - "2:11: Reserved name \"foo bar\" is not a valid identifier.\n"); + ExpectHasWarnings( + R"pb( + enum TestEnum { + FOO = 1; + reserved "foo bar"; + } + )pb", + "3:17: Reserved name \"foo bar\" is not a valid identifier.\n"); } // ------------------------------------------------------------------- @@ -1712,11 +1724,13 @@ TEST_F(ParseErrorTest, ReservedMissingQuotes) { } TEST_F(ParseErrorTest, ReservedInvalidIdentifier) { - ExpectHasErrors( - "message Foo {\n" - " reserved \"foo bar\";\n" - "}\n", - "1:11: Reserved name \"foo bar\" is not a valid identifier.\n"); + ExpectHasWarnings( + R"pb( + message Foo { + reserved "foo bar"; + } + )pb", + "2:17: Reserved name \"foo bar\" is not a valid identifier.\n"); } TEST_F(ParseErrorTest, ReservedNegativeNumber) { From 8f17f578552215bd1a3563fe4c2538775064f351 Mon Sep 17 00:00:00 2001 From: Josh Humphries Date: Wed, 21 Sep 2022 22:12:49 -0400 Subject: [PATCH 53/64] don't return false and abort parsing of current statement --- src/google/protobuf/compiler/parser.cc | 1 - src/google/protobuf/compiler/parser_unittest.cc | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index b937fa25b9..fafd3c57f6 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -1740,7 +1740,6 @@ bool Parser::ParseReservedName(std::string* name, const char* error_message) { DO(ConsumeString(name, error_message)); if (!io::Tokenizer::IsIdentifier(*name)) { AddWarning(line, col, absl::StrFormat("Reserved name \"%s\" is not a valid identifier.", *name)); - return false; } return true; } diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 9cd34f155c..4e261433a6 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -151,7 +151,7 @@ class ParserTest : public testing::Test { void ExpectHasWarnings(const char* text, const char* expected_warnings) { SetupParser(text); FileDescriptorProto file; - parser_->Parse(input_.get(), &file); + ASSERT_TRUE(parser_->Parse(input_.get(), &file)); EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); ASSERT_EQ("", error_collector_.text_); EXPECT_EQ(expected_warnings, error_collector_.warning_); From 0a60bdc070d22a74dc95be9b0509a9c3380955b9 Mon Sep 17 00:00:00 2001 From: Miguel Young de la Sota Date: Thu, 22 Sep 2022 12:29:04 -0400 Subject: [PATCH 54/64] Fix a UAF in descriptor.cc that slipped past CI --- src/google/protobuf/descriptor.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index dfe89c7073..3a089e3e94 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -5553,7 +5553,7 @@ void DescriptorBuilder::CheckFieldJsonNameUniqueness( absl::string_view existing_type = match.is_custom ? "custom" : "default"; // If the matched name differs (which it can only differ in case), include // it in the error message, for maximum clarity to user. - absl::string_view name_suffix = ""; + std::string name_suffix; if (details.orig_name != match.orig_name) { name_suffix = absl::StrCat(" (\"", match.orig_name, "\")"); } From c3e751aac6b4e1b51915c6b1dddd323f00a5b473 Mon Sep 17 00:00:00 2001 From: Mike Kruskal Date: Thu, 22 Sep 2022 11:21:39 -0700 Subject: [PATCH 55/64] Sync from Piper @475378801 PROTOBUF_SYNC_PIPER --- conformance/BUILD.bazel | 7 +- conformance/binary_json_conformance_suite.cc | 9 +- conformance/conformance_test.cc | 80 ++- conformance/conformance_test.h | 2 +- conformance/conformance_test_runner.cc | 8 +- conformance/text_format_conformance_suite.cc | 13 +- .../google/protobuf/GeneratedMessageV3.java | 2 +- .../protobuf/map_for_proto2_lite_test.proto | 3 + src/file_lists.cmake | 5 - src/google/protobuf/BUILD.bazel | 16 +- src/google/protobuf/arena.cc | 523 ++++++++++-------- src/google/protobuf/arena_impl.h | 202 ++++--- src/google/protobuf/arena_unittest.cc | 29 +- src/google/protobuf/compiler/BUILD.bazel | 3 +- .../compiler/command_line_interface.cc | 10 +- .../command_line_interface_unittest.cc | 9 +- src/google/protobuf/compiler/cpp/file.cc | 28 +- src/google/protobuf/compiler/cpp/message.cc | 71 ++- src/google/protobuf/compiler/cpp/service.cc | 2 +- .../protobuf/compiler/java/enum_field_lite.cc | 38 +- .../protobuf/compiler/java/generator.cc | 2 +- src/google/protobuf/compiler/java/helpers.cc | 4 +- .../protobuf/compiler/java/map_field_lite.cc | 2 + .../compiler/java/message_builder_lite.cc | 28 +- .../compiler/java/message_field_lite.cc | 23 +- .../protobuf/compiler/java/message_lite.cc | 63 ++- .../compiler/java/primitive_field_lite.cc | 18 +- .../compiler/java/string_field_lite.cc | 30 +- .../protobuf/compiler/python/generator.cc | 4 +- src/google/protobuf/descriptor.cc | 3 +- src/google/protobuf/descriptor_unittest.cc | 4 +- src/google/protobuf/io/BUILD.bazel | 1 + src/google/protobuf/io/printer.cc | 78 ++- src/google/protobuf/io/printer.h | 169 +++++- src/google/protobuf/io/printer_unittest.cc | 70 ++- src/google/protobuf/io/tokenizer.cc | 6 +- src/google/protobuf/map_field_test.cc | 1 + src/google/protobuf/port_def.inc | 9 + src/google/protobuf/port_undef.inc | 2 + src/google/protobuf/stubs/BUILD.bazel | 4 - src/google/protobuf/stubs/stringprintf.cc | 176 ------ src/google/protobuf/stubs/stringprintf.h | 87 --- .../protobuf/stubs/stringprintf_unittest.cc | 157 ------ src/google/protobuf/unittest.proto | 3 + .../protobuf/util/internal/proto_writer.h | 2 +- .../util/internal/protostream_objectsource.cc | 8 +- .../util/internal/protostream_objectwriter.h | 2 +- .../internal/protostream_objectwriter_test.cc | 2 +- src/google/protobuf/util/json_util.h | 2 +- .../protobuf/util/message_differencer.cc | 4 +- src/google/protobuf/util/time_util.cc | 8 +- src/google/protobuf/util/type_resolver_util.h | 6 +- src/google/protobuf/wire_format_lite.cc | 2 +- 53 files changed, 1012 insertions(+), 1028 deletions(-) delete mode 100644 src/google/protobuf/stubs/stringprintf.cc delete mode 100644 src/google/protobuf/stubs/stringprintf.h delete mode 100644 src/google/protobuf/stubs/stringprintf_unittest.cc diff --git a/conformance/BUILD.bazel b/conformance/BUILD.bazel index 0c37e159ed..5f8917db3f 100644 --- a/conformance/BUILD.bazel +++ b/conformance/BUILD.bazel @@ -143,7 +143,11 @@ cc_library( "conformance_test.h", ], includes = ["."], - deps = [":conformance_cc_proto"], + deps = [ + ":conformance_cc_proto", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:str_format", + ], ) cc_library( @@ -178,6 +182,7 @@ cc_binary( ":binary_json_conformance_suite", ":conformance_test", ":text_format_conformance_suite", + "@com_google_absl//absl/strings:str_format", ], ) diff --git a/conformance/binary_json_conformance_suite.cc b/conformance/binary_json_conformance_suite.cc index 7accca3ea3..689e8e1799 100644 --- a/conformance/binary_json_conformance_suite.cc +++ b/conformance/binary_json_conformance_suite.cc @@ -35,6 +35,7 @@ #include "google/protobuf/util/json_util.h" #include "google/protobuf/util/type_resolver_util.h" #include "absl/status/status.h" +#include "absl/strings/str_cat.h" #include "third_party/jsoncpp/json.h" #include "conformance_test.h" #include "google/protobuf/test_messages_proto2.pb.h" @@ -584,16 +585,16 @@ void BinaryAndJsonConformanceSuite::RunValidJsonTestWithValidator( if (response.result_case() != ConformanceResponse::kJsonPayload) { ReportFailure(effective_test_name, level, request, response, - "Expected JSON payload but got type %d.", - response.result_case()); + absl::StrCat("Expected JSON payload but got type ", + response.result_case())); return; } Json::Reader reader; Json::Value value; if (!reader.parse(response.json_payload(), value)) { ReportFailure(effective_test_name, level, request, response, - "JSON payload cannot be parsed as valid JSON: %s", - reader.getFormattedErrorMessages().c_str()); + absl::StrCat("JSON payload cannot be parsed as valid JSON: ", + reader.getFormattedErrorMessages())); return; } if (!validator(value)) { diff --git a/conformance/conformance_test.cc b/conformance/conformance_test.cc index 03b8a4cda1..e2a92969bd 100644 --- a/conformance/conformance_test.cc +++ b/conformance/conformance_test.cc @@ -36,12 +36,13 @@ #include #include -#include "google/protobuf/stubs/stringprintf.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "google/protobuf/util/field_comparator.h" #include "google/protobuf/util/json_util.h" #include "google/protobuf/util/message_differencer.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" #include "conformance/conformance.pb.h" using conformance::ConformanceRequest; @@ -177,10 +178,11 @@ string ConformanceTestSuite::ConformanceRequestSetting:: void ConformanceTestSuite::ReportSuccess(const string& test_name) { if (expected_to_fail_.erase(test_name) != 0) { - StringAppendF(&output_, - "ERROR: test %s is in the failure list, but test succeeded. " - "Remove it from the failure list.\n", - test_name.c_str()); + absl::StrAppendFormat( + &output_, + "ERROR: test %s is in the failure list, but test succeeded. " + "Remove it from the failure list.\n", + test_name); unexpected_succeeding_tests_.insert(test_name); } successes_++; @@ -190,33 +192,29 @@ void ConformanceTestSuite::ReportFailure(const string& test_name, ConformanceLevel level, const ConformanceRequest& request, const ConformanceResponse& response, - const char* fmt, ...) { + absl::string_view message) { if (expected_to_fail_.erase(test_name) == 1) { expected_failures_++; if (!verbose_) return; } else if (level == RECOMMENDED && !enforce_recommended_) { - StringAppendF(&output_, "WARNING, test=%s: ", test_name.c_str()); + absl::StrAppendFormat(&output_, "WARNING, test=%s: ", test_name); } else { - StringAppendF(&output_, "ERROR, test=%s: ", test_name.c_str()); + absl::StrAppendFormat(&output_, "ERROR, test=%s: ", test_name); unexpected_failing_tests_.insert(test_name); } - va_list args; - va_start(args, fmt); - StringAppendV(&output_, fmt, args); - va_end(args); - StringAppendF(&output_, " request=%s, response=%s\n", - request.ShortDebugString().c_str(), - response.ShortDebugString().c_str()); + absl::StrAppendFormat(&output_, "%s request=%s, response=%s\n", message, + request.ShortDebugString(), + response.ShortDebugString()); } void ConformanceTestSuite::ReportSkip(const string& test_name, const ConformanceRequest& request, const ConformanceResponse& response) { if (verbose_) { - StringAppendF(&output_, "SKIPPED, test=%s request=%s, response=%s\n", - test_name.c_str(), request.ShortDebugString().c_str(), - response.ShortDebugString().c_str()); + absl::StrAppendFormat( + &output_, "SKIPPED, test=%s request=%s, response=%s\n", test_name, + request.ShortDebugString(), response.ShortDebugString()); } skipped_.insert(test_name); } @@ -301,9 +299,10 @@ void ConformanceTestSuite::VerifyResponse( ReportSuccess(test_name); } } else { - ReportFailure(test_name, level, request, response, - "Output was not equivalent to reference message: %s.", - differences.c_str()); + ReportFailure( + test_name, level, request, response, + absl::StrCat("Output was not equivalent to reference message: ", + differences)); } } @@ -326,11 +325,9 @@ void ConformanceTestSuite::RunTest(const string& test_name, } if (verbose_) { - StringAppendF(&output_, - "conformance test: name=%s, request=%s, response=%s\n", - test_name.c_str(), - request.ShortDebugString().c_str(), - response->ShortDebugString().c_str()); + absl::StrAppendFormat( + &output_, "conformance test: name=%s, request=%s, response=%s\n", + test_name, request.ShortDebugString(), response->ShortDebugString()); } } @@ -341,13 +338,12 @@ bool ConformanceTestSuite::CheckSetEmpty( if (set_to_check.empty()) { return true; } else { - StringAppendF(&output_, "\n"); - StringAppendF(&output_, "%s\n\n", msg.c_str()); - for (std::set::const_iterator iter = set_to_check.begin(); - iter != set_to_check.end(); ++iter) { - StringAppendF(&output_, " %s\n", iter->c_str()); + absl::StrAppendFormat(&output_, "\n"); + absl::StrAppendFormat(&output_, "%s\n\n", msg); + for (absl::string_view v : set_to_check) { + absl::StrAppendFormat(&output_, " %s\n", v); } - StringAppendF(&output_, "\n"); + absl::StrAppendFormat(&output_, "\n"); if (!write_to_file.empty()) { std::string full_filename; @@ -362,13 +358,11 @@ bool ConformanceTestSuite::CheckSetEmpty( } std::ofstream os(*filename); if (os) { - for (std::set::const_iterator iter = set_to_check.begin(); - iter != set_to_check.end(); ++iter) { - os << *iter << "\n"; + for (absl::string_view v : set_to_check) { + os << v << "\n"; } } else { - StringAppendF(&output_, "Failed to open file: %s\n", - filename->c_str()); + absl::StrAppendFormat(&output_, "Failed to open file: %s\n", *filename); } } @@ -452,12 +446,12 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner, "features is not implemented)"); } - StringAppendF(&output_, - "CONFORMANCE SUITE %s: %d successes, %zu skipped, " - "%d expected failures, %zu unexpected failures.\n", - ok ? "PASSED" : "FAILED", successes_, skipped_.size(), - expected_failures_, unexpected_failing_tests_.size()); - StringAppendF(&output_, "\n"); + absl::StrAppendFormat(&output_, + "CONFORMANCE SUITE %s: %d successes, %zu skipped, " + "%d expected failures, %zu unexpected failures.\n", + ok ? "PASSED" : "FAILED", successes_, skipped_.size(), + expected_failures_, unexpected_failing_tests_.size()); + absl::StrAppendFormat(&output_, "\n"); output->assign(output_); diff --git a/conformance/conformance_test.h b/conformance/conformance_test.h index 5adf3f9420..f03b6d7038 100644 --- a/conformance/conformance_test.h +++ b/conformance/conformance_test.h @@ -276,7 +276,7 @@ class ConformanceTestSuite { void ReportFailure(const std::string& test_name, ConformanceLevel level, const conformance::ConformanceRequest& request, const conformance::ConformanceResponse& response, - const char* fmt, ...); + absl::string_view message); void ReportSkip(const std::string& test_name, const conformance::ConformanceRequest& request, const conformance::ConformanceResponse& response); diff --git a/conformance/conformance_test_runner.cc b/conformance/conformance_test_runner.cc index 47e91a785a..71224784ff 100644 --- a/conformance/conformance_test_runner.cc +++ b/conformance/conformance_test_runner.cc @@ -62,7 +62,7 @@ #include #include -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "conformance/conformance.pb.h" #include "conformance_test.h" @@ -165,9 +165,11 @@ void ForkPipeRunner::RunTest(const std::string &test_name, string error_msg; if (WIFEXITED(status)) { - StringAppendF(&error_msg, "child exited, status=%d", WEXITSTATUS(status)); + absl::StrAppendFormat(&error_msg, "child exited, status=%d", + WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { - StringAppendF(&error_msg, "child killed by signal %d", WTERMSIG(status)); + absl::StrAppendFormat(&error_msg, "child killed by signal %d", + WTERMSIG(status)); } GOOGLE_LOG(INFO) << error_msg; child_pid_ = -1; diff --git a/conformance/text_format_conformance_suite.cc b/conformance/text_format_conformance_suite.cc index 999f333509..958ed7b499 100644 --- a/conformance/text_format_conformance_suite.cc +++ b/conformance/text_format_conformance_suite.cc @@ -87,8 +87,7 @@ bool TextFormatConformanceTestSuite::ParseResponse( ReportFailure(test_name, level, request, response, absl::StrCat("Test was asked for ", WireFormatToString(requested_output), - " output but provided PROTOBUF instead.") - .c_str()); + " output but provided PROTOBUF instead.")); return false; } @@ -103,11 +102,11 @@ bool TextFormatConformanceTestSuite::ParseResponse( case ConformanceResponse::kTextPayload: { if (requested_output != conformance::TEXT_FORMAT) { - ReportFailure(test_name, level, request, response, - absl::StrCat("Test was asked for ", - WireFormatToString(requested_output), - " output but provided TEXT_FORMAT instead.") - .c_str()); + ReportFailure( + test_name, level, request, response, + absl::StrCat("Test was asked for ", + WireFormatToString(requested_output), + " output but provided TEXT_FORMAT instead.")); return false; } diff --git a/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java b/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java index 2b8f807951..e2b1a741b4 100644 --- a/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java +++ b/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java @@ -129,6 +129,7 @@ public abstract class GeneratedMessageV3 extends AbstractMessage implements Seri return internalGetFieldAccessorTable().descriptor; } + // TODO(gberg): remove this. Have to leave it for now to support old gencode. protected void mergeFromAndMakeImmutableInternal( CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { @@ -747,7 +748,6 @@ public abstract class GeneratedMessageV3 extends AbstractMessage implements Seri UnknownFieldSet.newBuilder(this.unknownFields).mergeFrom(unknownFields).build()); } - @Override public boolean isInitialized() { for (final FieldDescriptor field : getDescriptorForType().getFields()) { diff --git a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto index 4ec968819b..1ab94eb3b7 100644 --- a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto +++ b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto @@ -31,7 +31,10 @@ syntax = "proto2"; +package map_for_proto2_lite_test; option java_outer_classname = "MapForProto2TestProto"; +option optimize_for = LITE_RUNTIME; +option java_package = "map_lite_test"; message TestMap { message MessageValue { diff --git a/src/file_lists.cmake b/src/file_lists.cmake index 2a76933de4..a61e3f1373 100644 --- a/src/file_lists.cmake +++ b/src/file_lists.cmake @@ -65,7 +65,6 @@ set(libprotobuf_srcs ${protobuf_SOURCE_DIR}/src/google/protobuf/service.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/bytestream.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/common.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringprintf.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/structurally_valid.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/strutil.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/text_format.cc @@ -174,7 +173,6 @@ set(libprotobuf_hdrs ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/port.h ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/status_macros.h ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stl_util.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringprintf.h ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/strutil.h ${protobuf_SOURCE_DIR}/src/google/protobuf/text_format.h ${protobuf_SOURCE_DIR}/src/google/protobuf/unknown_field_set.h @@ -233,7 +231,6 @@ set(libprotobuf_lite_srcs ${protobuf_SOURCE_DIR}/src/google/protobuf/repeated_ptr_field.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/bytestream.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/common.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringprintf.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/structurally_valid.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/strutil.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format_lite.cc @@ -282,7 +279,6 @@ set(libprotobuf_lite_hdrs ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/port.h ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/status_macros.h ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stl_util.h - ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringprintf.h ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/strutil.h ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format_lite.h ) @@ -745,7 +741,6 @@ set(util_test_protos_files set(stubs_test_files ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/bytestream_unittest.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/common_unittest.cc - ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringprintf_unittest.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/structurally_valid_unittest.cc ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/strutil_unittest.cc ) diff --git a/src/google/protobuf/BUILD.bazel b/src/google/protobuf/BUILD.bazel index 8eaa0113e1..0578e6681c 100644 --- a/src/google/protobuf/BUILD.bazel +++ b/src/google/protobuf/BUILD.bazel @@ -108,7 +108,6 @@ WELL_KNOWN_TYPES = [ genrule( name = "gen_wkt_cc_sources", srcs = [wkt + ".proto" for wkt in WELL_KNOWN_TYPES], - exec_tools = ["//src/google/protobuf/compiler:protoc_nowkt"], outs = [wkt + ".pb.h" for wkt in WELL_KNOWN_TYPES] + [wkt + ".pb.cc" for wkt in WELL_KNOWN_TYPES], @@ -118,6 +117,7 @@ genrule( --proto_path=$$(dirname $$(dirname $$(dirname $(location any.proto)))) \ $(SRCS) """, + exec_tools = ["//src/google/protobuf/compiler:protoc_nowkt"], visibility = ["//visibility:private"], ) @@ -125,11 +125,11 @@ cc_library( name = "wkt_cc_proto", srcs = [wkt + ".pb.cc" for wkt in WELL_KNOWN_TYPES], hdrs = [wkt + ".pb.h" for wkt in WELL_KNOWN_TYPES], - deps = [":protobuf_nowkt"], copts = COPTS, include_prefix = "google/protobuf", linkopts = LINK_OPTS, visibility = ["//pkg:__pkg__"], + deps = [":protobuf_nowkt"], ) # Built-in runtime types @@ -313,7 +313,7 @@ cc_library( "//src/google/protobuf:__subpackages__", ], deps = [ - ":protobuf_lite", + ":protobuf_lite", "//src/google/protobuf/io", "//src/google/protobuf/io:gzip_stream", "//src/google/protobuf/io:printer", @@ -332,10 +332,6 @@ cc_library( cc_library( name = "protobuf", - deps = [ - ":protobuf_nowkt", - ":wkt_cc_proto", - ], copts = COPTS, include_prefix = "google/protobuf", linkopts = LINK_OPTS, @@ -344,6 +340,10 @@ cc_library( "//pkg:__pkg__", "//src/google/protobuf:__subpackages__", ], + deps = [ + ":protobuf_nowkt", + ":wkt_cc_proto", + ], ) # This provides just the header files for use in projects that need to build @@ -739,6 +739,7 @@ cc_test( ":protobuf", "//src/google/protobuf/compiler:importer", "//src/google/protobuf/testing", + "@com_google_absl//absl/strings:str_format", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], @@ -885,6 +886,7 @@ cc_test( ":protobuf", ":test_util", "//src/google/protobuf/stubs", + "@com_google_absl//absl/strings:str_format", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc index 4b4b19e325..6ba81f87ab 100644 --- a/src/google/protobuf/arena.cc +++ b/src/google/protobuf/arena.cc @@ -105,11 +105,42 @@ class GetDeallocator { size_t* space_allocated_; }; +constexpr ArenaBlock SerialArena::kSentryBlock; + +// It is guaranteed that this is constructed in `b`. IOW, this is not the first +// arena and `b` cannot be sentry. SerialArena::SerialArena(ArenaBlock* b, ThreadSafeArena& parent) - : parent_(parent), space_allocated_(b->size()) { + : ptr_{b->Pointer(kBlockHeaderSize + ThreadSafeArena::kSerialArenaSize)}, + limit_{b->Limit()}, + head_{b}, + space_allocated_{b->size()}, + parent_{parent} { + GOOGLE_DCHECK(!b->IsSentry()); +} + +// It is guaranteed that this is the first SerialArena. Use sentry block. +SerialArena::SerialArena(ThreadSafeArena& parent) + : head_{SentryBlock()}, parent_{parent} {} + +// It is guaranteed that this is the first SerialArena but `b` may be user +// provided or newly allocated to store AllocationPolicy. +SerialArena::SerialArena(FirstSerialArena, ArenaBlock* b, + ThreadSafeArena& parent) + : head_{b}, space_allocated_{b->size()}, parent_{parent} { + if (b->IsSentry()) return; + + set_ptr(b->Pointer(kBlockHeaderSize)); + limit_ = b->Limit(); +} + +void SerialArena::Init(ArenaBlock* b, size_t offset) { + set_ptr(b->Pointer(offset)); + limit_ = b->Limit(); set_head(b); - set_ptr(b->Pointer(kBlockHeaderSize + ThreadSafeArena::kSerialArenaSize)); - limit_ = b->Pointer(b->size() & static_cast(-8)); + space_used_.relaxed_set(0); + space_allocated_.relaxed_set(b->size()); + cached_block_length_ = 0; + cached_blocks_ = nullptr; } SerialArena* SerialArena::New(Memory mem, ThreadSafeArena& parent) { @@ -155,33 +186,36 @@ void SerialArena::AddCleanupFallback(void* elem, void (*destructor)(void*)) { } void SerialArena::AllocateNewBlock(size_t n) { - // Sync limit to block - head()->cleanup_nodes = limit_; + size_t used = 0; + size_t wasted = 0; + ArenaBlock* old_head = head(); + if (!old_head->IsSentry()) { + // Sync limit to block + old_head->cleanup_nodes = limit_; - // Record how much used in this block. - size_t used = static_cast(ptr() - head()->Pointer(kBlockHeaderSize)); - size_t wasted = head()->size() - used; - space_used_.store(space_used_.load(std::memory_order_relaxed) + used, - std::memory_order_relaxed); + // Record how much used in this block. + used = static_cast(ptr() - old_head->Pointer(kBlockHeaderSize)); + wasted = old_head->size() - used; + space_used_.relaxed_set(space_used_.relaxed_get() + used); + } // TODO(sbenza): Evaluate if pushing unused space into the cached blocks is a // win. In preliminary testing showed increased memory savings as expected, // but with a CPU regression. The regression might have been an artifact of // the microbenchmark. - auto mem = AllocateMemory(parent_.AllocPolicy(), head()->size(), n); + auto mem = AllocateMemory(parent_.AllocPolicy(), old_head->size(), n); // We don't want to emit an expensive RMW instruction that requires // exclusive access to a cacheline. Hence we write it in terms of a // regular add. - space_allocated_.store( - space_allocated_.load(std::memory_order_relaxed) + mem.size, - std::memory_order_relaxed); + space_allocated_.relaxed_set(space_allocated_.relaxed_get() + mem.size); ThreadSafeArenaStats::RecordAllocateStats(parent_.arena_stats_.MutableStats(), /*used=*/used, /*allocated=*/mem.size, wasted); - set_head(new (mem.ptr) ArenaBlock{head(), mem.size}); - set_ptr(head()->Pointer(kBlockHeaderSize)); - limit_ = head()->Pointer(head()->size()); + auto* new_head = new (mem.ptr) ArenaBlock{old_head, mem.size}; + set_head(new_head); + set_ptr(new_head->Pointer(kBlockHeaderSize)); + limit_ = new_head->Limit(); #ifdef ADDRESS_SANITIZER ASAN_POISON_MEMORY_REGION(ptr(), limit_ - ptr()); @@ -196,24 +230,26 @@ uint64_t SerialArena::SpaceUsed() const { // usage of the *current* block. // TODO(mkruskal) Consider eliminating this race in exchange for a possible // performance hit on ARM (see cl/455186837). - const uint64_t current_block_size = head()->size(); - uint64_t space_used = std::min( + const ArenaBlock* h = head(); + if (h->IsSentry()) return 0; + + const uint64_t current_block_size = h->size(); + uint64_t current_space_used = std::min( static_cast( - ptr() - const_cast(head())->Pointer(kBlockHeaderSize)), + ptr() - const_cast(h)->Pointer(kBlockHeaderSize)), current_block_size); - space_used += space_used_.load(std::memory_order_relaxed); - // Remove the overhead of the SerialArena itself. - space_used -= ThreadSafeArena::kSerialArenaSize; - return space_used; + return current_space_used + space_used_.relaxed_get(); } void SerialArena::CleanupList() { ArenaBlock* b = head(); + if (b->IsSentry()) return; + b->cleanup_nodes = limit_; do { - char* limit = reinterpret_cast( - b->Pointer(b->size() & static_cast(-8))); + char* limit = b->Limit(); char* it = reinterpret_cast(b->cleanup_nodes); + GOOGLE_DCHECK(!b->IsSentry() || it == limit); if (it < limit) { // A prefetch distance of 8 here was chosen arbitrarily. It makes the // pending nodes fill a cacheline which seemed nice. @@ -260,86 +296,79 @@ void SerialArena::CleanupList() { // Uses absl::container_internal::Layout to emulate the following: // // struct SerialArenaChunk { -// SerialArenaChunk* next_chunk; -// const uint32_t capacity; -// std::atomic size; -// std::atomic ids[]; -// std::atomic arenas[]; +// struct SerialArenaChunkHeader { +// SerialArenaChunk* next_chunk; +// uint32_t capacity; +// Atomic size; +// } header; +// Atomic ids[]; +// Atomic arenas[]; // }; // // where the size of "ids" and "arenas" is determined at runtime; hence the use // of Layout. -class ThreadSafeArena::SerialArenaChunk { - public: - explicit SerialArenaChunk(uint32_t capacity) { - set_next(nullptr); - set_capacity(capacity); - new (&size()) std::atomic{0}; +struct SerialArenaChunkHeader { + constexpr SerialArenaChunkHeader(uint32_t capacity, uint32_t size) + : next_chunk(nullptr), capacity(capacity), size(size) {} - for (unsigned i = 0; i < capacity; ++i) { - new (&id(i)) std::atomic{nullptr}; - } - - for (unsigned i = 0; i < capacity; ++i) { - new (&arena(i)) std::atomic{nullptr}; - } - } + ThreadSafeArena::SerialArenaChunk* next_chunk; + uint32_t capacity; + Atomic size; +}; +class ThreadSafeArena::SerialArenaChunk { + public: SerialArenaChunk(uint32_t capacity, void* me, SerialArena* serial) { - set_next(nullptr); - set_capacity(capacity); - new (&size()) std::atomic{1}; + new (&header()) SerialArenaChunkHeader{capacity, 1}; - new (&id(0)) std::atomic{me}; - for (unsigned i = 1; i < capacity; ++i) { - new (&id(i)) std::atomic{nullptr}; + new (&id(0)) Atomic{me}; + for (uint32_t i = 1; i < capacity; ++i) { + new (&id(i)) Atomic{nullptr}; } - new (&arena(0)) std::atomic{serial}; - for (unsigned i = 1; i < capacity; ++i) { - new (&arena(i)) std::atomic{nullptr}; + new (&arena(0)) Atomic{serial}; + for (uint32_t i = 1; i < capacity; ++i) { + new (&arena(i)) Atomic{nullptr}; } } + bool IsSentry() const { return capacity() == 0; } + // next_chunk - const SerialArenaChunk* next_chunk() const { - return *layout_type::Partial().Pointer(ptr()); - } - SerialArenaChunk* next_chunk() { - return *layout_type::Partial().Pointer(ptr()); - } + const SerialArenaChunk* next_chunk() const { return header().next_chunk; } + SerialArenaChunk* next_chunk() { return header().next_chunk; } void set_next(SerialArenaChunk* next_chunk) { - *layout_type::Partial().Pointer(ptr()) = next_chunk; + header().next_chunk = next_chunk; } // capacity - uint32_t capacity() const { - return *layout_type::Partial(1u).Pointer(ptr()); - } - void set_capacity(uint32_t capacity) { - *layout_type::Partial(1u).Pointer(ptr()) = capacity; - } + uint32_t capacity() const { return header().capacity; } + void set_capacity(uint32_t capacity) { header().capacity = capacity; } // ids: returns up to size(). - absl::Span> ids() const { + absl::Span> ids() const { return Layout(capacity()).Slice(ptr()).first(safe_size()); } - absl::Span> ids() { + absl::Span> ids() { return Layout(capacity()).Slice(ptr()).first(safe_size()); } - std::atomic& id(unsigned i) { + Atomic& id(uint32_t i) { GOOGLE_DCHECK_LT(i, capacity()); return Layout(capacity()).Pointer(ptr())[i]; } // arenas: returns up to size(). - absl::Span> arenas() const { + absl::Span> arenas() const { return Layout(capacity()).Slice(ptr()).first(safe_size()); } - absl::Span> arenas() { + absl::Span> arenas() { return Layout(capacity()).Slice(ptr()).first(safe_size()); } - std::atomic& arena(unsigned i) { + const Atomic& arena(uint32_t i) const { + GOOGLE_DCHECK_LT(i, capacity()); + return Layout(capacity()).Pointer(ptr())[i]; + } + Atomic& arena(uint32_t i) { GOOGLE_DCHECK_LT(i, capacity()); return Layout(capacity()).Pointer(ptr())[i]; } @@ -353,59 +382,68 @@ class ThreadSafeArena::SerialArenaChunk { // other paths, either race is not possible (GetSerialArenaFallback) or must // be prevented by users (CleanupList, Free). bool insert(void* me, SerialArena* serial) { - uint32_t idx = size().fetch_add(1, std::memory_order_relaxed); + uint32_t idx = size().relaxed_fetch_add(1); // Bail out if this chunk is full. if (idx >= capacity()) { // Write old value back to avoid potential overflow. - size().store(capacity(), std::memory_order_relaxed); + size().relaxed_set(capacity()); return false; } - id(idx).store(me, std::memory_order_relaxed); - arena(idx).store(serial, std::memory_order_relaxed); + id(idx).relaxed_set(me); + arena(idx).relaxed_set(serial); return true; } constexpr static size_t AllocSize(size_t n) { return Layout(n).AllocSize(); } private: - constexpr static int kNextChunk = 0; - constexpr static int kCapacity = 1; - constexpr static int kSize = 2; - constexpr static int kIds = 3; - constexpr static int kArenas = 4; + constexpr static int kHeader = 0; + constexpr static int kIds = 1; + constexpr static int kArenas = 2; - using layout_type = absl::container_internal::Layout< - SerialArenaChunk*, uint32_t, std::atomic, std::atomic, - std::atomic>; + using layout_type = + absl::container_internal::Layout, + Atomic>; const char* ptr() const { return reinterpret_cast(this); } char* ptr() { return reinterpret_cast(this); } - std::atomic& size() { - return *layout_type::Partial(1u, 1u).Pointer(ptr()); + SerialArenaChunkHeader& header() { + return *layout_type::Partial().Pointer(ptr()); } - - const std::atomic& size() const { - return *layout_type::Partial(1u, 1u).Pointer(ptr()); + const SerialArenaChunkHeader& header() const { + return *layout_type::Partial().Pointer(ptr()); } + Atomic& size() { return header().size; } + const Atomic& size() const { return header().size; } + // Returns the size capped by the capacity as fetch_add may result in a size // greater than capacity. uint32_t safe_size() const { - return std::min(capacity(), size().load(std::memory_order_relaxed)); + return std::min(capacity(), size().relaxed_get()); } constexpr static layout_type Layout(size_t n) { return layout_type( - /*next_chunk*/ 1, - /*capacity*/ 1, - /*size*/ 1, + /*header*/ 1, /*ids*/ n, /*arenas*/ n); } }; +constexpr SerialArenaChunkHeader kSentryArenaChunk = {0, 0}; + +ThreadSafeArena::SerialArenaChunk* ThreadSafeArena::SentrySerialArenaChunk() { + // const_cast is okay because the sentry chunk is never mutated. Also, + // reinterpret_cast is acceptable here as it should be identical to + // SerialArenaChunk with zero payload. This is a necessary trick to + // constexpr initialize kSentryArenaChunk. + return reinterpret_cast( + const_cast(&kSentryArenaChunk)); +} + ThreadSafeArena::CacheAlignedLifecycleIdGenerator ThreadSafeArena::lifecycle_id_generator_; @@ -427,59 +465,71 @@ PROTOBUF_THREAD_LOCAL ThreadSafeArena::ThreadCache nullptr}; #endif -void ThreadSafeArena::InitializeFrom(void* mem, size_t size) { - GOOGLE_DCHECK_EQ(reinterpret_cast(mem) & 7, 0u); - GOOGLE_DCHECK(!AllocPolicy()); // Reset should call InitializeWithPolicy instead. +ThreadSafeArena::ThreadSafeArena() : first_arena_(*this) { Init(); } + +// Constructor solely used by message-owned arena. +ThreadSafeArena::ThreadSafeArena(internal::MessageOwned) + : tag_and_id_(kMessageOwnedArena), first_arena_(*this) { + Init(); +} + +ThreadSafeArena::ThreadSafeArena(char* mem, size_t size) + : first_arena_(FirstSerialArena{}, FirstBlock(mem, size), *this) { Init(); +} + +ThreadSafeArena::ThreadSafeArena(void* mem, size_t size, + const AllocationPolicy& policy) + : first_arena_(FirstSerialArena{}, FirstBlock(mem, size, policy), *this) { + InitializeWithPolicy(policy); +} - // Ignore initial block if it is too small. - if (mem != nullptr && size >= kBlockHeaderSize + kSerialArenaSize) { +ArenaBlock* ThreadSafeArena::FirstBlock(void* buf, size_t size) { + GOOGLE_DCHECK_EQ(reinterpret_cast(buf) & 7, 0u); + if (buf == nullptr || size <= kBlockHeaderSize) { + return SerialArena::SentryBlock(); + } + // Record user-owned block. + alloc_policy_.set_is_user_owned_initial_block(true); + return new (buf) ArenaBlock{nullptr, size}; +} + +ArenaBlock* ThreadSafeArena::FirstBlock(void* buf, size_t size, + const AllocationPolicy& policy) { + if (policy.IsDefault()) return FirstBlock(buf, size); + + GOOGLE_DCHECK_EQ(reinterpret_cast(buf) & 7, 0u); + + SerialArena::Memory mem; + if (buf == nullptr || size < kBlockHeaderSize + kAllocPolicySize) { + mem = AllocateMemory(&policy, 0, kAllocPolicySize); + } else { + mem = {buf, size}; + // Record user-owned block. alloc_policy_.set_is_user_owned_initial_block(true); - SetInitialBlock(mem, size); } + + return new (mem.ptr) ArenaBlock{nullptr, mem.size}; } -void ThreadSafeArena::InitializeWithPolicy(void* mem, size_t size, - AllocationPolicy policy) { +void ThreadSafeArena::InitializeWithPolicy(const AllocationPolicy& policy) { + Init(); + + if (policy.IsDefault()) return; + #ifndef NDEBUG const uint64_t old_alloc_policy = alloc_policy_.get_raw(); // If there was a policy (e.g., in Reset()), make sure flags were preserved. #define GOOGLE_DCHECK_POLICY_FLAGS_() \ if (old_alloc_policy > 3) \ - GOOGLE_CHECK_EQ(old_alloc_policy & 3, alloc_policy_.get_raw() & 3) + GOOGLE_CHECK_EQ(old_alloc_policy & 3, alloc_policy_.get_raw() & 3) #else #define GOOGLE_DCHECK_POLICY_FLAGS_() #endif // NDEBUG - if (policy.IsDefault()) { - // Legacy code doesn't use the API above, but provides the initial block - // through ArenaOptions. I suspect most do not touch the allocation - // policy parameters. - InitializeFrom(mem, size); - GOOGLE_DCHECK_POLICY_FLAGS_(); - return; - } - GOOGLE_DCHECK_EQ(reinterpret_cast(mem) & 7, 0u); - Init(); - - // Ignore initial block if it is too small. We include an optional - // AllocationPolicy in this check, so that this can be allocated on the - // first block. - constexpr size_t kAPSize = internal::AlignUpTo8(sizeof(AllocationPolicy)); - constexpr size_t kMinimumSize = kBlockHeaderSize + kSerialArenaSize + kAPSize; - // Make sure we have an initial block to store the AllocationPolicy. - if (mem != nullptr && size >= kMinimumSize) { - alloc_policy_.set_is_user_owned_initial_block(true); - } else { - auto tmp = AllocateMemory(&policy, 0, kMinimumSize); - mem = tmp.ptr; - size = tmp.size; - } - SerialArena* sa = SetInitialBlock(mem, size); - // We ensured enough space so this cannot fail. void* p; - if (!sa || !sa->MaybeAllocateAligned(kAPSize, &p)) { + if (!first_arena_.MaybeAllocateAligned(kAllocPolicySize, &p)) { GOOGLE_LOG(FATAL) << "MaybeAllocateAligned cannot fail here."; return; } @@ -500,11 +550,10 @@ uint64_t ThreadSafeArena::GetNextLifeCycleId() { constexpr uint64_t kDelta = 2; constexpr uint64_t kInc = ThreadCache::kPerThreadIds * kDelta; if (PROTOBUF_PREDICT_FALSE((id & (kInc - 1)) == 0)) { - constexpr auto relaxed = std::memory_order_relaxed; // On platforms that don't support uint64_t atomics we can certainly not // afford to increment by large intervals and expect uniqueness due to // wrapping, hence we only add by 1. - id = lifecycle_id_generator_.id.fetch_add(1, relaxed) * kInc; + id = lifecycle_id_generator_.id.relaxed_fetch_add(1) * kInc; } tc.next_lifecycle_id = id + kDelta; return id; @@ -532,9 +581,6 @@ ThreadSafeArena::SerialArenaChunk* ThreadSafeArena::NewSerialArenaChunk( next_bytes = SerialArenaChunk::AllocSize(next_capacity); void* mem; mem = ::operator new(next_bytes); - if (serial == nullptr) { - return new (mem) SerialArenaChunk{next_capacity}; - } return new (mem) SerialArenaChunk{next_capacity, id, serial}; } @@ -542,10 +588,9 @@ ThreadSafeArena::SerialArenaChunk* ThreadSafeArena::NewSerialArenaChunk( // Tries to reserve an entry by atomic fetch_add. If the head chunk is already // full (size >= capacity), acquires the mutex and adds a new head. void ThreadSafeArena::AddSerialArena(void* id, SerialArena* serial) { - SerialArenaChunk* head = head_.load(std::memory_order_acquire); - GOOGLE_DCHECK_NE(head, nullptr); + SerialArenaChunk* head = head_.atomic_get(); // Fast path without acquiring mutex. - if (head->insert(id, serial)) { + if (!head->IsSentry() && head->insert(id, serial)) { return; } @@ -553,7 +598,7 @@ void ThreadSafeArena::AddSerialArena(void* id, SerialArena* serial) { absl::MutexLock lock(&mutex_); // Refetch and if someone else installed a new head, try allocating on that! - SerialArenaChunk* new_head = head_.load(std::memory_order_acquire); + SerialArenaChunk* new_head = head_.atomic_get(); if (new_head != head) { if (new_head->insert(id, serial)) return; // Update head to link to the latest one. @@ -565,7 +610,7 @@ void ThreadSafeArena::AddSerialArena(void* id, SerialArena* serial) { // Use "std::memory_order_release" to make sure prior stores are visible after // this one. - head_.store(new_head, std::memory_order_release); + head_.atomic_set(new_head); } void ThreadSafeArena::Init() { @@ -576,17 +621,20 @@ void ThreadSafeArena::Init() { } else { GOOGLE_DCHECK_EQ(tag_and_id_, kMessageOwnedArena); } - auto* empty_chunk = NewSerialArenaChunk(0, nullptr, nullptr); - head_.store(empty_chunk, std::memory_order_relaxed); - GOOGLE_DCHECK_EQ(message_owned, IsMessageOwned()); arena_stats_ = Sample(); -} + head_.relaxed_set(SentrySerialArenaChunk()); + GOOGLE_DCHECK_EQ(message_owned, IsMessageOwned()); + first_owner_ = &thread_cache(); -SerialArena* ThreadSafeArena::SetInitialBlock(void* mem, size_t size) { - SerialArena* serial = SerialArena::New({mem, size}, *this); - AddSerialArena(&thread_cache(), serial); - CacheSerialArena(serial); - return serial; + // Record allocation for the first block that was either user-provided or + // newly allocated. + ThreadSafeArenaStats::RecordAllocateStats( + arena_stats_.MutableStats(), + /*used=*/0, + /*allocated=*/first_arena_.SpaceAllocated(), + /*wasted=*/0); + + CacheSerialArena(&first_arena_); } ThreadSafeArena::~ThreadSafeArena() { @@ -602,27 +650,35 @@ ThreadSafeArena::~ThreadSafeArena() { ASAN_UNPOISON_MEMORY_REGION(mem.ptr, mem.size); #endif // ADDRESS_SANITIZER space_allocated += mem.size; - } else { + } else if (mem.size > 0) { GetDeallocator(alloc_policy_.get(), &space_allocated)(mem); } } SerialArena::Memory ThreadSafeArena::Free(size_t* space_allocated) { - SerialArena::Memory mem = {nullptr, 0}; auto deallocator = GetDeallocator(alloc_policy_.get(), space_allocated); - PerSerialArena([deallocator, &mem](SerialArena* a) { - if (mem.ptr) deallocator(mem); - mem = a->Free(deallocator); - }); - // Free chunks that stored SerialArena. - SerialArenaChunk* chunk = head_.load(std::memory_order_relaxed); - while (chunk != nullptr) { - SerialArenaChunk* next_chunk = chunk->next_chunk(); + + WalkSerialArenaChunk([deallocator](SerialArenaChunk* chunk) { + absl::Span> span = chunk->arenas(); + // Walks arenas backward to handle the first serial arena the last. Freeing + // in reverse-order to the order in which objects were created may not be + // necessary to Free and we should revisit this. (b/247560530) + for (auto it = span.rbegin(); it != span.rend(); ++it) { + SerialArena* serial = it->relaxed_get(); + GOOGLE_DCHECK_NE(serial, nullptr); + // Always frees the first block of "serial" as it cannot be user-provided. + SerialArena::Memory mem = serial->Free(deallocator); + GOOGLE_DCHECK_NE(mem.ptr, nullptr); + deallocator(mem); + } + + // Delete the chunk as we're done with it. internal::SizedDelete(chunk, SerialArenaChunk::AllocSize(chunk->capacity())); - chunk = next_chunk; - } - return mem; + }); + + // The first block of the first arena is special and let the caller handle it. + return first_arena_.Free(deallocator); } uint64_t ThreadSafeArena::Reset() { @@ -630,32 +686,29 @@ uint64_t ThreadSafeArena::Reset() { // refer to memory in other blocks. CleanupList(); - // Discard all blocks except the special block (if present). + // Discard all blocks except the first one. Whether it is user-provided or + // allocated, always reuse the first block for the first arena. size_t space_allocated = 0; auto mem = Free(&space_allocated); - - AllocationPolicy* policy = alloc_policy_.get(); - if (policy) { - auto saved_policy = *policy; - if (alloc_policy_.is_user_owned_initial_block()) { - space_allocated += mem.size; - } else { - GetDeallocator(alloc_policy_.get(), &space_allocated)(mem); - mem.ptr = nullptr; - mem.size = 0; - } - InitializeWithPolicy(mem.ptr, mem.size, saved_policy); + space_allocated += mem.size; + + // Reset the first arena with the first block. This avoids redundant + // free / allocation and re-allocating for AllocationPolicy. Adjust offset if + // we need to preserve alloc_policy_. + if (alloc_policy_.is_user_owned_initial_block() || + alloc_policy_.get() != nullptr) { + size_t offset = alloc_policy_.get() == nullptr + ? kBlockHeaderSize + : kBlockHeaderSize + kAllocPolicySize; + first_arena_.Init(new (mem.ptr) ArenaBlock{nullptr, mem.size}, offset); } else { - // Nullptr policy - if (alloc_policy_.is_user_owned_initial_block()) { - space_allocated += mem.size; - InitializeFrom(mem.ptr, mem.size); - } else { - GetDeallocator(alloc_policy_.get(), &space_allocated)(mem); - Init(); - } + first_arena_.Init(SerialArena::SentryBlock(), 0); } + // Since the first block and potential alloc_policy on the first block is + // preserved, this can be initialized by Init(). + Init(); + return space_allocated; } @@ -685,51 +738,62 @@ void* ThreadSafeArena::AllocateAlignedWithCleanupFallback( } template -void ThreadSafeArena::PerConstSerialArena(Functor fn) const { - const SerialArenaChunk* chunk = head_.load(std::memory_order_acquire); - - for (; chunk; chunk = chunk->next_chunk()) { - absl::Span> span = chunk->arenas(); - // Walks arenas backward to handle the first serial arena the last. This is - // necessary to special-case the initial block. - for (auto it = span.crbegin(); it != span.crend(); ++it) { - const SerialArena* serial = it->load(std::memory_order_relaxed); - // It is possible that newly added SerialArena is not updated although - // size was. This is acceptable for SpaceAllocated and SpaceUsed. - if (serial == nullptr) continue; - fn(serial); - } +void ThreadSafeArena::WalkConstSerialArenaChunk(Functor fn) const { + const SerialArenaChunk* chunk = head_.atomic_get(); + + for (; !chunk->IsSentry(); chunk = chunk->next_chunk()) { + fn(chunk); } } template -void ThreadSafeArena::PerSerialArena(Functor fn) { +void ThreadSafeArena::WalkSerialArenaChunk(Functor fn) { // By omitting an Acquire barrier we help the sanitizer that any user code // that doesn't properly synchronize Reset() or the destructor will throw a // TSAN warning. - SerialArenaChunk* chunk = head_.load(std::memory_order_relaxed); + SerialArenaChunk* chunk = head_.relaxed_get(); - for (; chunk; chunk = chunk->next_chunk()) { - absl::Span> span = chunk->arenas(); - // Walks arenas backward to handle the first serial arena the last. This is - // necessary to special-case the initial block. - for (auto it = span.rbegin(); it != span.rend(); ++it) { - SerialArena* serial = it->load(std::memory_order_relaxed); - GOOGLE_DCHECK_NE(serial, nullptr); + while (!chunk->IsSentry()) { + // Cache next chunk in case this chunk is destroyed. + SerialArenaChunk* next_chunk = chunk->next_chunk(); + fn(chunk); + chunk = next_chunk; + } +} + +template +void ThreadSafeArena::PerConstSerialArenaInChunk(Functor fn) const { + WalkConstSerialArenaChunk([&fn](const SerialArenaChunk* chunk) { + for (const auto& each : chunk->arenas()) { + const SerialArena* serial = each.relaxed_get(); + // It is possible that newly added SerialArena is not updated although + // size was. This is acceptable for SpaceAllocated and SpaceUsed. if (serial == nullptr) continue; fn(serial); } - } + }); } uint64_t ThreadSafeArena::SpaceAllocated() const { - uint64_t space_allocated = 0; - PerConstSerialArena([&space_allocated](const SerialArena* serial) { + uint64_t space_allocated = first_arena_.SpaceAllocated(); + PerConstSerialArenaInChunk([&space_allocated](const SerialArena* serial) { space_allocated += serial->SpaceAllocated(); }); return space_allocated; } +uint64_t ThreadSafeArena::SpaceUsed() const { + // First arena is inlined to ThreadSafeArena and the first block's overhead is + // smaller than others that contain SerialArena. + uint64_t space_used = first_arena_.SpaceUsed(); + PerConstSerialArenaInChunk([&space_used](const SerialArena* serial) { + // SerialArena on chunks directly allocated from the block and needs to be + // subtracted from SpaceUsed. + space_used += serial->SpaceUsed() - kSerialArenaSize; + }); + return space_used - (alloc_policy_.get() ? sizeof(AllocationPolicy) : 0); +} + template PROTOBUF_NOINLINE void* ThreadSafeArena::AllocateAlignedFallback(size_t n) { return GetSerialArenaFallback()->AllocateAligned(n); @@ -740,35 +804,42 @@ template void* ThreadSafeArena::AllocateAlignedFallback< template void* ThreadSafeArena::AllocateAlignedFallback(size_t); -uint64_t ThreadSafeArena::SpaceUsed() const { - uint64_t space_used = 0; - PerConstSerialArena([&space_used](const SerialArena* serial) { - space_used += serial->SpaceUsed(); - }); - return space_used - (alloc_policy_.get() ? sizeof(AllocationPolicy) : 0); -} - void ThreadSafeArena::CleanupList() { - PerSerialArena([](SerialArena* a) { a->CleanupList(); }); + WalkSerialArenaChunk([](SerialArenaChunk* chunk) { + absl::Span> span = chunk->arenas(); + // Walks arenas backward to handle the first serial arena the last. + // Destroying in reverse-order to the construction is often assumed by users + // and required not to break inter-object dependencies. (b/247560530) + for (auto it = span.rbegin(); it != span.rend(); ++it) { + SerialArena* serial = it->relaxed_get(); + GOOGLE_DCHECK_NE(serial, nullptr); + serial->CleanupList(); + } + }); + // First arena must be cleaned up last. (b/247560530) + first_arena_.CleanupList(); } PROTOBUF_NOINLINE SerialArena* ThreadSafeArena::GetSerialArenaFallback() { void* const id = &thread_cache(); - SerialArena* serial = nullptr; + if (id == first_owner_) { + CacheSerialArena(&first_arena_); + return &first_arena_; + } // Search matching SerialArena. - SerialArenaChunk* chunk = head_.load(std::memory_order_acquire); - for (; chunk; chunk = chunk->next_chunk()) { - absl::Span> ids = chunk->ids(); - for (unsigned i = 0; i < ids.size(); ++i) { - if (ids[i].load(std::memory_order_relaxed) == id) { - serial = chunk->arena(i).load(std::memory_order_relaxed); + SerialArena* serial = nullptr; + WalkConstSerialArenaChunk([&serial, id](const SerialArenaChunk* chunk) { + absl::Span> ids = chunk->ids(); + for (uint32_t i = 0; i < ids.size(); ++i) { + if (ids[i].relaxed_get() == id) { + serial = chunk->arena(i).relaxed_get(); GOOGLE_DCHECK_NE(serial, nullptr); break; } } - } + }); if (!serial) { // This thread doesn't have any SerialArena, which also means it doesn't diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h index b8969a52ca..43056f539f 100644 --- a/src/google/protobuf/arena_impl.h +++ b/src/google/protobuf/arena_impl.h @@ -36,6 +36,7 @@ #include #include #include +#include #include #include "google/protobuf/stubs/common.h" @@ -45,10 +46,6 @@ #include "google/protobuf/port.h" -#ifdef ADDRESS_SANITIZER -#include -#endif // ADDRESS_SANITIZER - #include "google/protobuf/arena_config.h" #include "google/protobuf/arenaz_sampler.h" @@ -90,26 +87,55 @@ inline PROTOBUF_ALWAYS_INLINE void* AlignTo(void* p, size_t a) { } } +// Wraps std::atomic to avoid accidentally accessing the atomic variable via +// a default memory order (std::memory_order_seq_cst). +template +struct Atomic { + constexpr explicit Atomic(T v) : val(v) {} + + T relaxed_get() const { return val.load(std::memory_order_relaxed); } + T relaxed_get() { return val.load(std::memory_order_relaxed); } + void relaxed_set(T v) { val.store(v, std::memory_order_relaxed); } + + T atomic_get() const { return val.load(std::memory_order_acquire); } + T atomic_get() { return val.load(std::memory_order_acquire); } + void atomic_set(T v) { val.store(v, std::memory_order_release); } + + T relaxed_fetch_add(T v) { + return val.fetch_add(v, std::memory_order_relaxed); + } + + private: + std::atomic val; +}; + // Arena blocks are variable length malloc-ed objects. The following structure // describes the common header for all blocks. struct ArenaBlock { + // For the sentry block with zero-size where ptr_, limit_, cleanup_nodes all + // point to "this". + constexpr ArenaBlock() + : next(nullptr), cleanup_nodes(this), relaxed_size(0) {} + ArenaBlock(ArenaBlock* next, size_t size) : next(next), cleanup_nodes(nullptr), relaxed_size(size) { GOOGLE_DCHECK_GT(size, sizeof(ArenaBlock)); } char* Pointer(size_t n) { - GOOGLE_DCHECK(n <= size()); + GOOGLE_DCHECK_LE(n, size()); return reinterpret_cast(this) + n; } + char* Limit() { return Pointer(size() & static_cast(-8)); } - size_t size() const { return relaxed_size.load(std::memory_order_relaxed); } + size_t size() const { return relaxed_size.relaxed_get(); } + bool IsSentry() const { return size() == 0; } ArenaBlock* const next; void* cleanup_nodes; private: - const std::atomic relaxed_size; + const Atomic relaxed_size; // data follows }; @@ -344,6 +370,11 @@ enum class AllocationClient { kDefault, kArray }; class ThreadSafeArena; +// Tag type used to invoke the constructor of the first SerialArena. +struct FirstSerialArena { + explicit FirstSerialArena() = default; +}; + // A simple arena allocator. Calls to allocate functions must be properly // serialized by the caller, hence this class cannot be used as a general // purpose allocator in a multi-threaded program. It serves as a building block @@ -363,9 +394,7 @@ class PROTOBUF_EXPORT SerialArena { }; void CleanupList(); - uint64_t SpaceAllocated() const { - return space_allocated_.load(std::memory_order_relaxed); - } + uint64_t SpaceAllocated() const { return space_allocated_.relaxed_get(); } uint64_t SpaceUsed() const; bool HasSpace(size_t n) const { @@ -384,9 +413,7 @@ class PROTOBUF_EXPORT SerialArena { if (cached_head == nullptr) return nullptr; void* ret = cached_head; -#ifdef ADDRESS_SANITIZER - ASAN_UNPOISON_MEMORY_REGION(ret, size); -#endif // ADDRESS_SANITIZER + PROTOBUF_UNPOISON_MEMORY_REGION(ret, size); cached_head = cached_head->next; return ret; } @@ -417,9 +444,7 @@ class PROTOBUF_EXPORT SerialArena { private: void* AllocateFromExisting(size_t n) { -#ifdef ADDRESS_SANITIZER - ASAN_UNPOISON_MEMORY_REGION(ptr(), n); -#endif // ADDRESS_SANITIZER + PROTOBUF_UNPOISON_MEMORY_REGION(ptr(), n); void* ret = ptr(); set_ptr(static_cast(ret) + n); return ret; @@ -451,13 +476,12 @@ class PROTOBUF_EXPORT SerialArena { std::copy(cached_blocks_, cached_blocks_ + cached_block_length_, new_list); -#ifdef ADDRESS_SANITIZER // We need to unpoison this memory before filling it in case it has been // poisoned by another santizer client. - ASAN_UNPOISON_MEMORY_REGION( + PROTOBUF_UNPOISON_MEMORY_REGION( new_list + cached_block_length_, (new_size - cached_block_length_) * sizeof(CachedBlock*)); -#endif + std::fill(new_list + cached_block_length_, new_list + new_size, nullptr); cached_blocks_ = new_list; @@ -473,9 +497,7 @@ class PROTOBUF_EXPORT SerialArena { auto* new_node = static_cast(p); new_node->next = cached_head; cached_head = new_node; -#ifdef ADDRESS_SANITIZER - ASAN_POISON_MEMORY_REGION(p, size); -#endif // ADDRESS_SANITIZER + PROTOBUF_POISON_MEMORY_REGION(p, size); } public: @@ -533,9 +555,7 @@ class PROTOBUF_EXPORT SerialArena { void* AllocateFromExistingWithCleanupFallback(size_t n, size_t align, void (*destructor)(void*)) { n = AlignUpTo(n, align); -#ifdef ADDRESS_SANITIZER - ASAN_UNPOISON_MEMORY_REGION(ptr(), n); -#endif // ADDRESS_SANITIZER + PROTOBUF_UNPOISON_MEMORY_REGION(ptr(), n); void* ret = internal::AlignTo(ptr(), align); set_ptr(ptr() + n); GOOGLE_DCHECK_GE(limit_, ptr()); @@ -548,9 +568,7 @@ class PROTOBUF_EXPORT SerialArena { cleanup::Tag tag = cleanup::Type(destructor); size_t n = cleanup::Size(tag); -#ifdef ADDRESS_SANITIZER - ASAN_UNPOISON_MEMORY_REGION(limit_ - n, n); -#endif // ADDRESS_SANITIZER + PROTOBUF_UNPOISON_MEMORY_REGION(limit_ - n, n); limit_ -= n; GOOGLE_DCHECK_GE(limit_, ptr()); cleanup::CreateNode(tag, limit_, elem, destructor); @@ -559,6 +577,13 @@ class PROTOBUF_EXPORT SerialArena { private: friend class ThreadSafeArena; + static constexpr ArenaBlock kSentryBlock = {}; + + static ArenaBlock* SentryBlock() { + // const_cast<> is okay as kSentryBlock will never be mutated. + return const_cast(&kSentryBlock); + } + // Creates a new SerialArena inside mem using the remaining memory as for // future allocations. // The `parent` arena must outlive the serial arena, which is guaranteed @@ -568,30 +593,20 @@ class PROTOBUF_EXPORT SerialArena { template Memory Free(Deallocator deallocator); - ThreadSafeArena& parent_; - std::atomic head_; // Head of linked list of blocks. - std::atomic space_used_{0}; // Necessary for metrics. - std::atomic space_allocated_; + // Members are declared here to track sizeof(SerialArena) and hotness + // centrally. They are (roughly) laid out in descending order of hotness. // Next pointer to allocate from. Always 8-byte aligned. Points inside // head_ (and head_->pos will always be non-canonical). We keep these // here to reduce indirection. - std::atomic ptr_; - - // Helper getters/setters to handle relaxed operations on atomic variables. - ArenaBlock* head() { return head_.load(std::memory_order_relaxed); } - const ArenaBlock* head() const { - return head_.load(std::memory_order_relaxed); - } - void set_head(ArenaBlock* head) { - return head_.store(head, std::memory_order_relaxed); - } - char* ptr() { return ptr_.load(std::memory_order_relaxed); } - const char* ptr() const { return ptr_.load(std::memory_order_relaxed); } - void set_ptr(char* ptr) { return ptr_.store(ptr, std::memory_order_relaxed); } - + Atomic ptr_{nullptr}; // Limiting address up to which memory can be allocated from the head block. - char* limit_; + char* limit_ = nullptr; + + Atomic head_{nullptr}; // Head of linked list of blocks. + Atomic space_used_{0}; // Necessary for metrics. + Atomic space_allocated_{0}; + ThreadSafeArena& parent_; // Repeated*Field and Arena play together to reduce memory consumption by // reusing blocks. Currently, natural growth of the repeated field types makes @@ -607,14 +622,28 @@ class PROTOBUF_EXPORT SerialArena { uint8_t cached_block_length_ = 0; CachedBlock** cached_blocks_ = nullptr; + // Helper getters/setters to handle relaxed operations on atomic variables. + ArenaBlock* head() { return head_.relaxed_get(); } + const ArenaBlock* head() const { return head_.relaxed_get(); } + void set_head(ArenaBlock* head) { return head_.relaxed_set(head); } + + char* ptr() { return ptr_.relaxed_get(); } + const char* ptr() const { return ptr_.relaxed_get(); } + void set_ptr(char* ptr) { return ptr_.relaxed_set(ptr); } + // Constructor is private as only New() should be used. inline SerialArena(ArenaBlock* b, ThreadSafeArena& parent); + // Constructors to handle the first SerialArena. + inline explicit SerialArena(ThreadSafeArena& parent); + inline SerialArena(FirstSerialArena, ArenaBlock* b, ThreadSafeArena& parent); + void* AllocateAlignedFallback(size_t n); void* AllocateAlignedWithCleanupFallback(size_t n, size_t align, void (*destructor)(void*)); void AddCleanupFallback(void* elem, void (*destructor)(void*)); - void AllocateNewBlock(size_t n); + inline void AllocateNewBlock(size_t n); + inline void Init(ArenaBlock* b, size_t offset); public: static constexpr size_t kBlockHeaderSize = AlignUpTo8(sizeof(ArenaBlock)); @@ -635,19 +664,15 @@ struct MessageOwned { // use #ifdef the select the best implementation based on hardware / OS. class PROTOBUF_EXPORT ThreadSafeArena { public: - ThreadSafeArena() { Init(); } + ThreadSafeArena(); // Constructor solely used by message-owned arena. - ThreadSafeArena(internal::MessageOwned) : tag_and_id_(kMessageOwnedArena) { - Init(); - } + explicit ThreadSafeArena(internal::MessageOwned); - ThreadSafeArena(char* mem, size_t size) { InitializeFrom(mem, size); } + ThreadSafeArena(char* mem, size_t size); explicit ThreadSafeArena(void* mem, size_t size, - const AllocationPolicy& policy) { - InitializeWithPolicy(mem, size, policy); - } + const AllocationPolicy& policy); // All protos have pointers back to the arena hence Arena must have // pointer stability. @@ -712,6 +737,7 @@ class PROTOBUF_EXPORT ThreadSafeArena { friend class ArenaBenchmark; friend class TcParser; friend class SerialArena; + friend struct SerialArenaChunkHeader; static uint64_t GetNextLifeCycleId(); class SerialArenaChunk; @@ -720,33 +746,49 @@ class PROTOBUF_EXPORT ThreadSafeArena { // grow based on "prev_num_slots". static SerialArenaChunk* NewSerialArenaChunk(uint32_t prev_capacity, void* id, SerialArena* serial); + static SerialArenaChunk* SentrySerialArenaChunk(); + + // Returns the first ArenaBlock* for the first SerialArena. If users provide + // one, use it if it's acceptable. Otherwise returns a sentry block. + ArenaBlock* FirstBlock(void* buf, size_t size); + // Same as the above but returns a valid block if "policy" is not default. + ArenaBlock* FirstBlock(void* buf, size_t size, + const AllocationPolicy& policy); // Adds SerialArena to the chunked list. May create a new chunk. void AddSerialArena(void* id, SerialArena* serial); + // Members are declared here to track sizeof(ThreadSafeArena) and hotness + // centrally. + // Unique for each arena. Changes on Reset(). uint64_t tag_and_id_ = 0; - // The LSB of tag_and_id_ indicates if the arena is message-owned. - enum : uint64_t { kMessageOwnedArena = 1 }; TaggedAllocationPolicyPtr alloc_policy_; // Tagged pointer to AllocPolicy. - - static_assert(std::is_trivially_destructible{}, - "SerialArena needs to be trivially destructible."); - // Pointer to a linked list of SerialArenaChunk. - std::atomic head_; + ThreadSafeArenaStatsHandle arena_stats_; // Adding a new chunk to head_ must be protected by mutex_. absl::Mutex mutex_; + // Pointer to a linked list of SerialArenaChunk. + Atomic head_{nullptr}; + + void* first_owner_; + // Must be declared after alloc_policy_; otherwise, it may lose info on + // user-provided initial block. + SerialArena first_arena_; + + // The LSB of tag_and_id_ indicates if the arena is message-owned. + enum : uint64_t { kMessageOwnedArena = 1 }; + + static_assert(std::is_trivially_destructible{}, + "SerialArena needs to be trivially destructible."); const AllocationPolicy* AllocPolicy() const { return alloc_policy_.get(); } - void InitializeFrom(void* mem, size_t size); - void InitializeWithPolicy(void* mem, size_t size, AllocationPolicy policy); + void InitializeWithPolicy(const AllocationPolicy& policy); void* AllocateAlignedWithCleanupFallback(size_t n, size_t align, void (*destructor)(void*)); void Init(); - SerialArena* SetInitialBlock(void* mem, size_t size); // Delete or Destruct all objects owned by the arena. void CleanupList(); @@ -776,15 +818,19 @@ class PROTOBUF_EXPORT ThreadSafeArena { template void* AllocateAlignedFallback(size_t n); - // Executes callback function over chunked list of SerialArena in reverse - // chronological order. Passes const SerialArena*. + // Executes callback function over SerialArenaChunk. Passes const + // SerialArenaChunk*. + template + void WalkConstSerialArenaChunk(Functor fn) const; + + // Executes callback function over SerialArenaChunk. template - void PerConstSerialArena(Functor fn) const; + void WalkSerialArenaChunk(Functor fn); - // Executes callback function over chunked list of SerialArena in reverse - // chronological order. + // Executes callback function over SerialArena in chunked list in reverse + // chronological order. Passes const SerialArena*. template - void PerSerialArena(Functor fn); + void PerConstSerialArenaInChunk(Functor fn) const; // Releases all memory except the first block which it returns. The first // block might be owned by the user and thus need some extra checks before @@ -826,7 +872,9 @@ class PROTOBUF_EXPORT ThreadSafeArena { #pragma warning(disable : 4324) #endif struct alignas(kCacheAlignment) CacheAlignedLifecycleIdGenerator { - std::atomic id; + constexpr CacheAlignedLifecycleIdGenerator() : id{0} {} + + Atomic id; }; static CacheAlignedLifecycleIdGenerator lifecycle_id_generator_; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) @@ -842,14 +890,14 @@ class PROTOBUF_EXPORT ThreadSafeArena { static ThreadCache& thread_cache() { return thread_cache_; } #endif - ThreadSafeArenaStatsHandle arena_stats_; - public: - // kBlockHeaderSize is sizeof(Block), aligned up to the nearest multiple of 8 - // to protect the invariant that pos is always at a multiple of 8. + // kBlockHeaderSize is sizeof(ArenaBlock), aligned up to the nearest multiple + // of 8 to protect the invariant that pos is always at a multiple of 8. static constexpr size_t kBlockHeaderSize = SerialArena::kBlockHeaderSize; static constexpr size_t kSerialArenaSize = (sizeof(SerialArena) + 7) & static_cast(-8); + static constexpr size_t kAllocPolicySize = + AlignUpTo8(sizeof(AllocationPolicy)); static_assert(kBlockHeaderSize % 8 == 0, "kBlockHeaderSize must be a multiple of 8."); static_assert(kSerialArenaSize % 8 == 0, diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc index c576a35a2f..8d76d7f205 100644 --- a/src/google/protobuf/arena_unittest.cc +++ b/src/google/protobuf/arena_unittest.cc @@ -46,6 +46,7 @@ #include #include #include "absl/strings/string_view.h" +#include "absl/synchronization/barrier.h" #include "google/protobuf/arena_test_util.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/extension_set.h" @@ -281,7 +282,8 @@ TEST(ArenaTest, CreateWithMoveArguments) { TEST(ArenaTest, InitialBlockTooSmall) { // Construct a small blocks of memory to be used by the arena allocator; then, // allocate an object which will not fit in the initial block. - for (int size = 0; size <= Arena::kBlockOverhead + 32; size++) { + for (uint32_t size = 0; size <= internal::SerialArena::kBlockHeaderSize + 32; + size++) { std::vector arena_block(size); ArenaOptions options; options.initial_block = arena_block.data(); @@ -1407,6 +1409,31 @@ TEST(ArenaTest, SpaceAllocated_and_Used) { EXPECT_EQ(1024, arena_2.Reset()); } +namespace { + +void VerifyArenaOverhead(Arena& arena, size_t overhead) { + EXPECT_EQ(0, arena.SpaceAllocated()); + + // Allocate a tiny block and record the allocation size. + constexpr size_t kTinySize = 8; + Arena::CreateArray(&arena, kTinySize); + uint64_t space_allocated = arena.SpaceAllocated(); + + // Next allocation expects to fill up the block but no new block. + uint64_t next_size = space_allocated - overhead - kTinySize; + Arena::CreateArray(&arena, next_size); + + EXPECT_EQ(space_allocated, arena.SpaceAllocated()); +} + +} // namespace + +TEST(ArenaTest, FirstArenaOverhead) { + Arena arena; + VerifyArenaOverhead(arena, internal::SerialArena::kBlockHeaderSize); +} + + TEST(ArenaTest, BlockSizeDoubling) { Arena arena; EXPECT_EQ(0, arena.SpaceUsed()); diff --git a/src/google/protobuf/compiler/BUILD.bazel b/src/google/protobuf/compiler/BUILD.bazel index 50901c3c11..baae70ed3a 100644 --- a/src/google/protobuf/compiler/BUILD.bazel +++ b/src/google/protobuf/compiler/BUILD.bazel @@ -84,6 +84,7 @@ cc_library( ":importer", "//src/google/protobuf:protobuf_nowkt", "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:str_format", ], ) @@ -126,8 +127,8 @@ cc_library( "//pkg:__pkg__", ], deps = [ - "//:protobuf", ":protoc_lib_nowkt", + "//:protobuf", ], ) diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc index dba9729834..9595520b86 100644 --- a/src/google/protobuf/compiler/command_line_interface.cc +++ b/src/google/protobuf/compiler/command_line_interface.cc @@ -76,7 +76,7 @@ #include "google/protobuf/compiler/plugin.pb.h" #include "google/protobuf/stubs/strutil.h" #include "absl/strings/match.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/strings/substitute.h" @@ -2618,7 +2618,7 @@ void GatherOccupiedFieldRanges( void FormatFreeFieldNumbers(const std::string& name, const std::set& ranges) { std::string output; - StringAppendF(&output, "%-35s free:", name.c_str()); + absl::StrAppendFormat(&output, "%-35s free:", name.c_str()); int next_free_number = 1; for (std::set::const_iterator i = ranges.begin(); i != ranges.end(); ++i) { @@ -2629,17 +2629,17 @@ void FormatFreeFieldNumbers(const std::string& name, if (next_free_number < i->first) { if (next_free_number + 1 == i->first) { // Singleton - StringAppendF(&output, " %d", next_free_number); + absl::StrAppendFormat(&output, " %d", next_free_number); } else { // Range - StringAppendF(&output, " %d-%d", next_free_number, + absl::StrAppendFormat(&output, " %d-%d", next_free_number, i->first - 1); } } next_free_number = i->second; } if (next_free_number <= FieldDescriptor::kMaxNumber) { - StringAppendF(&output, " %d-INF", next_free_number); + absl::StrAppendFormat(&output, " %d-INF", next_free_number); } std::cout << output << std::endl; } diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc index 1ac81e6a77..39bfd1c920 100644 --- a/src/google/protobuf/compiler/command_line_interface_unittest.cc +++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc @@ -38,6 +38,8 @@ #include +#include "absl/strings/str_format.h" + #ifndef _MSC_VER #include #endif @@ -45,7 +47,6 @@ #include #include -#include "google/protobuf/stubs/stringprintf.h" #include "google/protobuf/testing/file.h" #include "google/protobuf/testing/file.h" #include "google/protobuf/testing/file.h" @@ -2259,9 +2260,9 @@ TEST_F(CommandLineInterfaceTest, PluginReceivesCompilerVersion) { Run("protocol_compiler --plug_out=$tmpdir --proto_path=$tmpdir foo.proto"); - ExpectErrorSubstring(StringPrintf("Saw compiler_version: %d %s", - GOOGLE_PROTOBUF_VERSION, - GOOGLE_PROTOBUF_VERSION_SUFFIX)); + ExpectErrorSubstring(absl::StrFormat("Saw compiler_version: %d %s", + GOOGLE_PROTOBUF_VERSION, + GOOGLE_PROTOBUF_VERSION_SUFFIX)); } TEST_F(CommandLineInterfaceTest, GeneratorPluginNotFound) { diff --git a/src/google/protobuf/compiler/cpp/file.cc b/src/google/protobuf/compiler/cpp/file.cc index 729e66e240..dc07ed455a 100644 --- a/src/google/protobuf/compiler/cpp/file.cc +++ b/src/google/protobuf/compiler/cpp/file.cc @@ -41,6 +41,7 @@ #include #include #include +#include #include #include "google/protobuf/compiler/scc.h" @@ -51,7 +52,7 @@ #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" @@ -860,13 +861,13 @@ void FileGenerator::GenerateSource(io::Printer* p) { void FileGenerator::GenerateReflectionInitializationCode(io::Printer* p) { if (!message_generators_.empty()) { - p->Emit({{"len", absl::StrCat(message_generators_.size())}}, R"cc( + p->Emit({{"len", message_generators_.size()}}, R"cc( static ::_pb::Metadata $file_level_metadata$[$len$]; )cc"); } if (!enum_generators_.empty()) { - p->Emit({{"len", absl::StrCat(enum_generators_.size())}}, R"cc( + p->Emit({{"len", enum_generators_.size()}}, R"cc( static const ::_pb::EnumDescriptor* $file_level_enum_descriptors$[$len$]; )cc"); } else { @@ -877,7 +878,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* p) { } if (HasGenericServices(file_, options_) && file_->service_count() > 0) { - p->Emit({{"len", absl::StrCat(file_->service_count())}}, R"cc( + p->Emit({{"len", file_->service_count()}}, R"cc( static const ::_pb::ServiceDescriptor* $file_level_service_descriptors$[$len$]; )cc"); @@ -1015,7 +1016,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* p) { if (num_deps > 0) { p->Emit( { - {"len", absl::StrCat(num_deps)}, + {"len", num_deps}, {"deps", [&] { for (auto dep : refs.strong_reflection_files) { @@ -1046,13 +1047,13 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* p) { p->Emit( { {"eager", eager ? "true" : "false"}, - {"file_proto_len", absl::StrCat(file_data.size())}, + {"file_proto_len", file_data.size()}, {"proto_name", desc_name}, {"deps_ptr", num_deps == 0 ? "nullptr" : absl::StrCat(p->LookupVar("desc_table"), "_deps")}, - {"num_deps", absl::StrCat(num_deps)}, - {"num_msgs", absl::StrCat(message_generators_.size())}, + {"num_deps", num_deps}, + {"num_msgs", message_generators_.size()}, {"msgs_ptr", message_generators_.empty() ? "nullptr" : std::string(p->LookupVar("file_level_metadata"))}, @@ -1116,8 +1117,7 @@ class FileGenerator::ForwardDeclarations { void Print(io::Printer* p, const Options& options) const { for (const auto& e : enums_) { - auto a = p->WithAnnotations({{"enum", e.second}}); - p->Emit({{"enum", e.first}}, R"cc( + p->Emit({{"enum", e.first, e.second}}, R"cc( enum $enum$ : int; bool $enum$_IsValid(int value); )cc"); @@ -1125,10 +1125,9 @@ class FileGenerator::ForwardDeclarations { for (const auto& c : classes_) { const Descriptor* desc = c.second; - auto a = p->WithAnnotations({{"class", desc}}); p->Emit( { - {"class", c.first}, + {"class", c.first, desc}, {"default_type", DefaultInstanceType(desc, options)}, {"default_name", DefaultInstanceName(desc, options)}, }, @@ -1254,9 +1253,8 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* p) { IncludeFile("net/proto2/public/port_def.inc", p); p->Emit( { - {"min_version", - absl::StrCat(PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC)}, - {"version", absl::StrCat(PROTOBUF_VERSION)}, + {"min_version", PROTOBUF_MIN_HEADER_VERSION_FOR_PROTOC}, + {"version", PROTOBUF_VERSION}, }, R"( #if PROTOBUF_VERSION < $min_version$ diff --git a/src/google/protobuf/compiler/cpp/message.cc b/src/google/protobuf/compiler/cpp/message.cc index e779bc61a9..79d634dba9 100644 --- a/src/google/protobuf/compiler/cpp/message.cc +++ b/src/google/protobuf/compiler/cpp/message.cc @@ -53,9 +53,10 @@ #include "google/protobuf/map_entry_lite.h" #include "google/protobuf/wire_format.h" #include "google/protobuf/stubs/strutil.h" +#include "absl/container/flat_hash_map.h" #include "absl/strings/ascii.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" @@ -791,38 +792,36 @@ void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) { format.AddMap(vars); - if (field->is_repeated()) { + if (field->is_repeated()) { + format("$deprecated_attr$int ${1$$name$_size$}$() const$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); + if (!IsFieldStripped(field, options_)) { format( - "$deprecated_attr$int ${1$$name$_size$}$() const$2$\n", field, - !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); - if (!IsFieldStripped(field, options_)) { - format( - "private:\n" - "int ${1$_internal_$name$_size$}$() const;\n" - "public:\n", - field); - } - } else if (HasHasMethod(field)) { + "private:\n" + "int ${1$_internal_$name$_size$}$() const;\n" + "public:\n", + field); + } + } else if (HasHasMethod(field)) { + format("$deprecated_attr$bool ${1$has_$name$$}$() const$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); + if (!IsFieldStripped(field, options_)) { format( - "$deprecated_attr$bool ${1$has_$name$$}$() const$2$\n", field, - !IsFieldStripped(field, options_) ? ";" : " {__builtin_trap();}"); - if (!IsFieldStripped(field, options_)) { - format( - "private:\n" - "bool _internal_has_$name$() const;\n" - "public:\n"); - } - } else if (HasPrivateHasMethod(field)) { - if (!IsFieldStripped(field, options_)) { - format( - "private:\n" - "bool ${1$_internal_has_$name$$}$() const;\n" - "public:\n", - field); - } + "private:\n" + "bool _internal_has_$name$() const;\n" + "public:\n"); + } + } else if (HasPrivateHasMethod(field)) { + if (!IsFieldStripped(field, options_)) { + format( + "private:\n" + "bool ${1$_internal_has_$name$$}$() const;\n" + "public:\n", + field); } - format("$deprecated_attr$void ${1$clear_$name$$}$()$2$\n", field, - !IsFieldStripped(field, options_) ? ";" : "{__builtin_trap();}"); + } + format("$deprecated_attr$void ${1$clear_$name$$}$()$2$\n", field, + !IsFieldStripped(field, options_) ? ";" : "{__builtin_trap();}"); // Generate type-specific accessor declarations. field_generators_.get(field).GenerateAccessorDeclarations(printer); @@ -1267,9 +1266,9 @@ void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* printer) { GenerateSingularFieldHasBits(field, format); } - if (!IsCrossFileMaybeMap(field)) { - GenerateFieldClear(field, true, format); - } + if (!IsCrossFileMaybeMap(field)) { + GenerateFieldClear(field, true, format); + } // Generate type-specific accessors. if (!IsFieldStripped(field, options_)) { field_generators_.get(field).GenerateInlineAccessorDefinitions(printer); @@ -2130,8 +2129,7 @@ void MessageGenerator::GenerateClassMethods(io::Printer* printer) { format("};\n\n"); for (auto field : FieldRange(descriptor_)) { if (!IsFieldStripped(field, options_)) { - field_generators_.get(field).GenerateInternalAccessorDefinitions( - printer); + field_generators_.get(field).GenerateInternalAccessorDefinitions(printer); } } @@ -2677,8 +2675,7 @@ void MessageGenerator::GenerateConstexprConstructor(io::Printer* printer) { continue; } put_sep(); - field_generators_.get(field).GenerateConstexprAggregateInitializer( - printer); + field_generators_.get(field).GenerateConstexprAggregateInitializer(printer); } if (ShouldSplit(descriptor_, options_)) { put_sep(); diff --git a/src/google/protobuf/compiler/cpp/service.cc b/src/google/protobuf/compiler/cpp/service.cc index eae9e77512..baa58b97ce 100644 --- a/src/google/protobuf/compiler/cpp/service.cc +++ b/src/google/protobuf/compiler/cpp/service.cc @@ -138,7 +138,7 @@ void ServiceGenerator::GenerateImplementation(io::Printer* printer) { auto vars = printer->WithVars(&vars_); printer->Emit( { - {"index", absl::StrCat(index_in_metadata_)}, + {"index", index_in_metadata_}, {"no_impl_methods", [&] { GenerateNotImplementedMethods(printer); }}, {"call_method", [&] { GenerateCallMethod(printer); }}, {"get_request", [&] { GenerateGetPrototype(kRequest, printer); }}, diff --git a/src/google/protobuf/compiler/java/enum_field_lite.cc b/src/google/protobuf/compiler/java/enum_field_lite.cc index c221a33368..d6595c5b82 100644 --- a/src/google/protobuf/compiler/java/enum_field_lite.cc +++ b/src/google/protobuf/compiler/java/enum_field_lite.cc @@ -137,6 +137,9 @@ void SetEnumVariables(const FieldDescriptor* descriptor, int messageBitIndex, // We use `x.getClass()` as a null check because it generates less bytecode // than an `if (x == null) { throw ... }` statement. (*variables)["null_check"] = "value.getClass();\n"; + // Calls to Annotate() use variable ranges to know which text to annotate. + (*variables)["{"] = ""; + (*variables)["}"] = ""; } } // namespace @@ -165,15 +168,19 @@ void ImmutableEnumFieldLiteGenerator::GenerateInterfaceMembers( if (HasHazzer(descriptor_)) { WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + "$deprecation$boolean ${$has$capitalized_name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); } if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldEnumValueAccessorDocComment(printer, descriptor_, GETTER); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value();\n"); + "$deprecation$int ${$get$capitalized_name$Value$}$();\n"); + printer->Annotate("{", "}", descriptor_); } WriteFieldAccessorDocComment(printer, descriptor_, GETTER); - printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, + "$deprecation$$type$ ${$get$capitalized_name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); } void ImmutableEnumFieldLiteGenerator::GenerateMembers( @@ -550,24 +557,31 @@ int RepeatedImmutableEnumFieldLiteGenerator::GetNumBitsForMessage() const { void RepeatedImmutableEnumFieldLiteGenerator::GenerateInterfaceMembers( io::Printer* printer) const { WriteFieldAccessorDocComment(printer, descriptor_, LIST_GETTER); - printer->Print( - variables_, - "$deprecation$java.util.List<$type$> get$capitalized_name$List();\n"); + printer->Print(variables_, + "$deprecation$java.util.List<$type$> " + "${$get$capitalized_name$List$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldAccessorDocComment(printer, descriptor_, LIST_COUNT); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); + "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldAccessorDocComment(printer, descriptor_, LIST_INDEXED_GETTER); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); + printer->Print( + variables_, + "$deprecation$$type$ ${$get$capitalized_name$$}$(int index);\n"); + printer->Annotate("{", "}", descriptor_); if (SupportUnknownEnumValue(descriptor_->file())) { WriteFieldEnumValueAccessorDocComment(printer, descriptor_, LIST_GETTER); printer->Print(variables_, "$deprecation$java.util.List\n" - "get$capitalized_name$ValueList();\n"); + "${$get$capitalized_name$ValueList$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldEnumValueAccessorDocComment(printer, descriptor_, LIST_INDEXED_GETTER); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value(int index);\n"); + printer->Print( + variables_, + "$deprecation$int ${$get$capitalized_name$Value$}$(int index);\n"); + printer->Annotate("{", "}", descriptor_); } } diff --git a/src/google/protobuf/compiler/java/generator.cc b/src/google/protobuf/compiler/java/generator.cc index 52bca03ea9..2f345efdf5 100644 --- a/src/google/protobuf/compiler/java/generator.cc +++ b/src/google/protobuf/compiler/java/generator.cc @@ -39,7 +39,7 @@ #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "google/protobuf/compiler/java/file.h" #include "google/protobuf/compiler/java/generator_factory.h" #include "google/protobuf/compiler/java/helpers.h" diff --git a/src/google/protobuf/compiler/java/helpers.cc b/src/google/protobuf/compiler/java/helpers.cc index 680a750766..2fe7a0a4a4 100644 --- a/src/google/protobuf/compiler/java/helpers.cc +++ b/src/google/protobuf/compiler/java/helpers.cc @@ -45,7 +45,7 @@ #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" @@ -1114,7 +1114,7 @@ void EscapeUtf16ToString(uint16_t code, std::string* output) { } else if (code >= 0x20 && code <= 0x7f) { output->push_back(static_cast(code)); } else { - output->append(StringPrintf("\\u%04x", code)); + output->append(absl::StrFormat("\\u%04x", code)); } } diff --git a/src/google/protobuf/compiler/java/map_field_lite.cc b/src/google/protobuf/compiler/java/map_field_lite.cc index 471bbdaab9..22bc306586 100644 --- a/src/google/protobuf/compiler/java/map_field_lite.cc +++ b/src/google/protobuf/compiler/java/map_field_lite.cc @@ -178,6 +178,8 @@ void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex, (*variables)["default_entry"] = (*variables)["capitalized_name"] + "DefaultEntryHolder.defaultEntry"; + // { and } variables are used as delimiters when emitting annotations. + (*variables)["{"] = (*variables)["}"] = ""; } } // namespace diff --git a/src/google/protobuf/compiler/java/message_builder_lite.cc b/src/google/protobuf/compiler/java/message_builder_lite.cc index c444794c9e..adff67eb33 100644 --- a/src/google/protobuf/compiler/java/message_builder_lite.cc +++ b/src/google/protobuf/compiler/java/message_builder_lite.cc @@ -37,6 +37,7 @@ #include #include #include +#include #include #include "google/protobuf/io/coded_stream.h" @@ -82,21 +83,27 @@ MessageBuilderLiteGenerator::~MessageBuilderLiteGenerator() {} void MessageBuilderLiteGenerator::Generate(io::Printer* printer) { WriteMessageDocComment(printer, descriptor_); + std::map vars = { + {"{", ""}, + {"}", ""}, + {"classname", name_resolver_->GetImmutableClassName(descriptor_)}, + {"extra_interfaces", ExtraBuilderInterfaces(descriptor_)}, + {"extendible", + descriptor_->extension_range_count() > 0 ? "Extendable" : ""}, + }; printer->Print( - "public static final class Builder extends\n" + vars, + "public static final class ${$Builder$}$ extends\n" " com.google.protobuf.GeneratedMessageLite.$extendible$Builder<\n" " $classname$, Builder> implements\n" " $extra_interfaces$\n" - " $classname$OrBuilder {\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "extra_interfaces", ExtraBuilderInterfaces(descriptor_), "extendible", - descriptor_->extension_range_count() > 0 ? "Extendable" : ""); + " $classname$OrBuilder {\n"); + printer->Annotate("{", "}", descriptor_); printer->Indent(); GenerateCommonBuilderMethods(printer); // oneof - std::map vars; for (auto oneof : oneofs_) { vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name; vars["oneof_capitalized_name"] = @@ -107,16 +114,19 @@ void MessageBuilderLiteGenerator::Generate(io::Printer* printer) { printer->Print(vars, "@java.lang.Override\n" "public $oneof_capitalized_name$Case\n" - " get$oneof_capitalized_name$Case() {\n" + " ${$get$oneof_capitalized_name$Case$}$() {\n" " return instance.get$oneof_capitalized_name$Case();\n" - "}\n" + "}\n"); + printer->Annotate("{", "}", oneof); + printer->Print(vars, "\n" - "public Builder clear$oneof_capitalized_name$() {\n" + "public Builder ${$clear$oneof_capitalized_name$$}$() {\n" " copyOnWrite();\n" " instance.clear$oneof_capitalized_name$();\n" " return this;\n" "}\n" "\n"); + printer->Annotate("{", "}", oneof); } for (int i = 0; i < descriptor_->field_count(); i++) { diff --git a/src/google/protobuf/compiler/java/message_field_lite.cc b/src/google/protobuf/compiler/java/message_field_lite.cc index 5a05939c95..bc7c99f5e1 100644 --- a/src/google/protobuf/compiler/java/message_field_lite.cc +++ b/src/google/protobuf/compiler/java/message_field_lite.cc @@ -110,6 +110,9 @@ void SetMessageVariables(const FieldDescriptor* descriptor, int messageBitIndex, // We use `x.getClass()` as a null check because it generates less bytecode // than an `if (x == null) { throw ... }` statement. (*variables)["null_check"] = "value.getClass();\n"; + // Annotations often use { and } to determine ranges. + (*variables)["{"] = ""; + (*variables)["}"] = ""; } } // namespace @@ -140,9 +143,13 @@ int ImmutableMessageFieldLiteGenerator::GetNumBitsForMessage() const { void ImmutableMessageFieldLiteGenerator::GenerateInterfaceMembers( io::Printer* printer) const { WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); - printer->Print(variables_, "$deprecation$boolean has$capitalized_name$();\n"); + printer->Print(variables_, + "$deprecation$boolean ${$has$capitalized_name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldAccessorDocComment(printer, descriptor_, GETTER); - printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, + "$deprecation$$type$ ${$get$capitalized_name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); } void ImmutableMessageFieldLiteGenerator::GenerateMembers( @@ -523,13 +530,17 @@ void RepeatedImmutableMessageFieldLiteGenerator::GenerateInterfaceMembers( WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$java.util.List<$type$> \n" - " get$capitalized_name$List();\n"); + " ${$get$capitalized_name$List$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); + printer->Print( + variables_, + "$deprecation$$type$ ${$get$capitalized_name$$}$(int index);\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); + "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); + printer->Annotate("{", "}", descriptor_); } void RepeatedImmutableMessageFieldLiteGenerator::GenerateMembers( diff --git a/src/google/protobuf/compiler/java/message_lite.cc b/src/google/protobuf/compiler/java/message_lite.cc index 504e072bee..fc44cb172d 100644 --- a/src/google/protobuf/compiler/java/message_lite.cc +++ b/src/google/protobuf/compiler/java/message_lite.cc @@ -38,6 +38,7 @@ #include #include #include +#include #include #include "google/protobuf/io/coded_stream.h" @@ -117,29 +118,32 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) { MaybePrintGeneratedAnnotation(context_, printer, descriptor_, /* immutable = */ true, "OrBuilder"); + std::map variables = { + {"{", ""}, + {"}", ""}, + {"deprecation", + descriptor_->options().deprecated() ? "@java.lang.Deprecated " : ""}, + {"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_)}, + {"classname", descriptor_->name()}, + }; + if (!context_->options().opensource_runtime) { printer->Print("@com.google.protobuf.Internal.ProtoNonnullApi\n"); } if (descriptor_->extension_range_count() > 0) { printer->Print( + variables, "$deprecation$public interface ${$$classname$OrBuilder$}$ extends \n" " $extra_interfaces$\n" " com.google.protobuf.GeneratedMessageLite.\n" " ExtendableMessageOrBuilder<\n" - " $classname$, $classname$.Builder> {\n", - "deprecation", - descriptor_->options().deprecated() ? "@java.lang.Deprecated " : "", - "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name(), "{", "", "}", ""); + " $classname$, $classname$.Builder> {\n"); } else { printer->Print( + variables, "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n" " $extra_interfaces$\n" - " com.google.protobuf.MessageLiteOrBuilder {\n", - "deprecation", - descriptor_->options().deprecated() ? "@java.lang.Deprecated " : "", - "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name(), "{", "", "}", ""); + " com.google.protobuf.MessageLiteOrBuilder {\n"); } printer->Annotate("{", "}", descriptor_); @@ -150,13 +154,15 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) { .GenerateInterfaceMembers(printer); } for (auto oneof : oneofs_) { - printer->Print( - "\n" - "public $classname$.$oneof_capitalized_name$Case " - "get$oneof_capitalized_name$Case();\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo(oneof)->capitalized_name, "classname", - context_->GetNameResolver()->GetImmutableClassName(descriptor_)); + variables["oneof_capitalized_name"] = + context_->GetOneofGeneratorInfo(oneof)->capitalized_name; + variables["classname"] = + context_->GetNameResolver()->GetImmutableClassName(descriptor_); + printer->Print(variables, + "\n" + "public ${$$classname$.$oneof_capitalized_name$Case$}$ " + "get$oneof_capitalized_name$Case();\n"); + printer->Annotate("{", "}", oneof); } printer->Outdent(); @@ -168,7 +174,7 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) { void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true); - std::map variables; + std::map variables = {{"{", ""}, {"}", ""}}; variables["static"] = is_own_file ? " " : " static "; variables["classname"] = descriptor_->name(); variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_); @@ -185,7 +191,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { if (descriptor_->extension_range_count() > 0) { printer->Print( variables, - "$deprecation$public $static$final class $classname$ extends\n" + "$deprecation$public $static$final class ${$$classname$$}$ extends\n" " com.google.protobuf.GeneratedMessageLite.ExtendableMessage<\n" " $classname$, $classname$.Builder> implements\n" " $extra_interfaces$\n" @@ -196,7 +202,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { } else { printer->Print( variables, - "$deprecation$public $static$final class $classname$ extends\n" + "$deprecation$public $static$final class ${$$classname$$}$ extends\n" " com.google.protobuf.GeneratedMessageLite<\n" " $classname$, $classname$.Builder> implements\n" " $extra_interfaces$\n" @@ -204,6 +210,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { builder_type = "com.google.protobuf.GeneratedMessageLite.Builder"; } + printer->Annotate("{", "}", descriptor_); printer->Indent(); GenerateConstructor(printer); @@ -236,7 +243,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { } // oneof - std::map vars; + std::map vars = {{"{", ""}, {"}", ""}}; for (auto oneof : oneofs_) { vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name; vars["oneof_capitalized_name"] = @@ -249,13 +256,15 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { "private java.lang.Object $oneof_name$_;\n"); } // OneofCase enum - printer->Print(vars, "public enum $oneof_capitalized_name$Case {\n"); + printer->Print(vars, "public enum ${$$oneof_capitalized_name$Case$}$ {\n"); + printer->Annotate("{", "}", oneof); printer->Indent(); for (int j = 0; j < (oneof)->field_count(); j++) { const FieldDescriptor* field = (oneof)->field(j); printer->Print("$field_name$($field_number$),\n", "field_name", absl::AsciiStrToUpper(field->name()), "field_number", absl::StrCat(field->number())); + printer->Annotate("field_name", field); } printer->Print("$cap_oneof_name$_NOT_SET(0);\n", "cap_oneof_name", absl::AsciiStrToUpper(vars["oneof_name"])); @@ -303,16 +312,19 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Print(vars, "@java.lang.Override\n" "public $oneof_capitalized_name$Case\n" - "get$oneof_capitalized_name$Case() {\n" + "${$get$oneof_capitalized_name$Case$}$() {\n" " return $oneof_capitalized_name$Case.forNumber(\n" " $oneof_name$Case_);\n" - "}\n" + "}\n"); + printer->Annotate("{", "}", oneof); + printer->Print(vars, "\n" - "private void clear$oneof_capitalized_name$() {\n" + "private void ${$clear$oneof_capitalized_name$$}$() {\n" " $oneof_name$Case_ = 0;\n" " $oneof_name$_ = null;\n" "}\n" "\n"); + printer->Annotate("{", "}", oneof); } // Fields @@ -320,6 +332,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { printer->Print("public static final int $constant_name$ = $number$;\n", "constant_name", FieldConstantName(descriptor_->field(i)), "number", absl::StrCat(descriptor_->field(i)->number())); + printer->Annotate("constant_name", descriptor_->field(i)); field_generators_.get(descriptor_->field(i)).GenerateMembers(printer); printer->Print("\n"); } diff --git a/src/google/protobuf/compiler/java/primitive_field_lite.cc b/src/google/protobuf/compiler/java/primitive_field_lite.cc index b7ff8912c3..6db3a8c657 100644 --- a/src/google/protobuf/compiler/java/primitive_field_lite.cc +++ b/src/google/protobuf/compiler/java/primitive_field_lite.cc @@ -193,6 +193,8 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, GenerateGetBitFromLocal(builderBitIndex); (*variables)["set_has_field_bit_to_local"] = GenerateSetBitToLocal(messageBitIndex); + // Annotations often use { and } variables to denote ranges. + (*variables)["{"] = (*variables)["}"] = ""; } } // namespace @@ -224,7 +226,9 @@ void ImmutablePrimitiveFieldLiteGenerator::GenerateInterfaceMembers( "$deprecation$boolean has$capitalized_name$();\n"); } WriteFieldAccessorDocComment(printer, descriptor_, GETTER); - printer->Print(variables_, "$deprecation$$type$ get$capitalized_name$();\n"); + printer->Print(variables_, + "$deprecation$$type$ ${$get$capitalized_name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); } void ImmutablePrimitiveFieldLiteGenerator::GenerateMembers( @@ -527,13 +531,17 @@ void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateInterfaceMembers( WriteFieldAccessorDocComment(printer, descriptor_, LIST_GETTER); printer->Print(variables_, "$deprecation$java.util.List<$boxed_type$> " - "get$capitalized_name$List();\n"); + "${$get$capitalized_name$List$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldAccessorDocComment(printer, descriptor_, LIST_COUNT); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); + "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldAccessorDocComment(printer, descriptor_, LIST_INDEXED_GETTER); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); + printer->Print( + variables_, + "$deprecation$$type$ ${$get$capitalized_name$$}$(int index);\n"); + printer->Annotate("{", "}", descriptor_); } void RepeatedImmutablePrimitiveFieldLiteGenerator::GenerateMembers( diff --git a/src/google/protobuf/compiler/java/string_field_lite.cc b/src/google/protobuf/compiler/java/string_field_lite.cc index 73e849917a..13fb9296e6 100644 --- a/src/google/protobuf/compiler/java/string_field_lite.cc +++ b/src/google/protobuf/compiler/java/string_field_lite.cc @@ -129,6 +129,8 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor, GenerateGetBitFromLocal(builderBitIndex); (*variables)["set_has_field_bit_to_local"] = GenerateSetBitToLocal(messageBitIndex); + // Annotations often use { and } variables to denote text ranges. + (*variables)["{"] = (*variables)["}"] = ""; } } // namespace @@ -182,15 +184,19 @@ void ImmutableStringFieldLiteGenerator::GenerateInterfaceMembers( if (HasHazzer(descriptor_)) { WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); + "$deprecation$boolean ${$has$capitalized_name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); } WriteFieldAccessorDocComment(printer, descriptor_, GETTER); - printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$();\n"); + printer->Print( + variables_, + "$deprecation$java.lang.String ${$get$capitalized_name$$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldStringBytesAccessorDocComment(printer, descriptor_, GETTER); printer->Print(variables_, "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes();\n"); + " ${$get$capitalized_name$Bytes$}$();\n"); + printer->Annotate("{", "}", descriptor_); } void ImmutableStringFieldLiteGenerator::GenerateMembers( @@ -569,18 +575,22 @@ void RepeatedImmutableStringFieldLiteGenerator::GenerateInterfaceMembers( WriteFieldAccessorDocComment(printer, descriptor_, LIST_GETTER); printer->Print(variables_, "$deprecation$java.util.List\n" - " get$capitalized_name$List();\n"); + " ${$get$capitalized_name$List$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldAccessorDocComment(printer, descriptor_, LIST_COUNT); printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); + "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldAccessorDocComment(printer, descriptor_, LIST_INDEXED_GETTER); - printer->Print( - variables_, - "$deprecation$java.lang.String get$capitalized_name$(int index);\n"); + printer->Print(variables_, + "$deprecation$java.lang.String " + "${$get$capitalized_name$$}$(int index);\n"); + printer->Annotate("{", "}", descriptor_); WriteFieldAccessorDocComment(printer, descriptor_, LIST_INDEXED_GETTER); printer->Print(variables_, "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes(int index);\n"); + " ${$get$capitalized_name$Bytes$}$(int index);\n"); + printer->Annotate("{", "}", descriptor_); } void RepeatedImmutableStringFieldLiteGenerator::GenerateMembers( diff --git a/src/google/protobuf/compiler/python/generator.cc b/src/google/protobuf/compiler/python/generator.cc index deb5b09f94..1ff2497ccc 100644 --- a/src/google/protobuf/compiler/python/generator.cc +++ b/src/google/protobuf/compiler/python/generator.cc @@ -58,7 +58,7 @@ #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/strip.h" #include "absl/strings/substitute.h" @@ -1345,7 +1345,7 @@ void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const { OptionsValue(value_descriptor.options().SerializeAsString()); if (value_options != "None") { PrintDescriptorOptionsFixingCode( - StringPrintf("%s.values_by_name[\"%s\"]", descriptor_name.c_str(), + absl::StrFormat("%s.values_by_name[\"%s\"]", descriptor_name.c_str(), value_descriptor.name().c_str()), value_options, printer_); } diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 3a089e3e94..0f3c6326bf 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -59,7 +59,6 @@ #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" -#include "google/protobuf/stubs/stringprintf.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/substitute.h" @@ -1634,7 +1633,7 @@ FileDescriptorTables::FindEnumValueByNumberCreatingIfUnknown( // EnumDescriptor (it's not a part of the enum as originally defined), but // we do insert it into the table so that we can return the same pointer // later. - std::string enum_value_name = StringPrintf( + std::string enum_value_name = absl::StrFormat( "UNKNOWN_ENUM_VALUE_%s_%d", parent->name().c_str(), number); auto* pool = DescriptorPool::generated_pool(); auto* tables = const_cast(pool->tables_.get()); diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index aa02305a0e..54ab6fbd65 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc @@ -44,9 +44,9 @@ #include "google/protobuf/unittest.pb.h" #include "google/protobuf/unittest_custom_options.pb.h" #include "google/protobuf/descriptor.pb.h" +#include "absl/strings/str_format.h" #include "google/protobuf/stubs/common.h" #include "google/protobuf/stubs/logging.h" -#include "google/protobuf/stubs/stringprintf.h" #include "google/protobuf/unittest_lazy_dependencies.pb.h" #include "google/protobuf/unittest_proto3_arena.pb.h" #include "google/protobuf/io/tokenizer.h" @@ -591,7 +591,7 @@ class SimpleErrorCollector : public io::ErrorCollector { public: // implements ErrorCollector --------------------------------------- void AddError(int line, int column, const std::string& message) override { - last_error_ = StringPrintf("%d:%d:", line, column) + message; + last_error_ = absl::StrFormat("%d:%d:%s", line, column, message); } const std::string& last_error() { return last_error_; } diff --git a/src/google/protobuf/io/BUILD.bazel b/src/google/protobuf/io/BUILD.bazel index f53c612918..cce62964fd 100644 --- a/src/google/protobuf/io/BUILD.bazel +++ b/src/google/protobuf/io/BUILD.bazel @@ -144,6 +144,7 @@ cc_test( "//src/google/protobuf/testing", "@com_google_absl//absl/container:flat_hash_map", "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:str_format", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], diff --git a/src/google/protobuf/io/printer.cc b/src/google/protobuf/io/printer.cc index 99dc5bd778..4ea62d3789 100644 --- a/src/google/protobuf/io/printer.cc +++ b/src/google/protobuf/io/printer.cc @@ -46,11 +46,12 @@ #include "google/protobuf/stubs/logging.h" #include "google/protobuf/stubs/common.h" +#include "absl/container/flat_hash_map.h" #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/types/optional.h" @@ -61,9 +62,8 @@ namespace google { namespace protobuf { namespace io { namespace { -// Returns the number of spaces stripped. -size_t ConsumeInitialRawStringIndent(absl::string_view& format) { - size_t len = 0; +// Returns the number of spaces of the first non empty line. +size_t RawStringIndentLen(absl::string_view format) { // We are processing a call that looks like // // p->Emit(R"cc( @@ -72,10 +72,19 @@ size_t ConsumeInitialRawStringIndent(absl::string_view& format) { // }; // )cc"); // - // We need to discard all leading newlines, then consume all spaces until - // we reach a non-space; this run of spaces is stripped off at the start of - // each line. - + // or + // + // p->Emit(R"cc( + // + // class Foo { + // int x, y, z; + // }; + // )cc"); + // + // To compute the indent, we need to discard all leading newlines, then + // count all spaces until we reach a non-space; this run of spaces is + // stripped off at the start of each line. + size_t len = 0; while (absl::ConsumePrefix(&format, "\n")) { } @@ -169,41 +178,17 @@ void Printer::Outdent() { } void Printer::Emit( - std::initializer_list>>> + std::initializer_list< + VarDefinition> vars, absl::string_view format, SourceLocation loc) { PrintOptions opts; opts.strip_raw_string_indentation = true; opts.loc = loc; - absl::flat_hash_map>> - map; - map.reserve(vars.size()); - for (auto& var : vars) { - auto result = map.insert(var); - GOOGLE_CHECK(result.second) << "repeated variable in Emit() call: \"" << var.first - << "\""; - } - - var_lookups_.emplace_back([&map](absl::string_view var) -> LookupResult { - auto it = map.find(var); - if (it == map.end()) { - return absl::nullopt; - } - if (auto* str = absl::get_if(&it->second)) { - return *str; - } - - auto* f = absl::get_if>(&it->second); - GOOGLE_CHECK(f != nullptr); - return *f; - }); + auto defs = WithDefs(vars); PrintImpl(format, {}, opts); - - var_lookups_.pop_back(); } absl::optional> Printer::GetSubstitutionRange( @@ -305,7 +290,7 @@ void Printer::PrintCodegenTrace(absl::optional loc) { sink_.Write("\n"); } - PrintRaw(StringPrintf("%s @%s:%d\n", options_.comment_start, + PrintRaw(absl::StrFormat("%s @%s:%d\n", options_.comment_start, loc->file_name(), loc->line())); at_start_of_line_ = true; } @@ -314,7 +299,7 @@ bool Printer::ValidateIndexLookupInBounds(size_t index, size_t current_arg_index, size_t args_len, PrintOptions opts) { if (!Validate(index < args_len, opts, [this, index] { - return StringPrintf("annotation %c{%d%c is out of bounds", + return absl::StrFormat("annotation %c{%d%c is out of bounds", options_.variable_delimiter, index + 1, options_.variable_delimiter); })) { @@ -322,7 +307,7 @@ bool Printer::ValidateIndexLookupInBounds(size_t index, } if (!Validate( index <= current_arg_index, opts, [this, index, current_arg_index] { - return StringPrintf( + return absl::StrFormat( "annotation arg must be in correct order as given; expected " "%c{%d%c but got %c{%d%c", options_.variable_delimiter, current_arg_index + 1, @@ -352,9 +337,16 @@ void Printer::PrintImpl(absl::string_view format, substitutions_.clear(); } - size_t raw_string_indent_len = opts.strip_raw_string_indentation - ? ConsumeInitialRawStringIndent(format) - : 0; + size_t raw_string_indent_len = + opts.strip_raw_string_indentation ? RawStringIndentLen(format) : 0; + + if (opts.strip_raw_string_indentation) { + // We only want to remove a single newline from the input string to allow + // extra newlines at the start to go into the generated code. + absl::ConsumePrefix(&format, "\n"); + while (absl::ConsumePrefix(&format, " ")) { + } + } PrintCodegenTrace(opts.loc); @@ -534,7 +526,7 @@ void Printer::PrintImpl(absl::string_view format, annot_records.pop_back(); if (!Validate(record_var.first == var, opts, [record_var, var] { - return StringPrintf( + return absl::StrFormat( "_start and _end variables must match, but got %s and %s, " "respectively", record_var.first, var); @@ -659,7 +651,7 @@ void Printer::PrintImpl(absl::string_view format, Validate(arg_index == args.size(), opts, [original] { return absl::StrCat("unused args: ", original); }); Validate(annot_stack.empty(), opts, [this, original] { - return StringPrintf( + return absl::StrFormat( "annotation range was not closed; expected %c}%c: %s", options_.variable_delimiter, options_.variable_delimiter, original); }); diff --git a/src/google/protobuf/io/printer.h b/src/google/protobuf/io/printer.h index 176f484f8e..fb41ef0a9a 100644 --- a/src/google/protobuf/io/printer.h +++ b/src/google/protobuf/io/printer.h @@ -46,15 +46,16 @@ #include #include +#include "google/protobuf/stubs/logging.h" +#include "google/protobuf/stubs/common.h" #include "absl/cleanup/cleanup.h" #include "absl/container/flat_hash_map.h" #include "absl/functional/function_ref.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "absl/types/variant.h" #include "google/protobuf/io/zero_copy_sink.h" -#include "google/protobuf/port.h" // Must be included last. @@ -163,6 +164,10 @@ class AnnotationProtoCollector : public AnnotationCollector { // "Thing", rather than " Thing". This helps minimize awkward whitespace in the // output. // +// The value may be any type that can be stringified with `absl::StrCat`: +// +// p.Emit({{"num", 5}}, "x = $num$;"); +// // If a variable is referenced in the format string that is missing, the program // will crash. Callers must statically know that every variable reference is // valid, and MUST NOT pass user-provided strings directly into Emit(). @@ -255,6 +260,19 @@ class AnnotationProtoCollector : public AnnotationCollector { // The span corresponding to whatever $class_name$ expands to will be annotated // as having come from message_descriptor. // +// For convenience, this can be done with a single WithVars(), using the special +// three-argument form: +// +// auto v = p.WithVars({{"class_name", my_class_name, message_descriptor}}); +// p.Emit(R"cc( +// class $class_name$ { +// public: +// $class_name$(int x); +// // Etc. +// }; +// )cc"); +// +// // Alternatively, a range may be given explicitly: // // auto a = p.WithAnnotations({{"my_desc", message_descriptor}}); @@ -267,11 +285,11 @@ class AnnotationProtoCollector : public AnnotationCollector { // )cc"); // // The special $_start$ and $_end$ variables indicate the start and end of an -// annotated span, which is annotated with the variable that follows. +// annotated span, which is annotated with the variable that follows. This +// form can produce somewhat unreadable format strings and is not recommended. // // Note that whitespace after a $_start$ and before an $_end$ is not printed. // -// // # Indentation // // Printer tracks an indentation amount to add to each new line, independent @@ -407,6 +425,60 @@ class PROTOBUF_EXPORT Printer { } }; + // Sink type for constructing values to pass to WithVars() and Emit(). + template + struct VarDefinition { + using StringOrCallback = absl::variant>; + + template + VarDefinition(Key&& key, Value&& value) + : key(std::forward(key)), + value(ToStringOrCallback(std::forward(value), Rank2{})), + annotation(absl::nullopt) {} + + // NOTE: This is an overload rather than taking optional + // with a default argument of nullopt, because we want to pick up + // AnnotationRecord's user-defined conversions. Because going from + // e.g. Descriptor* -> optional requires two user-defined + // conversions, this does not work. + template + VarDefinition(Key&& key, Value&& value, AnnotationRecord annotation) + : key(std::forward(key)), + value(ToStringOrCallback(std::forward(value), Rank2{})), + annotation(std::move(annotation)) {} + + K key; + StringOrCallback value; + absl::optional annotation; + + private: + // go/ranked-overloads + struct Rank0 {}; + struct Rank1 : Rank0 {}; + struct Rank2 : Rank1 {}; + + // Dummy template for delayed instantiation, which is required for the + // static assert below to kick in only when this function is called when it + // shouldn't. + // + // This is done to produce a better error message than the "candidate does + // not match" SFINAE errors. + template + StringOrCallback ToStringOrCallback(std::function cb, Rank2) { + static_assert( + allowed, "callback-typed variables are not allowed in this location"); + return cb; + } + + // Separate from the AlphaNum overload to avoid copies when taking strings + // by value. + StringOrCallback ToStringOrCallback(std::string s, Rank1) { return s; } + + StringOrCallback ToStringOrCallback(const absl::AlphaNum& s, Rank0) { + return std::string(s.Piece()); + } + }; + public: static constexpr char kDefaultVariableDelimiter = '$'; static constexpr absl::string_view kProtocCodegenTrace = @@ -418,8 +490,8 @@ class PROTOBUF_EXPORT Printer { Options(const Options&) = default; Options(Options&&) = default; Options(char variable_delimiter, AnnotationCollector* annotation_collector) - : variable_delimiter(variable_delimiter), - annotation_collector(annotation_collector) {} + : variable_delimiter(variable_delimiter), + annotation_collector(annotation_collector) {} // The delimiter for variable substitutions, e.g. $foo$. char variable_delimiter = kDefaultVariableDelimiter; @@ -495,6 +567,10 @@ class PROTOBUF_EXPORT Printer { return absl::MakeCleanup([this] { var_lookups_.pop_back(); }); } + auto WithVars(std::initializer_list< + VarDefinition> + vars); + // Looks up a variable set with WithVars(). // // Will crash if: @@ -539,7 +615,7 @@ class PROTOBUF_EXPORT Printer { } // Increases the indentation by `indent` spaces; when nullopt, increments - // indentation by the configured default spaces_per_indentation. + // indentation by the configured default spaces_per_indent. // // Returns an RAII object that removes this indentation. auto WithIndent(absl::optional indent = absl::nullopt) { @@ -562,15 +638,11 @@ class PROTOBUF_EXPORT Printer { // documentation for more details. // // `format` MUST be a string constant. - void Emit( - std::initializer_list< - std::pair>>> - vars, - absl::string_view format, SourceLocation loc = SourceLocation::current()); + void Emit(std::initializer_list< + VarDefinition> + vars, + absl::string_view format, + SourceLocation loc = SourceLocation::current()); // Write a string directly to the underlying output, performing no formatting // of any sort. @@ -745,6 +817,11 @@ class PROTOBUF_EXPORT Printer { // Prints a codegen trace, for the given location in the compiler's source. void PrintCodegenTrace(absl::optional loc); + // The core implementation for "fully-elaborated" variable definitions. This + // is a private function to avoid users being able to set `allow_callbacks`. + template + auto WithDefs(std::initializer_list> vars); + // Returns the start and end of the value that was substituted in place of // the variable `varname` in the last call to PrintImpl() (with // `use_substitution_map` set), if such a variable was substituted exactly @@ -776,6 +853,66 @@ class PROTOBUF_EXPORT Printer { // current line. std::vector line_start_variables_; }; + +template +auto Printer::WithDefs( + std::initializer_list> vars) { + absl::flat_hash_map>> + var_map; + var_map.reserve(vars.size()); + + absl::flat_hash_map annotation_map; + + for (auto& var : vars) { + auto result = var_map.insert({var.key, var.value}); + GOOGLE_CHECK(result.second) << "repeated variable in Emit() or WithVars() call: \"" + << var.key << "\""; + if (var.annotation.has_value()) { + annotation_map.insert({var.key, *var.annotation}); + } + } + + var_lookups_.emplace_back( + [map = std::move(var_map)](absl::string_view var) -> LookupResult { + auto it = map.find(var); + if (it == map.end()) { + return absl::nullopt; + } + if (auto* str = absl::get_if(&it->second)) { + return *str; + } + + auto* f = absl::get_if>(&it->second); + GOOGLE_CHECK(f != nullptr); + return *f; + }); + + bool has_annotations = !annotation_map.empty(); + if (has_annotations) { + annotation_lookups_.emplace_back( + [map = std::move(annotation_map)]( + absl::string_view var) -> absl::optional { + auto it = map.find(var); + if (it == map.end()) { + return absl::nullopt; + } + return it->second; + }); + } + + return absl::MakeCleanup([this, has_annotations] { + var_lookups_.pop_back(); + if (has_annotations) { + annotation_lookups_.pop_back(); + } + }); +} + +inline auto Printer::WithVars( + std::initializer_list> + vars) { + return WithDefs(vars); +} } // namespace io } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/io/printer_unittest.cc b/src/google/protobuf/io/printer_unittest.cc index 7e1ebafaef..4e2dd7aa90 100644 --- a/src/google/protobuf/io/printer_unittest.cc +++ b/src/google/protobuf/io/printer_unittest.cc @@ -548,20 +548,49 @@ TEST_F(PrinterTest, Emit) { "}\n"); } -TEST_F(PrinterTest, EmitWithSubs) { +TEST_F(PrinterTest, EmitKeepsExtraLine) { { Printer printer(output()); - printer.Emit({{"class", "Foo"}, {"f1", "x"}, {"f2", "y"}, {"f3", "z"}}, - R"cc( - class $class$ { - int $f1$, $f2$, $f3$; - }; - )cc"); + printer.Emit(R"cc( + + class Foo { + int x, y, z; + }; + )cc"); + printer.Emit(R"java( + + public final class Bar { + Bar() {} + } + )java"); } EXPECT_EQ(written(), + "\n" "class Foo {\n" " int x, y, z;\n" + "};\n" + "\n" + "public final class Bar {\n" + " Bar() {}\n" + "}\n"); +} + +TEST_F(PrinterTest, EmitWithSubs) { + { + Printer printer(output()); + printer.Emit( + {{"class", "Foo"}, {"f1", "x"}, {"f2", "y"}, {"f3", "z"}, {"init", 42}}, + R"cc( + class $class$ { + int $f1$, $f2$, $f3$ = $init$; + }; + )cc"); + } + + EXPECT_EQ(written(), + "class Foo {\n" + " int x, y, z = 42;\n" "};\n"); } @@ -573,17 +602,18 @@ TEST_F(PrinterTest, EmitWithVars) { {"f1", "x"}, {"f2", "y"}, {"f3", "z"}, + {"init", 42}, }); printer.Emit(R"cc( class $class$ { - int $f1$, $f2$, $f3$; + int $f1$, $f2$, $f3$ = $init$; }; )cc"); } EXPECT_EQ(written(), "class Foo {\n" - " int x, y, z;\n" + " int x, y, z = 42;\n" "};\n"); } @@ -681,6 +711,28 @@ TEST_F(PrinterTest, EmitSameNameAnnotationFileNameOnly) { ElementsAre(Annotation(6, 9, "file.proto", IsEmpty()))); } +TEST_F(PrinterTest, EmitThreeArgWithVars) { + FakeAnnotationCollector collector; + { + Printer printer(output(), '$', &collector); + auto v = printer.WithVars({{"class", "Foo", "file.proto"}}); + + printer.Emit({{"f1", "x"}, {"f2", "y"}, {"f3", "z"}}, R"cc( + class $class$ { + int $f1$, $f2$, $f3$; + }; + )cc"); + } + + EXPECT_EQ(written(), + "class Foo {\n" + " int x, y, z;\n" + "};\n"); + + EXPECT_THAT(collector.Get(), + ElementsAre(Annotation(6, 9, "file.proto", IsEmpty()))); +} + TEST_F(PrinterTest, EmitRangeAnnotation) { FakeAnnotationCollector collector; { diff --git a/src/google/protobuf/io/tokenizer.cc b/src/google/protobuf/io/tokenizer.cc index 4fcf81b3dc..992d8c0b17 100644 --- a/src/google/protobuf/io/tokenizer.cc +++ b/src/google/protobuf/io/tokenizer.cc @@ -93,7 +93,7 @@ #include "google/protobuf/stubs/common.h" #include "google/protobuf/stubs/logging.h" #include "absl/strings/escaping.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "google/protobuf/io/strtod.h" #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/stubs/stl_util.h" @@ -708,7 +708,7 @@ bool Tokenizer::Next() { if (current_char_ & 0x80) { error_collector_->AddError( line_, column_, - StringPrintf("Interpreting non ascii codepoint %d.", + absl::StrFormat("Interpreting non ascii codepoint %d.", static_cast(current_char_))); } NextChar(); @@ -1058,7 +1058,7 @@ static void AppendUTF8(uint32_t code_point, std::string* output) { // Unicode code points end at 0x10FFFF, so this is out-of-range. // ConsumeString permits hex values up to 0x1FFFFF, and FetchUnicodePoint // doesn't perform a range check. - StringAppendF(output, "\\U%08x", code_point); + absl::StrAppendFormat(output, "\\U%08x", code_point); return; } tmp = ghtonl(tmp); diff --git a/src/google/protobuf/map_field_test.cc b/src/google/protobuf/map_field_test.cc index d0116bd91b..e5c296fc00 100644 --- a/src/google/protobuf/map_field_test.cc +++ b/src/google/protobuf/map_field_test.cc @@ -42,6 +42,7 @@ #include "google/protobuf/message.h" #include "google/protobuf/repeated_field.h" #include +#include "absl/strings/str_format.h" #include "google/protobuf/arena_test_util.h" #include "google/protobuf/map_test_util.h" diff --git a/src/google/protobuf/port_def.inc b/src/google/protobuf/port_def.inc index 0d6db17f8e..0fcc90d815 100644 --- a/src/google/protobuf/port_def.inc +++ b/src/google/protobuf/port_def.inc @@ -118,6 +118,15 @@ #define PROTOBUF_has_builtin_DEFINED_ #endif +#ifdef ADDRESS_SANITIZER +#include +#define PROTOBUF_POISON_MEMORY_REGION(p, n) ASAN_POISON_MEMORY_REGION(p, n) +#define PROTOBUF_UNPOISON_MEMORY_REGION(p, n) ASAN_UNPOISON_MEMORY_REGION(p, n) +#else // ADDRESS_SANITIZER +#define PROTOBUF_POISON_MEMORY_REGION(p, n) +#define PROTOBUF_UNPOISON_MEMORY_REGION(p, n) +#endif // ADDRESS_SANITIZER + // Portable PROTOBUF_BUILTIN_BSWAPxx definitions // Code must check for availability, e.g.: `defined(PROTOBUF_BUILTIN_BSWAP32)` #ifdef PROTOBUF_BUILTIN_BSWAP16 diff --git a/src/google/protobuf/port_undef.inc b/src/google/protobuf/port_undef.inc index e991502faa..00b721b72d 100644 --- a/src/google/protobuf/port_undef.inc +++ b/src/google/protobuf/port_undef.inc @@ -35,6 +35,8 @@ #error "port_undef.inc must be included after port_def.inc" #endif +#undef PROTOBUF_POISON_MEMORY_REGION +#undef PROTOBUF_UNPOISON_MEMORY_REGION #undef PROTOBUF_BUILTIN_BSWAP16 #undef PROTOBUF_BUILTIN_BSWAP32 #undef PROTOBUF_BUILTIN_BSWAP64 diff --git a/src/google/protobuf/stubs/BUILD.bazel b/src/google/protobuf/stubs/BUILD.bazel index 15db8bf717..98f497e518 100644 --- a/src/google/protobuf/stubs/BUILD.bazel +++ b/src/google/protobuf/stubs/BUILD.bazel @@ -14,7 +14,6 @@ cc_library( srcs = [ "bytestream.cc", "common.cc", - "stringprintf.cc", "structurally_valid.cc", "strutil.cc", ], @@ -28,7 +27,6 @@ cc_library( "port.h", "status_macros.h", "stl_util.h", - "stringprintf.h", "strutil.h", ], copts = COPTS, @@ -59,7 +57,6 @@ cc_library( "port.h", "status_macros.h", "stl_util.h", - "stringprintf.h", "strutil.h", ], deps = [ @@ -76,7 +73,6 @@ cc_test( srcs = [ "bytestream_unittest.cc", "common_unittest.cc", - "stringprintf_unittest.cc", "structurally_valid_unittest.cc", "strutil_unittest.cc", ], diff --git a/src/google/protobuf/stubs/stringprintf.cc b/src/google/protobuf/stubs/stringprintf.cc deleted file mode 100644 index 2e6613ebb3..0000000000 --- a/src/google/protobuf/stubs/stringprintf.cc +++ /dev/null @@ -1,176 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// from google3/base/stringprintf.cc - -#include "google/protobuf/stubs/stringprintf.h" - -#include -#include // For va_list and related operations -#include // MSVC requires this for _vsnprintf - -#include - -#include "google/protobuf/stubs/common.h" -#include "google/protobuf/stubs/logging.h" - -namespace google { -namespace protobuf { - -#ifdef _MSC_VER -#ifndef va_copy -// Define va_copy for MSVC. This is a hack, assuming va_list is simply a -// pointer into the stack and is safe to copy. -#define va_copy(dest, src) ((dest) = (src)) -#endif -#endif - -void StringAppendV(std::string* dst, const char* format, va_list ap) { - // First try with a small fixed size buffer - static const int kSpaceLength = 1024; - char space[kSpaceLength]; - - // It's possible for methods that use a va_list to invalidate - // the data in it upon use. The fix is to make a copy - // of the structure before using it and use that copy instead. - va_list backup_ap; - va_copy(backup_ap, ap); - int result = vsnprintf(space, kSpaceLength, format, backup_ap); - va_end(backup_ap); - - if (result < kSpaceLength) { - if (result >= 0) { - // Normal case -- everything fit. - dst->append(space, result); - return; - } - -#ifdef _MSC_VER - { - // Error or MSVC running out of space. MSVC 8.0 and higher - // can be asked about space needed with the special idiom below: - va_copy(backup_ap, ap); - result = vsnprintf(nullptr, 0, format, backup_ap); - va_end(backup_ap); - } -#endif - - if (result < 0) { - // Just an error. - return; - } - } - - // Increase the buffer size to the size requested by vsnprintf, - // plus one for the closing \0. - int length = result+1; - char* buf = new char[length]; - - // Restore the va_list before we use it again - va_copy(backup_ap, ap); - result = vsnprintf(buf, length, format, backup_ap); - va_end(backup_ap); - - if (result >= 0 && result < length) { - // It fit - dst->append(buf, result); - } - delete[] buf; -} - -std::string StringPrintf(const char* format, ...) { - va_list ap; - va_start(ap, format); - std::string result; - StringAppendV(&result, format, ap); - va_end(ap); - return result; -} - -const std::string& SStringPrintf(std::string* dst, const char* format, ...) { - va_list ap; - va_start(ap, format); - dst->clear(); - StringAppendV(dst, format, ap); - va_end(ap); - return *dst; -} - -void StringAppendF(std::string* dst, const char* format, ...) { - va_list ap; - va_start(ap, format); - StringAppendV(dst, format, ap); - va_end(ap); -} - -// Max arguments supported by StringPrintVector -const int kStringPrintfVectorMaxArgs = 32; - -// An empty block of zero for filler arguments. This is const so that if -// printf tries to write to it (via %n) then the program gets a SIGSEGV -// and we can fix the problem or protect against an attack. -static const char string_printf_empty_block[256] = { '\0' }; - -std::string StringPrintfVector(const char* format, - const std::vector& v) { - GOOGLE_CHECK_LE(v.size(), kStringPrintfVectorMaxArgs) - << "StringPrintfVector currently only supports up to " - << kStringPrintfVectorMaxArgs << " arguments. " - << "Feel free to add support for more if you need it."; - - // Add filler arguments so that bogus format+args have a harder time - // crashing the program, corrupting the program (%n), - // or displaying random chunks of memory to users. - - const char* cstr[kStringPrintfVectorMaxArgs]; - for (int i = 0; i < v.size(); ++i) { - cstr[i] = v[i].c_str(); - } - for (int i = v.size(); i < kStringPrintfVectorMaxArgs; ++i) { - cstr[i] = &string_printf_empty_block[0]; - } - - // I do not know any way to pass kStringPrintfVectorMaxArgs arguments, - // or any way to build a va_list by hand, or any API for printf - // that accepts an array of arguments. The best I can do is stick - // this COMPILE_ASSERT right next to the actual statement. - - static_assert(kStringPrintfVectorMaxArgs == 32, "arg_count_mismatch"); - return StringPrintf(format, - cstr[0], cstr[1], cstr[2], cstr[3], cstr[4], - cstr[5], cstr[6], cstr[7], cstr[8], cstr[9], - cstr[10], cstr[11], cstr[12], cstr[13], cstr[14], - cstr[15], cstr[16], cstr[17], cstr[18], cstr[19], - cstr[20], cstr[21], cstr[22], cstr[23], cstr[24], - cstr[25], cstr[26], cstr[27], cstr[28], cstr[29], - cstr[30], cstr[31]); -} -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/stubs/stringprintf.h b/src/google/protobuf/stubs/stringprintf.h deleted file mode 100644 index e1c0561dcd..0000000000 --- a/src/google/protobuf/stubs/stringprintf.h +++ /dev/null @@ -1,87 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// from google3/base/stringprintf.h -// -// Printf variants that place their output in a C++ string. -// -// Usage: -// string result = StringPrintf("%d %s\n", 10, "hello"); -// SStringPrintf(&result, "%d %s\n", 10, "hello"); -// StringAppendF(&result, "%d %s\n", 20, "there"); - -#ifndef GOOGLE_PROTOBUF_STUBS_STRINGPRINTF_H -#define GOOGLE_PROTOBUF_STUBS_STRINGPRINTF_H - -#include - -#include -#include - -#include "google/protobuf/stubs/common.h" - -// Must be last. -#include "google/protobuf/port_def.inc" // NOLINT - -namespace google { -namespace protobuf { - -// Return a C++ string -PROTOBUF_EXPORT extern std::string StringPrintf(const char* format, ...); - -// Store result into a supplied string and return it -PROTOBUF_EXPORT extern const std::string& SStringPrintf(std::string* dst, - const char* format, - ...); - -// Append result to a supplied string -PROTOBUF_EXPORT extern void StringAppendF(std::string* dst, const char* format, - ...); - -// Lower-level routine that takes a va_list and appends to a specified -// string. All other routines are just convenience wrappers around it. -PROTOBUF_EXPORT extern void StringAppendV(std::string* dst, const char* format, - va_list ap); - -// The max arguments supported by StringPrintfVector -PROTOBUF_EXPORT extern const int kStringPrintfVectorMaxArgs; - -// You can use this version when all your arguments are strings, but -// you don't know how many arguments you'll have at compile time. -// StringPrintfVector will LOG(FATAL) if v.size() > kStringPrintfVectorMaxArgs -PROTOBUF_EXPORT extern std::string StringPrintfVector( - const char* format, const std::vector& v); - -} // namespace protobuf -} // namespace google - -#include "google/protobuf/port_undef.inc" - -#endif // GOOGLE_PROTOBUF_STUBS_STRINGPRINTF_H diff --git a/src/google/protobuf/stubs/stringprintf_unittest.cc b/src/google/protobuf/stubs/stringprintf_unittest.cc deleted file mode 100644 index c53e190f50..0000000000 --- a/src/google/protobuf/stubs/stringprintf_unittest.cc +++ /dev/null @@ -1,157 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2012 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// from google3/base/stringprintf_unittest.cc - -#include "google/protobuf/stubs/stringprintf.h" - -#include - -#include -#include -#include - -#include "google/protobuf/testing/googletest.h" - -namespace google { -namespace protobuf { -namespace { - -TEST(StringPrintfTest, Empty) { -#if 0 - // gcc 2.95.3, gcc 4.1.0, and gcc 4.2.2 all warn about this: - // warning: zero-length printf format string. - // so we do not allow them in google3. - EXPECT_EQ("", StringPrintf("")); -#endif - EXPECT_EQ("", StringPrintf("%s", std::string().c_str())); - EXPECT_EQ("", StringPrintf("%s", "")); -} - -TEST(StringPrintfTest, Misc) { -// MSVC and mingw does not support $ format specifier. -#if !defined(_MSC_VER) && !defined(__MINGW32__) - EXPECT_EQ("123hello w", StringPrintf("%3$d%2$s %1$c", 'w', "hello", 123)); -#endif // !_MSC_VER -} - -TEST(StringAppendFTest, Empty) { - std::string value("Hello"); - const char* empty = ""; - StringAppendF(&value, "%s", empty); - EXPECT_EQ("Hello", value); -} - -TEST(StringAppendFTest, EmptyString) { - std::string value("Hello"); - StringAppendF(&value, "%s", ""); - EXPECT_EQ("Hello", value); -} - -TEST(StringAppendFTest, String) { - std::string value("Hello"); - StringAppendF(&value, " %s", "World"); - EXPECT_EQ("Hello World", value); -} - -TEST(StringAppendFTest, Int) { - std::string value("Hello"); - StringAppendF(&value, " %d", 123); - EXPECT_EQ("Hello 123", value); -} - -TEST(StringPrintfTest, Multibyte) { - // If we are in multibyte mode and feed invalid multibyte sequence, - // StringPrintf should return an empty string instead of running - // out of memory while trying to determine destination buffer size. - // see b/4194543. - - char* old_locale_c = setlocale(LC_CTYPE, nullptr); - ASSERT_TRUE(old_locale_c != nullptr); - std::string old_locale = old_locale_c; - // Push locale with multibyte mode - setlocale(LC_CTYPE, "en_US.utf8"); - - const char kInvalidCodePoint[] = "\375\067s"; - std::string value = StringPrintf("%.*s", 3, kInvalidCodePoint); - - // In some versions of glibc (e.g. eglibc-2.11.1, aka GRTEv2), snprintf - // returns error given an invalid codepoint. Other versions - // (e.g. eglibc-2.15, aka pre-GRTEv3) emit the codepoint verbatim. - // We test that the output is one of the above. - EXPECT_TRUE(value.empty() || value == kInvalidCodePoint); - - // Repeat with longer string, to make sure that the dynamically - // allocated path in StringAppendV is handled correctly. - const size_t n = 2048; - std::array buf; - memset(&buf[0], ' ', n - 3); - memcpy(&buf[0] + n - 3, kInvalidCodePoint, 4); - value = StringPrintf("%.*s", n, &buf[0]); - // See GRTEv2 vs. GRTEv3 comment above. - EXPECT_TRUE(value.empty() || value == &buf[0]); - - setlocale(LC_CTYPE, old_locale.c_str()); -} - -TEST(StringPrintfTest, NoMultibyte) { - // No multibyte handling, but the string contains funny chars. - char* old_locale_c = setlocale(LC_CTYPE, nullptr); - ASSERT_TRUE(old_locale_c != nullptr); - std::string old_locale = old_locale_c; - setlocale(LC_CTYPE, "POSIX"); - std::string value = StringPrintf("%.*s", 3, "\375\067s"); - setlocale(LC_CTYPE, old_locale.c_str()); - EXPECT_EQ("\375\067s", value); -} - -TEST(StringPrintfTest, DontOverwriteErrno) { - // Check that errno isn't overwritten unless we're printing - // something significantly larger than what people are normally - // printing in their badly written PLOG() statements. - errno = ECHILD; - std::string value = StringPrintf("Hello, %s!", "World"); - EXPECT_EQ(ECHILD, errno); -} - -TEST(StringPrintfTest, LargeBuf) { - // Check that the large buffer is handled correctly. - int n = 2048; - char* buf = new char[n+1]; - memset(buf, ' ', n); - buf[n] = 0; - std::string value = StringPrintf("%s", buf); - EXPECT_EQ(buf, value); - delete[] buf; -} - -} // anonymous namespace -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/unittest.proto b/src/google/protobuf/unittest.proto index 419a3dfe4f..a8078158ea 100644 --- a/src/google/protobuf/unittest.proto +++ b/src/google/protobuf/unittest.proto @@ -359,6 +359,9 @@ message TestMixedFieldsAndExtensions { message TestGroup { optional group OptionalGroup = 16 { optional int32 a = 17; + optional int32 zz = 89; // fast table size must be at least 16, for this + // field to be parsed by the fast parser, since + // 89 - 17 = 72 is a multiple of 8. } optional ForeignEnum optional_foreign_enum = 22; } diff --git a/src/google/protobuf/util/internal/proto_writer.h b/src/google/protobuf/util/internal/proto_writer.h index f19b191cca..81c8b25120 100644 --- a/src/google/protobuf/util/internal/proto_writer.h +++ b/src/google/protobuf/util/internal/proto_writer.h @@ -41,8 +41,8 @@ #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/descriptor.h" -#include "google/protobuf/stubs/bytestream.h" #include "absl/status/status.h" +#include "google/protobuf/stubs/bytestream.h" #include "google/protobuf/port.h" #include "google/protobuf/util/internal/datapiece.h" #include "google/protobuf/util/internal/error_listener.h" diff --git a/src/google/protobuf/util/internal/protostream_objectsource.cc b/src/google/protobuf/util/internal/protostream_objectsource.cc index 63a9dc1836..367205fe4c 100644 --- a/src/google/protobuf/util/internal/protostream_objectsource.cc +++ b/src/google/protobuf/util/internal/protostream_objectsource.cc @@ -47,7 +47,7 @@ #include "absl/base/casts.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "absl/time/time.h" #include "google/protobuf/util/internal/constants.h" @@ -332,7 +332,7 @@ absl::Status ProtoStreamObjectSource::RenderTimestamp( absl::Time tm = absl::FromUnixSeconds(seconds); std::string formatted_seconds = absl::FormatTime(kRfc3339TimeFormat, tm, absl::UTCTimeZone()); - std::string formatted_time = StringPrintf( + std::string formatted_time = absl::StrFormat( "%s%sZ", formatted_seconds.c_str(), FormatNanos( nanos, @@ -374,7 +374,7 @@ absl::Status ProtoStreamObjectSource::RenderDuration( sign = "-"; nanos = -nanos; } - std::string formatted_duration = StringPrintf( + std::string formatted_duration = absl::StrFormat( "%s%lld%ss", sign.c_str(), static_cast(seconds), // NOLINT FormatNanos( nanos, @@ -1111,7 +1111,7 @@ std::string FormatNanos(uint32_t nanos, bool with_trailing_zeros) { const int precision = (nanos % 1000 != 0) ? 9 : (nanos % 1000000 != 0) ? 6 : 3; - std::string formatted = StringPrintf( + std::string formatted = absl::StrFormat( "%.*f", precision, static_cast(nanos) / kNanosPerSecond); // remove the leading 0 before decimal. return formatted.substr(1); diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.h b/src/google/protobuf/util/internal/protostream_objectwriter.h index 95fedf891d..35933c1477 100644 --- a/src/google/protobuf/util/internal/protostream_objectwriter.h +++ b/src/google/protobuf/util/internal/protostream_objectwriter.h @@ -40,9 +40,9 @@ #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/descriptor.h" -#include "google/protobuf/stubs/bytestream.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" +#include "google/protobuf/stubs/bytestream.h" #include "absl/strings/string_view.h" #include "google/protobuf/port.h" #include "google/protobuf/util/internal/datapiece.h" diff --git a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc index 640085ff79..22a2bf0d70 100644 --- a/src/google/protobuf/util/internal/protostream_objectwriter_test.cc +++ b/src/google/protobuf/util/internal/protostream_objectwriter_test.cc @@ -40,8 +40,8 @@ #include "google/protobuf/descriptor.pb.h" #include "google/protobuf/message.h" #include "google/protobuf/util/internal/mock_error_listener.h" -#include "google/protobuf/stubs/bytestream.h" #include +#include "google/protobuf/stubs/bytestream.h" #include "absl/strings/string_view.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/dynamic_message.h" diff --git a/src/google/protobuf/util/json_util.h b/src/google/protobuf/util/json_util.h index 5ee4f83ed0..fe7444197a 100644 --- a/src/google/protobuf/util/json_util.h +++ b/src/google/protobuf/util/json_util.h @@ -34,8 +34,8 @@ #define GOOGLE_PROTOBUF_UTIL_JSON_UTIL_H__ -#include "google/protobuf/stubs/bytestream.h" #include "absl/status/status.h" +#include "google/protobuf/stubs/bytestream.h" #include "absl/strings/string_view.h" #include "google/protobuf/message.h" #include "google/protobuf/util/type_resolver.h" diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc index ba4db190d4..00a0e9d7e6 100644 --- a/src/google/protobuf/util/message_differencer.cc +++ b/src/google/protobuf/util/message_differencer.cc @@ -59,7 +59,7 @@ #include "absl/strings/escaping.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "google/protobuf/util/field_comparator.h" // Always include as last one, otherwise it can break compilation @@ -2091,7 +2091,7 @@ void MessageDifferencer::StreamReporter::PrintUnknownFieldValue( "0x", absl::Hex(unknown_field->fixed64(), absl::kZeroPad16)); break; case UnknownField::TYPE_LENGTH_DELIMITED: - output = StringPrintf( + output = absl::StrFormat( "\"%s\"", absl::CEscape(unknown_field->length_delimited()).c_str()); break; case UnknownField::TYPE_GROUP: diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc index 94154a0e3c..0d5a173020 100644 --- a/src/google/protobuf/util/time_util.cc +++ b/src/google/protobuf/util/time_util.cc @@ -37,7 +37,7 @@ #include "google/protobuf/timestamp.pb.h" #include "absl/numeric/int128.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" #include "absl/time/clock.h" #include "absl/time/time.h" @@ -127,11 +127,11 @@ Duration CreateNormalized(int64_t seconds, int32_t nanos) { // precision to represent the exact value. std::string FormatNanos(int32_t nanos) { if (nanos % kNanosPerMillisecond == 0) { - return StringPrintf("%03d", nanos / kNanosPerMillisecond); + return absl::StrFormat("%03d", nanos / kNanosPerMillisecond); } else if (nanos % kNanosPerMicrosecond == 0) { - return StringPrintf("%06d", nanos / kNanosPerMicrosecond); + return absl::StrFormat("%06d", nanos / kNanosPerMicrosecond); } else { - return StringPrintf("%09d", nanos); + return absl::StrFormat("%09d", nanos); } } diff --git a/src/google/protobuf/util/type_resolver_util.h b/src/google/protobuf/util/type_resolver_util.h index f8e9c194cc..0327e61d5d 100644 --- a/src/google/protobuf/util/type_resolver_util.h +++ b/src/google/protobuf/util/type_resolver_util.h @@ -35,15 +35,15 @@ #include +// Must be included last. +#include "google/protobuf/port_def.inc" + namespace google { namespace protobuf { class DescriptorPool; namespace util { class TypeResolver; -// Must be included last. -#include "google/protobuf/port_def.inc" - // Creates a TypeResolver that serves type information in the given descriptor // pool. Caller takes ownership of the returned TypeResolver. PROTOBUF_EXPORT TypeResolver* NewTypeResolverForDescriptorPool( diff --git a/src/google/protobuf/wire_format_lite.cc b/src/google/protobuf/wire_format_lite.cc index 612ae40c69..7241a9eba1 100644 --- a/src/google/protobuf/wire_format_lite.cc +++ b/src/google/protobuf/wire_format_lite.cc @@ -45,7 +45,7 @@ #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/io/zero_copy_stream_impl_lite.h" #include "absl/strings/str_cat.h" -#include "google/protobuf/stubs/stringprintf.h" +#include "absl/strings/str_format.h" // Must be included last. From 1bd3d1932abc77f7e27d4e906397df5d36b6a1c5 Mon Sep 17 00:00:00 2001 From: Mike Kruskal Date: Thu, 22 Sep 2022 11:25:41 -0700 Subject: [PATCH 56/64] Update changelog --- CHANGES.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGES.txt b/CHANGES.txt index 3b0681e3fe..13d7b7332e 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -25,6 +25,7 @@ * Reduce memory consumption of MessageSet parsing. * Save code space by avoiding inlining of large-in-aggregate code-space MessageLite::~MessageLite destructor. * Breaking change: delete Arena::Init + * Make a PROTOBUF_POISON/UNPOISON to reduce noise in the source Kotlin @@ -37,6 +38,7 @@ * Performance improvement for repeated use of FieldMaskUtil#merge by caching constructed FieldMaskTrees. * Optimized Java proto serialization gencode for protos having many extension ranges with few fields in between. + * More thoroughly annotate public generated code in Java lite protocol buffers. Python * Changes ordering of printed fields in .pyi files from lexicographic to the same ordering found in the proto descriptor. From 2ce17c08a25b97dc38b0da59099f00e0ce7adec2 Mon Sep 17 00:00:00 2001 From: Mike Kruskal Date: Thu, 22 Sep 2022 13:55:51 -0700 Subject: [PATCH 57/64] Fixing sync problems --- .../protobuf/map_for_proto2_lite_test.proto | 3 --- src/google/protobuf/arena.cc | 23 +++++++++++++------ src/google/protobuf/arena_impl.h | 13 +++-------- 3 files changed, 19 insertions(+), 20 deletions(-) diff --git a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto index 1ab94eb3b7..fd479bb1ff 100644 --- a/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto +++ b/java/core/src/test/proto/com/google/protobuf/map_for_proto2_lite_test.proto @@ -128,6 +128,3 @@ message ReservedAsMapFieldWithEnumValue { // null is not a 'reserved word' per se but as a literal needs similar care map null = 10; } -package map_for_proto2_lite_test; -option java_package = "map_lite_test"; -option optimize_for = LITE_RUNTIME; diff --git a/src/google/protobuf/arena.cc b/src/google/protobuf/arena.cc index 6ba81f87ab..7a0503792d 100644 --- a/src/google/protobuf/arena.cc +++ b/src/google/protobuf/arena.cc @@ -53,6 +53,17 @@ namespace google { namespace protobuf { namespace internal { +namespace { + +PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT ArenaBlock +kSentryArenaBlock = {}; + +ArenaBlock* SentryArenaBlock() { + // const_cast<> is okay as kSentryArenaBlock will never be mutated. + return const_cast(&kSentryArenaBlock); +} + +} static SerialArena::Memory AllocateMemory(const AllocationPolicy* policy_ptr, size_t last_size, size_t min_bytes) { @@ -105,8 +116,6 @@ class GetDeallocator { size_t* space_allocated_; }; -constexpr ArenaBlock SerialArena::kSentryBlock; - // It is guaranteed that this is constructed in `b`. IOW, this is not the first // arena and `b` cannot be sentry. SerialArena::SerialArena(ArenaBlock* b, ThreadSafeArena& parent) @@ -120,7 +129,7 @@ SerialArena::SerialArena(ArenaBlock* b, ThreadSafeArena& parent) // It is guaranteed that this is the first SerialArena. Use sentry block. SerialArena::SerialArena(ThreadSafeArena& parent) - : head_{SentryBlock()}, parent_{parent} {} + : head_{SentryArenaBlock()}, parent_{parent} {} // It is guaranteed that this is the first SerialArena but `b` may be user // provided or newly allocated to store AllocationPolicy. @@ -308,7 +317,7 @@ void SerialArena::CleanupList() { // where the size of "ids" and "arenas" is determined at runtime; hence the use // of Layout. struct SerialArenaChunkHeader { - constexpr SerialArenaChunkHeader(uint32_t capacity, uint32_t size) + PROTOBUF_CONSTEXPR SerialArenaChunkHeader(uint32_t capacity, uint32_t size) : next_chunk(nullptr), capacity(capacity), size(size) {} ThreadSafeArena::SerialArenaChunk* next_chunk; @@ -433,7 +442,7 @@ class ThreadSafeArena::SerialArenaChunk { } }; -constexpr SerialArenaChunkHeader kSentryArenaChunk = {0, 0}; +PROTOBUF_CONSTEXPR SerialArenaChunkHeader kSentryArenaChunk = {0, 0}; ThreadSafeArena::SerialArenaChunk* ThreadSafeArena::SentrySerialArenaChunk() { // const_cast is okay because the sentry chunk is never mutated. Also, @@ -487,7 +496,7 @@ ThreadSafeArena::ThreadSafeArena(void* mem, size_t size, ArenaBlock* ThreadSafeArena::FirstBlock(void* buf, size_t size) { GOOGLE_DCHECK_EQ(reinterpret_cast(buf) & 7, 0u); if (buf == nullptr || size <= kBlockHeaderSize) { - return SerialArena::SentryBlock(); + return SentryArenaBlock(); } // Record user-owned block. alloc_policy_.set_is_user_owned_initial_block(true); @@ -702,7 +711,7 @@ uint64_t ThreadSafeArena::Reset() { : kBlockHeaderSize + kAllocPolicySize; first_arena_.Init(new (mem.ptr) ArenaBlock{nullptr, mem.size}, offset); } else { - first_arena_.Init(SerialArena::SentryBlock(), 0); + first_arena_.Init(SentryArenaBlock(), 0); } // Since the first block and potential alloc_policy on the first block is diff --git a/src/google/protobuf/arena_impl.h b/src/google/protobuf/arena_impl.h index 43056f539f..fa4d6f50c8 100644 --- a/src/google/protobuf/arena_impl.h +++ b/src/google/protobuf/arena_impl.h @@ -91,7 +91,7 @@ inline PROTOBUF_ALWAYS_INLINE void* AlignTo(void* p, size_t a) { // a default memory order (std::memory_order_seq_cst). template struct Atomic { - constexpr explicit Atomic(T v) : val(v) {} + PROTOBUF_CONSTEXPR explicit Atomic(T v) : val(v) {} T relaxed_get() const { return val.load(std::memory_order_relaxed); } T relaxed_get() { return val.load(std::memory_order_relaxed); } @@ -114,7 +114,7 @@ struct Atomic { struct ArenaBlock { // For the sentry block with zero-size where ptr_, limit_, cleanup_nodes all // point to "this". - constexpr ArenaBlock() + PROTOBUF_CONSTEXPR ArenaBlock() : next(nullptr), cleanup_nodes(this), relaxed_size(0) {} ArenaBlock(ArenaBlock* next, size_t size) @@ -577,13 +577,6 @@ class PROTOBUF_EXPORT SerialArena { private: friend class ThreadSafeArena; - static constexpr ArenaBlock kSentryBlock = {}; - - static ArenaBlock* SentryBlock() { - // const_cast<> is okay as kSentryBlock will never be mutated. - return const_cast(&kSentryBlock); - } - // Creates a new SerialArena inside mem using the remaining memory as for // future allocations. // The `parent` arena must outlive the serial arena, which is guaranteed @@ -872,7 +865,7 @@ class PROTOBUF_EXPORT ThreadSafeArena { #pragma warning(disable : 4324) #endif struct alignas(kCacheAlignment) CacheAlignedLifecycleIdGenerator { - constexpr CacheAlignedLifecycleIdGenerator() : id{0} {} + PROTOBUF_CONSTEXPR CacheAlignedLifecycleIdGenerator() : id{0} {} Atomic id; }; From 7c646286699b8eaef19285644ba9856ffcb93552 Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Mon, 19 Sep 2022 13:19:31 -0400 Subject: [PATCH 58/64] [ObjC] Output directive to disable clang-format on generated files. Regenerate the WKTs accordingly. --- objectivec/GPBAny.pbobjc.h | 4 ++++ objectivec/GPBAny.pbobjc.m | 4 ++++ objectivec/GPBApi.pbobjc.h | 4 ++++ objectivec/GPBApi.pbobjc.m | 4 ++++ objectivec/GPBDuration.pbobjc.h | 4 ++++ objectivec/GPBDuration.pbobjc.m | 4 ++++ objectivec/GPBEmpty.pbobjc.h | 4 ++++ objectivec/GPBEmpty.pbobjc.m | 4 ++++ objectivec/GPBFieldMask.pbobjc.h | 4 ++++ objectivec/GPBFieldMask.pbobjc.m | 4 ++++ objectivec/GPBSourceContext.pbobjc.h | 4 ++++ objectivec/GPBSourceContext.pbobjc.m | 4 ++++ objectivec/GPBStruct.pbobjc.h | 4 ++++ objectivec/GPBStruct.pbobjc.m | 4 ++++ objectivec/GPBTimestamp.pbobjc.h | 4 ++++ objectivec/GPBTimestamp.pbobjc.m | 4 ++++ objectivec/GPBType.pbobjc.h | 4 ++++ objectivec/GPBType.pbobjc.m | 4 ++++ objectivec/GPBWrappers.pbobjc.h | 4 ++++ objectivec/GPBWrappers.pbobjc.m | 4 ++++ .../protobuf/compiler/objectivec/objectivec_file.cc | 10 ++++++++-- 21 files changed, 88 insertions(+), 2 deletions(-) diff --git a/objectivec/GPBAny.pbobjc.h b/objectivec/GPBAny.pbobjc.h index 7fb4129b13..e30acc0aec 100644 --- a/objectivec/GPBAny.pbobjc.h +++ b/objectivec/GPBAny.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -172,3 +174,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBAny.pbobjc.m b/objectivec/GPBAny.pbobjc.m index 7632c8c279..e838675145 100644 --- a/objectivec/GPBAny.pbobjc.m +++ b/objectivec/GPBAny.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBAny.pbobjc.h" @@ -98,3 +100,5 @@ typedef struct GPBAny__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBApi.pbobjc.h b/objectivec/GPBApi.pbobjc.h index 1848aa6a91..3cd0821bac 100644 --- a/objectivec/GPBApi.pbobjc.h +++ b/objectivec/GPBApi.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -296,3 +298,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBApi.pbobjc.m b/objectivec/GPBApi.pbobjc.m index 7f86a087ff..88a215eb15 100644 --- a/objectivec/GPBApi.pbobjc.m +++ b/objectivec/GPBApi.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBApi.pbobjc.h" @@ -352,3 +354,5 @@ typedef struct GPBMixin__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBDuration.pbobjc.h b/objectivec/GPBDuration.pbobjc.h index d6236b07f3..fda9b4733f 100644 --- a/objectivec/GPBDuration.pbobjc.h +++ b/objectivec/GPBDuration.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -131,3 +133,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBDuration.pbobjc.m b/objectivec/GPBDuration.pbobjc.m index 11ba5e5f7b..bc610923f4 100644 --- a/objectivec/GPBDuration.pbobjc.m +++ b/objectivec/GPBDuration.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/duration.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBDuration.pbobjc.h" @@ -93,3 +95,5 @@ typedef struct GPBDuration__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBEmpty.pbobjc.h b/objectivec/GPBEmpty.pbobjc.h index 5878223a43..26ef9a6907 100644 --- a/objectivec/GPBEmpty.pbobjc.h +++ b/objectivec/GPBEmpty.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/empty.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -58,3 +60,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBEmpty.pbobjc.m b/objectivec/GPBEmpty.pbobjc.m index 8aefddb5b4..49f703099a 100644 --- a/objectivec/GPBEmpty.pbobjc.m +++ b/objectivec/GPBEmpty.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/empty.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBEmpty.pbobjc.h" @@ -69,3 +71,5 @@ typedef struct GPBEmpty__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBFieldMask.pbobjc.h b/objectivec/GPBFieldMask.pbobjc.h index b7eccff21c..87898ad254 100644 --- a/objectivec/GPBFieldMask.pbobjc.h +++ b/objectivec/GPBFieldMask.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -259,3 +261,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBFieldMask.pbobjc.m b/objectivec/GPBFieldMask.pbobjc.m index ab25d3f9b1..f820fd826d 100644 --- a/objectivec/GPBFieldMask.pbobjc.m +++ b/objectivec/GPBFieldMask.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/field_mask.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBFieldMask.pbobjc.h" @@ -82,3 +84,5 @@ typedef struct GPBFieldMask__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBSourceContext.pbobjc.h b/objectivec/GPBSourceContext.pbobjc.h index b17fec0b78..e747dc0b9f 100644 --- a/objectivec/GPBSourceContext.pbobjc.h +++ b/objectivec/GPBSourceContext.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/source_context.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -63,3 +65,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBSourceContext.pbobjc.m b/objectivec/GPBSourceContext.pbobjc.m index 376d4421de..094f32380a 100644 --- a/objectivec/GPBSourceContext.pbobjc.m +++ b/objectivec/GPBSourceContext.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/source_context.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBSourceContext.pbobjc.h" @@ -82,3 +84,5 @@ typedef struct GPBSourceContext__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBStruct.pbobjc.h b/objectivec/GPBStruct.pbobjc.h index ff4eefde52..eaa531ed9a 100644 --- a/objectivec/GPBStruct.pbobjc.h +++ b/objectivec/GPBStruct.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/struct.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -190,3 +192,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBStruct.pbobjc.m b/objectivec/GPBStruct.pbobjc.m index 726cfb860e..3707178eb8 100644 --- a/objectivec/GPBStruct.pbobjc.m +++ b/objectivec/GPBStruct.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/struct.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBStruct.pbobjc.h" @@ -295,3 +297,5 @@ typedef struct GPBListValue__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBTimestamp.pbobjc.h b/objectivec/GPBTimestamp.pbobjc.h index 8203383bdd..6d6a93028f 100644 --- a/objectivec/GPBTimestamp.pbobjc.h +++ b/objectivec/GPBTimestamp.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -162,3 +164,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBTimestamp.pbobjc.m b/objectivec/GPBTimestamp.pbobjc.m index 72d348f42a..1792ecb3ab 100644 --- a/objectivec/GPBTimestamp.pbobjc.m +++ b/objectivec/GPBTimestamp.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBTimestamp.pbobjc.h" @@ -93,3 +95,5 @@ typedef struct GPBTimestamp__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBType.pbobjc.h b/objectivec/GPBType.pbobjc.h index 969219f03f..ef9b74bf5f 100644 --- a/objectivec/GPBType.pbobjc.h +++ b/objectivec/GPBType.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -430,3 +432,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBType.pbobjc.m b/objectivec/GPBType.pbobjc.m index f5fc1efece..5c8c73e169 100644 --- a/objectivec/GPBType.pbobjc.m +++ b/objectivec/GPBType.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBType.pbobjc.h" @@ -707,3 +709,5 @@ typedef struct GPBOption__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBWrappers.pbobjc.h b/objectivec/GPBWrappers.pbobjc.h index e6741ae120..11b052a6ba 100644 --- a/objectivec/GPBWrappers.pbobjc.h +++ b/objectivec/GPBWrappers.pbobjc.h @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/wrappers.proto +// clang-format off + #import "GPBDescriptor.h" #import "GPBMessage.h" #import "GPBRootObject.h" @@ -205,3 +207,5 @@ CF_EXTERN_C_END #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/objectivec/GPBWrappers.pbobjc.m b/objectivec/GPBWrappers.pbobjc.m index b02a0716e2..45ee1a3b94 100644 --- a/objectivec/GPBWrappers.pbobjc.m +++ b/objectivec/GPBWrappers.pbobjc.m @@ -1,6 +1,8 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/wrappers.proto +// clang-format off + #import "GPBProtocolBuffers_RuntimeSupport.h" #import "GPBWrappers.pbobjc.h" @@ -441,3 +443,5 @@ typedef struct GPBBytesValue__storage_ { #pragma clang diagnostic pop // @@protoc_insertion_point(global_scope) + +// clange-format on diff --git a/src/google/protobuf/compiler/objectivec/objectivec_file.cc b/src/google/protobuf/compiler/objectivec/objectivec_file.cc index 84910fff23..fc51baf866 100644 --- a/src/google/protobuf/compiler/objectivec/objectivec_file.cc +++ b/src/google/protobuf/compiler/objectivec/objectivec_file.cc @@ -377,7 +377,9 @@ void FileGenerator::GenerateHeader(io::Printer* printer) { "\n" "#pragma clang diagnostic pop\n" "\n" - "// @@protoc_insertion_point(global_scope)\n"); + "// @@protoc_insertion_point(global_scope)\n" + "\n" + "// clange-format on\n"); } void FileGenerator::GenerateSource(io::Printer* printer) { @@ -638,7 +640,9 @@ void FileGenerator::GenerateSource(io::Printer* printer) { "\n" "#pragma clang diagnostic pop\n" "\n" - "// @@protoc_insertion_point(global_scope)\n"); + "// @@protoc_insertion_point(global_scope)\n" + "\n" + "// clange-format on\n"); } // Helper to print the import of the runtime support at the top of generated @@ -650,6 +654,8 @@ void FileGenerator::PrintFileRuntimePreamble( printer->Print( "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" "// source: $filename$\n" + "\n" + "// clang-format off\n" "\n", "filename", file_->name()); From 9e069b2e515472bac1428c010f93eca7d4c499d9 Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Mon, 19 Sep 2022 13:34:01 -0400 Subject: [PATCH 59/64] [ObjC] Tweak some things to be better shape for clang-format. - Minor formatting changes to make thing happy. - Block clang-format from the PDDM macro definitions to avoid it wrapping things. - Don't add clang-format directives to the expansion, easier to handling it outside of there. --- objectivec/DevTools/pddm.py | 3 +- objectivec/DevTools/pddm_tests.py | 6 -- objectivec/GPBArray.h | 73 ++++++++++------ objectivec/GPBArray.m | 85 +++++++++---------- objectivec/GPBArray_PackagePrivate.h | 2 - objectivec/GPBCodedOutputStream.h | 16 ++-- objectivec/GPBCodedOutputStream.m | 42 +-------- objectivec/GPBDictionary.h | 7 +- objectivec/GPBDictionary.m | 44 +++------- objectivec/GPBDictionary_PackagePrivate.h | 17 ++-- objectivec/GPBMessage.m | 45 ++-------- objectivec/GPBProtocolBuffers.h | 2 + .../GPBProtocolBuffers_RuntimeSupport.h | 2 + objectivec/GPBUtilities.h | 11 ++- objectivec/GPBUtilities.m | 36 +++----- objectivec/GPBUtilities_PackagePrivate.h | 19 ++--- objectivec/Tests/GPBArrayTests.m | 21 ++--- objectivec/Tests/GPBDictionaryTests+Bool.m | 19 +---- objectivec/Tests/GPBDictionaryTests+Int32.m | 5 +- objectivec/Tests/GPBDictionaryTests+Int64.m | 5 +- objectivec/Tests/GPBDictionaryTests+String.m | 10 +-- objectivec/Tests/GPBDictionaryTests+UInt32.m | 5 +- objectivec/Tests/GPBDictionaryTests+UInt64.m | 5 +- objectivec/Tests/GPBMessageTests+Merge.m | 66 +++----------- objectivec/Tests/GPBMessageTests+Runtime.m | 21 +++-- .../Tests/GPBMessageTests+Serialization.m | 16 ++-- objectivec/Tests/GPBUtilitiesTests.m | 6 ++ 27 files changed, 230 insertions(+), 359 deletions(-) diff --git a/objectivec/DevTools/pddm.py b/objectivec/DevTools/pddm.py index 60ff0894a1..11925b15d5 100755 --- a/objectivec/DevTools/pddm.py +++ b/objectivec/DevTools/pddm.py @@ -485,14 +485,13 @@ class SourceFile(object): if self._macro_collection: # Always add a blank line, seems to read better. (If need be, add an # option to the EXPAND to indicate if this should be done.) - result.extend([_GENERATED_CODE_LINE, '// clang-format off', '']) + result.extend([_GENERATED_CODE_LINE, '']) macro = line[directive_len:].strip() try: expand_result = self._macro_collection.Expand(macro) # Since expansions are line oriented, strip trailing whitespace # from the lines. lines = [x.rstrip() for x in expand_result.split('\n')] - lines.append('// clang-format on') result.append('\n'.join(lines)) except PDDMError as e: raise PDDMError('%s\n...while expanding "%s" from the section' diff --git a/objectivec/DevTools/pddm_tests.py b/objectivec/DevTools/pddm_tests.py index d5b88c93c7..2d9c47fba0 100755 --- a/objectivec/DevTools/pddm_tests.py +++ b/objectivec/DevTools/pddm_tests.py @@ -418,24 +418,18 @@ baz foo //%PDDM-EXPAND mumble(abc) // This block of code is generated, do not edit it directly. -// clang-format off abc: doAbc(int abc); -// clang-format on //%PDDM-EXPAND-END mumble(abc) bar //%PDDM-EXPAND mumble(def) // This block of code is generated, do not edit it directly. -// clang-format off def: doDef(int def); -// clang-format on //%PDDM-EXPAND mumble(ghi) // This block of code is generated, do not edit it directly. -// clang-format off ghi: doGhi(int ghi); -// clang-format on //%PDDM-EXPAND-END (2 expansions) baz //%PDDM-DEFINE mumble(a_) diff --git a/objectivec/GPBArray.h b/objectivec/GPBArray.h index 5aea75cd6e..4985dbe402 100644 --- a/objectivec/GPBArray.h +++ b/objectivec/GPBArray.h @@ -34,9 +34,11 @@ NS_ASSUME_NONNULL_BEGIN +// Disable clang-format for the macros. +// clang-format off + //%PDDM-EXPAND DECLARE_ARRAYS() // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Int32 @@ -135,7 +137,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -147,7 +150,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, + BOOL *stop))block; /** * Adds a value to this array. @@ -307,7 +311,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(uint32_t value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(uint32_t value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -319,7 +324,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(uint32_t value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(uint32_t value, NSUInteger idx, + BOOL *stop))block; /** * Adds a value to this array. @@ -479,7 +485,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int64_t value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int64_t value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -491,7 +498,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(int64_t value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(int64_t value, NSUInteger idx, + BOOL *stop))block; /** * Adds a value to this array. @@ -651,7 +659,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(uint64_t value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(uint64_t value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -663,7 +672,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(uint64_t value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(uint64_t value, NSUInteger idx, + BOOL *stop))block; /** * Adds a value to this array. @@ -823,7 +833,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(float value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(float value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -835,7 +846,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(float value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(float value, NSUInteger idx, + BOOL *stop))block; /** * Adds a value to this array. @@ -995,7 +1007,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(double value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(double value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -1007,7 +1020,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(double value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(double value, NSUInteger idx, + BOOL *stop))block; /** * Adds a value to this array. @@ -1167,7 +1181,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(BOOL value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(BOOL value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -1179,7 +1194,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(BOOL value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(BOOL value, NSUInteger idx, + BOOL *stop))block; /** * Adds a value to this array. @@ -1370,7 +1386,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -1382,7 +1399,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, + BOOL *stop))block; // These methods bypass the validationFunc to provide access to values that were not // known at the time the binary was compiled. @@ -1404,7 +1422,8 @@ NS_ASSUME_NONNULL_BEGIN * **idx**: The index of the current value. * **stop**: A pointer to a boolean that when set stops the enumeration. **/ -- (void)enumerateRawValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block; +- (void)enumerateRawValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, + BOOL *stop))block; /** * Enumerates the values on this array with the given block. @@ -1416,7 +1435,8 @@ NS_ASSUME_NONNULL_BEGIN * **stop**: A pointer to a boolean that when set stops the enumeration. **/ - (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block; + usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, + BOOL *stop))block; // If value is not a valid enumerator as defined by validationFunc, these // methods will assert in debug, and will log in release and assign the value @@ -1536,7 +1556,6 @@ NS_ASSUME_NONNULL_BEGIN @end -// clang-format on //%PDDM-EXPAND-END DECLARE_ARRAYS() NS_ASSUME_NONNULL_END @@ -1781,7 +1800,8 @@ NS_ASSUME_NONNULL_END //% * **idx**: The index of the current value. //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ -//%- (void)enumerateRawValuesWithBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, BOOL *stop))block; +//%- (void)enumerateRawValuesWithBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, +//% BOOL *stop))block; //% //%/** //% * Enumerates the values on this array with the given block. @@ -1793,7 +1813,8 @@ NS_ASSUME_NONNULL_END //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ //%- (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts -//% usingBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, BOOL *stop))block; +//% usingBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, +//% BOOL *stop))block; //% //%// If value is not a valid enumerator as defined by validationFunc, these //%// methods will assert in debug, and will log in release and assign the value @@ -1823,7 +1844,8 @@ NS_ASSUME_NONNULL_END //% * **idx**: The index of the current value. //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ -//%- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, BOOL *stop))block; +//%- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, +//% BOOL *stop))block; //% //%/** //% * Enumerates the values on this array with the given block. @@ -1835,7 +1857,8 @@ NS_ASSUME_NONNULL_END //% * **stop**: A pointer to a boolean that when set stops the enumeration. //% **/ //%- (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts -//% usingBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, BOOL *stop))block; +//% usingBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, +//% BOOL *stop))block; //%PDDM-DEFINE ARRAY_MUTABLE_INTERFACE(NAME, TYPE, HELPER_NAME) //%/** @@ -1967,3 +1990,5 @@ NS_ASSUME_NONNULL_END //% //%// No validation applies to these methods. //% + +// clang-format on diff --git a/objectivec/GPBArray.m b/objectivec/GPBArray.m index bb9a0777af..1db7a8f638 100644 --- a/objectivec/GPBArray.m +++ b/objectivec/GPBArray.m @@ -47,6 +47,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return (value != kGPBUnrecognizedEnumeratorValue); } +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE VALIDATE_RANGE(INDEX, COUNT) //% if (INDEX >= COUNT) { //% [NSException raise:NSRangeException @@ -194,12 +197,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { //% return result; //%} //% -//%- (void)enumerate##ACCESSOR_NAME##ValuesWithBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, BOOL *stop))block { +//%- (void)enumerate##ACCESSOR_NAME##ValuesWithBlock:(void(NS_NOESCAPE ^)(TYPE value, NSUInteger idx, BOOL *stop))block { //% [self enumerate##ACCESSOR_NAME##ValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; //%} //% //%- (void)enumerate##ACCESSOR_NAME##ValuesWithOptions:(NSEnumerationOptions)opts -//% ACCESSOR_NAME$S usingBlock:(void (NS_NOESCAPE ^)(TYPE value, NSUInteger idx, BOOL *stop))block { +//% ACCESSOR_NAME$S usingBlock:(void(NS_NOESCAPE ^)(TYPE value, NSUInteger idx, BOOL *stop))block { //% // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). //% BOOL stop = NO; //% if ((opts & NSEnumerationReverse) == 0) { @@ -292,10 +295,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { //% _values[idx2] = temp; //%} //% - //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Int32, int32_t, %d) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Int32 @@ -406,12 +407,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return result; } -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { @@ -542,10 +543,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(UInt32, uint32_t, %u) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - UInt32 @@ -656,12 +655,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return result; } -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(uint32_t value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(uint32_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(uint32_t value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(uint32_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { @@ -792,10 +791,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Int64, int64_t, %lld) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Int64 @@ -906,12 +903,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return result; } -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int64_t value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(int64_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(int64_t value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(int64_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { @@ -1042,10 +1039,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(UInt64, uint64_t, %llu) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - UInt64 @@ -1156,12 +1151,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return result; } -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(uint64_t value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(uint64_t value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(uint64_t value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(uint64_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { @@ -1292,10 +1287,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Float, float, %f) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Float @@ -1406,12 +1399,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return result; } -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(float value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(float value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(float value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(float value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { @@ -1542,10 +1535,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Double, double, %lf) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Double @@ -1656,12 +1647,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return result; } -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(double value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(double value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(double value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(double value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { @@ -1792,10 +1783,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_INTERFACE_SIMPLE(Bool, BOOL, %d) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool @@ -1906,12 +1895,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return result; } -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(BOOL value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(BOOL value, NSUInteger idx, BOOL *stop))block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(BOOL value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(BOOL value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { @@ -2042,9 +2031,10 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND-END (7 expansions) +// clang-format on + #pragma mark - Enum @implementation GPBEnumArray { @@ -2138,9 +2128,11 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { count:_count]; } +// Disable clang-format for the macros. +// clang-format off + //%PDDM-EXPAND ARRAY_IMMUTABLE_CORE(Enum, int32_t, Raw, %d) // This block of code is generated, do not edit it directly. -// clang-format off - (void)dealloc { NSAssert(!_autocreator, @@ -2180,12 +2172,12 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return result; } -- (void)enumerateRawValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateRawValuesWithBlock:(void(NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { [self enumerateRawValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateRawValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; if ((opts & NSEnumerationReverse) == 0) { @@ -2200,21 +2192,22 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } } } -// clang-format on //%PDDM-EXPAND-END ARRAY_IMMUTABLE_CORE(Enum, int32_t, Raw, %d) +// clang-format on + - (int32_t)valueAtIndex:(NSUInteger)index { +// clang-format off //%PDDM-EXPAND VALIDATE_RANGE(index, _count) // This block of code is generated, do not edit it directly. -// clang-format off if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } -// clang-format on //%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) +// clang-format on int32_t result = _values[index]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; @@ -2223,17 +2216,17 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (int32_t)rawValueAtIndex:(NSUInteger)index { +// clang-format off //%PDDM-EXPAND VALIDATE_RANGE(index, _count) // This block of code is generated, do not edit it directly. -// clang-format off if (index >= _count) { [NSException raise:NSRangeException format:@"Index (%lu) beyond bounds (%lu)", (unsigned long)index, (unsigned long)_count]; } -// clang-format on //%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) +// clang-format on return _values[index]; } @@ -2271,9 +2264,10 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } } +// clang-format off + //%PDDM-EXPAND ARRAY_MUTABLE_CORE(Enum, int32_t, Raw, %d) // This block of code is generated, do not edit it directly. -// clang-format off - (void)internalResizeToCapacity:(NSUInteger)newCapacity { _values = reallocf(_values, newCapacity * sizeof(int32_t)); @@ -2379,10 +2373,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { _values[idx2] = temp; } -// clang-format on //%PDDM-EXPAND MUTATION_METHODS(Enum, int32_t, , EnumValidationList, EnumValidationOne) // This block of code is generated, do not edit it directly. -// clang-format off - (void)addValue:(int32_t)value { [self addValues:&value count:1]; @@ -2449,7 +2441,6 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } _values[index] = value; } -// clang-format on //%PDDM-EXPAND-END (2 expansions) //%PDDM-DEFINE MUTATION_HOOK_EnumValidationList() @@ -2470,6 +2461,8 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { //% } //% +// clang-format on + @end #pragma mark - NSArray Subclass @@ -2556,17 +2549,17 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state - objects:(id __unsafe_unretained [])buffer + objects:(id __unsafe_unretained[])buffer count:(NSUInteger)len { return [_array countByEnumeratingWithState:state objects:buffer count:len]; } -- (void)enumerateObjectsUsingBlock:(void (NS_NOESCAPE ^)(id obj, NSUInteger idx, BOOL *stop))block { +- (void)enumerateObjectsUsingBlock:(void(NS_NOESCAPE ^)(id obj, NSUInteger idx, BOOL *stop))block { [_array enumerateObjectsUsingBlock:block]; } - (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(id obj, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(id obj, NSUInteger idx, BOOL *stop))block { [_array enumerateObjectsWithOptions:opts usingBlock:block]; } diff --git a/objectivec/GPBArray_PackagePrivate.h b/objectivec/GPBArray_PackagePrivate.h index 07eab89d6e..35a4538131 100644 --- a/objectivec/GPBArray_PackagePrivate.h +++ b/objectivec/GPBArray_PackagePrivate.h @@ -54,7 +54,6 @@ //%PDDM-EXPAND DECLARE_ARRAY_EXTRAS() // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Int32 @@ -120,7 +119,6 @@ } @end -// clang-format on //%PDDM-EXPAND-END DECLARE_ARRAY_EXTRAS() #pragma mark - NSArray Subclass diff --git a/objectivec/GPBCodedOutputStream.h b/objectivec/GPBCodedOutputStream.h index 5dde974e3a..304a24ef52 100644 --- a/objectivec/GPBCodedOutputStream.h +++ b/objectivec/GPBCodedOutputStream.h @@ -171,13 +171,13 @@ extern NSString *const GPBCodedOutputStreamException_WriteFailed; * @param offset The offset into the blob to start writing out. * @param length The number of bytes from the blob to write out. **/ -- (void)writeRawPtr:(const void *)data - offset:(size_t)offset - length:(size_t)length; +- (void)writeRawPtr:(const void *)data offset:(size_t)offset length:(size_t)length; + +// Disable clang-format for the macros. +// clang-format off //%PDDM-EXPAND _WRITE_DECLS() // This block of code is generated, do not edit it directly. -// clang-format off /** * Write a double for the given field number. @@ -631,9 +631,10 @@ extern NSString *const GPBCodedOutputStreamException_WriteFailed; - (void)writeUnknownGroupNoTag:(int32_t)fieldNumber value:(GPBUnknownFieldSet *)value; -// clang-format on //%PDDM-EXPAND-END _WRITE_DECLS() +// clang-format on + /** Write a MessageSet extension field to the stream. For historical reasons, the wire format differs from normal fields. @@ -656,6 +657,9 @@ reasons, the wire format differs from normal fields. NS_ASSUME_NONNULL_END +// Disable clang-format for the macros. +// clang-format off + // Write methods for types that can be in packed arrays. //%PDDM-DEFINE _WRITE_PACKABLE_DECLS(NAME, ARRAY_TYPE, TYPE) //%/** @@ -755,3 +759,5 @@ NS_ASSUME_NONNULL_END //%_WRITE_UNPACKABLE_DECLS(Bytes, NSData) //%_WRITE_GROUP_DECLS(Group, GPBMessage) //%_WRITE_GROUP_DECLS(UnknownGroup, GPBUnknownFieldSet) + +// clang-format on diff --git a/objectivec/GPBCodedOutputStream.m b/objectivec/GPBCodedOutputStream.m index 4e2a51413a..5a147aa7c6 100644 --- a/objectivec/GPBCodedOutputStream.m +++ b/objectivec/GPBCodedOutputStream.m @@ -418,6 +418,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, GPBWriteRawVarint64(&state_, GPBEncodeZigZag64(value)); } +// clang-format off + //%PDDM-DEFINE WRITE_PACKABLE_DEFNS(NAME, ARRAY_TYPE, TYPE, ACCESSOR_NAME) //%- (void)write##NAME##Array:(int32_t)fieldNumber //% NAME$S values:(GPB##ARRAY_TYPE##Array *)values @@ -452,7 +454,6 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, //% //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Double, Double, double, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeDoubleArray:(int32_t)fieldNumber values:(GPBDoubleArray *)values @@ -478,10 +479,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Float, Float, float, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeFloatArray:(int32_t)fieldNumber values:(GPBFloatArray *)values @@ -507,10 +506,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(UInt64, UInt64, uint64_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeUInt64Array:(int32_t)fieldNumber values:(GPBUInt64Array *)values @@ -536,10 +533,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Int64, Int64, int64_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeInt64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values @@ -565,10 +560,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Int32, Int32, int32_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeInt32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values @@ -594,10 +587,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(UInt32, UInt32, uint32_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeUInt32Array:(int32_t)fieldNumber values:(GPBUInt32Array *)values @@ -623,10 +614,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Fixed64, UInt64, uint64_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeFixed64Array:(int32_t)fieldNumber values:(GPBUInt64Array *)values @@ -652,10 +641,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Fixed32, UInt32, uint32_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeFixed32Array:(int32_t)fieldNumber values:(GPBUInt32Array *)values @@ -681,10 +668,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SInt32, Int32, int32_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeSInt32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values @@ -710,10 +695,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SInt64, Int64, int64_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeSInt64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values @@ -739,10 +722,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SFixed64, Int64, int64_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeSFixed64Array:(int32_t)fieldNumber values:(GPBInt64Array *)values @@ -768,10 +749,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(SFixed32, Int32, int32_t, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeSFixed32Array:(int32_t)fieldNumber values:(GPBInt32Array *)values @@ -797,10 +776,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Bool, Bool, BOOL, ) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeBoolArray:(int32_t)fieldNumber values:(GPBBoolArray *)values @@ -826,10 +803,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_PACKABLE_DEFNS(Enum, Enum, int32_t, Raw) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeEnumArray:(int32_t)fieldNumber values:(GPBEnumArray *)values @@ -855,10 +830,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(String, NSString) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeStringArray:(int32_t)fieldNumber values:(NSArray *)values { for (NSString *value in values) { @@ -866,10 +839,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Message, GPBMessage) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeMessageArray:(int32_t)fieldNumber values:(NSArray *)values { for (GPBMessage *value in values) { @@ -877,10 +848,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Bytes, NSData) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeBytesArray:(int32_t)fieldNumber values:(NSArray *)values { for (NSData *value in values) { @@ -888,10 +857,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(Group, GPBMessage) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeGroupArray:(int32_t)fieldNumber values:(NSArray *)values { for (GPBMessage *value in values) { @@ -899,10 +866,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND WRITE_UNPACKABLE_DEFNS(UnknownGroup, GPBUnknownFieldSet) // This block of code is generated, do not edit it directly. -// clang-format off - (void)writeUnknownGroupArray:(int32_t)fieldNumber values:(NSArray *)values { for (GPBUnknownFieldSet *value in values) { @@ -910,9 +875,10 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } } -// clang-format on //%PDDM-EXPAND-END (19 expansions) +// clang-format on + - (void)writeMessageSetExtension:(int32_t)fieldNumber value:(GPBMessage *)value { GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, diff --git a/objectivec/GPBDictionary.h b/objectivec/GPBDictionary.h index 28d880d6f7..90440e3f41 100644 --- a/objectivec/GPBDictionary.h +++ b/objectivec/GPBDictionary.h @@ -43,9 +43,11 @@ NS_ASSUME_NONNULL_BEGIN +// Disable clang-format for the macros. +// clang-format off + //%PDDM-EXPAND DECLARE_DICTIONARIES() // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - UInt32 -> UInt32 @@ -5479,7 +5481,6 @@ NS_ASSUME_NONNULL_BEGIN @end -// clang-format on //%PDDM-EXPAND-END DECLARE_DICTIONARIES() NS_ASSUME_NONNULL_END @@ -5770,3 +5771,5 @@ NS_ASSUME_NONNULL_END //% **/ //%- (void)setRawValue:(VALUE_TYPE)rawValue forKey:(KEY_TYPE##KisP$S##KisP)key; //% + +// clang-format on diff --git a/objectivec/GPBDictionary.m b/objectivec/GPBDictionary.m index 77642c27f9..ccb2554444 100644 --- a/objectivec/GPBDictionary.m +++ b/objectivec/GPBDictionary.m @@ -73,6 +73,9 @@ static BOOL DictDefault_IsValidValue(int32_t value) { return (value != kGPBUnrecognizedEnumeratorValue); } +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE SERIALIZE_SUPPORT_2_TYPE(VALUE_NAME, VALUE_TYPE, GPBDATATYPE_NAME1, GPBDATATYPE_NAME2) //%static size_t ComputeDict##VALUE_NAME##FieldSize(VALUE_TYPE value, uint32_t fieldNum, GPBDataType dataType) { //% if (dataType == GPBDataType##GPBDATATYPE_NAME1) { @@ -147,7 +150,6 @@ static BOOL DictDefault_IsValidValue(int32_t value) { //%SERIALIZE_SUPPORT_3_TYPE(Object, id, Message, String, Bytes) //%PDDM-EXPAND SERIALIZE_SUPPORT_HELPERS() // This block of code is generated, do not edit it directly. -// clang-format off static size_t ComputeDictInt32FieldSize(int32_t value, uint32_t fieldNum, GPBDataType dataType) { if (dataType == GPBDataTypeInt32) { @@ -326,9 +328,10 @@ static void WriteDictObjectField(GPBCodedOutputStream *stream, id value, uint32_ } } -// clang-format on //%PDDM-EXPAND-END SERIALIZE_SUPPORT_HELPERS() +// clang-format on + size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) { GPBDataType mapValueType = GPBGetFieldDataType(field); size_t result = 0; @@ -570,6 +573,9 @@ void GPBDictionaryReadEntry(id mapDictionary, // Macros for the common basic cases. // +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE DICTIONARY_IMPL_FOR_POD_KEY(KEY_NAME, KEY_TYPE) //%DICTIONARY_POD_IMPL_FOR_KEY(KEY_NAME, KEY_TYPE, , POD) //%DICTIONARY_POD_KEY_TO_OBJECT_IMPL(KEY_NAME, KEY_TYPE, Object, id) @@ -1429,7 +1435,6 @@ void GPBDictionaryReadEntry(id mapDictionary, //%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(UInt32, uint32_t) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - UInt32 -> UInt32 @@ -3176,10 +3181,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(Int32, int32_t) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Int32 -> UInt32 @@ -4926,10 +4929,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(UInt64, uint64_t) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - UInt64 -> UInt32 @@ -6676,10 +6677,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_IMPL_FOR_POD_KEY(Int64, int64_t) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Int64 -> UInt32 @@ -8426,10 +8425,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_POD_IMPL_FOR_KEY(String, NSString, *, OBJECT) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - String -> UInt32 @@ -10032,13 +10029,11 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND-END (5 expansions) //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(UInt32, uint32_t) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> UInt32 @@ -10246,10 +10241,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Int32, int32_t) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Int32 @@ -10457,10 +10450,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(UInt64, uint64_t) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> UInt64 @@ -10668,10 +10659,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Int64, int64_t) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Int64 @@ -10879,10 +10868,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Bool, BOOL) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Bool @@ -11090,10 +11077,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Float, float) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Float @@ -11301,10 +11286,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_POD_IMPL(Double, double) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Double @@ -11512,10 +11495,8 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND DICTIONARY_BOOL_KEY_TO_OBJECT_IMPL(Object, id) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Object @@ -11744,9 +11725,10 @@ void GPBDictionaryReadEntry(id mapDictionary, @end -// clang-format on //%PDDM-EXPAND-END (8 expansions) +// clang-format on + #pragma mark - Bool -> Enum @implementation GPBBoolEnumDictionary { @@ -11916,9 +11898,10 @@ void GPBDictionaryReadEntry(id mapDictionary, } } +// clang-format off + //%PDDM-EXPAND SERIAL_DATA_FOR_ENTRY_POD_Enum(Bool) // This block of code is generated, do not edit it directly. -// clang-format off - (NSData *)serializedDataForUnknownValue:(int32_t)value forKey:(GPBGenericValue *)key @@ -11933,9 +11916,10 @@ void GPBDictionaryReadEntry(id mapDictionary, return data; } -// clang-format on //%PDDM-EXPAND-END SERIAL_DATA_FOR_ENTRY_POD_Enum(Bool) +// clang-format on + - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field { GPBDataType valueDataType = GPBGetFieldDataType(field); NSUInteger count = 0; diff --git a/objectivec/GPBDictionary_PackagePrivate.h b/objectivec/GPBDictionary_PackagePrivate.h index d494b7ee88..82f053e7bf 100644 --- a/objectivec/GPBDictionary_PackagePrivate.h +++ b/objectivec/GPBDictionary_PackagePrivate.h @@ -46,6 +46,9 @@ - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block; @end +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(KEY_NAME) //%DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(KEY_NAME) //%DICTIONARY_PRIVATE_INTERFACES(KEY_NAME, Object, Object) @@ -82,7 +85,6 @@ //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(UInt32) // This block of code is generated, do not edit it directly. -// clang-format off @interface GPBUInt32UInt32Dictionary () { @package @@ -144,10 +146,8 @@ __attribute__((ns_returns_retained)); @end -// clang-format on //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Int32) // This block of code is generated, do not edit it directly. -// clang-format off @interface GPBInt32UInt32Dictionary () { @package @@ -209,10 +209,8 @@ __attribute__((ns_returns_retained)); @end -// clang-format on //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(UInt64) // This block of code is generated, do not edit it directly. -// clang-format off @interface GPBUInt64UInt32Dictionary () { @package @@ -274,10 +272,8 @@ __attribute__((ns_returns_retained)); @end -// clang-format on //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Int64) // This block of code is generated, do not edit it directly. -// clang-format off @interface GPBInt64UInt32Dictionary () { @package @@ -339,10 +335,8 @@ __attribute__((ns_returns_retained)); @end -// clang-format on //%PDDM-EXPAND DICTIONARY_PRIV_INTERFACES_FOR_POD_KEY(Bool) // This block of code is generated, do not edit it directly. -// clang-format off @interface GPBBoolUInt32Dictionary () { @package @@ -404,10 +398,8 @@ __attribute__((ns_returns_retained)); @end -// clang-format on //%PDDM-EXPAND DICTIONARY_POD_PRIV_INTERFACES_FOR_KEY(String) // This block of code is generated, do not edit it directly. -// clang-format off @interface GPBStringUInt32Dictionary () { @package @@ -460,9 +452,10 @@ keyDataType:(GPBDataType)keyDataType; @end -// clang-format on //%PDDM-EXPAND-END (6 expansions) +// clang-format on + #pragma mark - NSDictionary Subclass @interface GPBAutocreatedDictionary : NSMutableDictionary { diff --git a/objectivec/GPBMessage.m b/objectivec/GPBMessage.m index b293604608..b494f36418 100644 --- a/objectivec/GPBMessage.m +++ b/objectivec/GPBMessage.m @@ -1344,6 +1344,10 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } uint32_t fieldNumber = GPBFieldNumber(field); + switch (GPBGetFieldDataType(field)) { + +// clang-format off + //%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE) //%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE) //%PDDM-DEFINE FIELD_CASE_FULL(TYPE, REAL_TYPE, ARRAY_TYPE) @@ -1386,12 +1390,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { //% } //% break; //% - - switch (GPBGetFieldDataType(field)) { - //%PDDM-EXPAND FIELD_CASE(Bool, Bool) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeBool: if (fieldType == GPBFieldTypeRepeated) { @@ -1410,10 +1410,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(Fixed32, UInt32) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeFixed32: if (fieldType == GPBFieldTypeRepeated) { @@ -1432,10 +1430,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(SFixed32, Int32) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeSFixed32: if (fieldType == GPBFieldTypeRepeated) { @@ -1454,10 +1450,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(Float, Float) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeFloat: if (fieldType == GPBFieldTypeRepeated) { @@ -1476,10 +1470,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(Fixed64, UInt64) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeFixed64: if (fieldType == GPBFieldTypeRepeated) { @@ -1498,10 +1490,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(SFixed64, Int64) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeSFixed64: if (fieldType == GPBFieldTypeRepeated) { @@ -1520,10 +1510,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(Double, Double) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeDouble: if (fieldType == GPBFieldTypeRepeated) { @@ -1542,10 +1530,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(Int32, Int32) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeInt32: if (fieldType == GPBFieldTypeRepeated) { @@ -1564,10 +1550,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(Int64, Int64) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeInt64: if (fieldType == GPBFieldTypeRepeated) { @@ -1586,10 +1570,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(SInt32, Int32) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeSInt32: if (fieldType == GPBFieldTypeRepeated) { @@ -1608,10 +1590,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(SInt64, Int64) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeSInt64: if (fieldType == GPBFieldTypeRepeated) { @@ -1630,10 +1610,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(UInt32, UInt32) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeUInt32: if (fieldType == GPBFieldTypeRepeated) { @@ -1652,10 +1630,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE(UInt64, UInt64) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeUInt64: if (fieldType == GPBFieldTypeRepeated) { @@ -1674,10 +1650,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE_FULL(Enum, Int32, Enum) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeEnum: if (fieldType == GPBFieldTypeRepeated) { @@ -1696,10 +1670,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE2(Bytes) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeBytes: if (fieldType == GPBFieldTypeRepeated) { @@ -1722,10 +1694,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE2(String) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeString: if (fieldType == GPBFieldTypeRepeated) { @@ -1748,10 +1718,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE2(Message) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeMessage: if (fieldType == GPBFieldTypeRepeated) { @@ -1774,10 +1742,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND FIELD_CASE2(Group) // This block of code is generated, do not edit it directly. -// clang-format off case GPBDataTypeGroup: if (fieldType == GPBFieldTypeRepeated) { @@ -1800,8 +1766,9 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } break; -// clang-format on //%PDDM-EXPAND-END (18 expansions) + +// clang-format off } } diff --git a/objectivec/GPBProtocolBuffers.h b/objectivec/GPBProtocolBuffers.h index 619c08228b..e5f4713c93 100644 --- a/objectivec/GPBProtocolBuffers.h +++ b/objectivec/GPBProtocolBuffers.h @@ -28,7 +28,9 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// clang-format off #import "GPBBootstrap.h" +// clang-format on #import "GPBArray.h" #import "GPBCodedInputStream.h" diff --git a/objectivec/GPBProtocolBuffers_RuntimeSupport.h b/objectivec/GPBProtocolBuffers_RuntimeSupport.h index 04dde620a2..804a68a73b 100644 --- a/objectivec/GPBProtocolBuffers_RuntimeSupport.h +++ b/objectivec/GPBProtocolBuffers_RuntimeSupport.h @@ -31,7 +31,9 @@ // This header is meant to only be used by the generated source, it should not // be included in code using protocol buffers. +// clang-format off #import "GPBBootstrap.h" +// clang-format on #import "GPBDescriptor_PackagePrivate.h" #import "GPBExtensionInternals.h" diff --git a/objectivec/GPBUtilities.h b/objectivec/GPBUtilities.h index 75759b2334..fd5a4634a5 100644 --- a/objectivec/GPBUtilities.h +++ b/objectivec/GPBUtilities.h @@ -102,9 +102,11 @@ void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field); **/ void GPBClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof); +// Disable clang-format for the macros. +// clang-format off + //%PDDM-EXPAND GPB_ACCESSORS() // This block of code is generated, do not edit it directly. -// clang-format off // @@ -395,9 +397,10 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, id dictionary); -// clang-format on //%PDDM-EXPAND-END GPB_ACCESSORS() +// clang-format on + /** * Returns an empty NSData to assign to byte fields when you wish to assign them * to empty. Prevents allocating a lot of little [NSData data] objects. @@ -413,6 +416,8 @@ NS_ASSUME_NONNULL_END CF_EXTERN_C_END +// Disable clang-format for the macros. +// clang-format off //%PDDM-DEFINE GPB_ACCESSORS() //% @@ -549,3 +554,5 @@ CF_EXTERN_C_END //% **/ //%void GPBSetMessage##NAME##Field(GPBMessage *self, GPBFieldDescriptor *field, TYPE TisP##value); //% + +// clang-format on diff --git a/objectivec/GPBUtilities.m b/objectivec/GPBUtilities.m index cd0910c577..739e36cdeb 100644 --- a/objectivec/GPBUtilities.m +++ b/objectivec/GPBUtilities.m @@ -371,6 +371,8 @@ static void GPBMaybeClearOneofPrivate(GPBMessage *self, #pragma mark - IVar accessors +// clang-format off + //%PDDM-DEFINE IVAR_POD_ACCESSORS_DEFN(NAME, TYPE) //%TYPE GPBGetMessage##NAME##Field(GPBMessage *self, //% TYPE$S NAME$S GPBFieldDescriptor *field) { @@ -501,6 +503,8 @@ static void GPBMaybeClearOneofPrivate(GPBMessage *self, //%} //% +// clang-format on + // Object types are handled slightly differently, they need to be released // and retained. @@ -804,9 +808,10 @@ void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self, GPBBecomeVisibleToAutocreator(self); } +// clang-format off + //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int32, int32_t) // This block of code is generated, do not edit it directly. -// clang-format off int32_t GPBGetMessageInt32Field(GPBMessage *self, GPBFieldDescriptor *field) { @@ -876,10 +881,8 @@ void GPBSetInt32IvarWithFieldPrivate(GPBMessage *self, GPBBecomeVisibleToAutocreator(self); } -// clang-format on //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt32, uint32_t) // This block of code is generated, do not edit it directly. -// clang-format off uint32_t GPBGetMessageUInt32Field(GPBMessage *self, GPBFieldDescriptor *field) { @@ -949,10 +952,8 @@ void GPBSetUInt32IvarWithFieldPrivate(GPBMessage *self, GPBBecomeVisibleToAutocreator(self); } -// clang-format on //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Int64, int64_t) // This block of code is generated, do not edit it directly. -// clang-format off int64_t GPBGetMessageInt64Field(GPBMessage *self, GPBFieldDescriptor *field) { @@ -1022,10 +1023,8 @@ void GPBSetInt64IvarWithFieldPrivate(GPBMessage *self, GPBBecomeVisibleToAutocreator(self); } -// clang-format on //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(UInt64, uint64_t) // This block of code is generated, do not edit it directly. -// clang-format off uint64_t GPBGetMessageUInt64Field(GPBMessage *self, GPBFieldDescriptor *field) { @@ -1095,10 +1094,8 @@ void GPBSetUInt64IvarWithFieldPrivate(GPBMessage *self, GPBBecomeVisibleToAutocreator(self); } -// clang-format on //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Float, float) // This block of code is generated, do not edit it directly. -// clang-format off float GPBGetMessageFloatField(GPBMessage *self, GPBFieldDescriptor *field) { @@ -1168,10 +1165,8 @@ void GPBSetFloatIvarWithFieldPrivate(GPBMessage *self, GPBBecomeVisibleToAutocreator(self); } -// clang-format on //%PDDM-EXPAND IVAR_POD_ACCESSORS_DEFN(Double, double) // This block of code is generated, do not edit it directly. -// clang-format off double GPBGetMessageDoubleField(GPBMessage *self, GPBFieldDescriptor *field) { @@ -1241,14 +1236,12 @@ void GPBSetDoubleIvarWithFieldPrivate(GPBMessage *self, GPBBecomeVisibleToAutocreator(self); } -// clang-format on //%PDDM-EXPAND-END (6 expansions) // Aliases are function calls that are virtually the same. //%PDDM-EXPAND IVAR_ALIAS_DEFN_COPY_OBJECT(String, NSString) // This block of code is generated, do not edit it directly. -// clang-format off // Only exists for public api, no core code should use this. NSString *GPBGetMessageStringField(GPBMessage *self, @@ -1279,10 +1272,8 @@ void GPBSetMessageStringField(GPBMessage *self, GPBSetCopyObjectIvarWithField(self, field, (id)value); } -// clang-format on //%PDDM-EXPAND IVAR_ALIAS_DEFN_COPY_OBJECT(Bytes, NSData) // This block of code is generated, do not edit it directly. -// clang-format off // Only exists for public api, no core code should use this. NSData *GPBGetMessageBytesField(GPBMessage *self, @@ -1313,10 +1304,8 @@ void GPBSetMessageBytesField(GPBMessage *self, GPBSetCopyObjectIvarWithField(self, field, (id)value); } -// clang-format on //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Message, GPBMessage) // This block of code is generated, do not edit it directly. -// clang-format off // Only exists for public api, no core code should use this. GPBMessage *GPBGetMessageMessageField(GPBMessage *self, @@ -1347,10 +1336,8 @@ void GPBSetMessageMessageField(GPBMessage *self, GPBSetObjectIvarWithField(self, field, (id)value); } -// clang-format on //%PDDM-EXPAND IVAR_ALIAS_DEFN_OBJECT(Group, GPBMessage) // This block of code is generated, do not edit it directly. -// clang-format off // Only exists for public api, no core code should use this. GPBMessage *GPBGetMessageGroupField(GPBMessage *self, @@ -1381,9 +1368,10 @@ void GPBSetMessageGroupField(GPBMessage *self, GPBSetObjectIvarWithField(self, field, (id)value); } -// clang-format on //%PDDM-EXPAND-END (4 expansions) +// clang-format on + // GPBGetMessageRepeatedField is defined in GPBMessage.m // Only exists for public api, no core code should use this. @@ -2050,12 +2038,12 @@ NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \ _Pragma("unused(idx, stop)"); \ [result \ - appendFormat:@"%@%d: " #FORMAT "\n", lineIndent, fieldNumber, value]; \ + appendFormat:@"%@%d: " FORMAT "\n", lineIndent, fieldNumber, value]; \ }]; - PRINT_LOOP(varintList, uint64_t, %llu); - PRINT_LOOP(fixed32List, uint32_t, 0x%X); - PRINT_LOOP(fixed64List, uint64_t, 0x%llX); + PRINT_LOOP(varintList, uint64_t, "%llu"); + PRINT_LOOP(fixed32List, uint32_t, "0x%X"); + PRINT_LOOP(fixed64List, uint64_t, "0x%llX"); #undef PRINT_LOOP diff --git a/objectivec/GPBUtilities_PackagePrivate.h b/objectivec/GPBUtilities_PackagePrivate.h index 3d3d7349ec..042396b4d8 100644 --- a/objectivec/GPBUtilities_PackagePrivate.h +++ b/objectivec/GPBUtilities_PackagePrivate.h @@ -209,68 +209,59 @@ GPBGetHasIvarField(GPBMessage *self, GPBFieldDescriptor *field) { #pragma clang diagnostic pop +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE GPB_IVAR_SET_DECL(NAME, TYPE) //%void GPBSet##NAME##IvarWithFieldPrivate(GPBMessage *self, //% NAME$S GPBFieldDescriptor *field, //% NAME$S TYPE value); //%PDDM-EXPAND GPB_IVAR_SET_DECL(Bool, BOOL) // This block of code is generated, do not edit it directly. -// clang-format off void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, BOOL value); -// clang-format on //%PDDM-EXPAND GPB_IVAR_SET_DECL(Int32, int32_t) // This block of code is generated, do not edit it directly. -// clang-format off void GPBSetInt32IvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, int32_t value); -// clang-format on //%PDDM-EXPAND GPB_IVAR_SET_DECL(UInt32, uint32_t) // This block of code is generated, do not edit it directly. -// clang-format off void GPBSetUInt32IvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, uint32_t value); -// clang-format on //%PDDM-EXPAND GPB_IVAR_SET_DECL(Int64, int64_t) // This block of code is generated, do not edit it directly. -// clang-format off void GPBSetInt64IvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, int64_t value); -// clang-format on //%PDDM-EXPAND GPB_IVAR_SET_DECL(UInt64, uint64_t) // This block of code is generated, do not edit it directly. -// clang-format off void GPBSetUInt64IvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, uint64_t value); -// clang-format on //%PDDM-EXPAND GPB_IVAR_SET_DECL(Float, float) // This block of code is generated, do not edit it directly. -// clang-format off void GPBSetFloatIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, float value); -// clang-format on //%PDDM-EXPAND GPB_IVAR_SET_DECL(Double, double) // This block of code is generated, do not edit it directly. -// clang-format off void GPBSetDoubleIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, double value); -// clang-format on //%PDDM-EXPAND-END (7 expansions) +// clang-format on + void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, int32_t value); diff --git a/objectivec/Tests/GPBArrayTests.m b/objectivec/Tests/GPBArrayTests.m index 9b004bc338..6bb5c1da27 100644 --- a/objectivec/Tests/GPBArrayTests.m +++ b/objectivec/Tests/GPBArrayTests.m @@ -87,6 +87,9 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { #pragma mark - PDDM Macros +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE ARRAY_TESTS(NAME, TYPE, VAL1, VAL2, VAL3, VAL4) //%ARRAY_TESTS2(NAME, TYPE, VAL1, VAL2, VAL3, VAL4, ) //%PDDM-DEFINE ARRAY_TESTS2(NAME, TYPE, VAL1, VAL2, VAL3, VAL4, HELPER) @@ -433,7 +436,6 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { //% //%PDDM-EXPAND ARRAY_TESTS(Int32, int32_t, 1, 2, 3, 4) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Int32 @@ -776,10 +778,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_TESTS(UInt32, uint32_t, 11U, 12U, 13U, 14U) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - UInt32 @@ -1122,10 +1122,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_TESTS(Int64, int64_t, 31LL, 32LL, 33LL, 34LL) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Int64 @@ -1468,10 +1466,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_TESTS(UInt64, uint64_t, 41ULL, 42ULL, 43ULL, 44ULL) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - UInt64 @@ -1814,10 +1810,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_TESTS(Float, float, 51.f, 52.f, 53.f, 54.f) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Float @@ -2160,10 +2154,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_TESTS(Double, double, 61., 62., 63., 64.) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Double @@ -2506,10 +2498,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_TESTS(Bool, BOOL, TRUE, TRUE, FALSE, FALSE) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool @@ -2852,10 +2842,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @end -// clang-format on //%PDDM-EXPAND ARRAY_TESTS2(Enum, int32_t, 71, 72, 73, 74, Raw) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Enum @@ -3198,9 +3186,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @end -// clang-format on //%PDDM-EXPAND-END (8 expansions) +// clang-format on + #pragma mark - Non macro-based Enum tests // These are hand written tests to cover the verification and raw methods. diff --git a/objectivec/Tests/GPBDictionaryTests+Bool.m b/objectivec/Tests/GPBDictionaryTests+Bool.m index fbab9ffbd1..ea4e79a1f7 100644 --- a/objectivec/Tests/GPBDictionaryTests+Bool.m +++ b/objectivec/Tests/GPBDictionaryTests+Bool.m @@ -36,13 +36,15 @@ #import "GPBTestUtilities.h" #import "objectivec/Tests/UnittestRuntimeProto2.pbobjc.h" +// Disable clang-format for the macros. +// clang-format off + // Pull in the macros (using an external file because expanding all tests // in a single file makes a file that is failing to work with within Xcode. //%PDDM-IMPORT-DEFINES GPBDictionaryTests.pddm //%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(UInt32, uint32_t, 100U, 101U) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> UInt32 @@ -346,10 +348,8 @@ @end -// clang-format on //%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Int32, int32_t, 200, 201) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Int32 @@ -653,10 +653,8 @@ @end -// clang-format on //%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(UInt64, uint64_t, 300U, 301U) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> UInt64 @@ -960,10 +958,8 @@ @end -// clang-format on //%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Int64, int64_t, 400, 401) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Int64 @@ -1267,10 +1263,8 @@ @end -// clang-format on //%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Bool, BOOL, NO, YES) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Bool @@ -1574,10 +1568,8 @@ @end -// clang-format on //%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Float, float, 500.f, 501.f) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Float @@ -1881,10 +1873,8 @@ @end -// clang-format on //%PDDM-EXPAND BOOL_TESTS_FOR_POD_VALUE(Double, double, 600., 601.) // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Double @@ -2188,10 +2178,8 @@ @end -// clang-format on //%PDDM-EXPAND TESTS_FOR_BOOL_KEY_OBJECT_VALUE(Object, NSString*, @"abc", @"def") // This block of code is generated, do not edit it directly. -// clang-format off #pragma mark - Bool -> Object @@ -2460,7 +2448,6 @@ @end -// clang-format on //%PDDM-EXPAND-END (8 expansions) diff --git a/objectivec/Tests/GPBDictionaryTests+Int32.m b/objectivec/Tests/GPBDictionaryTests+Int32.m index 3ffdd2164a..0b46b0fcff 100644 --- a/objectivec/Tests/GPBDictionaryTests+Int32.m +++ b/objectivec/Tests/GPBDictionaryTests+Int32.m @@ -36,13 +36,15 @@ #import "GPBTestUtilities.h" #import "objectivec/Tests/UnittestRuntimeProto2.pbobjc.h" +// Disable clang-format for the macros. +// clang-format off + // Pull in the macros (using an external file because expanding all tests // in a single file makes a file that is failing to work with within Xcode. //%PDDM-IMPORT-DEFINES GPBDictionaryTests.pddm //%PDDM-EXPAND TEST_FOR_POD_KEY(Int32, int32_t, 11, 12, 13, 14) // This block of code is generated, do not edit it directly. -// clang-format off // To let the testing macros work, add some extra methods to simplify things. @interface GPBInt32EnumDictionary (TestingTweak) @@ -3673,6 +3675,5 @@ static BOOL TestingEnum_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND-END TEST_FOR_POD_KEY(Int32, int32_t, 11, 12, 13, 14) diff --git a/objectivec/Tests/GPBDictionaryTests+Int64.m b/objectivec/Tests/GPBDictionaryTests+Int64.m index 9d8a946659..9456791811 100644 --- a/objectivec/Tests/GPBDictionaryTests+Int64.m +++ b/objectivec/Tests/GPBDictionaryTests+Int64.m @@ -36,13 +36,15 @@ #import "GPBTestUtilities.h" #import "objectivec/Tests/UnittestRuntimeProto2.pbobjc.h" +// Disable clang-format for the macros. +// clang-format off + // Pull in the macros (using an external file because expanding all tests // in a single file makes a file that is failing to work with within Xcode. //%PDDM-IMPORT-DEFINES GPBDictionaryTests.pddm //%PDDM-EXPAND TEST_FOR_POD_KEY(Int64, int64_t, 21LL, 22LL, 23LL, 24LL) // This block of code is generated, do not edit it directly. -// clang-format off // To let the testing macros work, add some extra methods to simplify things. @interface GPBInt64EnumDictionary (TestingTweak) @@ -3673,6 +3675,5 @@ static BOOL TestingEnum_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND-END TEST_FOR_POD_KEY(Int64, int64_t, 21LL, 22LL, 23LL, 24LL) diff --git a/objectivec/Tests/GPBDictionaryTests+String.m b/objectivec/Tests/GPBDictionaryTests+String.m index c2fdac3a2a..181dfc6240 100644 --- a/objectivec/Tests/GPBDictionaryTests+String.m +++ b/objectivec/Tests/GPBDictionaryTests+String.m @@ -36,13 +36,15 @@ #import "GPBTestUtilities.h" #import "objectivec/Tests/UnittestRuntimeProto2.pbobjc.h" +// Disable clang-format for the macros. +// clang-format off + // Pull in the macros (using an external file because expanding all tests // in a single file makes a file that is failing to work with within Xcode. //%PDDM-IMPORT-DEFINES GPBDictionaryTests.pddm -//%PDDM-EXPAND TESTS_FOR_POD_VALUES(String, NSString, *, Objects, @"foo", @"bar", @"baz", @"mumble") +//%PDDM-EXPAND TESTS_FOR_POD_VALUES(String,NSString,*,Objects,@"foo",@"bar",@"baz",@"mumble") // This block of code is generated, do not edit it directly. -// clang-format off // To let the testing macros work, add some extra methods to simplify things. @interface GPBStringEnumDictionary (TestingTweak) @@ -3381,6 +3383,4 @@ static BOOL TestingEnum_IsValidValue(int32_t value) { @end -// clang-format on -//%PDDM-EXPAND-END TESTS_FOR_POD_VALUES(String, NSString, *, Objects, @"foo", @"bar", @"baz", @"mumble") - +//%PDDM-EXPAND-END TESTS_FOR_POD_VALUES(String,NSString,*,Objects,@"foo",@"bar",@"baz",@"mumble") diff --git a/objectivec/Tests/GPBDictionaryTests+UInt32.m b/objectivec/Tests/GPBDictionaryTests+UInt32.m index a00dd625b3..edc2e7457d 100644 --- a/objectivec/Tests/GPBDictionaryTests+UInt32.m +++ b/objectivec/Tests/GPBDictionaryTests+UInt32.m @@ -36,13 +36,15 @@ #import "GPBTestUtilities.h" #import "objectivec/Tests/UnittestRuntimeProto2.pbobjc.h" +// Disable clang-format for the macros. +// clang-format off + // Pull in the macros (using an external file because expanding all tests // in a single file makes a file that is failing to work with within Xcode. //%PDDM-IMPORT-DEFINES GPBDictionaryTests.pddm //%PDDM-EXPAND TEST_FOR_POD_KEY(UInt32, uint32_t, 1U, 2U, 3U, 4U) // This block of code is generated, do not edit it directly. -// clang-format off // To let the testing macros work, add some extra methods to simplify things. @interface GPBUInt32EnumDictionary (TestingTweak) @@ -3673,6 +3675,5 @@ static BOOL TestingEnum_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND-END TEST_FOR_POD_KEY(UInt32, uint32_t, 1U, 2U, 3U, 4U) diff --git a/objectivec/Tests/GPBDictionaryTests+UInt64.m b/objectivec/Tests/GPBDictionaryTests+UInt64.m index e1ac1437f7..7f6c9838fd 100644 --- a/objectivec/Tests/GPBDictionaryTests+UInt64.m +++ b/objectivec/Tests/GPBDictionaryTests+UInt64.m @@ -36,13 +36,15 @@ #import "GPBTestUtilities.h" #import "objectivec/Tests/UnittestRuntimeProto2.pbobjc.h" +// Disable clang-format for the macros. +// clang-format off + // Pull in the macros (using an external file because expanding all tests // in a single file makes a file that is failing to work with within Xcode. //%PDDM-IMPORT-DEFINES GPBDictionaryTests.pddm //%PDDM-EXPAND TEST_FOR_POD_KEY(UInt64, uint64_t, 31ULL, 32ULL, 33ULL, 34ULL) // This block of code is generated, do not edit it directly. -// clang-format off // To let the testing macros work, add some extra methods to simplify things. @interface GPBUInt64EnumDictionary (TestingTweak) @@ -3673,5 +3675,4 @@ static BOOL TestingEnum_IsValidValue(int32_t value) { @end -// clang-format on //%PDDM-EXPAND-END TEST_FOR_POD_KEY(UInt64, uint64_t, 31ULL, 32ULL, 33ULL, 34ULL) diff --git a/objectivec/Tests/GPBMessageTests+Merge.m b/objectivec/Tests/GPBMessageTests+Merge.m index 8469746158..743b521677 100644 --- a/objectivec/Tests/GPBMessageTests+Merge.m +++ b/objectivec/Tests/GPBMessageTests+Merge.m @@ -258,6 +258,9 @@ dst.oneofEnum = Message2_Enum_Bar; +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE MERGE2_TEST(SET_NAME, SET_VALUE, CLEARED_NAME, CLEARED_DEFAULT) //% src.oneof##SET_NAME = SET_VALUE; //% [dst mergeFrom:src]; @@ -267,7 +270,6 @@ //% //%PDDM-EXPAND MERGE2_TEST(Int32, 10, Enum, Message2_Enum_Baz) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofInt32 = 10; [dst mergeFrom:src]; @@ -275,10 +277,8 @@ XCTAssertEqual(dst.oneofInt32, 10); XCTAssertEqual(dst.oneofEnum, Message2_Enum_Baz); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Int64, 11, Int32, 100) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofInt64 = 11; [dst mergeFrom:src]; @@ -286,10 +286,8 @@ XCTAssertEqual(dst.oneofInt64, 11); XCTAssertEqual(dst.oneofInt32, 100); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Uint32, 12U, Int64, 101) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofUint32 = 12U; [dst mergeFrom:src]; @@ -297,10 +295,8 @@ XCTAssertEqual(dst.oneofUint32, 12U); XCTAssertEqual(dst.oneofInt64, 101); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Uint64, 13U, Uint32, 102U) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofUint64 = 13U; [dst mergeFrom:src]; @@ -308,10 +304,8 @@ XCTAssertEqual(dst.oneofUint64, 13U); XCTAssertEqual(dst.oneofUint32, 102U); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Sint32, 14, Uint64, 103U) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofSint32 = 14; [dst mergeFrom:src]; @@ -319,10 +313,8 @@ XCTAssertEqual(dst.oneofSint32, 14); XCTAssertEqual(dst.oneofUint64, 103U); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Sint64, 15, Sint32, 104) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofSint64 = 15; [dst mergeFrom:src]; @@ -330,10 +322,8 @@ XCTAssertEqual(dst.oneofSint64, 15); XCTAssertEqual(dst.oneofSint32, 104); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Fixed32, 16U, Sint64, 105) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofFixed32 = 16U; [dst mergeFrom:src]; @@ -341,10 +331,8 @@ XCTAssertEqual(dst.oneofFixed32, 16U); XCTAssertEqual(dst.oneofSint64, 105); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Fixed64, 17U, Fixed32, 106U) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofFixed64 = 17U; [dst mergeFrom:src]; @@ -352,10 +340,8 @@ XCTAssertEqual(dst.oneofFixed64, 17U); XCTAssertEqual(dst.oneofFixed32, 106U); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Sfixed32, 18, Fixed64, 107U) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofSfixed32 = 18; [dst mergeFrom:src]; @@ -363,10 +349,8 @@ XCTAssertEqual(dst.oneofSfixed32, 18); XCTAssertEqual(dst.oneofFixed64, 107U); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Sfixed64, 19, Sfixed32, 108) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofSfixed64 = 19; [dst mergeFrom:src]; @@ -374,10 +358,8 @@ XCTAssertEqual(dst.oneofSfixed64, 19); XCTAssertEqual(dst.oneofSfixed32, 108); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Float, 20.0f, Sfixed64, 109) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofFloat = 20.0f; [dst mergeFrom:src]; @@ -385,10 +367,8 @@ XCTAssertEqual(dst.oneofFloat, 20.0f); XCTAssertEqual(dst.oneofSfixed64, 109); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Double, 21.0, Float, 110.0f) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofDouble = 21.0; [dst mergeFrom:src]; @@ -396,10 +376,8 @@ XCTAssertEqual(dst.oneofDouble, 21.0); XCTAssertEqual(dst.oneofFloat, 110.0f); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Bool, NO, Double, 111.0) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofBool = NO; [dst mergeFrom:src]; @@ -407,10 +385,8 @@ XCTAssertEqual(dst.oneofBool, NO); XCTAssertEqual(dst.oneofDouble, 111.0); -// clang-format on //%PDDM-EXPAND MERGE2_TEST(Enum, Message2_Enum_Bar, Bool, YES) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofEnum = Message2_Enum_Bar; [dst mergeFrom:src]; @@ -418,9 +394,10 @@ XCTAssertEqual(dst.oneofEnum, Message2_Enum_Bar); XCTAssertEqual(dst.oneofBool, YES); -// clang-format on //%PDDM-EXPAND-END (14 expansions) +// clang-format on + NSString *oneofStringDefault = @"string"; NSData *oneofBytesDefault = [@"data" dataUsingEncoding:NSUTF8StringEncoding]; @@ -506,6 +483,9 @@ dst.oneofEnum = Message3_Enum_Bar; +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE MERGE3_TEST(SET_NAME, SET_VALUE, CLEARED_NAME, CLEARED_DEFAULT) //% src.oneof##SET_NAME = SET_VALUE; //% [dst mergeFrom:src]; @@ -515,7 +495,6 @@ //% //%PDDM-EXPAND MERGE3_TEST(Int32, 10, Enum, Message3_Enum_Foo) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofInt32 = 10; [dst mergeFrom:src]; @@ -523,10 +502,8 @@ XCTAssertEqual(dst.oneofInt32, 10); XCTAssertEqual(dst.oneofEnum, Message3_Enum_Foo); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Int64, 11, Int32, 0) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofInt64 = 11; [dst mergeFrom:src]; @@ -534,10 +511,8 @@ XCTAssertEqual(dst.oneofInt64, 11); XCTAssertEqual(dst.oneofInt32, 0); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Uint32, 12U, Int64, 0) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofUint32 = 12U; [dst mergeFrom:src]; @@ -545,10 +520,8 @@ XCTAssertEqual(dst.oneofUint32, 12U); XCTAssertEqual(dst.oneofInt64, 0); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Uint64, 13U, Uint32, 0U) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofUint64 = 13U; [dst mergeFrom:src]; @@ -556,10 +529,8 @@ XCTAssertEqual(dst.oneofUint64, 13U); XCTAssertEqual(dst.oneofUint32, 0U); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Sint32, 14, Uint64, 0U) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofSint32 = 14; [dst mergeFrom:src]; @@ -567,10 +538,8 @@ XCTAssertEqual(dst.oneofSint32, 14); XCTAssertEqual(dst.oneofUint64, 0U); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Sint64, 15, Sint32, 0) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofSint64 = 15; [dst mergeFrom:src]; @@ -578,10 +547,8 @@ XCTAssertEqual(dst.oneofSint64, 15); XCTAssertEqual(dst.oneofSint32, 0); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Fixed32, 16U, Sint64, 0) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofFixed32 = 16U; [dst mergeFrom:src]; @@ -589,10 +556,8 @@ XCTAssertEqual(dst.oneofFixed32, 16U); XCTAssertEqual(dst.oneofSint64, 0); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Fixed64, 17U, Fixed32, 0U) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofFixed64 = 17U; [dst mergeFrom:src]; @@ -600,10 +565,8 @@ XCTAssertEqual(dst.oneofFixed64, 17U); XCTAssertEqual(dst.oneofFixed32, 0U); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Sfixed32, 18, Fixed64, 0U) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofSfixed32 = 18; [dst mergeFrom:src]; @@ -611,10 +574,8 @@ XCTAssertEqual(dst.oneofSfixed32, 18); XCTAssertEqual(dst.oneofFixed64, 0U); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Sfixed64, 19, Sfixed32, 0) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofSfixed64 = 19; [dst mergeFrom:src]; @@ -622,10 +583,8 @@ XCTAssertEqual(dst.oneofSfixed64, 19); XCTAssertEqual(dst.oneofSfixed32, 0); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Float, 20.0f, Sfixed64, 0) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofFloat = 20.0f; [dst mergeFrom:src]; @@ -633,10 +592,8 @@ XCTAssertEqual(dst.oneofFloat, 20.0f); XCTAssertEqual(dst.oneofSfixed64, 0); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Double, 21.0, Float, 0.0f) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofDouble = 21.0; [dst mergeFrom:src]; @@ -644,10 +601,8 @@ XCTAssertEqual(dst.oneofDouble, 21.0); XCTAssertEqual(dst.oneofFloat, 0.0f); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Bool, YES, Double, 0.0) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofBool = YES; [dst mergeFrom:src]; @@ -655,10 +610,8 @@ XCTAssertEqual(dst.oneofBool, YES); XCTAssertEqual(dst.oneofDouble, 0.0); -// clang-format on //%PDDM-EXPAND MERGE3_TEST(Enum, Message3_Enum_Bar, Bool, NO) // This block of code is generated, do not edit it directly. -// clang-format off src.oneofEnum = Message3_Enum_Bar; [dst mergeFrom:src]; @@ -666,9 +619,10 @@ XCTAssertEqual(dst.oneofEnum, Message3_Enum_Bar); XCTAssertEqual(dst.oneofBool, NO); -// clang-format on //%PDDM-EXPAND-END (14 expansions) +// clang-format on + NSString *oneofStringDefault = @""; NSData *oneofBytesDefault = [NSData data]; diff --git a/objectivec/Tests/GPBMessageTests+Runtime.m b/objectivec/Tests/GPBMessageTests+Runtime.m index cdaea3419a..aefdf755df 100644 --- a/objectivec/Tests/GPBMessageTests+Runtime.m +++ b/objectivec/Tests/GPBMessageTests+Runtime.m @@ -337,6 +337,9 @@ // being true. // +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE PROTO2_TEST_HAS_FIELD(FIELD, NON_ZERO_VALUE, ZERO_VALUE) //% { // optional##FIELD :: NON_ZERO_VALUE //% Message2 *msg = [[Message2 alloc] init]; @@ -399,7 +402,6 @@ //%PROTO2_TEST_CLEAR_FIELD_WITH_NIL(Message, [Message2 message]) //%PDDM-EXPAND PROTO2_TEST_HAS_FIELDS() // This block of code is generated, do not edit it directly. -// clang-format off { // optionalInt32 :: 1 Message2 *msg = [[Message2 alloc] init]; @@ -753,8 +755,9 @@ [msg release]; } -// clang-format on //%PDDM-EXPAND-END PROTO2_TEST_HAS_FIELDS() + +// clang-format on } - (void)testProto3SingleFieldHasBehavior { @@ -763,6 +766,9 @@ // being true. When set to the default, shouldn't be true. // +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE PROTO3_TEST_HAS_FIELD(FIELD, NON_ZERO_VALUE, ZERO_VALUE) //% { // optional##FIELD //% Message3 *msg = [[Message3 alloc] init]; @@ -815,7 +821,6 @@ //%PROTO3_TEST_CLEAR_FIELD_WITH_NIL(Message, [Message3 message]) //%PDDM-EXPAND PROTO3_TEST_HAS_FIELDS() // This block of code is generated, do not edit it directly. -// clang-format off { // optionalInt32 Message3 *msg = [[Message3 alloc] init]; @@ -1015,8 +1020,9 @@ [msg release]; } -// clang-format on //%PDDM-EXPAND-END PROTO3_TEST_HAS_FIELDS() + +// clang-format on } - (void)testProto3SingleOptionalFieldHasBehavior { @@ -1024,6 +1030,9 @@ // Setting to any value including the default (0) should result in true. // +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE PROTO3_TEST_OPTIONAL_HAS_FIELD(FIELD, NON_ZERO_VALUE, ZERO_VALUE) //% { // optional##FIELD //% Message3Optional *msg = [[Message3Optional alloc] init]; @@ -1060,7 +1069,6 @@ //%PROTO3_TEST_OPTIONAL_HAS_FIELD(Enum, Message3Optional_Enum_Bar, Message3Optional_Enum_Foo) //%PDDM-EXPAND PROTO3_TEST_OPTIONAL_HAS_FIELDS() // This block of code is generated, do not edit it directly. -// clang-format off { // optionalInt32 Message3Optional *msg = [[Message3Optional alloc] init]; @@ -1258,8 +1266,9 @@ [msg release]; } -// clang-format on //%PDDM-EXPAND-END PROTO3_TEST_OPTIONAL_HAS_FIELDS() + +// clang-format on } - (void)testAccessingProto2UnknownEnumValues { diff --git a/objectivec/Tests/GPBMessageTests+Serialization.m b/objectivec/Tests/GPBMessageTests+Serialization.m index 0427683e03..cfbc59718e 100644 --- a/objectivec/Tests/GPBMessageTests+Serialization.m +++ b/objectivec/Tests/GPBMessageTests+Serialization.m @@ -113,6 +113,9 @@ // Proto3 optionals should be just like proto2, zero values also get serialized. // +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(FIELD, ZERO_VALUE, EXPECTED_LEN) //% { // optional##FIELD //% Message3Optional *msg = [[Message3Optional alloc] init]; @@ -153,7 +156,6 @@ //%PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(Enum, Message3Optional_Enum_Foo, 3) //%PDDM-EXPAND PROTO3_TEST_SERIALIZE_OPTIONAL_FIELDS() // This block of code is generated, do not edit it directly. -// clang-format off { // optionalInt32 Message3Optional *msg = [[Message3Optional alloc] init]; @@ -415,8 +417,9 @@ [msg release]; } -// clang-format on //%PDDM-EXPAND-END PROTO3_TEST_SERIALIZE_OPTIONAL_FIELDS() + +// clang-format on } - (void)testProto2UnknownEnumToUnknownField { @@ -520,6 +523,9 @@ XCTAssertEqual(orig.oneofE1, UnknownEnumsMyEnumPlusExtra_EExtra); } +// Disable clang-format for the macros. +// clang-format off + //%PDDM-DEFINE TEST_ROUNDTRIP_ONEOF(MESSAGE, FIELD, VALUE) //%TEST_ROUNDTRIP_ONEOF_ADV(MESSAGE, FIELD, VALUE, ) //%PDDM-DEFINE TEST_ROUNDTRIP_ONEOF_ADV(MESSAGE, FIELD, VALUE, EQ_SUFFIX) @@ -583,7 +589,6 @@ //% //%PDDM-EXPAND TEST_ROUNDTRIP_ONEOFS(2, NO) // This block of code is generated, do not edit it directly. -// clang-format off - (void)testProto2RoundTripOneof { @@ -814,10 +819,8 @@ [subMessage release]; } -// clang-format on //%PDDM-EXPAND TEST_ROUNDTRIP_ONEOFS(3, YES) // This block of code is generated, do not edit it directly. -// clang-format off - (void)testProto3RoundTripOneof { @@ -1034,9 +1037,10 @@ [subMessage release]; } -// clang-format on //%PDDM-EXPAND-END (2 expansions) +// clang-format on + - (void)testPackedUnpackedMessageParsing { // packed is optional, a repeated field should parse when packed or unpacked. diff --git a/objectivec/Tests/GPBUtilitiesTests.m b/objectivec/Tests/GPBUtilitiesTests.m index 5c3d36fcdb..6a639e16bc 100644 --- a/objectivec/Tests/GPBUtilitiesTests.m +++ b/objectivec/Tests/GPBUtilitiesTests.m @@ -62,6 +62,7 @@ - (void)testGPBDecodeTextFormatName { uint8_t decodeData[] = { + // clang-format off 0x6, // An inlined string (first to make sure the leading null is handled // correctly, and with a key of zero to check that). @@ -80,6 +81,7 @@ // underscore, lower + 30 (01 op), as is + 30 (00 op), as is + 13 (00 op), // underscore, as is + 3 (00 op) 0xE8, 0x07, 0x04, 0xA5, 0xA4, 0xA2, 0xBF, 0x1F, 0x0E, 0x84, 0x0, + // clang-format on }; NSString *inputStr = @"abcdefghIJ"; @@ -104,10 +106,12 @@ // An inlined string (and key of zero). XCTAssertEqualObjects(GPBDecodeTextFormatName(decodeData, 0, inputStr), @"zbcdefghIJ"); + // clang-format off // Long name so multiple decode ops are needed. inputStr = @"longFieldNameIsLooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong1000"; XCTAssertEqualObjects(GPBDecodeTextFormatName(decodeData, 1000, inputStr), @"long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1000"); + // clang-format on } - (void)testTextFormat { @@ -141,12 +145,14 @@ message.subEnum = self_autorelease_RetainCount; message.new_p.copy_p = @"foo"; + // clang-format off NSString *expected = @"_cmd: true\n" @"isProxy: true\n" @"SubEnum: retainCount\n" @"New {\n" @" copy: \"foo\"\n" @"}\n"; + // clang-format on NSString *result = GPBTextFormatForMessage(message, nil); XCTAssertEqualObjects(expected, result); } From 5d0b2175c3b0339081e5906b7684212f2051f3fd Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Mon, 19 Sep 2022 17:20:35 -0400 Subject: [PATCH 60/64] Format the headers. --- objectivec/GPBBootstrap.h | 9 +- objectivec/GPBCodedInputStream.h | 2 +- .../GPBCodedInputStream_PackagePrivate.h | 16 +-- .../GPBCodedOutputStream_PackagePrivate.h | 68 ++++----- objectivec/GPBDescriptor.h | 10 +- objectivec/GPBDescriptor_PackagePrivate.h | 130 +++++++++--------- objectivec/GPBDictionary_PackagePrivate.h | 19 +-- objectivec/GPBExtensionInternals.h | 11 +- objectivec/GPBExtensionRegistry.h | 2 +- objectivec/GPBMessage.h | 9 +- objectivec/GPBMessage_PackagePrivate.h | 7 +- objectivec/GPBUnknownField.h | 6 +- objectivec/GPBUnknownFieldSet.h | 2 +- objectivec/GPBUtilities.h | 7 +- objectivec/GPBUtilities_PackagePrivate.h | 49 +++---- objectivec/GPBWellKnownTypes.h | 12 +- 16 files changed, 147 insertions(+), 212 deletions(-) diff --git a/objectivec/GPBBootstrap.h b/objectivec/GPBBootstrap.h index ea5986b8bf..4fbcbab41c 100644 --- a/objectivec/GPBBootstrap.h +++ b/objectivec/GPBBootstrap.h @@ -42,7 +42,7 @@ // Used in the generated code to give sizes to enums. int32_t was chosen based // on the fact that Protocol Buffers enums are limited to this range. #if !__has_feature(objc_fixed_enum) - #error All supported Xcode versions should support objc_fixed_enum. +#error All supported Xcode versions should support objc_fixed_enum. #endif // If the headers are imported into Objective-C++, we can run into an issue @@ -52,9 +52,11 @@ // providing a local definition. The default case has to use NS_ENUM for the // magic that is Swift bridging of enums. #if (defined(__cplusplus) && __cplusplus && __cplusplus < 201103L) - #define GPB_ENUM(X) enum X : int32_t X; enum X : int32_t +#define GPB_ENUM(X) \ + enum X : int32_t X; \ + enum X : int32_t #else - #define GPB_ENUM(X) NS_ENUM(int32_t, X) +#define GPB_ENUM(X) NS_ENUM(int32_t, X) #endif /** @@ -138,7 +140,6 @@ // - Gets changed when support for the older generated code is dropped. #define GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION 30001 - // This is a legacy constant now frozen in time for old generated code. If // GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION ever gets moved above 30001 then // this should also change to break code compiled with an old runtime that diff --git a/objectivec/GPBCodedInputStream.h b/objectivec/GPBCodedInputStream.h index b7e1c7e6ab..cbfaaf1cf0 100644 --- a/objectivec/GPBCodedInputStream.h +++ b/objectivec/GPBCodedInputStream.h @@ -185,7 +185,7 @@ CF_EXTERN_C_END * extensions for message. **/ - (void)readMessage:(GPBMessage *)message - extensionRegistry:(nullable id)extensionRegistry; + extensionRegistry:(nullable id)extensionRegistry; /** * Reads and discards a single field, given its tag value. diff --git a/objectivec/GPBCodedInputStream_PackagePrivate.h b/objectivec/GPBCodedInputStream_PackagePrivate.h index cdfb0dcc3f..2dfc902c95 100644 --- a/objectivec/GPBCodedInputStream_PackagePrivate.h +++ b/objectivec/GPBCodedInputStream_PackagePrivate.h @@ -65,8 +65,7 @@ typedef struct GPBCodedInputStreamState { // Reads a group field value from the stream and merges it into the given // UnknownFieldSet. -- (void)readUnknownGroup:(int32_t)fieldNumber - message:(GPBUnknownFieldSet *)message; +- (void)readUnknownGroup:(int32_t)fieldNumber message:(GPBUnknownFieldSet *)message; // Reads a map entry. - (void)readMapEntry:(id)mapDictionary @@ -97,16 +96,13 @@ NSString *GPBCodedInputStreamReadRetainedString(GPBCodedInputStreamState *state) __attribute((ns_returns_retained)); NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) __attribute((ns_returns_retained)); -NSData *GPBCodedInputStreamReadRetainedBytesNoCopy( - GPBCodedInputStreamState *state) __attribute((ns_returns_retained)); +NSData *GPBCodedInputStreamReadRetainedBytesNoCopy(GPBCodedInputStreamState *state) + __attribute((ns_returns_retained)); -size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, - size_t byteLimit); -void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, - size_t oldLimit); +size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, size_t byteLimit); +void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, size_t oldLimit); size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state); BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state); -void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, - int32_t value); +void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, int32_t value); CF_EXTERN_C_END diff --git a/objectivec/GPBCodedOutputStream_PackagePrivate.h b/objectivec/GPBCodedOutputStream_PackagePrivate.h index 2e7bb4c4a2..98e2d95a32 100644 --- a/objectivec/GPBCodedOutputStream_PackagePrivate.h +++ b/objectivec/GPBCodedOutputStream_PackagePrivate.h @@ -34,46 +34,27 @@ NS_ASSUME_NONNULL_BEGIN CF_EXTERN_C_BEGIN -size_t GPBComputeDoubleSize(int32_t fieldNumber, double value) - __attribute__((const)); -size_t GPBComputeFloatSize(int32_t fieldNumber, float value) - __attribute__((const)); -size_t GPBComputeUInt64Size(int32_t fieldNumber, uint64_t value) - __attribute__((const)); -size_t GPBComputeInt64Size(int32_t fieldNumber, int64_t value) - __attribute__((const)); -size_t GPBComputeInt32Size(int32_t fieldNumber, int32_t value) - __attribute__((const)); -size_t GPBComputeFixed64Size(int32_t fieldNumber, uint64_t value) - __attribute__((const)); -size_t GPBComputeFixed32Size(int32_t fieldNumber, uint32_t value) - __attribute__((const)); -size_t GPBComputeBoolSize(int32_t fieldNumber, BOOL value) - __attribute__((const)); -size_t GPBComputeStringSize(int32_t fieldNumber, NSString *value) - __attribute__((const)); -size_t GPBComputeGroupSize(int32_t fieldNumber, GPBMessage *value) - __attribute__((const)); -size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, - GPBUnknownFieldSet *value) - __attribute__((const)); -size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) - __attribute__((const)); -size_t GPBComputeBytesSize(int32_t fieldNumber, NSData *value) - __attribute__((const)); -size_t GPBComputeUInt32Size(int32_t fieldNumber, uint32_t value) - __attribute__((const)); -size_t GPBComputeSFixed32Size(int32_t fieldNumber, int32_t value) - __attribute__((const)); -size_t GPBComputeSFixed64Size(int32_t fieldNumber, int64_t value) - __attribute__((const)); -size_t GPBComputeSInt32Size(int32_t fieldNumber, int32_t value) - __attribute__((const)); -size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) - __attribute__((const)); +size_t GPBComputeDoubleSize(int32_t fieldNumber, double value) __attribute__((const)); +size_t GPBComputeFloatSize(int32_t fieldNumber, float value) __attribute__((const)); +size_t GPBComputeUInt64Size(int32_t fieldNumber, uint64_t value) __attribute__((const)); +size_t GPBComputeInt64Size(int32_t fieldNumber, int64_t value) __attribute__((const)); +size_t GPBComputeInt32Size(int32_t fieldNumber, int32_t value) __attribute__((const)); +size_t GPBComputeFixed64Size(int32_t fieldNumber, uint64_t value) __attribute__((const)); +size_t GPBComputeFixed32Size(int32_t fieldNumber, uint32_t value) __attribute__((const)); +size_t GPBComputeBoolSize(int32_t fieldNumber, BOOL value) __attribute__((const)); +size_t GPBComputeStringSize(int32_t fieldNumber, NSString *value) __attribute__((const)); +size_t GPBComputeGroupSize(int32_t fieldNumber, GPBMessage *value) __attribute__((const)); +size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, GPBUnknownFieldSet *value) + __attribute__((const)); +size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) __attribute__((const)); +size_t GPBComputeBytesSize(int32_t fieldNumber, NSData *value) __attribute__((const)); +size_t GPBComputeUInt32Size(int32_t fieldNumber, uint32_t value) __attribute__((const)); +size_t GPBComputeSFixed32Size(int32_t fieldNumber, int32_t value) __attribute__((const)); +size_t GPBComputeSFixed64Size(int32_t fieldNumber, int64_t value) __attribute__((const)); +size_t GPBComputeSInt32Size(int32_t fieldNumber, int32_t value) __attribute__((const)); +size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) __attribute__((const)); size_t GPBComputeTagSize(int32_t fieldNumber) __attribute__((const)); -size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) - __attribute__((const)); +size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) __attribute__((const)); size_t GPBComputeDoubleSizeNoTag(double value) __attribute__((const)); size_t GPBComputeFloatSizeNoTag(float value) __attribute__((const)); @@ -85,8 +66,7 @@ size_t GPBComputeFixed32SizeNoTag(uint32_t value) __attribute__((const)); size_t GPBComputeBoolSizeNoTag(BOOL value) __attribute__((const)); size_t GPBComputeStringSizeNoTag(NSString *value) __attribute__((const)); size_t GPBComputeGroupSizeNoTag(GPBMessage *value) __attribute__((const)); -size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) - __attribute__((const)); +size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) __attribute__((const)); size_t GPBComputeMessageSizeNoTag(GPBMessage *value) __attribute__((const)); size_t GPBComputeBytesSizeNoTag(NSData *value) __attribute__((const)); size_t GPBComputeUInt32SizeNoTag(int32_t value) __attribute__((const)); @@ -103,8 +83,7 @@ size_t GPBComputeRawVarint32Size(int32_t value) __attribute__((const)); size_t GPBComputeRawVarint64Size(int64_t value) __attribute__((const)); // Note that this will calculate the size of 64 bit values truncated to 32. -size_t GPBComputeRawVarint32SizeForInteger(NSInteger value) - __attribute__((const)); +size_t GPBComputeRawVarint32SizeForInteger(NSInteger value) __attribute__((const)); // Compute the number of bytes that would be needed to encode a // MessageSet extension to the stream. For historical reasons, @@ -118,8 +97,7 @@ size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, GPBMessage *value) size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, NSData *value) __attribute__((const)); -size_t GPBComputeEnumSize(int32_t fieldNumber, int32_t value) - __attribute__((const)); +size_t GPBComputeEnumSize(int32_t fieldNumber, int32_t value) __attribute__((const)); CF_EXTERN_C_END diff --git a/objectivec/GPBDescriptor.h b/objectivec/GPBDescriptor.h index fd66b0e9f0..750eaeed6d 100644 --- a/objectivec/GPBDescriptor.h +++ b/objectivec/GPBDescriptor.h @@ -62,14 +62,14 @@ typedef NS_ENUM(uint8_t, GPBFieldType) { /** * Describes a proto message. **/ -@interface GPBDescriptor : NSObject +@interface GPBDescriptor : NSObject /** Name of the message. */ @property(nonatomic, readonly, copy) NSString *name; /** Fields declared in the message. */ -@property(nonatomic, readonly, strong, nullable) NSArray *fields; +@property(nonatomic, readonly, strong, nullable) NSArray *fields; /** Oneofs declared in the message. */ -@property(nonatomic, readonly, strong, nullable) NSArray *oneofs; +@property(nonatomic, readonly, strong, nullable) NSArray *oneofs; /** Extension range declared for the message. */ @property(nonatomic, readonly, nullable) const GPBExtensionRange *extensionRanges; /** Number of extension ranges declared for the message. */ @@ -139,7 +139,7 @@ typedef NS_ENUM(uint8_t, GPBFieldType) { /** Name of the oneof field. */ @property(nonatomic, readonly) NSString *name; /** Fields declared in the oneof. */ -@property(nonatomic, readonly) NSArray *fields; +@property(nonatomic, readonly) NSArray *fields; /** * Gets the field for the given number. @@ -293,7 +293,7 @@ typedef NS_ENUM(uint8_t, GPBFieldType) { /** * Describes a proto extension. **/ -@interface GPBExtensionDescriptor : NSObject +@interface GPBExtensionDescriptor : NSObject /** Field number under which the extension is stored. */ @property(nonatomic, readonly) uint32_t fieldNumber; /** The containing message class, i.e. the class extended by this extension. */ diff --git a/objectivec/GPBDescriptor_PackagePrivate.h b/objectivec/GPBDescriptor_PackagePrivate.h index 408f8d4e10..3e07226f46 100644 --- a/objectivec/GPBDescriptor_PackagePrivate.h +++ b/objectivec/GPBDescriptor_PackagePrivate.h @@ -37,12 +37,12 @@ // Describes attributes of the field. typedef NS_OPTIONS(uint16_t, GPBFieldFlags) { - GPBFieldNone = 0, + GPBFieldNone = 0, // These map to standard protobuf concepts. - GPBFieldRequired = 1 << 0, - GPBFieldRepeated = 1 << 1, - GPBFieldPacked = 1 << 2, - GPBFieldOptional = 1 << 3, + GPBFieldRequired = 1 << 0, + GPBFieldRepeated = 1 << 1, + GPBFieldPacked = 1 << 2, + GPBFieldOptional = 1 << 3, GPBFieldHasDefaultValue = 1 << 4, // Indicate that the field should "clear" when set to zero value. This is the @@ -60,19 +60,19 @@ typedef NS_OPTIONS(uint16_t, GPBFieldFlags) { // These bits are used to mark the field as a map and what the key // type is. - GPBFieldMapKeyMask = 0xF << 8, - GPBFieldMapKeyInt32 = 1 << 8, - GPBFieldMapKeyInt64 = 2 << 8, - GPBFieldMapKeyUInt32 = 3 << 8, - GPBFieldMapKeyUInt64 = 4 << 8, - GPBFieldMapKeySInt32 = 5 << 8, - GPBFieldMapKeySInt64 = 6 << 8, - GPBFieldMapKeyFixed32 = 7 << 8, - GPBFieldMapKeyFixed64 = 8 << 8, - GPBFieldMapKeySFixed32 = 9 << 8, + GPBFieldMapKeyMask = 0xF << 8, + GPBFieldMapKeyInt32 = 1 << 8, + GPBFieldMapKeyInt64 = 2 << 8, + GPBFieldMapKeyUInt32 = 3 << 8, + GPBFieldMapKeyUInt64 = 4 << 8, + GPBFieldMapKeySInt32 = 5 << 8, + GPBFieldMapKeySInt64 = 6 << 8, + GPBFieldMapKeyFixed32 = 7 << 8, + GPBFieldMapKeyFixed64 = 8 << 8, + GPBFieldMapKeySFixed32 = 9 << 8, GPBFieldMapKeySFixed64 = 10 << 8, - GPBFieldMapKeyBool = 11 << 8, - GPBFieldMapKeyString = 12 << 8, + GPBFieldMapKeyBool = 11 << 8, + GPBFieldMapKeyString = 12 << 8, }; // NOTE: The structures defined here have their members ordered to minimize @@ -88,7 +88,7 @@ typedef struct GPBMessageFieldDescription { // kept around right now for backwards compatibility. // clazz is used iff GPBDescriptorInitializationFlag_UsesClassRefs is set. char *className; // Name of the class of the message. - Class clazz; // Class of the message. + Class clazz; // Class of the message. // For enums only: If EnumDescriptors are compiled in, it will be that, // otherwise it will be the verifier. GPBEnumDescriptorFunc enumDescFunc; @@ -120,10 +120,10 @@ typedef struct GPBMessageFieldDescriptionWithDefault { // Describes attributes of the extension. typedef NS_OPTIONS(uint8_t, GPBExtensionOptions) { - GPBExtensionNone = 0, + GPBExtensionNone = 0, // These map to standard protobuf concepts. - GPBExtensionRepeated = 1 << 0, - GPBExtensionPacked = 1 << 1, + GPBExtensionRepeated = 1 << 0, + GPBExtensionPacked = 1 << 1, GPBExtensionSetWireFormat = 1 << 2, }; @@ -132,10 +132,10 @@ typedef struct GPBExtensionDescription { GPBGenericValue defaultValue; const char *singletonName; // Before 3.12, `extendedClass` was just a `const char *`. Thanks to nested - // initialization (https://en.cppreference.com/w/c/language/struct_initialization#Nested_initialization) - // old generated code with `.extendedClass = GPBStringifySymbol(Something)` - // still works; and the current generator can use `extendedClass.clazz`, to - // pass a Class reference. + // initialization + // (https://en.cppreference.com/w/c/language/struct_initialization#Nested_initialization) old + // generated code with `.extendedClass = GPBStringifySymbol(Something)` still works; and the + // current generator can use `extendedClass.clazz`, to pass a Class reference. union { const char *name; Class clazz; @@ -150,9 +150,9 @@ typedef struct GPBExtensionDescription { union { const char *messageOrGroupClassName; union { - const char *name; - Class clazz; - } messageOrGroupClass; + const char *name; + Class clazz; + } messageOrGroupClass; }; GPBEnumDescriptorFunc enumDescriptorFunc; int32_t fieldNumber; @@ -161,14 +161,14 @@ typedef struct GPBExtensionDescription { } GPBExtensionDescription; typedef NS_OPTIONS(uint32_t, GPBDescriptorInitializationFlags) { - GPBDescriptorInitializationFlag_None = 0, + GPBDescriptorInitializationFlag_None = 0, GPBDescriptorInitializationFlag_FieldsWithDefault = 1 << 0, - GPBDescriptorInitializationFlag_WireFormat = 1 << 1, + GPBDescriptorInitializationFlag_WireFormat = 1 << 1, // This is used as a stopgap as we move from using class names to class // references. The runtime needs to support both until we allow a // breaking change in the runtime. - GPBDescriptorInitializationFlag_UsesClassRefs = 1 << 2, + GPBDescriptorInitializationFlag_UsesClassRefs = 1 << 2, // This flag is used to indicate that the generated sources already contain // the `GPBFieldClearHasIvarOnZero` flag and it doesn't have to be computed @@ -185,14 +185,13 @@ typedef NS_OPTIONS(uint32_t, GPBDescriptorInitializationFlags) { } // fieldDescriptions have to be long lived, they are held as raw pointers. -+ (instancetype) - allocDescriptorForClass:(Class)messageClass - rootClass:(Class)rootClass - file:(GPBFileDescriptor *)file - fields:(void *)fieldDescriptions - fieldCount:(uint32_t)fieldCount - storageSize:(uint32_t)storageSize - flags:(GPBDescriptorInitializationFlags)flags; ++ (instancetype)allocDescriptorForClass:(Class)messageClass + rootClass:(Class)rootClass + file:(GPBFileDescriptor *)file + fields:(void *)fieldDescriptions + fieldCount:(uint32_t)fieldCount + storageSize:(uint32_t)storageSize + flags:(GPBDescriptorInitializationFlags)flags; - (instancetype)initWithClass:(Class)messageClass file:(GPBFileDescriptor *)file @@ -220,8 +219,7 @@ typedef NS_OPTIONS(uint32_t, GPBDescriptorInitializationFlags) { - (instancetype)initWithPackage:(NSString *)package objcPrefix:(NSString *)objcPrefix syntax:(GPBFileSyntax)syntax; -- (instancetype)initWithPackage:(NSString *)package - syntax:(GPBFileSyntax)syntax; +- (instancetype)initWithPackage:(NSString *)package syntax:(GPBFileSyntax)syntax; @end @interface GPBOneofDescriptor () { @@ -258,19 +256,17 @@ typedef NS_OPTIONS(uint32_t, GPBDescriptorInitializationFlags) { @interface GPBEnumDescriptor () // valueNames, values and extraTextFormatInfo have to be long lived, they are // held as raw pointers. -+ (instancetype) - allocDescriptorForName:(NSString *)name - valueNames:(const char *)valueNames - values:(const int32_t *)values - count:(uint32_t)valueCount - enumVerifier:(GPBEnumValidationFunc)enumVerifier; -+ (instancetype) - allocDescriptorForName:(NSString *)name - valueNames:(const char *)valueNames - values:(const int32_t *)values - count:(uint32_t)valueCount - enumVerifier:(GPBEnumValidationFunc)enumVerifier - extraTextFormatInfo:(const char *)extraTextFormatInfo; ++ (instancetype)allocDescriptorForName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier; ++ (instancetype)allocDescriptorForName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier + extraTextFormatInfo:(const char *)extraTextFormatInfo; - (instancetype)initWithName:(NSString *)name valueNames:(const char *)valueNames @@ -309,8 +305,7 @@ CF_EXTERN_C_BEGIN #pragma clang diagnostic ignored "-Wdirect-ivar-access" GPB_INLINE BOOL GPBFieldIsMapOrArray(GPBFieldDescriptor *field) { - return (field->description_->flags & - (GPBFieldRepeated | GPBFieldMapKeyMask)) != 0; + return (field->description_->flags & (GPBFieldRepeated | GPBFieldMapKeyMask)) != 0; } GPB_INLINE GPBDataType GPBGetFieldDataType(GPBFieldDescriptor *field) { @@ -353,22 +348,21 @@ GPB_INLINE BOOL GPBExtensionIsWireFormat(GPBExtensionDescription *description) { // Helper for compile time assets. #ifndef GPBInternalCompileAssert - #if __has_feature(c_static_assert) || __has_extension(c_static_assert) - #define GPBInternalCompileAssert(test, msg) _Static_assert((test), #msg) - #else - // Pre-Xcode 7 support. - #define GPBInternalCompileAssertSymbolInner(line, msg) GPBInternalCompileAssert ## line ## __ ## msg - #define GPBInternalCompileAssertSymbol(line, msg) GPBInternalCompileAssertSymbolInner(line, msg) - #define GPBInternalCompileAssert(test, msg) \ - typedef char GPBInternalCompileAssertSymbol(__LINE__, msg) [ ((test) ? 1 : -1) ] - #endif // __has_feature(c_static_assert) || __has_extension(c_static_assert) -#endif // GPBInternalCompileAssert +#if __has_feature(c_static_assert) || __has_extension(c_static_assert) +#define GPBInternalCompileAssert(test, msg) _Static_assert((test), #msg) +#else +// Pre-Xcode 7 support. +#define GPBInternalCompileAssertSymbolInner(line, msg) GPBInternalCompileAssert##line##__##msg +#define GPBInternalCompileAssertSymbol(line, msg) GPBInternalCompileAssertSymbolInner(line, msg) +#define GPBInternalCompileAssert(test, msg) \ + typedef char GPBInternalCompileAssertSymbol(__LINE__, msg)[((test) ? 1 : -1)] +#endif // __has_feature(c_static_assert) || __has_extension(c_static_assert) +#endif // GPBInternalCompileAssert // Sanity check that there isn't padding between the field description // structures with and without a default. GPBInternalCompileAssert(sizeof(GPBMessageFieldDescriptionWithDefault) == - (sizeof(GPBGenericValue) + - sizeof(GPBMessageFieldDescription)), + (sizeof(GPBGenericValue) + sizeof(GPBMessageFieldDescription)), DescriptionsWithDefault_different_size_than_expected); CF_EXTERN_C_END diff --git a/objectivec/GPBDictionary_PackagePrivate.h b/objectivec/GPBDictionary_PackagePrivate.h index 82f053e7bf..3735fa5905 100644 --- a/objectivec/GPBDictionary_PackagePrivate.h +++ b/objectivec/GPBDictionary_PackagePrivate.h @@ -41,8 +41,7 @@ - (size_t)computeSerializedSizeAsField:(GPBFieldDescriptor *)field; - (void)writeToCodedOutputStream:(GPBCodedOutputStream *)outputStream asField:(GPBFieldDescriptor *)field; -- (void)setGPBGenericValue:(GPBGenericValue *)value - forGPBGenericValueKey:(GPBGenericValue *)key; +- (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key; - (void)enumerateForTextFormat:(void (^)(id keyObj, id valueObj))block; @end @@ -459,7 +458,7 @@ #pragma mark - NSDictionary Subclass @interface GPBAutocreatedDictionary : NSMutableDictionary { - @package + @package GPB_UNSAFE_UNRETAINED GPBMessage *_autocreator; } @end @@ -470,24 +469,20 @@ CF_EXTERN_C_BEGIN // Helper to compute size when an NSDictionary is used for the map instead // of a custom type. -size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, - GPBFieldDescriptor *field); +size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field); // Helper to write out when an NSDictionary is used for the map instead // of a custom type. -void GPBDictionaryWriteToStreamInternalHelper( - GPBCodedOutputStream *outputStream, NSDictionary *dict, - GPBFieldDescriptor *field); +void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream, + NSDictionary *dict, GPBFieldDescriptor *field); // Helper to check message initialization when an NSDictionary is used for // the map instead of a custom type. -BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, - GPBFieldDescriptor *field); +BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field); // Helper to read a map instead. void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream, - idregistry, - GPBFieldDescriptor *field, + id registry, GPBFieldDescriptor *field, GPBMessage *parentMessage); CF_EXTERN_C_END diff --git a/objectivec/GPBExtensionInternals.h b/objectivec/GPBExtensionInternals.h index 854b57fe89..af2aba6841 100644 --- a/objectivec/GPBExtensionInternals.h +++ b/objectivec/GPBExtensionInternals.h @@ -36,15 +36,12 @@ @class GPBCodedOutputStream; @protocol GPBExtensionRegistry; -void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, - BOOL isPackedOnStream, +void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream, GPBCodedInputStream *input, - idextensionRegistry, + id extensionRegistry, GPBMessage *message); -size_t GPBComputeExtensionSerializedSizeIncludingTag( - GPBExtensionDescriptor *extension, id value); +size_t GPBComputeExtensionSerializedSizeIncludingTag(GPBExtensionDescriptor *extension, id value); -void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, - id value, +void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, id value, GPBCodedOutputStream *output); diff --git a/objectivec/GPBExtensionRegistry.h b/objectivec/GPBExtensionRegistry.h index b1850568d9..2c1270b19f 100644 --- a/objectivec/GPBExtensionRegistry.h +++ b/objectivec/GPBExtensionRegistry.h @@ -72,7 +72,7 @@ NS_ASSUME_NONNULL_BEGIN * MyMessage *msg = [MyMessage parseData:data extensionRegistry:registry error:&parseError]; * ``` **/ -@interface GPBExtensionRegistry : NSObject +@interface GPBExtensionRegistry : NSObject /** * Adds the given GPBExtensionDescriptor to this registry. diff --git a/objectivec/GPBMessage.h b/objectivec/GPBMessage.h index f80778bc39..76602b17fe 100644 --- a/objectivec/GPBMessage.h +++ b/objectivec/GPBMessage.h @@ -80,7 +80,7 @@ CF_EXTERN_C_END * @c +parseFromData:extensionRegistry:error: to provide an extension * registry. **/ -@interface GPBMessage : NSObject +@interface GPBMessage : NSObject // If you add an instance method/property to this class that may conflict with // fields declared in protos, you need to update objective_helpers.cc. The main @@ -427,8 +427,7 @@ CF_EXTERN_C_END * @param extension The extension descriptor under which to set the value. * @param value The value to be set as the extension. **/ -- (void)setExtension:(GPBExtensionDescriptor *)extension - value:(nullable id)value; +- (void)setExtension:(GPBExtensionDescriptor *)extension value:(nullable id)value; /** * Adds the given value to the extension for this message. This only applies @@ -449,9 +448,7 @@ CF_EXTERN_C_END * @param index The index of the extension to be replaced. * @param value The value to be replaced in the repeated extension. **/ -- (void)setExtension:(GPBExtensionDescriptor *)extension - index:(NSUInteger)index - value:(id)value; +- (void)setExtension:(GPBExtensionDescriptor *)extension index:(NSUInteger)index value:(id)value; /** * Clears the given extension for this message. diff --git a/objectivec/GPBMessage_PackagePrivate.h b/objectivec/GPBMessage_PackagePrivate.h index a8755a29ce..70b47a59bc 100644 --- a/objectivec/GPBMessage_PackagePrivate.h +++ b/objectivec/GPBMessage_PackagePrivate.h @@ -83,8 +83,7 @@ typedef struct GPBMessage_Storage *GPBMessage_StoragePtr; // Parses the next delimited message of this type from the input and merges it // with this message. - (void)mergeDelimitedFromCodedInputStream:(GPBCodedInputStream *)input - extensionRegistry: - (id)extensionRegistry; + extensionRegistry:(id)extensionRegistry; - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data; @@ -92,14 +91,12 @@ typedef struct GPBMessage_Storage *GPBMessage_StoragePtr; CF_EXTERN_C_BEGIN - // Call this before using the readOnlySemaphore_. This ensures it is created only once. void GPBPrepareReadOnlySemaphore(GPBMessage *self); // Returns a new instance that was automatically created by |autocreator| for // its field |field|. -GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, - GPBMessage *autocreator, +GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator, GPBFieldDescriptor *field) __attribute__((ns_returns_retained)); diff --git a/objectivec/GPBUnknownField.h b/objectivec/GPBUnknownField.h index 5b96023b16..a188990cf4 100644 --- a/objectivec/GPBUnknownField.h +++ b/objectivec/GPBUnknownField.h @@ -40,7 +40,7 @@ NS_ASSUME_NONNULL_BEGIN * Store an unknown field. These are used in conjunction with * GPBUnknownFieldSet. **/ -@interface GPBUnknownField : NSObject +@interface GPBUnknownField : NSObject /** Initialize a field with the given number. */ - (instancetype)initWithNumber:(int32_t)number; @@ -58,10 +58,10 @@ NS_ASSUME_NONNULL_BEGIN @property(nonatomic, readonly, strong) GPBUInt64Array *fixed64List; /** An array of data values for this field. */ -@property(nonatomic, readonly, strong) NSArray *lengthDelimitedList; +@property(nonatomic, readonly, strong) NSArray *lengthDelimitedList; /** An array of groups of values for this field. */ -@property(nonatomic, readonly, strong) NSArray *groupList; +@property(nonatomic, readonly, strong) NSArray *groupList; /** * Add a value to the varintList. diff --git a/objectivec/GPBUnknownFieldSet.h b/objectivec/GPBUnknownFieldSet.h index 1b5f24f392..aed5b52d4c 100644 --- a/objectivec/GPBUnknownFieldSet.h +++ b/objectivec/GPBUnknownFieldSet.h @@ -40,7 +40,7 @@ NS_ASSUME_NONNULL_BEGIN * applies for files declared with the "proto2" syntax. Files declared with the * "proto3" syntax discard the unknown values. **/ -@interface GPBUnknownFieldSet : NSObject +@interface GPBUnknownFieldSet : NSObject /** * Tests to see if the given field number has a value. diff --git a/objectivec/GPBUtilities.h b/objectivec/GPBUtilities.h index fd5a4634a5..e49ada59ab 100644 --- a/objectivec/GPBUtilities.h +++ b/objectivec/GPBUtilities.h @@ -50,8 +50,7 @@ NS_ASSUME_NONNULL_BEGIN * * @return An NSString with the TextFormat of the message. **/ -NSString *GPBTextFormatForMessage(GPBMessage *message, - NSString * __nullable lineIndent); +NSString *GPBTextFormatForMessage(GPBMessage *message, NSString *__nullable lineIndent); /** * Generates a string that should be a valid "TextFormat" for the C++ version @@ -63,8 +62,8 @@ NSString *GPBTextFormatForMessage(GPBMessage *message, * * @return An NSString with the TextFormat of the unknown field set. **/ -NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet * __nullable unknownSet, - NSString * __nullable lineIndent); +NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *__nullable unknownSet, + NSString *__nullable lineIndent); /** * Checks if the given field number is set on a message. diff --git a/objectivec/GPBUtilities_PackagePrivate.h b/objectivec/GPBUtilities_PackagePrivate.h index 042396b4d8..f04ed8316b 100644 --- a/objectivec/GPBUtilities_PackagePrivate.h +++ b/objectivec/GPBUtilities_PackagePrivate.h @@ -40,17 +40,15 @@ #define GPBStringify(S) #S #define GPBStringifySymbol(S) GPBStringify(S) -#define GPBNSStringify(S) @#S +#define GPBNSStringify(S) @ #S #define GPBNSStringifySymbol(S) GPBNSStringify(S) // Macros for generating a Class from a class name. These are used in // the generated GPB descriptor classes wherever an Objective C class // reference is needed for a generated class. #define GPBObjCClassSymbol(name) OBJC_CLASS_$_##name -#define GPBObjCClass(name) \ - ((__bridge Class)&(GPBObjCClassSymbol(name))) -#define GPBObjCClassDeclaration(name) \ - extern const GPBObjcClass_t GPBObjCClassSymbol(name) +#define GPBObjCClass(name) ((__bridge Class) & (GPBObjCClassSymbol(name))) +#define GPBObjCClassDeclaration(name) extern const GPBObjcClass_t GPBObjCClassSymbol(name) // Constant to internally mark when there is no has bit. #define GPBNoHasBit INT32_MAX @@ -120,7 +118,7 @@ GPB_INLINE int64_t GPBLogicalRightShift64(int64_t value, int32_t spaces) { // negative values must be sign-extended to 64 bits to be varint encoded, // thus always taking 10 bytes on the wire.) GPB_INLINE int32_t GPBDecodeZigZag32(uint32_t n) { - return (int32_t)(GPBLogicalRightShift32((int32_t)n, 1) ^ -((int32_t)(n) & 1)); + return (int32_t)(GPBLogicalRightShift32((int32_t)n, 1) ^ -((int32_t)(n)&1)); } // Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers @@ -128,7 +126,7 @@ GPB_INLINE int32_t GPBDecodeZigZag32(uint32_t n) { // negative values must be sign-extended to 64 bits to be varint encoded, // thus always taking 10 bytes on the wire.) GPB_INLINE int64_t GPBDecodeZigZag64(uint64_t n) { - return (int64_t)(GPBLogicalRightShift64((int64_t)n, 1) ^ -((int64_t)(n) & 1)); + return (int64_t)(GPBLogicalRightShift64((int64_t)n, 1) ^ -((int64_t)(n)&1)); } // Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers @@ -197,12 +195,10 @@ GPB_INLINE BOOL GPBFieldStoresObject(GPBFieldDescriptor *field) { } BOOL GPBGetHasIvar(GPBMessage *self, int32_t index, uint32_t fieldNumber); -void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, - BOOL value); +void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, BOOL value); uint32_t GPBGetHasOneof(GPBMessage *self, int32_t index); -GPB_INLINE BOOL -GPBGetHasIvarField(GPBMessage *self, GPBFieldDescriptor *field) { +GPB_INLINE BOOL GPBGetHasIvarField(GPBMessage *self, GPBFieldDescriptor *field) { GPBMessageFieldDescription *fieldDesc = field->description_; return GPBGetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number); } @@ -262,28 +258,21 @@ void GPBSetDoubleIvarWithFieldPrivate(GPBMessage *self, // clang-format on -void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self, - GPBFieldDescriptor *field, - int32_t value); +void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, int32_t value); id GPBGetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); -void GPBSetObjectIvarWithFieldPrivate(GPBMessage *self, - GPBFieldDescriptor *field, id value); -void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, - GPBFieldDescriptor *field, - id __attribute__((ns_consumed)) - value); +void GPBSetObjectIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, id value); +void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, + id __attribute__((ns_consumed)) value); // GPBGetObjectIvarWithField will automatically create the field (message) if // it doesn't exist. GPBGetObjectIvarWithFieldNoAutocreate will return nil. -id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, - GPBFieldDescriptor *field); +id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, GPBFieldDescriptor *field); // Clears and releases the autocreated message ivar, if it's autocreated. If // it's not set as autocreated, this method does nothing. -void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field); +void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); // Returns an Objective C encoding for |selector|. |instanceSel| should be // YES if it's an instance selector (as opposed to a class selector). @@ -293,17 +282,13 @@ const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel); // Helper for text format name encoding. // decodeData is the data describing the special decodes. // key and inputString are the input that needs decoding. -NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, - NSString *inputString); - +NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, NSString *inputString); // Shims from the older generated code into the runtime. -void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, - GPBFieldDescriptor *field, - int32_t value, +void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int32_t value, GPBFileSyntax syntax); -void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, - int32_t oneofHasIndex, uint32_t fieldNumberNotToClear); +void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, int32_t oneofHasIndex, + uint32_t fieldNumberNotToClear); // A series of selectors that are used solely to get @encoding values // for them by the dynamic protobuf runtime code. See diff --git a/objectivec/GPBWellKnownTypes.h b/objectivec/GPBWellKnownTypes.h index 80d9db00e9..765ad24fb8 100644 --- a/objectivec/GPBWellKnownTypes.h +++ b/objectivec/GPBWellKnownTypes.h @@ -141,8 +141,7 @@ typedef NS_ENUM(NSInteger, GPBWellKnownTypesErrorCode) { * * @return A newly configured GPBAny with the given message, or nil on failure. */ -+ (nullable instancetype)anyWithMessage:(nonnull GPBMessage *)message - error:(NSError **)errorPtr; ++ (nullable instancetype)anyWithMessage:(nonnull GPBMessage *)message error:(NSError **)errorPtr; /** * Convenience method to create a GPBAny containing the serialized message. @@ -168,8 +167,7 @@ typedef NS_ENUM(NSInteger, GPBWellKnownTypesErrorCode) { * * @return A newly configured GPBAny with the given message, or nil on failure. */ -- (nullable instancetype)initWithMessage:(nonnull GPBMessage *)message - error:(NSError **)errorPtr; +- (nullable instancetype)initWithMessage:(nonnull GPBMessage *)message error:(NSError **)errorPtr; /** * Initializes a GPBAny to contain the serialized message. @@ -195,8 +193,7 @@ typedef NS_ENUM(NSInteger, GPBWellKnownTypesErrorCode) { * * @return Whether the packing was successful or not. */ -- (BOOL)packWithMessage:(nonnull GPBMessage *)message - error:(NSError **)errorPtr; +- (BOOL)packWithMessage:(nonnull GPBMessage *)message error:(NSError **)errorPtr; /** * Packs the serialized message into this GPBAny. @@ -225,8 +222,7 @@ typedef NS_ENUM(NSInteger, GPBWellKnownTypesErrorCode) { * @return An instance of the given class populated with the contained data, or * nil on failure. */ -- (nullable GPBMessage *)unpackMessageClass:(Class)messageClass - error:(NSError **)errorPtr; +- (nullable GPBMessage *)unpackMessageClass:(Class)messageClass error:(NSError **)errorPtr; @end From 189f6325d4587f3bd0567daa7e36b622e04895e4 Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Mon, 19 Sep 2022 17:21:13 -0400 Subject: [PATCH 61/64] Format the runtime sources. --- objectivec/GPBArray.m | 47 ++- objectivec/GPBCodedInputStream.m | 62 ++-- objectivec/GPBCodedOutputStream.m | 105 +++---- objectivec/GPBDescriptor.m | 208 +++++-------- objectivec/GPBDictionary.m | 101 +++---- objectivec/GPBExtensionInternals.m | 144 +++++---- objectivec/GPBExtensionRegistry.m | 24 +- objectivec/GPBMessage.m | 199 +++++------- objectivec/GPBProtocolBuffers.m | 1 - objectivec/GPBRootObject.m | 41 +-- objectivec/GPBUnknownField.m | 93 +++--- objectivec/GPBUnknownFieldSet.m | 75 ++--- objectivec/GPBUtilities.m | 465 +++++++++++++---------------- objectivec/GPBWellKnownTypes.m | 79 ++--- 14 files changed, 677 insertions(+), 967 deletions(-) diff --git a/objectivec/GPBArray.m b/objectivec/GPBArray.m index 1db7a8f638..eba7d15a6b 100644 --- a/objectivec/GPBArray.m +++ b/objectivec/GPBArray.m @@ -2056,19 +2056,15 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { return [[[self alloc] initWithValidationFunction:func] autorelease]; } -+ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func - rawValue:(int32_t)value { - return [[[self alloc] initWithValidationFunction:func - rawValues:&value - count:1] autorelease]; ++ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func rawValue:(int32_t)value { + return [[[self alloc] initWithValidationFunction:func rawValues:&value count:1] autorelease]; } + (instancetype)arrayWithValueArray:(GPBEnumArray *)array { - return [[(GPBEnumArray*)[self alloc] initWithValueArray:array] autorelease]; + return [[(GPBEnumArray *)[self alloc] initWithValueArray:array] autorelease]; } -+ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func - capacity:(NSUInteger)count { ++ (instancetype)arrayWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count { return [[[self alloc] initWithValidationFunction:func capacity:count] autorelease]; } @@ -2091,7 +2087,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func - rawValues:(const int32_t [])values + rawValues:(const int32_t[])values count:(NSUInteger)count { self = [self initWithValidationFunction:func]; if (self) { @@ -2103,17 +2099,16 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { _count = count; } else { [self release]; - [NSException raise:NSMallocException - format:@"Failed to allocate %lu bytes", - (unsigned long)(count * sizeof(int32_t))]; + [NSException + raise:NSMallocException + format:@"Failed to allocate %lu bytes", (unsigned long)(count * sizeof(int32_t))]; } } } return self; } -- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func - capacity:(NSUInteger)count { +- (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func capacity:(NSUInteger)count { self = [self initWithValidationFunction:func]; if (self && count) { [self internalResizeToCapacity:count]; @@ -2122,10 +2117,9 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (instancetype)copyWithZone:(NSZone *)zone { - return [[GPBEnumArray allocWithZone:zone] - initWithValidationFunction:_validationFunc - rawValues:_values - count:_count]; + return [[GPBEnumArray allocWithZone:zone] initWithValidationFunction:_validationFunc + rawValues:_values + count:_count]; } // Disable clang-format for the macros. @@ -2197,7 +2191,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { // clang-format on - (int32_t)valueAtIndex:(NSUInteger)index { -// clang-format off + // clang-format off //%PDDM-EXPAND VALIDATE_RANGE(index, _count) // This block of code is generated, do not edit it directly. @@ -2207,7 +2201,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { (unsigned long)index, (unsigned long)_count]; } //%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) -// clang-format on + // clang-format on int32_t result = _values[index]; if (!_validationFunc(result)) { result = kGPBUnrecognizedEnumeratorValue; @@ -2216,7 +2210,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (int32_t)rawValueAtIndex:(NSUInteger)index { -// clang-format off + // clang-format off //%PDDM-EXPAND VALIDATE_RANGE(index, _count) // This block of code is generated, do not edit it directly. @@ -2226,16 +2220,18 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { (unsigned long)index, (unsigned long)_count]; } //%PDDM-EXPAND-END VALIDATE_RANGE(index, _count) -// clang-format on + // clang-format on return _values[index]; } -- (void)enumerateValuesWithBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { +- (void)enumerateValuesWithBlock:(void(NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop)) + block { [self enumerateValuesWithOptions:(NSEnumerationOptions)0 usingBlock:block]; } - (void)enumerateValuesWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(int32_t value, NSUInteger idx, BOOL *stop)) + block { // NSEnumerationConcurrent isn't currently supported (and Apple's docs say that is ok). BOOL stop = NO; GPBEnumValidationFunc func = _validationFunc; @@ -2472,8 +2468,7 @@ static BOOL ArrayDefault_IsValidValue(int32_t value) { } - (void)dealloc { - NSAssert(!_autocreator, - @"%@: Autocreator must be cleared before release, autocreator: %@", + NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_array release]; [super dealloc]; diff --git a/objectivec/GPBCodedInputStream.m b/objectivec/GPBCodedInputStream.m index 25dde75320..ad5c75e4ef 100644 --- a/objectivec/GPBCodedInputStream.m +++ b/objectivec/GPBCodedInputStream.m @@ -36,8 +36,7 @@ #import "GPBUtilities_PackagePrivate.h" #import "GPBWireFormat.h" -NSString *const GPBCodedInputStreamException = - GPBNSStringifySymbol(GPBCodedInputStreamException); +NSString *const GPBCodedInputStreamException = GPBNSStringifySymbol(GPBCodedInputStreamException); NSString *const GPBCodedInputStreamUnderlyingErrorKey = GPBNSStringifySymbol(GPBCodedInputStreamUnderlyingErrorKey); @@ -55,16 +54,14 @@ static const NSUInteger kDefaultRecursionLimit = 100; static void RaiseException(NSInteger code, NSString *reason) { NSDictionary *errorInfo = nil; if ([reason length]) { - errorInfo = @{ GPBErrorReasonKey: reason }; + errorInfo = @{GPBErrorReasonKey : reason}; } NSError *error = [NSError errorWithDomain:GPBCodedInputStreamErrorDomain code:code userInfo:errorInfo]; - NSDictionary *exceptionInfo = - @{ GPBCodedInputStreamUnderlyingErrorKey: error }; - [[NSException exceptionWithName:GPBCodedInputStreamException - reason:reason + NSDictionary *exceptionInfo = @{GPBCodedInputStreamUnderlyingErrorKey : error}; + [[NSException exceptionWithName:GPBCodedInputStreamException reason:reason userInfo:exceptionInfo] raise]; } @@ -105,7 +102,7 @@ static int32_t ReadRawLittleEndian32(GPBCodedInputStreamState *state) { static int64_t ReadRawLittleEndian64(GPBCodedInputStreamState *state) { CheckSize(state, sizeof(int64_t)); // Not using OSReadLittleInt64 because it has undocumented dependency - // on reads being aligned. + // on reads being aligned. int64_t value; memcpy(&value, state->bytes + state->bufferPos, sizeof(int64_t)); value = OSSwapLittleToHostInt64(value); @@ -215,8 +212,7 @@ int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) { state->lastTag = ReadRawVarint32(state); // Tags have to include a valid wireformat. if (!GPBWireFormatIsValidTag(state->lastTag)) { - RaiseException(GPBCodedInputStreamErrorInvalidTag, - @"Invalid wireformat in tag."); + RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Invalid wireformat in tag."); } // Zero is not a valid field number. if (GPBWireFormatGetTagFieldNumber(state->lastTag) == 0) { @@ -226,8 +222,7 @@ int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) { return state->lastTag; } -NSString *GPBCodedInputStreamReadRetainedString( - GPBCodedInputStreamState *state) { +NSString *GPBCodedInputStreamReadRetainedString(GPBCodedInputStreamState *state) { int32_t size = ReadRawVarint32(state); NSString *result; if (size == 0) { @@ -254,28 +249,24 @@ NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) { int32_t size = ReadRawVarint32(state); if (size < 0) return nil; CheckSize(state, size); - NSData *result = [[NSData alloc] initWithBytes:state->bytes + state->bufferPos - length:size]; + NSData *result = [[NSData alloc] initWithBytes:state->bytes + state->bufferPos length:size]; state->bufferPos += size; return result; } -NSData *GPBCodedInputStreamReadRetainedBytesNoCopy( - GPBCodedInputStreamState *state) { +NSData *GPBCodedInputStreamReadRetainedBytesNoCopy(GPBCodedInputStreamState *state) { int32_t size = ReadRawVarint32(state); if (size < 0) return nil; CheckSize(state, size); // Cast is safe because freeWhenDone is NO. - NSData *result = [[NSData alloc] - initWithBytesNoCopy:(void *)(state->bytes + state->bufferPos) - length:size - freeWhenDone:NO]; + NSData *result = [[NSData alloc] initWithBytesNoCopy:(void *)(state->bytes + state->bufferPos) + length:size + freeWhenDone:NO]; state->bufferPos += size; return result; } -size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, - size_t byteLimit) { +size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, size_t byteLimit) { byteLimit += state->bufferPos; size_t oldLimit = state->currentLimit; if (byteLimit > oldLimit) { @@ -285,8 +276,7 @@ size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state, return oldLimit; } -void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, - size_t oldLimit) { +void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state, size_t oldLimit) { state->currentLimit = oldLimit; } @@ -295,12 +285,10 @@ size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state) { } BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state) { - return (state->bufferPos == state->bufferSize) || - (state->bufferPos == state->currentLimit); + return (state->bufferPos == state->bufferSize) || (state->bufferPos == state->currentLimit); } -void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, - int32_t value) { +void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, int32_t value) { if (state->lastTag != value) { RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Unexpected tag read"); } @@ -360,8 +348,8 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, case GPBWireFormatStartGroup: [self skipMessage]; GPBCodedInputStreamCheckLastTagWas( - &state_, GPBWireFormatMakeTag(GPBWireFormatGetTagFieldNumber(tag), - GPBWireFormatEndGroup)); + &state_, + GPBWireFormatMakeTag(GPBWireFormatGetTagFieldNumber(tag), GPBWireFormatEndGroup)); return YES; case GPBWireFormatEndGroup: return NO; @@ -438,18 +426,17 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, CheckRecursionLimit(&state_); ++state_.recursionDepth; [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry]; - GPBCodedInputStreamCheckLastTagWas( - &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); + GPBCodedInputStreamCheckLastTagWas(&state_, + GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); --state_.recursionDepth; } -- (void)readUnknownGroup:(int32_t)fieldNumber - message:(GPBUnknownFieldSet *)message { +- (void)readUnknownGroup:(int32_t)fieldNumber message:(GPBUnknownFieldSet *)message { CheckRecursionLimit(&state_); ++state_.recursionDepth; [message mergeFromCodedInputStream:self]; - GPBCodedInputStreamCheckLastTagWas( - &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); + GPBCodedInputStreamCheckLastTagWas(&state_, + GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup)); --state_.recursionDepth; } @@ -473,8 +460,7 @@ void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state, int32_t length = ReadRawVarint32(&state_); size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length); ++state_.recursionDepth; - GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field, - parentMessage); + GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field, parentMessage); GPBCodedInputStreamCheckLastTagWas(&state_, 0); --state_.recursionDepth; GPBCodedInputStreamPopLimit(&state_, oldLimit); diff --git a/objectivec/GPBCodedOutputStream.m b/objectivec/GPBCodedOutputStream.m index 5a147aa7c6..6dd537a467 100644 --- a/objectivec/GPBCodedOutputStream.m +++ b/objectivec/GPBCodedOutputStream.m @@ -67,8 +67,7 @@ static void GPBRefreshBuffer(GPBOutputBufferState *state) { [NSException raise:GPBCodedOutputStreamException_OutOfSpace format:@""]; } if (state->position != 0) { - NSInteger written = - [state->output write:state->bytes maxLength:state->position]; + NSInteger written = [state->output write:state->bytes maxLength:state->position]; if (written != (NSInteger)state->position) { [NSException raise:GPBCodedOutputStreamException_WriteFailed format:@""]; } @@ -118,27 +117,24 @@ static void GPBWriteInt32NoTag(GPBOutputBufferState *state, int32_t value) { } } -static void GPBWriteUInt32(GPBOutputBufferState *state, int32_t fieldNumber, - uint32_t value) { +static void GPBWriteUInt32(GPBOutputBufferState *state, int32_t fieldNumber, uint32_t value) { GPBWriteTagWithFormat(state, fieldNumber, GPBWireFormatVarint); GPBWriteRawVarint32(state, value); } -static void GPBWriteTagWithFormat(GPBOutputBufferState *state, - uint32_t fieldNumber, GPBWireFormat format) { +static void GPBWriteTagWithFormat(GPBOutputBufferState *state, uint32_t fieldNumber, + GPBWireFormat format) { GPBWriteRawVarint32(state, GPBWireFormatMakeTag(fieldNumber, format)); } -static void GPBWriteRawLittleEndian32(GPBOutputBufferState *state, - int32_t value) { +static void GPBWriteRawLittleEndian32(GPBOutputBufferState *state, int32_t value) { GPBWriteRawByte(state, (value)&0xFF); GPBWriteRawByte(state, (value >> 8) & 0xFF); GPBWriteRawByte(state, (value >> 16) & 0xFF); GPBWriteRawByte(state, (value >> 24) & 0xFF); } -static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, - int64_t value) { +static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, int64_t value) { GPBWriteRawByte(state, (int32_t)(value)&0xFF); GPBWriteRawByte(state, (int32_t)(value >> 8) & 0xFF); GPBWriteRawByte(state, (int32_t)(value >> 16) & 0xFF); @@ -170,8 +166,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, // This initializer isn't exposed, but it is the designated initializer. // Setting OutputStream and NSData is to control the buffering behavior/size // of the work, but that is more obvious via the bufferSize: version. -- (instancetype)initWithOutputStream:(NSOutputStream *)output - data:(NSMutableData *)data { +- (instancetype)initWithOutputStream:(NSOutputStream *)output data:(NSMutableData *)data { if ((self = [super init])) { buffer_ = [data retain]; state_.bytes = [data mutableBytes]; @@ -184,8 +179,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, + (instancetype)streamWithOutputStream:(NSOutputStream *)output { NSMutableData *data = [NSMutableData dataWithLength:PAGE_SIZE]; - return [[[self alloc] initWithOutputStream:output - data:data] autorelease]; + return [[[self alloc] initWithOutputStream:output data:data] autorelease]; } + (instancetype)streamWithData:(NSMutableData *)data { @@ -277,8 +271,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, return; } - const char *quickString = - CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8); + const char *quickString = CFStringGetCStringPtr((CFStringRef)value, kCFStringEncodingUTF8); // Fast path: Most strings are short, if the buffer already has space, // add to it directly. @@ -300,9 +293,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, remainingRange:NULL]; } if (result) { - NSAssert2((usedBufferLength == length), - @"Our UTF8 calc was wrong? %tu vs %zd", usedBufferLength, - length); + NSAssert2((usedBufferLength == length), @"Our UTF8 calc was wrong? %tu vs %zd", + usedBufferLength, length); state_.position += usedBufferLength; return; } @@ -311,9 +303,8 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, } else { // Slow path: just get it as data and write it out. NSData *utf8Data = [value dataUsingEncoding:NSUTF8StringEncoding]; - NSAssert2(([utf8Data length] == length), - @"Strings UTF8 length was wrong? %tu vs %zd", [utf8Data length], - length); + NSAssert2(([utf8Data length] == length), @"Strings UTF8 length was wrong? %tu vs %zd", + [utf8Data length], length); [self writeRawData:utf8Data]; } } @@ -333,14 +324,12 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, [self writeGroupNoTag:fieldNumber value:value]; } -- (void)writeUnknownGroupNoTag:(int32_t)fieldNumber - value:(const GPBUnknownFieldSet *)value { +- (void)writeUnknownGroupNoTag:(int32_t)fieldNumber value:(const GPBUnknownFieldSet *)value { [value writeToCodedOutputStream:self]; GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatEndGroup); } -- (void)writeUnknownGroup:(int32_t)fieldNumber - value:(GPBUnknownFieldSet *)value { +- (void)writeUnknownGroup:(int32_t)fieldNumber value:(GPBUnknownFieldSet *)value { GPBWriteTagWithFormat(&state_, fieldNumber, GPBWireFormatStartGroup); [self writeUnknownGroupNoTag:fieldNumber value:value]; } @@ -879,23 +868,18 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, // clang-format on -- (void)writeMessageSetExtension:(int32_t)fieldNumber - value:(GPBMessage *)value { - GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, - GPBWireFormatStartGroup); +- (void)writeMessageSetExtension:(int32_t)fieldNumber value:(GPBMessage *)value { + GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatStartGroup); GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber); [self writeMessage:GPBWireFormatMessageSetMessage value:value]; - GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, - GPBWireFormatEndGroup); + GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatEndGroup); } - (void)writeRawMessageSetExtension:(int32_t)fieldNumber value:(NSData *)value { - GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, - GPBWireFormatStartGroup); + GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatStartGroup); GPBWriteUInt32(&state_, GPBWireFormatMessageSetTypeId, fieldNumber); [self writeBytes:GPBWireFormatMessageSetMessage value:value]; - GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, - GPBWireFormatEndGroup); + GPBWriteTagWithFormat(&state_, GPBWireFormatMessageSetItem, GPBWireFormatEndGroup); } - (void)flush { @@ -912,9 +896,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, [self writeRawPtr:[data bytes] offset:0 length:[data length]]; } -- (void)writeRawPtr:(const void *)value - offset:(size_t)offset - length:(size_t)length { +- (void)writeRawPtr:(const void *)value offset:(size_t)offset length:(size_t)length { if (value == nil || length == 0) { return; } @@ -929,8 +911,7 @@ static void GPBWriteRawLittleEndian64(GPBOutputBufferState *state, // Write extends past current buffer. Fill the rest of this buffer and // flush. size_t bytesWritten = bufferBytesLeft; - memcpy(state_.bytes + state_.position, ((uint8_t *)value) + offset, - bytesWritten); + memcpy(state_.bytes + state_.position, ((uint8_t *)value) + offset, bytesWritten); offset += bytesWritten; length -= bytesWritten; state_.position = bufferLength; @@ -993,13 +974,9 @@ size_t GPBComputeFloatSizeNoTag(Float32 value) { return LITTLE_ENDIAN_32_SIZE; } -size_t GPBComputeUInt64SizeNoTag(uint64_t value) { - return GPBComputeRawVarint64Size(value); -} +size_t GPBComputeUInt64SizeNoTag(uint64_t value) { return GPBComputeRawVarint64Size(value); } -size_t GPBComputeInt64SizeNoTag(int64_t value) { - return GPBComputeRawVarint64Size(value); -} +size_t GPBComputeInt64SizeNoTag(int64_t value) { return GPBComputeRawVarint64Size(value); } size_t GPBComputeInt32SizeNoTag(int32_t value) { if (value >= 0) { @@ -1034,13 +1011,9 @@ size_t GPBComputeStringSizeNoTag(NSString *value) { return GPBComputeRawVarint32SizeForInteger(length) + length; } -size_t GPBComputeGroupSizeNoTag(GPBMessage *value) { - return [value serializedSize]; -} +size_t GPBComputeGroupSizeNoTag(GPBMessage *value) { return [value serializedSize]; } -size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) { - return value.serializedSize; -} +size_t GPBComputeUnknownGroupSizeNoTag(GPBUnknownFieldSet *value) { return value.serializedSize; } size_t GPBComputeMessageSizeNoTag(GPBMessage *value) { size_t size = [value serializedSize]; @@ -1052,13 +1025,9 @@ size_t GPBComputeBytesSizeNoTag(NSData *value) { return GPBComputeRawVarint32SizeForInteger(valueLength) + valueLength; } -size_t GPBComputeUInt32SizeNoTag(int32_t value) { - return GPBComputeRawVarint32Size(value); -} +size_t GPBComputeUInt32SizeNoTag(int32_t value) { return GPBComputeRawVarint32Size(value); } -size_t GPBComputeEnumSizeNoTag(int32_t value) { - return GPBComputeInt32SizeNoTag(value); -} +size_t GPBComputeEnumSizeNoTag(int32_t value) { return GPBComputeInt32SizeNoTag(value); } size_t GPBComputeSFixed32SizeNoTag(int32_t value) { #pragma unused(value) @@ -1118,10 +1087,8 @@ size_t GPBComputeGroupSize(int32_t fieldNumber, GPBMessage *value) { return GPBComputeTagSize(fieldNumber) * 2 + GPBComputeGroupSizeNoTag(value); } -size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, - GPBUnknownFieldSet *value) { - return GPBComputeTagSize(fieldNumber) * 2 + - GPBComputeUnknownGroupSizeNoTag(value); +size_t GPBComputeUnknownGroupSize(int32_t fieldNumber, GPBUnknownFieldSet *value) { + return GPBComputeTagSize(fieldNumber) * 2 + GPBComputeUnknownGroupSizeNoTag(value); } size_t GPBComputeMessageSize(int32_t fieldNumber, GPBMessage *value) { @@ -1153,27 +1120,23 @@ size_t GPBComputeSInt32Size(int32_t fieldNumber, int32_t value) { } size_t GPBComputeSInt64Size(int32_t fieldNumber, int64_t value) { - return GPBComputeTagSize(fieldNumber) + - GPBComputeRawVarint64Size(GPBEncodeZigZag64(value)); + return GPBComputeTagSize(fieldNumber) + GPBComputeRawVarint64Size(GPBEncodeZigZag64(value)); } -size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, - GPBMessage *value) { +size_t GPBComputeMessageSetExtensionSize(int32_t fieldNumber, GPBMessage *value) { return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 + GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) + GPBComputeMessageSize(GPBWireFormatMessageSetMessage, value); } -size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, - NSData *value) { +size_t GPBComputeRawMessageSetExtensionSize(int32_t fieldNumber, NSData *value) { return GPBComputeTagSize(GPBWireFormatMessageSetItem) * 2 + GPBComputeUInt32Size(GPBWireFormatMessageSetTypeId, fieldNumber) + GPBComputeBytesSize(GPBWireFormatMessageSetMessage, value); } size_t GPBComputeTagSize(int32_t fieldNumber) { - return GPBComputeRawVarint32Size( - GPBWireFormatMakeTag(fieldNumber, GPBWireFormatVarint)); + return GPBComputeRawVarint32Size(GPBWireFormatMakeTag(fieldNumber, GPBWireFormatVarint)); } size_t GPBComputeWireFormatTagSize(int field_number, GPBDataType dataType) { diff --git a/objectivec/GPBDescriptor.m b/objectivec/GPBDescriptor.m index c29b95539f..f6feaffe4e 100644 --- a/objectivec/GPBDescriptor.m +++ b/objectivec/GPBDescriptor.m @@ -32,9 +32,9 @@ #import +#import "GPBMessage_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h" #import "GPBWireFormat.h" -#import "GPBMessage_PackagePrivate.h" // Direct access is use for speed, to avoid even internally declaring things // read/write, etc. The warning is enabled in the project to ensure code calling @@ -48,16 +48,15 @@ static const char kParentClassValueKey = 0; static const char kClassNameSuffixKey = 0; // Utility function to generate selectors on the fly. -static SEL SelFromStrings(const char *prefix, const char *middle, - const char *suffix, BOOL takesArg) { +static SEL SelFromStrings(const char *prefix, const char *middle, const char *suffix, + BOOL takesArg) { if (prefix == NULL && suffix == NULL && !takesArg) { return sel_getUid(middle); } const size_t prefixLen = prefix != NULL ? strlen(prefix) : 0; const size_t middleLen = strlen(middle); const size_t suffixLen = suffix != NULL ? strlen(suffix) : 0; - size_t totalLen = - prefixLen + middleLen + suffixLen + 1; // include space for null on end. + size_t totalLen = prefixLen + middleLen + suffixLen + 1; // include space for null on end. if (takesArg) { totalLen += 1; } @@ -82,12 +81,10 @@ static SEL SelFromStrings(const char *prefix, const char *middle, return result; } -static NSArray *NewFieldsArrayForHasIndex(int hasIndex, - NSArray *allMessageFields) +static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSArray *allMessageFields) __attribute__((ns_returns_retained)); -static NSArray *NewFieldsArrayForHasIndex(int hasIndex, - NSArray *allMessageFields) { +static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSArray *allMessageFields) { NSMutableArray *result = [[NSMutableArray alloc] init]; for (GPBFieldDescriptor *fieldDesc in allMessageFields) { if (fieldDesc->description_->hasIndex == hasIndex) { @@ -111,25 +108,21 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, @synthesize file = file_; @synthesize wireFormat = wireFormat_; -+ (instancetype) - allocDescriptorForClass:(Class)messageClass - rootClass:(Class)rootClass - file:(GPBFileDescriptor *)file - fields:(void *)fieldDescriptions - fieldCount:(uint32_t)fieldCount - storageSize:(uint32_t)storageSize - flags:(GPBDescriptorInitializationFlags)flags { ++ (instancetype)allocDescriptorForClass:(Class)messageClass + rootClass:(Class)rootClass + file:(GPBFileDescriptor *)file + fields:(void *)fieldDescriptions + fieldCount:(uint32_t)fieldCount + storageSize:(uint32_t)storageSize + flags:(GPBDescriptorInitializationFlags)flags { // The rootClass is no longer used, but it is passed in to ensure it // was started up during initialization also. (void)rootClass; NSMutableArray *fields = nil; GPBFileSyntax syntax = file.syntax; - BOOL fieldsIncludeDefault = - (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0; - BOOL usesClassRefs = - (flags & GPBDescriptorInitializationFlag_UsesClassRefs) != 0; - BOOL proto3OptionalKnown = - (flags & GPBDescriptorInitializationFlag_Proto3OptionalKnown) != 0; + BOOL fieldsIncludeDefault = (flags & GPBDescriptorInitializationFlag_FieldsWithDefault) != 0; + BOOL usesClassRefs = (flags & GPBDescriptorInitializationFlag_UsesClassRefs) != 0; + BOOL proto3OptionalKnown = (flags & GPBDescriptorInitializationFlag_Proto3OptionalKnown) != 0; void *desc; for (uint32_t i = 0; i < fieldCount; ++i) { @@ -193,10 +186,9 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, for (uint32_t i = 0, hasIndex = firstHasIndex; i < count; ++i, --hasIndex) { const char *name = oneofNames[i]; NSArray *fieldsForOneof = NewFieldsArrayForHasIndex(hasIndex, fields_); - NSCAssert(fieldsForOneof.count > 0, - @"No fields for this oneof? (%s:%d)", name, hasIndex); - GPBOneofDescriptor *oneofDescriptor = - [[GPBOneofDescriptor alloc] initWithName:name fields:fieldsForOneof]; + NSCAssert(fieldsForOneof.count > 0, @"No fields for this oneof? (%s:%d)", name, hasIndex); + GPBOneofDescriptor *oneofDescriptor = [[GPBOneofDescriptor alloc] initWithName:name + fields:fieldsForOneof]; [oneofs addObject:oneofDescriptor]; [oneofDescriptor release]; [fieldsForOneof release]; @@ -210,8 +202,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSValue *extraInfoValue = [NSValue valueWithPointer:extraTextFormatInfo]; for (GPBFieldDescriptor *fieldDescriptor in fields_) { if (fieldDescriptor->description_->flags & GPBFieldTextFormatNameCustom) { - objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey, - extraInfoValue, + objc_setAssociatedObject(fieldDescriptor, &kTextFormatExtraValueKey, extraInfoValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } } @@ -224,9 +215,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, } - (void)setupContainingMessageClass:(Class)messageClass { - objc_setAssociatedObject(self, &kParentClassValueKey, - messageClass, - OBJC_ASSOCIATION_ASSIGN); + objc_setAssociatedObject(self, &kParentClassValueKey, messageClass, OBJC_ASSOCIATION_ASSIGN); } - (void)setupContainingMessageClassName:(const char *)msgClassName { @@ -240,9 +229,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, - (void)setupMessageClassNameSuffix:(NSString *)suffix { if (suffix.length) { - objc_setAssociatedObject(self, &kClassNameSuffixKey, - suffix, - OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(self, &kClassNameSuffixKey, suffix, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } } @@ -260,9 +247,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, GPBFileDescriptor *file = self.file; NSString *objcPrefix = file.objcPrefix; if (objcPrefix && ![className hasPrefix:objcPrefix]) { - NSAssert(0, - @"Class didn't have correct prefix? (%@ - %@)", - className, objcPrefix); + NSAssert(0, @"Class didn't have correct prefix? (%@ - %@)", className, objcPrefix); return nil; } GPBDescriptor *parent = self.containingType; @@ -274,19 +259,16 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSString *suffix = objc_getAssociatedObject(parent, &kClassNameSuffixKey); if (suffix) { if (![parentClassName hasSuffix:suffix]) { - NSAssert(0, - @"ParentMessage class didn't have correct suffix? (%@ - %@)", - className, suffix); + NSAssert(0, @"ParentMessage class didn't have correct suffix? (%@ - %@)", className, + suffix); return nil; } - parentClassName = - [parentClassName substringToIndex:(parentClassName.length - suffix.length)]; + parentClassName = [parentClassName substringToIndex:(parentClassName.length - suffix.length)]; } NSString *parentPrefix = [parentClassName stringByAppendingString:@"_"]; if (![className hasPrefix:parentPrefix]) { - NSAssert(0, - @"Class didn't have the correct parent name prefix? (%@ - %@)", - parentPrefix, className); + NSAssert(0, @"Class didn't have the correct parent name prefix? (%@ - %@)", parentPrefix, + className); return nil; } name = [className substringFromIndex:parentPrefix.length]; @@ -298,9 +280,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, NSString *suffix = objc_getAssociatedObject(self, &kClassNameSuffixKey); if (suffix) { if (![name hasSuffix:suffix]) { - NSAssert(0, - @"Message class didn't have correct suffix? (%@ - %@)", - name, suffix); + NSAssert(0, @"Message class didn't have correct suffix? (%@ - %@)", name, suffix); return nil; } name = [name substringToIndex:(name.length - suffix.length)]; @@ -372,8 +352,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, return self; } -- (instancetype)initWithPackage:(NSString *)package - syntax:(GPBFileSyntax)syntax { +- (instancetype)initWithPackage:(NSString *)package syntax:(GPBFileSyntax)syntax { self = [super init]; if (self) { package_ = [package copy]; @@ -414,7 +393,7 @@ static NSArray *NewFieldsArrayForHasIndex(int hasIndex, } - (NSString *)name { - return (NSString * _Nonnull)@(name_); + return (NSString *_Nonnull)@(name_); } - (GPBFieldDescriptor *)fieldWithNumber:(uint32_t)fieldNumber { @@ -444,19 +423,17 @@ uint32_t GPBFieldTag(GPBFieldDescriptor *self) { // Maps are repeated messages on the wire. format = GPBWireFormatForType(GPBDataTypeMessage, NO); } else { - format = GPBWireFormatForType(description->dataType, - ((description->flags & GPBFieldPacked) != 0)); + format = + GPBWireFormatForType(description->dataType, ((description->flags & GPBFieldPacked) != 0)); } return GPBWireFormatMakeTag(description->number, format); } uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { GPBMessageFieldDescription *description = self->description_; - NSCAssert((description->flags & GPBFieldRepeated) != 0, - @"Only valid on repeated fields"); + NSCAssert((description->flags & GPBFieldRepeated) != 0, @"Only valid on repeated fields"); GPBWireFormat format = - GPBWireFormatForType(description->dataType, - ((description->flags & GPBFieldPacked) == 0)); + GPBWireFormatForType(description->dataType, ((description->flags & GPBFieldPacked) == 0)); return GPBWireFormatMakeTag(description->number, format); } @@ -516,10 +493,8 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { // - not repeated/map // - not in a oneof (negative has index) // - not a message (the flag doesn't make sense for messages) - BOOL clearOnZero = ((syntax == GPBFileSyntaxProto3) && - !isMapOrArray && - (coreDesc->hasIndex >= 0) && - !isMessage); + BOOL clearOnZero = ((syntax == GPBFileSyntaxProto3) && !isMapOrArray && + (coreDesc->hasIndex >= 0) && !isMessage); if (clearOnZero) { coreDesc->flags |= GPBFieldClearHasIvarOnZero; } @@ -534,8 +509,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { // It is a single field; it gets has/setHas selectors if... // - not in a oneof (negative has index) // - not clearing on zero - if ((coreDesc->hasIndex >= 0) && - ((coreDesc->flags & GPBFieldClearHasIvarOnZero) == 0)) { + if ((coreDesc->hasIndex >= 0) && ((coreDesc->flags & GPBFieldClearHasIvarOnZero) == 0)) { hasOrCountSel_ = SelFromStrings("has", coreDesc->name, NULL, NO); setHasSel_ = SelFromStrings("setHas", coreDesc->name, NULL, YES); } @@ -556,11 +530,9 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } } else if (dataType == GPBDataTypeEnum) { if ((coreDesc->flags & GPBFieldHasEnumDescriptor) != 0) { - enumHandling_.enumDescriptor_ = - coreDesc->dataTypeSpecific.enumDescFunc(); + enumHandling_.enumDescriptor_ = coreDesc->dataTypeSpecific.enumDescFunc(); } else { - enumHandling_.enumVerifier_ = - coreDesc->dataTypeSpecific.enumVerifier; + enumHandling_.enumVerifier_ = coreDesc->dataTypeSpecific.enumVerifier; } } @@ -576,8 +548,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { memcpy(&length, bytes, sizeof(length)); length = ntohl(length); bytes += sizeof(length); - defaultValue_.valueData = - [[NSData alloc] initWithBytes:bytes length:length]; + defaultValue_.valueData = [[NSData alloc] initWithBytes:bytes length:length]; } } } @@ -586,8 +557,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } - (void)dealloc { - if (description_->dataType == GPBDataTypeBytes && - !(description_->flags & GPBFieldRepeated)) { + if (description_->dataType == GPBDataTypeBytes && !(description_->flags & GPBFieldRepeated)) { [defaultValue_.valueData release]; } [super dealloc]; @@ -606,7 +576,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } - (NSString *)name { - return (NSString * _Nonnull)@(description_->name); + return (NSString *_Nonnull)@(description_->name); } - (BOOL)isRequired { @@ -666,8 +636,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } - (BOOL)isValidEnumValue:(int32_t)value { - NSAssert(description_->dataType == GPBDataTypeEnum, - @"Field Must be of type GPBDataTypeEnum"); + NSAssert(description_->dataType == GPBDataTypeEnum, @"Field Must be of type GPBDataTypeEnum"); if (description_->flags & GPBFieldHasEnumDescriptor) { return enumHandling_.enumDescriptor_.enumVerifier(value); } else { @@ -703,15 +672,13 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { - (NSString *)textFormatName { if ((description_->flags & GPBFieldTextFormatNameCustom) != 0) { - NSValue *extraInfoValue = - objc_getAssociatedObject(self, &kTextFormatExtraValueKey); + NSValue *extraInfoValue = objc_getAssociatedObject(self, &kTextFormatExtraValueKey); // Support can be left out at generation time. if (!extraInfoValue) { return nil; } const uint8_t *extraTextFormatInfo = [extraInfoValue pointerValue]; - return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self), - self.name); + return GPBDecodeTextFormatName(extraTextFormatInfo, GPBFieldNumber(self), self.name); } // The logic here has to match SetCommonFieldVariables() from @@ -726,8 +693,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } // Remove "Array" from the end for repeated fields. - if (((description_->flags & GPBFieldRepeated) != 0) && - [name hasSuffix:@"Array"]) { + if (((description_->flags & GPBFieldRepeated) != 0) && [name hasSuffix:@"Array"]) { name = [name substringToIndex:(len - 5)]; len = [name length]; } @@ -739,9 +705,8 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { if (firstChar >= 'a' && firstChar <= 'z') { NSString *firstCharString = [NSString stringWithFormat:@"%C", (unichar)(firstChar - 'a' + 'A')]; - NSString *result = - [name stringByReplacingCharactersInRange:NSMakeRange(0, 1) - withString:firstCharString]; + NSString *result = [name stringByReplacingCharactersInRange:NSMakeRange(0, 1) + withString:firstCharString]; return result; } return name; @@ -784,12 +749,11 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { @synthesize name = name_; @synthesize enumVerifier = enumVerifier_; -+ (instancetype) - allocDescriptorForName:(NSString *)name - valueNames:(const char *)valueNames - values:(const int32_t *)values - count:(uint32_t)valueCount - enumVerifier:(GPBEnumValidationFunc)enumVerifier { ++ (instancetype)allocDescriptorForName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier { GPBEnumDescriptor *descriptor = [[self alloc] initWithName:name valueNames:valueNames values:values @@ -798,13 +762,12 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { return descriptor; } -+ (instancetype) - allocDescriptorForName:(NSString *)name - valueNames:(const char *)valueNames - values:(const int32_t *)values - count:(uint32_t)valueCount - enumVerifier:(GPBEnumValidationFunc)enumVerifier - extraTextFormatInfo:(const char *)extraTextFormatInfo { ++ (instancetype)allocDescriptorForName:(NSString *)name + valueNames:(const char *)valueNames + values:(const int32_t *)values + count:(uint32_t)valueCount + enumVerifier:(GPBEnumValidationFunc)enumVerifier + extraTextFormatInfo:(const char *)extraTextFormatInfo { // Call the common case. GPBEnumDescriptor *descriptor = [self allocDescriptorForName:name valueNames:valueNames @@ -892,27 +855,26 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } - (BOOL)getValue:(int32_t *)outValue forEnumTextFormatName:(NSString *)textFormatName { - if (nameOffsets_ == NULL) [self calcValueNameOffsets]; - if (nameOffsets_ == NULL) return NO; + if (nameOffsets_ == NULL) [self calcValueNameOffsets]; + if (nameOffsets_ == NULL) return NO; - for (uint32_t i = 0; i < valueCount_; ++i) { - NSString *valueTextFormatName = [self getEnumTextFormatNameForIndex:i]; - if ([valueTextFormatName isEqual:textFormatName]) { - if (outValue) { - *outValue = values_[i]; - } - return YES; - } + for (uint32_t i = 0; i < valueCount_; ++i) { + NSString *valueTextFormatName = [self getEnumTextFormatNameForIndex:i]; + if ([valueTextFormatName isEqual:textFormatName]) { + if (outValue) { + *outValue = values_[i]; + } + return YES; } - return NO; + } + return NO; } - (NSString *)textFormatNameForValue:(int32_t)number { // Find the EnumValue descriptor and its index. BOOL foundIt = NO; uint32_t valueDescriptorIndex; - for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_; - ++valueDescriptorIndex) { + for (valueDescriptorIndex = 0; valueDescriptorIndex < valueCount_; ++valueDescriptorIndex) { if (values_[valueDescriptorIndex] == number) { foundIt = YES; break; @@ -955,8 +917,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { // See if it is in the map of special format handling. if (extraTextFormatInfo_) { - result = GPBDecodeTextFormatName(extraTextFormatInfo_, - (int32_t)index, shortName); + result = GPBDecodeTextFormatName(extraTextFormatInfo_, (int32_t)index, shortName); } // Logic here needs to match what objectivec_enum.cc does in the proto // compiler. @@ -1005,16 +966,14 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { GPBDataType type = description_->dataType; if (type == GPBDataTypeBytes) { // Data stored as a length prefixed c-string in descriptor records. - const uint8_t *bytes = - (const uint8_t *)description_->defaultValue.valueData; + const uint8_t *bytes = (const uint8_t *)description_->defaultValue.valueData; if (bytes) { uint32_t length; memcpy(&length, bytes, sizeof(length)); // The length is stored in network byte order. length = ntohl(length); bytes += sizeof(length); - defaultValue_.valueData = - [[NSData alloc] initWithBytes:bytes length:length]; + defaultValue_.valueData = [[NSData alloc] initWithBytes:bytes length:length]; } } else if (type == GPBDataTypeMessage || type == GPBDataTypeGroup) { // The default is looked up in -defaultValue instead since extensions @@ -1032,8 +991,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } - (void)dealloc { - if ((description_->dataType == GPBDataTypeBytes) && - !GPBExtensionIsRepeated(description_)) { + if ((description_->dataType == GPBDataTypeBytes) && !GPBExtensionIsRepeated(description_)) { [defaultValue_.valueData release]; } [super dealloc]; @@ -1046,7 +1004,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } - (NSString *)singletonName { - return (NSString * _Nonnull)@(description_->singletonName); + return (NSString *_Nonnull)@(description_->singletonName); } - (const char *)singletonNameC { @@ -1062,15 +1020,12 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { } - (GPBWireFormat)wireType { - return GPBWireFormatForType(description_->dataType, - GPBExtensionIsPacked(description_)); + return GPBWireFormatForType(description_->dataType, GPBExtensionIsPacked(description_)); } - (GPBWireFormat)alternateWireType { - NSAssert(GPBExtensionIsRepeated(description_), - @"Only valid on repeated extensions"); - return GPBWireFormatForType(description_->dataType, - !GPBExtensionIsPacked(description_)); + NSAssert(GPBExtensionIsRepeated(description_), @"Only valid on repeated extensions"); + return GPBWireFormatForType(description_->dataType, !GPBExtensionIsPacked(description_)); } - (BOOL)isRepeated { @@ -1126,8 +1081,7 @@ uint32_t GPBFieldAlternateTag(GPBFieldDescriptor *self) { return @(defaultValue_.valueUInt64); case GPBDataTypeBytes: // Like message fields, the default is zero length data. - return (defaultValue_.valueData ? defaultValue_.valueData - : GPBEmptyNSData()); + return (defaultValue_.valueData ? defaultValue_.valueData : GPBEmptyNSData()); case GPBDataTypeString: // Like message fields, the default is zero length string. return (defaultValue_.valueString ? defaultValue_.valueString : @""); diff --git a/objectivec/GPBDictionary.m b/objectivec/GPBDictionary.m index ccb2554444..d90e9f1031 100644 --- a/objectivec/GPBDictionary.m +++ b/objectivec/GPBDictionary.m @@ -58,10 +58,9 @@ // xcrun clang -dM -E -x c /dev/null | grep __apple_build_version__ // Example usage: // #if GPB_STATIC_ANALYZER_ONLY(5621, 5623) ... #endif -#define GPB_STATIC_ANALYZER_ONLY(BEGIN_APPLE_BUILD_VERSION, END_APPLE_BUILD_VERSION) \ - (defined(__clang_analyzer__) && \ - (__apple_build_version__ >= BEGIN_APPLE_BUILD_VERSION && \ - __apple_build_version__ <= END_APPLE_BUILD_VERSION)) +#define GPB_STATIC_ANALYZER_ONLY(BEGIN_APPLE_BUILD_VERSION, END_APPLE_BUILD_VERSION) \ + (defined(__clang_analyzer__) && (__apple_build_version__ >= BEGIN_APPLE_BUILD_VERSION && \ + __apple_build_version__ <= END_APPLE_BUILD_VERSION)) enum { kMapKeyFieldNumber = 1, @@ -349,8 +348,7 @@ size_t GPBDictionaryComputeSizeInternalHelper(NSDictionary *dict, GPBFieldDescri } void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream, - NSDictionary *dict, - GPBFieldDescriptor *field) { + NSDictionary *dict, GPBFieldDescriptor *field) { NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type"); GPBDataType mapValueType = GPBGetFieldDataType(field); uint32_t tag = GPBWireFormatMakeTag(GPBFieldNumber(field), GPBWireFormatLengthDelimited); @@ -374,7 +372,7 @@ void GPBDictionaryWriteToStreamInternalHelper(GPBCodedOutputStream *outputStream BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescriptor *field) { NSCAssert(field.mapKeyDataType == GPBDataTypeString, @"Unexpected key type"); NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeMessage, @"Unexpected value type"); - #pragma unused(field) // For when asserts are off in release. +#pragma unused(field) // For when asserts are off in release. GPBMessage *msg; NSEnumerator *objects = [dict objectEnumerator]; while ((msg = [objects nextObject])) { @@ -386,11 +384,8 @@ BOOL GPBDictionaryIsInitializedInternalHelper(NSDictionary *dict, GPBFieldDescri } // Note: if the type is an object, it the retain pass back to the caller. -static void ReadValue(GPBCodedInputStream *stream, - GPBGenericValue *valueToFill, - GPBDataType type, - idregistry, - GPBFieldDescriptor *field) { +static void ReadValue(GPBCodedInputStream *stream, GPBGenericValue *valueToFill, GPBDataType type, + id registry, GPBFieldDescriptor *field) { switch (type) { case GPBDataTypeBool: valueToFill->valueBool = GPBCodedInputStreamReadBool(&stream->state_); @@ -455,10 +450,8 @@ static void ReadValue(GPBCodedInputStream *stream, } } -void GPBDictionaryReadEntry(id mapDictionary, - GPBCodedInputStream *stream, - idregistry, - GPBFieldDescriptor *field, +void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream, + id registry, GPBFieldDescriptor *field, GPBMessage *parentMessage) { GPBDataType keyDataType = field.mapKeyDataType; GPBDataType valueDataType = GPBGetFieldDataType(field); @@ -472,8 +465,7 @@ void GPBDictionaryReadEntry(id mapDictionary, } GPBCodedInputStreamState *state = &stream->state_; - uint32_t keyTag = - GPBWireFormatMakeTag(kMapKeyFieldNumber, GPBWireFormatForType(keyDataType, NO)); + uint32_t keyTag = GPBWireFormatMakeTag(kMapKeyFieldNumber, GPBWireFormatForType(keyDataType, NO)); uint32_t valueTag = GPBWireFormatMakeTag(kMapValueFieldNumber, GPBWireFormatForType(valueDataType, NO)); @@ -488,7 +480,7 @@ void GPBDictionaryReadEntry(id mapDictionary, // zero signals EOF / limit reached break; } else { // Unknown - if (![stream skipField:tag]){ + if (![stream skipField:tag]) { hitError = YES; break; } @@ -529,21 +521,20 @@ void GPBDictionaryReadEntry(id mapDictionary, if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { #if GPB_STATIC_ANALYZER_ONLY(6020053, 7000181) - // Limited to Xcode 6.4 - 7.2, are known to fail here. The upper end can - // be raised as needed for new Xcodes. - // - // This is only needed on a "shallow" analyze; on a "deep" analyze, the - // existing code path gets this correct. In shallow, the analyzer decides - // GPBDataTypeIsObject(valueDataType) is both false and true on a single - // path through this function, allowing nil to be used for the - // setObject:forKey:. - if (value.valueString == nil) { - value.valueString = [@"" retain]; - } + // Limited to Xcode 6.4 - 7.2, are known to fail here. The upper end can + // be raised as needed for new Xcodes. + // + // This is only needed on a "shallow" analyze; on a "deep" analyze, the + // existing code path gets this correct. In shallow, the analyzer decides + // GPBDataTypeIsObject(valueDataType) is both false and true on a single + // path through this function, allowing nil to be used for the + // setObject:forKey:. + if (value.valueString == nil) { + value.valueString = [@"" retain]; + } #endif // mapDictionary is an NSMutableDictionary - [(NSMutableDictionary *)mapDictionary setObject:value.valueString - forKey:key.valueString]; + [(NSMutableDictionary *)mapDictionary setObject:value.valueString forKey:key.valueString]; } else { if (valueDataType == GPBDataTypeEnum) { if (GPBHasPreservingUnknownEnumSemantics([parentMessage descriptor].file.syntax) || @@ -11749,8 +11740,8 @@ void GPBDictionaryReadEntry(id mapDictionary, } - (instancetype)initWithValidationFunction:(GPBEnumValidationFunc)func - rawValues:(const int32_t [])rawValues - forKeys:(const BOOL [])keys + rawValues:(const int32_t[])rawValues + forKeys:(const BOOL[])keys count:(NSUInteger)count { self = [super init]; if (self) { @@ -11790,8 +11781,7 @@ void GPBDictionaryReadEntry(id mapDictionary, #if !defined(NS_BLOCK_ASSERTIONS) - (void)dealloc { - NSAssert(!_autocreator, - @"%@: Autocreator must be cleared before release, autocreator: %@", + NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [super dealloc]; } @@ -11840,7 +11830,7 @@ void GPBDictionaryReadEntry(id mapDictionary, return (_valueSet[0] ? 1 : 0) + (_valueSet[1] ? 1 : 0); } -- (BOOL)getEnum:(int32_t*)value forKey:(BOOL)key { +- (BOOL)getEnum:(int32_t *)value forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (value) { @@ -11855,7 +11845,7 @@ void GPBDictionaryReadEntry(id mapDictionary, return NO; } -- (BOOL)getRawValue:(int32_t*)rawValue forKey:(BOOL)key { +- (BOOL)getRawValue:(int32_t *)rawValue forKey:(BOOL)key { int idx = (key ? 1 : 0); if (_valueSet[idx]) { if (rawValue) { @@ -11866,8 +11856,8 @@ void GPBDictionaryReadEntry(id mapDictionary, return NO; } -- (void)enumerateKeysAndRawValuesUsingBlock: - (void (NS_NOESCAPE ^)(BOOL key, int32_t value, BOOL *stop))block { +- (void)enumerateKeysAndRawValuesUsingBlock:(void(NS_NOESCAPE ^)(BOOL key, int32_t value, + BOOL *stop))block { BOOL stop = NO; if (_valueSet[0]) { block(NO, _values[0], &stop); @@ -11877,8 +11867,8 @@ void GPBDictionaryReadEntry(id mapDictionary, } } -- (void)enumerateKeysAndEnumsUsingBlock: - (void (NS_NOESCAPE ^)(BOOL key, int32_t rawValue, BOOL *stop))block { +- (void)enumerateKeysAndEnumsUsingBlock:(void(NS_NOESCAPE ^)(BOOL key, int32_t rawValue, + BOOL *stop))block { BOOL stop = NO; GPBEnumValidationFunc func = _validationFunc; int32_t validatedValue; @@ -11956,7 +11946,7 @@ void GPBDictionaryReadEntry(id mapDictionary, } } -- (void)enumerateForTextFormat:(void (NS_NOESCAPE ^)(id keyObj, id valueObj))block { +- (void)enumerateForTextFormat:(void(NS_NOESCAPE ^)(id keyObj, id valueObj))block { if (_valueSet[0]) { block(@"false", @(_values[0])); } @@ -11965,8 +11955,7 @@ void GPBDictionaryReadEntry(id mapDictionary, } } -- (void)setGPBGenericValue:(GPBGenericValue *)value - forGPBGenericValueKey:(GPBGenericValue *)key { +- (void)setGPBGenericValue:(GPBGenericValue *)value forGPBGenericValueKey:(GPBGenericValue *)key { int idx = (key->valueBool ? 1 : 0); _values[idx] = value->valueInt32; _valueSet[idx] = YES; @@ -11989,8 +11978,7 @@ void GPBDictionaryReadEntry(id mapDictionary, - (void)setEnum:(int32_t)value forKey:(BOOL)key { if (!_validationFunc(value)) { [NSException raise:NSInvalidArgumentException - format:@"GPBBoolEnumDictionary: Attempt to set an unknown enum value (%d)", - value]; + format:@"GPBBoolEnumDictionary: Attempt to set an unknown enum value (%d)", value]; } int idx = (key ? 1 : 0); _values[idx] = value; @@ -12027,8 +12015,7 @@ void GPBDictionaryReadEntry(id mapDictionary, } - (void)dealloc { - NSAssert(!_autocreator, - @"%@: Autocreator must be cleared before release, autocreator: %@", + NSAssert(!_autocreator, @"%@: Autocreator must be cleared before release, autocreator: %@", [self class], _autocreator); [_dictionary release]; [super dealloc]; @@ -12036,14 +12023,12 @@ void GPBDictionaryReadEntry(id mapDictionary, #pragma mark Required NSDictionary overrides -- (instancetype)initWithObjects:(const id [])objects - forKeys:(const id [])keys +- (instancetype)initWithObjects:(const id[])objects + forKeys:(const id[])keys count:(NSUInteger)count { self = [super init]; if (self) { - _dictionary = [[NSMutableDictionary alloc] initWithObjects:objects - forKeys:keys - count:count]; + _dictionary = [[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys count:count]; } return self; } @@ -12116,16 +12101,12 @@ void GPBDictionaryReadEntry(id mapDictionary, } } -- (void)enumerateKeysAndObjectsUsingBlock:(void (NS_NOESCAPE ^)(id key, - id obj, - BOOL *stop))block { +- (void)enumerateKeysAndObjectsUsingBlock:(void(NS_NOESCAPE ^)(id key, id obj, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsUsingBlock:block]; } - (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts - usingBlock:(void (NS_NOESCAPE ^)(id key, - id obj, - BOOL *stop))block { + usingBlock:(void(NS_NOESCAPE ^)(id key, id obj, BOOL *stop))block { [_dictionary enumerateKeysAndObjectsWithOptions:opts usingBlock:block]; } diff --git a/objectivec/GPBExtensionInternals.m b/objectivec/GPBExtensionInternals.m index b74591e0a0..dbfa10025d 100644 --- a/objectivec/GPBExtensionInternals.m +++ b/objectivec/GPBExtensionInternals.m @@ -40,7 +40,7 @@ static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, GPBCodedInputStream *input, - idextensionRegistry, + id extensionRegistry, GPBMessage *existingValue) __attribute__((ns_returns_retained)); @@ -65,11 +65,11 @@ GPB_INLINE size_t DataTypeSize(GPBDataType dataType) { } static size_t ComputePBSerializedSizeNoTagOfObject(GPBDataType dataType, id object) { -#define FIELD_CASE(TYPE, ACCESSOR) \ - case GPBDataType##TYPE: \ +#define FIELD_CASE(TYPE, ACCESSOR) \ + case GPBDataType##TYPE: \ return GPBCompute##TYPE##SizeNoTag([(NSNumber *)object ACCESSOR]); -#define FIELD_CASE2(TYPE) \ - case GPBDataType##TYPE: \ +#define FIELD_CASE2(TYPE) \ + case GPBDataType##TYPE: \ return GPBCompute##TYPE##SizeNoTag(object); switch (dataType) { FIELD_CASE(Bool, boolValue) @@ -95,14 +95,13 @@ static size_t ComputePBSerializedSizeNoTagOfObject(GPBDataType dataType, id obje #undef FIELD_CASE2 } -static size_t ComputeSerializedSizeIncludingTagOfObject( - GPBExtensionDescription *description, id object) { -#define FIELD_CASE(TYPE, ACCESSOR) \ - case GPBDataType##TYPE: \ - return GPBCompute##TYPE##Size(description->fieldNumber, \ - [(NSNumber *)object ACCESSOR]); -#define FIELD_CASE2(TYPE) \ - case GPBDataType##TYPE: \ +static size_t ComputeSerializedSizeIncludingTagOfObject(GPBExtensionDescription *description, + id object) { +#define FIELD_CASE(TYPE, ACCESSOR) \ + case GPBDataType##TYPE: \ + return GPBCompute##TYPE##Size(description->fieldNumber, [(NSNumber *)object ACCESSOR]); +#define FIELD_CASE2(TYPE) \ + case GPBDataType##TYPE: \ return GPBCompute##TYPE##Size(description->fieldNumber, object); switch (description->dataType) { FIELD_CASE(Bool, boolValue) @@ -124,8 +123,7 @@ static size_t ComputeSerializedSizeIncludingTagOfObject( FIELD_CASE2(Group) case GPBDataTypeMessage: if (GPBExtensionIsWireFormat(description)) { - return GPBComputeMessageSetExtensionSize(description->fieldNumber, - object); + return GPBComputeMessageSetExtensionSize(description->fieldNumber, object); } else { return GPBComputeMessageSize(description->fieldNumber, object); } @@ -134,8 +132,8 @@ static size_t ComputeSerializedSizeIncludingTagOfObject( #undef FIELD_CASE2 } -static size_t ComputeSerializedSizeIncludingTagOfArray( - GPBExtensionDescription *description, NSArray *values) { +static size_t ComputeSerializedSizeIncludingTagOfArray(GPBExtensionDescription *description, + NSArray *values) { if (GPBExtensionIsPacked(description)) { size_t size = 0; size_t typeSize = DataTypeSize(description->dataType); @@ -143,8 +141,7 @@ static size_t ComputeSerializedSizeIncludingTagOfArray( size = values.count * typeSize; } else { for (id value in values) { - size += - ComputePBSerializedSizeNoTagOfObject(description->dataType, value); + size += ComputePBSerializedSizeNoTagOfObject(description->dataType, value); } } return size + GPBComputeTagSize(description->fieldNumber) + @@ -158,13 +155,12 @@ static size_t ComputeSerializedSizeIncludingTagOfArray( } } -static void WriteObjectIncludingTagToCodedOutputStream( - id object, GPBExtensionDescription *description, - GPBCodedOutputStream *output) { -#define FIELD_CASE(TYPE, ACCESSOR) \ - case GPBDataType##TYPE: \ - [output write##TYPE:description->fieldNumber \ - value:[(NSNumber *)object ACCESSOR]]; \ +static void WriteObjectIncludingTagToCodedOutputStream(id object, + GPBExtensionDescription *description, + GPBCodedOutputStream *output) { +#define FIELD_CASE(TYPE, ACCESSOR) \ + case GPBDataType##TYPE: \ + [output write##TYPE:description->fieldNumber value:[(NSNumber *)object ACCESSOR]]; \ return; #define FIELD_CASE2(TYPE) \ case GPBDataType##TYPE: \ @@ -200,9 +196,8 @@ static void WriteObjectIncludingTagToCodedOutputStream( #undef FIELD_CASE2 } -static void WriteObjectNoTagToCodedOutputStream( - id object, GPBExtensionDescription *description, - GPBCodedOutputStream *output) { +static void WriteObjectNoTagToCodedOutputStream(id object, GPBExtensionDescription *description, + GPBCodedOutputStream *output) { #define FIELD_CASE(TYPE, ACCESSOR) \ case GPBDataType##TYPE: \ [output write##TYPE##NoTag:[(NSNumber *)object ACCESSOR]]; \ @@ -237,20 +232,18 @@ static void WriteObjectNoTagToCodedOutputStream( #undef FIELD_CASE2 } -static void WriteArrayIncludingTagsToCodedOutputStream( - NSArray *values, GPBExtensionDescription *description, - GPBCodedOutputStream *output) { +static void WriteArrayIncludingTagsToCodedOutputStream(NSArray *values, + GPBExtensionDescription *description, + GPBCodedOutputStream *output) { if (GPBExtensionIsPacked(description)) { - [output writeTag:description->fieldNumber - format:GPBWireFormatLengthDelimited]; + [output writeTag:description->fieldNumber format:GPBWireFormatLengthDelimited]; size_t dataSize = 0; size_t typeSize = DataTypeSize(description->dataType); if (typeSize != 0) { dataSize = values.count * typeSize; } else { for (id value in values) { - dataSize += - ComputePBSerializedSizeNoTagOfObject(description->dataType, value); + dataSize += ComputePBSerializedSizeNoTagOfObject(description->dataType, value); } } [output writeRawVarintSizeTAs32:dataSize]; @@ -270,23 +263,18 @@ static void WriteArrayIncludingTagsToCodedOutputStream( #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" -void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, - BOOL isPackedOnStream, +void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, BOOL isPackedOnStream, GPBCodedInputStream *input, - idextensionRegistry, + id extensionRegistry, GPBMessage *message) { GPBExtensionDescription *description = extension->description_; GPBCodedInputStreamState *state = &input->state_; if (isPackedOnStream) { - NSCAssert(GPBExtensionIsRepeated(description), - @"How was it packed if it isn't repeated?"); + NSCAssert(GPBExtensionIsRepeated(description), @"How was it packed if it isn't repeated?"); int32_t length = GPBCodedInputStreamReadInt32(state); size_t limit = GPBCodedInputStreamPushLimit(state, length); while (GPBCodedInputStreamBytesUntilLimit(state) > 0) { - id value = NewSingleValueFromInputStream(extension, - input, - extensionRegistry, - nil); + id value = NewSingleValueFromInputStream(extension, input, extensionRegistry, nil); [message addExtension:extension value:value]; [value release]; } @@ -297,10 +285,7 @@ void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, if (!isRepeated && GPBDataTypeIsMessage(description->dataType)) { existingValue = [message getExistingExtension:extension]; } - id value = NewSingleValueFromInputStream(extension, - input, - extensionRegistry, - existingValue); + id value = NewSingleValueFromInputStream(extension, input, extensionRegistry, existingValue); if (isRepeated) { [message addExtension:extension value:value]; } else { @@ -310,8 +295,7 @@ void GPBExtensionMergeFromInputStream(GPBExtensionDescriptor *extension, } } -void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, - id value, +void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, id value, GPBCodedOutputStream *output) { GPBExtensionDescription *description = extension->description_; if (GPBExtensionIsRepeated(description)) { @@ -321,8 +305,7 @@ void GPBWriteExtensionValueToOutputStream(GPBExtensionDescriptor *extension, } } -size_t GPBComputeExtensionSerializedSizeIncludingTag( - GPBExtensionDescriptor *extension, id value) { +size_t GPBComputeExtensionSerializedSizeIncludingTag(GPBExtensionDescriptor *extension, id value) { GPBExtensionDescription *description = extension->description_; if (GPBExtensionIsRepeated(description)) { return ComputeSerializedSizeIncludingTagOfArray(description, value); @@ -334,27 +317,43 @@ size_t GPBComputeExtensionSerializedSizeIncludingTag( // Note that this returns a retained value intentionally. static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, GPBCodedInputStream *input, - idextensionRegistry, + id extensionRegistry, GPBMessage *existingValue) { GPBExtensionDescription *description = extension->description_; GPBCodedInputStreamState *state = &input->state_; switch (description->dataType) { - case GPBDataTypeBool: return [[NSNumber alloc] initWithBool:GPBCodedInputStreamReadBool(state)]; - case GPBDataTypeFixed32: return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadFixed32(state)]; - case GPBDataTypeSFixed32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSFixed32(state)]; - case GPBDataTypeFloat: return [[NSNumber alloc] initWithFloat:GPBCodedInputStreamReadFloat(state)]; - case GPBDataTypeFixed64: return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadFixed64(state)]; - case GPBDataTypeSFixed64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSFixed64(state)]; - case GPBDataTypeDouble: return [[NSNumber alloc] initWithDouble:GPBCodedInputStreamReadDouble(state)]; - case GPBDataTypeInt32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadInt32(state)]; - case GPBDataTypeInt64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadInt64(state)]; - case GPBDataTypeSInt32: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSInt32(state)]; - case GPBDataTypeSInt64: return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSInt64(state)]; - case GPBDataTypeUInt32: return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadUInt32(state)]; - case GPBDataTypeUInt64: return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadUInt64(state)]; - case GPBDataTypeBytes: return GPBCodedInputStreamReadRetainedBytes(state); - case GPBDataTypeString: return GPBCodedInputStreamReadRetainedString(state); - case GPBDataTypeEnum: return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadEnum(state)]; + case GPBDataTypeBool: + return [[NSNumber alloc] initWithBool:GPBCodedInputStreamReadBool(state)]; + case GPBDataTypeFixed32: + return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadFixed32(state)]; + case GPBDataTypeSFixed32: + return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSFixed32(state)]; + case GPBDataTypeFloat: + return [[NSNumber alloc] initWithFloat:GPBCodedInputStreamReadFloat(state)]; + case GPBDataTypeFixed64: + return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadFixed64(state)]; + case GPBDataTypeSFixed64: + return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSFixed64(state)]; + case GPBDataTypeDouble: + return [[NSNumber alloc] initWithDouble:GPBCodedInputStreamReadDouble(state)]; + case GPBDataTypeInt32: + return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadInt32(state)]; + case GPBDataTypeInt64: + return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadInt64(state)]; + case GPBDataTypeSInt32: + return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadSInt32(state)]; + case GPBDataTypeSInt64: + return [[NSNumber alloc] initWithLongLong:GPBCodedInputStreamReadSInt64(state)]; + case GPBDataTypeUInt32: + return [[NSNumber alloc] initWithUnsignedInt:GPBCodedInputStreamReadUInt32(state)]; + case GPBDataTypeUInt64: + return [[NSNumber alloc] initWithUnsignedLongLong:GPBCodedInputStreamReadUInt64(state)]; + case GPBDataTypeBytes: + return GPBCodedInputStreamReadRetainedBytes(state); + case GPBDataTypeString: + return GPBCodedInputStreamReadRetainedString(state); + case GPBDataTypeEnum: + return [[NSNumber alloc] initWithInt:GPBCodedInputStreamReadEnum(state)]; case GPBDataTypeGroup: case GPBDataTypeMessage: { GPBMessage *message; @@ -367,15 +366,14 @@ static id NewSingleValueFromInputStream(GPBExtensionDescriptor *extension, if (description->dataType == GPBDataTypeGroup) { [input readGroup:description->fieldNumber - message:message + message:message extensionRegistry:extensionRegistry]; } else { // description->dataType == GPBDataTypeMessage if (GPBExtensionIsWireFormat(description)) { // For MessageSet fields the message length will have already been // read. - [message mergeFromCodedInputStream:input - extensionRegistry:extensionRegistry]; + [message mergeFromCodedInputStream:input extensionRegistry:extensionRegistry]; } else { [input readMessage:message extensionRegistry:extensionRegistry]; } diff --git a/objectivec/GPBExtensionRegistry.m b/objectivec/GPBExtensionRegistry.m index e3ff7c4059..04f1bcac9f 100644 --- a/objectivec/GPBExtensionRegistry.m +++ b/objectivec/GPBExtensionRegistry.m @@ -40,8 +40,8 @@ - (instancetype)init { if ((self = [super init])) { // The keys are ObjC classes, so straight up ptr comparisons are fine. - mutableClassMap_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, - &kCFTypeDictionaryValueCallBacks); + mutableClassMap_ = + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks); } return self; } @@ -69,13 +69,13 @@ } Class containingMessageClass = extension.containingMessageClass; - CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) - CFDictionaryGetValue(mutableClassMap_, containingMessageClass); + CFMutableDictionaryRef extensionMap = + (CFMutableDictionaryRef)CFDictionaryGetValue(mutableClassMap_, containingMessageClass); if (extensionMap == nil) { // Use a custom dictionary here because the keys are numbers and conversion // back and forth from NSNumber isn't worth the cost. - extensionMap = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, - &kCFTypeDictionaryValueCallBacks); + extensionMap = + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(mutableClassMap_, containingMessageClass, extensionMap); CFRelease(extensionMap); } @@ -87,13 +87,11 @@ - (GPBExtensionDescriptor *)extensionForDescriptor:(GPBDescriptor *)descriptor fieldNumber:(NSInteger)fieldNumber { Class messageClass = descriptor.messageClass; - CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) - CFDictionaryGetValue(mutableClassMap_, messageClass); + CFMutableDictionaryRef extensionMap = + (CFMutableDictionaryRef)CFDictionaryGetValue(mutableClassMap_, messageClass); ssize_t key = fieldNumber; GPBExtensionDescriptor *result = - (extensionMap - ? CFDictionaryGetValue(extensionMap, (const void *)key) - : nil); + (extensionMap ? CFDictionaryGetValue(extensionMap, (const void *)key) : nil); return result; } @@ -107,8 +105,8 @@ static void CopySubDictionary(const void *key, const void *value, void *context) Class containingMessageClass = key; CFMutableDictionaryRef otherExtensionMap = (CFMutableDictionaryRef)value; - CFMutableDictionaryRef extensionMap = (CFMutableDictionaryRef) - CFDictionaryGetValue(mutableClassMap, containingMessageClass); + CFMutableDictionaryRef extensionMap = + (CFMutableDictionaryRef)CFDictionaryGetValue(mutableClassMap, containingMessageClass); if (extensionMap == nil) { extensionMap = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, otherExtensionMap); CFDictionarySetValue(mutableClassMap, containingMessageClass, extensionMap); diff --git a/objectivec/GPBMessage.m b/objectivec/GPBMessage.m index b494f36418..efb0088e42 100644 --- a/objectivec/GPBMessage.m +++ b/objectivec/GPBMessage.m @@ -30,8 +30,8 @@ #import "GPBMessage_PackagePrivate.h" -#import #import +#import #import #import "GPBArray_PackagePrivate.h" @@ -51,8 +51,7 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" -NSString *const GPBMessageErrorDomain = - GPBNSStringifySymbol(GPBMessageErrorDomain); +NSString *const GPBMessageErrorDomain = GPBNSStringifySymbol(GPBMessageErrorDomain); NSString *const GPBErrorReasonKey = @"Reason"; @@ -97,27 +96,20 @@ static NSString *const kGPBDataCoderKey = @"GPBData"; } @end -static id CreateArrayForField(GPBFieldDescriptor *field, - GPBMessage *autocreator) +static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator) __attribute__((ns_returns_retained)); -static id GetOrCreateArrayIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field); +static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); -static id CreateMapForField(GPBFieldDescriptor *field, - GPBMessage *autocreator) +static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator) __attribute__((ns_returns_retained)); -static id GetOrCreateMapIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field); +static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field); -static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, - NSZone *zone) +static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone) __attribute__((ns_returns_retained)); #ifdef DEBUG static NSError *MessageError(NSInteger code, NSDictionary *userInfo) { - return [NSError errorWithDomain:GPBMessageErrorDomain - code:code - userInfo:userInfo]; + return [NSError errorWithDomain:GPBMessageErrorDomain code:code userInfo:userInfo]; } #endif @@ -133,7 +125,7 @@ static NSError *ErrorFromException(NSException *exception) { NSString *reason = exception.reason; NSDictionary *userInfo = nil; if ([reason length]) { - userInfo = @{ GPBErrorReasonKey : reason }; + userInfo = @{GPBErrorReasonKey : reason}; } error = [NSError errorWithDomain:GPBMessageErrorDomain @@ -143,24 +135,20 @@ static NSError *ErrorFromException(NSException *exception) { return error; } -static void CheckExtension(GPBMessage *self, - GPBExtensionDescriptor *extension) { +static void CheckExtension(GPBMessage *self, GPBExtensionDescriptor *extension) { if (![self isKindOfClass:extension.containingMessageClass]) { - [NSException - raise:NSInvalidArgumentException - format:@"Extension %@ used on wrong class (%@ instead of %@)", - extension.singletonName, - [self class], extension.containingMessageClass]; + [NSException raise:NSInvalidArgumentException + format:@"Extension %@ used on wrong class (%@ instead of %@)", + extension.singletonName, [self class], extension.containingMessageClass]; } } -static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, - NSZone *zone) { +static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, NSZone *zone) { if (extensionMap.count == 0) { return nil; } - NSMutableDictionary *result = [[NSMutableDictionary allocWithZone:zone] - initWithCapacity:extensionMap.count]; + NSMutableDictionary *result = + [[NSMutableDictionary allocWithZone:zone] initWithCapacity:extensionMap.count]; for (GPBExtensionDescriptor *extension in extensionMap) { id value = [extensionMap objectForKey:extension]; @@ -168,8 +156,7 @@ static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, if (extension.repeated) { if (isMessageExtension) { - NSMutableArray *list = - [[NSMutableArray alloc] initWithCapacity:[value count]]; + NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:[value count]]; for (GPBMessage *listValue in value) { GPBMessage *copiedValue = [listValue copyWithZone:zone]; [list addObject:copiedValue]; @@ -196,8 +183,7 @@ static NSMutableDictionary *CloneExtensionMap(NSDictionary *extensionMap, return result; } -static id CreateArrayForField(GPBFieldDescriptor *field, - GPBMessage *autocreator) { +static id CreateArrayForField(GPBFieldDescriptor *field, GPBMessage *autocreator) { id result; GPBDataType fieldDataType = GPBGetFieldDataType(field); switch (fieldDataType) { @@ -230,8 +216,7 @@ static id CreateArrayForField(GPBFieldDescriptor *field, break; case GPBDataTypeEnum: - result = [[GPBEnumArray alloc] - initWithValidationFunction:field.enumDescriptor.enumVerifier]; + result = [[GPBEnumArray alloc] initWithValidationFunction:field.enumDescriptor.enumVerifier]; break; case GPBDataTypeBytes: @@ -249,7 +234,7 @@ static id CreateArrayForField(GPBFieldDescriptor *field, if (autocreator) { if (GPBDataTypeIsObject(fieldDataType)) { GPBAutocreatedArray *autoArray = result; - autoArray->_autocreator = autocreator; + autoArray->_autocreator = autocreator; } else { GPBInt32Array *gpbArray = result; gpbArray->_autocreator = autocreator; @@ -259,8 +244,7 @@ static id CreateArrayForField(GPBFieldDescriptor *field, return result; } -static id CreateMapForField(GPBFieldDescriptor *field, - GPBMessage *autocreator) { +static id CreateMapForField(GPBFieldDescriptor *field, GPBMessage *autocreator) { id result; GPBDataType keyDataType = field.mapKeyDataType; GPBDataType valueDataType = GPBGetFieldDataType(field); @@ -545,10 +529,9 @@ static id CreateMapForField(GPBFieldDescriptor *field, } if (autocreator) { - if ((keyDataType == GPBDataTypeString) && - GPBDataTypeIsObject(valueDataType)) { + if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { GPBAutocreatedDictionary *autoDict = result; - autoDict->_autocreator = autocreator; + autoDict->_autocreator = autocreator; } else { GPBInt32Int32Dictionary *gpbDict = result; gpbDict->_autocreator = autocreator; @@ -570,8 +553,7 @@ static id CreateMapForField(GPBFieldDescriptor *field, // repeated/map field parsed into the autorelease pool which is both a memory // and performance hit. -static id GetOrCreateArrayIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field) { +static id GetOrCreateArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { id array = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!array) { // No lock needed, this is called from places expecting to mutate @@ -611,8 +593,7 @@ static id GetArrayIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { return expected; } -static id GetOrCreateMapIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field) { +static id GetOrCreateMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { id dict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (!dict) { // No lock needed, this is called from places expecting to mutate @@ -641,8 +622,7 @@ static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { } // Some other thread set it, release the one created and return what got set. - if ((field.mapKeyDataType == GPBDataTypeString) && - GPBFieldDataTypeIsObject(field)) { + if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) { GPBAutocreatedDictionary *autoDict = autocreated; autoDict->_autocreator = nil; } else { @@ -655,8 +635,7 @@ static id GetMapIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { #endif // !defined(__clang_analyzer__) -GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, - GPBMessage *autocreator, +GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, GPBMessage *autocreator, GPBFieldDescriptor *field) { GPBMessage *message = [[msgClass alloc] init]; message->autocreator_ = autocreator; @@ -664,13 +643,12 @@ GPBMessage *GPBCreateMessageWithAutocreator(Class msgClass, return message; } -static GPBMessage *CreateMessageWithAutocreatorForExtension( - Class msgClass, GPBMessage *autocreator, GPBExtensionDescriptor *extension) +static GPBMessage *CreateMessageWithAutocreatorForExtension(Class msgClass, GPBMessage *autocreator, + GPBExtensionDescriptor *extension) __attribute__((ns_returns_retained)); -static GPBMessage *CreateMessageWithAutocreatorForExtension( - Class msgClass, GPBMessage *autocreator, - GPBExtensionDescriptor *extension) { +static GPBMessage *CreateMessageWithAutocreatorForExtension(Class msgClass, GPBMessage *autocreator, + GPBExtensionDescriptor *extension) { GPBMessage *message = [[msgClass alloc] init]; message->autocreator_ = autocreator; message->autocreatorExtension_ = [extension retain]; @@ -689,8 +667,7 @@ void GPBBecomeVisibleToAutocreator(GPBMessage *self) { // This will recursively make all parent messages visible until it reaches a // super-creator that's visible. if (self->autocreatorField_) { - GPBSetObjectIvarWithFieldPrivate(self->autocreator_, - self->autocreatorField_, self); + GPBSetObjectIvarWithFieldPrivate(self->autocreator_, self->autocreatorField_, self); } else { [self->autocreator_ setExtension:self->autocreatorExtension_ value:self]; } @@ -726,8 +703,7 @@ void GPBAutocreatedDictionaryModified(GPBMessage *self, id dictionary) { if (field.fieldType == GPBFieldTypeMap) { id curDict = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (curDict == dictionary) { - if ((field.mapKeyDataType == GPBDataTypeString) && - GPBFieldDataTypeIsObject(field)) { + if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) { GPBAutocreatedDictionary *autoDict = dictionary; autoDict->_autocreator = nil; } else { @@ -751,18 +727,15 @@ void GPBClearMessageAutocreator(GPBMessage *self) { // Either the autocreator must have its "has" flag set to YES, or it must be // NO and not equal to ourselves. BOOL autocreatorHas = - (self->autocreatorField_ - ? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_) - : [self->autocreator_ hasExtension:self->autocreatorExtension_]); + (self->autocreatorField_ ? GPBGetHasIvarField(self->autocreator_, self->autocreatorField_) + : [self->autocreator_ hasExtension:self->autocreatorExtension_]); GPBMessage *autocreatorFieldValue = (self->autocreatorField_ - ? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_, - self->autocreatorField_) + ? GPBGetObjectIvarWithFieldNoAutocreate(self->autocreator_, self->autocreatorField_) : [self->autocreator_->autocreatedExtensionMap_ objectForKey:self->autocreatorExtension_]); NSCAssert(autocreatorHas || autocreatorFieldValue != self, - @"Cannot clear autocreator because it still refers to self, self: %@.", - self); + @"Cannot clear autocreator because it still refers to self, self: %@.", self); #endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS) @@ -791,7 +764,9 @@ void GPBPrepareReadOnlySemaphore(GPBMessage *self) { // The Xcode 9.2 (and 9.3 beta) static analyzer thinks worker is leaked // (doesn't seem to know about atomic_compare_exchange_strong); so just // for the analyzer, let it think worker is also released in this case. - else { dispatch_release(worker); } + else { + dispatch_release(worker); + } #endif } @@ -848,9 +823,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { if (!descriptor) { // Use a dummy file that marks it as proto2 syntax so when used generically // it supports unknowns/etc. - fileDescriptor = - [[GPBFileDescriptor alloc] initWithPackage:@"internal" - syntax:GPBFileSyntaxProto2]; + fileDescriptor = [[GPBFileDescriptor alloc] initWithPackage:@"internal" + syntax:GPBFileSyntaxProto2]; descriptor = [GPBDescriptor allocDescriptorForClass:[GPBMessage class] rootClass:Nil @@ -869,8 +843,8 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { - (instancetype)init { if ((self = [super init])) { - messageStorage_ = (GPBMessage_StoragePtr)( - ((uint8_t *)self) + class_getInstanceSize([self class])); + messageStorage_ = + (GPBMessage_StoragePtr)(((uint8_t *)self) + class_getInstanceSize([self class])); } return self; @@ -889,8 +863,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { if (errorPtr) { *errorPtr = nil; } - } - @catch (NSException *exception) { + } @catch (NSException *exception) { [self release]; self = nil; if (errorPtr) { @@ -911,8 +884,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } - (instancetype)initWithCodedInputStream:(GPBCodedInputStream *)input - extensionRegistry: - (id)extensionRegistry + extensionRegistry:(id)extensionRegistry error:(NSError **)errorPtr { if ((self = [self init])) { @try { @@ -920,8 +892,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { if (errorPtr) { *errorPtr = nil; } - } - @catch (NSException *exception) { + } @catch (NSException *exception) { [self release]; self = nil; if (errorPtr) { @@ -979,17 +950,16 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { if (field.mapKeyDataType == GPBDataTypeString) { // Map is an NSDictionary. NSDictionary *existingDict = value; - NSMutableDictionary *newDict = [[NSMutableDictionary alloc] - initWithCapacity:existingDict.count]; + NSMutableDictionary *newDict = + [[NSMutableDictionary alloc] initWithCapacity:existingDict.count]; newValue = newDict; - [existingDict enumerateKeysAndObjectsUsingBlock:^(NSString *key, - GPBMessage *msg, - BOOL *stop) { + [existingDict + enumerateKeysAndObjectsUsingBlock:^(NSString *key, GPBMessage *msg, BOOL *stop) { #pragma unused(stop) - GPBMessage *copiedMsg = [msg copyWithZone:zone]; - [newDict setObject:copiedMsg forKey:key]; - [copiedMsg release]; - }]; + GPBMessage *copiedMsg = [msg copyWithZone:zone]; + [newDict setObject:copiedMsg forKey:key]; + [copiedMsg release]; + }]; } else { // Is one of the GPB*ObjectDictionary classes. Type doesn't // matter, just need one to invoke the selector. @@ -1008,8 +978,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { newValue = [value copyWithZone:zone]; } } else { - if ((field.mapKeyDataType == GPBDataTypeString) && - GPBFieldDataTypeIsObject(field)) { + if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) { // NSDictionary newValue = [value mutableCopyWithZone:zone]; } else { @@ -1041,8 +1010,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { id *typePtr = (id *)&storage[field->description_->offset]; *typePtr = NULL; } - } else if (GPBFieldDataTypeIsObject(field) && - GPBGetHasIvarField(self, field)) { + } else if (GPBFieldDataTypeIsObject(field) && GPBGetHasIvarField(self, field)) { // A set string/data value (message picked off above), copy it. id value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); id newValue = [value copyWithZone:zone]; @@ -1093,8 +1061,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } } } else { - if ((field.mapKeyDataType == GPBDataTypeString) && - GPBFieldDataTypeIsObject(field)) { + if ((field.mapKeyDataType == GPBDataTypeString) && GPBFieldDataTypeIsObject(field)) { if ([arrayOrMap isKindOfClass:[GPBAutocreatedDictionary class]]) { GPBAutocreatedDictionary *autoDict = arrayOrMap; if (autoDict->_autocreator == self) { @@ -1115,8 +1082,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { GPBClearAutocreatedMessageIvarWithField(self, field); GPBMessage *value = GPBGetObjectIvarWithFieldNoAutocreate(self, field); [value release]; - } else if (GPBFieldDataTypeIsObject(field) && - GPBGetHasIvarField(self, field)) { + } else if (GPBFieldDataTypeIsObject(field) && GPBGetHasIvarField(self, field)) { id value = GPBGetObjectIvarWithField(self, field); [value release]; } @@ -1168,8 +1134,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { return NO; } } else { - NSAssert(field.isOptional, - @"%@: Single message field %@ not required or optional?", + NSAssert(field.isOptional, @"%@: Single message field %@ not required or optional?", [self class], field.name); if (GPBGetHasIvarField(self, field)) { GPBMessage *message = GPBGetMessageMessageField(self, field); @@ -1187,15 +1152,13 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } } else { // fieldType == GPBFieldTypeMap if (field.mapKeyDataType == GPBDataTypeString) { - NSDictionary *map = - GPBGetObjectIvarWithFieldNoAutocreate(self, field); + NSDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (map && !GPBDictionaryIsInitializedInternalHelper(map, field)) { return NO; } } else { // Real type is GPB*ObjectDictionary, exact type doesn't matter. - GPBInt32ObjectDictionary *map = - GPBGetObjectIvarWithFieldNoAutocreate(self, field); + GPBInt32ObjectDictionary *map = GPBGetObjectIvarWithFieldNoAutocreate(self, field); if (map && ![map isInitialized]) { return NO; } @@ -1206,9 +1169,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { __block BOOL result = YES; [extensionMap_ - enumerateKeysAndObjectsUsingBlock:^(GPBExtensionDescriptor *extension, - id obj, - BOOL *stop) { + enumerateKeysAndObjectsUsingBlock:^(GPBExtensionDescriptor *extension, id obj, BOOL *stop) { if (GPBExtensionIsMessage(extension)) { if (extension.isRepeated) { for (GPBMessage *msg in obj) { @@ -1241,18 +1202,15 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } #endif NSMutableData *data = [NSMutableData dataWithLength:[self serializedSize]]; - GPBCodedOutputStream *stream = - [[GPBCodedOutputStream alloc] initWithData:data]; + GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithData:data]; @try { [self writeToCodedOutputStream:stream]; - } - @catch (NSException *exception) { + } @catch (NSException *exception) { // This really shouldn't happen. The only way writeToCodedOutputStream: // could throw is if something in the library has a bug and the // serializedSize was wrong. #ifdef DEBUG - NSLog(@"%@: Internal exception while building message data: %@", - [self class], exception); + NSLog(@"%@: Internal exception while building message data: %@", [self class], exception); #endif data = nil; } @@ -1263,20 +1221,17 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { - (NSData *)delimitedData { size_t serializedSize = [self serializedSize]; size_t varintSize = GPBComputeRawVarint32SizeForInteger(serializedSize); - NSMutableData *data = - [NSMutableData dataWithLength:(serializedSize + varintSize)]; - GPBCodedOutputStream *stream = - [[GPBCodedOutputStream alloc] initWithData:data]; + NSMutableData *data = [NSMutableData dataWithLength:(serializedSize + varintSize)]; + GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithData:data]; @try { [self writeDelimitedToCodedOutputStream:stream]; - } - @catch (NSException *exception) { + } @catch (NSException *exception) { // This really shouldn't happen. The only way writeToCodedOutputStream: // could throw is if something in the library has a bug and the // serializedSize was wrong. #ifdef DEBUG - NSLog(@"%@: Internal exception while building message delimitedData: %@", - [self class], exception); + NSLog(@"%@: Internal exception while building message delimitedData: %@", [self class], + exception); #endif // If it happens, truncate. data.length = 0; @@ -1286,8 +1241,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } - (void)writeToOutputStream:(NSOutputStream *)output { - GPBCodedOutputStream *stream = - [[GPBCodedOutputStream alloc] initWithOutputStream:output]; + GPBCodedOutputStream *stream = [[GPBCodedOutputStream alloc] initWithOutputStream:output]; [self writeToCodedOutputStream:stream]; [stream release]; } @@ -1322,8 +1276,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { } - (void)writeDelimitedToOutputStream:(NSOutputStream *)output { - GPBCodedOutputStream *codedOutput = - [[GPBCodedOutputStream alloc] initWithOutputStream:output]; + GPBCodedOutputStream *codedOutput = [[GPBCodedOutputStream alloc] initWithOutputStream:output]; [self writeDelimitedToCodedOutputStream:codedOutput]; [codedOutput release]; } @@ -1333,8 +1286,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { [self writeToCodedOutputStream:output]; } -- (void)writeField:(GPBFieldDescriptor *)field - toCodedOutputStream:(GPBCodedOutputStream *)output { +- (void)writeField:(GPBFieldDescriptor *)field toCodedOutputStream:(GPBCodedOutputStream *)output { GPBFieldType fieldType = field.fieldType; if (fieldType == GPBFieldTypeSingle) { BOOL has = GPBGetHasIvarField(self, field); @@ -1345,8 +1297,7 @@ static GPBUnknownFieldSet *GetOrMakeUnknownFields(GPBMessage *self) { uint32_t fieldNumber = GPBFieldNumber(field); switch (GPBGetFieldDataType(field)) { - -// clang-format off + // clang-format off //%PDDM-DEFINE FIELD_CASE(TYPE, REAL_TYPE) //%FIELD_CASE_FULL(TYPE, REAL_TYPE, REAL_TYPE) diff --git a/objectivec/GPBProtocolBuffers.m b/objectivec/GPBProtocolBuffers.m index 0545ae9b2b..c2833c5bb4 100644 --- a/objectivec/GPBProtocolBuffers.m +++ b/objectivec/GPBProtocolBuffers.m @@ -31,7 +31,6 @@ // If you want to build protocol buffers in your own project without adding the // project dependency, you can just add this file. - // This warning seems to treat code differently when it is #imported than when // it is inline in the file. GPBDictionary.m compiles cleanly in other targets, // but when #imported here it triggers a bunch of warnings that don't make diff --git a/objectivec/GPBRootObject.m b/objectivec/GPBRootObject.m index bad2f9a7a1..3126440046 100644 --- a/objectivec/GPBRootObject.m +++ b/objectivec/GPBRootObject.m @@ -73,26 +73,22 @@ static uint32_t jenkins_one_at_a_time_hash(const char *key) { // to worry about deallocation. All of the items are added to it at // startup, and so the keys don't need to be retained/released. // Keys are NULL terminated char *. -static const void *GPBRootExtensionKeyRetain(CFAllocatorRef allocator, - const void *value) { +static const void *GPBRootExtensionKeyRetain(CFAllocatorRef allocator, const void *value) { #pragma unused(allocator) return value; } -static void GPBRootExtensionKeyRelease(CFAllocatorRef allocator, - const void *value) { +static void GPBRootExtensionKeyRelease(CFAllocatorRef allocator, const void *value) { #pragma unused(allocator) #pragma unused(value) } static CFStringRef GPBRootExtensionCopyKeyDescription(const void *value) { const char *key = (const char *)value; - return CFStringCreateWithCString(kCFAllocatorDefault, key, - kCFStringEncodingUTF8); + return CFStringCreateWithCString(kCFAllocatorDefault, key, kCFStringEncodingUTF8); } -static Boolean GPBRootExtensionKeyEqual(const void *value1, - const void *value2) { +static Boolean GPBRootExtensionKeyEqual(const void *value1, const void *value2) { const char *key1 = (const char *)value1; const char *key2 = (const char *)value2; return strcmp(key1, key2) == 0; @@ -117,17 +113,16 @@ static GPBExtensionRegistry *gDefaultExtensionRegistry = NULL; if (!gExtensionSingletonDictionary) { gExtensionSingletonDictionarySemaphore = dispatch_semaphore_create(1); CFDictionaryKeyCallBacks keyCallBacks = { - // See description above for reason for using custom dictionary. - 0, - GPBRootExtensionKeyRetain, - GPBRootExtensionKeyRelease, - GPBRootExtensionCopyKeyDescription, - GPBRootExtensionKeyEqual, - GPBRootExtensionKeyHash, + // See description above for reason for using custom dictionary. + 0, + GPBRootExtensionKeyRetain, + GPBRootExtensionKeyRelease, + GPBRootExtensionCopyKeyDescription, + GPBRootExtensionKeyEqual, + GPBRootExtensionKeyHash, }; - gExtensionSingletonDictionary = - CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks, - &kCFTypeDictionaryValueCallBacks); + gExtensionSingletonDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &keyCallBacks, + &kCFTypeDictionaryValueCallBacks); gDefaultExtensionRegistry = [[GPBExtensionRegistry alloc] init]; } @@ -147,8 +142,7 @@ static GPBExtensionRegistry *gDefaultExtensionRegistry = NULL; + (void)globallyRegisterExtension:(GPBExtensionDescriptor *)field { const char *key = [field singletonNameC]; - dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, - DISPATCH_TIME_FOREVER); + dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, DISPATCH_TIME_FOREVER); CFDictionarySetValue(gExtensionSingletonDictionary, key, field); dispatch_semaphore_signal(gExtensionSingletonDictionarySemaphore); } @@ -189,8 +183,7 @@ static id ExtensionForName(id self, SEL _cmd) { // initialized and Message classes ensure their Root was also initialized. NSAssert(gExtensionSingletonDictionary, @"Startup order broken!"); - dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, - DISPATCH_TIME_FOREVER); + dispatch_semaphore_wait(gExtensionSingletonDictionarySemaphore, DISPATCH_TIME_FOREVER); id extension = (id)CFDictionaryGetValue(gExtensionSingletonDictionary, key); // We can't remove the key from the dictionary here (as an optimization), // two threads could have gone into +resolveClassMethod: for the same method, @@ -212,8 +205,7 @@ BOOL GPBResolveExtensionClassMethod(Class self, SEL sel) { // file. id extension = ExtensionForName(self, sel); if (extension != nil) { - const char *encoding = - GPBMessageEncodingForSelector(@selector(getClassValue), NO); + const char *encoding = GPBMessageEncodingForSelector(@selector(getClassValue), NO); Class metaClass = objc_getMetaClass(class_getName(self)); IMP imp = imp_implementationWithBlock(^(id obj) { #pragma unused(obj) @@ -234,7 +226,6 @@ BOOL GPBResolveExtensionClassMethod(Class self, SEL sel) { return NO; } - + (BOOL)resolveClassMethod:(SEL)sel { if (GPBResolveExtensionClassMethod(self, sel)) { return YES; diff --git a/objectivec/GPBUnknownField.m b/objectivec/GPBUnknownField.m index 7fa8cade2d..262d08234e 100644 --- a/objectivec/GPBUnknownField.m +++ b/objectivec/GPBUnknownField.m @@ -40,8 +40,8 @@ GPBUInt64Array *mutableVarintList_; GPBUInt32Array *mutableFixed32List_; GPBUInt64Array *mutableFixed64List_; - NSMutableArray *mutableLengthDelimitedList_; - NSMutableArray *mutableGroupList_; + NSMutableArray *mutableLengthDelimitedList_; + NSMutableArray *mutableGroupList_; } @synthesize number = number_; @@ -75,16 +75,14 @@ #pragma clang diagnostic ignored "-Wdirect-ivar-access" - (id)copyWithZone:(NSZone *)zone { - GPBUnknownField *result = - [[GPBUnknownField allocWithZone:zone] initWithNumber:number_]; + GPBUnknownField *result = [[GPBUnknownField allocWithZone:zone] initWithNumber:number_]; result->mutableFixed32List_ = [mutableFixed32List_ copyWithZone:zone]; result->mutableFixed64List_ = [mutableFixed64List_ copyWithZone:zone]; - result->mutableLengthDelimitedList_ = - [mutableLengthDelimitedList_ mutableCopyWithZone:zone]; + result->mutableLengthDelimitedList_ = [mutableLengthDelimitedList_ mutableCopyWithZone:zone]; result->mutableVarintList_ = [mutableVarintList_ copyWithZone:zone]; if (mutableGroupList_.count) { - result->mutableGroupList_ = [[NSMutableArray allocWithZone:zone] - initWithCapacity:mutableGroupList_.count]; + result->mutableGroupList_ = + [[NSMutableArray allocWithZone:zone] initWithCapacity:mutableGroupList_.count]; for (GPBUnknownFieldSet *group in mutableGroupList_) { GPBUnknownFieldSet *copied = [group copyWithZone:zone]; [result->mutableGroupList_ addObject:copied]; @@ -99,26 +97,21 @@ if (![object isKindOfClass:[GPBUnknownField class]]) return NO; GPBUnknownField *field = (GPBUnknownField *)object; if (number_ != field->number_) return NO; - BOOL equalVarint = - (mutableVarintList_.count == 0 && field->mutableVarintList_.count == 0) || - [mutableVarintList_ isEqual:field->mutableVarintList_]; + BOOL equalVarint = (mutableVarintList_.count == 0 && field->mutableVarintList_.count == 0) || + [mutableVarintList_ isEqual:field->mutableVarintList_]; if (!equalVarint) return NO; - BOOL equalFixed32 = (mutableFixed32List_.count == 0 && - field->mutableFixed32List_.count == 0) || + BOOL equalFixed32 = (mutableFixed32List_.count == 0 && field->mutableFixed32List_.count == 0) || [mutableFixed32List_ isEqual:field->mutableFixed32List_]; if (!equalFixed32) return NO; - BOOL equalFixed64 = (mutableFixed64List_.count == 0 && - field->mutableFixed64List_.count == 0) || + BOOL equalFixed64 = (mutableFixed64List_.count == 0 && field->mutableFixed64List_.count == 0) || [mutableFixed64List_ isEqual:field->mutableFixed64List_]; if (!equalFixed64) return NO; BOOL equalLDList = - (mutableLengthDelimitedList_.count == 0 && - field->mutableLengthDelimitedList_.count == 0) || + (mutableLengthDelimitedList_.count == 0 && field->mutableLengthDelimitedList_.count == 0) || [mutableLengthDelimitedList_ isEqual:field->mutableLengthDelimitedList_]; if (!equalLDList) return NO; - BOOL equalGroupList = - (mutableGroupList_.count == 0 && field->mutableGroupList_.count == 0) || - [mutableGroupList_ isEqual:field->mutableGroupList_]; + BOOL equalGroupList = (mutableGroupList_.count == 0 && field->mutableGroupList_.count == 0) || + [mutableGroupList_ isEqual:field->mutableGroupList_]; if (!equalGroupList) return NO; return YES; } @@ -160,23 +153,20 @@ - (size_t)serializedSize { __block size_t result = 0; int32_t number = number_; - [mutableVarintList_ - enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + [mutableVarintList_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) - result += GPBComputeUInt64Size(number, value); - }]; + result += GPBComputeUInt64Size(number, value); + }]; - [mutableFixed32List_ - enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + [mutableFixed32List_ enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) - result += GPBComputeFixed32Size(number, value); - }]; + result += GPBComputeFixed32Size(number, value); + }]; - [mutableFixed64List_ - enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + [mutableFixed64List_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) - result += GPBComputeFixed64Size(number, value); - }]; + result += GPBComputeFixed64Size(number, value); + }]; for (NSData *data in mutableLengthDelimitedList_) { result += GPBComputeBytesSize(number, data); @@ -205,25 +195,21 @@ - (NSString *)description { NSMutableString *description = - [NSMutableString stringWithFormat:@"<%@ %p>: Field: %d {\n", - [self class], self, number_]; - [mutableVarintList_ - enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + [NSMutableString stringWithFormat:@"<%@ %p>: Field: %d {\n", [self class], self, number_]; + [mutableVarintList_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) - [description appendFormat:@"\t%llu\n", value]; - }]; + [description appendFormat:@"\t%llu\n", value]; + }]; - [mutableFixed32List_ - enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { + [mutableFixed32List_ enumerateValuesWithBlock:^(uint32_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) - [description appendFormat:@"\t%u\n", value]; - }]; + [description appendFormat:@"\t%u\n", value]; + }]; - [mutableFixed64List_ - enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { + [mutableFixed64List_ enumerateValuesWithBlock:^(uint64_t value, NSUInteger idx, BOOL *stop) { #pragma unused(idx, stop) - [description appendFormat:@"\t%llu\n", value]; - }]; + [description appendFormat:@"\t%llu\n", value]; + }]; for (NSData *data in mutableLengthDelimitedList_) { [description appendFormat:@"\t%@\n", data]; @@ -269,16 +255,14 @@ if (mutableLengthDelimitedList_ == nil) { mutableLengthDelimitedList_ = [otherLengthDelimitedList mutableCopy]; } else { - [mutableLengthDelimitedList_ - addObjectsFromArray:otherLengthDelimitedList]; + [mutableLengthDelimitedList_ addObjectsFromArray:otherLengthDelimitedList]; } } NSArray *otherGroupList = other.groupList; if (otherGroupList.count > 0) { if (mutableGroupList_ == nil) { - mutableGroupList_ = - [[NSMutableArray alloc] initWithCapacity:otherGroupList.count]; + mutableGroupList_ = [[NSMutableArray alloc] initWithCapacity:otherGroupList.count]; } // Make our own mutable copies. for (GPBUnknownFieldSet *group in otherGroupList) { @@ -299,8 +283,7 @@ - (void)addFixed32:(uint32_t)value { if (mutableFixed32List_ == nil) { - mutableFixed32List_ = - [[GPBUInt32Array alloc] initWithValues:&value count:1]; + mutableFixed32List_ = [[GPBUInt32Array alloc] initWithValues:&value count:1]; } else { [mutableFixed32List_ addValue:value]; } @@ -308,8 +291,7 @@ - (void)addFixed64:(uint64_t)value { if (mutableFixed64List_ == nil) { - mutableFixed64List_ = - [[GPBUInt64Array alloc] initWithValues:&value count:1]; + mutableFixed64List_ = [[GPBUInt64Array alloc] initWithValues:&value count:1]; } else { [mutableFixed64List_ addValue:value]; } @@ -317,8 +299,7 @@ - (void)addLengthDelimited:(NSData *)value { if (mutableLengthDelimitedList_ == nil) { - mutableLengthDelimitedList_ = - [[NSMutableArray alloc] initWithObjects:&value count:1]; + mutableLengthDelimitedList_ = [[NSMutableArray alloc] initWithObjects:&value count:1]; } else { [mutableLengthDelimitedList_ addObject:value]; } diff --git a/objectivec/GPBUnknownFieldSet.m b/objectivec/GPBUnknownFieldSet.m index a7335f050b..101e102b0a 100644 --- a/objectivec/GPBUnknownFieldSet.m +++ b/objectivec/GPBUnknownFieldSet.m @@ -40,8 +40,7 @@ static void checkNumber(int32_t number) { if (number == 0) { - [NSException raise:NSInvalidArgumentException - format:@"Zero is not a valid field number."]; + [NSException raise:NSInvalidArgumentException format:@"Zero is not a valid field number."]; } } @@ -111,8 +110,7 @@ static void CopyWorker(const void *key, const void *value, void *context) { - (GPBUnknownField *)getField:(int32_t)number { ssize_t key = number; - GPBUnknownField *result = - fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil; + GPBUnknownField *result = fields_ ? CFDictionaryGetValue(fields_, (void *)key) : nil; return result; } @@ -125,8 +123,7 @@ static void CopyWorker(const void *key, const void *value, void *context) { size_t count = CFDictionaryGetCount(fields_); ssize_t keys[count]; GPBUnknownField *values[count]; - CFDictionaryGetKeysAndValues(fields_, (const void **)keys, - (const void **)values); + CFDictionaryGetKeysAndValues(fields_, (const void **)keys, (const void **)values); struct GPBFieldPair { ssize_t key; GPBUnknownField *value; @@ -135,12 +132,11 @@ static void CopyWorker(const void *key, const void *value, void *context) { pairs[i].key = keys[i]; pairs[i].value = values[i]; }; - qsort_b(pairs, count, sizeof(struct GPBFieldPair), - ^(const void *first, const void *second) { - const struct GPBFieldPair *a = first; - const struct GPBFieldPair *b = second; - return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); - }); + qsort_b(pairs, count, sizeof(struct GPBFieldPair), ^(const void *first, const void *second) { + const struct GPBFieldPair *a = first; + const struct GPBFieldPair *b = second; + return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); + }); for (size_t i = 0; i < count; ++i) { values[i] = pairs[i].value; }; @@ -154,8 +150,7 @@ static void CopyWorker(const void *key, const void *value, void *context) { size_t count = CFDictionaryGetCount(fields_); ssize_t keys[count]; GPBUnknownField *values[count]; - CFDictionaryGetKeysAndValues(fields_, (const void **)keys, - (const void **)values); + CFDictionaryGetKeysAndValues(fields_, (const void **)keys, (const void **)values); if (count > 1) { struct GPBFieldPair { ssize_t key; @@ -166,12 +161,11 @@ static void CopyWorker(const void *key, const void *value, void *context) { pairs[i].key = keys[i]; pairs[i].value = values[i]; }; - qsort_b(pairs, count, sizeof(struct GPBFieldPair), - ^(const void *first, const void *second) { - const struct GPBFieldPair *a = first; - const struct GPBFieldPair *b = second; - return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); - }); + qsort_b(pairs, count, sizeof(struct GPBFieldPair), ^(const void *first, const void *second) { + const struct GPBFieldPair *a = first; + const struct GPBFieldPair *b = second; + return (a->key > b->key) ? 1 : ((a->key == b->key) ? 0 : -1); + }); for (size_t i = 0; i < count; ++i) { GPBUnknownField *value = pairs[i].value; [value writeToOutput:output]; @@ -182,16 +176,15 @@ static void CopyWorker(const void *key, const void *value, void *context) { } - (NSString *)description { - NSMutableString *description = [NSMutableString - stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self]; + NSMutableString *description = + [NSMutableString stringWithFormat:@"<%@ %p>: TextFormat: {\n", [self class], self]; NSString *textFormat = GPBTextFormatForUnknownFieldSet(self, @" "); [description appendString:textFormat]; [description appendString:@"}"]; return description; } -static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value, - void *context) { +static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; size_t *result = context; @@ -201,14 +194,12 @@ static void GPBUnknownFieldSetSerializedSize(const void *key, const void *value, - (size_t)serializedSize { size_t result = 0; if (fields_) { - CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize, - &result); + CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSize, &result); } return result; } -static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key, - const void *value, +static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; @@ -218,13 +209,11 @@ static void GPBUnknownFieldSetWriteAsMessageSetTo(const void *key, - (void)writeAsMessageSetTo:(GPBCodedOutputStream *)output { if (fields_) { - CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo, - output); + CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetWriteAsMessageSetTo, output); } } -static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, - const void *value, +static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; @@ -235,16 +224,14 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, - (size_t)serializedSizeAsMessageSet { size_t result = 0; if (fields_) { - CFDictionaryApplyFunction( - fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result); + CFDictionaryApplyFunction(fields_, GPBUnknownFieldSetSerializedSizeAsMessageSet, &result); } return result; } - (NSData *)data { NSMutableData *data = [NSMutableData dataWithLength:self.serializedSize]; - GPBCodedOutputStream *output = - [[GPBCodedOutputStream alloc] initWithData:data]; + GPBCodedOutputStream *output = [[GPBCodedOutputStream alloc] initWithData:data]; [self writeToCodedOutputStream:output]; [output release]; return data; @@ -260,8 +247,8 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, if (!fields_) { // Use a custom dictionary here because the keys are numbers and conversion // back and forth from NSNumber isn't worth the cost. - fields_ = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, - &kCFTypeDictionaryValueCallBacks); + fields_ = + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks); } ssize_t key = number; CFDictionarySetValue(fields_, (const void *)key, field); @@ -269,8 +256,7 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, - (GPBUnknownField *)mutableFieldForNumber:(int32_t)number create:(BOOL)create { ssize_t key = number; - GPBUnknownField *existing = - fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil; + GPBUnknownField *existing = fields_ ? CFDictionaryGetValue(fields_, (const void *)key) : nil; if (!existing && create) { existing = [[GPBUnknownField alloc] initWithNumber:number]; // This retains existing. @@ -280,8 +266,7 @@ static void GPBUnknownFieldSetSerializedSizeAsMessageSet(const void *key, return existing; } -static void GPBUnknownFieldSetMergeUnknownFields(const void *key, - const void *value, +static void GPBUnknownFieldSetMergeUnknownFields(const void *key, const void *value, void *context) { #pragma unused(key) GPBUnknownField *field = value; @@ -304,8 +289,7 @@ static void GPBUnknownFieldSetMergeUnknownFields(const void *key, - (void)mergeUnknownFields:(GPBUnknownFieldSet *)other { if (other && other->fields_) { - CFDictionaryApplyFunction(other->fields_, - GPBUnknownFieldSetMergeUnknownFields, self); + CFDictionaryApplyFunction(other->fields_, GPBUnknownFieldSetMergeUnknownFields, self); } } @@ -362,8 +346,7 @@ static void GPBUnknownFieldSetMergeUnknownFields(const void *key, } - (void)mergeMessageSetMessage:(int32_t)number data:(NSData *)messageData { - [[self mutableFieldForNumber:number create:YES] - addLengthDelimited:messageData]; + [[self mutableFieldForNumber:number create:YES] addLengthDelimited:messageData]; } - (void)addUnknownMapEntry:(int32_t)fieldNum value:(NSData *)data { diff --git a/objectivec/GPBUtilities.m b/objectivec/GPBUtilities.m index 739e36cdeb..d355ee4113 100644 --- a/objectivec/GPBUtilities.m +++ b/objectivec/GPBUtilities.m @@ -45,28 +45,24 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" -static void AppendTextFormatForMessage(GPBMessage *message, - NSMutableString *toStr, +static void AppendTextFormatForMessage(GPBMessage *message, NSMutableString *toStr, NSString *lineIndent); // Are two datatypes the same basic type representation (ex Int32 and SInt32). // Marked unused because currently only called from asserts/debug. -static BOOL DataTypesEquivalent(GPBDataType type1, - GPBDataType type2) __attribute__ ((unused)); +static BOOL DataTypesEquivalent(GPBDataType type1, GPBDataType type2) __attribute__((unused)); // Basic type representation for a type (ex: for SInt32 it is Int32). // Marked unused because currently only called from asserts/debug. -static GPBDataType BaseDataType(GPBDataType type) __attribute__ ((unused)); +static GPBDataType BaseDataType(GPBDataType type) __attribute__((unused)); // String name for a data type. // Marked unused because currently only called from asserts/debug. -static NSString *TypeToString(GPBDataType dataType) __attribute__ ((unused)); +static NSString *TypeToString(GPBDataType dataType) __attribute__((unused)); // Helper for clearing oneofs. -static void GPBMaybeClearOneofPrivate(GPBMessage *self, - GPBOneofDescriptor *oneof, - int32_t oneofHasIndex, - uint32_t fieldNumberNotToClear); +static void GPBMaybeClearOneofPrivate(GPBMessage *self, GPBOneofDescriptor *oneof, + int32_t oneofHasIndex, uint32_t fieldNumberNotToClear); NSData *GPBEmptyNSData(void) { static dispatch_once_t onceToken; @@ -118,52 +114,58 @@ void GPBMessageDropUnknownFieldsRecursively(GPBMessage *initialMessage) { id rawFieldMap = GPBGetObjectIvarWithFieldNoAutocreate(msg, field); switch (field.mapKeyDataType) { case GPBDataTypeBool: - [(GPBBoolObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( - BOOL key, id _Nonnull object, BOOL * _Nonnull stop) { - #pragma unused(key, stop) - [todo addObject:object]; - }]; + [(GPBBoolObjectDictionary *)rawFieldMap + enumerateKeysAndObjectsUsingBlock:^(BOOL key, id _Nonnull object, + BOOL *_Nonnull stop) { +#pragma unused(key, stop) + [todo addObject:object]; + }]; break; case GPBDataTypeFixed32: case GPBDataTypeUInt32: - [(GPBUInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( - uint32_t key, id _Nonnull object, BOOL * _Nonnull stop) { - #pragma unused(key, stop) - [todo addObject:object]; - }]; + [(GPBUInt32ObjectDictionary *)rawFieldMap + enumerateKeysAndObjectsUsingBlock:^(uint32_t key, id _Nonnull object, + BOOL *_Nonnull stop) { +#pragma unused(key, stop) + [todo addObject:object]; + }]; break; case GPBDataTypeInt32: case GPBDataTypeSFixed32: case GPBDataTypeSInt32: - [(GPBInt32ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( - int32_t key, id _Nonnull object, BOOL * _Nonnull stop) { - #pragma unused(key, stop) - [todo addObject:object]; - }]; + [(GPBInt32ObjectDictionary *)rawFieldMap + enumerateKeysAndObjectsUsingBlock:^(int32_t key, id _Nonnull object, + BOOL *_Nonnull stop) { +#pragma unused(key, stop) + [todo addObject:object]; + }]; break; case GPBDataTypeFixed64: case GPBDataTypeUInt64: - [(GPBUInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( - uint64_t key, id _Nonnull object, BOOL * _Nonnull stop) { - #pragma unused(key, stop) - [todo addObject:object]; - }]; + [(GPBUInt64ObjectDictionary *)rawFieldMap + enumerateKeysAndObjectsUsingBlock:^(uint64_t key, id _Nonnull object, + BOOL *_Nonnull stop) { +#pragma unused(key, stop) + [todo addObject:object]; + }]; break; case GPBDataTypeInt64: case GPBDataTypeSFixed64: case GPBDataTypeSInt64: - [(GPBInt64ObjectDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( - int64_t key, id _Nonnull object, BOOL * _Nonnull stop) { - #pragma unused(key, stop) - [todo addObject:object]; - }]; + [(GPBInt64ObjectDictionary *)rawFieldMap + enumerateKeysAndObjectsUsingBlock:^(int64_t key, id _Nonnull object, + BOOL *_Nonnull stop) { +#pragma unused(key, stop) + [todo addObject:object]; + }]; break; case GPBDataTypeString: - [(NSDictionary*)rawFieldMap enumerateKeysAndObjectsUsingBlock:^( - NSString * _Nonnull key, GPBMessage * _Nonnull obj, BOOL * _Nonnull stop) { - #pragma unused(key, stop) - [todo addObject:obj]; - }]; + [(NSDictionary *)rawFieldMap + enumerateKeysAndObjectsUsingBlock:^( + NSString *_Nonnull key, GPBMessage *_Nonnull obj, BOOL *_Nonnull stop) { +#pragma unused(key, stop) + [todo addObject:obj]; + }]; break; case GPBDataTypeFloat: case GPBDataTypeDouble: @@ -175,8 +177,8 @@ void GPBMessageDropUnknownFieldsRecursively(GPBMessage *initialMessage) { } break; } // switch(field.mapKeyDataType) - } // switch(field.fieldType) - } // for(fields) + } // switch(field.fieldType) + } // for(fields) // Handle any extensions holding messages. for (GPBExtensionDescriptor *extension in [msg extensionsCurrentlySet]) { @@ -195,7 +197,6 @@ void GPBMessageDropUnknownFieldsRecursively(GPBMessage *initialMessage) { } // while(todo.count) } - // -- About Version Checks -- // There's actually 3 places these checks all come into play: // 1. When the generated source is compile into .o files, the header check @@ -228,8 +229,7 @@ void GPBCheckRuntimeVersionSupport(int32_t objcRuntimeVersion) { format:@"Proto generation source compiled against runtime" @" version %d, but this version of the runtime only" @" supports back to %d!", - objcRuntimeVersion, - GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION]; + objcRuntimeVersion, GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION]; } } @@ -288,18 +288,16 @@ void GPBClearMessageField(GPBMessage *self, GPBFieldDescriptor *field) { } void GPBClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof) { - #if defined(DEBUG) && DEBUG - NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof, - @"OneofDescriptor %@ doesn't appear to be for %@ messages.", - oneof.name, [self class]); - #endif +#if defined(DEBUG) && DEBUG + NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof, + @"OneofDescriptor %@ doesn't appear to be for %@ messages.", oneof.name, [self class]); +#endif GPBFieldDescriptor *firstField = oneof->fields_[0]; GPBMaybeClearOneofPrivate(self, oneof, firstField->description_->hasIndex, 0); } BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) { - NSCAssert(self->messageStorage_ != NULL, - @"%@: All messages should have storage (from init)", + NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); if (idx < 0) { NSCAssert(fieldNumber != 0, @"Invalid field number."); @@ -309,21 +307,18 @@ BOOL GPBGetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber) { NSCAssert(idx != GPBNoHasBit, @"Invalid has bit."); uint32_t byteIndex = idx / 32; uint32_t bitMask = (1U << (idx % 32)); - BOOL hasIvar = - (self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO; + BOOL hasIvar = (self->messageStorage_->_has_storage_[byteIndex] & bitMask) ? YES : NO; return hasIvar; } } uint32_t GPBGetHasOneof(GPBMessage *self, int32_t idx) { - NSCAssert(idx < 0, @"%@: invalid index (%d) for oneof.", - [self class], idx); + NSCAssert(idx < 0, @"%@: invalid index (%d) for oneof.", [self class], idx); uint32_t result = self->messageStorage_->_has_storage_[-idx]; return result; } -void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, - BOOL value) { +void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, BOOL value) { if (idx < 0) { NSCAssert(fieldNumber != 0, @"Invalid field number."); uint32_t *has_storage = self->messageStorage_->_has_storage_; @@ -341,10 +336,8 @@ void GPBSetHasIvar(GPBMessage *self, int32_t idx, uint32_t fieldNumber, } } -static void GPBMaybeClearOneofPrivate(GPBMessage *self, - GPBOneofDescriptor *oneof, - int32_t oneofHasIndex, - uint32_t fieldNumberNotToClear) { +static void GPBMaybeClearOneofPrivate(GPBMessage *self, GPBOneofDescriptor *oneof, + int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) { uint32_t fieldNumberSet = GPBGetHasOneof(self, oneofHasIndex); if ((fieldNumberSet == fieldNumberNotToClear) || (fieldNumberSet == 0)) { // Do nothing/nothing set in the oneof. @@ -354,9 +347,8 @@ static void GPBMaybeClearOneofPrivate(GPBMessage *self, // Like GPBClearMessageField(), free the memory if an objecttype is set, // pod types don't need to do anything. GPBFieldDescriptor *fieldSet = [oneof fieldWithNumber:fieldNumberSet]; - NSCAssert(fieldSet, - @"%@: oneof set to something (%u) not in the oneof?", - [self class], fieldNumberSet); + NSCAssert(fieldSet, @"%@: oneof set to something (%u) not in the oneof?", [self class], + fieldNumberSet); if (fieldSet && GPBFieldStoresObject(fieldSet)) { uint8_t *storage = (uint8_t *)self->messageStorage_; id *typePtr = (id *)&storage[fieldSet->description_->offset]; @@ -508,8 +500,7 @@ static void GPBMaybeClearOneofPrivate(GPBMessage *self, // Object types are handled slightly differently, they need to be released // and retained. -void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field) { +void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, GPBFieldDescriptor *field) { if (GPBGetHasIvarField(self, field)) { return; } @@ -522,14 +513,12 @@ void GPBClearAutocreatedMessageIvarWithField(GPBMessage *self, } // This exists only for bridging some aliased types, nothing else should use it. -static void GPBSetObjectIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field, id value) { +static void GPBSetObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, id value) { if (self == nil || field == nil) return; GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value retain]); } -static void GPBSetCopyObjectIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field, id value); +static void GPBSetCopyObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, id value); // GPBSetCopyObjectIvarWithField is blocked from the analyzer because it flags // a leak for the -copy even though GPBSetRetainedObjectIvarWithFieldPrivate @@ -537,23 +526,19 @@ static void GPBSetCopyObjectIvarWithField(GPBMessage *self, // with the -retain in GPBSetObjectIvarWithField. #if !defined(__clang_analyzer__) // This exists only for bridging some aliased types, nothing else should use it. -static void GPBSetCopyObjectIvarWithField(GPBMessage *self, - GPBFieldDescriptor *field, id value) { +static void GPBSetCopyObjectIvarWithField(GPBMessage *self, GPBFieldDescriptor *field, id value) { if (self == nil || field == nil) return; GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value copy]); } #endif // !defined(__clang_analyzer__) -void GPBSetObjectIvarWithFieldPrivate(GPBMessage *self, - GPBFieldDescriptor *field, id value) { +void GPBSetObjectIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, id value) { GPBSetRetainedObjectIvarWithFieldPrivate(self, field, [value retain]); } -void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, - GPBFieldDescriptor *field, +void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, id value) { - NSCAssert(self->messageStorage_ != NULL, - @"%@: All messages should have storage (from init)", + NSCAssert(self->messageStorage_ != NULL, @"%@: All messages should have storage (from init)", [self class]); #if defined(__clang_analyzer__) if (self->messageStorage_ == NULL) return; @@ -562,8 +547,7 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, BOOL isMapOrArray = GPBFieldIsMapOrArray(field); BOOL fieldIsMessage = GPBDataTypeIsMessage(fieldType); #if defined(DEBUG) && DEBUG - if (value == nil && !isMapOrArray && !fieldIsMessage && - field.hasDefaultValue) { + if (value == nil && !isMapOrArray && !fieldIsMessage && field.hasDefaultValue) { // Setting a message to nil is an obvious way to "clear" the value // as there is no way to set a non-empty default value for messages. // @@ -584,8 +568,8 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, @"empty, or call '%@.%@ = NO' to reset it to it's default value of " @"'%@'. Defaulting to resetting default value.", className, propName, className, propName, - (fieldType == GPBDataTypeString) ? @"@\"\"" : @"GPBEmptyNSData()", - className, hasSel, field.defaultValue.valueString); + (fieldType == GPBDataTypeString) ? @"@\"\"" : @"GPBEmptyNSData()", className, hasSel, + field.defaultValue.valueString); // Note: valueString, depending on the type, it could easily be // valueData/valueMessage. } @@ -602,8 +586,7 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, BOOL setHasValue = (value != nil); // If the field should clear on a "zero" value, then check if the string/data // was zero length, and clear instead. - if (((fieldDesc->flags & GPBFieldClearHasIvarOnZero) != 0) && - ([value length] == 0)) { + if (((fieldDesc->flags & GPBFieldClearHasIvarOnZero) != 0) && ([value length] == 0)) { setHasValue = NO; // The value passed in was retained, it must be released since we // aren't saving anything in the field. @@ -637,10 +620,9 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, gpbArray->_autocreator = nil; } } - } else { // GPBFieldTypeMap + } else { // GPBFieldTypeMap // If the old map was autocreated by us, then clear it. - if ((field.mapKeyDataType == GPBDataTypeString) && - GPBDataTypeIsObject(fieldType)) { + if ((field.mapKeyDataType == GPBDataTypeString) && GPBDataTypeIsObject(fieldType)) { if ([oldValue isKindOfClass:[GPBAutocreatedDictionary class]]) { GPBAutocreatedDictionary *autoDict = oldValue; if (autoDict->_autocreator == self) { @@ -668,8 +650,7 @@ void GPBSetRetainedObjectIvarWithFieldPrivate(GPBMessage *self, GPBBecomeVisibleToAutocreator(self); } -id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, - GPBFieldDescriptor *field) { +id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, GPBFieldDescriptor *field) { if (self->messageStorage_ == nil) { return nil; } @@ -680,80 +661,68 @@ id GPBGetObjectIvarWithFieldNoAutocreate(GPBMessage *self, // Only exists for public api, no core code should use this. int32_t GPBGetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field) { - #if defined(DEBUG) && DEBUG - NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, - @"FieldDescriptor %@ doesn't appear to be for %@ messages.", - field.name, [self class]); - NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum, - @"Attempting to get value of type Enum from field %@ " - @"of %@ which is of type %@.", - [self class], field.name, - TypeToString(GPBGetFieldDataType(field))); - #endif +#if defined(DEBUG) && DEBUG + NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, + @"FieldDescriptor %@ doesn't appear to be for %@ messages.", field.name, [self class]); + NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum, + @"Attempting to get value of type Enum from field %@ " + @"of %@ which is of type %@.", + [self class], field.name, TypeToString(GPBGetFieldDataType(field))); +#endif int32_t result = GPBGetMessageInt32Field(self, field); // If this is presevering unknown enums, make sure the value is valid before // returning it. GPBFileSyntax syntax = [self descriptor].file.syntax; - if (GPBHasPreservingUnknownEnumSemantics(syntax) && - ![field isValidEnumValue:result]) { + if (GPBHasPreservingUnknownEnumSemantics(syntax) && ![field isValidEnumValue:result]) { result = kGPBUnrecognizedEnumeratorValue; } return result; } // Only exists for public api, no core code should use this. -void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, - int32_t value) { - #if defined(DEBUG) && DEBUG - NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, - @"FieldDescriptor %@ doesn't appear to be for %@ messages.", - field.name, [self class]); - NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum, - @"Attempting to set field %@ of %@ which is of type %@ with " - @"value of type Enum.", - [self class], field.name, - TypeToString(GPBGetFieldDataType(field))); - #endif +void GPBSetMessageEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) { +#if defined(DEBUG) && DEBUG + NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, + @"FieldDescriptor %@ doesn't appear to be for %@ messages.", field.name, [self class]); + NSCAssert(GPBGetFieldDataType(field) == GPBDataTypeEnum, + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type Enum.", + [self class], field.name, TypeToString(GPBGetFieldDataType(field))); +#endif GPBSetEnumIvarWithFieldPrivate(self, field, value); } -void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self, - GPBFieldDescriptor *field, int32_t value) { +void GPBSetEnumIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) { // Don't allow in unknown values. Proto3 can use the Raw method. if (![field isValidEnumValue:value]) { [NSException raise:NSInvalidArgumentException - format:@"%@.%@: Attempt to set an unknown enum value (%d)", - [self class], field.name, value]; + format:@"%@.%@: Attempt to set an unknown enum value (%d)", [self class], + field.name, value]; } GPBSetInt32IvarWithFieldPrivate(self, field, value); } // Only exists for public api, no core code should use this. -int32_t GPBGetMessageRawEnumField(GPBMessage *self, - GPBFieldDescriptor *field) { +int32_t GPBGetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field) { int32_t result = GPBGetMessageInt32Field(self, field); return result; } // Only exists for public api, no core code should use this. -void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, - int32_t value) { +void GPBSetMessageRawEnumField(GPBMessage *self, GPBFieldDescriptor *field, int32_t value) { GPBSetInt32IvarWithFieldPrivate(self, field, value); } -BOOL GPBGetMessageBoolField(GPBMessage *self, - GPBFieldDescriptor *field) { +BOOL GPBGetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field) { #if defined(DEBUG) && DEBUG NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, - @"FieldDescriptor %@ doesn't appear to be for %@ messages.", - field.name, [self class]); + @"FieldDescriptor %@ doesn't appear to be for %@ messages.", field.name, [self class]); NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool), @"Attempting to get value of type bool from field %@ " @"of %@ which is of type %@.", - [self class], field.name, - TypeToString(GPBGetFieldDataType(field))); + [self class], field.name, TypeToString(GPBGetFieldDataType(field))); #endif if (GPBGetHasIvarField(self, field)) { // Bools are stored in the has bits to avoid needing explicit space in the @@ -768,26 +737,20 @@ BOOL GPBGetMessageBoolField(GPBMessage *self, } // Only exists for public api, no core code should use this. -void GPBSetMessageBoolField(GPBMessage *self, - GPBFieldDescriptor *field, - BOOL value) { +void GPBSetMessageBoolField(GPBMessage *self, GPBFieldDescriptor *field, BOOL value) { if (self == nil || field == nil) return; - #if defined(DEBUG) && DEBUG - NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, - @"FieldDescriptor %@ doesn't appear to be for %@ messages.", - field.name, [self class]); - NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool), - @"Attempting to set field %@ of %@ which is of type %@ with " - @"value of type bool.", - [self class], field.name, - TypeToString(GPBGetFieldDataType(field))); - #endif +#if defined(DEBUG) && DEBUG + NSCAssert([[self descriptor] fieldWithNumber:field.number] == field, + @"FieldDescriptor %@ doesn't appear to be for %@ messages.", field.name, [self class]); + NSCAssert(DataTypesEquivalent(GPBGetFieldDataType(field), GPBDataTypeBool), + @"Attempting to set field %@ of %@ which is of type %@ with " + @"value of type bool.", + [self class], field.name, TypeToString(GPBGetFieldDataType(field))); +#endif GPBSetBoolIvarWithFieldPrivate(self, field, value); } -void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self, - GPBFieldDescriptor *field, - BOOL value) { +void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self, GPBFieldDescriptor *field, BOOL value) { GPBMessageFieldDescription *fieldDesc = field->description_; GPBOneofDescriptor *oneof = field->containingOneof_; if (oneof) { @@ -802,8 +765,7 @@ void GPBSetBoolIvarWithFieldPrivate(GPBMessage *self, // If the value is zero, then we only count the field as "set" if the field // shouldn't auto clear on zero. - BOOL hasValue = ((value != (BOOL)0) - || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0)); + BOOL hasValue = ((value != (BOOL)0) || ((fieldDesc->flags & GPBFieldClearHasIvarOnZero) == 0)); GPBSetHasIvar(self, fieldDesc->hasIndex, fieldDesc->number, hasValue); GPBBecomeVisibleToAutocreator(self); } @@ -1379,8 +1341,7 @@ void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id #if defined(DEBUG) && DEBUG if (field.fieldType != GPBFieldTypeRepeated) { [NSException raise:NSInvalidArgumentException - format:@"%@.%@ is not a repeated field.", - [self class], field.name]; + format:@"%@.%@ is not a repeated field.", [self class], field.name]; } Class expectedClass = Nil; switch (GPBGetFieldDataType(field)) { @@ -1423,8 +1384,8 @@ void GPBSetMessageRepeatedField(GPBMessage *self, GPBFieldDescriptor *field, id } if (array && ![array isKindOfClass:expectedClass]) { [NSException raise:NSInvalidArgumentException - format:@"%@.%@: Expected %@ object, got %@.", - [self class], field.name, expectedClass, [array class]]; + format:@"%@.%@: Expected %@ object, got %@.", [self class], field.name, + expectedClass, [array class]]; } #endif GPBSetObjectIvarWithField(self, field, array); @@ -1456,7 +1417,7 @@ static GPBDataType BaseDataType(GPBDataType type) { case GPBDataTypeBytes: case GPBDataTypeString: return type; - } + } } static BOOL DataTypesEquivalent(GPBDataType type1, GPBDataType type2) { @@ -1498,13 +1459,11 @@ static NSString *TypeToString(GPBDataType dataType) { // GPBGetMessageMapField is defined in GPBMessage.m // Only exists for public api, no core code should use this. -void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, - id dictionary) { +void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, id dictionary) { #if defined(DEBUG) && DEBUG if (field.fieldType != GPBFieldTypeMap) { [NSException raise:NSInvalidArgumentException - format:@"%@.%@ is not a map<> field.", - [self class], field.name]; + format:@"%@.%@ is not a map<> field.", [self class], field.name]; } if (dictionary) { GPBDataType keyDataType = field.mapKeyDataType; @@ -1515,20 +1474,17 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, keyStr = @"String"; } Class expectedClass = Nil; - if ((keyDataType == GPBDataTypeString) && - GPBDataTypeIsObject(valueDataType)) { + if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { expectedClass = [NSMutableDictionary class]; } else { - NSString *className = - [NSString stringWithFormat:@"GPB%@%@Dictionary", keyStr, valueStr]; + NSString *className = [NSString stringWithFormat:@"GPB%@%@Dictionary", keyStr, valueStr]; expectedClass = NSClassFromString(className); NSCAssert(expectedClass, @"Missing a class (%@)?", expectedClass); } if (![dictionary isKindOfClass:expectedClass]) { [NSException raise:NSInvalidArgumentException - format:@"%@.%@: Expected %@ object, got %@.", - [self class], field.name, expectedClass, - [dictionary class]]; + format:@"%@.%@: Expected %@ object, got %@.", [self class], field.name, + expectedClass, [dictionary class]]; } } #endif @@ -1538,13 +1494,12 @@ void GPBSetMessageMapField(GPBMessage *self, GPBFieldDescriptor *field, #pragma mark - Misc Dynamic Runtime Utils const char *GPBMessageEncodingForSelector(SEL selector, BOOL instanceSel) { - Protocol *protocol = - objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol)); + Protocol *protocol = objc_getProtocol(GPBStringifySymbol(GPBMessageSignatureProtocol)); NSCAssert(protocol, @"Missing GPBMessageSignatureProtocol"); struct objc_method_description description = protocol_getMethodDescription(protocol, selector, NO, instanceSel); - NSCAssert(description.name != Nil && description.types != nil, - @"Missing method for selector %@", NSStringFromSelector(selector)); + NSCAssert(description.name != Nil && description.types != nil, @"Missing method for selector %@", + NSStringFromSelector(selector)); return description.types; } @@ -1556,19 +1511,30 @@ static void AppendStringEscaped(NSString *toPrint, NSMutableString *destStr) { for (NSUInteger i = 0; i < len; ++i) { unichar aChar = [toPrint characterAtIndex:i]; switch (aChar) { - case '\n': [destStr appendString:@"\\n"]; break; - case '\r': [destStr appendString:@"\\r"]; break; - case '\t': [destStr appendString:@"\\t"]; break; - case '\"': [destStr appendString:@"\\\""]; break; - case '\'': [destStr appendString:@"\\\'"]; break; - case '\\': [destStr appendString:@"\\\\"]; break; + case '\n': + [destStr appendString:@"\\n"]; + break; + case '\r': + [destStr appendString:@"\\r"]; + break; + case '\t': + [destStr appendString:@"\\t"]; + break; + case '\"': + [destStr appendString:@"\\\""]; + break; + case '\'': + [destStr appendString:@"\\\'"]; + break; + case '\\': + [destStr appendString:@"\\\\"]; + break; default: // This differs slightly from the C++ code in that the C++ doesn't // generate UTF8; it looks at the string in UTF8, but escapes every // byte > 0x7E. if (aChar < 0x20) { - [destStr appendFormat:@"\\%d%d%d", - (aChar / 64), ((aChar % 64) / 8), (aChar % 8)]; + [destStr appendFormat:@"\\%d%d%d", (aChar / 64), ((aChar % 64) / 8), (aChar % 8)]; } else { [destStr appendFormat:@"%C", aChar]; } @@ -1584,12 +1550,24 @@ static void AppendBufferAsString(NSData *buffer, NSMutableString *destStr) { [destStr appendString:@"\""]; for (const char *srcEnd = src + srcLen; src < srcEnd; src++) { switch (*src) { - case '\n': [destStr appendString:@"\\n"]; break; - case '\r': [destStr appendString:@"\\r"]; break; - case '\t': [destStr appendString:@"\\t"]; break; - case '\"': [destStr appendString:@"\\\""]; break; - case '\'': [destStr appendString:@"\\\'"]; break; - case '\\': [destStr appendString:@"\\\\"]; break; + case '\n': + [destStr appendString:@"\\n"]; + break; + case '\r': + [destStr appendString:@"\\r"]; + break; + case '\t': + [destStr appendString:@"\\t"]; + break; + case '\"': + [destStr appendString:@"\\\""]; + break; + case '\'': + [destStr appendString:@"\\\'"]; + break; + case '\\': + [destStr appendString:@"\\\\"]; + break; default: if (isprint(*src)) { [destStr appendFormat:@"%c", *src]; @@ -1605,31 +1583,29 @@ static void AppendBufferAsString(NSData *buffer, NSMutableString *destStr) { [destStr appendString:@"\""]; } -static void AppendTextFormatForMapMessageField( - id map, GPBFieldDescriptor *field, NSMutableString *toStr, - NSString *lineIndent, NSString *fieldName, NSString *lineEnding) { +static void AppendTextFormatForMapMessageField(id map, GPBFieldDescriptor *field, + NSMutableString *toStr, NSString *lineIndent, + NSString *fieldName, NSString *lineEnding) { GPBDataType keyDataType = field.mapKeyDataType; GPBDataType valueDataType = GPBGetFieldDataType(field); BOOL isMessageValue = GPBDataTypeIsMessage(valueDataType); NSString *msgStartFirst = [NSString stringWithFormat:@"%@%@ {%@\n", lineIndent, fieldName, lineEnding]; - NSString *msgStart = - [NSString stringWithFormat:@"%@%@ {\n", lineIndent, fieldName]; + NSString *msgStart = [NSString stringWithFormat:@"%@%@ {\n", lineIndent, fieldName]; NSString *msgEnd = [NSString stringWithFormat:@"%@}\n", lineIndent]; NSString *keyLine = [NSString stringWithFormat:@"%@ key: ", lineIndent]; - NSString *valueLine = [NSString stringWithFormat:@"%@ value%s ", lineIndent, - (isMessageValue ? "" : ":")]; + NSString *valueLine = + [NSString stringWithFormat:@"%@ value%s ", lineIndent, (isMessageValue ? "" : ":")]; __block BOOL isFirst = YES; - if ((keyDataType == GPBDataTypeString) && - GPBDataTypeIsObject(valueDataType)) { + if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { // map is an NSDictionary. NSDictionary *dict = map; [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) { - #pragma unused(stop) +#pragma unused(stop) [toStr appendString:(isFirst ? msgStartFirst : msgStart)]; isFirst = NO; @@ -1729,10 +1705,8 @@ static void AppendTextFormatForMapMessageField( } } -static void AppendTextFormatForMessageField(GPBMessage *message, - GPBFieldDescriptor *field, - NSMutableString *toStr, - NSString *lineIndent) { +static void AppendTextFormatForMessageField(GPBMessage *message, GPBFieldDescriptor *field, + NSMutableString *toStr, NSString *lineIndent) { id arrayOrMap; NSUInteger count; GPBFieldType fieldType = field.fieldType; @@ -1780,8 +1754,7 @@ static void AppendTextFormatForMessageField(GPBMessage *message, } if (fieldType == GPBFieldTypeMap) { - AppendTextFormatForMapMessageField(arrayOrMap, field, toStr, lineIndent, - fieldName, lineEnding); + AppendTextFormatForMapMessageField(arrayOrMap, field, toStr, lineIndent, fieldName, lineEnding); return; } @@ -1792,8 +1765,7 @@ static void AppendTextFormatForMessageField(GPBMessage *message, BOOL isMessageField = GPBDataTypeIsMessage(fieldDataType); for (NSUInteger j = 0; j < count; ++j) { // Start the line. - [toStr appendFormat:@"%@%@%s ", lineIndent, fieldName, - (isMessageField ? "" : ":")]; + [toStr appendFormat:@"%@%@%s ", lineIndent, fieldName, (isMessageField ? "" : ":")]; // The value. switch (fieldDataType) { @@ -1859,9 +1831,8 @@ static void AppendTextFormatForMessageField(GPBMessage *message, case GPBDataTypeGroup: case GPBDataTypeMessage: { - GPBMessage *v = - (isRepeated ? [(NSArray *)array objectAtIndex:j] - : GPBGetObjectIvarWithField(message, field)); + GPBMessage *v = (isRepeated ? [(NSArray *)array objectAtIndex:j] + : GPBGetObjectIvarWithField(message, field)); [toStr appendFormat:@"{%@\n", lineEnding]; NSString *subIndent = [lineIndent stringByAppendingString:@" "]; AppendTextFormatForMessage(v, toStr, subIndent); @@ -1878,11 +1849,9 @@ static void AppendTextFormatForMessageField(GPBMessage *message, } // for(count) } -static void AppendTextFormatForMessageExtensionRange(GPBMessage *message, - NSArray *activeExtensions, +static void AppendTextFormatForMessageExtensionRange(GPBMessage *message, NSArray *activeExtensions, GPBExtensionRange range, - NSMutableString *toStr, - NSString *lineIndent) { + NSMutableString *toStr, NSString *lineIndent) { uint32_t start = range.start; uint32_t end = range.end; for (GPBExtensionDescriptor *extension in activeExtensions) { @@ -1951,8 +1920,7 @@ static void AppendTextFormatForMessageExtensionRange(GPBMessage *message, #undef FIELD_CASE case GPBDataTypeBool: - [toStr appendString:([(NSNumber *)curValue boolValue] ? @"true" - : @"false")]; + [toStr appendString:([(NSNumber *)curValue boolValue] ? @"true" : @"false")]; break; case GPBDataTypeString: @@ -1983,32 +1951,29 @@ static void AppendTextFormatForMessageExtensionRange(GPBMessage *message, } // for..in(activeExtensions) } -static void AppendTextFormatForMessage(GPBMessage *message, - NSMutableString *toStr, +static void AppendTextFormatForMessage(GPBMessage *message, NSMutableString *toStr, NSString *lineIndent) { GPBDescriptor *descriptor = [message descriptor]; NSArray *fieldsArray = descriptor->fields_; NSUInteger fieldCount = fieldsArray.count; const GPBExtensionRange *extensionRanges = descriptor.extensionRanges; NSUInteger extensionRangesCount = descriptor.extensionRangesCount; - NSArray *activeExtensions = [[message extensionsCurrentlySet] - sortedArrayUsingSelector:@selector(compareByFieldNumber:)]; + NSArray *activeExtensions = + [[message extensionsCurrentlySet] sortedArrayUsingSelector:@selector(compareByFieldNumber:)]; for (NSUInteger i = 0, j = 0; i < fieldCount || j < extensionRangesCount;) { if (i == fieldCount) { - AppendTextFormatForMessageExtensionRange( - message, activeExtensions, extensionRanges[j++], toStr, lineIndent); + AppendTextFormatForMessageExtensionRange(message, activeExtensions, extensionRanges[j++], + toStr, lineIndent); } else if (j == extensionRangesCount || GPBFieldNumber(fieldsArray[i]) < extensionRanges[j].start) { - AppendTextFormatForMessageField(message, fieldsArray[i++], toStr, - lineIndent); + AppendTextFormatForMessageField(message, fieldsArray[i++], toStr, lineIndent); } else { - AppendTextFormatForMessageExtensionRange( - message, activeExtensions, extensionRanges[j++], toStr, lineIndent); + AppendTextFormatForMessageExtensionRange(message, activeExtensions, extensionRanges[j++], + toStr, lineIndent); } } - NSString *unknownFieldsStr = - GPBTextFormatForUnknownFieldSet(message.unknownFields, lineIndent); + NSString *unknownFieldsStr = GPBTextFormatForUnknownFieldSet(message.unknownFields, lineIndent); if ([unknownFieldsStr length] > 0) { [toStr appendFormat:@"%@# --- Unknown fields ---\n", lineIndent]; [toStr appendString:unknownFieldsStr]; @@ -2024,8 +1989,7 @@ NSString *GPBTextFormatForMessage(GPBMessage *message, NSString *lineIndent) { return buildString; } -NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, - NSString *lineIndent) { +NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, NSString *lineIndent) { if (unknownSet == nil) return @""; if (lineIndent == nil) lineIndent = @""; @@ -2033,13 +1997,11 @@ NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, for (GPBUnknownField *field in [unknownSet sortedFields]) { int32_t fieldNumber = [field number]; -#define PRINT_LOOP(PROPNAME, CTYPE, FORMAT) \ - [field.PROPNAME \ - enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \ - _Pragma("unused(idx, stop)"); \ - [result \ - appendFormat:@"%@%d: " FORMAT "\n", lineIndent, fieldNumber, value]; \ - }]; +#define PRINT_LOOP(PROPNAME, CTYPE, FORMAT) \ + [field.PROPNAME enumerateValuesWithBlock:^(CTYPE value, NSUInteger idx, BOOL * stop) { \ + _Pragma("unused(idx, stop)"); \ + [result appendFormat:@"%@%d: " FORMAT "\n", lineIndent, fieldNumber, value]; \ + }]; PRINT_LOOP(varintList, uint64_t, "%llu"); PRINT_LOOP(fixed32List, uint32_t, "0x%X"); @@ -2058,8 +2020,7 @@ NSString *GPBTextFormatForUnknownFieldSet(GPBUnknownFieldSet *unknownSet, for (GPBUnknownFieldSet *subUnknownSet in field.groupList) { [result appendFormat:@"%@%d: {\n", lineIndent, fieldNumber]; NSString *subIndent = [lineIndent stringByAppendingString:@" "]; - NSString *subUnknownSetStr = - GPBTextFormatForUnknownFieldSet(subUnknownSet, subIndent); + NSString *subUnknownSetStr = GPBTextFormatForUnknownFieldSet(subUnknownSet, subIndent); [result appendString:subUnknownSetStr]; [result appendFormat:@"%@}\n", lineIndent]; } @@ -2102,8 +2063,7 @@ static int32_t ReadRawVarint32FromData(const uint8_t **data) { return result; } } - [NSException raise:NSParseErrorException - format:@"Unable to read varint32"]; + [NSException raise:NSParseErrorException format:@"Unable to read varint32"]; } } } @@ -2111,8 +2071,7 @@ static int32_t ReadRawVarint32FromData(const uint8_t **data) { return result; } -NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, - NSString *inputStr) { +NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, NSString *inputStr) { // decodData form: // varint32: num entries // for each entry: @@ -2170,15 +2129,14 @@ NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, return result; } - NSMutableString *result = - [NSMutableString stringWithCapacity:[inputStr length]]; + NSMutableString *result = [NSMutableString stringWithCapacity:[inputStr length]]; - const uint8_t kAddUnderscore = 0b10000000; - const uint8_t kOpMask = 0b01100000; + const uint8_t kAddUnderscore = 0b10000000; + const uint8_t kOpMask = 0b01100000; // const uint8_t kOpAsIs = 0b00000000; - const uint8_t kOpFirstUpper = 0b01000000; - const uint8_t kOpFirstLower = 0b00100000; - const uint8_t kOpAllUpper = 0b01100000; + const uint8_t kOpFirstUpper = 0b01000000; + const uint8_t kOpFirstLower = 0b00100000; + const uint8_t kOpAllUpper = 0b01100000; const uint8_t kSegmentLenMask = 0b00011111; NSInteger i = 0; @@ -2221,26 +2179,23 @@ NSString *GPBDecodeTextFormatName(const uint8_t *decodeData, int32_t key, #pragma mark Legacy methods old generated code calls // Shim from the older generated code into the runtime. -void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, - GPBFieldDescriptor *field, - int32_t value, +void GPBSetInt32IvarWithFieldInternal(GPBMessage *self, GPBFieldDescriptor *field, int32_t value, GPBFileSyntax syntax) { #pragma unused(syntax) GPBSetMessageInt32Field(self, field, value); } -void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, - int32_t oneofHasIndex, uint32_t fieldNumberNotToClear) { +void GPBMaybeClearOneof(GPBMessage *self, GPBOneofDescriptor *oneof, int32_t oneofHasIndex, + uint32_t fieldNumberNotToClear) { #pragma unused(fieldNumberNotToClear) - #if defined(DEBUG) && DEBUG - NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof, - @"OneofDescriptor %@ doesn't appear to be for %@ messages.", - oneof.name, [self class]); - GPBFieldDescriptor *firstField __unused = oneof->fields_[0]; - NSCAssert(firstField->description_->hasIndex == oneofHasIndex, - @"Internal error, oneofHasIndex (%d) doesn't match (%d).", - firstField->description_->hasIndex, oneofHasIndex); - #endif +#if defined(DEBUG) && DEBUG + NSCAssert([[self descriptor] oneofWithName:oneof.name] == oneof, + @"OneofDescriptor %@ doesn't appear to be for %@ messages.", oneof.name, [self class]); + GPBFieldDescriptor *firstField __unused = oneof->fields_[0]; + NSCAssert(firstField->description_->hasIndex == oneofHasIndex, + @"Internal error, oneofHasIndex (%d) doesn't match (%d).", + firstField->description_->hasIndex, oneofHasIndex); +#endif GPBMaybeClearOneofPrivate(self, oneof, oneofHasIndex, 0); } diff --git a/objectivec/GPBWellKnownTypes.m b/objectivec/GPBWellKnownTypes.m index 2808afeb23..90e82d3cc9 100644 --- a/objectivec/GPBWellKnownTypes.m +++ b/objectivec/GPBWellKnownTypes.m @@ -36,18 +36,15 @@ #import "GPBUtilities_PackagePrivate.h" -NSString *const GPBWellKnownTypesErrorDomain = - GPBNSStringifySymbol(GPBWellKnownTypesErrorDomain); +NSString *const GPBWellKnownTypesErrorDomain = GPBNSStringifySymbol(GPBWellKnownTypesErrorDomain); static NSString *kTypePrefixGoogleApisCom = @"type.googleapis.com/"; -static NSTimeInterval TimeIntervalFromSecondsAndNanos(int64_t seconds, - int32_t nanos) { +static NSTimeInterval TimeIntervalFromSecondsAndNanos(int64_t seconds, int32_t nanos) { return seconds + (NSTimeInterval)nanos / 1e9; } -static int32_t SecondsAndNanosFromTimeInterval(NSTimeInterval time, - int64_t *outSeconds, +static int32_t SecondsAndNanosFromTimeInterval(NSTimeInterval time, int64_t *outSeconds, BOOL nanosMustBePositive) { NSTimeInterval seconds; NSTimeInterval nanos = modf(time, &seconds); @@ -79,8 +76,7 @@ static NSString *BuildTypeURL(NSString *typeURLPrefix, NSString *fullName) { static NSString *ParseTypeFromURL(NSString *typeURLString) { NSRange range = [typeURLString rangeOfString:@"/" options:NSBackwardsSearch]; - if ((range.location == NSNotFound) || - (NSMaxRange(range) == typeURLString.length)) { + if ((range.location == NSNotFound) || (NSMaxRange(range) == typeURLString.length)) { return nil; } NSString *result = [typeURLString substringFromIndex:range.location + 1]; @@ -98,8 +94,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { - (instancetype)initWithTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { if ((self = [super init])) { int64_t seconds; - int32_t nanos = SecondsAndNanosFromTimeInterval( - timeIntervalSince1970, &seconds, YES); + int32_t nanos = SecondsAndNanosFromTimeInterval(timeIntervalSince1970, &seconds, YES); self.seconds = seconds; self.nanos = nanos; } @@ -120,8 +115,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { - (void)setTimeIntervalSince1970:(NSTimeInterval)timeIntervalSince1970 { int64_t seconds; - int32_t nanos = - SecondsAndNanosFromTimeInterval(timeIntervalSince1970, &seconds, YES); + int32_t nanos = SecondsAndNanosFromTimeInterval(timeIntervalSince1970, &seconds, YES); self.seconds = seconds; self.nanos = nanos; } @@ -135,8 +129,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { - (instancetype)initWithTimeInterval:(NSTimeInterval)timeInterval { if ((self = [super init])) { int64_t seconds; - int32_t nanos = SecondsAndNanosFromTimeInterval( - timeInterval, &seconds, NO); + int32_t nanos = SecondsAndNanosFromTimeInterval(timeInterval, &seconds, NO); self.seconds = seconds; self.nanos = nanos; } @@ -153,8 +146,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { - (void)setTimeInterval:(NSTimeInterval)timeInterval { int64_t seconds; - int32_t nanos = - SecondsAndNanosFromTimeInterval(timeInterval, &seconds, NO); + int32_t nanos = SecondsAndNanosFromTimeInterval(timeInterval, &seconds, NO); self.seconds = seconds; self.nanos = nanos; } @@ -173,26 +165,19 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { @implementation GPBAny (GBPWellKnownTypes) -+ (instancetype)anyWithMessage:(GPBMessage *)message - error:(NSError **)errorPtr { - return [self anyWithMessage:message - typeURLPrefix:kTypePrefixGoogleApisCom - error:errorPtr]; ++ (instancetype)anyWithMessage:(GPBMessage *)message error:(NSError **)errorPtr { + return [self anyWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr]; } + (instancetype)anyWithMessage:(GPBMessage *)message typeURLPrefix:(NSString *)typeURLPrefix error:(NSError **)errorPtr { - return [[[self alloc] initWithMessage:message - typeURLPrefix:typeURLPrefix + return [[[self alloc] initWithMessage:message typeURLPrefix:typeURLPrefix error:errorPtr] autorelease]; } -- (instancetype)initWithMessage:(GPBMessage *)message - error:(NSError **)errorPtr { - return [self initWithMessage:message - typeURLPrefix:kTypePrefixGoogleApisCom - error:errorPtr]; +- (instancetype)initWithMessage:(GPBMessage *)message error:(NSError **)errorPtr { + return [self initWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr]; } - (instancetype)initWithMessage:(GPBMessage *)message @@ -200,9 +185,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { error:(NSError **)errorPtr { self = [self init]; if (self) { - if (![self packWithMessage:message - typeURLPrefix:typeURLPrefix - error:errorPtr]) { + if (![self packWithMessage:message typeURLPrefix:typeURLPrefix error:errorPtr]) { [self release]; self = nil; } @@ -210,11 +193,8 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { return self; } -- (BOOL)packWithMessage:(GPBMessage *)message - error:(NSError **)errorPtr { - return [self packWithMessage:message - typeURLPrefix:kTypePrefixGoogleApisCom - error:errorPtr]; +- (BOOL)packWithMessage:(GPBMessage *)message error:(NSError **)errorPtr { + return [self packWithMessage:message typeURLPrefix:kTypePrefixGoogleApisCom error:errorPtr]; } - (BOOL)packWithMessage:(GPBMessage *)message @@ -223,10 +203,9 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { NSString *fullName = [message descriptor].fullName; if (fullName.length == 0) { if (errorPtr) { - *errorPtr = - [NSError errorWithDomain:GPBWellKnownTypesErrorDomain - code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL - userInfo:nil]; + *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain + code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL + userInfo:nil]; } return NO; } @@ -238,15 +217,13 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { return YES; } -- (GPBMessage *)unpackMessageClass:(Class)messageClass - error:(NSError **)errorPtr { +- (GPBMessage *)unpackMessageClass:(Class)messageClass error:(NSError **)errorPtr { NSString *fullName = [messageClass descriptor].fullName; if (fullName.length == 0) { if (errorPtr) { - *errorPtr = - [NSError errorWithDomain:GPBWellKnownTypesErrorDomain - code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL - userInfo:nil]; + *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain + code:GPBWellKnownTypesErrorCodeFailedToComputeTypeURL + userInfo:nil]; } return nil; } @@ -254,10 +231,9 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { NSString *expectedFullName = ParseTypeFromURL(self.typeURL); if ((expectedFullName == nil) || ![expectedFullName isEqual:fullName]) { if (errorPtr) { - *errorPtr = - [NSError errorWithDomain:GPBWellKnownTypesErrorDomain - code:GPBWellKnownTypesErrorCodeTypeURLMismatch - userInfo:nil]; + *errorPtr = [NSError errorWithDomain:GPBWellKnownTypesErrorDomain + code:GPBWellKnownTypesErrorCodeTypeURLMismatch + userInfo:nil]; } return nil; } @@ -265,8 +241,7 @@ static NSString *ParseTypeFromURL(NSString *typeURLString) { // Any is proto3, which means no extensions, so this assumes anything put // within an any also won't need extensions. A second helper could be added // if needed. - return [messageClass parseFromData:self.value - error:errorPtr]; + return [messageClass parseFromData:self.value error:errorPtr]; } @end From ecd63bb219825dea6a03496527e8ea8565cf963a Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Mon, 19 Sep 2022 17:22:33 -0400 Subject: [PATCH 62/64] Format the test sources. --- objectivec/Tests/GPBArrayTests.m | 216 ++--- objectivec/Tests/GPBCodedInputStreamTests.m | 104 +- objectivec/Tests/GPBCodedOutputStreamTests.m | 173 ++-- objectivec/Tests/GPBCompileTest01.m | 2 - objectivec/Tests/GPBCompileTest02.m | 2 - objectivec/Tests/GPBCompileTest03.m | 2 - objectivec/Tests/GPBCompileTest04.m | 2 - objectivec/Tests/GPBCompileTest05.m | 2 - objectivec/Tests/GPBCompileTest06.m | 2 - objectivec/Tests/GPBCompileTest07.m | 2 - objectivec/Tests/GPBCompileTest08.m | 2 - objectivec/Tests/GPBCompileTest09.m | 2 - objectivec/Tests/GPBCompileTest10.m | 2 - objectivec/Tests/GPBCompileTest11.m | 2 - objectivec/Tests/GPBCompileTest12.m | 2 - objectivec/Tests/GPBCompileTest13.m | 2 - objectivec/Tests/GPBCompileTest14.m | 2 - objectivec/Tests/GPBCompileTest15.m | 2 - objectivec/Tests/GPBCompileTest16.m | 2 - objectivec/Tests/GPBCompileTest17.m | 2 - objectivec/Tests/GPBCompileTest18.m | 2 - objectivec/Tests/GPBCompileTest19.m | 2 - objectivec/Tests/GPBCompileTest20.m | 2 - objectivec/Tests/GPBCompileTest21.m | 2 - objectivec/Tests/GPBCompileTest22.m | 2 - objectivec/Tests/GPBCompileTest23.m | 2 - objectivec/Tests/GPBConcurrencyTests.m | 35 +- objectivec/Tests/GPBDescriptorTests.m | 66 +- objectivec/Tests/GPBDictionaryTests.m | 36 +- objectivec/Tests/GPBExtensionRegistryTest.m | 39 +- objectivec/Tests/GPBMessageTests+ClassNames.m | 60 +- objectivec/Tests/GPBMessageTests+Merge.m | 38 +- objectivec/Tests/GPBMessageTests+Runtime.m | 379 +++----- .../Tests/GPBMessageTests+Serialization.m | 141 ++- objectivec/Tests/GPBMessageTests.m | 491 ++++------ objectivec/Tests/GPBObjectiveCPlusPlusTest.mm | 13 +- objectivec/Tests/GPBPerfTests.m | 31 +- objectivec/Tests/GPBTestUtilities.h | 37 +- objectivec/Tests/GPBTestUtilities.m | 908 +++++++++--------- objectivec/Tests/GPBUnknownFieldSetTest.m | 59 +- objectivec/Tests/GPBUtilitiesTests.m | 62 +- objectivec/Tests/GPBWellKnownTypesTest.m | 91 +- objectivec/Tests/GPBWireFormatTests.m | 57 +- objectivec/Tests/UnitTests-Bridging-Header.h | 3 +- 44 files changed, 1256 insertions(+), 1829 deletions(-) diff --git a/objectivec/Tests/GPBArrayTests.m b/objectivec/Tests/GPBArrayTests.m index 6bb5c1da27..713b8f6cc2 100644 --- a/objectivec/Tests/GPBArrayTests.m +++ b/objectivec/Tests/GPBArrayTests.m @@ -40,8 +40,7 @@ @interface GPBEnumArray (TestingTweak) + (instancetype)arrayWithValue:(int32_t)value; + (instancetype)arrayWithCapacity:(NSUInteger)count; -- (instancetype)initWithValues:(const int32_t [])values - count:(NSUInteger)count; +- (instancetype)initWithValues:(const int32_t[])values count:(NSUInteger)count; @end static BOOL TestingEnum_IsValidValue(int32_t value) { @@ -77,11 +76,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { return [[[self alloc] initWithValidationFunction:TestingEnum_IsValidValue capacity:count] autorelease]; } -- (instancetype)initWithValues:(const int32_t [])values - count:(NSUInteger)count { - return [self initWithValidationFunction:TestingEnum_IsValidValue - rawValues:values - count:count]; +- (instancetype)initWithValues:(const int32_t[])values count:(NSUInteger)count { + return [self initWithValidationFunction:TestingEnum_IsValidValue rawValues:values count:count]; } @end @@ -3200,15 +3196,13 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { @implementation GPBEnumArrayCustomTests - (void)testRawBasics { - static const int32_t kValues[] = { 71, 272, 73, 374 }; - static const int32_t kValuesFiltered[] = { - 71, kGPBUnrecognizedEnumeratorValue, 73, kGPBUnrecognizedEnumeratorValue - }; + static const int32_t kValues[] = {71, 272, 73, 374}; + static const int32_t kValuesFiltered[] = {71, kGPBUnrecognizedEnumeratorValue, 73, + kGPBUnrecognizedEnumeratorValue}; XCTAssertEqual(GPBARRAYSIZE(kValues), GPBARRAYSIZE(kValuesFiltered)); - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue - rawValues:kValues - count:GPBARRAYSIZE(kValues)]; + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; XCTAssertNotNil(array); XCTAssertEqual(array.count, 4U); GPBEnumValidationFunc func = TestingEnum_IsValidValue; @@ -3237,19 +3231,19 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { idx2 = 0; [array enumerateRawValuesWithOptions:NSEnumerationReverse usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { - XCTAssertEqual(idx, (3 - idx2)); - XCTAssertEqual(value, kValues[idx]); - XCTAssertNotEqual(stop, NULL); - ++idx2; - }]; + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; idx2 = 0; [array enumerateValuesWithOptions:NSEnumerationReverse usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { - XCTAssertEqual(idx, (3 - idx2)); - XCTAssertEqual(value, kValuesFiltered[idx]); - XCTAssertNotEqual(stop, NULL); - ++idx2; - }]; + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValuesFiltered[idx]); + XCTAssertNotEqual(stop, NULL); + ++idx2; + }]; // Stopping the enumeration. idx2 = 0; [array enumerateRawValuesWithBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { @@ -3264,38 +3258,35 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { idx2 = 0; [array enumerateRawValuesWithOptions:NSEnumerationReverse usingBlock:^(int32_t value, NSUInteger idx, BOOL *stop) { - XCTAssertEqual(idx, (3 - idx2)); - XCTAssertEqual(value, kValues[idx]); - XCTAssertNotEqual(stop, NULL); - if (idx2 == 1) *stop = YES; - XCTAssertNotEqual(idx, 1U); - XCTAssertNotEqual(idx, 0U); - ++idx2; - }]; + XCTAssertEqual(idx, (3 - idx2)); + XCTAssertEqual(value, kValues[idx]); + XCTAssertNotEqual(stop, NULL); + if (idx2 == 1) *stop = YES; + XCTAssertNotEqual(idx, 1U); + XCTAssertNotEqual(idx, 0U); + ++idx2; + }]; [array release]; } - (void)testEquality { - const int32_t kValues1[] = { 71, 72, 173 }; // With unknown value - const int32_t kValues2[] = { 71, 74, 173 }; // With unknown value - const int32_t kValues3[] = { 71, 72, 173, 74 }; // With unknown value - GPBEnumArray *array1 = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue - rawValues:kValues1 - count:GPBARRAYSIZE(kValues1)]; + const int32_t kValues1[] = {71, 72, 173}; // With unknown value + const int32_t kValues2[] = {71, 74, 173}; // With unknown value + const int32_t kValues3[] = {71, 72, 173, 74}; // With unknown value + GPBEnumArray *array1 = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues1 + count:GPBARRAYSIZE(kValues1)]; XCTAssertNotNil(array1); GPBEnumArray *array1prime = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue2 rawValues:kValues1 count:GPBARRAYSIZE(kValues1)]; XCTAssertNotNil(array1prime); - GPBEnumArray *array2 = - [[GPBEnumArray alloc] initWithValues:kValues2 - count:GPBARRAYSIZE(kValues2)]; + GPBEnumArray *array2 = [[GPBEnumArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; XCTAssertNotNil(array2); - GPBEnumArray *array3 = - [[GPBEnumArray alloc] initWithValues:kValues3 - count:GPBARRAYSIZE(kValues3)]; + GPBEnumArray *array3 = [[GPBEnumArray alloc] initWithValues:kValues3 + count:GPBARRAYSIZE(kValues3)]; XCTAssertNotNil(array3); // 1/1Prime should be different objects, but equal. @@ -3318,13 +3309,11 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { } - (void)testCopy { - const int32_t kValues[] = { 71, 72 }; - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValues:kValues - count:GPBARRAYSIZE(kValues)]; + const int32_t kValues[] = {71, 72}; + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValues:kValues count:GPBARRAYSIZE(kValues)]; XCTAssertNotNil(array); - [array addRawValue:1000]; // Unknown + [array addRawValue:1000]; // Unknown XCTAssertEqual(array.count, 3U); XCTAssertEqual([array rawValueAtIndex:0], 71); XCTAssertEqual([array rawValueAtIndex:1], 72); @@ -3349,11 +3338,10 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { } - (void)testArrayFromArray { - const int32_t kValues[] = { 71, 172, 173, 74 }; // Unknowns - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue - rawValues:kValues - count:GPBARRAYSIZE(kValues)]; + const int32_t kValues[] = {71, 172, 173, 74}; // Unknowns + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; XCTAssertNotNil(array); GPBEnumArray *array2 = [GPBEnumArray arrayWithValueArray:array]; @@ -3367,38 +3355,34 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { } - (void)testUnknownAdds { - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue]; + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue]; XCTAssertNotNil(array); - XCTAssertThrowsSpecificNamed([array addValue:172], - NSException, NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed([array addValue:172], NSException, NSInvalidArgumentException); XCTAssertEqual(array.count, 0U); - const int32_t kValues1[] = { 172, 173 }; // Unknown - XCTAssertThrowsSpecificNamed([array addValues:kValues1 count:GPBARRAYSIZE(kValues1)], - NSException, NSInvalidArgumentException); + const int32_t kValues1[] = {172, 173}; // Unknown + XCTAssertThrowsSpecificNamed([array addValues:kValues1 count:GPBARRAYSIZE(kValues1)], NSException, + NSInvalidArgumentException); XCTAssertEqual(array.count, 0U); [array release]; } - (void)testRawAdds { - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue]; + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue]; XCTAssertNotNil(array); XCTAssertEqual(array.count, 0U); [array addRawValue:71]; // Valid XCTAssertEqual(array.count, 1U); - const int32_t kValues1[] = { 172, 173 }; // Unknown + const int32_t kValues1[] = {172, 173}; // Unknown [array addRawValues:kValues1 count:GPBARRAYSIZE(kValues1)]; XCTAssertEqual(array.count, 3U); - const int32_t kValues2[] = { 74, 71 }; - GPBEnumArray *array2 = - [[GPBEnumArray alloc] initWithValues:kValues2 - count:GPBARRAYSIZE(kValues2)]; + const int32_t kValues2[] = {74, 71}; + GPBEnumArray *array2 = [[GPBEnumArray alloc] initWithValues:kValues2 + count:GPBARRAYSIZE(kValues2)]; XCTAssertNotNil(array2); [array addRawValuesFromArray:array2]; XCTAssertEqual(array.count, 5U); @@ -3414,37 +3398,35 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { } - (void)testUnknownInserts { - const int32_t kValues[] = { 71, 72, 73 }; - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue - rawValues:kValues - count:GPBARRAYSIZE(kValues)]; + const int32_t kValues[] = {71, 72, 73}; + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; XCTAssertNotNil(array); XCTAssertEqual(array.count, 3U); // First - XCTAssertThrowsSpecificNamed([array insertValue:174 atIndex:0], - NSException, NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed([array insertValue:174 atIndex:0], NSException, + NSInvalidArgumentException); XCTAssertEqual(array.count, 3U); // Middle - XCTAssertThrowsSpecificNamed([array insertValue:274 atIndex:1], - NSException, NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed([array insertValue:274 atIndex:1], NSException, + NSInvalidArgumentException); XCTAssertEqual(array.count, 3U); // End - XCTAssertThrowsSpecificNamed([array insertValue:374 atIndex:3], - NSException, NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed([array insertValue:374 atIndex:3], NSException, + NSInvalidArgumentException); XCTAssertEqual(array.count, 3U); [array release]; } - (void)testRawInsert { - const int32_t kValues[] = { 71, 72, 73 }; - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue - rawValues:kValues - count:GPBARRAYSIZE(kValues)]; + const int32_t kValues[] = {71, 72, 73}; + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; XCTAssertNotNil(array); XCTAssertEqual(array.count, 3U); @@ -3461,8 +3443,7 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { XCTAssertEqual(array.count, 6U); // Too far. - XCTAssertThrowsSpecificNamed([array insertRawValue:74 atIndex:7], - NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array insertRawValue:74 atIndex:7], NSException, NSRangeException); XCTAssertEqual([array rawValueAtIndex:0], 174); XCTAssertEqual([array valueAtIndex:0], kGPBUnrecognizedEnumeratorValue); @@ -3477,17 +3458,16 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { } - (void)testUnknownInplaceMutation { - const int32_t kValues[] = { 71, 72, 73, 74 }; - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue - rawValues:kValues - count:GPBARRAYSIZE(kValues)]; + const int32_t kValues[] = {71, 72, 73, 74}; + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; XCTAssertNotNil(array); - XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:1 withValue:172], - NSException, NSInvalidArgumentException); - XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:3 withValue:274], - NSException, NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:1 withValue:172], NSException, + NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:3 withValue:274], NSException, + NSInvalidArgumentException); XCTAssertEqual(array.count, 4U); XCTAssertEqual([array valueAtIndex:0], 71); XCTAssertEqual([array valueAtIndex:1], 72); @@ -3496,13 +3476,11 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { [array release]; } - - (void)testRawInplaceMutation { - const int32_t kValues[] = { 71, 72, 73, 74 }; - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue - rawValues:kValues - count:GPBARRAYSIZE(kValues)]; + const int32_t kValues[] = {71, 72, 73, 74}; + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValidationFunction:TestingEnum_IsValidValue + rawValues:kValues + count:GPBARRAYSIZE(kValues)]; XCTAssertNotNil(array); [array replaceValueAtIndex:1 withRawValue:172]; // Unknown @@ -3515,16 +3493,14 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { XCTAssertEqual([array rawValueAtIndex:3], 274); XCTAssertEqual([array valueAtIndex:3], kGPBUnrecognizedEnumeratorValue); - XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withRawValue:74], - NSException, NSRangeException); + XCTAssertThrowsSpecificNamed([array replaceValueAtIndex:4 withRawValue:74], NSException, + NSRangeException); [array release]; } - (void)testRawInternalResizing { - const int32_t kValues[] = { 71, 172, 173, 74 }; // Unknown - GPBEnumArray *array = - [[GPBEnumArray alloc] initWithValues:kValues - count:GPBARRAYSIZE(kValues)]; + const int32_t kValues[] = {71, 172, 173, 74}; // Unknown + GPBEnumArray *array = [[GPBEnumArray alloc] initWithValues:kValues count:GPBARRAYSIZE(kValues)]; XCTAssertNotNil(array); // Add/remove to trigger the intneral buffer to grow/shrink. @@ -3600,13 +3576,13 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init]; NSArray *cpy = [array copy]; - XCTAssertTrue(cpy != array); // Ptr compare + XCTAssertTrue(cpy != array); // Ptr compare XCTAssertTrue([cpy isKindOfClass:[NSArray class]]); XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]); XCTAssertEqual(cpy.count, (NSUInteger)0); NSArray *cpy2 = [array copy]; - XCTAssertTrue(cpy2 != array); // Ptr compare + XCTAssertTrue(cpy2 != array); // Ptr compare // Can't compare cpy and cpy2 because NSArray has a singleton empty // array it uses, so the ptrs are the same. XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]); @@ -3622,14 +3598,14 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { GPBAutocreatedArray *array = [[GPBAutocreatedArray alloc] init]; NSMutableArray *cpy = [array mutableCopy]; - XCTAssertTrue(cpy != array); // Ptr compare + XCTAssertTrue(cpy != array); // Ptr compare XCTAssertTrue([cpy isKindOfClass:[NSMutableArray class]]); XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]); XCTAssertEqual(cpy.count, (NSUInteger)0); NSMutableArray *cpy2 = [array mutableCopy]; - XCTAssertTrue(cpy2 != array); // Ptr compare - XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue(cpy2 != array); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare XCTAssertTrue([cpy2 isKindOfClass:[NSMutableArray class]]); XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]); XCTAssertEqual(cpy2.count, (NSUInteger)0); @@ -3645,7 +3621,7 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { [array addObject:@"bar"]; NSArray *cpy = [array copy]; - XCTAssertTrue(cpy != array); // Ptr compare + XCTAssertTrue(cpy != array); // Ptr compare XCTAssertTrue([cpy isKindOfClass:[NSArray class]]); XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]); XCTAssertEqual(cpy.count, (NSUInteger)2); @@ -3653,8 +3629,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { XCTAssertEqualObjects(cpy[1], @"bar"); NSArray *cpy2 = [array copy]; - XCTAssertTrue(cpy2 != array); // Ptr compare - XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue(cpy2 != array); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]); XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]); XCTAssertEqual(cpy2.count, (NSUInteger)2); @@ -3672,7 +3648,7 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { [array addObject:@"bar"]; NSMutableArray *cpy = [array mutableCopy]; - XCTAssertTrue(cpy != array); // Ptr compare + XCTAssertTrue(cpy != array); // Ptr compare XCTAssertTrue([cpy isKindOfClass:[NSArray class]]); XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedArray class]]); XCTAssertEqual(cpy.count, (NSUInteger)2); @@ -3680,8 +3656,8 @@ static BOOL TestingEnum_IsValidValue2(int32_t value) { XCTAssertEqualObjects(cpy[1], @"bar"); NSMutableArray *cpy2 = [array mutableCopy]; - XCTAssertTrue(cpy2 != array); // Ptr compare - XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue(cpy2 != array); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare XCTAssertTrue([cpy2 isKindOfClass:[NSArray class]]); XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedArray class]]); XCTAssertEqual(cpy2.count, (NSUInteger)2); diff --git a/objectivec/Tests/GPBCodedInputStreamTests.m b/objectivec/Tests/GPBCodedInputStreamTests.m index 3dd9d3f934..05040625f6 100644 --- a/objectivec/Tests/GPBCodedInputStreamTests.m +++ b/objectivec/Tests/GPBCodedInputStreamTests.m @@ -82,8 +82,10 @@ [self assertReadZigZag64:bytes(0xFE, 0xFF, 0xFF, 0xFF, 0x0F) value:(int32_t)0x7FFFFFFF]; [self assertReadZigZag64:bytes(0xFF, 0xFF, 0xFF, 0xFF, 0x0F) value:(int32_t)0x80000000]; - [self assertReadZigZag64:bytes(0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01) value:0x7FFFFFFFFFFFFFFFL]; - [self assertReadZigZag64:bytes(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01) value:0x8000000000000000L]; + [self assertReadZigZag64:bytes(0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01) + value:0x7FFFFFFFFFFFFFFFL]; + [self assertReadZigZag64:bytes(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01) + value:0x8000000000000000L]; } - (void)assertReadVarint:(NSData*)data value:(int64_t)value { @@ -201,30 +203,25 @@ value:(0x22 << 0) | (0x22 << 7) | (0x22 << 14) | (0x74 << 21)]; // 2961488830 [self assertReadVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b) - value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | - (0x04 << 21) | (0x0bLL << 28)]; + value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x0bLL << 28)]; // 64-bit // 7256456126 [self assertReadVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b) - value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | - (0x04 << 21) | (0x1bLL << 28)]; + value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x1bLL << 28)]; // 41256202580718336 [self assertReadVarint:bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49) - value:(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | - (0x1c << 21) | (0x43LL << 28) | (0x49LL << 35) | - (0x24LL << 42) | (0x49LL << 49)]; + value:(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | (0x43LL << 28) | + (0x49LL << 35) | (0x24LL << 42) | (0x49LL << 49)]; // 11964378330978735131 - [self - assertReadVarint:bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, - 0xa6, 0x01) - value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (0x3bLL << 28) | (0x56LL << 35) | (0x00LL << 42) | - (0x05LL << 49) | (0x26LL << 56) | (0x01ULL << 63)]; + [self assertReadVarint:bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01) + value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | (0x3bLL << 28) | + (0x56LL << 35) | (0x00LL << 42) | (0x05LL << 49) | (0x26LL << 56) | + (0x01ULL << 63)]; // Failures - [self assertReadVarintFailure:bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x80, 0x80, 0x80, 0x00)]; + [self assertReadVarintFailure:bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x00)]; [self assertReadVarintFailure:bytes(0x80)]; } @@ -268,16 +265,12 @@ } - (void)testReadLittleEndian { - [self assertReadLittleEndian32:bytes(0x78, 0x56, 0x34, 0x12) - value:0x12345678]; - [self assertReadLittleEndian32:bytes(0xf0, 0xde, 0xbc, 0x9a) - value:0x9abcdef0]; + [self assertReadLittleEndian32:bytes(0x78, 0x56, 0x34, 0x12) value:0x12345678]; + [self assertReadLittleEndian32:bytes(0xf0, 0xde, 0xbc, 0x9a) value:0x9abcdef0]; - [self assertReadLittleEndian64:bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, - 0x12) + [self assertReadLittleEndian64:bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12) value:0x123456789abcdef0LL]; - [self assertReadLittleEndian64:bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, - 0x9a) + [self assertReadLittleEndian64:bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a) value:0x9abcdef012345678LL]; } @@ -287,8 +280,7 @@ NSData* rawBytes = message.data; XCTAssertEqual(message.serializedSize, (size_t)rawBytes.length); - TestAllTypes* message2 = - [TestAllTypes parseFromData:rawBytes extensionRegistry:nil error:NULL]; + TestAllTypes* message2 = [TestAllTypes parseFromData:rawBytes extensionRegistry:nil error:NULL]; [self assertAllFieldsSet:message2 repeatedCount:kGPBDefaultRepeatCount]; } @@ -300,8 +292,7 @@ // skipField() to skip each field on the other. Expect the same tags. GPBCodedInputStream* input1 = [GPBCodedInputStream streamWithData:rawBytes]; GPBCodedInputStream* input2 = [GPBCodedInputStream streamWithData:rawBytes]; - GPBUnknownFieldSet* unknownFields = - [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* unknownFields = [[[GPBUnknownFieldSet alloc] init] autorelease]; while (YES) { int32_t tag = [input1 readTag]; @@ -329,10 +320,9 @@ // Serialize and parse it. Make sure to parse from an InputStream, not // directly from a ByteString, so that CodedInputStream uses buffered // reading. - NSData *messageData = message.data; + NSData* messageData = message.data; XCTAssertNotNil(messageData); - GPBCodedInputStream* stream = - [GPBCodedInputStream streamWithData:messageData]; + GPBCodedInputStream* stream = [GPBCodedInputStream streamWithData:messageData]; TestAllTypes* message2 = [TestAllTypes parseFromCodedInputStream:stream extensionRegistry:nil error:NULL]; @@ -350,8 +340,7 @@ - (void)testReadMaliciouslyLargeBlob { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput]; int32_t tag = GPBWireFormatMakeTag(1, GPBWireFormatLengthDelimited); [output writeRawVarint32:tag]; @@ -360,8 +349,7 @@ [output writeRawData:[NSData dataWithBytes:bytes length:32]]; [output flush]; - NSData* data = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* data = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:[NSMutableData dataWithData:data]]; XCTAssertEqual(tag, [input readTag]); @@ -370,23 +358,21 @@ } - (void)testReadEmptyString { - NSData *data = bytes(0x00); + NSData* data = bytes(0x00); GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data]; XCTAssertEqualObjects(@"", [input readString]); } - (void)testInvalidGroupEndTagThrows { - NSData *data = bytes(0x0B, 0x1A, 0x02, 0x4B, 0x50, 0x14); + NSData* data = bytes(0x0B, 0x1A, 0x02, 0x4B, 0x50, 0x14); GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data]; - XCTAssertThrowsSpecificNamed([input skipMessage], - NSException, - GPBCodedInputStreamException, + XCTAssertThrowsSpecificNamed([input skipMessage], NSException, GPBCodedInputStreamException, @"should throw a GPBCodedInputStreamException exception "); } - (void)testBytesWithNegativeSize { - NSData *data = bytes(0xFF, 0xFF, 0xFF, 0xFF, 0x0F); - GPBCodedInputStream *input = [GPBCodedInputStream streamWithData:data]; + NSData* data = bytes(0xFF, 0xFF, 0xFF, 0xFF, 0x0F); + GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data]; XCTAssertNil([input readBytes]); } @@ -396,11 +382,10 @@ // again, it will help validate that class' handing of bad utf8. - (void)testReadMalformedString { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput]; - int32_t tag = GPBWireFormatMakeTag(TestAllTypes_FieldNumber_DefaultString, - GPBWireFormatLengthDelimited); + int32_t tag = + GPBWireFormatMakeTag(TestAllTypes_FieldNumber_DefaultString, GPBWireFormatLengthDelimited); [output writeRawVarint32:tag]; [output writeRawVarint32:5]; // Create an invalid utf-8 byte array. @@ -408,10 +393,9 @@ [output writeRawData:[NSData dataWithBytes:bytes length:sizeof(bytes)]]; [output flush]; - NSData *data = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* data = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data]; - NSError *error = nil; + NSError* error = nil; TestAllTypes* message = [TestAllTypes parseFromCodedInputStream:input extensionRegistry:nil error:&error]; @@ -425,27 +409,25 @@ // correctly. (Again, this is inpart in case a custom string class is ever // used again.) const char* strs[] = { - "\xEF\xBB\xBF String with BOM", - "String with \xEF\xBB\xBF in middle", - "String with end bom \xEF\xBB\xBF", - "\xEF\xBB\xBF\xe2\x99\xa1", // BOM White Heart - "\xEF\xBB\xBF\xEF\xBB\xBF String with Two BOM", + "\xEF\xBB\xBF String with BOM", + "String with \xEF\xBB\xBF in middle", + "String with end bom \xEF\xBB\xBF", + "\xEF\xBB\xBF\xe2\x99\xa1", // BOM White Heart + "\xEF\xBB\xBF\xEF\xBB\xBF String with Two BOM", }; for (size_t i = 0; i < GPBARRAYSIZE(strs); ++i) { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput]; - int32_t tag = GPBWireFormatMakeTag(TestAllTypes_FieldNumber_DefaultString, - GPBWireFormatLengthDelimited); + int32_t tag = + GPBWireFormatMakeTag(TestAllTypes_FieldNumber_DefaultString, GPBWireFormatLengthDelimited); [output writeRawVarint32:tag]; size_t length = strlen(strs[i]); [output writeRawVarint32:(int32_t)length]; [output writeRawData:[NSData dataWithBytes:strs[i] length:length]]; [output flush]; - NSData* data = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* data = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; GPBCodedInputStream* input = [GPBCodedInputStream streamWithData:data]; TestAllTypes* message = [TestAllTypes parseFromCodedInputStream:input extensionRegistry:nil diff --git a/objectivec/Tests/GPBCodedOutputStreamTests.m b/objectivec/Tests/GPBCodedOutputStreamTests.m index 11fefcee84..a619cae050 100644 --- a/objectivec/Tests/GPBCodedOutputStreamTests.m +++ b/objectivec/Tests/GPBCodedOutputStreamTests.m @@ -30,26 +30,23 @@ #import "GPBTestUtilities.h" -#import "GPBCodedOutputStream_PackagePrivate.h" #import "GPBCodedInputStream.h" +#import "GPBCodedOutputStream_PackagePrivate.h" #import "GPBUtilities_PackagePrivate.h" #import "objectivec/Tests/Unittest.pbobjc.h" @interface GPBCodedOutputStream (InternalMethods) // Declared in the .m file, expose for testing. -- (instancetype)initWithOutputStream:(NSOutputStream *)output - data:(NSMutableData *)data; +- (instancetype)initWithOutputStream:(NSOutputStream*)output data:(NSMutableData*)data; @end @interface GPBCodedOutputStream (Helper) -+ (instancetype)streamWithOutputStream:(NSOutputStream *)output - bufferSize:(size_t)bufferSize; ++ (instancetype)streamWithOutputStream:(NSOutputStream*)output bufferSize:(size_t)bufferSize; @end @implementation GPBCodedOutputStream (Helper) -+ (instancetype)streamWithOutputStream:(NSOutputStream *)output - bufferSize:(size_t)bufferSize { - NSMutableData *data = [NSMutableData dataWithLength:bufferSize]; ++ (instancetype)streamWithOutputStream:(NSOutputStream*)output bufferSize:(size_t)bufferSize { + NSMutableData* data = [NSMutableData dataWithLength:bufferSize]; return [[[self alloc] initWithOutputStream:output data:data] autorelease]; } @end @@ -81,20 +78,17 @@ - (void)assertWriteLittleEndian32:(NSData*)data value:(int32_t)value { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput]; [output writeRawLittleEndian32:(int32_t)value]; [output flush]; - NSData* actual = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; XCTAssertEqualObjects(data, actual); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { rawOutput = [NSOutputStream outputStreamToMemory]; - output = [GPBCodedOutputStream streamWithOutputStream:rawOutput - bufferSize:blockSize]; + output = [GPBCodedOutputStream streamWithOutputStream:rawOutput bufferSize:blockSize]; [output writeRawLittleEndian32:(int32_t)value]; [output flush]; @@ -105,20 +99,17 @@ - (void)assertWriteLittleEndian64:(NSData*)data value:(int64_t)value { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput]; [output writeRawLittleEndian64:value]; [output flush]; - NSData* actual = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; XCTAssertEqualObjects(data, actual); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { rawOutput = [NSOutputStream outputStreamToMemory]; - output = [GPBCodedOutputStream streamWithOutputStream:rawOutput - bufferSize:blockSize]; + output = [GPBCodedOutputStream streamWithOutputStream:rawOutput bufferSize:blockSize]; [output writeRawLittleEndian64:value]; [output flush]; @@ -131,29 +122,24 @@ // Only do 32-bit write if the value fits in 32 bits. if (GPBLogicalRightShift64(value, 32) == 0) { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput]; [output writeRawVarint32:(int32_t)value]; [output flush]; - NSData* actual = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; XCTAssertEqualObjects(data, actual); // Also try computing size. - XCTAssertEqual(GPBComputeRawVarint32Size((int32_t)value), - (size_t)data.length); + XCTAssertEqual(GPBComputeRawVarint32Size((int32_t)value), (size_t)data.length); } { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput]; [output writeRawVarint64:value]; [output flush]; - NSData* actual = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; XCTAssertEqualObjects(data, actual); // Also try computing size. @@ -165,52 +151,45 @@ // Only do 32-bit write if the value fits in 32 bits. if (GPBLogicalRightShift64(value, 32) == 0) { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput - bufferSize:blockSize]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput + bufferSize:blockSize]; [output writeRawVarint32:(int32_t)value]; [output flush]; - NSData* actual = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; XCTAssertEqualObjects(data, actual); } { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput - bufferSize:blockSize]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput + bufferSize:blockSize]; [output writeRawVarint64:value]; [output flush]; - NSData* actual = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; XCTAssertEqualObjects(data, actual); } } } - (void)assertWriteStringNoTag:(NSData*)data - value:(NSString *)value - context:(NSString *)contextMessage { + value:(NSString*)value + context:(NSString*)contextMessage { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput]; [output writeStringNoTag:value]; [output flush]; - NSData* actual = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; XCTAssertEqualObjects(data, actual, @"%@", contextMessage); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { rawOutput = [NSOutputStream outputStreamToMemory]; - output = [GPBCodedOutputStream streamWithOutputStream:rawOutput - bufferSize:blockSize]; + output = [GPBCodedOutputStream streamWithOutputStream:rawOutput bufferSize:blockSize]; [output writeStringNoTag:value]; [output flush]; @@ -243,51 +222,41 @@ // 1887747006 (no sign bit) [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x07) - value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | - (0x04 << 21) | (0x07LL << 28)]; + value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x07LL << 28)]; // 2961488830 (sign bit) [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b) - value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | - (0x04 << 21) | (0x0bLL << 28)]; + value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x0bLL << 28)]; } - (void)testWriteVarint6 { // 64-bit // 7256456126 [self assertWriteVarint:bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b) - value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | - (0x04 << 21) | (0x1bLL << 28)]; + value:(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x1bLL << 28)]; } - (void)testWriteVarint7 { // 41256202580718336 [self assertWriteVarint:bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49) - value:(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | - (0x1c << 21) | (0x43LL << 28) | (0x49LL << 35) | - (0x24LL << 42) | (0x49LL << 49)]; + value:(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | (0x43LL << 28) | + (0x49LL << 35) | (0x24LL << 42) | (0x49LL << 49)]; } - (void)testWriteVarint8 { // 11964378330978735131 - [self assertWriteVarint:bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, - 0xa6, 0x01) - value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | - (0x42 << 21) | (0x3bLL << 28) | (0x56LL << 35) | - (0x00LL << 42) | (0x05LL << 49) | (0x26LL << 56) | + [self assertWriteVarint:bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01) + value:(0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | (0x3bLL << 28) | + (0x56LL << 35) | (0x00LL << 42) | (0x05LL << 49) | (0x26LL << 56) | (0x01ULL << 63)]; } - (void)testWriteLittleEndian { - [self assertWriteLittleEndian32:bytes(0x78, 0x56, 0x34, 0x12) - value:0x12345678]; - [self assertWriteLittleEndian32:bytes(0xf0, 0xde, 0xbc, 0x9a) - value:0x9abcdef0]; + [self assertWriteLittleEndian32:bytes(0x78, 0x56, 0x34, 0x12) value:0x12345678]; + [self assertWriteLittleEndian32:bytes(0xf0, 0xde, 0xbc, 0x9a) value:0x9abcdef0]; - [self assertWriteLittleEndian64:bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, - 0x34, 0x12) + [self assertWriteLittleEndian64:bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12) value:0x123456789abcdef0LL]; - [self assertWriteLittleEndian64:bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, - 0xbc, 0x9a) + [self assertWriteLittleEndian64:bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a) value:0x9abcdef012345678LL]; } @@ -305,18 +274,12 @@ XCTAssertEqual(1ULL, GPBEncodeZigZag64(-1)); XCTAssertEqual(2ULL, GPBEncodeZigZag64(1)); XCTAssertEqual(3ULL, GPBEncodeZigZag64(-2)); - XCTAssertEqual(0x000000007FFFFFFEULL, - GPBEncodeZigZag64(0x000000003FFFFFFFLL)); - XCTAssertEqual(0x000000007FFFFFFFULL, - GPBEncodeZigZag64(0xFFFFFFFFC0000000LL)); - XCTAssertEqual(0x00000000FFFFFFFEULL, - GPBEncodeZigZag64(0x000000007FFFFFFFLL)); - XCTAssertEqual(0x00000000FFFFFFFFULL, - GPBEncodeZigZag64(0xFFFFFFFF80000000LL)); - XCTAssertEqual(0xFFFFFFFFFFFFFFFEULL, - GPBEncodeZigZag64(0x7FFFFFFFFFFFFFFFLL)); - XCTAssertEqual(0xFFFFFFFFFFFFFFFFULL, - GPBEncodeZigZag64(0x8000000000000000LL)); + XCTAssertEqual(0x000000007FFFFFFEULL, GPBEncodeZigZag64(0x000000003FFFFFFFLL)); + XCTAssertEqual(0x000000007FFFFFFFULL, GPBEncodeZigZag64(0xFFFFFFFFC0000000LL)); + XCTAssertEqual(0x00000000FFFFFFFEULL, GPBEncodeZigZag64(0x000000007FFFFFFFLL)); + XCTAssertEqual(0x00000000FFFFFFFFULL, GPBEncodeZigZag64(0xFFFFFFFF80000000LL)); + XCTAssertEqual(0xFFFFFFFFFFFFFFFEULL, GPBEncodeZigZag64(0x7FFFFFFFFFFFFFFFLL)); + XCTAssertEqual(0xFFFFFFFFFFFFFFFFULL, GPBEncodeZigZag64(0x8000000000000000LL)); // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) // were chosen semi-randomly via keyboard bashing. @@ -332,10 +295,8 @@ XCTAssertEqual(14927ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(14927))); XCTAssertEqual(-3612ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(-3612))); - XCTAssertEqual(856912304801416ULL, - GPBEncodeZigZag64(GPBDecodeZigZag64(856912304801416LL))); - XCTAssertEqual(-75123905439571256ULL, - GPBEncodeZigZag64(GPBDecodeZigZag64(-75123905439571256LL))); + XCTAssertEqual(856912304801416ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(856912304801416LL))); + XCTAssertEqual(-75123905439571256ULL, GPBEncodeZigZag64(GPBDecodeZigZag64(-75123905439571256LL))); } - (void)testWriteWholeMessage { @@ -344,21 +305,18 @@ TestAllTypes* message = [self allSetRepeatedCount:2]; NSData* rawBytes = message.data; - NSData* goldenData = - [self getDataFileNamed:@"golden_message" dataToWrite:rawBytes]; + NSData* goldenData = [self getDataFileNamed:@"golden_message" dataToWrite:rawBytes]; XCTAssertEqualObjects(rawBytes, goldenData); // Try different block sizes. for (int blockSize = 1; blockSize < 256; blockSize *= 2) { NSOutputStream* rawOutput = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream* output = - [GPBCodedOutputStream streamWithOutputStream:rawOutput - bufferSize:blockSize]; + GPBCodedOutputStream* output = [GPBCodedOutputStream streamWithOutputStream:rawOutput + bufferSize:blockSize]; [message writeToCodedOutputStream:output]; [output flush]; - NSData* actual = - [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + NSData* actual = [rawOutput propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; XCTAssertEqualObjects(rawBytes, actual); } @@ -366,8 +324,7 @@ // that was generated with 2. TestAllExtensions* extensions = [self allExtensionsSetRepeatedCount:2]; rawBytes = extensions.data; - goldenData = [self getDataFileNamed:@"golden_packed_fields_message" - dataToWrite:rawBytes]; + goldenData = [self getDataFileNamed:@"golden_packed_fields_message" dataToWrite:rawBytes]; XCTAssertEqualObjects(rawBytes, goldenData); } @@ -380,11 +337,10 @@ char zeroTest[] = "\0Test\0String"; // Note: there is a \0 at the end of this since it is a c-string. - NSString *asNSString = [[NSString alloc] initWithBytes:zeroTest + NSString* asNSString = [[NSString alloc] initWithBytes:zeroTest length:sizeof(zeroTest) encoding:NSUTF8StringEncoding]; - const char *cString = - CFStringGetCStringPtr((CFStringRef)asNSString, kCFStringEncodingUTF8); + const char* cString = CFStringGetCStringPtr((CFStringRef)asNSString, kCFStringEncodingUTF8); XCTAssertTrue(cString != NULL); // Again, if the above assert fails, then it means NSString no longer exposes // the raw utf8 storage of a string created from utf8 input, so the code using @@ -392,8 +348,7 @@ // a different code path); but the optimizations for when // CFStringGetCStringPtr does work could possibly go away. - XCTAssertEqual(sizeof(zeroTest), - [asNSString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); + XCTAssertEqual(sizeof(zeroTest), [asNSString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); XCTAssertTrue(0 == memcmp(cString, zeroTest, sizeof(zeroTest))); [asNSString release]; } @@ -405,25 +360,25 @@ // strings built via the NSString apis. So this round trips them to ensure // they are acting as expected. - NSArray *strs = @[ + NSArray* strs = @[ @"\0at start", @"in\0middle", @"at end\0", ]; int i = 0; - for (NSString *str in strs) { - NSData *asUTF8 = [str dataUsingEncoding:NSUTF8StringEncoding]; - NSMutableData *expected = [NSMutableData data]; + for (NSString* str in strs) { + NSData* asUTF8 = [str dataUsingEncoding:NSUTF8StringEncoding]; + NSMutableData* expected = [NSMutableData data]; uint8_t lengthByte = (uint8_t)asUTF8.length; [expected appendBytes:&lengthByte length:1]; [expected appendData:asUTF8]; - NSString *context = [NSString stringWithFormat:@"Loop %d - Literal", i]; + NSString* context = [NSString stringWithFormat:@"Loop %d - Literal", i]; [self assertWriteStringNoTag:expected value:str context:context]; // Force a new string to be built which gets a different class from the // NSString class cluster than the literal did. - NSString *str2 = [NSString stringWithFormat:@"%@", str]; + NSString* str2 = [NSString stringWithFormat:@"%@", str]; context = [NSString stringWithFormat:@"Loop %d - Built", i]; [self assertWriteStringNoTag:expected value:str2 context:context]; @@ -432,11 +387,11 @@ } - (void)testThatItThrowsWhenWriteRawPtrFails { - NSOutputStream *output = [NSOutputStream outputStreamToMemory]; - GPBCodedOutputStream *codedOutput = + NSOutputStream* output = [NSOutputStream outputStreamToMemory]; + GPBCodedOutputStream* codedOutput = [GPBCodedOutputStream streamWithOutputStream:output bufferSize:0]; // Skip buffering. [output close]; // Close the output stream to force failure on write. - const char *cString = "raw"; + const char* cString = "raw"; XCTAssertThrowsSpecificNamed([codedOutput writeRawPtr:cString offset:0 length:strlen(cString)], NSException, GPBCodedOutputStreamException_WriteFailed); } diff --git a/objectivec/Tests/GPBCompileTest01.m b/objectivec/Tests/GPBCompileTest01.m index c8bc433a04..c8a6e6bda9 100644 --- a/objectivec/Tests/GPBCompileTest01.m +++ b/objectivec/Tests/GPBCompileTest01.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBArray.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_1 = 0; diff --git a/objectivec/Tests/GPBCompileTest02.m b/objectivec/Tests/GPBCompileTest02.m index c44e201a4d..77e45894d4 100644 --- a/objectivec/Tests/GPBCompileTest02.m +++ b/objectivec/Tests/GPBCompileTest02.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBCodedInputStream.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_2 = 0; diff --git a/objectivec/Tests/GPBCompileTest03.m b/objectivec/Tests/GPBCompileTest03.m index 41994f94dd..f4945a7e26 100644 --- a/objectivec/Tests/GPBCompileTest03.m +++ b/objectivec/Tests/GPBCompileTest03.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBCodedOutputStream.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_3 = 0; diff --git a/objectivec/Tests/GPBCompileTest04.m b/objectivec/Tests/GPBCompileTest04.m index c31498f12c..da69c1dd6c 100644 --- a/objectivec/Tests/GPBCompileTest04.m +++ b/objectivec/Tests/GPBCompileTest04.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBDescriptor.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_4 = 0; diff --git a/objectivec/Tests/GPBCompileTest05.m b/objectivec/Tests/GPBCompileTest05.m index adb72252f5..e4665ea367 100644 --- a/objectivec/Tests/GPBCompileTest05.m +++ b/objectivec/Tests/GPBCompileTest05.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBDictionary.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_5 = 0; diff --git a/objectivec/Tests/GPBCompileTest06.m b/objectivec/Tests/GPBCompileTest06.m index b7505b02a6..c197b5620e 100644 --- a/objectivec/Tests/GPBCompileTest06.m +++ b/objectivec/Tests/GPBCompileTest06.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBExtensionRegistry.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_6 = 0; diff --git a/objectivec/Tests/GPBCompileTest07.m b/objectivec/Tests/GPBCompileTest07.m index 939bb7097d..83f7a8f1dd 100644 --- a/objectivec/Tests/GPBCompileTest07.m +++ b/objectivec/Tests/GPBCompileTest07.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBMessage.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_7 = 0; diff --git a/objectivec/Tests/GPBCompileTest08.m b/objectivec/Tests/GPBCompileTest08.m index a84f38cf71..48246f828e 100644 --- a/objectivec/Tests/GPBCompileTest08.m +++ b/objectivec/Tests/GPBCompileTest08.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBRootObject.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_8 = 0; diff --git a/objectivec/Tests/GPBCompileTest09.m b/objectivec/Tests/GPBCompileTest09.m index f8ccb4a00f..d1d8cdf9a9 100644 --- a/objectivec/Tests/GPBCompileTest09.m +++ b/objectivec/Tests/GPBCompileTest09.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBUnknownField.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_9 = 0; diff --git a/objectivec/Tests/GPBCompileTest10.m b/objectivec/Tests/GPBCompileTest10.m index d8318678db..31f610d2ff 100644 --- a/objectivec/Tests/GPBCompileTest10.m +++ b/objectivec/Tests/GPBCompileTest10.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBUnknownFieldSet.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_10 = 0; diff --git a/objectivec/Tests/GPBCompileTest11.m b/objectivec/Tests/GPBCompileTest11.m index 9f2c6b11a0..2f51ec90c6 100644 --- a/objectivec/Tests/GPBCompileTest11.m +++ b/objectivec/Tests/GPBCompileTest11.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBUtilities.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_11 = 0; diff --git a/objectivec/Tests/GPBCompileTest12.m b/objectivec/Tests/GPBCompileTest12.m index 3aa29b3171..9892bcfea4 100644 --- a/objectivec/Tests/GPBCompileTest12.m +++ b/objectivec/Tests/GPBCompileTest12.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBWellKnownTypes.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_12 = 0; diff --git a/objectivec/Tests/GPBCompileTest13.m b/objectivec/Tests/GPBCompileTest13.m index fef2af5f4a..d5168ae640 100644 --- a/objectivec/Tests/GPBCompileTest13.m +++ b/objectivec/Tests/GPBCompileTest13.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBWireFormat.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_13 = 0; diff --git a/objectivec/Tests/GPBCompileTest14.m b/objectivec/Tests/GPBCompileTest14.m index 1e64b7116d..cd59f6f3f8 100644 --- a/objectivec/Tests/GPBCompileTest14.m +++ b/objectivec/Tests/GPBCompileTest14.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBAny.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_14 = 0; diff --git a/objectivec/Tests/GPBCompileTest15.m b/objectivec/Tests/GPBCompileTest15.m index 2eaedb26fb..ad9a3f845e 100644 --- a/objectivec/Tests/GPBCompileTest15.m +++ b/objectivec/Tests/GPBCompileTest15.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBApi.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_15 = 0; diff --git a/objectivec/Tests/GPBCompileTest16.m b/objectivec/Tests/GPBCompileTest16.m index 25af89e002..c5b532ed28 100644 --- a/objectivec/Tests/GPBCompileTest16.m +++ b/objectivec/Tests/GPBCompileTest16.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBDuration.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_16 = 0; diff --git a/objectivec/Tests/GPBCompileTest17.m b/objectivec/Tests/GPBCompileTest17.m index c719ad31cc..02988e647a 100644 --- a/objectivec/Tests/GPBCompileTest17.m +++ b/objectivec/Tests/GPBCompileTest17.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBEmpty.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_17 = 0; diff --git a/objectivec/Tests/GPBCompileTest18.m b/objectivec/Tests/GPBCompileTest18.m index a02b2590e3..a652c6151f 100644 --- a/objectivec/Tests/GPBCompileTest18.m +++ b/objectivec/Tests/GPBCompileTest18.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBFieldMask.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_18 = 0; diff --git a/objectivec/Tests/GPBCompileTest19.m b/objectivec/Tests/GPBCompileTest19.m index b4472846e0..7ea31a81a0 100644 --- a/objectivec/Tests/GPBCompileTest19.m +++ b/objectivec/Tests/GPBCompileTest19.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBSourceContext.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_19 = 0; diff --git a/objectivec/Tests/GPBCompileTest20.m b/objectivec/Tests/GPBCompileTest20.m index 120ef5546d..d79ceea2a4 100644 --- a/objectivec/Tests/GPBCompileTest20.m +++ b/objectivec/Tests/GPBCompileTest20.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBStruct.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_20 = 0; diff --git a/objectivec/Tests/GPBCompileTest21.m b/objectivec/Tests/GPBCompileTest21.m index 766d890b70..0a273da815 100644 --- a/objectivec/Tests/GPBCompileTest21.m +++ b/objectivec/Tests/GPBCompileTest21.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBTimestamp.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_21 = 0; diff --git a/objectivec/Tests/GPBCompileTest22.m b/objectivec/Tests/GPBCompileTest22.m index 6d0955b73a..05cd01cf7c 100644 --- a/objectivec/Tests/GPBCompileTest22.m +++ b/objectivec/Tests/GPBCompileTest22.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBType.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_22 = 0; diff --git a/objectivec/Tests/GPBCompileTest23.m b/objectivec/Tests/GPBCompileTest23.m index 22f2db63bf..ec29f3af4c 100644 --- a/objectivec/Tests/GPBCompileTest23.m +++ b/objectivec/Tests/GPBCompileTest23.m @@ -28,13 +28,11 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - // This is a test including a single public header to ensure things build. // It helps test that imports are complete/ordered correctly. #import "GPBWrappers.pbobjc.h" - // Something in the body of this file so the compiler/linker won't complain // about an empty .o file. __attribute__((visibility("default"))) char dummy_symbol_23 = 0; diff --git a/objectivec/Tests/GPBConcurrencyTests.m b/objectivec/Tests/GPBConcurrencyTests.m index 1c39317b51..4ea62f9c5d 100644 --- a/objectivec/Tests/GPBConcurrencyTests.m +++ b/objectivec/Tests/GPBConcurrencyTests.m @@ -49,8 +49,7 @@ static const int kNumMessages = 100; - (NSArray *)createThreadsWithSelector:(SEL)selector object:(id)object { NSMutableArray *array = [NSMutableArray array]; for (NSUInteger i = 0; i < kNumThreads; i++) { - NSThread *thread = - [[NSThread alloc] initWithTarget:self selector:selector object:object]; + NSThread *thread = [[NSThread alloc] initWithTarget:self selector:selector object:object]; [array addObject:thread]; [thread release]; } @@ -88,9 +87,8 @@ static const int kNumMessages = 100; - (void)testConcurrentReadOfUnsetMessageField { NSArray *messages = [self createMessagesWithType:[TestAllTypes class]]; - NSArray *threads = - [self createThreadsWithSelector:@selector(readForeignMessage:) - object:messages]; + NSArray *threads = [self createThreadsWithSelector:@selector(readForeignMessage:) + object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestAllTypes *message in messages) { @@ -108,9 +106,7 @@ static const int kNumMessages = 100; - (void)testConcurrentReadOfUnsetRepeatedIntField { NSArray *messages = [self createMessagesWithType:[TestAllTypes class]]; - NSArray *threads = - [self createThreadsWithSelector:@selector(readRepeatedInt32:) - object:messages]; + NSArray *threads = [self createThreadsWithSelector:@selector(readRepeatedInt32:) object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestAllTypes *message in messages) { @@ -128,9 +124,8 @@ static const int kNumMessages = 100; - (void)testConcurrentReadOfUnsetRepeatedStringField { NSArray *messages = [self createMessagesWithType:[TestAllTypes class]]; - NSArray *threads = - [self createThreadsWithSelector:@selector(readRepeatedString:) - object:messages]; + NSArray *threads = [self createThreadsWithSelector:@selector(readRepeatedString:) + object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestAllTypes *message in messages) { @@ -147,11 +142,8 @@ static const int kNumMessages = 100; } - (void)testConcurrentReadOfUnsetInt32Int32MapField { - NSArray *messages = - [self createMessagesWithType:[TestRecursiveMessageWithRepeatedField class]]; - NSArray *threads = - [self createThreadsWithSelector:@selector(readInt32Int32Map:) - object:messages]; + NSArray *messages = [self createMessagesWithType:[TestRecursiveMessageWithRepeatedField class]]; + NSArray *threads = [self createThreadsWithSelector:@selector(readInt32Int32Map:) object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestRecursiveMessageWithRepeatedField *message in messages) { @@ -168,11 +160,9 @@ static const int kNumMessages = 100; } - (void)testConcurrentReadOfUnsetStringStringMapField { - NSArray *messages = - [self createMessagesWithType:[TestRecursiveMessageWithRepeatedField class]]; - NSArray *threads = - [self createThreadsWithSelector:@selector(readStringStringMap:) - object:messages]; + NSArray *messages = [self createMessagesWithType:[TestRecursiveMessageWithRepeatedField class]]; + NSArray *threads = [self createThreadsWithSelector:@selector(readStringStringMap:) + object:messages]; [self startThreads:threads]; [self joinThreads:threads]; for (TestRecursiveMessageWithRepeatedField *message in messages) { @@ -196,8 +186,7 @@ static const int kNumMessages = 100; NSArray *threads = [self createThreadsWithSelector:sel object:messages]; [self startThreads:threads]; [self joinThreads:threads]; - GPBExtensionDescriptor *extension = - [UnittestRoot optionalForeignMessageExtension]; + GPBExtensionDescriptor *extension = [UnittestRoot optionalForeignMessageExtension]; for (TestAllExtensions *message in messages) { XCTAssertFalse([message hasExtension:extension]); } diff --git a/objectivec/Tests/GPBDescriptorTests.m b/objectivec/Tests/GPBDescriptorTests.m index 6e83b3f4d9..e528be4041 100644 --- a/objectivec/Tests/GPBDescriptorTests.m +++ b/objectivec/Tests/GPBDescriptorTests.m @@ -54,13 +54,15 @@ GPBDescriptor *testAllTypesDesc = [TestAllTypes descriptor]; XCTAssertEqualObjects(testAllTypesDesc.fullName, @"objc.protobuf.tests.TestAllTypes"); GPBDescriptor *nestedMessageDesc = [TestAllTypes_NestedMessage descriptor]; - XCTAssertEqualObjects(nestedMessageDesc.fullName, @"objc.protobuf.tests.TestAllTypes.NestedMessage"); + XCTAssertEqualObjects(nestedMessageDesc.fullName, + @"objc.protobuf.tests.TestAllTypes.NestedMessage"); // Prefixes removed. GPBDescriptor *descDesc = [GPBTESTPrefixedParentMessage descriptor]; XCTAssertEqualObjects(descDesc.fullName, @"objc.protobuf.tests.options.PrefixedParentMessage"); GPBDescriptor *descExtRngDesc = [GPBTESTPrefixedParentMessage_Child descriptor]; - XCTAssertEqualObjects(descExtRngDesc.fullName, @"objc.protobuf.tests.options.PrefixedParentMessage.Child"); + XCTAssertEqualObjects(descExtRngDesc.fullName, + @"objc.protobuf.tests.options.PrefixedParentMessage.Child"); // Things that get "_Class" added. GPBDescriptor *pointDesc = [Point_Class descriptor]; @@ -73,16 +75,13 @@ GPBDescriptor *descriptor = [TestAllTypes descriptor]; // Nested Enum - GPBFieldDescriptor *fieldDescriptorWithName = - [descriptor fieldWithName:@"optionalNestedEnum"]; + GPBFieldDescriptor *fieldDescriptorWithName = [descriptor fieldWithName:@"optionalNestedEnum"]; XCTAssertNotNil(fieldDescriptorWithName); - GPBFieldDescriptor *fieldDescriptorWithNumber = - [descriptor fieldWithNumber:21]; + GPBFieldDescriptor *fieldDescriptorWithNumber = [descriptor fieldWithNumber:21]; XCTAssertNotNil(fieldDescriptorWithNumber); XCTAssertEqual(fieldDescriptorWithName, fieldDescriptorWithNumber); XCTAssertNotNil(fieldDescriptorWithNumber.enumDescriptor); - XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name, - @"TestAllTypes_NestedEnum"); + XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name, @"TestAllTypes_NestedEnum"); XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number); XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeEnum); @@ -93,8 +92,7 @@ XCTAssertNotNil(fieldDescriptorWithNumber); XCTAssertEqual(fieldDescriptorWithName, fieldDescriptorWithNumber); XCTAssertNotNil(fieldDescriptorWithNumber.enumDescriptor); - XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name, - @"ForeignEnum"); + XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name, @"ForeignEnum"); XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number); XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeEnum); @@ -105,8 +103,7 @@ XCTAssertNotNil(fieldDescriptorWithNumber); XCTAssertEqual(fieldDescriptorWithName, fieldDescriptorWithNumber); XCTAssertNotNil(fieldDescriptorWithNumber.enumDescriptor); - XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name, - @"ImportEnum"); + XCTAssertEqualObjects(fieldDescriptorWithNumber.enumDescriptor.name, @"ImportEnum"); XCTAssertEqual(fieldDescriptorWithName.number, fieldDescriptorWithNumber.number); XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeEnum); @@ -121,8 +118,7 @@ XCTAssertEqual(fieldDescriptorWithName.dataType, GPBDataTypeMessage); // Foreign Message - fieldDescriptorWithName = - [descriptor fieldWithName:@"optionalForeignMessage"]; + fieldDescriptorWithName = [descriptor fieldWithName:@"optionalForeignMessage"]; XCTAssertNotNil(fieldDescriptorWithName); fieldDescriptorWithNumber = [descriptor fieldWithNumber:19]; XCTAssertNotNil(fieldDescriptorWithNumber); @@ -152,22 +148,18 @@ NSString *enumName = [descriptor enumNameForValue:1]; XCTAssertNotNil(enumName); int32_t value; - XCTAssertTrue( - [descriptor getValue:&value forEnumName:@"TestAllTypes_NestedEnum_Foo"]); - XCTAssertTrue( - [descriptor getValue:NULL forEnumName:@"TestAllTypes_NestedEnum_Foo"]); + XCTAssertTrue([descriptor getValue:&value forEnumName:@"TestAllTypes_NestedEnum_Foo"]); + XCTAssertTrue([descriptor getValue:NULL forEnumName:@"TestAllTypes_NestedEnum_Foo"]); XCTAssertEqual(value, TestAllTypes_NestedEnum_Foo); enumName = [descriptor enumNameForValue:2]; XCTAssertNotNil(enumName); - XCTAssertTrue( - [descriptor getValue:&value forEnumName:@"TestAllTypes_NestedEnum_Bar"]); + XCTAssertTrue([descriptor getValue:&value forEnumName:@"TestAllTypes_NestedEnum_Bar"]); XCTAssertEqual(value, TestAllTypes_NestedEnum_Bar); enumName = [descriptor enumNameForValue:3]; XCTAssertNotNil(enumName); - XCTAssertTrue( - [descriptor getValue:&value forEnumName:@"TestAllTypes_NestedEnum_Baz"]); + XCTAssertTrue([descriptor getValue:&value forEnumName:@"TestAllTypes_NestedEnum_Baz"]); XCTAssertEqual(value, TestAllTypes_NestedEnum_Baz); // TextFormat @@ -182,10 +174,8 @@ XCTAssertNil(enumName); XCTAssertFalse([descriptor getValue:&value forEnumName:@"Unknown"]); XCTAssertFalse([descriptor getValue:NULL forEnumName:@"Unknown"]); - XCTAssertFalse([descriptor getValue:&value - forEnumName:@"TestAllTypes_NestedEnum_Unknown"]); - XCTAssertFalse([descriptor getValue:NULL - forEnumName:@"TestAllTypes_NestedEnum_Unknown"]); + XCTAssertFalse([descriptor getValue:&value forEnumName:@"TestAllTypes_NestedEnum_Unknown"]); + XCTAssertFalse([descriptor getValue:NULL forEnumName:@"TestAllTypes_NestedEnum_Unknown"]); XCTAssertFalse([descriptor getValue:NULL forEnumTextFormatName:@"Unknown"]); XCTAssertFalse([descriptor getValue:&value forEnumTextFormatName:@"Unknown"]); } @@ -194,17 +184,13 @@ GPBEnumDescriptor *descriptor = TestAllTypes_NestedEnum_EnumDescriptor(); XCTAssertEqual(descriptor.enumNameCount, 4U); - XCTAssertEqualObjects([descriptor getEnumNameForIndex:0], - @"TestAllTypes_NestedEnum_Foo"); + XCTAssertEqualObjects([descriptor getEnumNameForIndex:0], @"TestAllTypes_NestedEnum_Foo"); XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:0], @"FOO"); - XCTAssertEqualObjects([descriptor getEnumNameForIndex:1], - @"TestAllTypes_NestedEnum_Bar"); + XCTAssertEqualObjects([descriptor getEnumNameForIndex:1], @"TestAllTypes_NestedEnum_Bar"); XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:1], @"BAR"); - XCTAssertEqualObjects([descriptor getEnumNameForIndex:2], - @"TestAllTypes_NestedEnum_Baz"); + XCTAssertEqualObjects([descriptor getEnumNameForIndex:2], @"TestAllTypes_NestedEnum_Baz"); XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:2], @"BAZ"); - XCTAssertEqualObjects([descriptor getEnumNameForIndex:3], - @"TestAllTypes_NestedEnum_Neg"); + XCTAssertEqualObjects([descriptor getEnumNameForIndex:3], @"TestAllTypes_NestedEnum_Neg"); XCTAssertEqualObjects([descriptor getEnumTextFormatNameForIndex:3], @"NEG"); } @@ -286,8 +272,7 @@ - (void)testEnumValueValidator { GPBDescriptor *descriptor = [TestAllTypes descriptor]; - GPBFieldDescriptor *fieldDescriptor = - [descriptor fieldWithName:@"optionalNestedEnum"]; + GPBFieldDescriptor *fieldDescriptor = [descriptor fieldWithName:@"optionalNestedEnum"]; // Valid values XCTAssertTrue([fieldDescriptor isValidEnumValue:1]); @@ -325,12 +310,10 @@ // Pointer comparisons against lookups from message. - XCTAssertEqual([oneofFoo fieldWithNumber:TestOneof2_FieldNumber_FooString], - fooStringField); + XCTAssertEqual([oneofFoo fieldWithNumber:TestOneof2_FieldNumber_FooString], fooStringField); XCTAssertEqual([oneofFoo fieldWithName:@"fooString"], fooStringField); - XCTAssertEqual([oneofBar fieldWithNumber:TestOneof2_FieldNumber_BarString], - barStringField); + XCTAssertEqual([oneofBar fieldWithNumber:TestOneof2_FieldNumber_BarString], barStringField); XCTAssertEqual([oneofBar fieldWithName:@"barString"], barStringField); // Unknown oneof not found. @@ -354,8 +337,7 @@ // (pointer comparisons) XCTAssertEqual(fooStringField.containingOneof, oneofFoo); XCTAssertEqual(barStringField.containingOneof, oneofBar); - GPBFieldDescriptor *bazString = - [descriptor fieldWithNumber:TestOneof2_FieldNumber_BazString]; + GPBFieldDescriptor *bazString = [descriptor fieldWithNumber:TestOneof2_FieldNumber_BazString]; XCTAssertNotNil(bazString); XCTAssertNil(bazString.containingOneof); } diff --git a/objectivec/Tests/GPBDictionaryTests.m b/objectivec/Tests/GPBDictionaryTests.m index 52b4b32806..e5670d8133 100644 --- a/objectivec/Tests/GPBDictionaryTests.m +++ b/objectivec/Tests/GPBDictionaryTests.m @@ -56,17 +56,17 @@ XCTAssertTrue([dict isEqual:@{}]); XCTAssertTrue([dict isEqualToDictionary:@{}]); - XCTAssertFalse([dict isEqual:@{ @"foo" : @"bar" }]); - XCTAssertFalse([dict isEqualToDictionary:@{ @"foo" : @"bar" }]); + XCTAssertFalse([dict isEqual:@{@"foo" : @"bar"}]); + XCTAssertFalse([dict isEqualToDictionary:@{@"foo" : @"bar"}]); [dict setObject:@"bar" forKey:@"foo"]; XCTAssertFalse([dict isEqual:@{}]); XCTAssertFalse([dict isEqualToDictionary:@{}]); - XCTAssertTrue([dict isEqual:@{ @"foo" : @"bar" }]); - XCTAssertTrue([dict isEqualToDictionary:@{ @"foo" : @"bar" }]); - XCTAssertFalse([dict isEqual:@{ @"bar" : @"baz" }]); - XCTAssertFalse([dict isEqualToDictionary:@{ @"bar" : @"baz" }]); + XCTAssertTrue([dict isEqual:@{@"foo" : @"bar"}]); + XCTAssertTrue([dict isEqualToDictionary:@{@"foo" : @"bar"}]); + XCTAssertFalse([dict isEqual:@{@"bar" : @"baz"}]); + XCTAssertFalse([dict isEqualToDictionary:@{@"bar" : @"baz"}]); GPBAutocreatedDictionary *dict2 = [[GPBAutocreatedDictionary alloc] init]; @@ -90,14 +90,14 @@ GPBAutocreatedDictionary *dict = [[GPBAutocreatedDictionary alloc] init]; NSDictionary *cpy = [dict copy]; - XCTAssertTrue(cpy != dict); // Ptr compare + XCTAssertTrue(cpy != dict); // Ptr compare XCTAssertTrue([cpy isKindOfClass:[NSDictionary class]]); XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(cpy.count, (NSUInteger)0); NSDictionary *cpy2 = [dict copy]; - XCTAssertTrue(cpy2 != dict); // Ptr compare - XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue(cpy2 != dict); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare XCTAssertTrue([cpy2 isKindOfClass:[NSDictionary class]]); XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(cpy2.count, (NSUInteger)0); @@ -111,14 +111,14 @@ GPBAutocreatedDictionary *dict = [[GPBAutocreatedDictionary alloc] init]; NSMutableDictionary *cpy = [dict mutableCopy]; - XCTAssertTrue(cpy != dict); // Ptr compare + XCTAssertTrue(cpy != dict); // Ptr compare XCTAssertTrue([cpy isKindOfClass:[NSMutableDictionary class]]); XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(cpy.count, (NSUInteger)0); NSMutableDictionary *cpy2 = [dict mutableCopy]; - XCTAssertTrue(cpy2 != dict); // Ptr compare - XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue(cpy2 != dict); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare XCTAssertTrue([cpy2 isKindOfClass:[NSMutableDictionary class]]); XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(cpy2.count, (NSUInteger)0); @@ -134,7 +134,7 @@ dict[@"baz"] = @"mumble"; NSDictionary *cpy = [dict copy]; - XCTAssertTrue(cpy != dict); // Ptr compare + XCTAssertTrue(cpy != dict); // Ptr compare XCTAssertTrue([cpy isKindOfClass:[NSDictionary class]]); XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(cpy.count, (NSUInteger)2); @@ -142,8 +142,8 @@ XCTAssertEqualObjects(cpy[@"baz"], @"mumble"); NSDictionary *cpy2 = [dict copy]; - XCTAssertTrue(cpy2 != dict); // Ptr compare - XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue(cpy2 != dict); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare XCTAssertTrue([cpy2 isKindOfClass:[NSDictionary class]]); XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(cpy2.count, (NSUInteger)2); @@ -161,7 +161,7 @@ dict[@"baz"] = @"mumble"; NSMutableDictionary *cpy = [dict mutableCopy]; - XCTAssertTrue(cpy != dict); // Ptr compare + XCTAssertTrue(cpy != dict); // Ptr compare XCTAssertTrue([cpy isKindOfClass:[NSMutableDictionary class]]); XCTAssertFalse([cpy isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(cpy.count, (NSUInteger)2); @@ -169,8 +169,8 @@ XCTAssertEqualObjects(cpy[@"baz"], @"mumble"); NSMutableDictionary *cpy2 = [dict mutableCopy]; - XCTAssertTrue(cpy2 != dict); // Ptr compare - XCTAssertTrue(cpy2 != cpy); // Ptr compare + XCTAssertTrue(cpy2 != dict); // Ptr compare + XCTAssertTrue(cpy2 != cpy); // Ptr compare XCTAssertTrue([cpy2 isKindOfClass:[NSMutableDictionary class]]); XCTAssertFalse([cpy2 isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(cpy2.count, (NSUInteger)2); diff --git a/objectivec/Tests/GPBExtensionRegistryTest.m b/objectivec/Tests/GPBExtensionRegistryTest.m index eddefd751d..bdd237bab0 100644 --- a/objectivec/Tests/GPBExtensionRegistryTest.m +++ b/objectivec/Tests/GPBExtensionRegistryTest.m @@ -42,20 +42,17 @@ GPBExtensionRegistry *reg = [[[GPBExtensionRegistry alloc] init] autorelease]; XCTAssertNotNil(reg); - XCTAssertNil([reg extensionForDescriptor:[TestAllExtensions descriptor] - fieldNumber:1]); - XCTAssertNil([reg extensionForDescriptor:[TestAllTypes descriptor] - fieldNumber:1]); + XCTAssertNil([reg extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1]); + XCTAssertNil([reg extensionForDescriptor:[TestAllTypes descriptor] fieldNumber:1]); [reg addExtension:[UnittestRoot optionalInt32Extension]]; [reg addExtension:[UnittestRoot packedInt64Extension]]; XCTAssertTrue([reg extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1] == - [UnittestRoot optionalInt32Extension]); // ptr equality - XCTAssertNil([reg extensionForDescriptor:[TestAllTypes descriptor] - fieldNumber:1]); + [UnittestRoot optionalInt32Extension]); // ptr equality + XCTAssertNil([reg extensionForDescriptor:[TestAllTypes descriptor] fieldNumber:1]); XCTAssertTrue([reg extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91] == - [UnittestRoot packedInt64Extension]); // ptr equality + [UnittestRoot packedInt64Extension]); // ptr equality } - (void)testCopy { @@ -66,9 +63,9 @@ XCTAssertNotNil(reg2); XCTAssertTrue([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1] == - [UnittestRoot optionalInt32Extension]); // ptr equality + [UnittestRoot optionalInt32Extension]); // ptr equality XCTAssertTrue([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1] == - [UnittestRoot optionalInt32Extension]); // ptr equality + [UnittestRoot optionalInt32Extension]); // ptr equality // Message class that had registered extension(s) at the -copy time. @@ -76,11 +73,11 @@ [reg2 addExtension:[UnittestRoot optionalStringExtension]]; XCTAssertTrue([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:13] == - [UnittestRoot optionalBoolExtension]); // ptr equality + [UnittestRoot optionalBoolExtension]); // ptr equality XCTAssertNil([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:14]); XCTAssertNil([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:13]); XCTAssertTrue([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:14] == - [UnittestRoot optionalStringExtension]); // ptr equality + [UnittestRoot optionalStringExtension]); // ptr equality // Message class that did not have any registered extensions at the -copy time. @@ -88,12 +85,11 @@ [reg2 addExtension:[UnittestRoot packedSint32Extension]]; XCTAssertTrue([reg1 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91] == - [UnittestRoot packedInt64Extension]); // ptr equality + [UnittestRoot packedInt64Extension]); // ptr equality XCTAssertNil([reg1 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:94]); XCTAssertNil([reg2 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91]); XCTAssertTrue([reg2 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:94] == - [UnittestRoot packedSint32Extension]); // ptr equality - + [UnittestRoot packedSint32Extension]); // ptr equality } - (void)testAddExtensions { @@ -102,13 +98,12 @@ GPBExtensionRegistry *reg2 = [[[GPBExtensionRegistry alloc] init] autorelease]; - XCTAssertNil([reg2 extensionForDescriptor:[TestAllExtensions descriptor] - fieldNumber:1]); + XCTAssertNil([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1]); [reg2 addExtensions:reg1]; XCTAssertTrue([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:1] == - [UnittestRoot optionalInt32Extension]); // ptr equality + [UnittestRoot optionalInt32Extension]); // ptr equality // Confirm adding to the first doesn't add to the second. @@ -116,9 +111,9 @@ [reg1 addExtension:[UnittestRoot packedInt64Extension]]; XCTAssertTrue([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:13] == - [UnittestRoot optionalBoolExtension]); // ptr equality + [UnittestRoot optionalBoolExtension]); // ptr equality XCTAssertTrue([reg1 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91] == - [UnittestRoot packedInt64Extension]); // ptr equality + [UnittestRoot packedInt64Extension]); // ptr equality XCTAssertNil([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:13]); XCTAssertNil([reg2 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:91]); @@ -130,9 +125,9 @@ XCTAssertNil([reg1 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:14]); XCTAssertNil([reg1 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:94]); XCTAssertTrue([reg2 extensionForDescriptor:[TestAllExtensions descriptor] fieldNumber:14] == - [UnittestRoot optionalStringExtension]); // ptr equality + [UnittestRoot optionalStringExtension]); // ptr equality XCTAssertTrue([reg2 extensionForDescriptor:[TestPackedExtensions descriptor] fieldNumber:94] == - [UnittestRoot packedSint32Extension]); // ptr equality + [UnittestRoot packedSint32Extension]); // ptr equality } @end diff --git a/objectivec/Tests/GPBMessageTests+ClassNames.m b/objectivec/Tests/GPBMessageTests+ClassNames.m index b5a5c51d04..1b656d04f1 100644 --- a/objectivec/Tests/GPBMessageTests+ClassNames.m +++ b/objectivec/Tests/GPBMessageTests+ClassNames.m @@ -62,15 +62,15 @@ typedef struct MessageLackingClazz_storage_ { static GPBDescriptor *descriptor = nil; if (!descriptor) { static GPBMessageFieldDescription fields[] = { - { - .name = "foo", - .dataTypeSpecific.className = "NSString", - .number = 1, - .hasIndex = 0, - .offset = (uint32_t)offsetof(MessageLackingClazz_storage_, foo), - .flags = (GPBFieldFlags)(GPBFieldOptional), - .dataType = GPBDataTypeMessage, - }, + { + .name = "foo", + .dataTypeSpecific.className = "NSString", + .number = 1, + .hasIndex = 0, + .offset = (uint32_t)offsetof(MessageLackingClazz_storage_, foo), + .flags = (GPBFieldFlags)(GPBFieldOptional), + .dataType = GPBDataTypeMessage, + }, }; GPBFileDescriptor *desc = [[[GPBFileDescriptor alloc] initWithPackage:@"test" @@ -78,14 +78,14 @@ typedef struct MessageLackingClazz_storage_ { syntax:GPBFileSyntaxProto3] autorelease]; // GPBDescriptorInitializationFlag_UsesClassRefs intentionally not set here - descriptor = - [GPBDescriptor allocDescriptorForClass:[MessageLackingClazz class] - rootClass:[MessageLackingClazzRoot class] - file:desc - fields:fields - fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) - storageSize:sizeof(MessageLackingClazz_storage_) - flags:GPBDescriptorInitializationFlag_None]; + descriptor = [GPBDescriptor + allocDescriptorForClass:[MessageLackingClazz class] + rootClass:[MessageLackingClazzRoot class] + file:desc + fields:fields + fieldCount:(uint32_t)(sizeof(fields) / sizeof(GPBMessageFieldDescription)) + storageSize:sizeof(MessageLackingClazz_storage_) + flags:GPBDescriptorInitializationFlag_None]; [descriptor setupContainingMessageClassName:"MessageLackingClazz"]; } return descriptor; @@ -94,24 +94,24 @@ typedef struct MessageLackingClazz_storage_ { @implementation MessageLackingClazzRoot -+ (GPBExtensionRegistry*)extensionRegistry { ++ (GPBExtensionRegistry *)extensionRegistry { // This is called by +initialize so there is no need to worry // about thread safety and initialization of registry. - static GPBExtensionRegistry* registry = nil; + static GPBExtensionRegistry *registry = nil; if (!registry) { registry = [[GPBExtensionRegistry alloc] init]; static GPBExtensionDescription descriptions[] = { - { - .defaultValue.valueMessage = NULL, - .singletonName = "MessageLackingClazzRoot_ext1", - .extendedClass.name = "MessageLackingClazz", - .messageOrGroupClass.name = "MessageLackingClazz", - .enumDescriptorFunc = NULL, - .fieldNumber = 1, - .dataType = GPBDataTypeMessage, - // GPBExtensionUsesClazz Intentionally not set - .options = 0, - }, + { + .defaultValue.valueMessage = NULL, + .singletonName = "MessageLackingClazzRoot_ext1", + .extendedClass.name = "MessageLackingClazz", + .messageOrGroupClass.name = "MessageLackingClazz", + .enumDescriptorFunc = NULL, + .fieldNumber = 1, + .dataType = GPBDataTypeMessage, + // GPBExtensionUsesClazz Intentionally not set + .options = 0, + }, }; for (size_t i = 0; i < sizeof(descriptions) / sizeof(descriptions[0]); ++i) { // Intentionall using `-initWithExtensionDescription:` and not ` diff --git a/objectivec/Tests/GPBMessageTests+Merge.m b/objectivec/Tests/GPBMessageTests+Merge.m index 743b521677..a85341905d 100644 --- a/objectivec/Tests/GPBMessageTests+Merge.m +++ b/objectivec/Tests/GPBMessageTests+Merge.m @@ -197,9 +197,8 @@ // Known value. src.e = UnknownEnumsMyEnum_Bar; - src.repeatedEArray = - [GPBEnumArray arrayWithValidationFunction:UnknownEnumsMyEnum_IsValidValue - rawValue:UnknownEnumsMyEnum_Bar]; + src.repeatedEArray = [GPBEnumArray arrayWithValidationFunction:UnknownEnumsMyEnum_IsValidValue + rawValue:UnknownEnumsMyEnum_Bar]; src.repeatedPackedEArray = [GPBEnumArray arrayWithValidationFunction:UnknownEnumsMyEnum_IsValidValue rawValue:UnknownEnumsMyEnum_Bar]; @@ -211,8 +210,7 @@ XCTAssertEqual(dst.repeatedEArray.count, 1U); XCTAssertEqual([dst.repeatedEArray valueAtIndex:0], UnknownEnumsMyEnum_Bar); XCTAssertEqual(dst.repeatedPackedEArray.count, 1U); - XCTAssertEqual([dst.repeatedPackedEArray valueAtIndex:0], - UnknownEnumsMyEnum_Bar); + XCTAssertEqual([dst.repeatedPackedEArray valueAtIndex:0], UnknownEnumsMyEnum_Bar); XCTAssertEqual(dst.oneofE1, UnknownEnumsMyEnum_Bar); // Unknown value. @@ -220,9 +218,8 @@ const int32_t kUnknownValue = 666; SetUnknownEnumsMyMessage_E_RawValue(src, kUnknownValue); - src.repeatedEArray = - [GPBEnumArray arrayWithValidationFunction:UnknownEnumsMyEnum_IsValidValue - rawValue:kUnknownValue]; + src.repeatedEArray = [GPBEnumArray arrayWithValidationFunction:UnknownEnumsMyEnum_IsValidValue + rawValue:kUnknownValue]; src.repeatedPackedEArray = [GPBEnumArray arrayWithValidationFunction:UnknownEnumsMyEnum_IsValidValue rawValue:kUnknownValue]; @@ -238,13 +235,11 @@ UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); XCTAssertEqual([dst.repeatedEArray rawValueAtIndex:1], kUnknownValue); XCTAssertEqual(dst.repeatedPackedEArray.count, 2U); - XCTAssertEqual([dst.repeatedPackedEArray valueAtIndex:0], - UnknownEnumsMyEnum_Bar); + XCTAssertEqual([dst.repeatedPackedEArray valueAtIndex:0], UnknownEnumsMyEnum_Bar); XCTAssertEqual([dst.repeatedPackedEArray valueAtIndex:1], UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); XCTAssertEqual([dst.repeatedPackedEArray rawValueAtIndex:1], kUnknownValue); - XCTAssertEqual(dst.oneofE1, - UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); + XCTAssertEqual(dst.oneofE1, UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); XCTAssertEqual(UnknownEnumsMyMessage_OneofE1_RawValue(dst), kUnknownValue); } @@ -258,8 +253,8 @@ dst.oneofEnum = Message2_Enum_Bar; -// Disable clang-format for the macros. -// clang-format off + // Disable clang-format for the macros. + // clang-format off //%PDDM-DEFINE MERGE2_TEST(SET_NAME, SET_VALUE, CLEARED_NAME, CLEARED_DEFAULT) //% src.oneof##SET_NAME = SET_VALUE; @@ -396,7 +391,7 @@ //%PDDM-EXPAND-END (14 expansions) -// clang-format on + // clang-format on NSString *oneofStringDefault = @"string"; NSData *oneofBytesDefault = [@"data" dataUsingEncoding:NSUTF8StringEncoding]; @@ -410,8 +405,7 @@ src.oneofBytes = [@"bar" dataUsingEncoding:NSUTF8StringEncoding]; [dst mergeFrom:src]; XCTAssertEqual(dst.oOneOfCase, Message2_O_OneOfCase_OneofBytes); - XCTAssertEqualObjects(dst.oneofBytes, - [@"bar" dataUsingEncoding:NSUTF8StringEncoding]); + XCTAssertEqualObjects(dst.oneofBytes, [@"bar" dataUsingEncoding:NSUTF8StringEncoding]); XCTAssertEqualObjects(dst.oneofString, oneofStringDefault); Message2_OneofGroup *group = [Message2_OneofGroup message]; @@ -483,8 +477,8 @@ dst.oneofEnum = Message3_Enum_Bar; -// Disable clang-format for the macros. -// clang-format off + // Disable clang-format for the macros. + // clang-format off //%PDDM-DEFINE MERGE3_TEST(SET_NAME, SET_VALUE, CLEARED_NAME, CLEARED_DEFAULT) //% src.oneof##SET_NAME = SET_VALUE; @@ -621,7 +615,7 @@ //%PDDM-EXPAND-END (14 expansions) -// clang-format on + // clang-format on NSString *oneofStringDefault = @""; NSData *oneofBytesDefault = [NSData data]; @@ -635,11 +629,9 @@ src.oneofBytes = [@"bar" dataUsingEncoding:NSUTF8StringEncoding]; [dst mergeFrom:src]; XCTAssertEqual(dst.oOneOfCase, Message3_O_OneOfCase_OneofBytes); - XCTAssertEqualObjects(dst.oneofBytes, - [@"bar" dataUsingEncoding:NSUTF8StringEncoding]); + XCTAssertEqualObjects(dst.oneofBytes, [@"bar" dataUsingEncoding:NSUTF8StringEncoding]); XCTAssertEqualObjects(dst.oneofString, oneofStringDefault); - Message3 *subMessage = [Message3 message]; subMessage.optionalInt32 = 777; src.oneofMessage = subMessage; diff --git a/objectivec/Tests/GPBMessageTests+Runtime.m b/objectivec/Tests/GPBMessageTests+Runtime.m index aefdf755df..af28af35e3 100644 --- a/objectivec/Tests/GPBMessageTests+Runtime.m +++ b/objectivec/Tests/GPBMessageTests+Runtime.m @@ -98,14 +98,10 @@ for (NSString *name in names) { // build the selector, i.e. - hasOptionalInt32/setHasOptionalInt32: - SEL hasSel = NSSelectorFromString( - [NSString stringWithFormat:@"hasOptional%@", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasOptional%@:", name]); - XCTAssertTrue([Message2 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertTrue([Message2 instancesRespondToSelector:setHasSel], @"field: %@", - name); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasOptional%@", name]); + SEL setHasSel = NSSelectorFromString([NSString stringWithFormat:@"setHasOptional%@:", name]); + XCTAssertTrue([Message2 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertTrue([Message2 instancesRespondToSelector:setHasSel], @"field: %@", name); } // Repeated fields @@ -114,33 +110,24 @@ for (NSString *name in names) { // build the selector, i.e. - hasRepeatedInt32Array/setHasRepeatedInt32Array: - SEL hasSel = NSSelectorFromString( - [NSString stringWithFormat:@"hasRepeated%@Array", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasRepeated%@Array:", name]); - XCTAssertFalse([Message2 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertFalse([Message2 instancesRespondToSelector:setHasSel], - @"field: %@", name); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasRepeated%@Array", name]); + SEL setHasSel = + NSSelectorFromString([NSString stringWithFormat:@"setHasRepeated%@Array:", name]); + XCTAssertFalse([Message2 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertFalse([Message2 instancesRespondToSelector:setHasSel], @"field: %@", name); // build the selector, i.e. - repeatedInt32Array_Count - SEL countSel = NSSelectorFromString( - [NSString stringWithFormat:@"repeated%@Array_Count", name]); - XCTAssertTrue([Message2 instancesRespondToSelector:countSel], @"field: %@", - name); + SEL countSel = NSSelectorFromString([NSString stringWithFormat:@"repeated%@Array_Count", name]); + XCTAssertTrue([Message2 instancesRespondToSelector:countSel], @"field: %@", name); } // OneOf fields - no has*/setHas* for (NSString *name in names) { // build the selector, i.e. - hasOneofInt32/setHasOneofInt32: - SEL hasSel = - NSSelectorFromString([NSString stringWithFormat:@"hasOneof%@", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasOneof%@:", name]); - XCTAssertFalse([Message2 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertFalse([Message2 instancesRespondToSelector:setHasSel], - @"field: %@", name); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasOneof%@", name]); + SEL setHasSel = NSSelectorFromString([NSString stringWithFormat:@"setHasOneof%@:", name]); + XCTAssertFalse([Message2 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertFalse([Message2 instancesRespondToSelector:setHasSel], @"field: %@", name); } // map<> fields @@ -148,44 +135,23 @@ // - *Count NSArray *mapNames = @[ - @"Int32Int32", - @"Int64Int64", - @"Uint32Uint32", - @"Uint64Uint64", - @"Sint32Sint32", - @"Sint64Sint64", - @"Fixed32Fixed32", - @"Fixed64Fixed64", - @"Sfixed32Sfixed32", - @"Sfixed64Sfixed64", - @"Int32Float", - @"Int32Double", - @"BoolBool", - @"StringString", - @"StringBytes", - @"StringMessage", - @"Int32Bytes", - @"Int32Enum", - @"Int32Message", + @"Int32Int32", @"Int64Int64", @"Uint32Uint32", @"Uint64Uint64", + @"Sint32Sint32", @"Sint64Sint64", @"Fixed32Fixed32", @"Fixed64Fixed64", + @"Sfixed32Sfixed32", @"Sfixed64Sfixed64", @"Int32Float", @"Int32Double", + @"BoolBool", @"StringString", @"StringBytes", @"StringMessage", + @"Int32Bytes", @"Int32Enum", @"Int32Message", ]; for (NSString *name in mapNames) { // build the selector, i.e. - hasMapInt32Int32/setHasMapInt32Int32: - SEL hasSel = NSSelectorFromString( - [NSString stringWithFormat:@"hasMap%@", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasMap%@:", name]); - XCTAssertFalse([Message2 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertFalse([Message2 instancesRespondToSelector:setHasSel], - @"field: %@", name); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasMap%@", name]); + SEL setHasSel = NSSelectorFromString([NSString stringWithFormat:@"setHasMap%@:", name]); + XCTAssertFalse([Message2 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertFalse([Message2 instancesRespondToSelector:setHasSel], @"field: %@", name); // build the selector, i.e. - mapInt32Int32Count - SEL countSel = NSSelectorFromString( - [NSString stringWithFormat:@"map%@_Count", name]); - XCTAssertTrue([Message2 instancesRespondToSelector:countSel], @"field: %@", - name); + SEL countSel = NSSelectorFromString([NSString stringWithFormat:@"map%@_Count", name]); + XCTAssertTrue([Message2 instancesRespondToSelector:countSel], @"field: %@", name); } - } - (void)testProto3HasMethodSupport { @@ -217,21 +183,15 @@ for (NSString *name in names) { // build the selector, i.e. - hasOptionalInt32/setHasOptionalInt32: - SEL hasSel = NSSelectorFromString( - [NSString stringWithFormat:@"hasOptional%@", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasOptional%@:", name]); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasOptional%@", name]); + SEL setHasSel = NSSelectorFromString([NSString stringWithFormat:@"setHasOptional%@:", name]); if ([name isEqual:@"Message"]) { // Sub messages/groups are the exception. - XCTAssertTrue([Message3 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertTrue([Message3 instancesRespondToSelector:setHasSel], - @"field: %@", name); + XCTAssertTrue([Message3 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertTrue([Message3 instancesRespondToSelector:setHasSel], @"field: %@", name); } else { - XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel], - @"field: %@", name); + XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel], @"field: %@", name); } } @@ -241,33 +201,24 @@ for (NSString *name in names) { // build the selector, i.e. - hasRepeatedInt32Array/setHasRepeatedInt32Array: - SEL hasSel = NSSelectorFromString( - [NSString stringWithFormat:@"hasRepeated%@Array", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasRepeated%@Array:", name]); - XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel], - @"field: %@", name); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasRepeated%@Array", name]); + SEL setHasSel = + NSSelectorFromString([NSString stringWithFormat:@"setHasRepeated%@Array:", name]); + XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel], @"field: %@", name); // build the selector, i.e. - repeatedInt32Array_Count - SEL countSel = NSSelectorFromString( - [NSString stringWithFormat:@"repeated%@Array_Count", name]); - XCTAssertTrue([Message3 instancesRespondToSelector:countSel], @"field: %@", - name); + SEL countSel = NSSelectorFromString([NSString stringWithFormat:@"repeated%@Array_Count", name]); + XCTAssertTrue([Message3 instancesRespondToSelector:countSel], @"field: %@", name); } // OneOf fields - no has*/setHas* for (NSString *name in names) { // build the selector, i.e. - hasOneofInt32/setHasOneofInt32: - SEL hasSel = - NSSelectorFromString([NSString stringWithFormat:@"hasOneof%@", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasOneof%@:", name]); - XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel], - @"field: %@", name); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasOneof%@", name]); + SEL setHasSel = NSSelectorFromString([NSString stringWithFormat:@"setHasOneof%@:", name]); + XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel], @"field: %@", name); } // Single Optional fields @@ -277,14 +228,10 @@ for (NSString *name in names) { // build the selector, i.e. - hasOptionalInt32/setHasOptionalInt32: - SEL hasSel = NSSelectorFromString( - [NSString stringWithFormat:@"hasOptional%@", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasOptional%@:", name]); - XCTAssertTrue([Message3Optional instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertTrue([Message3Optional instancesRespondToSelector:setHasSel], - @"field: %@", name); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasOptional%@", name]); + SEL setHasSel = NSSelectorFromString([NSString stringWithFormat:@"setHasOptional%@:", name]); + XCTAssertTrue([Message3Optional instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertTrue([Message3Optional instancesRespondToSelector:setHasSel], @"field: %@", name); } // map<> fields @@ -292,42 +239,22 @@ // - *Count NSArray *mapNames = @[ - @"Int32Int32", - @"Int64Int64", - @"Uint32Uint32", - @"Uint64Uint64", - @"Sint32Sint32", - @"Sint64Sint64", - @"Fixed32Fixed32", - @"Fixed64Fixed64", - @"Sfixed32Sfixed32", - @"Sfixed64Sfixed64", - @"Int32Float", - @"Int32Double", - @"BoolBool", - @"StringString", - @"StringBytes", - @"StringMessage", - @"Int32Bytes", - @"Int32Enum", - @"Int32Message", + @"Int32Int32", @"Int64Int64", @"Uint32Uint32", @"Uint64Uint64", + @"Sint32Sint32", @"Sint64Sint64", @"Fixed32Fixed32", @"Fixed64Fixed64", + @"Sfixed32Sfixed32", @"Sfixed64Sfixed64", @"Int32Float", @"Int32Double", + @"BoolBool", @"StringString", @"StringBytes", @"StringMessage", + @"Int32Bytes", @"Int32Enum", @"Int32Message", ]; for (NSString *name in mapNames) { // build the selector, i.e. - hasMapInt32Int32/setHasMapInt32Int32: - SEL hasSel = NSSelectorFromString( - [NSString stringWithFormat:@"hasMap%@", name]); - SEL setHasSel = NSSelectorFromString( - [NSString stringWithFormat:@"setHasMap%@:", name]); - XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@", - name); - XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel], - @"field: %@", name); + SEL hasSel = NSSelectorFromString([NSString stringWithFormat:@"hasMap%@", name]); + SEL setHasSel = NSSelectorFromString([NSString stringWithFormat:@"setHasMap%@:", name]); + XCTAssertFalse([Message3 instancesRespondToSelector:hasSel], @"field: %@", name); + XCTAssertFalse([Message3 instancesRespondToSelector:setHasSel], @"field: %@", name); // build the selector, i.e. - mapInt32Int32Count - SEL countSel = NSSelectorFromString( - [NSString stringWithFormat:@"map%@_Count", name]); - XCTAssertTrue([Message3 instancesRespondToSelector:countSel], @"field: %@", - name); + SEL countSel = NSSelectorFromString([NSString stringWithFormat:@"map%@_Count", name]); + XCTAssertTrue([Message3 instancesRespondToSelector:countSel], @"field: %@", name); } } @@ -337,8 +264,8 @@ // being true. // -// Disable clang-format for the macros. -// clang-format off + // Disable clang-format for the macros. + // clang-format off //%PDDM-DEFINE PROTO2_TEST_HAS_FIELD(FIELD, NON_ZERO_VALUE, ZERO_VALUE) //% { // optional##FIELD :: NON_ZERO_VALUE @@ -757,7 +684,7 @@ //%PDDM-EXPAND-END PROTO2_TEST_HAS_FIELDS() -// clang-format on + // clang-format on } - (void)testProto3SingleFieldHasBehavior { @@ -766,8 +693,8 @@ // being true. When set to the default, shouldn't be true. // -// Disable clang-format for the macros. -// clang-format off + // Disable clang-format for the macros. + // clang-format off //%PDDM-DEFINE PROTO3_TEST_HAS_FIELD(FIELD, NON_ZERO_VALUE, ZERO_VALUE) //% { // optional##FIELD @@ -1022,7 +949,7 @@ //%PDDM-EXPAND-END PROTO3_TEST_HAS_FIELDS() -// clang-format on + // clang-format on } - (void)testProto3SingleOptionalFieldHasBehavior { @@ -1030,8 +957,8 @@ // Setting to any value including the default (0) should result in true. // -// Disable clang-format for the macros. -// clang-format off + // Disable clang-format for the macros. + // clang-format off //%PDDM-DEFINE PROTO3_TEST_OPTIONAL_HAS_FIELD(FIELD, NON_ZERO_VALUE, ZERO_VALUE) //% { // optional##FIELD @@ -1268,7 +1195,7 @@ //%PDDM-EXPAND-END PROTO3_TEST_OPTIONAL_HAS_FIELDS() -// clang-format on + // clang-format on } - (void)testAccessingProto2UnknownEnumValues { @@ -1277,13 +1204,11 @@ // Set it to something non zero, try and confirm it doesn't change. msg.optionalEnum = Message2_Enum_Bar; - XCTAssertThrowsSpecificNamed(msg.optionalEnum = 666, NSException, - NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed(msg.optionalEnum = 666, NSException, NSInvalidArgumentException); XCTAssertEqual(msg.optionalEnum, Message2_Enum_Bar); msg.oneofEnum = Message2_Enum_Bar; - XCTAssertThrowsSpecificNamed(msg.oneofEnum = 666, NSException, - NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed(msg.oneofEnum = 666, NSException, NSInvalidArgumentException); XCTAssertEqual(msg.oneofEnum, Message2_Enum_Bar); [msg release]; @@ -1295,20 +1220,17 @@ // Set it to something non zero, try and confirm it doesn't change. msg.optionalEnum = Message3_Enum_Bar; - XCTAssertThrowsSpecificNamed(msg.optionalEnum = 666, NSException, - NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed(msg.optionalEnum = 666, NSException, NSInvalidArgumentException); XCTAssertEqual(msg.optionalEnum, Message3_Enum_Bar); msg.oneofEnum = Message3_Enum_Bar; - XCTAssertThrowsSpecificNamed(msg.oneofEnum = 666, NSException, - NSInvalidArgumentException); + XCTAssertThrowsSpecificNamed(msg.oneofEnum = 666, NSException, NSInvalidArgumentException); XCTAssertEqual(msg.oneofEnum, Message3_Enum_Bar); // Set via raw api to confirm it works. SetMessage3_OptionalEnum_RawValue(msg, 666); - XCTAssertEqual(msg.optionalEnum, - Message3_Enum_GPBUnrecognizedEnumeratorValue); + XCTAssertEqual(msg.optionalEnum, Message3_Enum_GPBUnrecognizedEnumeratorValue); XCTAssertEqual(Message3_OptionalEnum_RawValue(msg), 666); SetMessage3_OneofEnum_RawValue(msg, 666); @@ -1672,8 +1594,7 @@ XCTAssertEqual(msg.oneofDouble, 111.0); XCTAssertEqual(msg.oneofBool, YES); XCTAssertEqualObjects(msg.oneofString, oneofStringDefault); - XCTAssertEqualObjects(msg.oneofBytes, - [@"bar" dataUsingEncoding:NSUTF8StringEncoding]); + XCTAssertEqualObjects(msg.oneofBytes, [@"bar" dataUsingEncoding:NSUTF8StringEncoding]); XCTAssertNotNil(msg.oneofGroup); XCTAssertNotNil(msg.oneofMessage); XCTAssertEqual(msg.oneofEnum, Message2_Enum_Baz); @@ -1756,24 +1677,15 @@ msg = [[Message2 alloc] init]; int32_t values[] = { - Message2_O_OneOfCase_OneofInt32, - Message2_O_OneOfCase_OneofInt64, - Message2_O_OneOfCase_OneofUint32, - Message2_O_OneOfCase_OneofUint64, - Message2_O_OneOfCase_OneofSint32, - Message2_O_OneOfCase_OneofSint64, - Message2_O_OneOfCase_OneofFixed32, - Message2_O_OneOfCase_OneofFixed64, - Message2_O_OneOfCase_OneofSfixed32, - Message2_O_OneOfCase_OneofSfixed64, - Message2_O_OneOfCase_OneofFloat, - Message2_O_OneOfCase_OneofDouble, - Message2_O_OneOfCase_OneofBool, - Message2_O_OneOfCase_OneofString, - Message2_O_OneOfCase_OneofBytes, - Message2_O_OneOfCase_OneofGroup, - Message2_O_OneOfCase_OneofMessage, - Message2_O_OneOfCase_OneofEnum, + Message2_O_OneOfCase_OneofInt32, Message2_O_OneOfCase_OneofInt64, + Message2_O_OneOfCase_OneofUint32, Message2_O_OneOfCase_OneofUint64, + Message2_O_OneOfCase_OneofSint32, Message2_O_OneOfCase_OneofSint64, + Message2_O_OneOfCase_OneofFixed32, Message2_O_OneOfCase_OneofFixed64, + Message2_O_OneOfCase_OneofSfixed32, Message2_O_OneOfCase_OneofSfixed64, + Message2_O_OneOfCase_OneofFloat, Message2_O_OneOfCase_OneofDouble, + Message2_O_OneOfCase_OneofBool, Message2_O_OneOfCase_OneofString, + Message2_O_OneOfCase_OneofBytes, Message2_O_OneOfCase_OneofGroup, + Message2_O_OneOfCase_OneofMessage, Message2_O_OneOfCase_OneofEnum, }; for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) { @@ -1841,8 +1753,7 @@ // No need to check the value was set, the above tests did that. Message2_ClearOOneOfCase(msg); // Nothing in the case. - XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase_GPBUnsetOneOfCase, - "Loop: %zd", i); + XCTAssertEqual(msg.oOneOfCase, Message2_O_OneOfCase_GPBUnsetOneOfCase, "Loop: %zd", i); // Confirm everything is back to defaults after a clear. XCTAssertEqual(msg.oneofInt32, 100, "Loop: %zd", i); XCTAssertEqual(msg.oneofInt64, 101, "Loop: %zd", i); @@ -2210,8 +2121,7 @@ XCTAssertEqual(msg.oneofDouble, 0.0); XCTAssertEqual(msg.oneofBool, NO); XCTAssertEqualObjects(msg.oneofString, oneofStringDefault); - XCTAssertEqualObjects(msg.oneofBytes, - [@"bar" dataUsingEncoding:NSUTF8StringEncoding]); + XCTAssertEqualObjects(msg.oneofBytes, [@"bar" dataUsingEncoding:NSUTF8StringEncoding]); XCTAssertNotNil(msg.oneofMessage); XCTAssertEqual(msg.oneofEnum, Message3_Enum_Foo); XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase_OneofBytes); @@ -2266,23 +2176,15 @@ msg = [[Message3 alloc] init]; int32_t values[] = { - Message3_O_OneOfCase_OneofInt32, - Message3_O_OneOfCase_OneofInt64, - Message3_O_OneOfCase_OneofUint32, - Message3_O_OneOfCase_OneofUint64, - Message3_O_OneOfCase_OneofSint32, - Message3_O_OneOfCase_OneofSint64, - Message3_O_OneOfCase_OneofFixed32, - Message3_O_OneOfCase_OneofFixed64, - Message3_O_OneOfCase_OneofSfixed32, - Message3_O_OneOfCase_OneofSfixed64, - Message3_O_OneOfCase_OneofFloat, - Message3_O_OneOfCase_OneofDouble, - Message3_O_OneOfCase_OneofBool, - Message3_O_OneOfCase_OneofString, - Message3_O_OneOfCase_OneofBytes, - Message3_O_OneOfCase_OneofMessage, - Message3_O_OneOfCase_OneofEnum, + Message3_O_OneOfCase_OneofInt32, Message3_O_OneOfCase_OneofInt64, + Message3_O_OneOfCase_OneofUint32, Message3_O_OneOfCase_OneofUint64, + Message3_O_OneOfCase_OneofSint32, Message3_O_OneOfCase_OneofSint64, + Message3_O_OneOfCase_OneofFixed32, Message3_O_OneOfCase_OneofFixed64, + Message3_O_OneOfCase_OneofSfixed32, Message3_O_OneOfCase_OneofSfixed64, + Message3_O_OneOfCase_OneofFloat, Message3_O_OneOfCase_OneofDouble, + Message3_O_OneOfCase_OneofBool, Message3_O_OneOfCase_OneofString, + Message3_O_OneOfCase_OneofBytes, Message3_O_OneOfCase_OneofMessage, + Message3_O_OneOfCase_OneofEnum, }; for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) { @@ -2347,8 +2249,7 @@ // No need to check the value was set, the above tests did that. Message3_ClearOOneOfCase(msg); // Nothing in the case. - XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase_GPBUnsetOneOfCase, - "Loop: %zd", i); + XCTAssertEqual(msg.oOneOfCase, Message3_O_OneOfCase_GPBUnsetOneOfCase, "Loop: %zd", i); // Confirm everything is back to defaults after a clear. XCTAssertEqual(msg.oneofInt32, 0, "Loop: %zd", i); XCTAssertEqual(msg.oneofInt64, 0, "Loop: %zd", i); @@ -2375,7 +2276,6 @@ } - (void)testProto2OneofSetToDefault { - // proto3 doesn't normally write out zero (default) fields, but if they are // in a oneof it does. proto2 doesn't have this special behavior, but we // still confirm setting to the explicit default does set the case to be @@ -2387,24 +2287,24 @@ Message2 *msg = [[Message2 alloc] init]; int32_t values[] = { - Message2_O_OneOfCase_OneofInt32, - Message2_O_OneOfCase_OneofInt64, - Message2_O_OneOfCase_OneofUint32, - Message2_O_OneOfCase_OneofUint64, - Message2_O_OneOfCase_OneofSint32, - Message2_O_OneOfCase_OneofSint64, - Message2_O_OneOfCase_OneofFixed32, - Message2_O_OneOfCase_OneofFixed64, - Message2_O_OneOfCase_OneofSfixed32, - Message2_O_OneOfCase_OneofSfixed64, - Message2_O_OneOfCase_OneofFloat, - Message2_O_OneOfCase_OneofDouble, - Message2_O_OneOfCase_OneofBool, - Message2_O_OneOfCase_OneofString, - Message2_O_OneOfCase_OneofBytes, - // Skip group - // Skip message - Message2_O_OneOfCase_OneofEnum, + Message2_O_OneOfCase_OneofInt32, + Message2_O_OneOfCase_OneofInt64, + Message2_O_OneOfCase_OneofUint32, + Message2_O_OneOfCase_OneofUint64, + Message2_O_OneOfCase_OneofSint32, + Message2_O_OneOfCase_OneofSint64, + Message2_O_OneOfCase_OneofFixed32, + Message2_O_OneOfCase_OneofFixed64, + Message2_O_OneOfCase_OneofSfixed32, + Message2_O_OneOfCase_OneofSfixed64, + Message2_O_OneOfCase_OneofFloat, + Message2_O_OneOfCase_OneofDouble, + Message2_O_OneOfCase_OneofBool, + Message2_O_OneOfCase_OneofString, + Message2_O_OneOfCase_OneofBytes, + // Skip group + // Skip message + Message2_O_OneOfCase_OneofEnum, }; for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) { @@ -2505,7 +2405,6 @@ } - (void)testProto3OneofSetToZero { - // Normally setting a proto3 field to the zero value should result in it being // reset/cleared. But in a oneof, it still gets recorded so it can go out // over the wire and the other side can see what was set in the oneof. @@ -2516,23 +2415,15 @@ Message3 *msg = [[Message3 alloc] init]; int32_t values[] = { - Message3_O_OneOfCase_OneofInt32, - Message3_O_OneOfCase_OneofInt64, - Message3_O_OneOfCase_OneofUint32, - Message3_O_OneOfCase_OneofUint64, - Message3_O_OneOfCase_OneofSint32, - Message3_O_OneOfCase_OneofSint64, - Message3_O_OneOfCase_OneofFixed32, - Message3_O_OneOfCase_OneofFixed64, - Message3_O_OneOfCase_OneofSfixed32, - Message3_O_OneOfCase_OneofSfixed64, - Message3_O_OneOfCase_OneofFloat, - Message3_O_OneOfCase_OneofDouble, - Message3_O_OneOfCase_OneofBool, - Message3_O_OneOfCase_OneofString, - Message3_O_OneOfCase_OneofBytes, - Message3_O_OneOfCase_OneofMessage, - Message3_O_OneOfCase_OneofEnum, + Message3_O_OneOfCase_OneofInt32, Message3_O_OneOfCase_OneofInt64, + Message3_O_OneOfCase_OneofUint32, Message3_O_OneOfCase_OneofUint64, + Message3_O_OneOfCase_OneofSint32, Message3_O_OneOfCase_OneofSint64, + Message3_O_OneOfCase_OneofFixed32, Message3_O_OneOfCase_OneofFixed64, + Message3_O_OneOfCase_OneofSfixed32, Message3_O_OneOfCase_OneofSfixed64, + Message3_O_OneOfCase_OneofFloat, Message3_O_OneOfCase_OneofDouble, + Message3_O_OneOfCase_OneofBool, Message3_O_OneOfCase_OneofString, + Message3_O_OneOfCase_OneofBytes, Message3_O_OneOfCase_OneofMessage, + Message3_O_OneOfCase_OneofEnum, }; for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) { @@ -2663,27 +2554,19 @@ XCTAssertNotEqual(msg1.repeatedStringArray, msg2.repeatedStringArray); XCTAssertNotEqual(msg1.repeatedBytesArray, msg2.repeatedBytesArray); XCTAssertNotEqual(msg1.repeatedGroupArray, msg2.repeatedGroupArray); - XCTAssertNotEqual(msg1.repeatedNestedMessageArray, - msg2.repeatedNestedMessageArray); - XCTAssertNotEqual(msg1.repeatedForeignMessageArray, - msg2.repeatedForeignMessageArray); - XCTAssertNotEqual(msg1.repeatedImportMessageArray, - msg2.repeatedImportMessageArray); + XCTAssertNotEqual(msg1.repeatedNestedMessageArray, msg2.repeatedNestedMessageArray); + XCTAssertNotEqual(msg1.repeatedForeignMessageArray, msg2.repeatedForeignMessageArray); + XCTAssertNotEqual(msg1.repeatedImportMessageArray, msg2.repeatedImportMessageArray); XCTAssertNotEqual(msg1.repeatedNestedEnumArray, msg2.repeatedNestedEnumArray); - XCTAssertNotEqual(msg1.repeatedForeignEnumArray, - msg2.repeatedForeignEnumArray); + XCTAssertNotEqual(msg1.repeatedForeignEnumArray, msg2.repeatedForeignEnumArray); XCTAssertNotEqual(msg1.repeatedImportEnumArray, msg2.repeatedImportEnumArray); - XCTAssertNotEqual(msg1.repeatedStringPieceArray, - msg2.repeatedStringPieceArray); + XCTAssertNotEqual(msg1.repeatedStringPieceArray, msg2.repeatedStringPieceArray); XCTAssertNotEqual(msg1.repeatedCordArray, msg2.repeatedCordArray); for (int i = 0; i < repeatCount; i++) { - XCTAssertNotEqual(msg1.repeatedNestedMessageArray[i], - msg2.repeatedNestedMessageArray[i]); - XCTAssertNotEqual(msg1.repeatedForeignMessageArray[i], - msg2.repeatedForeignMessageArray[i]); - XCTAssertNotEqual(msg1.repeatedImportMessageArray[i], - msg2.repeatedImportMessageArray[i]); + XCTAssertNotEqual(msg1.repeatedNestedMessageArray[i], msg2.repeatedNestedMessageArray[i]); + XCTAssertNotEqual(msg1.repeatedForeignMessageArray[i], msg2.repeatedForeignMessageArray[i]); + XCTAssertNotEqual(msg1.repeatedImportMessageArray[i], msg2.repeatedImportMessageArray[i]); } } @@ -2729,7 +2612,7 @@ GPBFieldDescriptor *fieldDescriptor = [[message descriptor] fieldWithName:@"repeatedStringArray"]; XCTAssertNotNil(fieldDescriptor); NSMutableArray *fieldArray = GPBGetMessageRepeatedField(message, fieldDescriptor); - XCTAssertNotNil(fieldArray); // Should have autocreated. + XCTAssertNotNil(fieldArray); // Should have autocreated. XCTAssertTrue(fieldArray == message.repeatedStringArray); // Same pointer } @@ -2749,7 +2632,7 @@ GPBFieldDescriptor *fieldDescriptor = [[message descriptor] fieldWithName:@"mapStringString"]; XCTAssertNotNil(fieldDescriptor); NSMutableDictionary *fieldMap = GPBGetMessageMapField(message, fieldDescriptor); - XCTAssertNotNil(fieldMap); // Should have autocreated. + XCTAssertNotNil(fieldMap); // Should have autocreated. XCTAssertTrue(fieldMap == message.mapStringString); // Same pointer } diff --git a/objectivec/Tests/GPBMessageTests+Serialization.m b/objectivec/Tests/GPBMessageTests+Serialization.m index cfbc59718e..3c2381c3de 100644 --- a/objectivec/Tests/GPBMessageTests+Serialization.m +++ b/objectivec/Tests/GPBMessageTests+Serialization.m @@ -113,8 +113,8 @@ // Proto3 optionals should be just like proto2, zero values also get serialized. // -// Disable clang-format for the macros. -// clang-format off + // Disable clang-format for the macros. + // clang-format off //%PDDM-DEFINE PROTO3_TEST_SERIALIZE_OPTIONAL_FIELD(FIELD, ZERO_VALUE, EXPECTED_LEN) //% { // optional##FIELD @@ -419,16 +419,15 @@ //%PDDM-EXPAND-END PROTO3_TEST_SERIALIZE_OPTIONAL_FIELDS() -// clang-format on + // clang-format on } - (void)testProto2UnknownEnumToUnknownField { Message3 *orig = [[Message3 alloc] init]; orig.optionalEnum = Message3_Enum_Extra3; - orig.repeatedEnumArray = - [GPBEnumArray arrayWithValidationFunction:Message3_Enum_IsValidValue - rawValue:Message3_Enum_Extra3]; + orig.repeatedEnumArray = [GPBEnumArray arrayWithValidationFunction:Message3_Enum_IsValidValue + rawValue:Message3_Enum_Extra3]; orig.oneofEnum = Message3_Enum_Extra3; NSData *data = [orig data]; @@ -447,15 +446,12 @@ XCTAssertEqual([unknownFields countOfFields], 3U); XCTAssertTrue([unknownFields hasField:Message2_FieldNumber_OptionalEnum]); - XCTAssertTrue( - [unknownFields hasField:Message2_FieldNumber_RepeatedEnumArray]); + XCTAssertTrue([unknownFields hasField:Message2_FieldNumber_RepeatedEnumArray]); XCTAssertTrue([unknownFields hasField:Message2_FieldNumber_OneofEnum]); - GPBUnknownField *field = - [unknownFields getField:Message2_FieldNumber_OptionalEnum]; + GPBUnknownField *field = [unknownFields getField:Message2_FieldNumber_OptionalEnum]; XCTAssertEqual(field.varintList.count, 1U); - XCTAssertEqual([field.varintList valueAtIndex:0], - (uint64_t)Message3_Enum_Extra3); + XCTAssertEqual([field.varintList valueAtIndex:0], (uint64_t)Message3_Enum_Extra3); field = [unknownFields getField:Message2_FieldNumber_RepeatedEnumArray]; XCTAssertEqual(field.varintList.count, 1U); @@ -463,36 +459,32 @@ field = [unknownFields getField:Message2_FieldNumber_OneofEnum]; XCTAssertEqual(field.varintList.count, 1U); - XCTAssertEqual([field.varintList valueAtIndex:0], - (uint64_t)Message3_Enum_Extra3); + XCTAssertEqual([field.varintList valueAtIndex:0], (uint64_t)Message3_Enum_Extra3); [msg release]; [orig release]; } - (void)testProto3UnknownEnumPreserving { - UnknownEnumsMyMessagePlusExtra *orig = - [UnknownEnumsMyMessagePlusExtra message]; + UnknownEnumsMyMessagePlusExtra *orig = [UnknownEnumsMyMessagePlusExtra message]; orig.e = UnknownEnumsMyEnumPlusExtra_EExtra; - orig.repeatedEArray = [GPBEnumArray - arrayWithValidationFunction:UnknownEnumsMyEnumPlusExtra_IsValidValue - rawValue:UnknownEnumsMyEnumPlusExtra_EExtra]; - orig.repeatedPackedEArray = [GPBEnumArray - arrayWithValidationFunction:UnknownEnumsMyEnumPlusExtra_IsValidValue - rawValue:UnknownEnumsMyEnumPlusExtra_EExtra]; + orig.repeatedEArray = + [GPBEnumArray arrayWithValidationFunction:UnknownEnumsMyEnumPlusExtra_IsValidValue + rawValue:UnknownEnumsMyEnumPlusExtra_EExtra]; + orig.repeatedPackedEArray = + [GPBEnumArray arrayWithValidationFunction:UnknownEnumsMyEnumPlusExtra_IsValidValue + rawValue:UnknownEnumsMyEnumPlusExtra_EExtra]; orig.oneofE1 = UnknownEnumsMyEnumPlusExtra_EExtra; // Everything should be there via raw values. NSData *data = [orig data]; XCTAssertNotNil(data); - UnknownEnumsMyMessage *msg = - [UnknownEnumsMyMessage parseFromData:data error:NULL]; + UnknownEnumsMyMessage *msg = [UnknownEnumsMyMessage parseFromData:data error:NULL]; XCTAssertEqual(msg.e, UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); - XCTAssertEqual(UnknownEnumsMyMessage_E_RawValue(msg), - UnknownEnumsMyEnumPlusExtra_EExtra); + XCTAssertEqual(UnknownEnumsMyMessage_E_RawValue(msg), UnknownEnumsMyEnumPlusExtra_EExtra); XCTAssertEqual(msg.repeatedEArray.count, 1U); XCTAssertEqual([msg.repeatedEArray valueAtIndex:0], UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); @@ -503,10 +495,8 @@ UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); XCTAssertEqual([msg.repeatedPackedEArray rawValueAtIndex:0], (UnknownEnumsMyEnum)UnknownEnumsMyEnumPlusExtra_EExtra); - XCTAssertEqual(msg.oneofE1, - UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); - XCTAssertEqual(UnknownEnumsMyMessage_OneofE1_RawValue(msg), - UnknownEnumsMyEnumPlusExtra_EExtra); + XCTAssertEqual(msg.oneofE1, UnknownEnumsMyEnum_GPBUnrecognizedEnumeratorValue); + XCTAssertEqual(UnknownEnumsMyMessage_OneofE1_RawValue(msg), UnknownEnumsMyEnumPlusExtra_EExtra); // Everything should go out and come back. @@ -515,11 +505,9 @@ XCTAssertEqual(orig.e, UnknownEnumsMyEnumPlusExtra_EExtra); XCTAssertEqual(orig.repeatedEArray.count, 1U); - XCTAssertEqual([orig.repeatedEArray valueAtIndex:0], - UnknownEnumsMyEnumPlusExtra_EExtra); + XCTAssertEqual([orig.repeatedEArray valueAtIndex:0], UnknownEnumsMyEnumPlusExtra_EExtra); XCTAssertEqual(orig.repeatedPackedEArray.count, 1U); - XCTAssertEqual([orig.repeatedPackedEArray valueAtIndex:0], - UnknownEnumsMyEnumPlusExtra_EExtra); + XCTAssertEqual([orig.repeatedPackedEArray valueAtIndex:0], UnknownEnumsMyEnumPlusExtra_EExtra); XCTAssertEqual(orig.oneofE1, UnknownEnumsMyEnumPlusExtra_EExtra); } @@ -1057,15 +1045,13 @@ @"Data should differ (packed vs unpacked) use"); NSError *error = nil; - TestPackedTypes *packedParse = - [TestPackedTypes parseFromData:unpackedData error:&error]; + TestPackedTypes *packedParse = [TestPackedTypes parseFromData:unpackedData error:&error]; XCTAssertNotNil(packedParse); XCTAssertNil(error); XCTAssertEqualObjects(packedParse, packedOrig); error = nil; - TestUnpackedTypes *unpackedParsed = - [TestUnpackedTypes parseFromData:packedData error:&error]; + TestUnpackedTypes *unpackedParsed = [TestUnpackedTypes parseFromData:packedData error:&error]; XCTAssertNotNil(unpackedParsed); XCTAssertNil(error); XCTAssertEqualObjects(unpackedParsed, unpackedOrig); @@ -1122,8 +1108,7 @@ XCTAssertEqualObjects(fieldsData, extsData); NSError *error = nil; - TestPackedTypes *fieldsParse = - [TestPackedTypes parseFromData:extsData error:&error]; + TestPackedTypes *fieldsParse = [TestPackedTypes parseFromData:extsData error:&error]; XCTAssertNotNil(fieldsParse); XCTAssertNil(error); XCTAssertEqualObjects(fieldsParse, fieldsOrig); @@ -1153,8 +1138,7 @@ XCTAssertNotNil(extsData); XCTAssertEqualObjects(fieldsData, extsData); - TestUnpackedTypes *fieldsParse = - [TestUnpackedTypes parseFromData:extsData error:NULL]; + TestUnpackedTypes *fieldsParse = [TestUnpackedTypes parseFromData:extsData error:NULL]; XCTAssertNotNil(fieldsParse); XCTAssertEqualObjects(fieldsParse, fieldsOrig); @@ -1167,11 +1151,9 @@ } - (void)testErrorSubsectionInvalidLimit { - NSData *data = DataFromCStr( - "\x0A\x08\x0A\x07\x12\x04\x72\x02\x4B\x50\x12\x04\x72\x02\x4B\x50"); + NSData *data = DataFromCStr("\x0A\x08\x0A\x07\x12\x04\x72\x02\x4B\x50\x12\x04\x72\x02\x4B\x50"); NSError *error = nil; - NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data - error:&error]; + NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data error:&error]; XCTAssertNil(msg); XCTAssertNotNil(error); XCTAssertEqualObjects(error.domain, GPBCodedInputStreamErrorDomain); @@ -1181,8 +1163,7 @@ - (void)testErrorSubsectionLimitReached { NSData *data = DataFromCStr("\x0A\x06\x12\x03\x72\x02\x4B\x50"); NSError *error = nil; - NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data - error:&error]; + NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data error:&error]; XCTAssertNil(msg); XCTAssertNotNil(error); XCTAssertEqualObjects(error.domain, GPBCodedInputStreamErrorDomain); @@ -1212,8 +1193,7 @@ - (void)testErrorInvalidSize { NSData *data = DataFromCStr("\x72\x03\x4B\x50"); NSError *error = nil; - NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data - error:&error]; + NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data error:&error]; XCTAssertNil(msg); XCTAssertNotNil(error); XCTAssertEqualObjects(error.domain, GPBCodedInputStreamErrorDomain); @@ -1223,8 +1203,7 @@ - (void)testErrorInvalidTag { NSData *data = DataFromCStr("\x0F"); NSError *error = nil; - NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data - error:&error]; + NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data error:&error]; XCTAssertNil(msg); XCTAssertNotNil(error); XCTAssertEqualObjects(error.domain, GPBCodedInputStreamErrorDomain); @@ -1234,12 +1213,7 @@ - (void)testZeroFieldNum { // These are ConformanceTestSuite::TestIllegalTags. - const char *tests[] = { - "\1DEADBEEF", - "\2\1\1", - "\3\4", - "\5DEAD" - }; + const char *tests[] = {"\1DEADBEEF", "\2\1\1", "\3\4", "\5DEAD"}; for (size_t i = 0; i < GPBARRAYSIZE(tests); ++i) { NSData *data = DataFromCStr(tests[i]); @@ -1267,27 +1241,25 @@ } - (void)testErrorRecursionDepthReached { - NSData *data = DataFromCStr( - "\x0A\xF2\x01\x0A\xEF\x01\x0A\xEC\x01\x0A\xE9\x01\x0A\xE6\x01" - "\x0A\xE3\x01\x0A\xE0\x01\x0A\xDD\x01\x0A\xDA\x01\x0A\xD7\x01" - "\x0A\xD4\x01\x0A\xD1\x01\x0A\xCE\x01\x0A\xCB\x01\x0A\xC8\x01" - "\x0A\xC5\x01\x0A\xC2\x01\x0A\xBF\x01\x0A\xBC\x01\x0A\xB9\x01" - "\x0A\xB6\x01\x0A\xB3\x01\x0A\xB0\x01\x0A\xAD\x01\x0A\xAA\x01" - "\x0A\xA7\x01\x0A\xA4\x01\x0A\xA1\x01\x0A\x9E\x01\x0A\x9B\x01" - "\x0A\x98\x01\x0A\x95\x01\x0A\x92\x01\x0A\x8F\x01\x0A\x8C\x01" - "\x0A\x89\x01\x0A\x86\x01\x0A\x83\x01\x0A\x80\x01\x0A\x7E" - "\x0A\x7C\x0A\x7A\x0A\x78\x0A\x76\x0A\x74\x0A\x72\x0A\x70" - "\x0A\x6E\x0A\x6C\x0A\x6A\x0A\x68\x0A\x66\x0A\x64\x0A\x62" - "\x0A\x60\x0A\x5E\x0A\x5C\x0A\x5A\x0A\x58\x0A\x56\x0A\x54" - "\x0A\x52\x0A\x50\x0A\x4E\x0A\x4C\x0A\x4A\x0A\x48\x0A\x46" - "\x0A\x44\x0A\x42\x0A\x40\x0A\x3E\x0A\x3C\x0A\x3A\x0A\x38" - "\x0A\x36\x0A\x34\x0A\x32\x0A\x30\x0A\x2E\x0A\x2C\x0A\x2A" - "\x0A\x28\x0A\x26\x0A\x24\x0A\x22\x0A\x20\x0A\x1E\x0A\x1C" - "\x0A\x1A\x0A\x18\x0A\x16\x0A\x14\x0A\x12\x0A\x10\x0A\x0E" - "\x0A\x0C\x0A\x0A\x0A\x08\x0A\x06\x12\x04\x72\x02\x4B\x50"); + NSData *data = DataFromCStr("\x0A\xF2\x01\x0A\xEF\x01\x0A\xEC\x01\x0A\xE9\x01\x0A\xE6\x01" + "\x0A\xE3\x01\x0A\xE0\x01\x0A\xDD\x01\x0A\xDA\x01\x0A\xD7\x01" + "\x0A\xD4\x01\x0A\xD1\x01\x0A\xCE\x01\x0A\xCB\x01\x0A\xC8\x01" + "\x0A\xC5\x01\x0A\xC2\x01\x0A\xBF\x01\x0A\xBC\x01\x0A\xB9\x01" + "\x0A\xB6\x01\x0A\xB3\x01\x0A\xB0\x01\x0A\xAD\x01\x0A\xAA\x01" + "\x0A\xA7\x01\x0A\xA4\x01\x0A\xA1\x01\x0A\x9E\x01\x0A\x9B\x01" + "\x0A\x98\x01\x0A\x95\x01\x0A\x92\x01\x0A\x8F\x01\x0A\x8C\x01" + "\x0A\x89\x01\x0A\x86\x01\x0A\x83\x01\x0A\x80\x01\x0A\x7E" + "\x0A\x7C\x0A\x7A\x0A\x78\x0A\x76\x0A\x74\x0A\x72\x0A\x70" + "\x0A\x6E\x0A\x6C\x0A\x6A\x0A\x68\x0A\x66\x0A\x64\x0A\x62" + "\x0A\x60\x0A\x5E\x0A\x5C\x0A\x5A\x0A\x58\x0A\x56\x0A\x54" + "\x0A\x52\x0A\x50\x0A\x4E\x0A\x4C\x0A\x4A\x0A\x48\x0A\x46" + "\x0A\x44\x0A\x42\x0A\x40\x0A\x3E\x0A\x3C\x0A\x3A\x0A\x38" + "\x0A\x36\x0A\x34\x0A\x32\x0A\x30\x0A\x2E\x0A\x2C\x0A\x2A" + "\x0A\x28\x0A\x26\x0A\x24\x0A\x22\x0A\x20\x0A\x1E\x0A\x1C" + "\x0A\x1A\x0A\x18\x0A\x16\x0A\x14\x0A\x12\x0A\x10\x0A\x0E" + "\x0A\x0C\x0A\x0A\x0A\x08\x0A\x06\x12\x04\x72\x02\x4B\x50"); NSError *error = nil; - NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data - error:&error]; + NestedTestAllTypes *msg = [NestedTestAllTypes parseFromData:data error:&error]; XCTAssertNil(msg); XCTAssertNotNil(error); XCTAssertEqualObjects(error.domain, GPBCodedInputStreamErrorDomain); @@ -1298,9 +1270,7 @@ NSData *data = DataFromCStr("\xFF\xFF\xFF\xFF\x0F"); GPBCodedInputStream *input = [GPBCodedInputStream streamWithData:data]; NSError *error; - [GPBMessage parseDelimitedFromCodedInputStream:input - extensionRegistry:nil - error:&error]; + [GPBMessage parseDelimitedFromCodedInputStream:input extensionRegistry:nil error:&error]; XCTAssertNil(error); } @@ -1436,10 +1406,8 @@ initWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue] autorelease]; orig.unknownMapField = [[[GPBInt32EnumDictionary alloc] initWithValidationFunction:Proto2MapEnumPlusExtra_IsValidValue] autorelease]; - [orig.knownMapField setEnum:Proto2MapEnumPlusExtra_EProto2MapEnumFoo - forKey:0]; - [orig.unknownMapField setEnum:Proto2MapEnumPlusExtra_EProto2MapEnumExtra - forKey:0]; + [orig.knownMapField setEnum:Proto2MapEnumPlusExtra_EProto2MapEnumFoo forKey:0]; + [orig.unknownMapField setEnum:Proto2MapEnumPlusExtra_EProto2MapEnumExtra forKey:0]; NSData *data = [orig data]; XCTAssertNotNil(data); @@ -1451,8 +1419,7 @@ XCTAssertEqual(msg1.unknownFields.countOfFields, 1U); data = [msg1 data]; - TestEnumMapPlusExtra *msg2 = - [TestEnumMapPlusExtra parseFromData:data error:NULL]; + TestEnumMapPlusExtra *msg2 = [TestEnumMapPlusExtra parseFromData:data error:NULL]; val = -1; XCTAssertEqual(msg2.knownMapField.count, 1U); XCTAssertTrue([msg2.knownMapField getEnum:&val forKey:0]); diff --git a/objectivec/Tests/GPBMessageTests.m b/objectivec/Tests/GPBMessageTests.m index 202d1ef8ce..cf0474e898 100644 --- a/objectivec/Tests/GPBMessageTests.m +++ b/objectivec/Tests/GPBMessageTests.m @@ -36,12 +36,12 @@ #import "GPBDescriptor.h" #import "GPBDictionary_PackagePrivate.h" #import "GPBMessage_PackagePrivate.h" -#import "GPBUnknownField_PackagePrivate.h" #import "GPBUnknownFieldSet_PackagePrivate.h" +#import "GPBUnknownField_PackagePrivate.h" #import "objectivec/Tests/Unittest.pbobjc.h" +#import "objectivec/Tests/UnittestImport.pbobjc.h" #import "objectivec/Tests/UnittestObjc.pbobjc.h" #import "objectivec/Tests/UnittestObjcOptions.pbobjc.h" -#import "objectivec/Tests/UnittestImport.pbobjc.h" // Helper class to test KVO. @interface GPBKVOTestObserver : NSObject { @@ -49,7 +49,7 @@ NSString *keyPath_; } -@property (nonatomic) BOOL didObserve; +@property(nonatomic) BOOL didObserve; - (id)initWithObservee:(id)observee keyPath:(NSString *)keyPath; @end @@ -76,8 +76,7 @@ - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change - context:(void *)context -{ + context:(void *)context { #pragma unused(object) #pragma unused(change) #pragma unused(context) @@ -156,12 +155,9 @@ [message setExtension:[UnittestRoot optionalStringExtension] value:@"foo"]; ForeignMessage *foreignMessage = [ForeignMessage message]; foreignMessage.c = 4; - [message setExtension:[UnittestRoot optionalForeignMessageExtension] - value:foreignMessage]; - TestAllTypes_NestedMessage *nestedMessage = - [TestAllTypes_NestedMessage message]; - [message setExtension:[UnittestRoot optionalNestedMessageExtension] - value:nestedMessage]; + [message setExtension:[UnittestRoot optionalForeignMessageExtension] value:foreignMessage]; + TestAllTypes_NestedMessage *nestedMessage = [TestAllTypes_NestedMessage message]; + [message setExtension:[UnittestRoot optionalNestedMessageExtension] value:nestedMessage]; return message; } @@ -170,13 +166,10 @@ [message setExtension:[UnittestRoot optionalInt64Extension] value:@6]; [message setExtension:[UnittestRoot optionalStringExtension] value:@"bar"]; ForeignMessage *foreignMessage = [ForeignMessage message]; - [message setExtension:[UnittestRoot optionalForeignMessageExtension] - value:foreignMessage]; - TestAllTypes_NestedMessage *nestedMessage = - [TestAllTypes_NestedMessage message]; + [message setExtension:[UnittestRoot optionalForeignMessageExtension] value:foreignMessage]; + TestAllTypes_NestedMessage *nestedMessage = [TestAllTypes_NestedMessage message]; nestedMessage.bb = 7; - [message setExtension:[UnittestRoot optionalNestedMessageExtension] - value:nestedMessage]; + [message setExtension:[UnittestRoot optionalNestedMessageExtension] value:nestedMessage]; return message; } @@ -187,13 +180,10 @@ [message setExtension:[UnittestRoot optionalStringExtension] value:@"bar"]; ForeignMessage *foreignMessage = [ForeignMessage message]; foreignMessage.c = 4; - [message setExtension:[UnittestRoot optionalForeignMessageExtension] - value:foreignMessage]; - TestAllTypes_NestedMessage *nestedMessage = - [TestAllTypes_NestedMessage message]; + [message setExtension:[UnittestRoot optionalForeignMessageExtension] value:foreignMessage]; + TestAllTypes_NestedMessage *nestedMessage = [TestAllTypes_NestedMessage message]; nestedMessage.bb = 7; - [message setExtension:[UnittestRoot optionalNestedMessageExtension] - value:nestedMessage]; + [message setExtension:[UnittestRoot optionalNestedMessageExtension] value:nestedMessage]; return message; } @@ -211,11 +201,9 @@ result = [[self.mergeDestinationWithoutForeignMessageIvar copy] autorelease]; [result mergeFrom:self.mergeSource]; resultData = [result data]; - mergeResultData = - [self.mergeResultForDestinationWithoutForeignMessageIvar data]; + mergeResultData = [self.mergeResultForDestinationWithoutForeignMessageIvar data]; XCTAssertEqualObjects(resultData, mergeResultData); - XCTAssertEqualObjects( - result, self.mergeResultForDestinationWithoutForeignMessageIvar); + XCTAssertEqualObjects(result, self.mergeResultForDestinationWithoutForeignMessageIvar); // Test when destination is empty. // The result must is same as the source. @@ -239,8 +227,7 @@ result = [self mergeExtensionsDestination]; NSData *data = [[self mergeExtensionsSource] data]; XCTAssertNotNil(data); - [result mergeFromData:data - extensionRegistry:[UnittestRoot extensionRegistry]]; + [result mergeFromData:data extensionRegistry:[UnittestRoot extensionRegistry]]; resultData = [result data]; XCTAssertEqualObjects(resultData, mergeResultData); XCTAssertEqualObjects(result, [self mergeExtensionsResult]); @@ -306,16 +293,13 @@ [message setExtension:[TestRequired single] value:[TestRequired message]]; XCTAssertFalse(message.initialized); - [message setExtension:[TestRequired single] - value:self.testRequiredInitialized]; + [message setExtension:[TestRequired single] value:self.testRequiredInitialized]; XCTAssertTrue(message.initialized); [message addExtension:[TestRequired multi] value:[TestRequired message]]; XCTAssertFalse(message.initialized); - [message setExtension:[TestRequired multi] - index:0 - value:self.testRequiredInitialized]; + [message setExtension:[TestRequired multi] index:0 value:self.testRequiredInitialized]; XCTAssertTrue(message.initialized); } @@ -367,8 +351,7 @@ - (void)testParseUninitialized { NSError *error = nil; - TestRequired *msg = - [TestRequired parseFromData:GPBEmptyNSData() error:&error]; + TestRequired *msg = [TestRequired parseFromData:GPBEmptyNSData() error:&error]; // In DEBUG, the parse will fail, but in non DEBUG, it passes because // the check isn't done (for speed). #ifdef DEBUG @@ -388,8 +371,7 @@ - (void)testCoding { GPBMessage *original = [self mergeResult]; - NSData *data = - [NSKeyedArchiver archivedDataWithRootObject:original]; + NSData *data = [NSKeyedArchiver archivedDataWithRootObject:original]; id unarchivedObject = [NSKeyedUnarchiver unarchiveObjectWithData:data]; XCTAssertEqualObjects(unarchivedObject, original); @@ -411,8 +393,7 @@ NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data]; [unarchiver setRequiresSecureCoding:YES]; - id unarchivedObject = [unarchiver decodeObjectOfClass:[GPBMessage class] - forKey:key]; + id unarchivedObject = [unarchiver decodeObjectOfClass:[GPBMessage class] forKey:key]; [unarchiver finishDecoding]; XCTAssertEqualObjects(unarchivedObject, original); @@ -485,9 +466,7 @@ - (void)testKVOBasic { TestAllTypes *message = [TestAllTypes message]; GPBKVOTestObserver *observer = - [[[GPBKVOTestObserver alloc] initWithObservee:message - keyPath:@"optionalString"] - autorelease]; + [[[GPBKVOTestObserver alloc] initWithObservee:message keyPath:@"optionalString"] autorelease]; XCTAssertFalse(observer.didObserve); message.defaultString = @"Hello"; XCTAssertFalse(observer.didObserve); @@ -499,12 +478,10 @@ TestAllTypes *message = [TestAllTypes message]; GPBKVOTestObserver *autocreateObserver = [[[GPBKVOTestObserver alloc] initWithObservee:message - keyPath:@"optionalImportMessage"] - autorelease]; - GPBKVOTestObserver *innerFieldObserver = - [[[GPBKVOTestObserver alloc] initWithObservee:message - keyPath:@"optionalImportMessage.d"] - autorelease]; + keyPath:@"optionalImportMessage"] autorelease]; + GPBKVOTestObserver *innerFieldObserver = + [[[GPBKVOTestObserver alloc] initWithObservee:message + keyPath:@"optionalImportMessage.d"] autorelease]; XCTAssertFalse(autocreateObserver.didObserve); XCTAssertFalse(innerFieldObserver.didObserve); @@ -536,10 +513,8 @@ TestAllTypes *message = [TestAllTypes message]; [self setAllFields:message repeatedCount:kGPBDefaultRepeatCount]; - GPBUnknownFieldSet *unknownFields = - [[[GPBUnknownFieldSet alloc] init] autorelease]; - GPBUnknownField *field = - [[[GPBUnknownField alloc] initWithNumber:2] autorelease]; + GPBUnknownFieldSet *unknownFields = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownField *field = [[[GPBUnknownField alloc] initWithNumber:2] autorelease]; [field addVarint:2]; [unknownFields addField:field]; field = [[[GPBUnknownField alloc] initWithNumber:3] autorelease]; @@ -567,8 +542,7 @@ TestAllTypes *message = [TestAllTypes message]; GPBDescriptor *descriptor = [[message class] descriptor]; XCTAssertNotNil(descriptor); - GPBFieldDescriptor *fieldDescriptor = - [descriptor fieldWithName:@"defaultInt32"]; + GPBFieldDescriptor *fieldDescriptor = [descriptor fieldWithName:@"defaultInt32"]; XCTAssertNotNil(fieldDescriptor); GPBGenericValue defaultValue = [fieldDescriptor defaultValue]; [message setDefaultInt32:defaultValue.valueInt32]; @@ -679,8 +653,7 @@ TestAllTypes *message = [TestAllTypes message]; [self setAllFields:message repeatedCount:kGPBDefaultRepeatCount]; [self modifyRepeatedFields:message]; - [self assertRepeatedFieldsModified:message - repeatedCount:kGPBDefaultRepeatCount]; + [self assertRepeatedFieldsModified:message repeatedCount:kGPBDefaultRepeatCount]; } - (void)testClear { @@ -712,19 +685,16 @@ GPBMessage *message2 = [TestAllExtensions message]; [message2 addExtension:[UnittestRoot repeatedInt32Extension] value:@1]; - XCTAssertEqual( - [[message2 getExtension:[UnittestRoot repeatedInt32Extension]] count], - (NSUInteger)1); + XCTAssertEqual([[message2 getExtension:[UnittestRoot repeatedInt32Extension]] count], + (NSUInteger)1); [message2 clearExtension:[UnittestRoot repeatedInt32Extension]]; - XCTAssertEqual( - [[message2 getExtension:[UnittestRoot repeatedInt32Extension]] count], - (NSUInteger)0); + XCTAssertEqual([[message2 getExtension:[UnittestRoot repeatedInt32Extension]] count], + (NSUInteger)0); // Clearing an unset extension field shouldn't make the target message // visible. GPBMessage *message3 = [TestAllExtensions message]; - GPBMessage *extension_msg = - [message3 getExtension:[UnittestObjcRoot recursiveExtension]]; + GPBMessage *extension_msg = [message3 getExtension:[UnittestObjcRoot recursiveExtension]]; XCTAssertFalse([message3 hasExtension:[UnittestObjcRoot recursiveExtension]]); [extension_msg clearExtension:[UnittestRoot optionalInt32Extension]]; XCTAssertFalse([message3 hasExtension:[UnittestObjcRoot recursiveExtension]]); @@ -745,15 +715,11 @@ // They should auto create something when fetched. TestAllTypes_OptionalGroup *optionalGroup = [message.optionalGroup retain]; - TestAllTypes_NestedMessage *optionalNestedMessage = - [message.optionalNestedMessage retain]; - ForeignMessage *optionalForeignMessage = - [message.optionalForeignMessage retain]; + TestAllTypes_NestedMessage *optionalNestedMessage = [message.optionalNestedMessage retain]; + ForeignMessage *optionalForeignMessage = [message.optionalForeignMessage retain]; ImportMessage *optionalImportMessage = [message.optionalImportMessage retain]; - PublicImportMessage *optionalPublicImportMessage = - [message.optionalPublicImportMessage retain]; - TestAllTypes_NestedMessage *optionalLazyMessage = - [message.optionalLazyMessage retain]; + PublicImportMessage *optionalPublicImportMessage = [message.optionalPublicImportMessage retain]; + TestAllTypes_NestedMessage *optionalLazyMessage = [message.optionalLazyMessage retain]; XCTAssertNotNil(optionalGroup); XCTAssertNotNil(optionalNestedMessage); @@ -779,8 +745,7 @@ XCTAssertEqual(message.optionalNestedMessage, optionalNestedMessage); XCTAssertEqual(message.optionalForeignMessage, optionalForeignMessage); XCTAssertEqual(message.optionalImportMessage, optionalImportMessage); - XCTAssertEqual(message.optionalPublicImportMessage, - optionalPublicImportMessage); + XCTAssertEqual(message.optionalPublicImportMessage, optionalPublicImportMessage); XCTAssertEqual(message.optionalLazyMessage, optionalLazyMessage); // And the default objects for a second message should be distinct (again, @@ -793,8 +758,7 @@ XCTAssertNotEqual(message2.optionalNestedMessage, optionalNestedMessage); XCTAssertNotEqual(message2.optionalForeignMessage, optionalForeignMessage); XCTAssertNotEqual(message2.optionalImportMessage, optionalImportMessage); - XCTAssertNotEqual(message2.optionalPublicImportMessage, - optionalPublicImportMessage); + XCTAssertNotEqual(message2.optionalPublicImportMessage, optionalPublicImportMessage); XCTAssertNotEqual(message2.optionalLazyMessage, optionalLazyMessage); // Setting the values to nil will clear the has flag, and on next access you @@ -819,8 +783,7 @@ XCTAssertNotEqual(message.optionalNestedMessage, optionalNestedMessage); XCTAssertNotEqual(message.optionalForeignMessage, optionalForeignMessage); XCTAssertNotEqual(message.optionalImportMessage, optionalImportMessage); - XCTAssertNotEqual(message.optionalPublicImportMessage, - optionalPublicImportMessage); + XCTAssertNotEqual(message.optionalPublicImportMessage, optionalPublicImportMessage); XCTAssertNotEqual(message.optionalLazyMessage, optionalLazyMessage); [optionalGroup release]; @@ -853,8 +816,7 @@ XCTAssertFalse([message2 hasOptionalNestedMessage]); // Intentionally doing a pointer comparison. - XCTAssertNotEqual(message.optionalNestedMessage, - message2.optionalNestedMessage); + XCTAssertNotEqual(message.optionalNestedMessage, message2.optionalNestedMessage); } - (void)testClearAutocreatedSubmessage { @@ -880,10 +842,9 @@ ForeignMessage *subMessage; @autoreleasepool { TestAllTypes *message2 = [TestAllTypes message]; - subMessage = message2.optionalForeignMessage; // Autocreated + subMessage = message2.optionalForeignMessage; // Autocreated message.optionalForeignMessage = subMessage; - XCTAssertTrue(GPBWasMessageAutocreatedBy(message.optionalForeignMessage, - message2)); + XCTAssertTrue(GPBWasMessageAutocreatedBy(message.optionalForeignMessage, message2)); } // Should be the same object, and should still be live. @@ -1019,8 +980,7 @@ // Setting autocreated submessage to another value should cause the old one to // lose its creator. TestAllTypes *message = [TestAllTypes message]; - TestAllTypes_NestedMessage *nestedMessage = - [message.optionalNestedMessage retain]; + TestAllTypes_NestedMessage *nestedMessage = [message.optionalNestedMessage retain]; message.optionalNestedMessage = [TestAllTypes_NestedMessage message]; XCTAssertTrue([message hasOptionalNestedMessage]); @@ -1039,8 +999,7 @@ XCTAssertNil(message.optionalNestedMessage.unknownFields); XCTAssertFalse([message hasOptionalNestedMessage]); - GPBUnknownFieldSet *unknownFields = - [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet *unknownFields = [[[GPBUnknownFieldSet alloc] init] autorelease]; message.optionalNestedMessage.unknownFields = unknownFields; XCTAssertTrue([message hasOptionalNestedMessage]); @@ -1089,10 +1048,8 @@ - (void)testDefaultingArrays { // Basic tests for default creation of arrays in a message. - TestRecursiveMessageWithRepeatedField *message = - [TestRecursiveMessageWithRepeatedField message]; - TestRecursiveMessageWithRepeatedField *message2 = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message = [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message2 = [TestRecursiveMessageWithRepeatedField message]; // Simply accessing the array should not make any fields visible. XCTAssertNotNil(message.a.a.iArray); @@ -1159,11 +1116,9 @@ XCTAssertNotNil(message.repeatedStringArray); TestAllTypes *message4 = [[message3 copy] autorelease]; XCTAssertNotEqual(message3.repeatedInt32Array, message4.repeatedInt32Array); - XCTAssertEqualObjects(message3.repeatedInt32Array, - message4.repeatedInt32Array); + XCTAssertEqualObjects(message3.repeatedInt32Array, message4.repeatedInt32Array); XCTAssertNotEqual(message3.repeatedStringArray, message4.repeatedStringArray); - XCTAssertEqualObjects(message3.repeatedStringArray, - message4.repeatedStringArray); + XCTAssertEqualObjects(message3.repeatedStringArray, message4.repeatedStringArray); } - (void)testAutocreatedArrayRetain { @@ -1176,18 +1131,13 @@ message.repeatedStringArray = message2.repeatedStringArray; // Pointer conparision XCTAssertEqual(message.repeatedInt32Array->_autocreator, message2); - XCTAssertTrue([message.repeatedStringArray - isKindOfClass:[GPBAutocreatedArray class]]); - XCTAssertEqual( - ((GPBAutocreatedArray *)message.repeatedStringArray)->_autocreator, - message2); + XCTAssertTrue([message.repeatedStringArray isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertEqual(((GPBAutocreatedArray *)message.repeatedStringArray)->_autocreator, message2); } XCTAssertNil(message.repeatedInt32Array->_autocreator); - XCTAssertTrue( - [message.repeatedStringArray isKindOfClass:[GPBAutocreatedArray class]]); - XCTAssertNil( - ((GPBAutocreatedArray *)message.repeatedStringArray)->_autocreator); + XCTAssertTrue([message.repeatedStringArray isKindOfClass:[GPBAutocreatedArray class]]); + XCTAssertNil(((GPBAutocreatedArray *)message.repeatedStringArray)->_autocreator); } - (void)testSetNilAutocreatedArray { @@ -1245,8 +1195,7 @@ XCTAssertNotNil(message.a); XCTAssertNotNil(message.a.strArray); XCTAssertFalse([message hasA]); - GPBAutocreatedArray *strArray = - (GPBAutocreatedArray *)[message.a.strArray retain]; + GPBAutocreatedArray *strArray = (GPBAutocreatedArray *)[message.a.strArray retain]; XCTAssertTrue([strArray isKindOfClass:[GPBAutocreatedArray class]]); XCTAssertEqual(strArray->_autocreator, message.a); // Pointer comparison message.a.strArray = [NSMutableArray arrayWithObject:@"foo"]; @@ -1286,8 +1235,7 @@ - (void)testAutocreatedArrayRemoveAllValues { // Calling removeAllValues on autocreated array should not cause it to be // visible. - TestRecursiveMessageWithRepeatedField *message = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message = [TestRecursiveMessageWithRepeatedField message]; [message.a.iArray removeAll]; XCTAssertFalse([message hasA]); [message.a.strArray removeAllObjects]; @@ -1296,10 +1244,8 @@ - (void)testDefaultingMaps { // Basic tests for default creation of maps in a message. - TestRecursiveMessageWithRepeatedField *message = - [TestRecursiveMessageWithRepeatedField message]; - TestRecursiveMessageWithRepeatedField *message2 = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message = [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message2 = [TestRecursiveMessageWithRepeatedField message]; // Simply accessing the map should not make any fields visible. XCTAssertNotNil(message.a.a.iToI); @@ -1349,28 +1295,23 @@ - (void)testAutocreatedMapCopy { // Copy should not copy autocreated maps. - TestRecursiveMessageWithRepeatedField *message = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message = [TestRecursiveMessageWithRepeatedField message]; XCTAssertNotNil(message.strToStr); XCTAssertNotNil(message.iToI); - TestRecursiveMessageWithRepeatedField *message2 = - [[message copy] autorelease]; + TestRecursiveMessageWithRepeatedField *message2 = [[message copy] autorelease]; // Pointer conparisions. XCTAssertNotEqual(message.strToStr, message2.strToStr); XCTAssertNotEqual(message.iToI, message2.iToI); // Mutable copy should copy empty arrays that were explicitly set (end up // with different objects that are equal). - TestRecursiveMessageWithRepeatedField *message3 = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message3 = [TestRecursiveMessageWithRepeatedField message]; message3.iToI = [[[GPBInt32Int32Dictionary alloc] init] autorelease]; [message3.iToI setInt32:10 forKey:20]; - message3.strToStr = - [NSMutableDictionary dictionaryWithObject:@"abc" forKey:@"123"]; + message3.strToStr = [NSMutableDictionary dictionaryWithObject:@"abc" forKey:@"123"]; XCTAssertNotNil(message.iToI); XCTAssertNotNil(message.iToI); - TestRecursiveMessageWithRepeatedField *message4 = - [[message3 copy] autorelease]; + TestRecursiveMessageWithRepeatedField *message4 = [[message3 copy] autorelease]; XCTAssertNotEqual(message3.iToI, message4.iToI); XCTAssertEqualObjects(message3.iToI, message4.iToI); XCTAssertNotEqual(message3.strToStr, message4.strToStr); @@ -1379,8 +1320,7 @@ - (void)testAutocreatedMapRetain { // Should be able to retain autocreated map while the creator is dealloced. - TestRecursiveMessageWithRepeatedField *message = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message = [TestRecursiveMessageWithRepeatedField message]; @autoreleasepool { TestRecursiveMessageWithRepeatedField *message2 = @@ -1389,27 +1329,20 @@ message.strToStr = message2.strToStr; // Pointer conparision XCTAssertEqual(message.iToI->_autocreator, message2); - XCTAssertTrue([message.strToStr - isKindOfClass:[GPBAutocreatedDictionary class]]); - XCTAssertEqual( - ((GPBAutocreatedDictionary *)message.strToStr)->_autocreator, - message2); + XCTAssertTrue([message.strToStr isKindOfClass:[GPBAutocreatedDictionary class]]); + XCTAssertEqual(((GPBAutocreatedDictionary *)message.strToStr)->_autocreator, message2); } XCTAssertNil(message.iToI->_autocreator); - XCTAssertTrue( - [message.strToStr isKindOfClass:[GPBAutocreatedDictionary class]]); - XCTAssertNil( - ((GPBAutocreatedDictionary *)message.strToStr)->_autocreator); + XCTAssertTrue([message.strToStr isKindOfClass:[GPBAutocreatedDictionary class]]); + XCTAssertNil(((GPBAutocreatedDictionary *)message.strToStr)->_autocreator); } - (void)testSetNilAutocreatedMap { // Setting map to nil should cause it to lose its delegate. - TestRecursiveMessageWithRepeatedField *message = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message = [TestRecursiveMessageWithRepeatedField message]; GPBInt32Int32Dictionary *iToI = [message.iToI retain]; - GPBAutocreatedDictionary *strToStr = - (GPBAutocreatedDictionary *)[message.strToStr retain]; + GPBAutocreatedDictionary *strToStr = (GPBAutocreatedDictionary *)[message.strToStr retain]; XCTAssertTrue([strToStr isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(iToI->_autocreator, message); XCTAssertEqual(strToStr->_autocreator, message); @@ -1426,15 +1359,13 @@ // an autocreated one or a straight NSDictionary. // The real test here is that nothing crashes while doing the work. - TestRecursiveMessageWithRepeatedField *message = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message = [TestRecursiveMessageWithRepeatedField message]; message.strToStr[@"foo"] = @"bar"; XCTAssertEqual(message.strToStr_Count, (NSUInteger)1); message.strToStr = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"bar", @"key1", @"baz", @"key2", nil]; XCTAssertEqual(message.strToStr_Count, (NSUInteger)2); - message.strToStr = - [NSMutableDictionary dictionaryWithObject:@"baz" forKey:@"mumble"]; + message.strToStr = [NSMutableDictionary dictionaryWithObject:@"baz" forKey:@"mumble"]; XCTAssertEqual(message.strToStr_Count, (NSUInteger)1); } @@ -1463,12 +1394,10 @@ XCTAssertNotNil(message.a); XCTAssertNotNil(message.a.strToStr); XCTAssertFalse([message hasA]); - GPBAutocreatedDictionary *strToStr = - (GPBAutocreatedDictionary *)[message.a.strToStr retain]; + GPBAutocreatedDictionary *strToStr = (GPBAutocreatedDictionary *)[message.a.strToStr retain]; XCTAssertTrue([strToStr isKindOfClass:[GPBAutocreatedDictionary class]]); XCTAssertEqual(strToStr->_autocreator, message.a); // Pointer comparison - message.a.strToStr = - [NSMutableDictionary dictionaryWithObject:@"abc" forKey:@"def"]; + message.a.strToStr = [NSMutableDictionary dictionaryWithObject:@"abc" forKey:@"def"]; XCTAssertTrue([message hasA]); XCTAssertNotEqual(message.a.strToStr, strToStr); // Pointer comparison XCTAssertNil(strToStr->_autocreator); @@ -1504,8 +1433,7 @@ - (void)testAutocreatedMapRemoveAllValues { // Calling removeAll on autocreated map should not cause it to be visible. - TestRecursiveMessageWithRepeatedField *message = - [TestRecursiveMessageWithRepeatedField message]; + TestRecursiveMessageWithRepeatedField *message = [TestRecursiveMessageWithRepeatedField message]; [message.a.iToI removeAll]; XCTAssertFalse([message hasA]); [message.a.strToStr removeAllObjects]; @@ -1522,8 +1450,7 @@ TestAllExtensions *message = [TestAllExtensions message]; [self setAllExtensions:message repeatedCount:kGPBDefaultRepeatCount]; [self modifyRepeatedExtensions:message]; - [self assertRepeatedExtensionsModified:message - repeatedCount:kGPBDefaultRepeatCount]; + [self assertRepeatedExtensionsModified:message repeatedCount:kGPBDefaultRepeatCount]; } - (void)testExtensionDefaults { @@ -1564,16 +1491,11 @@ XCTAssertFalse([message hasExtension:[UnittestRoot optionalGroupExtension]]); XCTAssertFalse([message hasExtension:[UnittestRoot optionalGroupExtension]]); - XCTAssertFalse( - [message hasExtension:[UnittestRoot optionalNestedMessageExtension]]); - XCTAssertFalse( - [message hasExtension:[UnittestRoot optionalForeignMessageExtension]]); - XCTAssertFalse( - [message hasExtension:[UnittestRoot optionalImportMessageExtension]]); - XCTAssertFalse([message - hasExtension:[UnittestRoot optionalPublicImportMessageExtension]]); - XCTAssertFalse( - [message hasExtension:[UnittestRoot optionalLazyMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalNestedMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalForeignMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalImportMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalPublicImportMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalLazyMessageExtension]]); // They should auto create something when fetched. @@ -1585,8 +1507,8 @@ [message getExtension:[UnittestRoot optionalForeignMessageExtension]]; ImportMessage *optionalImportMessage = [message getExtension:[UnittestRoot optionalImportMessageExtension]]; - PublicImportMessage *optionalPublicImportMessage = [message - getExtension:[UnittestRoot optionalPublicImportMessageExtension]]; + PublicImportMessage *optionalPublicImportMessage = + [message getExtension:[UnittestRoot optionalPublicImportMessageExtension]]; TestAllTypes_NestedMessage *optionalLazyMessage = [message getExtension:[UnittestRoot optionalLazyMessageExtension]]; @@ -1611,23 +1533,17 @@ // And they set that value back in to the message since the value created was // mutable (so a second fetch should give the same object). - XCTAssertEqual([message getExtension:[UnittestRoot optionalGroupExtension]], - optionalGroup); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalNestedMessageExtension]], - optionalNestedMessage); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalForeignMessageExtension]], - optionalForeignMessage); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalImportMessageExtension]], - optionalImportMessage); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalPublicImportMessageExtension]], - optionalPublicImportMessage); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalLazyMessageExtension]], - optionalLazyMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalGroupExtension]], optionalGroup); + XCTAssertEqual([message getExtension:[UnittestRoot optionalNestedMessageExtension]], + optionalNestedMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalForeignMessageExtension]], + optionalForeignMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalImportMessageExtension]], + optionalImportMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalPublicImportMessageExtension]], + optionalPublicImportMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalLazyMessageExtension]], + optionalLazyMessage); // And the default objects for a second message should be distinct (again, // since they are mutable, each needs their own copy). @@ -1635,70 +1551,47 @@ TestAllExtensions *message2 = [TestAllExtensions message]; // Intentionally doing a pointer comparison. - XCTAssertNotEqual( - [message2 getExtension:[UnittestRoot optionalGroupExtension]], - optionalGroup); - XCTAssertNotEqual( - [message2 getExtension:[UnittestRoot optionalNestedMessageExtension]], - optionalNestedMessage); - XCTAssertNotEqual( - [message2 getExtension:[UnittestRoot optionalForeignMessageExtension]], - optionalForeignMessage); - XCTAssertNotEqual( - [message2 getExtension:[UnittestRoot optionalImportMessageExtension]], - optionalImportMessage); - XCTAssertNotEqual( - [message2 getExtension:[UnittestRoot optionalPublicImportMessageExtension]], - optionalPublicImportMessage); - XCTAssertNotEqual( - [message2 getExtension:[UnittestRoot optionalLazyMessageExtension]], - optionalLazyMessage); + XCTAssertNotEqual([message2 getExtension:[UnittestRoot optionalGroupExtension]], optionalGroup); + XCTAssertNotEqual([message2 getExtension:[UnittestRoot optionalNestedMessageExtension]], + optionalNestedMessage); + XCTAssertNotEqual([message2 getExtension:[UnittestRoot optionalForeignMessageExtension]], + optionalForeignMessage); + XCTAssertNotEqual([message2 getExtension:[UnittestRoot optionalImportMessageExtension]], + optionalImportMessage); + XCTAssertNotEqual([message2 getExtension:[UnittestRoot optionalPublicImportMessageExtension]], + optionalPublicImportMessage); + XCTAssertNotEqual([message2 getExtension:[UnittestRoot optionalLazyMessageExtension]], + optionalLazyMessage); // Clear values, and on next access you get back new submessages. [message setExtension:[UnittestRoot optionalGroupExtension] value:nil]; [message setExtension:[UnittestRoot optionalGroupExtension] value:nil]; - [message setExtension:[UnittestRoot optionalNestedMessageExtension] - value:nil]; - [message setExtension:[UnittestRoot optionalForeignMessageExtension] - value:nil]; - [message setExtension:[UnittestRoot optionalImportMessageExtension] - value:nil]; - [message setExtension:[UnittestRoot optionalPublicImportMessageExtension] - value:nil]; + [message setExtension:[UnittestRoot optionalNestedMessageExtension] value:nil]; + [message setExtension:[UnittestRoot optionalForeignMessageExtension] value:nil]; + [message setExtension:[UnittestRoot optionalImportMessageExtension] value:nil]; + [message setExtension:[UnittestRoot optionalPublicImportMessageExtension] value:nil]; [message setExtension:[UnittestRoot optionalLazyMessageExtension] value:nil]; XCTAssertFalse([message hasExtension:[UnittestRoot optionalGroupExtension]]); XCTAssertFalse([message hasExtension:[UnittestRoot optionalGroupExtension]]); - XCTAssertFalse( - [message hasExtension:[UnittestRoot optionalNestedMessageExtension]]); - XCTAssertFalse( - [message hasExtension:[UnittestRoot optionalForeignMessageExtension]]); - XCTAssertFalse( - [message hasExtension:[UnittestRoot optionalImportMessageExtension]]); - XCTAssertFalse([message - hasExtension:[UnittestRoot optionalPublicImportMessageExtension]]); - XCTAssertFalse( - [message hasExtension:[UnittestRoot optionalLazyMessageExtension]]); - - XCTAssertEqual([message getExtension:[UnittestRoot optionalGroupExtension]], - optionalGroup); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalNestedMessageExtension]], - optionalNestedMessage); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalForeignMessageExtension]], - optionalForeignMessage); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalImportMessageExtension]], - optionalImportMessage); - XCTAssertEqual( - [message - getExtension:[UnittestRoot optionalPublicImportMessageExtension]], - optionalPublicImportMessage); - XCTAssertEqual( - [message getExtension:[UnittestRoot optionalLazyMessageExtension]], - optionalLazyMessage); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalNestedMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalForeignMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalImportMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalPublicImportMessageExtension]]); + XCTAssertFalse([message hasExtension:[UnittestRoot optionalLazyMessageExtension]]); + + XCTAssertEqual([message getExtension:[UnittestRoot optionalGroupExtension]], optionalGroup); + XCTAssertEqual([message getExtension:[UnittestRoot optionalNestedMessageExtension]], + optionalNestedMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalForeignMessageExtension]], + optionalForeignMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalImportMessageExtension]], + optionalImportMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalPublicImportMessageExtension]], + optionalPublicImportMessage); + XCTAssertEqual([message getExtension:[UnittestRoot optionalLazyMessageExtension]], + optionalLazyMessage); } - (void)testMultiplePointersToAutocreatedExtension { @@ -1708,13 +1601,11 @@ TestAllExtensions *message2 = [TestAllExtensions message]; GPBExtensionDescriptor *extension = [UnittestRoot optionalGroupExtension]; [message setExtension:extension value:[message2 getExtension:extension]]; - XCTAssertEqual([message getExtension:extension], - [message2 getExtension:extension]); + XCTAssertEqual([message getExtension:extension], [message2 getExtension:extension]); XCTAssertFalse([message2 hasExtension:extension]); XCTAssertTrue([message hasExtension:extension]); - TestAllTypes_OptionalGroup *extensionValue = - [message2 getExtension:extension]; + TestAllTypes_OptionalGroup *extensionValue = [message2 getExtension:extension]; extensionValue.a = 1; XCTAssertTrue([message2 hasExtension:extension]); XCTAssertTrue([message hasExtension:extension]); @@ -1723,12 +1614,10 @@ - (void)testCopyWithAutocreatedExtension { // Mutable copy shouldn't copy autocreated extensions. TestAllExtensions *message = [TestAllExtensions message]; - GPBExtensionDescriptor *optionalGroupExtension = - [UnittestRoot optionalGroupExtension]; + GPBExtensionDescriptor *optionalGroupExtension = [UnittestRoot optionalGroupExtension]; GPBExtensionDescriptor *optionalNestedMessageExtesion = [UnittestRoot optionalNestedMessageExtension]; - TestAllTypes_OptionalGroup *optionalGroup = - [message getExtension:optionalGroupExtension]; + TestAllTypes_OptionalGroup *optionalGroup = [message getExtension:optionalGroupExtension]; optionalGroup.a = 42; XCTAssertNotNil(optionalGroup); XCTAssertNotNil([message getExtension:optionalNestedMessageExtesion]); @@ -1755,13 +1644,11 @@ - (void)testClearMessageAutocreatedExtension { // Call clear should cause it to recreate its autocreated extensions. TestAllExtensions *message = [TestAllExtensions message]; - GPBExtensionDescriptor *optionalGroupExtension = - [UnittestRoot optionalGroupExtension]; + GPBExtensionDescriptor *optionalGroupExtension = [UnittestRoot optionalGroupExtension]; TestAllTypes_OptionalGroup *optionalGroup = [[message getExtension:optionalGroupExtension] retain]; [message clear]; - TestAllTypes_OptionalGroup *optionalGroupNew = - [message getExtension:optionalGroupExtension]; + TestAllTypes_OptionalGroup *optionalGroupNew = [message getExtension:optionalGroupExtension]; // Intentionally doing a pointer comparison. XCTAssertNotEqual(optionalGroup, optionalGroupNew); @@ -1772,42 +1659,37 @@ // Should be able to retain autocreated extension while the creator is // dealloced. TestAllExtensions *message = [TestAllExtensions message]; - GPBExtensionDescriptor *optionalGroupExtension = - [UnittestRoot optionalGroupExtension]; + GPBExtensionDescriptor *optionalGroupExtension = [UnittestRoot optionalGroupExtension]; @autoreleasepool { TestAllExtensions *message2 = [TestAllExtensions message]; [message setExtension:optionalGroupExtension value:[message2 getExtension:optionalGroupExtension]]; - XCTAssertTrue(GPBWasMessageAutocreatedBy( - [message getExtension:optionalGroupExtension], message2)); + XCTAssertTrue( + GPBWasMessageAutocreatedBy([message getExtension:optionalGroupExtension], message2)); } - XCTAssertFalse(GPBWasMessageAutocreatedBy( - [message getExtension:optionalGroupExtension], message)); + XCTAssertFalse( + GPBWasMessageAutocreatedBy([message getExtension:optionalGroupExtension], message)); } - (void)testClearAutocreatedExtension { // Clearing autocreated extension should NOT cause it to lose its creator. TestAllExtensions *message = [TestAllExtensions message]; - GPBExtensionDescriptor *optionalGroupExtension = - [UnittestRoot optionalGroupExtension]; + GPBExtensionDescriptor *optionalGroupExtension = [UnittestRoot optionalGroupExtension]; TestAllTypes_OptionalGroup *optionalGroup = [[message getExtension:optionalGroupExtension] retain]; [message clearExtension:optionalGroupExtension]; - TestAllTypes_OptionalGroup *optionalGroupNew = - [message getExtension:optionalGroupExtension]; + TestAllTypes_OptionalGroup *optionalGroupNew = [message getExtension:optionalGroupExtension]; XCTAssertEqual(optionalGroup, optionalGroupNew); XCTAssertFalse([message hasExtension:optionalGroupExtension]); [optionalGroup release]; // Clearing autocreated extension should not cause its creator to become // visible - GPBExtensionDescriptor *recursiveExtension = - [UnittestObjcRoot recursiveExtension]; + GPBExtensionDescriptor *recursiveExtension = [UnittestObjcRoot recursiveExtension]; TestAllExtensions *message_lvl2 = [message getExtension:recursiveExtension]; - TestAllExtensions *message_lvl3 = - [message_lvl2 getExtension:recursiveExtension]; + TestAllExtensions *message_lvl3 = [message_lvl2 getExtension:recursiveExtension]; [message_lvl3 clearExtension:recursiveExtension]; XCTAssertFalse([message hasExtension:recursiveExtension]); } @@ -1816,13 +1698,10 @@ // Setting an extension should cause the extension to appear to its creator. // Test this several levels deep. TestAllExtensions *message = [TestAllExtensions message]; - GPBExtensionDescriptor *recursiveExtension = - [UnittestObjcRoot recursiveExtension]; + GPBExtensionDescriptor *recursiveExtension = [UnittestObjcRoot recursiveExtension]; TestAllExtensions *message_lvl2 = [message getExtension:recursiveExtension]; - TestAllExtensions *message_lvl3 = - [message_lvl2 getExtension:recursiveExtension]; - TestAllExtensions *message_lvl4 = - [message_lvl3 getExtension:recursiveExtension]; + TestAllExtensions *message_lvl3 = [message_lvl2 getExtension:recursiveExtension]; + TestAllExtensions *message_lvl4 = [message_lvl3 getExtension:recursiveExtension]; XCTAssertFalse([message hasExtension:recursiveExtension]); XCTAssertFalse([message_lvl2 hasExtension:recursiveExtension]); XCTAssertFalse([message_lvl3 hasExtension:recursiveExtension]); @@ -1840,18 +1719,15 @@ - (void)testSetAutocreatedExtensionToSelf { // Setting extension to itself should cause it to become visible. TestAllExtensions *message = [TestAllExtensions message]; - GPBExtensionDescriptor *optionalGroupExtension = - [UnittestRoot optionalGroupExtension]; + GPBExtensionDescriptor *optionalGroupExtension = [UnittestRoot optionalGroupExtension]; XCTAssertNotNil([message getExtension:optionalGroupExtension]); XCTAssertFalse([message hasExtension:optionalGroupExtension]); - [message setExtension:optionalGroupExtension - value:[message getExtension:optionalGroupExtension]]; + [message setExtension:optionalGroupExtension value:[message getExtension:optionalGroupExtension]]; XCTAssertTrue([message hasExtension:optionalGroupExtension]); } - (void)testAutocreatedExtensionMemoryLeaks { - GPBExtensionDescriptor *recursiveExtension = - [UnittestObjcRoot recursiveExtension]; + GPBExtensionDescriptor *recursiveExtension = [UnittestObjcRoot recursiveExtension]; // Test for memory leaks with autocreated extensions. TestAllExtensions *message; @@ -1863,8 +1739,7 @@ message_lvl2 = [[message getExtension:recursiveExtension] retain]; message_lvl3 = [[message_lvl2 getExtension:recursiveExtension] retain]; message_lvl4 = [[message_lvl3 getExtension:recursiveExtension] retain]; - [message_lvl2 setExtension:[UnittestRoot optionalInt32Extension] - value:@(1)]; + [message_lvl2 setExtension:[UnittestRoot optionalInt32Extension] value:@(1)]; } XCTAssertEqual(message.retainCount, (NSUInteger)1); @@ -1884,8 +1759,7 @@ } - (void)testSetExtensionWithAutocreatedValue { - GPBExtensionDescriptor *recursiveExtension = - [UnittestObjcRoot recursiveExtension]; + GPBExtensionDescriptor *recursiveExtension = [UnittestObjcRoot recursiveExtension]; TestAllExtensions *message; @autoreleasepool { @@ -1895,8 +1769,7 @@ // This statements checks that the extension value isn't accidentally // dealloced when removing it from the autocreated map. - [message setExtension:recursiveExtension - value:[message getExtension:recursiveExtension]]; + [message setExtension:recursiveExtension value:[message getExtension:recursiveExtension]]; XCTAssertTrue([message hasExtension:recursiveExtension]); [message release]; } @@ -1909,26 +1782,22 @@ } - (void)testGenerateAndParseUnknownMessage { - GPBUnknownFieldSet *unknowns = - [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet *unknowns = [[[GPBUnknownFieldSet alloc] init] autorelease]; [unknowns mergeVarintField:123 value:456]; GPBMessage *message = [GPBMessage message]; [message setUnknownFields:unknowns]; NSData *data = [message data]; - GPBMessage *message2 = - [GPBMessage parseFromData:data extensionRegistry:nil error:NULL]; + GPBMessage *message2 = [GPBMessage parseFromData:data extensionRegistry:nil error:NULL]; XCTAssertEqualObjects(message, message2); } - (void)testDelimitedWriteAndParseMultipleMessages { - GPBUnknownFieldSet *unknowns1 = - [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet *unknowns1 = [[[GPBUnknownFieldSet alloc] init] autorelease]; [unknowns1 mergeVarintField:123 value:456]; GPBMessage *message1 = [GPBMessage message]; [message1 setUnknownFields:unknowns1]; - GPBUnknownFieldSet *unknowns2 = - [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet *unknowns2 = [[[GPBUnknownFieldSet alloc] init] autorelease]; [unknowns2 mergeVarintField:789 value:987]; [unknowns2 mergeVarintField:654 value:321]; GPBMessage *message2 = [GPBMessage message]; @@ -1937,8 +1806,7 @@ NSMutableData *delimitedData = [NSMutableData data]; [delimitedData appendData:[message1 delimitedData]]; [delimitedData appendData:[message2 delimitedData]]; - GPBCodedInputStream *input = - [GPBCodedInputStream streamWithData:delimitedData]; + GPBCodedInputStream *input = [GPBCodedInputStream streamWithData:delimitedData]; GPBMessage *message3 = [GPBMessage parseDelimitedFromCodedInputStream:input extensionRegistry:nil error:NULL]; @@ -1970,8 +1838,7 @@ } - (void)testEnumDescriptorFromExtensionDescriptor { - GPBExtensionDescriptor *extDescriptor = - [UnittestRoot optionalForeignEnumExtension]; + GPBExtensionDescriptor *extDescriptor = [UnittestRoot optionalForeignEnumExtension]; XCTAssertEqual(extDescriptor.dataType, GPBDataTypeEnum); GPBEnumDescriptor *enumDescriptor = extDescriptor.enumDescriptor; GPBEnumDescriptor *expectedDescriptor = ForeignEnum_EnumDescriptor(); @@ -2078,8 +1945,7 @@ // Repeated field (shouldn't ever be an issue since developer has to use the // right GPBArray methods themselves). - msg.mumbleArray = [GPBEnumArray - arrayWithValidationFunction:EnumTestMsg_MyEnum_IsValidValue]; + msg.mumbleArray = [GPBEnumArray arrayWithValidationFunction:EnumTestMsg_MyEnum_IsValidValue]; [msg.mumbleArray addValue:EnumTestMsg_MyEnum_Zero]; [msg.mumbleArray addValue:EnumTestMsg_MyEnum_One]; [msg.mumbleArray addValue:EnumTestMsg_MyEnum_Two]; @@ -2095,14 +1961,11 @@ XCTAssertNotNil(data); msgPrime = [EnumTestMsg parseFromData:data error:NULL]; XCTAssertEqualObjects(msgPrime, msg); - XCTAssertEqual([msgPrime.mumbleArray valueAtIndex:0], - EnumTestMsg_MyEnum_Zero); + XCTAssertEqual([msgPrime.mumbleArray valueAtIndex:0], EnumTestMsg_MyEnum_Zero); XCTAssertEqual([msgPrime.mumbleArray valueAtIndex:1], EnumTestMsg_MyEnum_One); XCTAssertEqual([msgPrime.mumbleArray valueAtIndex:2], EnumTestMsg_MyEnum_Two); - XCTAssertEqual([msgPrime.mumbleArray valueAtIndex:3], - EnumTestMsg_MyEnum_NegOne); - XCTAssertEqual([msgPrime.mumbleArray valueAtIndex:4], - EnumTestMsg_MyEnum_NegTwo); + XCTAssertEqual([msgPrime.mumbleArray valueAtIndex:3], EnumTestMsg_MyEnum_NegOne); + XCTAssertEqual([msgPrime.mumbleArray valueAtIndex:4], EnumTestMsg_MyEnum_NegTwo); } - (void)testReservedWordNaming { @@ -2200,12 +2063,12 @@ msg1.boolField32 = YES; msg2.boolField32 = YES; - XCTAssertTrue(msg1 != msg2); // Different pointers. + XCTAssertTrue(msg1 != msg2); // Different pointers. XCTAssertEqual([msg1 hash], [msg2 hash]); XCTAssertEqualObjects(msg1, msg2); BoolOnlyMessage *msg1Prime = [[msg1 copy] autorelease]; - XCTAssertTrue(msg1Prime != msg1); // Different pointers. + XCTAssertTrue(msg1Prime != msg1); // Different pointers. XCTAssertEqual([msg1 hash], [msg1Prime hash]); XCTAssertEqualObjects(msg1, msg1Prime); @@ -2252,24 +2115,26 @@ TestMessageOfMaps *msg2 = [[msg copy] autorelease]; XCTAssertNotNil(msg2); XCTAssertEqualObjects(msg2, msg); - XCTAssertTrue(msg2 != msg); // ptr compare - XCTAssertTrue(msg.strToStr != msg2.strToStr); // ptr compare - XCTAssertTrue(msg.intToStr != msg2.intToStr); // ptr compare - XCTAssertTrue(msg.intToInt != msg2.intToInt); // ptr compare - XCTAssertTrue(msg.strToBool != msg2.strToBool); // ptr compare - XCTAssertTrue(msg.boolToStr != msg2.boolToStr); // ptr compare + XCTAssertTrue(msg2 != msg); // ptr compare + XCTAssertTrue(msg.strToStr != msg2.strToStr); // ptr compare + XCTAssertTrue(msg.intToStr != msg2.intToStr); // ptr compare + XCTAssertTrue(msg.intToInt != msg2.intToInt); // ptr compare + XCTAssertTrue(msg.strToBool != msg2.strToBool); // ptr compare + XCTAssertTrue(msg.boolToStr != msg2.boolToStr); // ptr compare XCTAssertTrue(msg.boolToBool != msg2.boolToBool); // ptr compare - XCTAssertTrue(msg.intToBool != msg2.intToBool); // ptr compare - XCTAssertTrue(msg.boolToInt != msg2.boolToInt); // ptr compare - XCTAssertTrue(msg.strToMsg != msg2.strToMsg); // ptr compare - XCTAssertTrue(msg.intToMsg != msg2.intToMsg); // ptr compare - XCTAssertTrue(msg.boolToMsg != msg2.boolToMsg); // ptr compare + XCTAssertTrue(msg.intToBool != msg2.intToBool); // ptr compare + XCTAssertTrue(msg.boolToInt != msg2.boolToInt); // ptr compare + XCTAssertTrue(msg.strToMsg != msg2.strToMsg); // ptr compare + XCTAssertTrue(msg.intToMsg != msg2.intToMsg); // ptr compare + XCTAssertTrue(msg.boolToMsg != msg2.boolToMsg); // ptr compare XCTAssertTrue(msg.strToMsg[@"baz"] != msg2.strToMsg[@"baz"]); // ptr compare XCTAssertEqualObjects(msg.strToMsg[@"baz"], msg2.strToMsg[@"baz"]); - XCTAssertTrue([msg.intToMsg objectForKey:222] != [msg2.intToMsg objectForKey:222]); // ptr compare + XCTAssertTrue([msg.intToMsg objectForKey:222] != + [msg2.intToMsg objectForKey:222]); // ptr compare XCTAssertEqualObjects([msg.intToMsg objectForKey:222], [msg2.intToMsg objectForKey:222]); - XCTAssertTrue([msg.boolToMsg objectForKey:YES] != [msg2.boolToMsg objectForKey:YES]); // ptr compare + XCTAssertTrue([msg.boolToMsg objectForKey:YES] != + [msg2.boolToMsg objectForKey:YES]); // ptr compare XCTAssertEqualObjects([msg.boolToMsg objectForKey:YES], [msg2.boolToMsg objectForKey:YES]); } diff --git a/objectivec/Tests/GPBObjectiveCPlusPlusTest.mm b/objectivec/Tests/GPBObjectiveCPlusPlusTest.mm index 73c52e8cd4..a89bb473b4 100644 --- a/objectivec/Tests/GPBObjectiveCPlusPlusTest.mm +++ b/objectivec/Tests/GPBObjectiveCPlusPlusTest.mm @@ -28,10 +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. - #import "GPBTestUtilities.h" - // // This is just a compile test (here to make sure things never regress). // @@ -48,15 +46,14 @@ // Sanity check the conditions of the test within the Xcode project. #if !__cplusplus - #error This isn't compiled as Objective C++? +#error This isn't compiled as Objective C++? #elif __cplusplus >= 201103L - // If this trips, it means the Xcode default might have change (or someone - // edited the testing project) and it might be time to revisit the GPB_ENUM - // define in GPBBootstrap.h. - #warning Did the Xcode default for C++ spec change? +// If this trips, it means the Xcode default might have change (or someone +// edited the testing project) and it might be time to revisit the GPB_ENUM +// define in GPBBootstrap.h. +#warning Did the Xcode default for C++ spec change? #endif - // Dummy XCTest. @interface GPBObjectiveCPlusPlusTests : GPBTestCase @end diff --git a/objectivec/Tests/GPBPerfTests.m b/objectivec/Tests/GPBPerfTests.m index 90174689bb..7c1cbc53e1 100644 --- a/objectivec/Tests/GPBPerfTests.m +++ b/objectivec/Tests/GPBPerfTests.m @@ -69,9 +69,9 @@ static const uint32_t kRepeatedCount = 100; // lock across threads when parsing different instances. The Serial version of the test should run // around ~2 times slower than the Parallel version since it's parsing the protos in the same // thread. - TestAllTypes *allTypesMessage = [TestAllTypes message]; + TestAllTypes* allTypesMessage = [TestAllTypes message]; [self setAllFields:allTypesMessage repeatedCount:2]; - NSData *allTypesData = allTypesMessage.data; + NSData* allTypesData = allTypesMessage.data; [self measureBlock:^{ for (int i = 0; i < 500; ++i) { @@ -86,9 +86,9 @@ static const uint32_t kRepeatedCount = 100; // not lock across threads when parsing different instances. The Serial version of the test should // run around ~2 times slower than the Parallel version since it's parsing the protos in the same // thread. - TestAllTypes *allTypesMessage = [TestAllTypes message]; + TestAllTypes* allTypesMessage = [TestAllTypes message]; [self setAllFields:allTypesMessage repeatedCount:2]; - NSData *allTypesData = allTypesMessage.data; + NSData* allTypesData = allTypesMessage.data; dispatch_queue_t concurrentQueue = dispatch_queue_create("perfQueue", DISPATCH_QUEUE_CONCURRENT); @@ -104,7 +104,9 @@ static const uint32_t kRepeatedCount = 100; [TestAllTypes parseFromData:allTypesData error:NULL]; }); - dispatch_group_notify(group, concurrentQueue, ^{}); + dispatch_group_notify(group, concurrentQueue, + ^{ + }); dispatch_release(group); } @@ -118,9 +120,9 @@ static const uint32_t kRepeatedCount = 100; // lock across threads when parsing different instances when using extensions. The Serial version // of the test should run around ~2 times slower than the Parallel version since it's parsing the // protos in the same thread. - TestAllExtensions *allExtensionsMessage = [TestAllExtensions message]; + TestAllExtensions* allExtensionsMessage = [TestAllExtensions message]; [self setAllExtensions:allExtensionsMessage repeatedCount:2]; - NSData *allExtensionsData = allExtensionsMessage.data; + NSData* allExtensionsData = allExtensionsMessage.data; [self measureBlock:^{ for (int i = 0; i < 500; ++i) { @@ -139,9 +141,9 @@ static const uint32_t kRepeatedCount = 100; // not lock across threads when parsing different instances when using extensions. The Serial // version of the test should run around ~2 times slower than the Parallel version since it's // parsing the protos in the same thread. - TestAllExtensions *allExtensionsMessage = [TestAllExtensions message]; + TestAllExtensions* allExtensionsMessage = [TestAllExtensions message]; [self setAllExtensions:allExtensionsMessage repeatedCount:2]; - NSData *allExtensionsData = allExtensionsMessage.data; + NSData* allExtensionsData = allExtensionsMessage.data; dispatch_queue_t concurrentQueue = dispatch_queue_create("perfQueue", DISPATCH_QUEUE_CONCURRENT); @@ -161,7 +163,9 @@ static const uint32_t kRepeatedCount = 100; error:NULL]; }); - dispatch_group_notify(group, concurrentQueue, ^{}); + dispatch_group_notify(group, concurrentQueue, + ^{ + }); dispatch_release(group); } @@ -177,8 +181,7 @@ static const uint32_t kRepeatedCount = 100; [self setAllExtensions:message repeatedCount:kRepeatedCount]; NSData* rawBytes = [message data]; [message release]; - TestAllExtensions* message2 = - [[TestAllExtensions alloc] initWithData:rawBytes error:NULL]; + TestAllExtensions* message2 = [[TestAllExtensions alloc] initWithData:rawBytes error:NULL]; [message2 release]; } }]; @@ -204,8 +207,8 @@ static const uint32_t kRepeatedCount = 100; [self setPackedExtensions:message repeatedCount:kRepeatedCount]; NSData* rawBytes = [message data]; [message release]; - TestPackedExtensions* message2 = - [[TestPackedExtensions alloc] initWithData:rawBytes error:NULL]; + TestPackedExtensions* message2 = [[TestPackedExtensions alloc] initWithData:rawBytes + error:NULL]; [message2 release]; } }]; diff --git a/objectivec/Tests/GPBTestUtilities.h b/objectivec/Tests/GPBTestUtilities.h index 780184b07c..bebd557e24 100644 --- a/objectivec/Tests/GPBTestUtilities.h +++ b/objectivec/Tests/GPBTestUtilities.h @@ -48,7 +48,6 @@ static inline NSData *DataFromCStr(const char *str) { #define GPBARRAYSIZE(a) ((sizeof(a) / sizeof((a[0])))) #endif // GPBARRAYSIZE - // The number of repetitions of any repeated objects inside of test messages. extern const uint32_t kGPBDefaultRepeatCount; @@ -56,16 +55,11 @@ extern const uint32_t kGPBDefaultRepeatCount; - (void)setAllFields:(TestAllTypes *)message repeatedCount:(uint32_t)count; - (void)clearAllFields:(TestAllTypes *)message; -- (void)setAllExtensions:(TestAllExtensions *)message - repeatedCount:(uint32_t)count; -- (void)setPackedFields:(TestPackedTypes *)message - repeatedCount:(uint32_t)count; -- (void)setUnpackedFields:(TestUnpackedTypes *)message - repeatedCount:(uint32_t)count; -- (void)setPackedExtensions:(TestPackedExtensions *)message - repeatedCount:(uint32_t)count; -- (void)setUnpackedExtensions:(TestUnpackedExtensions *)message - repeatedCount:(uint32_t)count; +- (void)setAllExtensions:(TestAllExtensions *)message repeatedCount:(uint32_t)count; +- (void)setPackedFields:(TestPackedTypes *)message repeatedCount:(uint32_t)count; +- (void)setUnpackedFields:(TestUnpackedTypes *)message repeatedCount:(uint32_t)count; +- (void)setPackedExtensions:(TestPackedExtensions *)message repeatedCount:(uint32_t)count; +- (void)setUnpackedExtensions:(TestUnpackedExtensions *)message repeatedCount:(uint32_t)count; - (void)setAllMapFields:(TestMap *)message numEntries:(uint32_t)count; - (TestAllTypes *)allSetRepeatedCount:(uint32_t)count; @@ -73,20 +67,14 @@ extern const uint32_t kGPBDefaultRepeatCount; - (TestPackedTypes *)packedSetRepeatedCount:(uint32_t)count; - (TestPackedExtensions *)packedExtensionsSetRepeatedCount:(uint32_t)count; -- (void)assertAllFieldsSet:(TestAllTypes *)message - repeatedCount:(uint32_t)count; -- (void)assertAllExtensionsSet:(TestAllExtensions *)message - repeatedCount:(uint32_t)count; -- (void)assertRepeatedFieldsModified:(TestAllTypes *)message - repeatedCount:(uint32_t)count; -- (void)assertRepeatedExtensionsModified:(TestAllExtensions *)message - repeatedCount:(uint32_t)count; +- (void)assertAllFieldsSet:(TestAllTypes *)message repeatedCount:(uint32_t)count; +- (void)assertAllExtensionsSet:(TestAllExtensions *)message repeatedCount:(uint32_t)count; +- (void)assertRepeatedFieldsModified:(TestAllTypes *)message repeatedCount:(uint32_t)count; +- (void)assertRepeatedExtensionsModified:(TestAllExtensions *)message repeatedCount:(uint32_t)count; - (void)assertExtensionsClear:(TestAllExtensions *)message; - (void)assertClear:(TestAllTypes *)message; -- (void)assertPackedFieldsSet:(TestPackedTypes *)message - repeatedCount:(uint32_t)count; -- (void)assertPackedExtensionsSet:(TestPackedExtensions *)message - repeatedCount:(uint32_t)count; +- (void)assertPackedFieldsSet:(TestPackedTypes *)message repeatedCount:(uint32_t)count; +- (void)assertPackedExtensionsSet:(TestPackedExtensions *)message repeatedCount:(uint32_t)count; - (void)modifyRepeatedExtensions:(TestAllExtensions *)message; - (void)modifyRepeatedFields:(TestAllTypes *)message; @@ -96,8 +84,7 @@ extern const uint32_t kGPBDefaultRepeatCount; - (NSData *)getDataFileNamed:(NSString *)name dataToWrite:(NSData *)dataToWrite; - (void)assertAllFieldsKVCMatch:(TestAllTypes *)message; -- (void)setAllFieldsViaKVC:(TestAllTypes *)message - repeatedCount:(uint32_t)count; +- (void)setAllFieldsViaKVC:(TestAllTypes *)message repeatedCount:(uint32_t)count; - (void)assertClearKVC:(TestAllTypes *)message; @end diff --git a/objectivec/Tests/GPBTestUtilities.m b/objectivec/Tests/GPBTestUtilities.m index edd143b387..37bd5d7de3 100644 --- a/objectivec/Tests/GPBTestUtilities.m +++ b/objectivec/Tests/GPBTestUtilities.m @@ -66,8 +66,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; // Return data for name. Optionally (based on #if setting) write out dataToWrite // to replace that data. Useful for setting golden masters. -- (NSData *)getDataFileNamed:(NSString *)name - dataToWrite:(NSData *)dataToWrite { +- (NSData *)getDataFileNamed:(NSString *)name dataToWrite:(NSData *)dataToWrite { NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSString *path = [bundle pathForResource:[name stringByDeletingPathExtension] ofType:[name pathExtension]]; @@ -93,63 +92,30 @@ const uint32_t kGPBDefaultRepeatCount = 2; // ------------------------------------------------------------------- - (void)modifyRepeatedExtensions:(TestAllExtensions *)message { - [message setExtension:[UnittestRoot repeatedInt32Extension] - index:1 - value:@501]; - [message setExtension:[UnittestRoot repeatedInt64Extension] - index:1 - value:@502]; - [message setExtension:[UnittestRoot repeatedUint32Extension] - index:1 - value:@503]; - [message setExtension:[UnittestRoot repeatedUint64Extension] - index:1 - value:@504]; - [message setExtension:[UnittestRoot repeatedSint32Extension] - index:1 - value:@505]; - [message setExtension:[UnittestRoot repeatedSint64Extension] - index:1 - value:@506]; - [message setExtension:[UnittestRoot repeatedFixed32Extension] - index:1 - value:@507]; - [message setExtension:[UnittestRoot repeatedFixed64Extension] - index:1 - value:@508]; - [message setExtension:[UnittestRoot repeatedSfixed32Extension] - index:1 - value:@509]; - [message setExtension:[UnittestRoot repeatedSfixed64Extension] - index:1 - value:@510]; - [message setExtension:[UnittestRoot repeatedFloatExtension] - index:1 - value:@511.0f]; - [message setExtension:[UnittestRoot repeatedDoubleExtension] - index:1 - value:@512.0]; - [message setExtension:[UnittestRoot repeatedBoolExtension] - index:1 - value:@YES]; - [message setExtension:[UnittestRoot repeatedStringExtension] - index:1 - value:@"515"]; + [message setExtension:[UnittestRoot repeatedInt32Extension] index:1 value:@501]; + [message setExtension:[UnittestRoot repeatedInt64Extension] index:1 value:@502]; + [message setExtension:[UnittestRoot repeatedUint32Extension] index:1 value:@503]; + [message setExtension:[UnittestRoot repeatedUint64Extension] index:1 value:@504]; + [message setExtension:[UnittestRoot repeatedSint32Extension] index:1 value:@505]; + [message setExtension:[UnittestRoot repeatedSint64Extension] index:1 value:@506]; + [message setExtension:[UnittestRoot repeatedFixed32Extension] index:1 value:@507]; + [message setExtension:[UnittestRoot repeatedFixed64Extension] index:1 value:@508]; + [message setExtension:[UnittestRoot repeatedSfixed32Extension] index:1 value:@509]; + [message setExtension:[UnittestRoot repeatedSfixed64Extension] index:1 value:@510]; + [message setExtension:[UnittestRoot repeatedFloatExtension] index:1 value:@511.0f]; + [message setExtension:[UnittestRoot repeatedDoubleExtension] index:1 value:@512.0]; + [message setExtension:[UnittestRoot repeatedBoolExtension] index:1 value:@YES]; + [message setExtension:[UnittestRoot repeatedStringExtension] index:1 value:@"515"]; [message setExtension:[UnittestRoot repeatedBytesExtension] index:1 value:[NSData gpbtu_dataWithUint32:516]]; RepeatedGroup_extension *repeatedGroup = [RepeatedGroup_extension message]; [repeatedGroup setA:517]; - [message setExtension:[UnittestRoot repeatedGroupExtension] - index:1 - value:repeatedGroup]; - TestAllTypes_NestedMessage *nestedMessage = - [TestAllTypes_NestedMessage message]; + [message setExtension:[UnittestRoot repeatedGroupExtension] index:1 value:repeatedGroup]; + TestAllTypes_NestedMessage *nestedMessage = [TestAllTypes_NestedMessage message]; [nestedMessage setBb:518]; - [message setExtension:[UnittestRoot repeatedNestedMessageExtension] - index:1 - value:nestedMessage]; + [message setExtension:[UnittestRoot repeatedNestedMessageExtension] index:1 value:nestedMessage]; ForeignMessage *foreignMessage = [ForeignMessage message]; [foreignMessage setC:519]; [message setExtension:[UnittestRoot repeatedForeignMessageExtension] @@ -157,9 +123,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; value:foreignMessage]; ImportMessage *importMessage = [ImportMessage message]; [importMessage setD:520]; - [message setExtension:[UnittestRoot repeatedImportMessageExtension] - index:1 - value:importMessage]; + [message setExtension:[UnittestRoot repeatedImportMessageExtension] index:1 value:importMessage]; [message setExtension:[UnittestRoot repeatedNestedEnumExtension] index:1 @@ -171,16 +135,11 @@ const uint32_t kGPBDefaultRepeatCount = 2; index:1 value:@(ImportEnum_ImportFoo)]; - [message setExtension:[UnittestRoot repeatedStringPieceExtension] - index:1 - value:@"524"]; - [message setExtension:[UnittestRoot repeatedCordExtension] - index:1 - value:@"525"]; + [message setExtension:[UnittestRoot repeatedStringPieceExtension] index:1 value:@"524"]; + [message setExtension:[UnittestRoot repeatedCordExtension] index:1 value:@"525"]; } -- (void)assertAllExtensionsSet:(TestAllExtensions *)message - repeatedCount:(uint32_t)count { +- (void)assertAllExtensionsSet:(TestAllExtensions *)message repeatedCount:(uint32_t)count { XCTAssertTrue([message hasExtension:[UnittestRoot optionalInt32Extension]]); XCTAssertTrue([message hasExtension:[UnittestRoot optionalInt64Extension]]); XCTAssertTrue([message hasExtension:[UnittestRoot optionalUint32Extension]]); @@ -238,29 +197,44 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertTrue([message hasExtension:[UnittestRoot defaultCordExtension]]); XCTAssertEqual(101, [[message getExtension:[UnittestRoot optionalInt32Extension]] intValue]); - XCTAssertEqual(102LL, [[message getExtension:[UnittestRoot optionalInt64Extension]] longLongValue]); - XCTAssertEqual(103U, [[message getExtension:[UnittestRoot optionalUint32Extension]] unsignedIntValue]); - XCTAssertEqual(104ULL, [[message getExtension:[UnittestRoot optionalUint64Extension]] unsignedLongLongValue]); + XCTAssertEqual(102LL, + [[message getExtension:[UnittestRoot optionalInt64Extension]] longLongValue]); + XCTAssertEqual(103U, + [[message getExtension:[UnittestRoot optionalUint32Extension]] unsignedIntValue]); + XCTAssertEqual(104ULL, [[message getExtension:[UnittestRoot optionalUint64Extension]] + unsignedLongLongValue]); XCTAssertEqual(105, [[message getExtension:[UnittestRoot optionalSint32Extension]] intValue]); - XCTAssertEqual(106LL, [[message getExtension:[UnittestRoot optionalSint64Extension]] longLongValue]); - XCTAssertEqual(107U, [[message getExtension:[UnittestRoot optionalFixed32Extension]] unsignedIntValue]); - XCTAssertEqual(108ULL, [[message getExtension:[UnittestRoot optionalFixed64Extension]] unsignedLongLongValue]); + XCTAssertEqual(106LL, + [[message getExtension:[UnittestRoot optionalSint64Extension]] longLongValue]); + XCTAssertEqual(107U, + [[message getExtension:[UnittestRoot optionalFixed32Extension]] unsignedIntValue]); + XCTAssertEqual(108ULL, [[message getExtension:[UnittestRoot optionalFixed64Extension]] + unsignedLongLongValue]); XCTAssertEqual(109, [[message getExtension:[UnittestRoot optionalSfixed32Extension]] intValue]); - XCTAssertEqual(110LL, [[message getExtension:[UnittestRoot optionalSfixed64Extension]] longLongValue]); - XCTAssertEqualWithAccuracy(111.0f, [[message getExtension:[UnittestRoot optionalFloatExtension]] floatValue], 0.01); - XCTAssertEqualWithAccuracy(112.0, [[message getExtension:[UnittestRoot optionalDoubleExtension]] doubleValue], 0.01); + XCTAssertEqual(110LL, + [[message getExtension:[UnittestRoot optionalSfixed64Extension]] longLongValue]); + XCTAssertEqualWithAccuracy( + 111.0f, [[message getExtension:[UnittestRoot optionalFloatExtension]] floatValue], 0.01); + XCTAssertEqualWithAccuracy( + 112.0, [[message getExtension:[UnittestRoot optionalDoubleExtension]] doubleValue], 0.01); XCTAssertTrue([[message getExtension:[UnittestRoot optionalBoolExtension]] boolValue]); XCTAssertEqualObjects(@"115", [message getExtension:[UnittestRoot optionalStringExtension]]); - XCTAssertEqualObjects([NSData gpbtu_dataWithEmbeddedNulls], [message getExtension:[UnittestRoot optionalBytesExtension]]); + XCTAssertEqualObjects([NSData gpbtu_dataWithEmbeddedNulls], + [message getExtension:[UnittestRoot optionalBytesExtension]]); - XCTAssertEqual(117, [(TestAllTypes_OptionalGroup*)[message getExtension:[UnittestRoot optionalGroupExtension]] a]); - XCTAssertEqual(118, [(TestAllTypes_NestedMessage*)[message getExtension:[UnittestRoot optionalNestedMessageExtension]] bb]); + XCTAssertEqual(117, [(TestAllTypes_OptionalGroup *)[message + getExtension:[UnittestRoot optionalGroupExtension]] a]); + XCTAssertEqual(118, [(TestAllTypes_NestedMessage *)[message + getExtension:[UnittestRoot optionalNestedMessageExtension]] bb]); XCTAssertEqual(119, [[message getExtension:[UnittestRoot optionalForeignMessageExtension]] c]); XCTAssertEqual(120, [[message getExtension:[UnittestRoot optionalImportMessageExtension]] d]); - XCTAssertEqual(TestAllTypes_NestedEnum_Baz, [[message getExtension:[UnittestRoot optionalNestedEnumExtension]] intValue]); - XCTAssertEqual(ForeignEnum_ForeignBaz, [[message getExtension:[UnittestRoot optionalForeignEnumExtension]] intValue]); - XCTAssertEqual(ImportEnum_ImportBaz, [[message getExtension:[UnittestRoot optionalImportEnumExtension]] intValue]); + XCTAssertEqual(TestAllTypes_NestedEnum_Baz, + [[message getExtension:[UnittestRoot optionalNestedEnumExtension]] intValue]); + XCTAssertEqual(ForeignEnum_ForeignBaz, + [[message getExtension:[UnittestRoot optionalForeignEnumExtension]] intValue]); + XCTAssertEqual(ImportEnum_ImportBaz, + [[message getExtension:[UnittestRoot optionalImportEnumExtension]] intValue]); XCTAssertEqualObjects(@"124", [message getExtension:[UnittestRoot optionalStringPieceExtension]]); XCTAssertEqualObjects(@"125", [message getExtension:[UnittestRoot optionalCordExtension]]); @@ -284,9 +258,12 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedBytesExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedGroupExtension]] count]); - XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedNestedMessageExtension]] count]); - XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedForeignMessageExtension]] count]); - XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedImportMessageExtension]] count]); + XCTAssertEqual(count, + [[message getExtension:[UnittestRoot repeatedNestedMessageExtension]] count]); + XCTAssertEqual(count, + [[message getExtension:[UnittestRoot repeatedForeignMessageExtension]] count]); + XCTAssertEqual(count, + [[message getExtension:[UnittestRoot repeatedImportMessageExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedNestedEnumExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedForeignEnumExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedImportEnumExtension]] count]); @@ -333,18 +310,20 @@ const uint32_t kGPBDefaultRepeatCount = 2; [data release]; extension = [message getExtension:[UnittestRoot repeatedGroupExtension]]; - XCTAssertEqual((int)(217 + i * 100), [(TestAllTypes_OptionalGroup*)extension[i] a]); + XCTAssertEqual((int)(217 + i * 100), [(TestAllTypes_OptionalGroup *)extension[i] a]); extension = [message getExtension:[UnittestRoot repeatedNestedMessageExtension]]; - XCTAssertEqual((int)(218 + i * 100), [(TestAllTypes_NestedMessage*)extension[i] bb]); + XCTAssertEqual((int)(218 + i * 100), [(TestAllTypes_NestedMessage *)extension[i] bb]); extension = [message getExtension:[UnittestRoot repeatedForeignMessageExtension]]; XCTAssertEqual((int)(219 + i * 100), [extension[i] c]); extension = [message getExtension:[UnittestRoot repeatedImportMessageExtension]]; XCTAssertEqual((int)(220 + i * 100), [extension[i] d]); extension = [message getExtension:[UnittestRoot repeatedNestedEnumExtension]]; - XCTAssertEqual((i % 2) ? TestAllTypes_NestedEnum_Bar : TestAllTypes_NestedEnum_Baz, [extension[i] intValue]); + XCTAssertEqual((i % 2) ? TestAllTypes_NestedEnum_Bar : TestAllTypes_NestedEnum_Baz, + [extension[i] intValue]); extension = [message getExtension:[UnittestRoot repeatedForeignEnumExtension]]; - XCTAssertEqual((i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz, [extension[i] intValue]); + XCTAssertEqual((i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz, + [extension[i] intValue]); extension = [message getExtension:[UnittestRoot repeatedImportEnumExtension]]; XCTAssertEqual((i % 2) ? ImportEnum_ImportBar : ImportEnum_ImportBaz, [extension[i] intValue]); @@ -385,24 +364,37 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertTrue([message hasExtension:[UnittestRoot defaultCordExtension]]); XCTAssertEqual(401, [[message getExtension:[UnittestRoot defaultInt32Extension]] intValue]); - XCTAssertEqual(402LL, [[message getExtension:[UnittestRoot defaultInt64Extension]] longLongValue]); - XCTAssertEqual(403U, [[message getExtension:[UnittestRoot defaultUint32Extension]] unsignedIntValue]); - XCTAssertEqual(404ULL, [[message getExtension:[UnittestRoot defaultUint64Extension]] unsignedLongLongValue]); + XCTAssertEqual(402LL, + [[message getExtension:[UnittestRoot defaultInt64Extension]] longLongValue]); + XCTAssertEqual(403U, + [[message getExtension:[UnittestRoot defaultUint32Extension]] unsignedIntValue]); + XCTAssertEqual( + 404ULL, [[message getExtension:[UnittestRoot defaultUint64Extension]] unsignedLongLongValue]); XCTAssertEqual(405, [[message getExtension:[UnittestRoot defaultSint32Extension]] intValue]); - XCTAssertEqual(406LL, [[message getExtension:[UnittestRoot defaultSint64Extension]] longLongValue]); - XCTAssertEqual(407U, [[message getExtension:[UnittestRoot defaultFixed32Extension]] unsignedIntValue]); - XCTAssertEqual(408ULL, [[message getExtension:[UnittestRoot defaultFixed64Extension]] unsignedLongLongValue]); + XCTAssertEqual(406LL, + [[message getExtension:[UnittestRoot defaultSint64Extension]] longLongValue]); + XCTAssertEqual(407U, + [[message getExtension:[UnittestRoot defaultFixed32Extension]] unsignedIntValue]); + XCTAssertEqual(408ULL, [[message getExtension:[UnittestRoot defaultFixed64Extension]] + unsignedLongLongValue]); XCTAssertEqual(409, [[message getExtension:[UnittestRoot defaultSfixed32Extension]] intValue]); - XCTAssertEqual(410LL,[[message getExtension:[UnittestRoot defaultSfixed64Extension]] longLongValue]); - XCTAssertEqualWithAccuracy(411.0f, [[message getExtension:[UnittestRoot defaultFloatExtension]] floatValue], 0.01); - XCTAssertEqualWithAccuracy(412.0, [[message getExtension:[UnittestRoot defaultDoubleExtension]] doubleValue], 0.01); + XCTAssertEqual(410LL, + [[message getExtension:[UnittestRoot defaultSfixed64Extension]] longLongValue]); + XCTAssertEqualWithAccuracy( + 411.0f, [[message getExtension:[UnittestRoot defaultFloatExtension]] floatValue], 0.01); + XCTAssertEqualWithAccuracy( + 412.0, [[message getExtension:[UnittestRoot defaultDoubleExtension]] doubleValue], 0.01); XCTAssertFalse([[message getExtension:[UnittestRoot defaultBoolExtension]] boolValue]); XCTAssertEqualObjects(@"415", [message getExtension:[UnittestRoot defaultStringExtension]]); - XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:416], [message getExtension:[UnittestRoot defaultBytesExtension]]); + XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:416], + [message getExtension:[UnittestRoot defaultBytesExtension]]); - XCTAssertEqual(TestAllTypes_NestedEnum_Foo, [[message getExtension:[UnittestRoot defaultNestedEnumExtension]] intValue]); - XCTAssertEqual(ForeignEnum_ForeignFoo, [[message getExtension:[UnittestRoot defaultForeignEnumExtension]] intValue]); - XCTAssertEqual(ImportEnum_ImportFoo, [[message getExtension:[UnittestRoot defaultImportEnumExtension]] intValue]); + XCTAssertEqual(TestAllTypes_NestedEnum_Foo, + [[message getExtension:[UnittestRoot defaultNestedEnumExtension]] intValue]); + XCTAssertEqual(ForeignEnum_ForeignFoo, + [[message getExtension:[UnittestRoot defaultForeignEnumExtension]] intValue]); + XCTAssertEqual(ImportEnum_ImportFoo, + [[message getExtension:[UnittestRoot defaultImportEnumExtension]] intValue]); XCTAssertEqualObjects(@"424", [message getExtension:[UnittestRoot defaultStringPieceExtension]]); XCTAssertEqualObjects(@"425", [message getExtension:[UnittestRoot defaultCordExtension]]); @@ -430,9 +422,12 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedBytesExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedGroupExtension]] count]); - XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedNestedMessageExtension]] count]); - XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedForeignMessageExtension]] count]); - XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedImportMessageExtension]] count]); + XCTAssertEqual(count, + [[message getExtension:[UnittestRoot repeatedNestedMessageExtension]] count]); + XCTAssertEqual(count, + [[message getExtension:[UnittestRoot repeatedForeignMessageExtension]] count]); + XCTAssertEqual(count, + [[message getExtension:[UnittestRoot repeatedImportMessageExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedNestedEnumExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedForeignEnumExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedImportEnumExtension]] count]); @@ -440,24 +435,37 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedStringPieceExtension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot repeatedCordExtension]] count]); - XCTAssertEqual(201,[[message getExtension:[UnittestRoot repeatedInt32Extension]][0] intValue]); - XCTAssertEqual(202LL, [[message getExtension:[UnittestRoot repeatedInt64Extension]][0] longLongValue]); - XCTAssertEqual(203U, [[message getExtension:[UnittestRoot repeatedUint32Extension]][0] unsignedIntValue]); - XCTAssertEqual(204ULL, [[message getExtension:[UnittestRoot repeatedUint64Extension]][0] unsignedLongLongValue]); + XCTAssertEqual(201, [[message getExtension:[UnittestRoot repeatedInt32Extension]][0] intValue]); + XCTAssertEqual(202LL, + [[message getExtension:[UnittestRoot repeatedInt64Extension]][0] longLongValue]); + XCTAssertEqual( + 203U, [[message getExtension:[UnittestRoot repeatedUint32Extension]][0] unsignedIntValue]); + XCTAssertEqual(204ULL, [[message getExtension:[UnittestRoot repeatedUint64Extension]][0] + unsignedLongLongValue]); XCTAssertEqual(205, [[message getExtension:[UnittestRoot repeatedSint32Extension]][0] intValue]); - XCTAssertEqual(206LL, [[message getExtension:[UnittestRoot repeatedSint64Extension]][0] longLongValue]); - XCTAssertEqual(207U, [[message getExtension:[UnittestRoot repeatedFixed32Extension]][0] unsignedIntValue]); - XCTAssertEqual(208ULL, [[message getExtension:[UnittestRoot repeatedFixed64Extension]][0] unsignedLongLongValue]); - XCTAssertEqual(209, [[message getExtension:[UnittestRoot repeatedSfixed32Extension]][0] intValue]); - XCTAssertEqual(210LL, [[message getExtension:[UnittestRoot repeatedSfixed64Extension]][0] longLongValue]); - XCTAssertEqualWithAccuracy(211.0f, [[message getExtension:[UnittestRoot repeatedFloatExtension]][0] floatValue], 0.01); - XCTAssertEqualWithAccuracy(212.0, [[message getExtension:[UnittestRoot repeatedDoubleExtension]][0] doubleValue], 0.01); + XCTAssertEqual(206LL, + [[message getExtension:[UnittestRoot repeatedSint64Extension]][0] longLongValue]); + XCTAssertEqual( + 207U, [[message getExtension:[UnittestRoot repeatedFixed32Extension]][0] unsignedIntValue]); + XCTAssertEqual(208ULL, [[message getExtension:[UnittestRoot repeatedFixed64Extension]][0] + unsignedLongLongValue]); + XCTAssertEqual(209, + [[message getExtension:[UnittestRoot repeatedSfixed32Extension]][0] intValue]); + XCTAssertEqual( + 210LL, [[message getExtension:[UnittestRoot repeatedSfixed64Extension]][0] longLongValue]); + XCTAssertEqualWithAccuracy( + 211.0f, [[message getExtension:[UnittestRoot repeatedFloatExtension]][0] floatValue], 0.01); + XCTAssertEqualWithAccuracy( + 212.0, [[message getExtension:[UnittestRoot repeatedDoubleExtension]][0] doubleValue], 0.01); XCTAssertFalse([[message getExtension:[UnittestRoot repeatedBoolExtension]][0] boolValue]); XCTAssertEqualObjects(@"215", [message getExtension:[UnittestRoot repeatedStringExtension]][0]); - XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:216], [message getExtension:[UnittestRoot repeatedBytesExtension]][0]); + XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:216], + [message getExtension:[UnittestRoot repeatedBytesExtension]][0]); - XCTAssertEqual(217, [(TestAllTypes_OptionalGroup*)[message getExtension:[UnittestRoot repeatedGroupExtension]][0] a]); - XCTAssertEqual(218, [(TestAllTypes_NestedMessage*)[message getExtension:[UnittestRoot repeatedNestedMessageExtension]][0] bb]); + XCTAssertEqual(217, [(TestAllTypes_OptionalGroup *)[message + getExtension:[UnittestRoot repeatedGroupExtension]][0] a]); + XCTAssertEqual(218, [(TestAllTypes_NestedMessage *)[message + getExtension:[UnittestRoot repeatedNestedMessageExtension]][0] bb]); XCTAssertEqual(219, [[message getExtension:[UnittestRoot repeatedForeignMessageExtension]][0] c]); XCTAssertEqual(220, [[message getExtension:[UnittestRoot repeatedImportMessageExtension]][0] d]); @@ -468,28 +476,42 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqual(ImportEnum_ImportBaz, [[message getExtension:[UnittestRoot repeatedImportEnumExtension]][0] intValue]); - XCTAssertEqualObjects(@"224", [message getExtension:[UnittestRoot repeatedStringPieceExtension]][0]); + XCTAssertEqualObjects(@"224", + [message getExtension:[UnittestRoot repeatedStringPieceExtension]][0]); XCTAssertEqualObjects(@"225", [message getExtension:[UnittestRoot repeatedCordExtension]][0]); // Actually verify the second (modified) elements now. XCTAssertEqual(501, [[message getExtension:[UnittestRoot repeatedInt32Extension]][1] intValue]); - XCTAssertEqual(502LL, [[message getExtension:[UnittestRoot repeatedInt64Extension]][1] longLongValue]); - XCTAssertEqual(503U, [[message getExtension:[UnittestRoot repeatedUint32Extension]][1] unsignedIntValue]); - XCTAssertEqual(504ULL, [[message getExtension:[UnittestRoot repeatedUint64Extension]][1] unsignedLongLongValue]); + XCTAssertEqual(502LL, + [[message getExtension:[UnittestRoot repeatedInt64Extension]][1] longLongValue]); + XCTAssertEqual( + 503U, [[message getExtension:[UnittestRoot repeatedUint32Extension]][1] unsignedIntValue]); + XCTAssertEqual(504ULL, [[message getExtension:[UnittestRoot repeatedUint64Extension]][1] + unsignedLongLongValue]); XCTAssertEqual(505, [[message getExtension:[UnittestRoot repeatedSint32Extension]][1] intValue]); - XCTAssertEqual(506LL, [[message getExtension:[UnittestRoot repeatedSint64Extension]][1] longLongValue]); - XCTAssertEqual(507U, [[message getExtension:[UnittestRoot repeatedFixed32Extension]][1] unsignedIntValue]); - XCTAssertEqual(508ULL, [[message getExtension:[UnittestRoot repeatedFixed64Extension]][1] unsignedLongLongValue]); - XCTAssertEqual(509, [[message getExtension:[UnittestRoot repeatedSfixed32Extension]][1] intValue]); - XCTAssertEqual(510LL, [[message getExtension:[UnittestRoot repeatedSfixed64Extension]][1] longLongValue]); - XCTAssertEqualWithAccuracy(511.0f, [[message getExtension:[UnittestRoot repeatedFloatExtension]][1] floatValue], 0.01); - XCTAssertEqualWithAccuracy(512.0, [[message getExtension:[UnittestRoot repeatedDoubleExtension]][1] doubleValue], 0.01); + XCTAssertEqual(506LL, + [[message getExtension:[UnittestRoot repeatedSint64Extension]][1] longLongValue]); + XCTAssertEqual( + 507U, [[message getExtension:[UnittestRoot repeatedFixed32Extension]][1] unsignedIntValue]); + XCTAssertEqual(508ULL, [[message getExtension:[UnittestRoot repeatedFixed64Extension]][1] + unsignedLongLongValue]); + XCTAssertEqual(509, + [[message getExtension:[UnittestRoot repeatedSfixed32Extension]][1] intValue]); + XCTAssertEqual( + 510LL, [[message getExtension:[UnittestRoot repeatedSfixed64Extension]][1] longLongValue]); + XCTAssertEqualWithAccuracy( + 511.0f, [[message getExtension:[UnittestRoot repeatedFloatExtension]][1] floatValue], 0.01); + XCTAssertEqualWithAccuracy( + 512.0, [[message getExtension:[UnittestRoot repeatedDoubleExtension]][1] doubleValue], 0.01); XCTAssertTrue([[message getExtension:[UnittestRoot repeatedBoolExtension]][1] boolValue]); XCTAssertEqualObjects(@"515", [message getExtension:[UnittestRoot repeatedStringExtension]][1]); - XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:516], [message getExtension:[UnittestRoot repeatedBytesExtension]][1]); + XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:516], + [message getExtension:[UnittestRoot repeatedBytesExtension]][1]); - XCTAssertEqual(517, [(TestAllTypes_OptionalGroup*)[message getExtension:[UnittestRoot repeatedGroupExtension]][1] a]); - XCTAssertEqual(518, [(TestAllTypes_NestedMessage*)[message getExtension:[UnittestRoot repeatedNestedMessageExtension]][1] bb]); + XCTAssertEqual(517, [(TestAllTypes_OptionalGroup *)[message + getExtension:[UnittestRoot repeatedGroupExtension]][1] a]); + XCTAssertEqual(518, [(TestAllTypes_NestedMessage *)[message + getExtension:[UnittestRoot repeatedNestedMessageExtension]][1] bb]); XCTAssertEqual(519, [[message getExtension:[UnittestRoot repeatedForeignMessageExtension]][1] c]); XCTAssertEqual(520, [[message getExtension:[UnittestRoot repeatedImportMessageExtension]][1] d]); @@ -500,14 +522,14 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqual(ImportEnum_ImportFoo, [[message getExtension:[UnittestRoot repeatedImportEnumExtension]][1] intValue]); - XCTAssertEqualObjects(@"524", [message getExtension:[UnittestRoot repeatedStringPieceExtension]][1]); + XCTAssertEqualObjects(@"524", + [message getExtension:[UnittestRoot repeatedStringPieceExtension]][1]); XCTAssertEqualObjects(@"525", [message getExtension:[UnittestRoot repeatedCordExtension]][1]); } // ------------------------------------------------------------------- -- (void)assertAllFieldsSet:(TestAllTypes *)message - repeatedCount:(uint32_t)count { +- (void)assertAllFieldsSet:(TestAllTypes *)message repeatedCount:(uint32_t)count { XCTAssertTrue(message.hasOptionalInt32); XCTAssertTrue(message.hasOptionalInt64); XCTAssertTrue(message.hasOptionalUint32); @@ -555,8 +577,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualWithAccuracy(112.0, message.optionalDouble, 0.1); XCTAssertTrue(message.optionalBool); XCTAssertEqualObjects(@"115", message.optionalString); - XCTAssertEqualObjects([NSData gpbtu_dataWithEmbeddedNulls], - message.optionalBytes); + XCTAssertEqualObjects([NSData gpbtu_dataWithEmbeddedNulls], message.optionalBytes); XCTAssertEqual(117, message.optionalGroup.a); XCTAssertEqual(118, message.optionalNestedMessage.bb); @@ -627,28 +648,19 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqual(count, message.repeatedCordArray_Count); for (uint32_t i = 0; i < count; ++i) { - XCTAssertEqual((int)(201 + i * 100), - [message.repeatedInt32Array valueAtIndex:i]); + XCTAssertEqual((int)(201 + i * 100), [message.repeatedInt32Array valueAtIndex:i]); XCTAssertEqual(202 + i * 100, [message.repeatedInt64Array valueAtIndex:i]); XCTAssertEqual(203 + i * 100, [message.repeatedUint32Array valueAtIndex:i]); XCTAssertEqual(204 + i * 100, [message.repeatedUint64Array valueAtIndex:i]); - XCTAssertEqual((int)(205 + i * 100), - [message.repeatedSint32Array valueAtIndex:i]); + XCTAssertEqual((int)(205 + i * 100), [message.repeatedSint32Array valueAtIndex:i]); XCTAssertEqual(206 + i * 100, [message.repeatedSint64Array valueAtIndex:i]); - XCTAssertEqual(207 + i * 100, - [message.repeatedFixed32Array valueAtIndex:i]); - XCTAssertEqual(208 + i * 100, - [message.repeatedFixed64Array valueAtIndex:i]); - XCTAssertEqual((int)(209 + i * 100), - [message.repeatedSfixed32Array valueAtIndex:i]); - XCTAssertEqual(210 + i * 100, - [message.repeatedSfixed64Array valueAtIndex:i]); - XCTAssertEqualWithAccuracy( - 211 + i * 100, [message.repeatedFloatArray valueAtIndex:i], 0.1); - XCTAssertEqualWithAccuracy( - 212 + i * 100, [message.repeatedDoubleArray valueAtIndex:i], 0.1); - XCTAssertEqual((i % 2) ? YES : NO, - [message.repeatedBoolArray valueAtIndex:i]); + XCTAssertEqual(207 + i * 100, [message.repeatedFixed32Array valueAtIndex:i]); + XCTAssertEqual(208 + i * 100, [message.repeatedFixed64Array valueAtIndex:i]); + XCTAssertEqual((int)(209 + i * 100), [message.repeatedSfixed32Array valueAtIndex:i]); + XCTAssertEqual(210 + i * 100, [message.repeatedSfixed64Array valueAtIndex:i]); + XCTAssertEqualWithAccuracy(211 + i * 100, [message.repeatedFloatArray valueAtIndex:i], 0.1); + XCTAssertEqualWithAccuracy(212 + i * 100, [message.repeatedDoubleArray valueAtIndex:i], 0.1); + XCTAssertEqual((i % 2) ? YES : NO, [message.repeatedBoolArray valueAtIndex:i]); NSString *string = [[NSString alloc] initWithFormat:@"%d", 215 + i * 100]; XCTAssertEqualObjects(string, message.repeatedStringArray[i]); @@ -658,14 +670,21 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects(data, message.repeatedBytesArray[i]); [data release]; - XCTAssertEqual((int)(217 + i * 100), ((TestAllTypes_RepeatedGroup*)message.repeatedGroupArray[i]).a); - XCTAssertEqual((int)(218 + i * 100), ((TestAllTypes_NestedMessage*)message.repeatedNestedMessageArray[i]).bb); - XCTAssertEqual((int)(219 + i * 100), ((ForeignMessage*)message.repeatedForeignMessageArray[i]).c); - XCTAssertEqual((int)(220 + i * 100), ((ImportMessage*)message.repeatedImportMessageArray[i]).d); - - XCTAssertEqual((i % 2) ? TestAllTypes_NestedEnum_Bar : TestAllTypes_NestedEnum_Baz, [message.repeatedNestedEnumArray valueAtIndex:i]); - XCTAssertEqual((i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz, [message.repeatedForeignEnumArray valueAtIndex:i]); - XCTAssertEqual((i % 2) ? ImportEnum_ImportBar : ImportEnum_ImportBaz, [message.repeatedImportEnumArray valueAtIndex:i]); + XCTAssertEqual((int)(217 + i * 100), + ((TestAllTypes_RepeatedGroup *)message.repeatedGroupArray[i]).a); + XCTAssertEqual((int)(218 + i * 100), + ((TestAllTypes_NestedMessage *)message.repeatedNestedMessageArray[i]).bb); + XCTAssertEqual((int)(219 + i * 100), + ((ForeignMessage *)message.repeatedForeignMessageArray[i]).c); + XCTAssertEqual((int)(220 + i * 100), + ((ImportMessage *)message.repeatedImportMessageArray[i]).d); + + XCTAssertEqual((i % 2) ? TestAllTypes_NestedEnum_Bar : TestAllTypes_NestedEnum_Baz, + [message.repeatedNestedEnumArray valueAtIndex:i]); + XCTAssertEqual((i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz, + [message.repeatedForeignEnumArray valueAtIndex:i]); + XCTAssertEqual((i % 2) ? ImportEnum_ImportBar : ImportEnum_ImportBaz, + [message.repeatedImportEnumArray valueAtIndex:i]); string = [[NSString alloc] initWithFormat:@"%d", 224 + i * 100]; XCTAssertEqualObjects(string, message.repeatedStringPieceArray[i]); @@ -715,8 +734,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualWithAccuracy(412.0, message.defaultDouble, 0.1); XCTAssertFalse(message.defaultBool); XCTAssertEqualObjects(@"415", message.defaultString); - XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:416], - message.defaultBytes); + XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:416], message.defaultBytes); XCTAssertEqual(TestAllTypes_NestedEnum_Foo, message.defaultNestedEnum); XCTAssertEqual(ForeignEnum_ForeignFoo, message.defaultForeignEnum); @@ -746,8 +764,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; TestAllTypes_OptionalGroup *allTypes = [TestAllTypes_OptionalGroup message]; [allTypes setA:117]; [message setOptionalGroup:allTypes]; - TestAllTypes_NestedMessage *nestedMessage = - [TestAllTypes_NestedMessage message]; + TestAllTypes_NestedMessage *nestedMessage = [TestAllTypes_NestedMessage message]; [nestedMessage setBb:118]; [message setOptionalNestedMessage:nestedMessage]; ForeignMessage *foreignMessage = [ForeignMessage message]; @@ -788,8 +805,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message.repeatedBytesArray addObject:data]; [data release]; - TestAllTypes_RepeatedGroup *testAll = - [[TestAllTypes_RepeatedGroup alloc] init]; + TestAllTypes_RepeatedGroup *testAll = [[TestAllTypes_RepeatedGroup alloc] init]; [testAll setA:217 + i * 100]; [message.repeatedGroupArray addObject:testAll]; [testAll release]; @@ -809,10 +825,13 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message.repeatedImportMessageArray addObject:importMessage]; [importMessage release]; - [message.repeatedNestedEnumArray addValue:(i % 2) ? TestAllTypes_NestedEnum_Bar : TestAllTypes_NestedEnum_Baz]; + [message.repeatedNestedEnumArray + addValue:(i % 2) ? TestAllTypes_NestedEnum_Bar : TestAllTypes_NestedEnum_Baz]; - [message.repeatedForeignEnumArray addValue:(i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz]; - [message.repeatedImportEnumArray addValue:(i % 2) ? ImportEnum_ImportBar : ImportEnum_ImportBaz]; + [message.repeatedForeignEnumArray + addValue:(i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz]; + [message.repeatedImportEnumArray + addValue:(i % 2) ? ImportEnum_ImportBar : ImportEnum_ImportBaz]; string = [[NSString alloc] initWithFormat:@"%d", 224 + i * 100]; [message.repeatedStringPieceArray addObject:string]; @@ -933,8 +952,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; message.hasDefaultCord = NO; } -- (void)setAllExtensions:(TestAllExtensions *)message - repeatedCount:(uint32_t)count { +- (void)setAllExtensions:(TestAllExtensions *)message repeatedCount:(uint32_t)count { [message setExtension:[UnittestRoot optionalInt32Extension] value:@101]; [message setExtension:[UnittestRoot optionalInt64Extension] value:@102L]; [message setExtension:[UnittestRoot optionalUint32Extension] value:@103]; @@ -954,60 +972,40 @@ const uint32_t kGPBDefaultRepeatCount = 2; OptionalGroup_extension *optionalGroup = [OptionalGroup_extension message]; [optionalGroup setA:117]; - [message setExtension:[UnittestRoot optionalGroupExtension] - value:optionalGroup]; - TestAllTypes_NestedMessage *nestedMessage = - [TestAllTypes_NestedMessage message]; + [message setExtension:[UnittestRoot optionalGroupExtension] value:optionalGroup]; + TestAllTypes_NestedMessage *nestedMessage = [TestAllTypes_NestedMessage message]; [nestedMessage setBb:118]; - [message setExtension:[UnittestRoot optionalNestedMessageExtension] - value:nestedMessage]; + [message setExtension:[UnittestRoot optionalNestedMessageExtension] value:nestedMessage]; ForeignMessage *foreignMessage = [ForeignMessage message]; [foreignMessage setC:119]; - [message setExtension:[UnittestRoot optionalForeignMessageExtension] - value:foreignMessage]; + [message setExtension:[UnittestRoot optionalForeignMessageExtension] value:foreignMessage]; ImportMessage *importMessage = [ImportMessage message]; [importMessage setD:120]; - [message setExtension:[UnittestRoot optionalImportMessageExtension] - value:importMessage]; + [message setExtension:[UnittestRoot optionalImportMessageExtension] value:importMessage]; [message setExtension:[UnittestRoot optionalNestedEnumExtension] value:@(TestAllTypes_NestedEnum_Baz)]; [message setExtension:[UnittestRoot optionalForeignEnumExtension] value:@(ForeignEnum_ForeignBaz)]; - [message setExtension:[UnittestRoot optionalImportEnumExtension] - value:@(ImportEnum_ImportBaz)]; + [message setExtension:[UnittestRoot optionalImportEnumExtension] value:@(ImportEnum_ImportBaz)]; - [message setExtension:[UnittestRoot optionalStringPieceExtension] - value:@"124"]; + [message setExtension:[UnittestRoot optionalStringPieceExtension] value:@"124"]; [message setExtension:[UnittestRoot optionalCordExtension] value:@"125"]; for (uint32_t i = 0; i < count; ++i) { - [message addExtension:[UnittestRoot repeatedInt32Extension] - value:@(201 + i * 100)]; - [message addExtension:[UnittestRoot repeatedInt64Extension] - value:@(202 + i * 100)]; - [message addExtension:[UnittestRoot repeatedUint32Extension] - value:@(203 + i * 100)]; - [message addExtension:[UnittestRoot repeatedUint64Extension] - value:@(204 + i * 100)]; - [message addExtension:[UnittestRoot repeatedSint32Extension] - value:@(205 + i * 100)]; - [message addExtension:[UnittestRoot repeatedSint64Extension] - value:@(206 + i * 100)]; - [message addExtension:[UnittestRoot repeatedFixed32Extension] - value:@(207 + i * 100)]; - [message addExtension:[UnittestRoot repeatedFixed64Extension] - value:@(208 + i * 100)]; - [message addExtension:[UnittestRoot repeatedSfixed32Extension] - value:@(209 + i * 100)]; - [message addExtension:[UnittestRoot repeatedSfixed64Extension] - value:@(210 + i * 100)]; - [message addExtension:[UnittestRoot repeatedFloatExtension] - value:@(211 + i * 100)]; - [message addExtension:[UnittestRoot repeatedDoubleExtension] - value:@(212 + i * 100)]; - [message addExtension:[UnittestRoot repeatedBoolExtension] - value:@((i % 2) ? YES : NO)]; + [message addExtension:[UnittestRoot repeatedInt32Extension] value:@(201 + i * 100)]; + [message addExtension:[UnittestRoot repeatedInt64Extension] value:@(202 + i * 100)]; + [message addExtension:[UnittestRoot repeatedUint32Extension] value:@(203 + i * 100)]; + [message addExtension:[UnittestRoot repeatedUint64Extension] value:@(204 + i * 100)]; + [message addExtension:[UnittestRoot repeatedSint32Extension] value:@(205 + i * 100)]; + [message addExtension:[UnittestRoot repeatedSint64Extension] value:@(206 + i * 100)]; + [message addExtension:[UnittestRoot repeatedFixed32Extension] value:@(207 + i * 100)]; + [message addExtension:[UnittestRoot repeatedFixed64Extension] value:@(208 + i * 100)]; + [message addExtension:[UnittestRoot repeatedSfixed32Extension] value:@(209 + i * 100)]; + [message addExtension:[UnittestRoot repeatedSfixed64Extension] value:@(210 + i * 100)]; + [message addExtension:[UnittestRoot repeatedFloatExtension] value:@(211 + i * 100)]; + [message addExtension:[UnittestRoot repeatedDoubleExtension] value:@(212 + i * 100)]; + [message addExtension:[UnittestRoot repeatedBoolExtension] value:@((i % 2) ? YES : NO)]; NSString *string = [[NSString alloc] initWithFormat:@"%d", 215 + i * 100]; [message addExtension:[UnittestRoot repeatedStringExtension] value:string]; [string release]; @@ -1015,40 +1013,31 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message addExtension:[UnittestRoot repeatedBytesExtension] value:data]; [data release]; - RepeatedGroup_extension *repeatedGroup = - [[RepeatedGroup_extension alloc] init]; + RepeatedGroup_extension *repeatedGroup = [[RepeatedGroup_extension alloc] init]; [repeatedGroup setA:217 + i * 100]; - [message addExtension:[UnittestRoot repeatedGroupExtension] - value:repeatedGroup]; + [message addExtension:[UnittestRoot repeatedGroupExtension] value:repeatedGroup]; [repeatedGroup release]; nestedMessage = [[TestAllTypes_NestedMessage alloc] init]; [nestedMessage setBb:218 + i * 100]; - [message addExtension:[UnittestRoot repeatedNestedMessageExtension] - value:nestedMessage]; + [message addExtension:[UnittestRoot repeatedNestedMessageExtension] value:nestedMessage]; [nestedMessage release]; foreignMessage = [[ForeignMessage alloc] init]; [foreignMessage setC:219 + i * 100]; - [message addExtension:[UnittestRoot repeatedForeignMessageExtension] - value:foreignMessage]; + [message addExtension:[UnittestRoot repeatedForeignMessageExtension] value:foreignMessage]; [foreignMessage release]; importMessage = [[ImportMessage alloc] init]; [importMessage setD:220 + i * 100]; - [message addExtension:[UnittestRoot repeatedImportMessageExtension] - value:importMessage]; + [message addExtension:[UnittestRoot repeatedImportMessageExtension] value:importMessage]; [importMessage release]; [message addExtension:[UnittestRoot repeatedNestedEnumExtension] - value:@((i % 2) ? TestAllTypes_NestedEnum_Bar - : TestAllTypes_NestedEnum_Baz)]; + value:@((i % 2) ? TestAllTypes_NestedEnum_Bar : TestAllTypes_NestedEnum_Baz)]; [message addExtension:[UnittestRoot repeatedForeignEnumExtension] - value:@((i % 2) ? ForeignEnum_ForeignBar - : ForeignEnum_ForeignBaz)]; - [message - addExtension:[UnittestRoot repeatedImportEnumExtension] - value:@((i % 2) ? ImportEnum_ImportBar : ImportEnum_ImportBaz)]; + value:@((i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz)]; + [message addExtension:[UnittestRoot repeatedImportEnumExtension] + value:@((i % 2) ? ImportEnum_ImportBar : ImportEnum_ImportBaz)]; string = [[NSString alloc] initWithFormat:@"%d", 224 + i * 100]; - [message addExtension:[UnittestRoot repeatedStringPieceExtension] - value:string]; + [message addExtension:[UnittestRoot repeatedStringPieceExtension] value:string]; [string release]; string = [[NSString alloc] initWithFormat:@"%d", 225 + i * 100]; @@ -1077,13 +1066,10 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message setExtension:[UnittestRoot defaultNestedEnumExtension] value:@(TestAllTypes_NestedEnum_Foo)]; - [message setExtension:[UnittestRoot defaultForeignEnumExtension] - value:@(ForeignEnum_ForeignFoo)]; - [message setExtension:[UnittestRoot defaultImportEnumExtension] - value:@(ImportEnum_ImportFoo)]; + [message setExtension:[UnittestRoot defaultForeignEnumExtension] value:@(ForeignEnum_ForeignFoo)]; + [message setExtension:[UnittestRoot defaultImportEnumExtension] value:@(ImportEnum_ImportFoo)]; - [message setExtension:[UnittestRoot defaultStringPieceExtension] - value:@"424"]; + [message setExtension:[UnittestRoot defaultStringPieceExtension] value:@"424"]; [message setExtension:[UnittestRoot defaultCordExtension] value:@"425"]; } @@ -1113,9 +1099,8 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message.mapInt32Bytes setObject:data forKey:113 + i * 100]; [data release]; - [message.mapInt32Enum - setEnum:(i % 2) ? MapEnum_MapEnumBar : MapEnum_MapEnumBaz - forKey:114 + i * 100]; + [message.mapInt32Enum setEnum:(i % 2) ? MapEnum_MapEnumBar : MapEnum_MapEnumBaz + forKey:114 + i * 100]; ForeignMessage *subMsg = [[ForeignMessage alloc] init]; subMsg.c = i + 1; @@ -1376,8 +1361,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualWithAccuracy(52e3, message.defaultDouble, 0.1); XCTAssertTrue(message.defaultBool); XCTAssertEqualObjects(@"hello", message.defaultString); - XCTAssertEqualObjects([NSData gpbtu_dataWithCString:"world"], - message.defaultBytes); + XCTAssertEqualObjects([NSData gpbtu_dataWithCString:"world"], message.defaultBytes); XCTAssertEqual(TestAllTypes_NestedEnum_Bar, message.defaultNestedEnum); XCTAssertEqual(ForeignEnum_ForeignBar, message.defaultForeignEnum); @@ -1419,20 +1403,29 @@ const uint32_t kGPBDefaultRepeatCount = 2; // Optional fields without defaults are set to zero or something like it. XCTAssertEqual(0, [[message getExtension:[UnittestRoot optionalInt32Extension]] intValue]); - XCTAssertEqual(0LL,[[message getExtension:[UnittestRoot optionalInt64Extension]] longLongValue]); - XCTAssertEqual(0U, [[message getExtension:[UnittestRoot optionalUint32Extension]] unsignedIntValue]); - XCTAssertEqual(0ULL, [[message getExtension:[UnittestRoot optionalUint64Extension]] unsignedLongLongValue]); + XCTAssertEqual(0LL, [[message getExtension:[UnittestRoot optionalInt64Extension]] longLongValue]); + XCTAssertEqual(0U, + [[message getExtension:[UnittestRoot optionalUint32Extension]] unsignedIntValue]); + XCTAssertEqual( + 0ULL, [[message getExtension:[UnittestRoot optionalUint64Extension]] unsignedLongLongValue]); XCTAssertEqual(0, [[message getExtension:[UnittestRoot optionalSint32Extension]] intValue]); - XCTAssertEqual(0LL, [[message getExtension:[UnittestRoot optionalSint64Extension]] longLongValue]); - XCTAssertEqual(0U, [[message getExtension:[UnittestRoot optionalFixed32Extension]] unsignedIntValue]); - XCTAssertEqual(0ULL, [[message getExtension:[UnittestRoot optionalFixed64Extension]] unsignedLongLongValue]); + XCTAssertEqual(0LL, + [[message getExtension:[UnittestRoot optionalSint64Extension]] longLongValue]); + XCTAssertEqual(0U, + [[message getExtension:[UnittestRoot optionalFixed32Extension]] unsignedIntValue]); + XCTAssertEqual( + 0ULL, [[message getExtension:[UnittestRoot optionalFixed64Extension]] unsignedLongLongValue]); XCTAssertEqual(0, [[message getExtension:[UnittestRoot optionalSfixed32Extension]] intValue]); - XCTAssertEqual(0LL, [[message getExtension:[UnittestRoot optionalSfixed64Extension]] longLongValue]); - XCTAssertEqualWithAccuracy(0.0f, [[message getExtension:[UnittestRoot optionalFloatExtension]] floatValue], 0.01); - XCTAssertEqualWithAccuracy(0.0, [[message getExtension:[UnittestRoot optionalDoubleExtension]] doubleValue], 0.01); + XCTAssertEqual(0LL, + [[message getExtension:[UnittestRoot optionalSfixed64Extension]] longLongValue]); + XCTAssertEqualWithAccuracy( + 0.0f, [[message getExtension:[UnittestRoot optionalFloatExtension]] floatValue], 0.01); + XCTAssertEqualWithAccuracy( + 0.0, [[message getExtension:[UnittestRoot optionalDoubleExtension]] doubleValue], 0.01); XCTAssertFalse([[message getExtension:[UnittestRoot optionalBoolExtension]] boolValue]); XCTAssertEqualObjects(@"", [message getExtension:[UnittestRoot optionalStringExtension]]); - XCTAssertEqualObjects(GPBEmptyNSData(), [message getExtension:[UnittestRoot optionalBytesExtension]]); + XCTAssertEqualObjects(GPBEmptyNSData(), + [message getExtension:[UnittestRoot optionalBytesExtension]]); // Embedded messages should also be clear. @@ -1441,18 +1434,20 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertFalse([[message getExtension:[UnittestRoot optionalForeignMessageExtension]] hasC]); XCTAssertFalse([[message getExtension:[UnittestRoot optionalImportMessageExtension]] hasD]); - XCTAssertEqual(0, [(TestAllTypes_OptionalGroup*)[message getExtension:[UnittestRoot optionalGroupExtension]] a]); - XCTAssertEqual(0, [(TestAllTypes_NestedMessage*)[message getExtension:[UnittestRoot optionalNestedMessageExtension]] bb]); + XCTAssertEqual(0, [(TestAllTypes_OptionalGroup *)[message + getExtension:[UnittestRoot optionalGroupExtension]] a]); + XCTAssertEqual(0, [(TestAllTypes_NestedMessage *)[message + getExtension:[UnittestRoot optionalNestedMessageExtension]] bb]); XCTAssertEqual(0, [[message getExtension:[UnittestRoot optionalForeignMessageExtension]] c]); XCTAssertEqual(0, [[message getExtension:[UnittestRoot optionalImportMessageExtension]] d]); // Enums without defaults are set to the first value in the enum. XCTAssertEqual(TestAllTypes_NestedEnum_Foo, - [[message getExtension:[UnittestRoot optionalNestedEnumExtension]] intValue]); + [[message getExtension:[UnittestRoot optionalNestedEnumExtension]] intValue]); XCTAssertEqual(ForeignEnum_ForeignFoo, - [[message getExtension:[UnittestRoot optionalForeignEnumExtension]] intValue]); + [[message getExtension:[UnittestRoot optionalForeignEnumExtension]] intValue]); XCTAssertEqual(ImportEnum_ImportFoo, - [[message getExtension:[UnittestRoot optionalImportEnumExtension]] intValue]); + [[message getExtension:[UnittestRoot optionalImportEnumExtension]] intValue]); XCTAssertEqualObjects(@"", [message getExtension:[UnittestRoot optionalStringPieceExtension]]); XCTAssertEqualObjects(@"", [message getExtension:[UnittestRoot optionalCordExtension]]); @@ -1510,28 +1505,36 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertFalse([message hasExtension:[UnittestRoot defaultCordExtension]]); // Fields with defaults have their default values (duh). - XCTAssertEqual( 41, [[message getExtension:[UnittestRoot defaultInt32Extension]] intValue]); - XCTAssertEqual( 42LL, [[message getExtension:[UnittestRoot defaultInt64Extension]] longLongValue]); - XCTAssertEqual( 43U, [[message getExtension:[UnittestRoot defaultUint32Extension]] unsignedIntValue]); - XCTAssertEqual( 44ULL, [[message getExtension:[UnittestRoot defaultUint64Extension]] unsignedLongLongValue]); + XCTAssertEqual(41, [[message getExtension:[UnittestRoot defaultInt32Extension]] intValue]); + XCTAssertEqual(42LL, [[message getExtension:[UnittestRoot defaultInt64Extension]] longLongValue]); + XCTAssertEqual(43U, + [[message getExtension:[UnittestRoot defaultUint32Extension]] unsignedIntValue]); + XCTAssertEqual( + 44ULL, [[message getExtension:[UnittestRoot defaultUint64Extension]] unsignedLongLongValue]); XCTAssertEqual(-45, [[message getExtension:[UnittestRoot defaultSint32Extension]] intValue]); - XCTAssertEqual( 46LL, [[message getExtension:[UnittestRoot defaultSint64Extension]] longLongValue]); - XCTAssertEqual( 47, [[message getExtension:[UnittestRoot defaultFixed32Extension]] intValue]); - XCTAssertEqual( 48ULL, [[message getExtension:[UnittestRoot defaultFixed64Extension]] unsignedLongLongValue]); - XCTAssertEqual( 49, [[message getExtension:[UnittestRoot defaultSfixed32Extension]] intValue]); - XCTAssertEqual(-50LL, [[message getExtension:[UnittestRoot defaultSfixed64Extension]] longLongValue]); - XCTAssertEqualWithAccuracy( 51.5f, [[message getExtension:[UnittestRoot defaultFloatExtension]] floatValue], 0.01); - XCTAssertEqualWithAccuracy( 52e3, [[message getExtension:[UnittestRoot defaultDoubleExtension]] doubleValue], 0.01); + XCTAssertEqual(46LL, + [[message getExtension:[UnittestRoot defaultSint64Extension]] longLongValue]); + XCTAssertEqual(47, [[message getExtension:[UnittestRoot defaultFixed32Extension]] intValue]); + XCTAssertEqual( + 48ULL, [[message getExtension:[UnittestRoot defaultFixed64Extension]] unsignedLongLongValue]); + XCTAssertEqual(49, [[message getExtension:[UnittestRoot defaultSfixed32Extension]] intValue]); + XCTAssertEqual(-50LL, + [[message getExtension:[UnittestRoot defaultSfixed64Extension]] longLongValue]); + XCTAssertEqualWithAccuracy( + 51.5f, [[message getExtension:[UnittestRoot defaultFloatExtension]] floatValue], 0.01); + XCTAssertEqualWithAccuracy( + 52e3, [[message getExtension:[UnittestRoot defaultDoubleExtension]] doubleValue], 0.01); XCTAssertTrue([[message getExtension:[UnittestRoot defaultBoolExtension]] boolValue]); XCTAssertEqualObjects(@"hello", [message getExtension:[UnittestRoot defaultStringExtension]]); - XCTAssertEqualObjects([NSData gpbtu_dataWithCString:"world"], [message getExtension:[UnittestRoot defaultBytesExtension]]); + XCTAssertEqualObjects([NSData gpbtu_dataWithCString:"world"], + [message getExtension:[UnittestRoot defaultBytesExtension]]); XCTAssertEqual(TestAllTypes_NestedEnum_Bar, - [[message getExtension:[UnittestRoot defaultNestedEnumExtension]] intValue]); + [[message getExtension:[UnittestRoot defaultNestedEnumExtension]] intValue]); XCTAssertEqual(ForeignEnum_ForeignBar, - [[message getExtension:[UnittestRoot defaultForeignEnumExtension]] intValue]); + [[message getExtension:[UnittestRoot defaultForeignEnumExtension]] intValue]); XCTAssertEqual(ImportEnum_ImportBar, - [[message getExtension:[UnittestRoot defaultImportEnumExtension]] intValue]); + [[message getExtension:[UnittestRoot defaultImportEnumExtension]] intValue]); XCTAssertEqualObjects(@"abc", [message getExtension:[UnittestRoot defaultStringPieceExtension]]); XCTAssertEqualObjects(@"123", [message getExtension:[UnittestRoot defaultCordExtension]]); @@ -1557,29 +1560,24 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message.repeatedBytesArray replaceObjectAtIndex:1 withObject:data]; [data release]; - TestAllTypes_RepeatedGroup *testAll = - [[TestAllTypes_RepeatedGroup alloc] init]; + TestAllTypes_RepeatedGroup *testAll = [[TestAllTypes_RepeatedGroup alloc] init]; [testAll setA:517]; [message.repeatedGroupArray replaceObjectAtIndex:1 withObject:testAll]; [testAll release]; - TestAllTypes_NestedMessage *nestedMessage = - [[TestAllTypes_NestedMessage alloc] init]; + TestAllTypes_NestedMessage *nestedMessage = [[TestAllTypes_NestedMessage alloc] init]; [nestedMessage setBb:518]; - [message.repeatedNestedMessageArray replaceObjectAtIndex:1 - withObject:nestedMessage]; + [message.repeatedNestedMessageArray replaceObjectAtIndex:1 withObject:nestedMessage]; [nestedMessage release]; ForeignMessage *foreignMessage = [[ForeignMessage alloc] init]; [foreignMessage setC:519]; - [message.repeatedForeignMessageArray replaceObjectAtIndex:1 - withObject:foreignMessage]; + [message.repeatedForeignMessageArray replaceObjectAtIndex:1 withObject:foreignMessage]; [foreignMessage release]; ImportMessage *importMessage = [[ImportMessage alloc] init]; [importMessage setD:520]; - [message.repeatedImportMessageArray replaceObjectAtIndex:1 - withObject:importMessage]; + [message.repeatedImportMessageArray replaceObjectAtIndex:1 withObject:importMessage]; [importMessage release]; [message.repeatedNestedEnumArray replaceValueAtIndex:1 withValue:TestAllTypes_NestedEnum_Foo]; @@ -1590,8 +1588,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message.repeatedCordArray replaceObjectAtIndex:1 withObject:@"525"]; } -- (void)assertRepeatedFieldsModified:(TestAllTypes *)message - repeatedCount:(uint32_t)count { +- (void)assertRepeatedFieldsModified:(TestAllTypes *)message repeatedCount:(uint32_t)count { // ModifyRepeatedFields only sets the second repeated element of each // field. In addition to verifying this, we also verify that the first // element and size were *not* modified. @@ -1664,13 +1661,12 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualWithAccuracy(212.0, [message.repeatedDoubleArray valueAtIndex:0], 0.01); XCTAssertFalse([message.repeatedBoolArray valueAtIndex:0]); XCTAssertEqualObjects(@"215", message.repeatedStringArray[0]); - XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:216], - message.repeatedBytesArray[0]); + XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:216], message.repeatedBytesArray[0]); - XCTAssertEqual(217, ((TestAllTypes_RepeatedGroup*)message.repeatedGroupArray[0]).a); - XCTAssertEqual(218, ((TestAllTypes_NestedMessage*)message.repeatedNestedMessageArray[0]).bb); - XCTAssertEqual(219, ((ForeignMessage*)message.repeatedForeignMessageArray[0]).c); - XCTAssertEqual(220, ((ImportMessage*)message.repeatedImportMessageArray[0]).d); + XCTAssertEqual(217, ((TestAllTypes_RepeatedGroup *)message.repeatedGroupArray[0]).a); + XCTAssertEqual(218, ((TestAllTypes_NestedMessage *)message.repeatedNestedMessageArray[0]).bb); + XCTAssertEqual(219, ((ForeignMessage *)message.repeatedForeignMessageArray[0]).c); + XCTAssertEqual(220, ((ImportMessage *)message.repeatedImportMessageArray[0]).d); XCTAssertEqual(TestAllTypes_NestedEnum_Baz, [message.repeatedNestedEnumArray valueAtIndex:0]); XCTAssertEqual(ForeignEnum_ForeignBaz, [message.repeatedForeignEnumArray valueAtIndex:0]); @@ -1694,13 +1690,12 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualWithAccuracy(512.0, [message.repeatedDoubleArray valueAtIndex:1], 0.01); XCTAssertTrue([message.repeatedBoolArray valueAtIndex:1]); XCTAssertEqualObjects(@"515", message.repeatedStringArray[1]); - XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:516], - message.repeatedBytesArray[1]); + XCTAssertEqualObjects([NSData gpbtu_dataWithUint32:516], message.repeatedBytesArray[1]); - XCTAssertEqual(517, ((TestAllTypes_RepeatedGroup*)message.repeatedGroupArray[1]).a); - XCTAssertEqual(518, ((TestAllTypes_NestedMessage*)message.repeatedNestedMessageArray[1]).bb); - XCTAssertEqual(519, ((ForeignMessage*)message.repeatedForeignMessageArray[1]).c); - XCTAssertEqual(520, ((ImportMessage*)message.repeatedImportMessageArray[1]).d); + XCTAssertEqual(517, ((TestAllTypes_RepeatedGroup *)message.repeatedGroupArray[1]).a); + XCTAssertEqual(518, ((TestAllTypes_NestedMessage *)message.repeatedNestedMessageArray[1]).bb); + XCTAssertEqual(519, ((ForeignMessage *)message.repeatedForeignMessageArray[1]).c); + XCTAssertEqual(520, ((ImportMessage *)message.repeatedImportMessageArray[1]).d); XCTAssertEqual(TestAllTypes_NestedEnum_Foo, [message.repeatedNestedEnumArray valueAtIndex:1]); XCTAssertEqual(ForeignEnum_ForeignFoo, [message.repeatedForeignEnumArray valueAtIndex:1]); @@ -1710,8 +1705,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects(@"525", message.repeatedCordArray[1]); } -- (void)setPackedFields:(TestPackedTypes *)message - repeatedCount:(uint32_t)count { +- (void)setPackedFields:(TestPackedTypes *)message repeatedCount:(uint32_t)count { // Must match -setUnpackedFields:repeatedCount: // Must match -setPackedExtensions:repeatedCount: // Must match -setUnpackedExtensions:repeatedCount: @@ -1755,13 +1749,11 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message.packedBoolArray addValue:(i % 2) ? YES : NO]; } for (uint32_t i = 0; i < count; ++i) { - [message.packedEnumArray - addValue:(i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz]; + [message.packedEnumArray addValue:(i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz]; } } -- (void)setUnpackedFields:(TestUnpackedTypes *)message - repeatedCount:(uint32_t)count { +- (void)setUnpackedFields:(TestUnpackedTypes *)message repeatedCount:(uint32_t)count { // Must match -setPackedFields:repeatedCount: // Must match -setPackedExtensions:repeatedCount: // Must match -setUnpackedExtensions:repeatedCount: @@ -1805,13 +1797,11 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message.unpackedBoolArray addValue:(i % 2) ? YES : NO]; } for (uint32_t i = 0; i < count; ++i) { - [message.unpackedEnumArray - addValue:(i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz]; + [message.unpackedEnumArray addValue:(i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz]; } } -- (void)assertPackedFieldsSet:(TestPackedTypes *)message - repeatedCount:(uint32_t)count { +- (void)assertPackedFieldsSet:(TestPackedTypes *)message repeatedCount:(uint32_t)count { XCTAssertEqual(count, message.packedInt32Array.count); XCTAssertEqual(count, message.packedInt64Array.count); XCTAssertEqual(count, message.packedUint32Array.count); @@ -1827,108 +1817,71 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqual(count, message.packedBoolArray.count); XCTAssertEqual(count, message.packedEnumArray.count); for (uint32_t i = 0; i < count; ++i) { - XCTAssertEqual((int)(601 + i * 100), - [message.packedInt32Array valueAtIndex:i]); + XCTAssertEqual((int)(601 + i * 100), [message.packedInt32Array valueAtIndex:i]); XCTAssertEqual(602 + i * 100, [message.packedInt64Array valueAtIndex:i]); XCTAssertEqual(603 + i * 100, [message.packedUint32Array valueAtIndex:i]); XCTAssertEqual(604 + i * 100, [message.packedUint64Array valueAtIndex:i]); - XCTAssertEqual((int)(605 + i * 100), - [message.packedSint32Array valueAtIndex:i]); + XCTAssertEqual((int)(605 + i * 100), [message.packedSint32Array valueAtIndex:i]); XCTAssertEqual(606 + i * 100, [message.packedSint64Array valueAtIndex:i]); XCTAssertEqual(607 + i * 100, [message.packedFixed32Array valueAtIndex:i]); XCTAssertEqual(608 + i * 100, [message.packedFixed64Array valueAtIndex:i]); - XCTAssertEqual((int)(609 + i * 100), - [message.packedSfixed32Array valueAtIndex:i]); + XCTAssertEqual((int)(609 + i * 100), [message.packedSfixed32Array valueAtIndex:i]); XCTAssertEqual(610 + i * 100, [message.packedSfixed64Array valueAtIndex:i]); - XCTAssertEqualWithAccuracy(611 + i * 100, - [message.packedFloatArray valueAtIndex:i], 0.01); - XCTAssertEqualWithAccuracy( - 612 + i * 100, [message.packedDoubleArray valueAtIndex:i], 0.01); - XCTAssertEqual((i % 2) ? YES : NO, - [message.packedBoolArray valueAtIndex:i]); + XCTAssertEqualWithAccuracy(611 + i * 100, [message.packedFloatArray valueAtIndex:i], 0.01); + XCTAssertEqualWithAccuracy(612 + i * 100, [message.packedDoubleArray valueAtIndex:i], 0.01); + XCTAssertEqual((i % 2) ? YES : NO, [message.packedBoolArray valueAtIndex:i]); XCTAssertEqual((i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz, [message.packedEnumArray valueAtIndex:i]); } } -- (void)setPackedExtensions:(TestPackedExtensions *)message - repeatedCount:(uint32_t)count { +- (void)setPackedExtensions:(TestPackedExtensions *)message repeatedCount:(uint32_t)count { // Must match -setPackedFields:repeatedCount: // Must match -setUnpackedFields:repeatedCount: // Must match -setUnpackedExtensions:repeatedCount: for (uint32_t i = 0; i < count; i++) { - [message addExtension:[UnittestRoot packedInt32Extension] - value:@(601 + i * 100)]; - [message addExtension:[UnittestRoot packedInt64Extension] - value:@(602 + i * 100)]; - [message addExtension:[UnittestRoot packedUint32Extension] - value:@(603 + i * 100)]; - [message addExtension:[UnittestRoot packedUint64Extension] - value:@(604 + i * 100)]; - [message addExtension:[UnittestRoot packedSint32Extension] - value:@(605 + i * 100)]; - [message addExtension:[UnittestRoot packedSint64Extension] - value:@(606 + i * 100)]; - [message addExtension:[UnittestRoot packedFixed32Extension] - value:@(607 + i * 100)]; - [message addExtension:[UnittestRoot packedFixed64Extension] - value:@(608 + i * 100)]; - [message addExtension:[UnittestRoot packedSfixed32Extension] - value:@(609 + i * 100)]; - [message addExtension:[UnittestRoot packedSfixed64Extension] - value:@(610 + i * 100)]; - [message addExtension:[UnittestRoot packedFloatExtension] - value:@(611 + i * 100)]; - [message addExtension:[UnittestRoot packedDoubleExtension] - value:@(612 + i * 100)]; - [message addExtension:[UnittestRoot packedBoolExtension] - value:@((i % 2) ? YES : NO)]; + [message addExtension:[UnittestRoot packedInt32Extension] value:@(601 + i * 100)]; + [message addExtension:[UnittestRoot packedInt64Extension] value:@(602 + i * 100)]; + [message addExtension:[UnittestRoot packedUint32Extension] value:@(603 + i * 100)]; + [message addExtension:[UnittestRoot packedUint64Extension] value:@(604 + i * 100)]; + [message addExtension:[UnittestRoot packedSint32Extension] value:@(605 + i * 100)]; + [message addExtension:[UnittestRoot packedSint64Extension] value:@(606 + i * 100)]; + [message addExtension:[UnittestRoot packedFixed32Extension] value:@(607 + i * 100)]; + [message addExtension:[UnittestRoot packedFixed64Extension] value:@(608 + i * 100)]; + [message addExtension:[UnittestRoot packedSfixed32Extension] value:@(609 + i * 100)]; + [message addExtension:[UnittestRoot packedSfixed64Extension] value:@(610 + i * 100)]; + [message addExtension:[UnittestRoot packedFloatExtension] value:@(611 + i * 100)]; + [message addExtension:[UnittestRoot packedDoubleExtension] value:@(612 + i * 100)]; + [message addExtension:[UnittestRoot packedBoolExtension] value:@((i % 2) ? YES : NO)]; [message addExtension:[UnittestRoot packedEnumExtension] - value:@((i % 2) ? ForeignEnum_ForeignBar - : ForeignEnum_ForeignBaz)]; + value:@((i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz)]; } } -- (void)setUnpackedExtensions:(TestUnpackedExtensions *)message - repeatedCount:(uint32_t)count { +- (void)setUnpackedExtensions:(TestUnpackedExtensions *)message repeatedCount:(uint32_t)count { // Must match -setPackedFields:repeatedCount: // Must match -setUnpackedFields:repeatedCount: // Must match -setPackedExtensions:repeatedCount: for (uint32_t i = 0; i < count; i++) { - [message addExtension:[UnittestRoot unpackedInt32Extension] - value:@(601 + i * 100)]; - [message addExtension:[UnittestRoot unpackedInt64Extension] - value:@(602 + i * 100)]; - [message addExtension:[UnittestRoot unpackedUint32Extension] - value:@(603 + i * 100)]; - [message addExtension:[UnittestRoot unpackedUint64Extension] - value:@(604 + i * 100)]; - [message addExtension:[UnittestRoot unpackedSint32Extension] - value:@(605 + i * 100)]; - [message addExtension:[UnittestRoot unpackedSint64Extension] - value:@(606 + i * 100)]; - [message addExtension:[UnittestRoot unpackedFixed32Extension] - value:@(607 + i * 100)]; - [message addExtension:[UnittestRoot unpackedFixed64Extension] - value:@(608 + i * 100)]; - [message addExtension:[UnittestRoot unpackedSfixed32Extension] - value:@(609 + i * 100)]; - [message addExtension:[UnittestRoot unpackedSfixed64Extension] - value:@(610 + i * 100)]; - [message addExtension:[UnittestRoot unpackedFloatExtension] - value:@(611 + i * 100)]; - [message addExtension:[UnittestRoot unpackedDoubleExtension] - value:@(612 + i * 100)]; - [message addExtension:[UnittestRoot unpackedBoolExtension] - value:@((i % 2) ? YES : NO)]; + [message addExtension:[UnittestRoot unpackedInt32Extension] value:@(601 + i * 100)]; + [message addExtension:[UnittestRoot unpackedInt64Extension] value:@(602 + i * 100)]; + [message addExtension:[UnittestRoot unpackedUint32Extension] value:@(603 + i * 100)]; + [message addExtension:[UnittestRoot unpackedUint64Extension] value:@(604 + i * 100)]; + [message addExtension:[UnittestRoot unpackedSint32Extension] value:@(605 + i * 100)]; + [message addExtension:[UnittestRoot unpackedSint64Extension] value:@(606 + i * 100)]; + [message addExtension:[UnittestRoot unpackedFixed32Extension] value:@(607 + i * 100)]; + [message addExtension:[UnittestRoot unpackedFixed64Extension] value:@(608 + i * 100)]; + [message addExtension:[UnittestRoot unpackedSfixed32Extension] value:@(609 + i * 100)]; + [message addExtension:[UnittestRoot unpackedSfixed64Extension] value:@(610 + i * 100)]; + [message addExtension:[UnittestRoot unpackedFloatExtension] value:@(611 + i * 100)]; + [message addExtension:[UnittestRoot unpackedDoubleExtension] value:@(612 + i * 100)]; + [message addExtension:[UnittestRoot unpackedBoolExtension] value:@((i % 2) ? YES : NO)]; [message addExtension:[UnittestRoot unpackedEnumExtension] - value:@((i % 2) ? ForeignEnum_ForeignBar - : ForeignEnum_ForeignBaz)]; + value:@((i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz)]; } } -- (void)assertPackedExtensionsSet:(TestPackedExtensions *)message - repeatedCount:(uint32_t)count{ +- (void)assertPackedExtensionsSet:(TestPackedExtensions *)message repeatedCount:(uint32_t)count { XCTAssertEqual(count, [[message getExtension:[UnittestRoot packedInt32Extension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot packedInt64Extension]] count]); XCTAssertEqual(count, [[message getExtension:[UnittestRoot packedUint32Extension]] count]); @@ -2016,20 +1969,24 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects([message valueForKey:@"hasOptionalNestedMessage"], @YES); XCTAssertNotNil(message.optionalNestedMessage); XCTAssertEqualObjects([message valueForKeyPath:@"optionalNestedMessage.hasBb"], @YES); - XCTAssertEqualObjects(@(message.optionalNestedMessage.bb), [message valueForKeyPath:@"optionalNestedMessage.bb"]); + XCTAssertEqualObjects(@(message.optionalNestedMessage.bb), + [message valueForKeyPath:@"optionalNestedMessage.bb"]); XCTAssertEqualObjects([message valueForKey:@"hasOptionalForeignMessage"], @YES); XCTAssertNotNil(message.optionalForeignMessage); XCTAssertEqualObjects([message valueForKeyPath:@"optionalForeignMessage.hasC"], @YES); - XCTAssertEqualObjects(@(message.optionalForeignMessage.c), [message valueForKeyPath:@"optionalForeignMessage.c"]); + XCTAssertEqualObjects(@(message.optionalForeignMessage.c), + [message valueForKeyPath:@"optionalForeignMessage.c"]); XCTAssertEqualObjects([message valueForKey:@"hasOptionalImportMessage"], @YES); XCTAssertNotNil(message.optionalForeignMessage); XCTAssertEqualObjects([message valueForKeyPath:@"optionalImportMessage.hasD"], @YES); - XCTAssertEqualObjects(@(message.optionalImportMessage.d), [message valueForKeyPath:@"optionalImportMessage.d"]); + XCTAssertEqualObjects(@(message.optionalImportMessage.d), + [message valueForKeyPath:@"optionalImportMessage.d"]); XCTAssertEqualObjects([message valueForKey:@"hasOptionalNestedEnum"], @YES); XCTAssertEqualObjects(@(message.optionalNestedEnum), [message valueForKey:@"optionalNestedEnum"]); XCTAssertEqualObjects([message valueForKey:@"hasOptionalForeignEnum"], @YES); - XCTAssertEqualObjects(@(message.optionalForeignEnum), [message valueForKey:@"optionalForeignEnum"]); + XCTAssertEqualObjects(@(message.optionalForeignEnum), + [message valueForKey:@"optionalForeignEnum"]); XCTAssertEqualObjects([message valueForKey:@"hasOptionalImportEnum"], @YES); XCTAssertEqualObjects(@(message.optionalImportEnum), [message valueForKey:@"optionalImportEnum"]); @@ -2048,10 +2005,14 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects(message.repeatedUint64Array, [message valueForKey:@"repeatedUint64Array"]); XCTAssertEqualObjects(message.repeatedSint32Array, [message valueForKey:@"repeatedSint32Array"]); XCTAssertEqualObjects(message.repeatedSint64Array, [message valueForKey:@"repeatedSint64Array"]); - XCTAssertEqualObjects(message.repeatedFixed32Array, [message valueForKey:@"repeatedFixed32Array"]); - XCTAssertEqualObjects(message.repeatedFixed64Array, [message valueForKey:@"repeatedFixed64Array"]); - XCTAssertEqualObjects(message.repeatedSfixed32Array, [message valueForKey:@"repeatedSfixed32Array"]); - XCTAssertEqualObjects(message.repeatedSfixed64Array, [message valueForKey:@"repeatedSfixed64Array"]); + XCTAssertEqualObjects(message.repeatedFixed32Array, + [message valueForKey:@"repeatedFixed32Array"]); + XCTAssertEqualObjects(message.repeatedFixed64Array, + [message valueForKey:@"repeatedFixed64Array"]); + XCTAssertEqualObjects(message.repeatedSfixed32Array, + [message valueForKey:@"repeatedSfixed32Array"]); + XCTAssertEqualObjects(message.repeatedSfixed64Array, + [message valueForKey:@"repeatedSfixed64Array"]); XCTAssertEqualObjects(message.repeatedFloatArray, [message valueForKey:@"repeatedFloatArray"]); XCTAssertEqualObjects(message.repeatedDoubleArray, [message valueForKey:@"repeatedDoubleArray"]); XCTAssertEqualObjects(message.repeatedBoolArray, [message valueForKey:@"repeatedBoolArray"]); @@ -2059,44 +2020,75 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects(message.repeatedBytesArray, [message valueForKey:@"repeatedBytesArray"]); XCTAssertEqualObjects(message.repeatedGroupArray, [message valueForKey:@"repeatedGroupArray"]); - XCTAssertEqualObjects(message.repeatedNestedMessageArray, [message valueForKey:@"repeatedNestedMessageArray"]); - XCTAssertEqualObjects(message.repeatedForeignMessageArray, [message valueForKey:@"repeatedForeignMessageArray"]); - XCTAssertEqualObjects(message.repeatedImportMessageArray, [message valueForKey:@"repeatedImportMessageArray"]); - - XCTAssertEqualObjects(message.repeatedNestedEnumArray, [message valueForKey:@"repeatedNestedEnumArray"]); - XCTAssertEqualObjects(message.repeatedForeignEnumArray, [message valueForKey:@"repeatedForeignEnumArray"]); - XCTAssertEqualObjects(message.repeatedImportEnumArray, [message valueForKey:@"repeatedImportEnumArray"]); - - XCTAssertEqualObjects(message.repeatedStringPieceArray, [message valueForKey:@"repeatedStringPieceArray"]); + XCTAssertEqualObjects(message.repeatedNestedMessageArray, + [message valueForKey:@"repeatedNestedMessageArray"]); + XCTAssertEqualObjects(message.repeatedForeignMessageArray, + [message valueForKey:@"repeatedForeignMessageArray"]); + XCTAssertEqualObjects(message.repeatedImportMessageArray, + [message valueForKey:@"repeatedImportMessageArray"]); + + XCTAssertEqualObjects(message.repeatedNestedEnumArray, + [message valueForKey:@"repeatedNestedEnumArray"]); + XCTAssertEqualObjects(message.repeatedForeignEnumArray, + [message valueForKey:@"repeatedForeignEnumArray"]); + XCTAssertEqualObjects(message.repeatedImportEnumArray, + [message valueForKey:@"repeatedImportEnumArray"]); + + XCTAssertEqualObjects(message.repeatedStringPieceArray, + [message valueForKey:@"repeatedStringPieceArray"]); XCTAssertEqualObjects(message.repeatedCordArray, [message valueForKey:@"repeatedCordArray"]); - XCTAssertEqualObjects(@(message.repeatedInt32Array_Count), [message valueForKey:@"repeatedInt32Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedInt64Array_Count), [message valueForKey:@"repeatedInt64Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedUint32Array_Count), [message valueForKey:@"repeatedUint32Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedUint64Array_Count), [message valueForKey:@"repeatedUint64Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedSint32Array_Count), [message valueForKey:@"repeatedSint32Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedSint64Array_Count), [message valueForKey:@"repeatedSint64Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedFixed32Array_Count), [message valueForKey:@"repeatedFixed32Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedFixed64Array_Count), [message valueForKey:@"repeatedFixed64Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedSfixed32Array_Count), [message valueForKey:@"repeatedSfixed32Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedSfixed64Array_Count), [message valueForKey:@"repeatedSfixed64Array_Count"]); - XCTAssertEqualObjects(@(message.repeatedFloatArray_Count), [message valueForKey:@"repeatedFloatArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedDoubleArray_Count), [message valueForKey:@"repeatedDoubleArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedBoolArray_Count), [message valueForKey:@"repeatedBoolArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedStringArray_Count), [message valueForKey:@"repeatedStringArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedBytesArray_Count), [message valueForKey:@"repeatedBytesArray_Count"]); - - XCTAssertEqualObjects(@(message.repeatedGroupArray_Count), [message valueForKey:@"repeatedGroupArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedNestedMessageArray_Count), [message valueForKey:@"repeatedNestedMessageArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedForeignMessageArray_Count), [message valueForKey:@"repeatedForeignMessageArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedImportMessageArray_Count), [message valueForKey:@"repeatedImportMessageArray_Count"]); - - XCTAssertEqualObjects(@(message.repeatedNestedEnumArray_Count), [message valueForKey:@"repeatedNestedEnumArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedForeignEnumArray_Count), [message valueForKey:@"repeatedForeignEnumArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedImportEnumArray_Count), [message valueForKey:@"repeatedImportEnumArray_Count"]); - - XCTAssertEqualObjects(@(message.repeatedStringPieceArray_Count), [message valueForKey:@"repeatedStringPieceArray_Count"]); - XCTAssertEqualObjects(@(message.repeatedCordArray_Count), [message valueForKey:@"repeatedCordArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedInt32Array_Count), + [message valueForKey:@"repeatedInt32Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedInt64Array_Count), + [message valueForKey:@"repeatedInt64Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedUint32Array_Count), + [message valueForKey:@"repeatedUint32Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedUint64Array_Count), + [message valueForKey:@"repeatedUint64Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedSint32Array_Count), + [message valueForKey:@"repeatedSint32Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedSint64Array_Count), + [message valueForKey:@"repeatedSint64Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedFixed32Array_Count), + [message valueForKey:@"repeatedFixed32Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedFixed64Array_Count), + [message valueForKey:@"repeatedFixed64Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedSfixed32Array_Count), + [message valueForKey:@"repeatedSfixed32Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedSfixed64Array_Count), + [message valueForKey:@"repeatedSfixed64Array_Count"]); + XCTAssertEqualObjects(@(message.repeatedFloatArray_Count), + [message valueForKey:@"repeatedFloatArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedDoubleArray_Count), + [message valueForKey:@"repeatedDoubleArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedBoolArray_Count), + [message valueForKey:@"repeatedBoolArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedStringArray_Count), + [message valueForKey:@"repeatedStringArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedBytesArray_Count), + [message valueForKey:@"repeatedBytesArray_Count"]); + + XCTAssertEqualObjects(@(message.repeatedGroupArray_Count), + [message valueForKey:@"repeatedGroupArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedNestedMessageArray_Count), + [message valueForKey:@"repeatedNestedMessageArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedForeignMessageArray_Count), + [message valueForKey:@"repeatedForeignMessageArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedImportMessageArray_Count), + [message valueForKey:@"repeatedImportMessageArray_Count"]); + + XCTAssertEqualObjects(@(message.repeatedNestedEnumArray_Count), + [message valueForKey:@"repeatedNestedEnumArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedForeignEnumArray_Count), + [message valueForKey:@"repeatedForeignEnumArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedImportEnumArray_Count), + [message valueForKey:@"repeatedImportEnumArray_Count"]); + + XCTAssertEqualObjects(@(message.repeatedStringPieceArray_Count), + [message valueForKey:@"repeatedStringPieceArray_Count"]); + XCTAssertEqualObjects(@(message.repeatedCordArray_Count), + [message valueForKey:@"repeatedCordArray_Count"]); // ----------------------------------------------------------------- @@ -2144,8 +2136,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects(message.defaultCord, [message valueForKey:@"defaultCord"]); } -- (void)setAllFieldsViaKVC:(TestAllTypes *)message - repeatedCount:(uint32_t)count { +- (void)setAllFieldsViaKVC:(TestAllTypes *)message repeatedCount:(uint32_t)count { [message setValue:@101 forKey:@"optionalInt32"]; [message setValue:@102 forKey:@"optionalInt64"]; [message setValue:@103 forKey:@"optionalUint32"]; @@ -2160,14 +2151,12 @@ const uint32_t kGPBDefaultRepeatCount = 2; [message setValue:@112 forKey:@"optionalDouble"]; [message setValue:@YES forKey:@"optionalBool"]; [message setValue:@"115" forKey:@"optionalString"]; - [message setValue:[NSData gpbtu_dataWithEmbeddedNulls] - forKey:@"optionalBytes"]; + [message setValue:[NSData gpbtu_dataWithEmbeddedNulls] forKey:@"optionalBytes"]; TestAllTypes_OptionalGroup *allTypes = [TestAllTypes_OptionalGroup message]; [allTypes setValue:@117 forKey:@"a"]; [message setValue:allTypes forKey:@"optionalGroup"]; - TestAllTypes_NestedMessage *nestedMessage = - [TestAllTypes_NestedMessage message]; + TestAllTypes_NestedMessage *nestedMessage = [TestAllTypes_NestedMessage message]; [nestedMessage setValue:@118 forKey:@"bb"]; [message setValue:nestedMessage forKey:@"optionalNestedMessage"]; ForeignMessage *foreignMessage = [ForeignMessage message]; @@ -2177,8 +2166,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; [importMessage setValue:@120 forKey:@"d"]; [message setValue:importMessage forKey:@"optionalImportMessage"]; - [message setValue:@(TestAllTypes_NestedEnum_Baz) - forKey:@"optionalNestedEnum"]; + [message setValue:@(TestAllTypes_NestedEnum_Baz) forKey:@"optionalNestedEnum"]; [message setValue:@(ForeignEnum_ForeignBaz) forKey:@"optionalForeignEnum"]; [message setValue:@(ImportEnum_ImportBaz) forKey:@"optionalImportEnum"]; @@ -2299,8 +2287,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; array = [[NSMutableArray alloc] initWithCapacity:count]; for (uint32_t i = 0; i < count; ++i) { - TestAllTypes_RepeatedGroup *testAll = - [[TestAllTypes_RepeatedGroup alloc] init]; + TestAllTypes_RepeatedGroup *testAll = [[TestAllTypes_RepeatedGroup alloc] init]; [testAll setA:217 + i * 100]; [array addObject:testAll]; [testAll release]; @@ -2339,26 +2326,22 @@ const uint32_t kGPBDefaultRepeatCount = 2; [array release]; { - GPBEnumArray *scratch = [GPBEnumArray - arrayWithValidationFunction:TestAllTypes_NestedEnum_IsValidValue]; + GPBEnumArray *scratch = + [GPBEnumArray arrayWithValidationFunction:TestAllTypes_NestedEnum_IsValidValue]; for (uint32_t i = 0; i < count; ++i) { - [scratch addValue:(i % 2) ? TestAllTypes_NestedEnum_Bar - : TestAllTypes_NestedEnum_Baz]; + [scratch addValue:(i % 2) ? TestAllTypes_NestedEnum_Bar : TestAllTypes_NestedEnum_Baz]; } [message setValue:scratch forKey:@"repeatedNestedEnumArray"]; } { - GPBEnumArray *scratch = - [GPBEnumArray arrayWithValidationFunction:ForeignEnum_IsValidValue]; + GPBEnumArray *scratch = [GPBEnumArray arrayWithValidationFunction:ForeignEnum_IsValidValue]; for (uint32_t i = 0; i < count; ++i) { - [scratch - addValue:(i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz]; + [scratch addValue:(i % 2) ? ForeignEnum_ForeignBar : ForeignEnum_ForeignBaz]; } [message setValue:scratch forKey:@"repeatedForeignEnumArray"]; } { - GPBEnumArray *scratch = - [GPBEnumArray arrayWithValidationFunction:ImportEnum_IsValidValue]; + GPBEnumArray *scratch = [GPBEnumArray arrayWithValidationFunction:ImportEnum_IsValidValue]; for (uint32_t i = 0; i < count; ++i) { [scratch addValue:(i % 2) ? ImportEnum_ImportBar : ImportEnum_ImportBaz]; } @@ -2428,8 +2411,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects([message valueForKey:@"hasOptionalGroup"], @NO); XCTAssertEqualObjects([message valueForKey:@"hasOptionalNestedMessage"], @NO); - XCTAssertEqualObjects([message valueForKey:@"hasOptionalForeignMessage"], - @NO); + XCTAssertEqualObjects([message valueForKey:@"hasOptionalForeignMessage"], @NO); XCTAssertEqualObjects([message valueForKey:@"hasOptionalImportMessage"], @NO); XCTAssertEqualObjects([message valueForKey:@"hasOptionalNestedEnum"], @NO); @@ -2454,8 +2436,7 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects([message valueForKey:@"optionalDouble"], @0); XCTAssertEqualObjects([message valueForKey:@"optionalBool"], @NO); XCTAssertEqualObjects([message valueForKey:@"optionalString"], @""); - XCTAssertEqualObjects([message valueForKey:@"optionalBytes"], - GPBEmptyNSData()); + XCTAssertEqualObjects([message valueForKey:@"optionalBytes"], GPBEmptyNSData()); // Embedded messages should also be exist, but be clear. XCTAssertNotNil([message valueForKeyPath:@"optionalGroup"]); @@ -2463,28 +2444,20 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertNotNil([message valueForKeyPath:@"optionalForeignMessage"]); XCTAssertNotNil([message valueForKeyPath:@"optionalImportMessage"]); XCTAssertEqualObjects([message valueForKeyPath:@"optionalGroup.hasA"], @NO); - XCTAssertEqualObjects( - [message valueForKeyPath:@"optionalNestedMessage.hasBb"], @NO); - XCTAssertEqualObjects( - [message valueForKeyPath:@"optionalForeignMessage.hasC"], @NO); - XCTAssertEqualObjects([message valueForKeyPath:@"optionalImportMessage.hasD"], - @NO); + XCTAssertEqualObjects([message valueForKeyPath:@"optionalNestedMessage.hasBb"], @NO); + XCTAssertEqualObjects([message valueForKeyPath:@"optionalForeignMessage.hasC"], @NO); + XCTAssertEqualObjects([message valueForKeyPath:@"optionalImportMessage.hasD"], @NO); XCTAssertEqualObjects([message valueForKeyPath:@"optionalGroup.a"], @0); - XCTAssertEqualObjects([message valueForKeyPath:@"optionalNestedMessage.bb"], - @0); - XCTAssertEqualObjects([message valueForKeyPath:@"optionalForeignMessage.c"], - @0); - XCTAssertEqualObjects([message valueForKeyPath:@"optionalImportMessage.d"], - @0); + XCTAssertEqualObjects([message valueForKeyPath:@"optionalNestedMessage.bb"], @0); + XCTAssertEqualObjects([message valueForKeyPath:@"optionalForeignMessage.c"], @0); + XCTAssertEqualObjects([message valueForKeyPath:@"optionalImportMessage.d"], @0); // Enums without defaults are set to the first value in the enum. XCTAssertEqualObjects([message valueForKey:@"optionalNestedEnum"], @(TestAllTypes_NestedEnum_Foo)); - XCTAssertEqualObjects([message valueForKey:@"optionalForeignEnum"], - @(ForeignEnum_ForeignFoo)); - XCTAssertEqualObjects([message valueForKey:@"optionalImportEnum"], - @(ImportEnum_ImportFoo)); + XCTAssertEqualObjects([message valueForKey:@"optionalForeignEnum"], @(ForeignEnum_ForeignFoo)); + XCTAssertEqualObjects([message valueForKey:@"optionalImportEnum"], @(ImportEnum_ImportFoo)); XCTAssertEqualObjects([message valueForKey:@"optionalStringPiece"], @""); XCTAssertEqualObjects([message valueForKey:@"optionalCord"], @""); @@ -2532,12 +2505,9 @@ const uint32_t kGPBDefaultRepeatCount = 2; XCTAssertEqualObjects([message valueForKey:@"defaultBytes"], [NSData gpbtu_dataWithCString:"world"]); - XCTAssertEqualObjects([message valueForKey:@"defaultNestedEnum"], - @(TestAllTypes_NestedEnum_Bar)); - XCTAssertEqualObjects([message valueForKey:@"defaultForeignEnum"], - @(ForeignEnum_ForeignBar)); - XCTAssertEqualObjects([message valueForKey:@"defaultImportEnum"], - @(ImportEnum_ImportBar)); + XCTAssertEqualObjects([message valueForKey:@"defaultNestedEnum"], @(TestAllTypes_NestedEnum_Bar)); + XCTAssertEqualObjects([message valueForKey:@"defaultForeignEnum"], @(ForeignEnum_ForeignBar)); + XCTAssertEqualObjects([message valueForKey:@"defaultImportEnum"], @(ImportEnum_ImportBar)); XCTAssertEqualObjects([message valueForKey:@"defaultStringPiece"], @"abc"); XCTAssertEqualObjects([message valueForKey:@"defaultCord"], @"123"); diff --git a/objectivec/Tests/GPBUnknownFieldSetTest.m b/objectivec/Tests/GPBUnknownFieldSetTest.m index 160f0c8d8d..b98f52ef08 100644 --- a/objectivec/Tests/GPBUnknownFieldSetTest.m +++ b/objectivec/Tests/GPBUnknownFieldSetTest.m @@ -30,8 +30,8 @@ #import "GPBTestUtilities.h" -#import "GPBUnknownField_PackagePrivate.h" #import "GPBUnknownFieldSet_PackagePrivate.h" +#import "GPBUnknownField_PackagePrivate.h" #import "objectivec/Tests/Unittest.pbobjc.h" @interface GPBUnknownFieldSet (GPBUnknownFieldSetTest) @@ -61,7 +61,7 @@ } - (void)testInvalidFieldNumber { - GPBUnknownFieldSet *set = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* set = [[[GPBUnknownFieldSet alloc] init] autorelease]; GPBUnknownField* field = [[[GPBUnknownField alloc] initWithNumber:0] autorelease]; XCTAssertThrowsSpecificNamed([set addField:field], NSException, NSInvalidArgumentException); } @@ -69,10 +69,10 @@ - (void)testEqualityAndHash { // Empty - GPBUnknownFieldSet *set1 = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* set1 = [[[GPBUnknownFieldSet alloc] init] autorelease]; XCTAssertTrue([set1 isEqual:set1]); XCTAssertFalse([set1 isEqual:@"foo"]); - GPBUnknownFieldSet *set2 = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* set2 = [[[GPBUnknownFieldSet alloc] init] autorelease]; XCTAssertEqualObjects(set1, set2); XCTAssertEqual([set1 hash], [set2 hash]); @@ -126,11 +126,11 @@ // Group - GPBUnknownFieldSet *group1 = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* group1 = [[[GPBUnknownFieldSet alloc] init] autorelease]; GPBUnknownField* fieldGroup1 = [[[GPBUnknownField alloc] initWithNumber:10] autorelease]; [fieldGroup1 addVarint:1]; [group1 addField:fieldGroup1]; - GPBUnknownFieldSet *group2 = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* group2 = [[[GPBUnknownFieldSet alloc] init] autorelease]; GPBUnknownField* fieldGroup2 = [[[GPBUnknownField alloc] initWithNumber:10] autorelease]; [fieldGroup2 addVarint:1]; [group2 addField:fieldGroup2]; @@ -153,10 +153,9 @@ // numbers as allFieldsData except that each field is some other wire // type. - (NSData*)getBizarroData { - GPBUnknownFieldSet* bizarroFields = - [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* bizarroFields = [[[GPBUnknownFieldSet alloc] init] autorelease]; NSUInteger count = [unknownFields_ countOfFields]; - int32_t *tags = malloc(count * sizeof(int32_t)); + int32_t* tags = malloc(count * sizeof(int32_t)); if (!tags) { XCTFail(@"Failed to make scratch buffer for testing"); return [NSData data]; @@ -168,20 +167,17 @@ GPBUnknownField* field = [unknownFields_ getField:tag]; if (field.varintList.count == 0) { // Original field is not a varint, so use a varint. - GPBUnknownField* varintField = - [[[GPBUnknownField alloc] initWithNumber:tag] autorelease]; + GPBUnknownField* varintField = [[[GPBUnknownField alloc] initWithNumber:tag] autorelease]; [varintField addVarint:1]; [bizarroFields addField:varintField]; } else { // Original field *is* a varint, so use something else. - GPBUnknownField* fixed32Field = - [[[GPBUnknownField alloc] initWithNumber:tag] autorelease]; + GPBUnknownField* fixed32Field = [[[GPBUnknownField alloc] initWithNumber:tag] autorelease]; [fixed32Field addFixed32:1]; [bizarroFields addField:fixed32Field]; } } - } - @finally { + } @finally { free(tags); } @@ -220,7 +216,7 @@ [field addLengthDelimited:DataFromCStr("data1")]; [set1 addField:field]; - GPBUnknownFieldSet *group1 = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* group1 = [[[GPBUnknownFieldSet alloc] init] autorelease]; GPBUnknownField* fieldGroup1 = [[[GPBUnknownField alloc] initWithNumber:200] autorelease]; [fieldGroup1 addVarint:100]; [group1 addField:fieldGroup1]; @@ -246,7 +242,7 @@ [field addLengthDelimited:DataFromCStr("data2")]; [set2 addField:field]; - GPBUnknownFieldSet *group2 = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* group2 = [[[GPBUnknownFieldSet alloc] init] autorelease]; GPBUnknownField* fieldGroup2 = [[[GPBUnknownField alloc] initWithNumber:201] autorelease]; [fieldGroup2 addVarint:99]; [group2 addField:fieldGroup2]; @@ -280,11 +276,11 @@ [field addLengthDelimited:DataFromCStr("data2")]; [set3 addField:field]; - GPBUnknownFieldSet *group3a = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* group3a = [[[GPBUnknownFieldSet alloc] init] autorelease]; GPBUnknownField* fieldGroup3a1 = [[[GPBUnknownField alloc] initWithNumber:200] autorelease]; [fieldGroup3a1 addVarint:100]; [group3a addField:fieldGroup3a1]; - GPBUnknownFieldSet *group3b = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* group3b = [[[GPBUnknownFieldSet alloc] init] autorelease]; GPBUnknownField* fieldGroup3b2 = [[[GPBUnknownField alloc] initWithNumber:201] autorelease]; [fieldGroup3b2 addVarint:99]; [group3b addField:fieldGroup3b2]; @@ -314,7 +310,7 @@ } - (void)testClearMessage { - TestEmptyMessage *message = [TestEmptyMessage message]; + TestEmptyMessage* message = [TestEmptyMessage message]; [message mergeFrom:emptyMessage_]; [message clear]; XCTAssertEqual(message.serializedSize, (size_t)0); @@ -322,9 +318,8 @@ - (void)testParseKnownAndUnknown { // Test mixing known and unknown fields when parsing. - GPBUnknownFieldSet *fields = [[unknownFields_ copy] autorelease]; - GPBUnknownField *field = - [[[GPBUnknownField alloc] initWithNumber:123456] autorelease]; + GPBUnknownFieldSet* fields = [[unknownFields_ copy] autorelease]; + GPBUnknownField* field = [[[GPBUnknownField alloc] initWithNumber:123456] autorelease]; [field addVarint:654321]; [fields addField:field]; @@ -344,10 +339,8 @@ // when parsing. NSData* bizarroData = [self getBizarroData]; - TestAllTypes* allTypesMessage = - [TestAllTypes parseFromData:bizarroData error:NULL]; - TestEmptyMessage* emptyMessage = - [TestEmptyMessage parseFromData:bizarroData error:NULL]; + TestAllTypes* allTypesMessage = [TestAllTypes parseFromData:bizarroData error:NULL]; + TestEmptyMessage* emptyMessage = [TestEmptyMessage parseFromData:bizarroData error:NULL]; // All fields should have been interpreted as unknown, so the debug strings // should be the same. @@ -361,8 +354,7 @@ TestEmptyMessageWithExtensions* message = [TestEmptyMessageWithExtensions parseFromData:allFieldsData_ error:NULL]; - XCTAssertEqual(unknownFields_.countOfFields, - message.unknownFields.countOfFields); + XCTAssertEqual(unknownFields_.countOfFields, message.unknownFields.countOfFields); XCTAssertEqualObjects(allFieldsData_, message.data); } @@ -371,10 +363,9 @@ // when parsing extensions. NSData* bizarroData = [self getBizarroData]; - TestAllExtensions* allExtensionsMessage = - [TestAllExtensions parseFromData:bizarroData error:NULL]; - TestEmptyMessage* emptyMessage = - [TestEmptyMessage parseFromData:bizarroData error:NULL]; + TestAllExtensions* allExtensionsMessage = [TestAllExtensions parseFromData:bizarroData + error:NULL]; + TestEmptyMessage* emptyMessage = [TestEmptyMessage parseFromData:bizarroData error:NULL]; // All fields should have been interpreted as unknown, so the debug strings // should be the same. @@ -465,7 +456,7 @@ // Group - GPBUnknownFieldSet *group = [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* group = [[[GPBUnknownFieldSet alloc] init] autorelease]; GPBUnknownField* fieldGroup = [[[GPBUnknownField alloc] initWithNumber:100] autorelease]; [fieldGroup addVarint:100]; [group addField:fieldGroup]; diff --git a/objectivec/Tests/GPBUtilitiesTests.m b/objectivec/Tests/GPBUtilitiesTests.m index 6a639e16bc..b4d52ad6f4 100644 --- a/objectivec/Tests/GPBUtilitiesTests.m +++ b/objectivec/Tests/GPBUtilitiesTests.m @@ -62,7 +62,7 @@ - (void)testGPBDecodeTextFormatName { uint8_t decodeData[] = { - // clang-format off + // clang-format off 0x6, // An inlined string (first to make sure the leading null is handled // correctly, and with a key of zero to check that). @@ -81,7 +81,7 @@ // underscore, lower + 30 (01 op), as is + 30 (00 op), as is + 13 (00 op), // underscore, as is + 3 (00 op) 0xE8, 0x07, 0x04, 0xA5, 0xA4, 0xA2, 0xBF, 0x1F, 0x0E, 0x84, 0x0, - // clang-format on + // clang-format on }; NSString *inputStr = @"abcdefghIJ"; @@ -125,10 +125,8 @@ NSString *fileName = @"text_format_unittest_data.txt"; NSData *resultData = [result dataUsingEncoding:NSUTF8StringEncoding]; - NSData *expectedData = - [self getDataFileNamed:fileName dataToWrite:resultData]; - NSString *expected = [[NSString alloc] initWithData:expectedData - encoding:NSUTF8StringEncoding]; + NSData *expectedData = [self getDataFileNamed:fileName dataToWrite:resultData]; + NSString *expected = [[NSString alloc] initWithData:expectedData encoding:NSUTF8StringEncoding]; XCTAssertEqualObjects(expected, result); [expected release]; } @@ -167,10 +165,8 @@ NSString *fileName = @"text_format_map_unittest_data.txt"; NSData *resultData = [result dataUsingEncoding:NSUTF8StringEncoding]; - NSData *expectedData = - [self getDataFileNamed:fileName dataToWrite:resultData]; - NSString *expected = [[NSString alloc] initWithData:expectedData - encoding:NSUTF8StringEncoding]; + NSData *expectedData = [self getDataFileNamed:fileName dataToWrite:resultData]; + NSString *expected = [[NSString alloc] initWithData:expectedData encoding:NSUTF8StringEncoding]; XCTAssertEqualObjects(expected, result); [expected release]; } @@ -189,10 +185,8 @@ // of the bracketed extension name. NSString *fileName = @"text_format_extensions_unittest_data.txt"; NSData *resultData = [result dataUsingEncoding:NSUTF8StringEncoding]; - NSData *expectedData = - [self getDataFileNamed:fileName dataToWrite:resultData]; - NSString *expected = [[NSString alloc] initWithData:expectedData - encoding:NSUTF8StringEncoding]; + NSData *expectedData = [self getDataFileNamed:fileName dataToWrite:resultData]; + NSString *expected = [[NSString alloc] initWithData:expectedData encoding:NSUTF8StringEncoding]; XCTAssertEqualObjects(expected, result); [expected release]; } @@ -201,7 +195,7 @@ TestAllTypes *message = [TestAllTypes message]; NSDictionary *repeatedFieldValues = @{ - @"repeatedStringArray" : [@[@"foo", @"bar"] mutableCopy], + @"repeatedStringArray" : [@[ @"foo", @"bar" ] mutableCopy], @"repeatedBoolArray" : [GPBBoolArray arrayWithValue:YES], @"repeatedInt32Array" : [GPBInt32Array arrayWithValue:14], @"repeatedInt64Array" : [GPBInt64Array arrayWithValue:15], @@ -214,23 +208,19 @@ rawValue:TestAllTypes_NestedEnum_Foo], }; for (NSString *fieldName in repeatedFieldValues) { - GPBFieldDescriptor *field = - [message.descriptor fieldWithName:fieldName]; + GPBFieldDescriptor *field = [message.descriptor fieldWithName:fieldName]; XCTAssertNotNil(field, @"No field with name: %@", fieldName); id expectedValues = repeatedFieldValues[fieldName]; GPBSetMessageRepeatedField(message, field, expectedValues); - XCTAssertEqualObjects(expectedValues, - [message valueForKeyPath:fieldName]); + XCTAssertEqualObjects(expectedValues, [message valueForKeyPath:fieldName]); } } // Helper to make an unknown field set with something in it. static GPBUnknownFieldSet *UnknownFieldsSetHelper(int num) { - GPBUnknownFieldSet *result = - [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet *result = [[[GPBUnknownFieldSet alloc] init] autorelease]; - GPBUnknownField *field = - [[[GPBUnknownField alloc] initWithNumber:num] autorelease]; + GPBUnknownField *field = [[[GPBUnknownField alloc] initWithNumber:num] autorelease]; [field addVarint:num]; [result addField:field]; @@ -252,32 +242,26 @@ static GPBUnknownFieldSet *UnknownFieldsSetHelper(int num) { OptionalGroup_extension *optionalGroup = [OptionalGroup_extension message]; optionalGroup.a = 123; optionalGroup.unknownFields = UnknownFieldsSetHelper(779); - [message setExtension:[UnittestRoot optionalGroupExtension] - value:optionalGroup]; + [message setExtension:[UnittestRoot optionalGroupExtension] value:optionalGroup]; // Message - TestAllTypes_NestedMessage *nestedMessage = - [TestAllTypes_NestedMessage message]; + TestAllTypes_NestedMessage *nestedMessage = [TestAllTypes_NestedMessage message]; nestedMessage.bb = 456; nestedMessage.unknownFields = UnknownFieldsSetHelper(778); - [message setExtension:[UnittestRoot optionalNestedMessageExtension] - value:nestedMessage]; + [message setExtension:[UnittestRoot optionalNestedMessageExtension] value:nestedMessage]; // Repeated Group - RepeatedGroup_extension *repeatedGroup = - [[RepeatedGroup_extension alloc] init]; + RepeatedGroup_extension *repeatedGroup = [[RepeatedGroup_extension alloc] init]; repeatedGroup.a = 567; repeatedGroup.unknownFields = UnknownFieldsSetHelper(780); - [message addExtension:[UnittestRoot repeatedGroupExtension] - value:repeatedGroup]; + [message addExtension:[UnittestRoot repeatedGroupExtension] value:repeatedGroup]; [repeatedGroup release]; // Repeated Message nestedMessage = [[TestAllTypes_NestedMessage alloc] init]; nestedMessage.bb = 678; nestedMessage.unknownFields = UnknownFieldsSetHelper(781); - [message addExtension:[UnittestRoot repeatedNestedMessageExtension] - value:nestedMessage]; + [message addExtension:[UnittestRoot repeatedNestedMessageExtension] value:nestedMessage]; [nestedMessage release]; } @@ -317,7 +301,8 @@ static GPBUnknownFieldSet *UnknownFieldsSetHelper(int num) { { XCTAssertTrue([message hasExtension:[UnittestRoot repeatedNestedMessageExtension]]); - NSArray *repeatedNestedMessages = [message getExtension:[UnittestRoot repeatedNestedMessageExtension]]; + NSArray *repeatedNestedMessages = + [message getExtension:[UnittestRoot repeatedNestedMessageExtension]]; XCTAssertEqual(repeatedNestedMessages.count, (NSUInteger)1); TestAllTypes_NestedMessage *repeatedNestedMessage = repeatedNestedMessages.firstObject; XCTAssertNotNil(repeatedNestedMessage); @@ -364,14 +349,14 @@ static GPBUnknownFieldSet *UnknownFieldsSetHelper(int num) { { XCTAssertTrue([message hasExtension:[UnittestRoot repeatedNestedMessageExtension]]); - NSArray *repeatedNestedMessages = [message getExtension:[UnittestRoot repeatedNestedMessageExtension]]; + NSArray *repeatedNestedMessages = + [message getExtension:[UnittestRoot repeatedNestedMessageExtension]]; XCTAssertEqual(repeatedNestedMessages.count, (NSUInteger)1); TestAllTypes_NestedMessage *repeatedNestedMessage = repeatedNestedMessages.firstObject; XCTAssertNotNil(repeatedNestedMessage); XCTAssertEqual(repeatedNestedMessage.bb, 678); XCTAssertNil(repeatedNestedMessage.unknownFields); } - } - (void)testDropMessageUnknownFieldsRecursively_Maps { @@ -420,7 +405,6 @@ static GPBUnknownFieldSet *UnknownFieldsSetHelper(int num) { XCTAssertNotNil(foreignMessage); XCTAssertNil(foreignMessage.unknownFields); } - } @end diff --git a/objectivec/Tests/GPBWellKnownTypesTest.m b/objectivec/Tests/GPBWellKnownTypesTest.m index b7f28a6d04..e6ee20a531 100644 --- a/objectivec/Tests/GPBWellKnownTypesTest.m +++ b/objectivec/Tests/GPBWellKnownTypesTest.m @@ -46,8 +46,7 @@ static const NSTimeInterval kTimeAccuracy = 1e-9; - (void)testTimeStamp { // Test negative and positive values. NSTimeInterval values[] = { - -428027599.483999967, -1234567.0, -0.5, 0, 0.75, 54321.0, 2468086,483999967 - }; + -428027599.483999967, -1234567.0, -0.5, 0, 0.75, 54321.0, 2468086, 483999967}; for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) { NSTimeInterval value = values[i]; @@ -55,30 +54,24 @@ static const NSTimeInterval kTimeAccuracy = 1e-9; NSDate *date = [NSDate dateWithTimeIntervalSince1970:value]; GPBTimestamp *timeStamp = [[GPBTimestamp alloc] initWithDate:date]; - XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0, - @"Offset %f - Date: %@", (double)value, date); - XCTAssertLessThan(timeStamp.nanos, 1e9, - @"Offset %f - Date: %@", (double)value, date); + XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0, @"Offset %f - Date: %@", (double)value, date); + XCTAssertLessThan(timeStamp.nanos, 1e9, @"Offset %f - Date: %@", (double)value, date); // Comparing timeIntervals instead of directly comparing dates because date // equality requires the time intervals to be exactly the same, and the // timeintervals go through a bit of floating point error as they are // converted back and forth from the internal representation. - XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970, - kTimeAccuracy, + XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970, kTimeAccuracy, @"Offset %f - Date: %@", (double)value, date); [timeStamp release]; // Test Creation - timeIntervalSince1970. timeStamp = [[GPBTimestamp alloc] initWithTimeIntervalSince1970:value]; - XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0, - @"Offset %f - Date: %@", (double)value, date); - XCTAssertLessThan(timeStamp.nanos, 1e9, - @"Offset %f - Date: %@", (double)value, date); + XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0, @"Offset %f - Date: %@", (double)value, date); + XCTAssertLessThan(timeStamp.nanos, 1e9, @"Offset %f - Date: %@", (double)value, date); - XCTAssertEqualWithAccuracy(value, timeStamp.timeIntervalSince1970, - kTimeAccuracy, + XCTAssertEqualWithAccuracy(value, timeStamp.timeIntervalSince1970, kTimeAccuracy, @"Offset %f - Date: %@", (double)value, date); [timeStamp release]; @@ -86,13 +79,10 @@ static const NSTimeInterval kTimeAccuracy = 1e-9; timeStamp = [[GPBTimestamp alloc] init]; timeStamp.date = date; - XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0, - @"Offset %f - Date: %@", (double)value, date); - XCTAssertLessThan(timeStamp.nanos, 1e9, - @"Offset %f - Date: %@", (double)value, date); + XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0, @"Offset %f - Date: %@", (double)value, date); + XCTAssertLessThan(timeStamp.nanos, 1e9, @"Offset %f - Date: %@", (double)value, date); - XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970, - kTimeAccuracy, + XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970, kTimeAccuracy, @"Offset %f - Date: %@", (double)value, date); [timeStamp release]; @@ -100,13 +90,10 @@ static const NSTimeInterval kTimeAccuracy = 1e-9; timeStamp = [[GPBTimestamp alloc] init]; timeStamp.timeIntervalSince1970 = value; - XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0, - @"Offset %f - Date: %@", (double)value, date); - XCTAssertLessThan(timeStamp.nanos, 1e9, - @"Offset %f - Date: %@", (double)value, date); + XCTAssertGreaterThanOrEqual(timeStamp.nanos, 0, @"Offset %f - Date: %@", (double)value, date); + XCTAssertLessThan(timeStamp.nanos, 1e9, @"Offset %f - Date: %@", (double)value, date); - XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970, - kTimeAccuracy, + XCTAssertEqualWithAccuracy(value, timeStamp.date.timeIntervalSince1970, kTimeAccuracy, @"Offset %f - Date: %@", (double)value, date); [timeStamp release]; @@ -115,50 +102,40 @@ static const NSTimeInterval kTimeAccuracy = 1e-9; - (void)testDuration { // Test negative and positive values. - NSTimeInterval values[] = { -1000.0001, -500.0, -0.5, 0, 0.75, 1000.0, 2000.0002 }; + NSTimeInterval values[] = {-1000.0001, -500.0, -0.5, 0, 0.75, 1000.0, 2000.0002}; for (size_t i = 0; i < GPBARRAYSIZE(values); ++i) { NSTimeInterval value = values[i]; // Test Creation. - GPBDuration *duration = - [[GPBDuration alloc] initWithTimeInterval:value]; - XCTAssertEqualWithAccuracy(value, duration.timeInterval, kTimeAccuracy, - @"For interval %f", (double)value); + GPBDuration *duration = [[GPBDuration alloc] initWithTimeInterval:value]; + XCTAssertEqualWithAccuracy(value, duration.timeInterval, kTimeAccuracy, @"For interval %f", + (double)value); if (value > 0) { - XCTAssertGreaterThanOrEqual(duration.seconds, 0, - @"For interval %f", (double)value); - XCTAssertGreaterThanOrEqual(duration.nanos, 0, - @"For interval %f", (double)value); + XCTAssertGreaterThanOrEqual(duration.seconds, 0, @"For interval %f", (double)value); + XCTAssertGreaterThanOrEqual(duration.nanos, 0, @"For interval %f", (double)value); } else { - XCTAssertLessThanOrEqual(duration.seconds, 0, - @"For interval %f", (double)value); - XCTAssertLessThanOrEqual(duration.nanos, 0, - @"For interval %f", (double)value); + XCTAssertLessThanOrEqual(duration.seconds, 0, @"For interval %f", (double)value); + XCTAssertLessThanOrEqual(duration.nanos, 0, @"For interval %f", (double)value); } [duration release]; // Test Mutation. duration = [[GPBDuration alloc] init]; duration.timeInterval = value; - XCTAssertEqualWithAccuracy(value, duration.timeInterval, kTimeAccuracy, - @"For interval %f", (double)value); + XCTAssertEqualWithAccuracy(value, duration.timeInterval, kTimeAccuracy, @"For interval %f", + (double)value); if (value > 0) { - XCTAssertGreaterThanOrEqual(duration.seconds, 0, - @"For interval %f", (double)value); - XCTAssertGreaterThanOrEqual(duration.nanos, 0, - @"For interval %f", (double)value); + XCTAssertGreaterThanOrEqual(duration.seconds, 0, @"For interval %f", (double)value); + XCTAssertGreaterThanOrEqual(duration.nanos, 0, @"For interval %f", (double)value); } else { - XCTAssertLessThanOrEqual(duration.seconds, 0, - @"For interval %f", (double)value); - XCTAssertLessThanOrEqual(duration.nanos, 0, - @"For interval %f", (double)value); + XCTAssertLessThanOrEqual(duration.seconds, 0, @"For interval %f", (double)value); + XCTAssertLessThanOrEqual(duration.nanos, 0, @"For interval %f", (double)value); } [duration release]; } } - (void)testAnyHelpers { - // Set and extract covers most of the code. AnyTestMessage *subMessage = [AnyTestMessage message]; @@ -177,8 +154,7 @@ static const NSTimeInterval kTimeAccuracy = 1e-9; XCTAssertTrue(message2.hasAnyValue); AnyTestMessage *subMessage2 = - (AnyTestMessage *)[message.anyValue unpackMessageClass:[AnyTestMessage class] - error:&err]; + (AnyTestMessage *)[message.anyValue unpackMessageClass:[AnyTestMessage class] error:&err]; XCTAssertNil(err); XCTAssertNotNil(subMessage2); XCTAssertEqual(subMessage2.int32Value, 12345); @@ -190,24 +166,21 @@ static const NSTimeInterval kTimeAccuracy = 1e-9; XCTAssertEqualObjects(data2, data); AnyTestMessage *subMessage3 = - (AnyTestMessage *)[message.anyValue unpackMessageClass:[AnyTestMessage class] - error:NULL]; + (AnyTestMessage *)[message.anyValue unpackMessageClass:[AnyTestMessage class] error:NULL]; XCTAssertNotNil(subMessage3); XCTAssertEqualObjects(subMessage2, subMessage3); // Try to extract wrong type. GPBTimestamp *wrongMessage = - (GPBTimestamp *)[message.anyValue unpackMessageClass:[GPBTimestamp class] - error:&err]; + (GPBTimestamp *)[message.anyValue unpackMessageClass:[GPBTimestamp class] error:&err]; XCTAssertNotNil(err); XCTAssertNil(wrongMessage); XCTAssertEqualObjects(err.domain, GPBWellKnownTypesErrorDomain); XCTAssertEqual(err.code, GPBWellKnownTypesErrorCodeTypeURLMismatch); - wrongMessage = - (GPBTimestamp *)[message.anyValue unpackMessageClass:[GPBTimestamp class] - error:NULL]; + wrongMessage = (GPBTimestamp *)[message.anyValue unpackMessageClass:[GPBTimestamp class] + error:NULL]; XCTAssertNil(wrongMessage); } diff --git a/objectivec/Tests/GPBWireFormatTests.m b/objectivec/Tests/GPBWireFormatTests.m index e100667d24..64456bc57e 100644 --- a/objectivec/Tests/GPBWireFormatTests.m +++ b/objectivec/Tests/GPBWireFormatTests.m @@ -54,15 +54,13 @@ } - (void)testSerializationPacked { - TestPackedTypes* message = - [self packedSetRepeatedCount:kGPBDefaultRepeatCount]; + TestPackedTypes* message = [self packedSetRepeatedCount:kGPBDefaultRepeatCount]; NSData* rawBytes = message.data; [self assertFieldsInOrder:rawBytes]; XCTAssertEqual(message.serializedSize, (size_t)rawBytes.length); - TestPackedTypes* message2 = - [TestPackedTypes parseFromData:rawBytes error:NULL]; + TestPackedTypes* message2 = [TestPackedTypes parseFromData:rawBytes error:NULL]; [self assertPackedFieldsSet:message2 repeatedCount:kGPBDefaultRepeatCount]; } @@ -72,8 +70,7 @@ // so if we serealize a TestAllExtensions then parse it as TestAllTypes // it should work. - TestAllExtensions* message = - [self allExtensionsSetRepeatedCount:kGPBDefaultRepeatCount]; + TestAllExtensions* message = [self allExtensionsSetRepeatedCount:kGPBDefaultRepeatCount]; NSData* rawBytes = message.data; [self assertFieldsInOrder:rawBytes]; XCTAssertEqual(message.serializedSize, (size_t)rawBytes.length); @@ -86,13 +83,11 @@ - (void)testSerializePackedExtensions { // TestPackedTypes and TestPackedExtensions should have compatible wire // formats; check that they serialize to the same string. - TestPackedExtensions* message = - [self packedExtensionsSetRepeatedCount:kGPBDefaultRepeatCount]; + TestPackedExtensions* message = [self packedExtensionsSetRepeatedCount:kGPBDefaultRepeatCount]; NSData* rawBytes = message.data; [self assertFieldsInOrder:rawBytes]; - TestPackedTypes* message2 = - [self packedSetRepeatedCount:kGPBDefaultRepeatCount]; + TestPackedTypes* message2 = [self packedSetRepeatedCount:kGPBDefaultRepeatCount]; NSData* rawBytes2 = message2.data; XCTAssertEqualObjects(rawBytes, rawBytes2); @@ -116,7 +111,6 @@ [self assertAllExtensionsSet:message2 repeatedCount:kGPBDefaultRepeatCount]; } - - (void)testExtensionsSerializedSize { size_t allSet = [self allSetRepeatedCount:kGPBDefaultRepeatCount].serializedSize; size_t extensionSet = [self allExtensionsSetRepeatedCount:kGPBDefaultRepeatCount].serializedSize; @@ -125,8 +119,7 @@ - (void)testParsePackedExtensions { // Ensure that packed extensions can be properly parsed. - TestPackedExtensions* message = - [self packedExtensionsSetRepeatedCount:kGPBDefaultRepeatCount]; + TestPackedExtensions* message = [self packedExtensionsSetRepeatedCount:kGPBDefaultRepeatCount]; NSData* rawBytes = message.data; [self assertFieldsInOrder:rawBytes]; @@ -136,8 +129,7 @@ extensionRegistry:registry error:NULL]; - [self assertPackedExtensionsSet:message2 - repeatedCount:kGPBDefaultRepeatCount]; + [self assertPackedExtensionsSet:message2 repeatedCount:kGPBDefaultRepeatCount]; } const int kUnknownTypeId = 1550055; @@ -145,15 +137,12 @@ const int kUnknownTypeId = 1550055; - (void)testSerializeMessageSet { // Set up a MSetMessage with two known messages and an unknown one. MSetMessage* message_set = [MSetMessage message]; - [[message_set getExtension:[MSetMessageExtension1 messageSetExtension]] - setI:123]; - [[message_set getExtension:[MSetMessageExtension2 messageSetExtension]] - setStr:@"foo"]; + [[message_set getExtension:[MSetMessageExtension1 messageSetExtension]] setI:123]; + [[message_set getExtension:[MSetMessageExtension2 messageSetExtension]] setStr:@"foo"]; GPBUnknownField* unknownField = [[[GPBUnknownField alloc] initWithNumber:kUnknownTypeId] autorelease]; [unknownField addLengthDelimited:[NSData dataWithBytes:"bar" length:3]]; - GPBUnknownFieldSet* unknownFieldSet = - [[[GPBUnknownFieldSet alloc] init] autorelease]; + GPBUnknownFieldSet* unknownFieldSet = [[[GPBUnknownFieldSet alloc] init] autorelease]; [unknownFieldSet addField:unknownField]; [message_set setUnknownFields:unknownFieldSet]; @@ -181,8 +170,7 @@ const int kUnknownTypeId = 1550055; error:NULL]; XCTAssertEqualObjects(message2.str, @"foo"); - XCTAssertEqualObjects([raw.itemArray[2] message], - [NSData dataWithBytes:"bar" length:3]); + XCTAssertEqualObjects([raw.itemArray[2] message], [NSData dataWithBytes:"bar" length:3]); } - (void)testParseMessageSet { @@ -217,26 +205,19 @@ const int kUnknownTypeId = 1550055; NSData* data = [raw data]; // Parse as a MSetMessage and check the contents. - MSetMessage* messageSet = - [MSetMessage parseFromData:data - extensionRegistry:[MSetUnittestMsetRoot extensionRegistry] - error:NULL]; - - XCTAssertEqual( - [[messageSet - getExtension:[MSetMessageExtension1 messageSetExtension]] i], - 123); - XCTAssertEqualObjects( - [[messageSet - getExtension:[MSetMessageExtension2 messageSetExtension]] str], - @"foo"); + MSetMessage* messageSet = [MSetMessage parseFromData:data + extensionRegistry:[MSetUnittestMsetRoot extensionRegistry] + error:NULL]; + + XCTAssertEqual([[messageSet getExtension:[MSetMessageExtension1 messageSetExtension]] i], 123); + XCTAssertEqualObjects([[messageSet getExtension:[MSetMessageExtension2 messageSetExtension]] str], + @"foo"); XCTAssertEqual([messageSet.unknownFields countOfFields], (NSUInteger)1); GPBUnknownField* unknownField = [messageSet.unknownFields getField:kUnknownTypeId]; XCTAssertNotNil(unknownField); XCTAssertEqual(unknownField.lengthDelimitedList.count, (NSUInteger)1); - XCTAssertEqualObjects(unknownField.lengthDelimitedList[0], - [NSData dataWithBytes:"bar" length:3]); + XCTAssertEqualObjects(unknownField.lengthDelimitedList[0], [NSData dataWithBytes:"bar" length:3]); } - (void)assertFieldsInOrder:(NSData*)data { diff --git a/objectivec/Tests/UnitTests-Bridging-Header.h b/objectivec/Tests/UnitTests-Bridging-Header.h index 16d272be7f..6d3d9ec5f3 100644 --- a/objectivec/Tests/UnitTests-Bridging-Header.h +++ b/objectivec/Tests/UnitTests-Bridging-Header.h @@ -1,5 +1,6 @@ // -// Use this file to import your target's public headers that you would like to expose to Swift. +// Use this file to import your target's public headers that you would like to +// expose to Swift. // #import "objectivec/Tests/UnittestRuntimeProto2.pbobjc.h" From bc4cbf9a05c58390ff4797cfa804f8daad378d70 Mon Sep 17 00:00:00 2001 From: Thomas Van Lenten Date: Tue, 20 Sep 2022 08:35:56 -0400 Subject: [PATCH 63/64] Remove the pre Xcode 10.2 support. objectivec/README.md lists Xcode 10.2 as the minimum, update things accordingly. - Remove code paths referencing the older versions. - Remove support from the testing script. --- objectivec/DevTools/full_mac_build.sh | 31 +++++------------------ objectivec/GPBDescriptor_PackagePrivate.h | 8 ------ objectivec/GPBDictionary.m | 24 ------------------ objectivec/GPBMessage.m | 6 ++--- objectivec/Tests/unittest_objc.proto | 3 +-- 5 files changed, 10 insertions(+), 62 deletions(-) diff --git a/objectivec/DevTools/full_mac_build.sh b/objectivec/DevTools/full_mac_build.sh index 77a21666f9..55b163fe1a 100755 --- a/objectivec/DevTools/full_mac_build.sh +++ b/objectivec/DevTools/full_mac_build.sh @@ -224,28 +224,10 @@ if [[ "${DO_XCODE_IOS_TESTS}" == "yes" ]] ; then # just pick a mix of OS Versions and 32/64 bit. # NOTE: Different Xcode have different simulated hardware/os support. case "${XCODE_VERSION}" in - [6-8].* ) - echo "ERROR: The unittests include Swift code that is now Swift 4.0." 1>&2 - echo "ERROR: Xcode 9.0 or higher is required to build the test suite, but the library works with Xcode 7.x." 1>&2 + [6-9].* ) + echo "ERROR: Xcode 10.2 or higher is required." 1>&2 exit 11 ;; - 9.[0-2]* ) - XCODEBUILD_TEST_BASE_IOS+=( - -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit - -destination "platform=iOS Simulator,name=iPhone 7,OS=latest" # 64bit - # 9.0-9.2 all seem to often fail running destinations in parallel - -disable-concurrent-testing - ) - ;; - 9.[3-4]* ) - XCODEBUILD_TEST_BASE_IOS+=( - # Xcode 9.3 chokes targeting iOS 8.x - http://www.openradar.me/39335367 - -destination "platform=iOS Simulator,name=iPhone 4s,OS=9.0" # 32bit - -destination "platform=iOS Simulator,name=iPhone 7,OS=latest" # 64bit - # 9.3 also seems to often fail running destinations in parallel - -disable-concurrent-testing - ) - ;; 10.*) XCODEBUILD_TEST_BASE_IOS+=( -destination "platform=iOS Simulator,name=iPhone 4s,OS=8.1" # 32bit @@ -292,9 +274,8 @@ if [[ "${DO_XCODE_OSX_TESTS}" == "yes" ]] ; then XCODEBUILD_TEST_BASE_OSX+=( -quiet ) fi case "${XCODE_VERSION}" in - [6-8].* ) - echo "ERROR: The unittests include Swift code that is now Swift 4.0." 1>&2 - echo "ERROR: Xcode 9.0 or higher is required to build the test suite, but the library works with Xcode 7.x." 1>&2 + [6-9].* ) + echo "ERROR: Xcode 10.2 or higher is required." 1>&2 exit 11 ;; esac @@ -315,7 +296,7 @@ if [[ "${DO_XCODE_TVOS_TESTS}" == "yes" ]] ; then ) case "${XCODE_VERSION}" in [6-9].* ) - echo "ERROR: Xcode 10.0 or higher is required to build the test suite." 1>&2 + echo "ERROR: Xcode 10.2 or higher is required." 1>&2 exit 11 ;; 10.* | 11.* | 12.*) @@ -323,7 +304,7 @@ if [[ "${DO_XCODE_TVOS_TESTS}" == "yes" ]] ; then -destination "platform=tvOS Simulator,name=Apple TV 4K,OS=latest" ) ;; - 13.*) + 13.* | 14.*) XCODEBUILD_TEST_BASE_TVOS+=( -destination "platform=tvOS Simulator,name=Apple TV 4K (2nd generation),OS=latest" ) diff --git a/objectivec/GPBDescriptor_PackagePrivate.h b/objectivec/GPBDescriptor_PackagePrivate.h index 3e07226f46..4774d4e2cb 100644 --- a/objectivec/GPBDescriptor_PackagePrivate.h +++ b/objectivec/GPBDescriptor_PackagePrivate.h @@ -348,15 +348,7 @@ GPB_INLINE BOOL GPBExtensionIsWireFormat(GPBExtensionDescription *description) { // Helper for compile time assets. #ifndef GPBInternalCompileAssert -#if __has_feature(c_static_assert) || __has_extension(c_static_assert) #define GPBInternalCompileAssert(test, msg) _Static_assert((test), #msg) -#else -// Pre-Xcode 7 support. -#define GPBInternalCompileAssertSymbolInner(line, msg) GPBInternalCompileAssert##line##__##msg -#define GPBInternalCompileAssertSymbol(line, msg) GPBInternalCompileAssertSymbolInner(line, msg) -#define GPBInternalCompileAssert(test, msg) \ - typedef char GPBInternalCompileAssertSymbol(__LINE__, msg)[((test) ? 1 : -1)] -#endif // __has_feature(c_static_assert) || __has_extension(c_static_assert) #endif // GPBInternalCompileAssert // Sanity check that there isn't padding between the field description diff --git a/objectivec/GPBDictionary.m b/objectivec/GPBDictionary.m index d90e9f1031..53ee568cc3 100644 --- a/objectivec/GPBDictionary.m +++ b/objectivec/GPBDictionary.m @@ -51,17 +51,6 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdirect-ivar-access" -// Used to include code only visible to specific versions of the static -// analyzer. Useful for wrapping code that only exists to silence the analyzer. -// Determine the values you want to use for BEGIN_APPLE_BUILD_VERSION, -// END_APPLE_BUILD_VERSION using: -// xcrun clang -dM -E -x c /dev/null | grep __apple_build_version__ -// Example usage: -// #if GPB_STATIC_ANALYZER_ONLY(5621, 5623) ... #endif -#define GPB_STATIC_ANALYZER_ONLY(BEGIN_APPLE_BUILD_VERSION, END_APPLE_BUILD_VERSION) \ - (defined(__clang_analyzer__) && (__apple_build_version__ >= BEGIN_APPLE_BUILD_VERSION && \ - __apple_build_version__ <= END_APPLE_BUILD_VERSION)) - enum { kMapKeyFieldNumber = 1, kMapValueFieldNumber = 2, @@ -520,19 +509,6 @@ void GPBDictionaryReadEntry(id mapDictionary, GPBCodedInputStream *stream, } if ((keyDataType == GPBDataTypeString) && GPBDataTypeIsObject(valueDataType)) { -#if GPB_STATIC_ANALYZER_ONLY(6020053, 7000181) - // Limited to Xcode 6.4 - 7.2, are known to fail here. The upper end can - // be raised as needed for new Xcodes. - // - // This is only needed on a "shallow" analyze; on a "deep" analyze, the - // existing code path gets this correct. In shallow, the analyzer decides - // GPBDataTypeIsObject(valueDataType) is both false and true on a single - // path through this function, allowing nil to be used for the - // setObject:forKey:. - if (value.valueString == nil) { - value.valueString = [@"" retain]; - } -#endif // mapDictionary is an NSMutableDictionary [(NSMutableDictionary *)mapDictionary setObject:value.valueString forKey:key.valueString]; } else { diff --git a/objectivec/GPBMessage.m b/objectivec/GPBMessage.m index efb0088e42..5a2c05956e 100644 --- a/objectivec/GPBMessage.m +++ b/objectivec/GPBMessage.m @@ -761,9 +761,9 @@ void GPBPrepareReadOnlySemaphore(GPBMessage *self) { dispatch_release(worker); } #if defined(__clang_analyzer__) - // The Xcode 9.2 (and 9.3 beta) static analyzer thinks worker is leaked - // (doesn't seem to know about atomic_compare_exchange_strong); so just - // for the analyzer, let it think worker is also released in this case. + // The static analyzer thinks worker is leaked (doesn't seem to know about + // atomic_compare_exchange_strong); so just for the analyzer, let it think + // worker is also released in this case. else { dispatch_release(worker); } diff --git a/objectivec/Tests/unittest_objc.proto b/objectivec/Tests/unittest_objc.proto index aed200bddb..c7e403410d 100644 --- a/objectivec/Tests/unittest_objc.proto +++ b/objectivec/Tests/unittest_objc.proto @@ -239,8 +239,7 @@ extend self { repeated sint32 byref = 3004 [packed = true]; } -// Test handing of fields that start with init* since Xcode 5's ARC support -// doesn't like messages that look like initializers but aren't. +// Test handing of fields that start with init*. message ObjCInitFoo { optional string init_val = 11; optional int32 init_size = 12; From 12bedd20c3f18307540809b4063e9544ea13c765 Mon Sep 17 00:00:00 2001 From: Mike Kruskal Date: Fri, 23 Sep 2022 14:31:09 -0700 Subject: [PATCH 64/64] Updating changelog --- CHANGES.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGES.txt b/CHANGES.txt index 13d7b7332e..fa223a22d1 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -39,6 +39,9 @@ constructed FieldMaskTrees. * Optimized Java proto serialization gencode for protos having many extension ranges with few fields in between. * More thoroughly annotate public generated code in Java lite protocol buffers. + * Fixed Bug in proto3 java lite repeated enum fields. Failed to call copyOnWrite before modifying previously built message. Causes modification to already "built" messages that should be immutable. + * Refactoring java full runtime to reuse sub-message builders and prepare to migrate parsing logic from parse constructor to builder. + * Fix Java reflection serialization of empty packed fields. Python * Changes ordering of printed fields in .pyi files from lexicographic to the same ordering found in the proto descriptor.