diff --git a/src/openssl/build_openssl.ps1 b/src/openssl/build_openssl.ps1 new file mode 100644 index 000000000..e4f95e902 --- /dev/null +++ b/src/openssl/build_openssl.ps1 @@ -0,0 +1,70 @@ +# Prerequsites to build openssl on windows: +# * perl (use Strawberry distribution if in doubt) +# https://strawberryperl.com/ +# https://strawberryperl.com/download/5.32.1.1/strawberry-perl-5.32.1.1-64bit.msi +# * nasm +# https://www.nasm.us/ +# https://www.nasm.us/pub/nasm/releasebuilds/2.15.05/win64/nasm-2.15.05-installer-x64.exe +# +# Setup cmd prompt (from which to run this script): +# * Open the 'x64 Native Tools Command Prompt for VS 2019' cmd prompt +# * Ensure that nasm and perl exes are in the path +# +# For more info, see the openssl github +# https://github.com/openssl/openssl + +$openssl="openssl-1_1_1" +$root = Resolve-Path "../.." +$work = Join-Path $root "work" +$src = Join-Path $root src +$target = Join-Path $root "windows" + +Push-Location +if (Test-Path $work) { + Remove-Item -Force -Recurse $work +} + +# clean +Remove-Item $target\lib\debug\libssl.lib +Remove-Item $target\lib\debug\libcrypto.lib +Remove-Item $target\lib\debug\ossl_static.pdb +Remove-Item $target\lib\release\libssl.lib +Remove-Item $target\lib\release\libcrypto.lib +if (Test-Path $target\include\openssl) { + Remove-Item -Force -Recurse $target\include\openssl +} + +# expand +unzip -q $src\openssl\$openssl -d $work + +$cmake_dir $work\$openssl +Set-Location $cmake_dir + +## For Debug +# configure +$debug_build_dir $work\$openssl\debug_build +$debug_install_dir $work\$protobuf\cmake\install +perl Configure --prefix=$work\$openssl\debug_build --openssldir=data --debug no-shared VC-WIN64A +# build +nmake +nmake install +# copy libs and symbols +Copy-Item $debug_build_dir\libssl.lib $target\lib\debug\ +Copy-Item $debug_build_dir\libcrypto.lib $target\lib\debug\ +Copy-Item $debug_build_dir\ossl_static.pdb $target\lib\debug\ + +## For Release +# configure +$release_build_dir $work\$openssl\release_build +$release_install_dir $work\$protobuf\cmake\install +perl Configure --prefix=$work\$openssl\release_build --openssldir=data --release no-shared VC-WIN64A +# build +nmake +nmake install +# copy libs and headers +Copy-Item $release_build_dir\libssl.lib $target\lib\release\ +Copy-Item $release_build_dir\libcrypto.lib $target\lib\release\ +Copy-Item -Recurse $release_build_dir\include\openssl $target\include\ + +Remove-Item -Force -Recurse $work +Pop-Location diff --git a/src/protobuf/build_protobuf.ps1 b/src/protobuf/build_protobuf.ps1 index f5a4256fa..3a1d429c9 100644 --- a/src/protobuf/build_protobuf.ps1 +++ b/src/protobuf/build_protobuf.ps1 @@ -1,4 +1,5 @@ -$protobuf = "protobuf-3.6.1" +$protobuf_zip_name = "protobuf-all-3.19.1" +$protobuf = "protobuf-3.19.1" $root = Resolve-Path "../.." $work = Join-Path $root "work" $src = Join-Path $root src @@ -7,6 +8,8 @@ Push-Location if (Test-Path $work) { Remove-Item -Force -Recurse $work } + +# clean Remove-Item $target\lib\debug\libproto*.* Remove-Item $target\lib\release\libproto*.* Remove-Item $target\bin\proto*.* @@ -18,40 +21,42 @@ if (Test-Path $target\include\google) { } # expand -unzip -q $src\protobuf\$protobuf -d $work +unzip -q $src\protobuf\$protobuf_zip_name -d $work -# copy headers -Copy-Item $work\$protobuf\src\google $target\include\google -Recurse +# configure +$cmake_dir $work\$protobuf\cmake +$build_dir $work\$protobuf\cmake\build +$install_dir $work\$protobuf\cmake\install +New-Item -ItemType Directory -Path $build_dir +Set-Location $build_dir +cmake -DCMAKE_INSTALL_PREFIX=$install_dir -Dprotoubf_BUILD_TESTS=OFF -G "Visual Studio 16 2019" $cmake_dir -# build release -cd $work\$protobuf -mkdir release -cd release -cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -Dprotobuf_BUILD_TESTS=OFF $work/$protobuf/cmake -cmake --build . -copy protoc.exe $target\bin -copy libprotobuf.lib $target\lib\release -copy libprotoc.lib $target\lib\release +## For Debug +# build +msbuild /m /p:platform=x64 /p:Configuration=Debug /p:debugtype=portable /clp:summary /clp:verbosity=minimal $build_dir\protobuf.sln +# copy libs and symbols +Copy-Item $build_dir\Debug\libprotobufd.lib $target\lib\debug\libprotobuf.lib +Copy-Item $build_dir\Debug\libprotobufd.pdb $target\lib\debug\libprotobuf.pdb +Copy-Item $build_dir\Debug\libprotocd.lib $target\lib\debug\libprotoc.lib +Copy-Item $build_dir\Debug\libprotocd.pdb $target\lib\debug\libprotoc.pdb -# debug -cd $work\$protobuf -mkdir debug -cd debug -cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Debug -Dprotobuf_BUILD_TESTS=OFF $work/$protobuf/cmake -cmake --build . -copy libprotobufd.lib $target\lib\debug\libprotobuf.lib -copy libprotocd.lib $target\lib\debug\libprotoc.lib -copy CMakeFiles\libprotobuf.dir\libprotobuf.pdb $target\lib\debug\libprotobuf.pdb -copy CMakeFiles\libprotoc.dir\libprotoc.pdb $target\lib\debug\libprotoc.pdb +## For Release +# build +msbuild /m /p:platform=x64 /p:Configuration=Release /clp:summary /clp:verbosity=minimal protobuf.sln +msbuild /m /p:platform=x64 /p:Configuration=Release /clp:summary /clp:verbosity=minimal INSTALL.vcxproj +# copy libs, headers, and protoc.exe +Copy-Item $build_dir\Release\libprotobuf.lib $target\lib\release\ +Copy-Item $build_dir\Release\libprotoc.lib $target\lib\release\ +Copy-Item $build_dir\Release\protoc.exe $target\bin\ +Copy-Item -Recurse $install_dir\include\google $target\include\ # python -cd $work\$protobuf -copy release\protoc.exe src/ -cd python -python setup.py build -mkdir $target\python -Copy-Item google $target\python\google -Recurse +Set-Location $work\$protobuf +Copy-Item $build_dir\Release\protoc.exe src/ +Set-Location python +python setup.py build_py +New-Item -ItemType Directory -Path $target\python +Copy-Item -Recurse google $target\python\google Remove-Item -Force -Recurse $work Pop-Location - diff --git a/src/protobuf/protobuf-all-3.19.1.zip b/src/protobuf/protobuf-all-3.19.1.zip new file mode 100644 index 000000000..74ca044e8 Binary files /dev/null and b/src/protobuf/protobuf-all-3.19.1.zip differ diff --git a/windows/bin/protoc.exe b/windows/bin/protoc.exe index e2065efb1..d87034025 100755 Binary files a/windows/bin/protoc.exe and b/windows/bin/protoc.exe differ diff --git a/windows/include/google/protobuf/any.cc b/windows/include/google/protobuf/any.cc deleted file mode 100644 index b94529e68..000000000 --- a/windows/include/google/protobuf/any.cc +++ /dev/null @@ -1,123 +0,0 @@ -// 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. - -#include - -#include - - -namespace google { -namespace protobuf { -namespace internal { - -namespace { -string GetTypeUrl(const Descriptor* message, - const string& type_url_prefix) { - if (!type_url_prefix.empty() && - type_url_prefix[type_url_prefix.size() - 1] == '/') { - return type_url_prefix + message->full_name(); - } else { - return type_url_prefix + "/" + message->full_name(); - } -} -} // namespace - -const char kAnyFullTypeName[] = "google.protobuf.Any"; -const char kTypeGoogleApisComPrefix[] = "type.googleapis.com/"; -const char kTypeGoogleProdComPrefix[] = "type.googleprod.com/"; - -AnyMetadata::AnyMetadata(UrlType* type_url, ValueType* value) - : type_url_(type_url), value_(value) { -} - -void AnyMetadata::PackFrom(const Message& message) { - PackFrom(message, kTypeGoogleApisComPrefix); -} - -void AnyMetadata::PackFrom(const Message& message, - const string& type_url_prefix) { - type_url_->SetNoArena(&::google::protobuf::internal::GetEmptyString(), - GetTypeUrl(message.GetDescriptor(), type_url_prefix)); - message.SerializeToString(value_->MutableNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited())); -} - -bool AnyMetadata::UnpackTo(Message* message) const { - if (!InternalIs(message->GetDescriptor())) { - return false; - } - return message->ParseFromString(value_->GetNoArena()); -} - -bool AnyMetadata::InternalIs(const Descriptor* descriptor) const { - const string type_url = type_url_->GetNoArena(); - string full_name; - if (!ParseAnyTypeUrl(type_url, &full_name)) { - return false; - } - return full_name == descriptor->full_name(); -} - -bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, - string* full_type_name) { - size_t pos = type_url.find_last_of("/"); - if (pos == string::npos || pos + 1 == type_url.size()) { - return false; - } - if (url_prefix) { - *url_prefix = type_url.substr(0, pos + 1); - } - *full_type_name = type_url.substr(pos + 1); - return true; -} - -bool ParseAnyTypeUrl(const string& type_url, string* full_type_name) { - return ParseAnyTypeUrl(type_url, NULL, full_type_name); -} - - -bool GetAnyFieldDescriptors(const Message& message, - const FieldDescriptor** type_url_field, - const FieldDescriptor** value_field) { - const Descriptor* descriptor = message.GetDescriptor(); - if (descriptor->full_name() != kAnyFullTypeName) { - return false; - } - *type_url_field = descriptor->FindFieldByNumber(1); - *value_field = descriptor->FindFieldByNumber(2); - return (*type_url_field != NULL && - (*type_url_field)->type() == FieldDescriptor::TYPE_STRING && - *value_field != NULL && - (*value_field)->type() == FieldDescriptor::TYPE_BYTES); -} - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/any.h b/windows/include/google/protobuf/any.h index a34e5f8ec..e8336fa14 100644 --- a/windows/include/google/protobuf/any.h +++ b/windows/include/google/protobuf/any.h @@ -34,49 +34,89 @@ #include #include -#include -#include #include +#include + +#include namespace google { namespace protobuf { + +class FieldDescriptor; +class Message; + namespace internal { +extern const char kAnyFullTypeName[]; // "google.protobuf.Any". +extern const char kTypeGoogleApisComPrefix[]; // "type.googleapis.com/". +extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". + +std::string GetTypeUrl(StringPiece message_name, + StringPiece type_url_prefix); + // Helper class used to implement google::protobuf::Any. -class LIBPROTOBUF_EXPORT AnyMetadata { +class PROTOBUF_EXPORT AnyMetadata { typedef ArenaStringPtr UrlType; typedef ArenaStringPtr ValueType; public: // AnyMetadata does not take ownership of "type_url" and "value". - AnyMetadata(UrlType* type_url, ValueType* value); + constexpr AnyMetadata(UrlType* type_url, ValueType* value) + : type_url_(type_url), value_(value) {} // Packs a message using the default type URL prefix: "type.googleapis.com". // The resulted type URL will be "type.googleapis.com/". - void PackFrom(const Message& message); + // Returns false if serializing the message failed. + template + bool PackFrom(Arena* arena, const T& message) { + return InternalPackFrom(arena, message, kTypeGoogleApisComPrefix, + T::FullMessageName()); + } + + bool PackFrom(Arena* arena, const Message& message); + // Packs a message using the given type URL prefix. The type URL will be // constructed by concatenating the message type's full name to the prefix - // with an optional "/" separator if the prefix doesn't already end up "/". + // with an optional "/" separator if the prefix doesn't already end with "/". // For example, both PackFrom(message, "type.googleapis.com") and // PackFrom(message, "type.googleapis.com/") yield the same result type // URL: "type.googleapis.com/". - void PackFrom(const Message& message, const string& type_url_prefix); + // Returns false if serializing the message failed. + template + bool PackFrom(Arena* arena, const T& message, + StringPiece type_url_prefix) { + return InternalPackFrom(arena, message, type_url_prefix, + T::FullMessageName()); + } + + bool PackFrom(Arena* arena, const Message& message, + StringPiece type_url_prefix); // Unpacks the payload into the given message. Returns false if the message's // type doesn't match the type specified in the type URL (i.e., the full // name after the last "/" of the type URL doesn't match the message's actual // full name) or parsing the payload has failed. + template + bool UnpackTo(T* message) const { + return InternalUnpackTo(T::FullMessageName(), message); + } + bool UnpackTo(Message* message) const; // Checks whether the type specified in the type URL matches the given type. - // A type is consdiered matching if its full name matches the full name after + // A type is considered matching if its full name matches the full name after // the last "/" in the type URL. - template + template bool Is() const { - return InternalIs(T::default_instance().GetDescriptor()); + return InternalIs(T::FullMessageName()); } private: - bool InternalIs(const Descriptor* message) const; + bool InternalPackFrom(Arena* arena, const MessageLite& message, + StringPiece type_url_prefix, + StringPiece type_name); + bool InternalUnpackTo(StringPiece type_name, + MessageLite* message) const; + bool InternalIs(StringPiece type_name) const; UrlType* type_url_; ValueType* value_; @@ -84,10 +124,6 @@ class LIBPROTOBUF_EXPORT AnyMetadata { GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AnyMetadata); }; -extern const char kAnyFullTypeName[]; // "google.protobuf.Any". -extern const char kTypeGoogleApisComPrefix[]; // "type.googleapis.com/". -extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". - // Get the proto type name from Any::type_url value. For example, passing // "type.googleapis.com/rpc.QueryOrigin" will return "rpc.QueryOrigin" in // *full_type_name. Returns false if the type_url does not have a "/" @@ -95,15 +131,15 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/". // // NOTE: this function is available publicly as: // google::protobuf::Any() // static method on the generated message type. -bool ParseAnyTypeUrl(const string& type_url, string* full_type_name); +bool ParseAnyTypeUrl(StringPiece type_url, std::string* full_type_name); // Get the proto type name and prefix from Any::type_url value. For example, // passing "type.googleapis.com/rpc.QueryOrigin" will return // "type.googleapis.com/" in *url_prefix and "rpc.QueryOrigin" in // *full_type_name. Returns false if the type_url does not have a "/" in the // type url separating the full type name. -bool ParseAnyTypeUrl(const string& type_url, string* url_prefix, - string* full_type_name); +bool ParseAnyTypeUrl(StringPiece type_url, std::string* url_prefix, + std::string* full_type_name); // See if message is of type google.protobuf.Any, if so, return the descriptors // for "type_url" and "value" fields. @@ -113,6 +149,8 @@ bool GetAnyFieldDescriptors(const Message& message, } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ANY_H__ diff --git a/windows/include/google/protobuf/any.pb.cc b/windows/include/google/protobuf/any.pb.cc deleted file mode 100644 index 9d632efee..000000000 --- a/windows/include/google/protobuf/any.pb.cc +++ /dev/null @@ -1,435 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: google/protobuf/any.proto - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif -// @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { -class AnyDefaultTypeInternal { - public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; -} _Any_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fany_2eproto { -static void InitDefaultsAny() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - { - void* ptr = &::google::protobuf::_Any_default_instance_; - new (ptr) ::google::protobuf::Any(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); - } - ::google::protobuf::Any::InitAsDefaultInstance(); -} - -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Any = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAny}, {}}; - -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Any.base); -} - -::google::protobuf::Metadata file_level_metadata[1]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, value_), -}; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::Any)}, -}; - -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_Any_default_instance_), -}; - -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} - -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_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(\014Bo\n\023com.google.protobufB\010AnyProtoP\001Z" - "%github.com/golang/protobuf/ptypes/any\242\002" - "\003GPB\252\002\036Google.Protobuf.WellKnownTypesb\006p" - "roto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 205); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/any.proto", &protobuf_RegisterTypes); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fany_2eproto -namespace google { -namespace protobuf { - -// =================================================================== - -void Any::InitAsDefaultInstance() { -} -void Any::PackFrom(const ::google::protobuf::Message& message) { - _any_metadata_.PackFrom(message); -} - -void Any::PackFrom(const ::google::protobuf::Message& message, - const ::std::string& type_url_prefix) { - _any_metadata_.PackFrom(message, type_url_prefix); -} - -bool Any::UnpackTo(::google::protobuf::Message* message) const { - return _any_metadata_.UnpackTo(message); -} -bool Any::ParseAnyTypeUrl(const string& type_url, - string* full_type_name) { - return ::google::protobuf::internal::ParseAnyTypeUrl(type_url, - full_type_name); -} - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int Any::kTypeUrlFieldNumber; -const int Any::kValueFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -Any::Any() - : ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base); - SharedCtor(); - // @@protoc_insertion_point(constructor:google.protobuf.Any) -} -Any::Any(const Any& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _any_metadata_(&type_url_, &value_) { - _internal_metadata_.MergeFrom(from._internal_metadata_); - type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.type_url().size() > 0) { - type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_); - } - value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.value().size() > 0) { - value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); - } - // @@protoc_insertion_point(copy_constructor:google.protobuf.Any) -} - -void Any::SharedCtor() { - type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -Any::~Any() { - // @@protoc_insertion_point(destructor:google.protobuf.Any) - SharedDtor(); -} - -void Any::SharedDtor() { - type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - value_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void Any::SetCachedSize(int size) const { - _cached_size_.Set(size); -} -const ::google::protobuf::Descriptor* Any::descriptor() { - ::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - -const Any& Any::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base); - return *internal_default_instance(); -} - - -void Any::Clear() { -// @@protoc_insertion_point(message_clear_start:google.protobuf.Any) - ::google::protobuf::uint32 cached_has_bits = 0; - // Prevent compiler warnings about cached_has_bits being unused - (void) cached_has_bits; - - type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _internal_metadata_.Clear(); -} - -bool Any::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:google.protobuf.Any) - for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // string type_url = 1; - case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_type_url())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->type_url().data(), static_cast(this->type_url().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, - "google.protobuf.Any.type_url")); - } else { - goto handle_unusual; - } - break; - } - - // bytes value = 2; - case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_value())); - } else { - goto handle_unusual; - } - break; - } - - default: { - handle_unusual: - if (tag == 0) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, _internal_metadata_.mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:google.protobuf.Any) - return true; -failure: - // @@protoc_insertion_point(parse_failure:google.protobuf.Any) - return false; -#undef DO_ -} - -void Any::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:google.protobuf.Any) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // string type_url = 1; - if (this->type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->type_url().data(), static_cast(this->type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Any.type_url"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->type_url(), output); - } - - // bytes value = 2; - if (this->value().size() > 0) { - ::google::protobuf::internal::WireFormatLite::WriteBytesMaybeAliased( - 2, this->value(), output); - } - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); - } - // @@protoc_insertion_point(serialize_end:google.protobuf.Any) -} - -::google::protobuf::uint8* Any::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Any) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // string type_url = 1; - if (this->type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->type_url().data(), static_cast(this->type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Any.type_url"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->type_url(), target); - } - - // bytes value = 2; - if (this->value().size() > 0) { - target = - ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( - 2, this->value(), target); - } - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); - } - // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Any) - return target; -} - -size_t Any::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Any) - size_t total_size = 0; - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); - } - // string type_url = 1; - if (this->type_url().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->type_url()); - } - - // bytes value = 2; - if (this->value().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->value()); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - SetCachedSize(cached_size); - return total_size; -} - -void Any::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Any) - GOOGLE_DCHECK_NE(&from, this); - const Any* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Any) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Any) - MergeFrom(*source); - } -} - -void Any::MergeFrom(const Any& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Any) - GOOGLE_DCHECK_NE(&from, this); - _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - if (from.type_url().size() > 0) { - - type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type_url_); - } - if (from.value().size() > 0) { - - value_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.value_); - } -} - -void Any::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Any) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Any::CopyFrom(const Any& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Any) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Any::IsInitialized() const { - return true; -} - -void Any::Swap(Any* other) { - if (other == this) return; - InternalSwap(other); -} -void Any::InternalSwap(Any* other) { - using std::swap; - type_url_.Swap(&other->type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - value_.Swap(&other->value_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - _internal_metadata_.Swap(&other->_internal_metadata_); -} - -::google::protobuf::Metadata Any::GetMetadata() const { - protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages]; -} - - -// @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Any* Arena::CreateMaybeMessage< ::google::protobuf::Any >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::Any >(arena); -} -} // namespace protobuf -} // namespace google - -// @@protoc_insertion_point(global_scope) diff --git a/windows/include/google/protobuf/any.pb.h b/windows/include/google/protobuf/any.pb.h index 157fc80c4..ab07cc70d 100644 --- a/windows/include/google/protobuf/any.pb.h +++ b/windows/include/google/protobuf/any.pb.h @@ -1,98 +1,113 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3019000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3019001 < 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 incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include #include #include -#include -#include +#include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export #include -#include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fany_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[1]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fany_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[1] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const uint32_t offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fany_2eproto -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_2eproto; +PROTOBUF_NAMESPACE_OPEN class Any; -class AnyDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Any* Arena::CreateMaybeMessage<::google::protobuf::Any>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +struct AnyDefaultTypeInternal; +PROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_; +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 LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ { +class PROTOBUF_EXPORT Any final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ { public: - Any(); - virtual ~Any(); + inline Any() : Any(nullptr) {} + ~Any() override; + explicit constexpr Any(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); Any(const Any& from); - - inline Any& operator=(const Any& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Any(Any&& from) noexcept : Any() { *this = ::std::move(from); } + inline Any& operator=(const Any& from) { + CopyFrom(from); + return *this; + } inline Any& operator=(Any&& from) noexcept { - if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { - if (this != &from) InternalSwap(&from); + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); } else { CopyFrom(from); } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); - static const Any& default_instance(); - static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Any& default_instance() { + return *internal_default_instance(); + } static inline const Any* internal_default_instance() { return reinterpret_cast( &_Any_default_instance_); @@ -102,44 +117,78 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in // implements Any ----------------------------------------------- - void PackFrom(const ::google::protobuf::Message& message); - void PackFrom(const ::google::protobuf::Message& message, - const ::std::string& type_url_prefix); - bool UnpackTo(::google::protobuf::Message* message) const; + bool PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message) { + return _any_metadata_.PackFrom(GetArena(), message); + } + bool PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message, + ::PROTOBUF_NAMESPACE_ID::ConstStringParam type_url_prefix) { + return _any_metadata_.PackFrom(GetArena(), message, type_url_prefix); + } + bool UnpackTo(::PROTOBUF_NAMESPACE_ID::Message* message) const { + return _any_metadata_.UnpackTo(message); + } + static bool GetAnyFieldDescriptors( + const ::PROTOBUF_NAMESPACE_ID::Message& message, + const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** type_url_field, + const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** value_field); + template ::value>::type> + bool PackFrom(const T& message) { + return _any_metadata_.PackFrom(GetArena(), message); + } + template ::value>::type> + bool PackFrom(const T& message, + ::PROTOBUF_NAMESPACE_ID::ConstStringParam type_url_prefix) { + return _any_metadata_.PackFrom(GetArena(), message, type_url_prefix);} + template ::value>::type> + bool UnpackTo(T* message) const { + return _any_metadata_.UnpackTo(message); + } template bool Is() const { return _any_metadata_.Is(); } - static bool ParseAnyTypeUrl(const string& type_url, - string* full_type_name); - - void Swap(Any* other); + static bool ParseAnyTypeUrl(::PROTOBUF_NAMESPACE_ID::ConstStringParam type_url, + std::string* full_type_name); friend void swap(Any& a, Any& b) { a.Swap(&b); } + inline void Swap(Any* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Any* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } // implements Message ---------------------------------------------- - inline Any* New() const final { - return CreateMaybeMessage(NULL); - } - - Any* New(::google::protobuf::Arena* arena) const final { + Any* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const Any& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const Any& from); - void Clear() final; + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: @@ -147,58 +196,73 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Any* other); + private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; - } - inline void* MaybeArenaPtr() const { - return NULL; + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Any"; } + protected: + explicit Any(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: - ::google::protobuf::Metadata GetMetadata() const final; + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- + enum : int { + kTypeUrlFieldNumber = 1, + kValueFieldNumber = 2, + }; // string type_url = 1; void clear_type_url(); - static const int kTypeUrlFieldNumber = 1; - const ::std::string& type_url() const; - void set_type_url(const ::std::string& value); - #if LANG_CXX11 - void set_type_url(::std::string&& value); - #endif - void set_type_url(const char* value); - void set_type_url(const char* value, size_t size); - ::std::string* mutable_type_url(); - ::std::string* release_type_url(); - void set_allocated_type_url(::std::string* type_url); + const std::string& type_url() const; + template + void set_type_url(ArgT0&& arg0, ArgT... args); + std::string* mutable_type_url(); + PROTOBUF_NODISCARD std::string* release_type_url(); + void set_allocated_type_url(std::string* type_url); + private: + const std::string& _internal_type_url() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_type_url(const std::string& value); + std::string* _internal_mutable_type_url(); + public: // bytes value = 2; void clear_value(); - static const int kValueFieldNumber = 2; - const ::std::string& value() const; - void set_value(const ::std::string& value); - #if LANG_CXX11 - void set_value(::std::string&& value); - #endif - void set_value(const char* value); - void set_value(const void* value, size_t size); - ::std::string* mutable_value(); - ::std::string* release_value(); - void set_allocated_value(::std::string* value); + const std::string& value() const; + template + void set_value(ArgT0&& arg0, ArgT... args); + std::string* mutable_value(); + PROTOBUF_NODISCARD std::string* release_value(); + void set_allocated_value(std::string* value); + private: + const std::string& _internal_value() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_value(const std::string& value); + std::string* _internal_mutable_value(); + public: // @@protoc_insertion_point(class_scope:google.protobuf.Any) private: + class _Internal; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr type_url_; - ::google::protobuf::internal::ArenaStringPtr value_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::AnyMetadata _any_metadata_; - friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata _any_metadata_; + friend struct ::TableStruct_google_2fprotobuf_2fany_2eproto; }; // =================================================================== @@ -213,107 +277,103 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in // string type_url = 1; inline void Any::clear_type_url() { - type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + type_url_.ClearToEmpty(); } -inline const ::std::string& Any::type_url() const { +inline const std::string& Any::type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Any.type_url) - return type_url_.GetNoArena(); + return _internal_type_url(); } -inline void Any::set_type_url(const ::std::string& value) { - - type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Any::set_type_url(ArgT0&& arg0, ArgT... args) { + + type_url_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Any.type_url) } -#if LANG_CXX11 -inline void Any::set_type_url(::std::string&& value) { - - type_url_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.type_url) -} -#endif -inline void Any::set_type_url(const char* value) { - GOOGLE_DCHECK(value != NULL); - - type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Any.type_url) -} -inline void Any::set_type_url(const char* value, size_t size) { - - type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.type_url) -} -inline ::std::string* Any::mutable_type_url() { - +inline std::string* Any::mutable_type_url() { + std::string* _s = _internal_mutable_type_url(); // @@protoc_insertion_point(field_mutable:google.protobuf.Any.type_url) - return type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Any::release_type_url() { - // @@protoc_insertion_point(field_release:google.protobuf.Any.type_url) +inline const std::string& Any::_internal_type_url() const { + return type_url_.Get(); +} +inline void Any::_internal_set_type_url(const std::string& value) { - return type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + type_url_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Any::set_allocated_type_url(::std::string* type_url) { - if (type_url != NULL) { +inline std::string* Any::_internal_mutable_type_url() { + + return type_url_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Any::release_type_url() { + // @@protoc_insertion_point(field_release:google.protobuf.Any.type_url) + return type_url_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Any::set_allocated_type_url(std::string* type_url) { + if (type_url != nullptr) { } else { } - type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url); + type_url_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), type_url, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (type_url_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.type_url) } // bytes value = 2; inline void Any::clear_value() { - value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + value_.ClearToEmpty(); } -inline const ::std::string& Any::value() const { +inline const std::string& Any::value() const { // @@protoc_insertion_point(field_get:google.protobuf.Any.value) - return value_.GetNoArena(); + return _internal_value(); } -inline void Any::set_value(const ::std::string& value) { - - value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Any::set_value(ArgT0&& arg0, ArgT... args) { + + value_.SetBytes(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Any.value) } -#if LANG_CXX11 -inline void Any::set_value(::std::string&& value) { - - value_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.value) -} -#endif -inline void Any::set_value(const char* value) { - GOOGLE_DCHECK(value != NULL); - - value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Any.value) -} -inline void Any::set_value(const void* value, size_t size) { - - value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.value) -} -inline ::std::string* Any::mutable_value() { - +inline std::string* Any::mutable_value() { + std::string* _s = _internal_mutable_value(); // @@protoc_insertion_point(field_mutable:google.protobuf.Any.value) - return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Any::release_value() { - // @@protoc_insertion_point(field_release:google.protobuf.Any.value) +inline const std::string& Any::_internal_value() const { + return value_.Get(); +} +inline void Any::_internal_set_value(const std::string& value) { - return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + value_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Any::set_allocated_value(::std::string* value) { - if (value != NULL) { +inline std::string* Any::_internal_mutable_value() { + + return value_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Any::release_value() { + // @@protoc_insertion_point(field_release:google.protobuf.Any.value) + return value_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Any::set_allocated_value(std::string* value) { + if (value != nullptr) { } else { } - value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); + value_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), value, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (value_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + value_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value) } @@ -323,9 +383,9 @@ inline void Any::set_allocated_value(::std::string* value) { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto diff --git a/windows/include/google/protobuf/any.proto b/windows/include/google/protobuf/any.proto index 493294255..6ed8a23cf 100644 --- a/windows/include/google/protobuf/any.proto +++ b/windows/include/google/protobuf/any.proto @@ -33,7 +33,7 @@ syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; -option go_package = "github.com/golang/protobuf/ptypes/any"; +option go_package = "google.golang.org/protobuf/types/known/anypb"; option java_package = "com.google.protobuf"; option java_outer_classname = "AnyProto"; option java_multiple_files = true; @@ -77,10 +77,13 @@ option objc_class_prefix = "GPB"; // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} -// any, err := ptypes.MarshalAny(foo) +// any, err := anypb.New(foo) +// if err != nil { +// ... +// } // ... // foo := &pb.Foo{} -// if err := ptypes.UnmarshalAny(any, foo); err != nil { +// if err := any.UnmarshalTo(foo); err != nil { // ... // } // @@ -121,7 +124,8 @@ option objc_class_prefix = "GPB"; // message Any { // A URL/resource name that uniquely identifies the type of the serialized - // protocol buffer message. The last segment of the URL's path must represent + // protocol buffer message. This string must contain at least + // one "/" character. The last segment of the URL's path must represent // the fully qualified name of the type (as in // `path/google.protobuf.Duration`). The name should be in a canonical form // (e.g., leading "." is not accepted). diff --git a/windows/include/google/protobuf/any_test.cc b/windows/include/google/protobuf/any_test.cc deleted file mode 100644 index 1bfaa63d8..000000000 --- a/windows/include/google/protobuf/any_test.cc +++ /dev/null @@ -1,89 +0,0 @@ -// 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. - -#include -#include - -namespace google { -namespace protobuf { -namespace { - -TEST(AnyTest, TestPackAndUnpack) { - protobuf_unittest::TestAny submessage; - submessage.set_int32_value(12345); - protobuf_unittest::TestAny message; - message.mutable_any_value()->PackFrom(submessage); - - string data = message.SerializeAsString(); - - ASSERT_TRUE(message.ParseFromString(data)); - EXPECT_TRUE(message.has_any_value()); - ASSERT_TRUE(message.any_value().UnpackTo(&submessage)); - EXPECT_EQ(12345, submessage.int32_value()); -} - -TEST(AnyTest, TestPackAndUnpackAny) { - // We can pack a Any message inside another Any message. - protobuf_unittest::TestAny submessage; - submessage.set_int32_value(12345); - google::protobuf::Any any; - any.PackFrom(submessage); - protobuf_unittest::TestAny message; - message.mutable_any_value()->PackFrom(any); - - string data = message.SerializeAsString(); - - ASSERT_TRUE(message.ParseFromString(data)); - EXPECT_TRUE(message.has_any_value()); - ASSERT_TRUE(message.any_value().UnpackTo(&any)); - ASSERT_TRUE(any.UnpackTo(&submessage)); - EXPECT_EQ(12345, submessage.int32_value()); -} - -TEST(AnyTest, TestIs) { - protobuf_unittest::TestAny submessage; - submessage.set_int32_value(12345); - google::protobuf::Any any; - any.PackFrom(submessage); - ASSERT_TRUE(any.ParseFromString(any.SerializeAsString())); - EXPECT_TRUE(any.Is()); - EXPECT_FALSE(any.Is()); - - protobuf_unittest::TestAny message; - message.mutable_any_value()->PackFrom(any); - ASSERT_TRUE(message.ParseFromString(message.SerializeAsString())); - EXPECT_FALSE(message.any_value().Is()); - EXPECT_TRUE(message.any_value().Is()); -} - -} // namespace -} // namespace protobuf - -} // namespace google diff --git a/windows/include/google/protobuf/any_test.proto b/windows/include/google/protobuf/any_test.proto deleted file mode 100644 index 0c5b30ba3..000000000 --- a/windows/include/google/protobuf/any_test.proto +++ /dev/null @@ -1,41 +0,0 @@ -// 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. - -syntax = "proto3"; - -package protobuf_unittest; - -import "google/protobuf/any.proto"; - -message TestAny { - int32 int32_value = 1; - google.protobuf.Any any_value = 2; - repeated google.protobuf.Any repeated_any_value = 3; -} diff --git a/windows/include/google/protobuf/api.pb.cc b/windows/include/google/protobuf/api.pb.cc deleted file mode 100644 index e0a249d04..000000000 --- a/windows/include/google/protobuf/api.pb.cc +++ /dev/null @@ -1,1589 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: google/protobuf/api.proto - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif -// @@protoc_insertion_point(includes) - -namespace protobuf_google_2fprotobuf_2fapi_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Method; -} // namespace protobuf_google_2fprotobuf_2fapi_2eproto -namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_SourceContext; -} // namespace protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto -namespace protobuf_google_2fprotobuf_2ftype_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2ftype_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Option; -} // namespace protobuf_google_2fprotobuf_2ftype_2eproto -namespace google { -namespace protobuf { -class ApiDefaultTypeInternal { - public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; -} _Api_default_instance_; -class MethodDefaultTypeInternal { - public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; -} _Method_default_instance_; -class MixinDefaultTypeInternal { - public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; -} _Mixin_default_instance_; -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fapi_2eproto { -static void InitDefaultsApi() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - { - void* ptr = &::google::protobuf::_Api_default_instance_; - new (ptr) ::google::protobuf::Api(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); - } - ::google::protobuf::Api::InitAsDefaultInstance(); -} - -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<4> scc_info_Api = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 4, InitDefaultsApi}, { - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base, - &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base, - &protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::scc_info_SourceContext.base, - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base,}}; - -static void InitDefaultsMethod() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - { - void* ptr = &::google::protobuf::_Method_default_instance_; - new (ptr) ::google::protobuf::Method(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); - } - ::google::protobuf::Method::InitAsDefaultInstance(); -} - -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_Method = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsMethod}, { - &protobuf_google_2fprotobuf_2ftype_2eproto::scc_info_Option.base,}}; - -static void InitDefaultsMixin() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - { - void* ptr = &::google::protobuf::_Mixin_default_instance_; - new (ptr) ::google::protobuf::Mixin(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); - } - ::google::protobuf::Mixin::InitAsDefaultInstance(); -} - -LIBPROTOBUF_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Mixin = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsMixin}, {}}; - -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Api.base); - ::google::protobuf::internal::InitSCC(&scc_info_Method.base); - ::google::protobuf::internal::InitSCC(&scc_info_Mixin.base); -} - -::google::protobuf::Metadata file_level_metadata[3]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, methods_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, version_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, source_context_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, mixins_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Api, syntax_), - ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, request_type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, request_streaming_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, response_type_url_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, response_streaming_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, options_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Method, syntax_), - ~0u, // no _has_bits_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Mixin, root_), -}; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, -1, sizeof(::google::protobuf::Api)}, - { 12, -1, sizeof(::google::protobuf::Method)}, - { 24, -1, sizeof(::google::protobuf::Mixin)}, -}; - -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::_Api_default_instance_), - reinterpret_cast(&::google::protobuf::_Method_default_instance_), - reinterpret_cast(&::google::protobuf::_Mixin_default_instance_), -}; - -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} - -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_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(\tBu\n\023com.google.pr" - "otobufB\010ApiProtoP\001Z+google.golang.org/ge" - "nproto/protobuf/api;api\242\002\003GPB\252\002\036Google.P" - "rotobuf.WellKnownTypesb\006proto3" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 750); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/api.proto", &protobuf_RegisterTypes); - ::protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::AddDescriptors(); - ::protobuf_google_2fprotobuf_2ftype_2eproto::AddDescriptors(); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fapi_2eproto -namespace google { -namespace protobuf { - -// =================================================================== - -void Api::InitAsDefaultInstance() { - ::google::protobuf::_Api_default_instance_._instance.get_mutable()->source_context_ = const_cast< ::google::protobuf::SourceContext*>( - ::google::protobuf::SourceContext::internal_default_instance()); -} -void Api::clear_options() { - options_.Clear(); -} -void Api::clear_source_context() { - if (GetArenaNoVirtual() == NULL && source_context_ != NULL) { - delete source_context_; - } - source_context_ = NULL; -} -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int Api::kNameFieldNumber; -const int Api::kMethodsFieldNumber; -const int Api::kOptionsFieldNumber; -const int Api::kVersionFieldNumber; -const int Api::kSourceContextFieldNumber; -const int Api::kMixinsFieldNumber; -const int Api::kSyntaxFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -Api::Api() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base); - SharedCtor(); - // @@protoc_insertion_point(constructor:google.protobuf.Api) -} -Api::Api(const Api& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), - methods_(from.methods_), - options_(from.options_), - mixins_(from.mixins_) { - _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.version().size() > 0) { - version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.version_); - } - if (from.has_source_context()) { - source_context_ = new ::google::protobuf::SourceContext(*from.source_context_); - } else { - source_context_ = NULL; - } - syntax_ = from.syntax_; - // @@protoc_insertion_point(copy_constructor:google.protobuf.Api) -} - -void Api::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - version_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(&source_context_, 0, static_cast( - reinterpret_cast(&syntax_) - - reinterpret_cast(&source_context_)) + sizeof(syntax_)); -} - -Api::~Api() { - // @@protoc_insertion_point(destructor:google.protobuf.Api) - SharedDtor(); -} - -void Api::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - version_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (this != internal_default_instance()) delete source_context_; -} - -void Api::SetCachedSize(int size) const { - _cached_size_.Set(size); -} -const ::google::protobuf::Descriptor* Api::descriptor() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - -const Api& Api::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base); - return *internal_default_instance(); -} - - -void Api::Clear() { -// @@protoc_insertion_point(message_clear_start:google.protobuf.Api) - ::google::protobuf::uint32 cached_has_bits = 0; - // Prevent compiler warnings about cached_has_bits being unused - (void) cached_has_bits; - - methods_.Clear(); - options_.Clear(); - mixins_.Clear(); - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (GetArenaNoVirtual() == NULL && source_context_ != NULL) { - delete source_context_; - } - source_context_ = NULL; - syntax_ = 0; - _internal_metadata_.Clear(); -} - -bool Api::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:google.protobuf.Api) - for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // string name = 1; - case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, - "google.protobuf.Api.name")); - } else { - goto handle_unusual; - } - break; - } - - // repeated .google.protobuf.Method methods = 2; - case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( - input, add_methods())); - } else { - goto handle_unusual; - } - break; - } - - // repeated .google.protobuf.Option options = 3; - case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( - input, add_options())); - } else { - goto handle_unusual; - } - break; - } - - // string version = 4; - case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_version())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->version().data(), static_cast(this->version().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, - "google.protobuf.Api.version")); - } else { - goto handle_unusual; - } - break; - } - - // .google.protobuf.SourceContext source_context = 5; - case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(42u /* 42 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( - input, mutable_source_context())); - } else { - goto handle_unusual; - } - break; - } - - // repeated .google.protobuf.Mixin mixins = 6; - case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( - input, add_mixins())); - } else { - goto handle_unusual; - } - break; - } - - // .google.protobuf.Syntax syntax = 7; - case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( - input, &value))); - set_syntax(static_cast< ::google::protobuf::Syntax >(value)); - } else { - goto handle_unusual; - } - break; - } - - default: { - handle_unusual: - if (tag == 0) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, _internal_metadata_.mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:google.protobuf.Api) - return true; -failure: - // @@protoc_insertion_point(parse_failure:google.protobuf.Api) - return false; -#undef DO_ -} - -void Api::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:google.protobuf.Api) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Api.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->name(), output); - } - - // repeated .google.protobuf.Method methods = 2; - for (unsigned int i = 0, - n = static_cast(this->methods_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, - this->methods(static_cast(i)), - output); - } - - // repeated .google.protobuf.Option options = 3; - for (unsigned int i = 0, - n = static_cast(this->options_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, - this->options(static_cast(i)), - output); - } - - // string version = 4; - if (this->version().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->version().data(), static_cast(this->version().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Api.version"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 4, this->version(), output); - } - - // .google.protobuf.SourceContext source_context = 5; - if (this->has_source_context()) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, this->_internal_source_context(), output); - } - - // repeated .google.protobuf.Mixin mixins = 6; - for (unsigned int i = 0, - n = static_cast(this->mixins_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 6, - this->mixins(static_cast(i)), - output); - } - - // .google.protobuf.Syntax syntax = 7; - if (this->syntax() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( - 7, this->syntax(), output); - } - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); - } - // @@protoc_insertion_point(serialize_end:google.protobuf.Api) -} - -::google::protobuf::uint8* Api::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Api) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Api.name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // repeated .google.protobuf.Method methods = 2; - for (unsigned int i = 0, - n = static_cast(this->methods_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageToArray( - 2, this->methods(static_cast(i)), deterministic, target); - } - - // repeated .google.protobuf.Option options = 3; - for (unsigned int i = 0, - n = static_cast(this->options_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageToArray( - 3, this->options(static_cast(i)), deterministic, target); - } - - // string version = 4; - if (this->version().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->version().data(), static_cast(this->version().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Api.version"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 4, this->version(), target); - } - - // .google.protobuf.SourceContext source_context = 5; - if (this->has_source_context()) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageToArray( - 5, this->_internal_source_context(), deterministic, target); - } - - // repeated .google.protobuf.Mixin mixins = 6; - for (unsigned int i = 0, - n = static_cast(this->mixins_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageToArray( - 6, this->mixins(static_cast(i)), deterministic, target); - } - - // .google.protobuf.Syntax syntax = 7; - if (this->syntax() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( - 7, this->syntax(), target); - } - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); - } - // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Api) - return target; -} - -size_t Api::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Api) - size_t total_size = 0; - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); - } - // repeated .google.protobuf.Method methods = 2; - { - unsigned int count = static_cast(this->methods_size()); - total_size += 1UL * count; - for (unsigned int i = 0; i < count; i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( - this->methods(static_cast(i))); - } - } - - // repeated .google.protobuf.Option options = 3; - { - unsigned int count = static_cast(this->options_size()); - total_size += 1UL * count; - for (unsigned int i = 0; i < count; i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( - this->options(static_cast(i))); - } - } - - // repeated .google.protobuf.Mixin mixins = 6; - { - unsigned int count = static_cast(this->mixins_size()); - total_size += 1UL * count; - for (unsigned int i = 0; i < count; i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( - this->mixins(static_cast(i))); - } - } - - // string name = 1; - if (this->name().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // string version = 4; - if (this->version().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->version()); - } - - // .google.protobuf.SourceContext source_context = 5; - if (this->has_source_context()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( - *source_context_); - } - - // .google.protobuf.Syntax syntax = 7; - if (this->syntax() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->syntax()); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - SetCachedSize(cached_size); - return total_size; -} - -void Api::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Api) - GOOGLE_DCHECK_NE(&from, this); - const Api* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Api) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Api) - MergeFrom(*source); - } -} - -void Api::MergeFrom(const Api& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Api) - GOOGLE_DCHECK_NE(&from, this); - _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - methods_.MergeFrom(from.methods_); - options_.MergeFrom(from.options_); - mixins_.MergeFrom(from.mixins_); - if (from.name().size() > 0) { - - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - if (from.version().size() > 0) { - - version_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.version_); - } - if (from.has_source_context()) { - mutable_source_context()->::google::protobuf::SourceContext::MergeFrom(from.source_context()); - } - if (from.syntax() != 0) { - set_syntax(from.syntax()); - } -} - -void Api::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Api) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Api::CopyFrom(const Api& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Api) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Api::IsInitialized() const { - return true; -} - -void Api::Swap(Api* other) { - if (other == this) return; - InternalSwap(other); -} -void Api::InternalSwap(Api* other) { - using std::swap; - CastToBase(&methods_)->InternalSwap(CastToBase(&other->methods_)); - CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - CastToBase(&mixins_)->InternalSwap(CastToBase(&other->mixins_)); - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - version_.Swap(&other->version_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - swap(source_context_, other->source_context_); - swap(syntax_, other->syntax_); - _internal_metadata_.Swap(&other->_internal_metadata_); -} - -::google::protobuf::Metadata Api::GetMetadata() const { - protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages]; -} - - -// =================================================================== - -void Method::InitAsDefaultInstance() { -} -void Method::clear_options() { - options_.Clear(); -} -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int Method::kNameFieldNumber; -const int Method::kRequestTypeUrlFieldNumber; -const int Method::kRequestStreamingFieldNumber; -const int Method::kResponseTypeUrlFieldNumber; -const int Method::kResponseStreamingFieldNumber; -const int Method::kOptionsFieldNumber; -const int Method::kSyntaxFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -Method::Method() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base); - SharedCtor(); - // @@protoc_insertion_point(constructor:google.protobuf.Method) -} -Method::Method(const Method& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), - options_(from.options_) { - _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.request_type_url().size() > 0) { - request_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.request_type_url_); - } - response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.response_type_url().size() > 0) { - response_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.response_type_url_); - } - ::memcpy(&request_streaming_, &from.request_streaming_, - static_cast(reinterpret_cast(&syntax_) - - reinterpret_cast(&request_streaming_)) + sizeof(syntax_)); - // @@protoc_insertion_point(copy_constructor:google.protobuf.Method) -} - -void Method::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - request_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - response_type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(&request_streaming_, 0, static_cast( - reinterpret_cast(&syntax_) - - reinterpret_cast(&request_streaming_)) + sizeof(syntax_)); -} - -Method::~Method() { - // @@protoc_insertion_point(destructor:google.protobuf.Method) - SharedDtor(); -} - -void Method::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - request_type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - response_type_url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void Method::SetCachedSize(int size) const { - _cached_size_.Set(size); -} -const ::google::protobuf::Descriptor* Method::descriptor() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - -const Method& Method::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base); - return *internal_default_instance(); -} - - -void Method::Clear() { -// @@protoc_insertion_point(message_clear_start:google.protobuf.Method) - ::google::protobuf::uint32 cached_has_bits = 0; - // Prevent compiler warnings about cached_has_bits being unused - (void) cached_has_bits; - - options_.Clear(); - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - request_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - response_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(&request_streaming_, 0, static_cast( - reinterpret_cast(&syntax_) - - reinterpret_cast(&request_streaming_)) + sizeof(syntax_)); - _internal_metadata_.Clear(); -} - -bool Method::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:google.protobuf.Method) - for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // string name = 1; - case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, - "google.protobuf.Method.name")); - } else { - goto handle_unusual; - } - break; - } - - // string request_type_url = 2; - case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_request_type_url())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->request_type_url().data(), static_cast(this->request_type_url().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, - "google.protobuf.Method.request_type_url")); - } else { - goto handle_unusual; - } - break; - } - - // bool request_streaming = 3; - case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { - - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &request_streaming_))); - } else { - goto handle_unusual; - } - break; - } - - // string response_type_url = 4; - case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_response_type_url())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->response_type_url().data(), static_cast(this->response_type_url().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, - "google.protobuf.Method.response_type_url")); - } else { - goto handle_unusual; - } - break; - } - - // bool response_streaming = 5; - case 5: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { - - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &response_streaming_))); - } else { - goto handle_unusual; - } - break; - } - - // repeated .google.protobuf.Option options = 6; - case 6: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(50u /* 50 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( - input, add_options())); - } else { - goto handle_unusual; - } - break; - } - - // .google.protobuf.Syntax syntax = 7; - case 7: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(56u /* 56 & 0xFF */)) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( - input, &value))); - set_syntax(static_cast< ::google::protobuf::Syntax >(value)); - } else { - goto handle_unusual; - } - break; - } - - default: { - handle_unusual: - if (tag == 0) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, _internal_metadata_.mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:google.protobuf.Method) - return true; -failure: - // @@protoc_insertion_point(parse_failure:google.protobuf.Method) - return false; -#undef DO_ -} - -void Method::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:google.protobuf.Method) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Method.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->name(), output); - } - - // string request_type_url = 2; - if (this->request_type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->request_type_url().data(), static_cast(this->request_type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Method.request_type_url"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 2, this->request_type_url(), output); - } - - // bool request_streaming = 3; - if (this->request_streaming() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->request_streaming(), output); - } - - // string response_type_url = 4; - if (this->response_type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->response_type_url().data(), static_cast(this->response_type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Method.response_type_url"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 4, this->response_type_url(), output); - } - - // bool response_streaming = 5; - if (this->response_streaming() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteBool(5, this->response_streaming(), output); - } - - // repeated .google.protobuf.Option options = 6; - for (unsigned int i = 0, - n = static_cast(this->options_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 6, - this->options(static_cast(i)), - output); - } - - // .google.protobuf.Syntax syntax = 7; - if (this->syntax() != 0) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( - 7, this->syntax(), output); - } - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); - } - // @@protoc_insertion_point(serialize_end:google.protobuf.Method) -} - -::google::protobuf::uint8* Method::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Method) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Method.name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // string request_type_url = 2; - if (this->request_type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->request_type_url().data(), static_cast(this->request_type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Method.request_type_url"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->request_type_url(), target); - } - - // bool request_streaming = 3; - if (this->request_streaming() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->request_streaming(), target); - } - - // string response_type_url = 4; - if (this->response_type_url().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->response_type_url().data(), static_cast(this->response_type_url().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Method.response_type_url"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 4, this->response_type_url(), target); - } - - // bool response_streaming = 5; - if (this->response_streaming() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(5, this->response_streaming(), target); - } - - // repeated .google.protobuf.Option options = 6; - for (unsigned int i = 0, - n = static_cast(this->options_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageToArray( - 6, this->options(static_cast(i)), deterministic, target); - } - - // .google.protobuf.Syntax syntax = 7; - if (this->syntax() != 0) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( - 7, this->syntax(), target); - } - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); - } - // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Method) - return target; -} - -size_t Method::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Method) - size_t total_size = 0; - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); - } - // repeated .google.protobuf.Option options = 6; - { - unsigned int count = static_cast(this->options_size()); - total_size += 1UL * count; - for (unsigned int i = 0; i < count; i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( - this->options(static_cast(i))); - } - } - - // string name = 1; - if (this->name().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // string request_type_url = 2; - if (this->request_type_url().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->request_type_url()); - } - - // string response_type_url = 4; - if (this->response_type_url().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->response_type_url()); - } - - // bool request_streaming = 3; - if (this->request_streaming() != 0) { - total_size += 1 + 1; - } - - // bool response_streaming = 5; - if (this->response_streaming() != 0) { - total_size += 1 + 1; - } - - // .google.protobuf.Syntax syntax = 7; - if (this->syntax() != 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->syntax()); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - SetCachedSize(cached_size); - return total_size; -} - -void Method::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Method) - GOOGLE_DCHECK_NE(&from, this); - const Method* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Method) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Method) - MergeFrom(*source); - } -} - -void Method::MergeFrom(const Method& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Method) - GOOGLE_DCHECK_NE(&from, this); - _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - options_.MergeFrom(from.options_); - if (from.name().size() > 0) { - - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - if (from.request_type_url().size() > 0) { - - request_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.request_type_url_); - } - if (from.response_type_url().size() > 0) { - - response_type_url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.response_type_url_); - } - if (from.request_streaming() != 0) { - set_request_streaming(from.request_streaming()); - } - if (from.response_streaming() != 0) { - set_response_streaming(from.response_streaming()); - } - if (from.syntax() != 0) { - set_syntax(from.syntax()); - } -} - -void Method::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Method) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Method::CopyFrom(const Method& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Method) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Method::IsInitialized() const { - return true; -} - -void Method::Swap(Method* other) { - if (other == this) return; - InternalSwap(other); -} -void Method::InternalSwap(Method* other) { - using std::swap; - CastToBase(&options_)->InternalSwap(CastToBase(&other->options_)); - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - request_type_url_.Swap(&other->request_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - response_type_url_.Swap(&other->response_type_url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - swap(request_streaming_, other->request_streaming_); - swap(response_streaming_, other->response_streaming_); - swap(syntax_, other->syntax_); - _internal_metadata_.Swap(&other->_internal_metadata_); -} - -::google::protobuf::Metadata Method::GetMetadata() const { - protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages]; -} - - -// =================================================================== - -void Mixin::InitAsDefaultInstance() { -} -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int Mixin::kNameFieldNumber; -const int Mixin::kRootFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -Mixin::Mixin() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base); - SharedCtor(); - // @@protoc_insertion_point(constructor:google.protobuf.Mixin) -} -Mixin::Mixin(const Mixin& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL) { - _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.name().size() > 0) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.root().size() > 0) { - root_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.root_); - } - // @@protoc_insertion_point(copy_constructor:google.protobuf.Mixin) -} - -void Mixin::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -Mixin::~Mixin() { - // @@protoc_insertion_point(destructor:google.protobuf.Mixin) - SharedDtor(); -} - -void Mixin::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - root_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void Mixin::SetCachedSize(int size) const { - _cached_size_.Set(size); -} -const ::google::protobuf::Descriptor* Mixin::descriptor() { - ::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - -const Mixin& Mixin::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base); - return *internal_default_instance(); -} - - -void Mixin::Clear() { -// @@protoc_insertion_point(message_clear_start:google.protobuf.Mixin) - ::google::protobuf::uint32 cached_has_bits = 0; - // Prevent compiler warnings about cached_has_bits being unused - (void) cached_has_bits; - - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - root_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - _internal_metadata_.Clear(); -} - -bool Mixin::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:google.protobuf.Mixin) - for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // string name = 1; - case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, - "google.protobuf.Mixin.name")); - } else { - goto handle_unusual; - } - break; - } - - // string root = 2; - case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_root())); - DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->root().data(), static_cast(this->root().length()), - ::google::protobuf::internal::WireFormatLite::PARSE, - "google.protobuf.Mixin.root")); - } else { - goto handle_unusual; - } - break; - } - - default: { - handle_unusual: - if (tag == 0) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, _internal_metadata_.mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:google.protobuf.Mixin) - return true; -failure: - // @@protoc_insertion_point(parse_failure:google.protobuf.Mixin) - return false; -#undef DO_ -} - -void Mixin::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:google.protobuf.Mixin) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Mixin.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->name(), output); - } - - // string root = 2; - if (this->root().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->root().data(), static_cast(this->root().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Mixin.root"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 2, this->root(), output); - } - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); - } - // @@protoc_insertion_point(serialize_end:google.protobuf.Mixin) -} - -::google::protobuf::uint8* Mixin::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Mixin) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // string name = 1; - if (this->name().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Mixin.name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // string root = 2; - if (this->root().size() > 0) { - ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( - this->root().data(), static_cast(this->root().length()), - ::google::protobuf::internal::WireFormatLite::SERIALIZE, - "google.protobuf.Mixin.root"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->root(), target); - } - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); - } - // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Mixin) - return target; -} - -size_t Mixin::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Mixin) - size_t total_size = 0; - - if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); - } - // string name = 1; - if (this->name().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // string root = 2; - if (this->root().size() > 0) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->root()); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - SetCachedSize(cached_size); - return total_size; -} - -void Mixin::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.Mixin) - GOOGLE_DCHECK_NE(&from, this); - const Mixin* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.Mixin) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.Mixin) - MergeFrom(*source); - } -} - -void Mixin::MergeFrom(const Mixin& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.Mixin) - GOOGLE_DCHECK_NE(&from, this); - _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - if (from.name().size() > 0) { - - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - if (from.root().size() > 0) { - - root_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.root_); - } -} - -void Mixin::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.Mixin) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Mixin::CopyFrom(const Mixin& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.Mixin) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Mixin::IsInitialized() const { - return true; -} - -void Mixin::Swap(Mixin* other) { - if (other == this) return; - InternalSwap(other); -} -void Mixin::InternalSwap(Mixin* other) { - using std::swap; - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - root_.Swap(&other->root_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - _internal_metadata_.Swap(&other->_internal_metadata_); -} - -::google::protobuf::Metadata Mixin::GetMetadata() const { - protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fapi_2eproto::file_level_metadata[kIndexInFileMessages]; -} - - -// @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Api* Arena::CreateMaybeMessage< ::google::protobuf::Api >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::Api >(arena); -} -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Method* Arena::CreateMaybeMessage< ::google::protobuf::Method >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::Method >(arena); -} -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::Mixin* Arena::CreateMaybeMessage< ::google::protobuf::Mixin >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::Mixin >(arena); -} -} // namespace protobuf -} // namespace google - -// @@protoc_insertion_point(global_scope) diff --git a/windows/include/google/protobuf/api.pb.h b/windows/include/google/protobuf/api.pb.h index 581e21a58..26e1946f8 100644 --- a/windows/include/google/protobuf/api.pb.h +++ b/windows/include/google/protobuf/api.pb.h @@ -1,31 +1,32 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/api.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3019000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3019001 < 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 incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include #include #include -#include -#include +#include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export @@ -33,75 +34,90 @@ #include #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto LIBPROTOBUF_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fapi_2eproto PROTOBUF_EXPORT +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fapi_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOBUF_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[3]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOBUF_EXPORT TableStruct_google_2fprotobuf_2fapi_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[3] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const uint32_t offsets[]; }; -void LIBPROTOBUF_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fapi_2eproto -namespace google { -namespace protobuf { +PROTOBUF_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fapi_2eproto; +PROTOBUF_NAMESPACE_OPEN class Api; -class ApiDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_; +struct ApiDefaultTypeInternal; +PROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_; class Method; -class MethodDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_; +struct MethodDefaultTypeInternal; +PROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_; class Mixin; -class MixinDefaultTypeInternal; -LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Api* Arena::CreateMaybeMessage<::google::protobuf::Api>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Method* Arena::CreateMaybeMessage<::google::protobuf::Method>(Arena*); -template<> LIBPROTOBUF_EXPORT ::google::protobuf::Mixin* Arena::CreateMaybeMessage<::google::protobuf::Mixin>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +struct MixinDefaultTypeInternal; +PROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_; +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 LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ { +class PROTOBUF_EXPORT Api final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ { public: - Api(); - virtual ~Api(); + inline Api() : Api(nullptr) {} + ~Api() override; + explicit constexpr Api(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); Api(const Api& from); - - inline Api& operator=(const Api& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Api(Api&& from) noexcept : Api() { *this = ::std::move(from); } + inline Api& operator=(const Api& from) { + CopyFrom(from); + return *this; + } inline Api& operator=(Api&& from) noexcept { - if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { - if (this != &from) InternalSwap(&from); + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); } else { CopyFrom(from); } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); - static const Api& default_instance(); - static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Api& default_instance() { + return *internal_default_instance(); + } static inline const Api* internal_default_instance() { return reinterpret_cast( &_Api_default_instance_); @@ -109,34 +125,47 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in static constexpr int kIndexInFileMessages = 0; - void Swap(Api* other); friend void swap(Api& a, Api& b) { a.Swap(&b); } + inline void Swap(Api* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Api* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } // implements Message ---------------------------------------------- - inline Api* New() const final { - return CreateMaybeMessage(NULL); - } - - Api* New(::google::protobuf::Arena* arena) const final { + Api* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const Api& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const Api& from); - void Clear() final; + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: @@ -144,149 +173,209 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Api* other); + private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; - } - inline void* MaybeArenaPtr() const { - return NULL; + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Api"; } + protected: + explicit Api(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: - ::google::protobuf::Metadata GetMetadata() const final; + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- + enum : int { + kMethodsFieldNumber = 2, + kOptionsFieldNumber = 3, + kMixinsFieldNumber = 6, + kNameFieldNumber = 1, + kVersionFieldNumber = 4, + kSourceContextFieldNumber = 5, + kSyntaxFieldNumber = 7, + }; // repeated .google.protobuf.Method methods = 2; int methods_size() const; + private: + int _internal_methods_size() const; + public: void clear_methods(); - static const int kMethodsFieldNumber = 2; - ::google::protobuf::Method* mutable_methods(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >* + ::PROTOBUF_NAMESPACE_ID::Method* mutable_methods(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Method >* mutable_methods(); - const ::google::protobuf::Method& methods(int index) const; - ::google::protobuf::Method* add_methods(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >& + private: + const ::PROTOBUF_NAMESPACE_ID::Method& _internal_methods(int index) const; + ::PROTOBUF_NAMESPACE_ID::Method* _internal_add_methods(); + public: + const ::PROTOBUF_NAMESPACE_ID::Method& methods(int index) const; + ::PROTOBUF_NAMESPACE_ID::Method* add_methods(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Method >& methods() const; // repeated .google.protobuf.Option options = 3; int options_size() const; + private: + int _internal_options_size() const; + public: void clear_options(); - static const int kOptionsFieldNumber = 3; - ::google::protobuf::Option* mutable_options(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >* + ::PROTOBUF_NAMESPACE_ID::Option* mutable_options(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* mutable_options(); - const ::google::protobuf::Option& options(int index) const; - ::google::protobuf::Option* add_options(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >& + private: + const ::PROTOBUF_NAMESPACE_ID::Option& _internal_options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* _internal_add_options(); + public: + const ::PROTOBUF_NAMESPACE_ID::Option& options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* add_options(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& options() const; // repeated .google.protobuf.Mixin mixins = 6; int mixins_size() const; + private: + int _internal_mixins_size() const; + public: void clear_mixins(); - static const int kMixinsFieldNumber = 6; - ::google::protobuf::Mixin* mutable_mixins(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >* + ::PROTOBUF_NAMESPACE_ID::Mixin* mutable_mixins(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Mixin >* mutable_mixins(); - const ::google::protobuf::Mixin& mixins(int index) const; - ::google::protobuf::Mixin* add_mixins(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >& + private: + const ::PROTOBUF_NAMESPACE_ID::Mixin& _internal_mixins(int index) const; + ::PROTOBUF_NAMESPACE_ID::Mixin* _internal_add_mixins(); + public: + const ::PROTOBUF_NAMESPACE_ID::Mixin& mixins(int index) const; + ::PROTOBUF_NAMESPACE_ID::Mixin* add_mixins(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Mixin >& mixins() const; // string name = 1; void clear_name(); - static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif - void set_name(const char* value); - void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: // string version = 4; void clear_version(); - static const int kVersionFieldNumber = 4; - const ::std::string& version() const; - void set_version(const ::std::string& value); - #if LANG_CXX11 - void set_version(::std::string&& value); - #endif - void set_version(const char* value); - void set_version(const char* value, size_t size); - ::std::string* mutable_version(); - ::std::string* release_version(); - void set_allocated_version(::std::string* version); + const std::string& version() const; + template + void set_version(ArgT0&& arg0, ArgT... args); + std::string* mutable_version(); + PROTOBUF_NODISCARD std::string* release_version(); + void set_allocated_version(std::string* version); + private: + const std::string& _internal_version() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_version(const std::string& value); + std::string* _internal_mutable_version(); + public: // .google.protobuf.SourceContext source_context = 5; bool has_source_context() const; - void clear_source_context(); - static const int kSourceContextFieldNumber = 5; private: - const ::google::protobuf::SourceContext& _internal_source_context() const; + bool _internal_has_source_context() const; public: - const ::google::protobuf::SourceContext& source_context() const; - ::google::protobuf::SourceContext* release_source_context(); - ::google::protobuf::SourceContext* mutable_source_context(); - void set_allocated_source_context(::google::protobuf::SourceContext* source_context); + void clear_source_context(); + const ::PROTOBUF_NAMESPACE_ID::SourceContext& source_context() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::SourceContext* release_source_context(); + ::PROTOBUF_NAMESPACE_ID::SourceContext* mutable_source_context(); + void set_allocated_source_context(::PROTOBUF_NAMESPACE_ID::SourceContext* source_context); + private: + const ::PROTOBUF_NAMESPACE_ID::SourceContext& _internal_source_context() const; + ::PROTOBUF_NAMESPACE_ID::SourceContext* _internal_mutable_source_context(); + public: + void unsafe_arena_set_allocated_source_context( + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context); + ::PROTOBUF_NAMESPACE_ID::SourceContext* unsafe_arena_release_source_context(); // .google.protobuf.Syntax syntax = 7; void clear_syntax(); - static const int kSyntaxFieldNumber = 7; - ::google::protobuf::Syntax syntax() const; - void set_syntax(::google::protobuf::Syntax value); + ::PROTOBUF_NAMESPACE_ID::Syntax syntax() const; + void set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value); + private: + ::PROTOBUF_NAMESPACE_ID::Syntax _internal_syntax() const; + void _internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value); + public: // @@protoc_insertion_point(class_scope:google.protobuf.Api) private: + class _Internal; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method > methods_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin > mixins_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr version_; - ::google::protobuf::SourceContext* source_context_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Method > methods_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Mixin > mixins_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr version_; + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; int syntax_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ { +class PROTOBUF_EXPORT Method final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Method) */ { public: - Method(); - virtual ~Method(); + inline Method() : Method(nullptr) {} + ~Method() override; + explicit constexpr Method(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); Method(const Method& from); - - inline Method& operator=(const Method& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Method(Method&& from) noexcept : Method() { *this = ::std::move(from); } + inline Method& operator=(const Method& from) { + CopyFrom(from); + return *this; + } inline Method& operator=(Method&& from) noexcept { - if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { - if (this != &from) InternalSwap(&from); + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); } else { CopyFrom(from); } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); - static const Method& default_instance(); - static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Method& default_instance() { + return *internal_default_instance(); + } static inline const Method* internal_default_instance() { return reinterpret_cast( &_Method_default_instance_); @@ -294,34 +383,47 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc static constexpr int kIndexInFileMessages = 1; - void Swap(Method* other); friend void swap(Method& a, Method& b) { a.Swap(&b); } + inline void Swap(Method* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Method* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } // implements Message ---------------------------------------------- - inline Method* New() const final { - return CreateMaybeMessage(NULL); - } - - Method* New(::google::protobuf::Arena* arena) const final { + Method* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const Method& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const Method& from); - void Clear() final; + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: @@ -329,139 +431,187 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Method* other); + private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; - } - inline void* MaybeArenaPtr() const { - return NULL; + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Method"; } + protected: + explicit Method(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: - ::google::protobuf::Metadata GetMetadata() const final; + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- + enum : int { + kOptionsFieldNumber = 6, + kNameFieldNumber = 1, + kRequestTypeUrlFieldNumber = 2, + kResponseTypeUrlFieldNumber = 4, + kRequestStreamingFieldNumber = 3, + kResponseStreamingFieldNumber = 5, + kSyntaxFieldNumber = 7, + }; // repeated .google.protobuf.Option options = 6; int options_size() const; + private: + int _internal_options_size() const; + public: void clear_options(); - static const int kOptionsFieldNumber = 6; - ::google::protobuf::Option* mutable_options(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >* + ::PROTOBUF_NAMESPACE_ID::Option* mutable_options(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* mutable_options(); - const ::google::protobuf::Option& options(int index) const; - ::google::protobuf::Option* add_options(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >& + private: + const ::PROTOBUF_NAMESPACE_ID::Option& _internal_options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* _internal_add_options(); + public: + const ::PROTOBUF_NAMESPACE_ID::Option& options(int index) const; + ::PROTOBUF_NAMESPACE_ID::Option* add_options(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& options() const; // string name = 1; void clear_name(); - static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif - void set_name(const char* value); - void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: // string request_type_url = 2; void clear_request_type_url(); - static const int kRequestTypeUrlFieldNumber = 2; - const ::std::string& request_type_url() const; - void set_request_type_url(const ::std::string& value); - #if LANG_CXX11 - void set_request_type_url(::std::string&& value); - #endif - void set_request_type_url(const char* value); - void set_request_type_url(const char* value, size_t size); - ::std::string* mutable_request_type_url(); - ::std::string* release_request_type_url(); - void set_allocated_request_type_url(::std::string* request_type_url); + const std::string& request_type_url() const; + template + void set_request_type_url(ArgT0&& arg0, ArgT... args); + std::string* mutable_request_type_url(); + PROTOBUF_NODISCARD std::string* release_request_type_url(); + void set_allocated_request_type_url(std::string* request_type_url); + private: + const std::string& _internal_request_type_url() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_request_type_url(const std::string& value); + std::string* _internal_mutable_request_type_url(); + public: // string response_type_url = 4; void clear_response_type_url(); - static const int kResponseTypeUrlFieldNumber = 4; - const ::std::string& response_type_url() const; - void set_response_type_url(const ::std::string& value); - #if LANG_CXX11 - void set_response_type_url(::std::string&& value); - #endif - void set_response_type_url(const char* value); - void set_response_type_url(const char* value, size_t size); - ::std::string* mutable_response_type_url(); - ::std::string* release_response_type_url(); - void set_allocated_response_type_url(::std::string* response_type_url); + const std::string& response_type_url() const; + template + void set_response_type_url(ArgT0&& arg0, ArgT... args); + std::string* mutable_response_type_url(); + PROTOBUF_NODISCARD std::string* release_response_type_url(); + void set_allocated_response_type_url(std::string* response_type_url); + private: + const std::string& _internal_response_type_url() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_response_type_url(const std::string& value); + std::string* _internal_mutable_response_type_url(); + public: // bool request_streaming = 3; void clear_request_streaming(); - static const int kRequestStreamingFieldNumber = 3; bool request_streaming() const; void set_request_streaming(bool value); + private: + bool _internal_request_streaming() const; + void _internal_set_request_streaming(bool value); + public: // bool response_streaming = 5; void clear_response_streaming(); - static const int kResponseStreamingFieldNumber = 5; bool response_streaming() const; void set_response_streaming(bool value); + private: + bool _internal_response_streaming() const; + void _internal_set_response_streaming(bool value); + public: // .google.protobuf.Syntax syntax = 7; void clear_syntax(); - static const int kSyntaxFieldNumber = 7; - ::google::protobuf::Syntax syntax() const; - void set_syntax(::google::protobuf::Syntax value); + ::PROTOBUF_NAMESPACE_ID::Syntax syntax() const; + void set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value); + private: + ::PROTOBUF_NAMESPACE_ID::Syntax _internal_syntax() const; + void _internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value); + public: // @@protoc_insertion_point(class_scope:google.protobuf.Method) private: + class _Internal; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option > options_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr request_type_url_; - ::google::protobuf::internal::ArenaStringPtr response_type_url_; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr request_type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr response_type_url_; bool request_streaming_; bool response_streaming_; int syntax_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ { +class PROTOBUF_EXPORT Mixin final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Mixin) */ { public: - Mixin(); - virtual ~Mixin(); + inline Mixin() : Mixin(nullptr) {} + ~Mixin() override; + explicit constexpr Mixin(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); Mixin(const Mixin& from); - - inline Mixin& operator=(const Mixin& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Mixin(Mixin&& from) noexcept : Mixin() { *this = ::std::move(from); } + inline Mixin& operator=(const Mixin& from) { + CopyFrom(from); + return *this; + } inline Mixin& operator=(Mixin&& from) noexcept { - if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { - if (this != &from) InternalSwap(&from); + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); } else { CopyFrom(from); } return *this; } - #endif - static const ::google::protobuf::Descriptor* descriptor(); - static const Mixin& default_instance(); - static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Mixin& default_instance() { + return *internal_default_instance(); + } static inline const Mixin* internal_default_instance() { return reinterpret_cast( &_Mixin_default_instance_); @@ -469,34 +619,47 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ static constexpr int kIndexInFileMessages = 2; - void Swap(Mixin* other); friend void swap(Mixin& a, Mixin& b) { a.Swap(&b); } + inline void Swap(Mixin* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Mixin* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } // implements Message ---------------------------------------------- - inline Mixin* New() const final { - return CreateMaybeMessage(NULL); - } - - Mixin* New(::google::protobuf::Arena* arena) const final { + Mixin* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const Mixin& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const Mixin& from); - void Clear() final; + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: @@ -504,57 +667,72 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Mixin* other); + private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; - } - inline void* MaybeArenaPtr() const { - return NULL; + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.Mixin"; } + protected: + explicit Mixin(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: - ::google::protobuf::Metadata GetMetadata() const final; + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- + enum : int { + kNameFieldNumber = 1, + kRootFieldNumber = 2, + }; // string name = 1; void clear_name(); - static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif - void set_name(const char* value); - void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: // string root = 2; void clear_root(); - static const int kRootFieldNumber = 2; - const ::std::string& root() const; - void set_root(const ::std::string& value); - #if LANG_CXX11 - void set_root(::std::string&& value); - #endif - void set_root(const char* value); - void set_root(const char* value, size_t size); - ::std::string* mutable_root(); - ::std::string* release_root(); - void set_allocated_root(::std::string* root); + const std::string& root() const; + template + void set_root(ArgT0&& arg0, ArgT... args); + std::string* mutable_root(); + PROTOBUF_NODISCARD std::string* release_root(); + void set_allocated_root(std::string* root); + private: + const std::string& _internal_root() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_root(const std::string& value); + std::string* _internal_mutable_root(); + public: // @@protoc_insertion_point(class_scope:google.protobuf.Mixin) private: + class _Internal; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr root_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr root_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // =================================================================== @@ -569,109 +747,127 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_ // string name = 1; inline void Api::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.ClearToEmpty(); } -inline const ::std::string& Api::name() const { +inline const std::string& Api::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.name) - return name_.GetNoArena(); + return _internal_name(); } -inline void Api::set_name(const ::std::string& value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Api::set_name(ArgT0&& arg0, ArgT... args) { + + name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Api.name) } -#if LANG_CXX11 -inline void Api::set_name(::std::string&& value) { - - name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Api.name) -} -#endif -inline void Api::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Api.name) -} -inline void Api::set_name(const char* value, size_t size) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.name) -} -inline ::std::string* Api::mutable_name() { - +inline std::string* Api::mutable_name() { + std::string* _s = _internal_mutable_name(); // @@protoc_insertion_point(field_mutable:google.protobuf.Api.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Api::release_name() { - // @@protoc_insertion_point(field_release:google.protobuf.Api.name) +inline const std::string& Api::_internal_name() const { + return name_.Get(); +} +inline void Api::_internal_set_name(const std::string& value) { - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Api::set_allocated_name(::std::string* name) { - if (name != NULL) { +inline std::string* Api::_internal_mutable_name() { + + return name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Api::release_name() { + // @@protoc_insertion_point(field_release:google.protobuf.Api.name) + return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Api::set_allocated_name(std::string* name) { + if (name != nullptr) { } else { } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (name_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.name) } // repeated .google.protobuf.Method methods = 2; -inline int Api::methods_size() const { +inline int Api::_internal_methods_size() const { return methods_.size(); } +inline int Api::methods_size() const { + return _internal_methods_size(); +} inline void Api::clear_methods() { methods_.Clear(); } -inline ::google::protobuf::Method* Api::mutable_methods(int index) { +inline ::PROTOBUF_NAMESPACE_ID::Method* Api::mutable_methods(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.methods) return methods_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Method >* Api::mutable_methods() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.methods) return &methods_; } -inline const ::google::protobuf::Method& Api::methods(int index) const { - // @@protoc_insertion_point(field_get:google.protobuf.Api.methods) +inline const ::PROTOBUF_NAMESPACE_ID::Method& Api::_internal_methods(int index) const { return methods_.Get(index); } -inline ::google::protobuf::Method* Api::add_methods() { - // @@protoc_insertion_point(field_add:google.protobuf.Api.methods) +inline const ::PROTOBUF_NAMESPACE_ID::Method& Api::methods(int index) const { + // @@protoc_insertion_point(field_get:google.protobuf.Api.methods) + return _internal_methods(index); +} +inline ::PROTOBUF_NAMESPACE_ID::Method* Api::_internal_add_methods() { return methods_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >& +inline ::PROTOBUF_NAMESPACE_ID::Method* Api::add_methods() { + ::PROTOBUF_NAMESPACE_ID::Method* _add = _internal_add_methods(); + // @@protoc_insertion_point(field_add:google.protobuf.Api.methods) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Method >& Api::methods() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.methods) return methods_; } // repeated .google.protobuf.Option options = 3; -inline int Api::options_size() const { +inline int Api::_internal_options_size() const { return options_.size(); } -inline ::google::protobuf::Option* Api::mutable_options(int index) { +inline int Api::options_size() const { + return _internal_options_size(); +} +inline ::PROTOBUF_NAMESPACE_ID::Option* Api::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.options) return options_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* Api::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.options) return &options_; } -inline const ::google::protobuf::Option& Api::options(int index) const { - // @@protoc_insertion_point(field_get:google.protobuf.Api.options) +inline const ::PROTOBUF_NAMESPACE_ID::Option& Api::_internal_options(int index) const { return options_.Get(index); } -inline ::google::protobuf::Option* Api::add_options() { - // @@protoc_insertion_point(field_add:google.protobuf.Api.options) +inline const ::PROTOBUF_NAMESPACE_ID::Option& Api::options(int index) const { + // @@protoc_insertion_point(field_get:google.protobuf.Api.options) + return _internal_options(index); +} +inline ::PROTOBUF_NAMESPACE_ID::Option* Api::_internal_add_options() { return options_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >& +inline ::PROTOBUF_NAMESPACE_ID::Option* Api::add_options() { + ::PROTOBUF_NAMESPACE_ID::Option* _add = _internal_add_options(); + // @@protoc_insertion_point(field_add:google.protobuf.Api.options) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& Api::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.options) return options_; @@ -679,95 +875,131 @@ Api::options() const { // string version = 4; inline void Api::clear_version() { - version_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + version_.ClearToEmpty(); } -inline const ::std::string& Api::version() const { +inline const std::string& Api::version() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.version) - return version_.GetNoArena(); + return _internal_version(); } -inline void Api::set_version(const ::std::string& value) { - - version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Api::set_version(ArgT0&& arg0, ArgT... args) { + + version_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Api.version) } -#if LANG_CXX11 -inline void Api::set_version(::std::string&& value) { - - version_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Api.version) -} -#endif -inline void Api::set_version(const char* value) { - GOOGLE_DCHECK(value != NULL); - - version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Api.version) -} -inline void Api::set_version(const char* value, size_t size) { - - version_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Api.version) -} -inline ::std::string* Api::mutable_version() { - +inline std::string* Api::mutable_version() { + std::string* _s = _internal_mutable_version(); // @@protoc_insertion_point(field_mutable:google.protobuf.Api.version) - return version_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Api::release_version() { - // @@protoc_insertion_point(field_release:google.protobuf.Api.version) +inline const std::string& Api::_internal_version() const { + return version_.Get(); +} +inline void Api::_internal_set_version(const std::string& value) { - return version_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + version_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Api::set_allocated_version(::std::string* version) { - if (version != NULL) { +inline std::string* Api::_internal_mutable_version() { + + return version_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Api::release_version() { + // @@protoc_insertion_point(field_release:google.protobuf.Api.version) + return version_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Api::set_allocated_version(std::string* version) { + if (version != nullptr) { } else { } - version_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), version); + version_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), version, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (version_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + version_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.version) } // .google.protobuf.SourceContext source_context = 5; +inline bool Api::_internal_has_source_context() const { + return this != internal_default_instance() && source_context_ != nullptr; +} inline bool Api::has_source_context() const { - return this != internal_default_instance() && source_context_ != NULL; + return _internal_has_source_context(); } -inline const ::google::protobuf::SourceContext& Api::_internal_source_context() const { - return *source_context_; +inline const ::PROTOBUF_NAMESPACE_ID::SourceContext& Api::_internal_source_context() const { + const ::PROTOBUF_NAMESPACE_ID::SourceContext* p = source_context_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_); } -inline const ::google::protobuf::SourceContext& Api::source_context() const { - const ::google::protobuf::SourceContext* p = source_context_; +inline const ::PROTOBUF_NAMESPACE_ID::SourceContext& Api::source_context() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.source_context) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::_SourceContext_default_instance_); + return _internal_source_context(); } -inline ::google::protobuf::SourceContext* Api::release_source_context() { - // @@protoc_insertion_point(field_release:google.protobuf.Api.source_context) +inline void Api::unsafe_arena_set_allocated_source_context( + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); + } + source_context_ = source_context; + if (source_context) { + + } else { + + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Api.source_context) +} +inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Api::release_source_context() { - ::google::protobuf::SourceContext* temp = source_context_; - source_context_ = NULL; + ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_; + source_context_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE return temp; } -inline ::google::protobuf::SourceContext* Api::mutable_source_context() { +inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Api::unsafe_arena_release_source_context() { + // @@protoc_insertion_point(field_release:google.protobuf.Api.source_context) - if (source_context_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual()); + ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_; + source_context_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Api::_internal_mutable_source_context() { + + if (source_context_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::SourceContext>(GetArenaForAllocation()); source_context_ = p; } - // @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context) return source_context_; } -inline void Api::set_allocated_source_context(::google::protobuf::SourceContext* source_context) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { - delete reinterpret_cast< ::google::protobuf::MessageLite*>(source_context_); +inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Api::mutable_source_context() { + ::PROTOBUF_NAMESPACE_ID::SourceContext* _msg = _internal_mutable_source_context(); + // @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context) + return _msg; +} +inline void Api::set_allocated_source_context(::PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); } if (source_context) { - ::google::protobuf::Arena* submessage_arena = NULL; + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper< + ::PROTOBUF_NAMESPACE_ID::MessageLite>::GetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context)); if (message_arena != submessage_arena) { - source_context = ::google::protobuf::internal::GetOwnedMessage( + source_context = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, source_context, submessage_arena); } @@ -779,30 +1011,40 @@ inline void Api::set_allocated_source_context(::google::protobuf::SourceContext* } // repeated .google.protobuf.Mixin mixins = 6; -inline int Api::mixins_size() const { +inline int Api::_internal_mixins_size() const { return mixins_.size(); } +inline int Api::mixins_size() const { + return _internal_mixins_size(); +} inline void Api::clear_mixins() { mixins_.Clear(); } -inline ::google::protobuf::Mixin* Api::mutable_mixins(int index) { +inline ::PROTOBUF_NAMESPACE_ID::Mixin* Api::mutable_mixins(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.mixins) return mixins_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Mixin >* Api::mutable_mixins() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.mixins) return &mixins_; } -inline const ::google::protobuf::Mixin& Api::mixins(int index) const { - // @@protoc_insertion_point(field_get:google.protobuf.Api.mixins) +inline const ::PROTOBUF_NAMESPACE_ID::Mixin& Api::_internal_mixins(int index) const { return mixins_.Get(index); } -inline ::google::protobuf::Mixin* Api::add_mixins() { - // @@protoc_insertion_point(field_add:google.protobuf.Api.mixins) +inline const ::PROTOBUF_NAMESPACE_ID::Mixin& Api::mixins(int index) const { + // @@protoc_insertion_point(field_get:google.protobuf.Api.mixins) + return _internal_mixins(index); +} +inline ::PROTOBUF_NAMESPACE_ID::Mixin* Api::_internal_add_mixins() { return mixins_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >& +inline ::PROTOBUF_NAMESPACE_ID::Mixin* Api::add_mixins() { + ::PROTOBUF_NAMESPACE_ID::Mixin* _add = _internal_add_mixins(); + // @@protoc_insertion_point(field_add:google.protobuf.Api.mixins) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Mixin >& Api::mixins() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.mixins) return mixins_; @@ -812,13 +1054,19 @@ Api::mixins() const { inline void Api::clear_syntax() { syntax_ = 0; } -inline ::google::protobuf::Syntax Api::syntax() const { - // @@protoc_insertion_point(field_get:google.protobuf.Api.syntax) - return static_cast< ::google::protobuf::Syntax >(syntax_); +inline ::PROTOBUF_NAMESPACE_ID::Syntax Api::_internal_syntax() const { + return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(syntax_); } -inline void Api::set_syntax(::google::protobuf::Syntax value) { +inline ::PROTOBUF_NAMESPACE_ID::Syntax Api::syntax() const { + // @@protoc_insertion_point(field_get:google.protobuf.Api.syntax) + return _internal_syntax(); +} +inline void Api::_internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { syntax_ = value; +} +inline void Api::set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { + _internal_set_syntax(value); // @@protoc_insertion_point(field_set:google.protobuf.Api.syntax) } @@ -828,107 +1076,103 @@ inline void Api::set_syntax(::google::protobuf::Syntax value) { // string name = 1; inline void Method::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.ClearToEmpty(); } -inline const ::std::string& Method::name() const { +inline const std::string& Method::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.name) - return name_.GetNoArena(); + return _internal_name(); } -inline void Method::set_name(const ::std::string& value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Method::set_name(ArgT0&& arg0, ArgT... args) { + + name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Method.name) } -#if LANG_CXX11 -inline void Method::set_name(::std::string&& value) { - - name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.name) -} -#endif -inline void Method::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Method.name) -} -inline void Method::set_name(const char* value, size_t size) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.name) -} -inline ::std::string* Method::mutable_name() { - +inline std::string* Method::mutable_name() { + std::string* _s = _internal_mutable_name(); // @@protoc_insertion_point(field_mutable:google.protobuf.Method.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Method::release_name() { - // @@protoc_insertion_point(field_release:google.protobuf.Method.name) +inline const std::string& Method::_internal_name() const { + return name_.Get(); +} +inline void Method::_internal_set_name(const std::string& value) { - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Method::set_allocated_name(::std::string* name) { - if (name != NULL) { +inline std::string* Method::_internal_mutable_name() { + + return name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Method::release_name() { + // @@protoc_insertion_point(field_release:google.protobuf.Method.name) + return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Method::set_allocated_name(std::string* name) { + if (name != nullptr) { } else { } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (name_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.name) } // string request_type_url = 2; inline void Method::clear_request_type_url() { - request_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + request_type_url_.ClearToEmpty(); } -inline const ::std::string& Method::request_type_url() const { +inline const std::string& Method::request_type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.request_type_url) - return request_type_url_.GetNoArena(); + return _internal_request_type_url(); } -inline void Method::set_request_type_url(const ::std::string& value) { - - request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Method::set_request_type_url(ArgT0&& arg0, ArgT... args) { + + request_type_url_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Method.request_type_url) } -#if LANG_CXX11 -inline void Method::set_request_type_url(::std::string&& value) { - - request_type_url_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.request_type_url) -} -#endif -inline void Method::set_request_type_url(const char* value) { - GOOGLE_DCHECK(value != NULL); - - request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Method.request_type_url) -} -inline void Method::set_request_type_url(const char* value, size_t size) { - - request_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.request_type_url) -} -inline ::std::string* Method::mutable_request_type_url() { - +inline std::string* Method::mutable_request_type_url() { + std::string* _s = _internal_mutable_request_type_url(); // @@protoc_insertion_point(field_mutable:google.protobuf.Method.request_type_url) - return request_type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Method::release_request_type_url() { - // @@protoc_insertion_point(field_release:google.protobuf.Method.request_type_url) +inline const std::string& Method::_internal_request_type_url() const { + return request_type_url_.Get(); +} +inline void Method::_internal_set_request_type_url(const std::string& value) { - return request_type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + request_type_url_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Method::set_allocated_request_type_url(::std::string* request_type_url) { - if (request_type_url != NULL) { +inline std::string* Method::_internal_mutable_request_type_url() { + + return request_type_url_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Method::release_request_type_url() { + // @@protoc_insertion_point(field_release:google.protobuf.Method.request_type_url) + return request_type_url_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Method::set_allocated_request_type_url(std::string* request_type_url) { + if (request_type_url != nullptr) { } else { } - request_type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), request_type_url); + request_type_url_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), request_type_url, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (request_type_url_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + request_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.request_type_url) } @@ -936,66 +1180,70 @@ inline void Method::set_allocated_request_type_url(::std::string* request_type_u inline void Method::clear_request_streaming() { request_streaming_ = false; } -inline bool Method::request_streaming() const { - // @@protoc_insertion_point(field_get:google.protobuf.Method.request_streaming) +inline bool Method::_internal_request_streaming() const { return request_streaming_; } -inline void Method::set_request_streaming(bool value) { +inline bool Method::request_streaming() const { + // @@protoc_insertion_point(field_get:google.protobuf.Method.request_streaming) + return _internal_request_streaming(); +} +inline void Method::_internal_set_request_streaming(bool value) { request_streaming_ = value; +} +inline void Method::set_request_streaming(bool value) { + _internal_set_request_streaming(value); // @@protoc_insertion_point(field_set:google.protobuf.Method.request_streaming) } // string response_type_url = 4; inline void Method::clear_response_type_url() { - response_type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + response_type_url_.ClearToEmpty(); } -inline const ::std::string& Method::response_type_url() const { +inline const std::string& Method::response_type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.response_type_url) - return response_type_url_.GetNoArena(); + return _internal_response_type_url(); } -inline void Method::set_response_type_url(const ::std::string& value) { - - response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Method::set_response_type_url(ArgT0&& arg0, ArgT... args) { + + response_type_url_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Method.response_type_url) } -#if LANG_CXX11 -inline void Method::set_response_type_url(::std::string&& value) { - - response_type_url_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Method.response_type_url) -} -#endif -inline void Method::set_response_type_url(const char* value) { - GOOGLE_DCHECK(value != NULL); - - response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Method.response_type_url) -} -inline void Method::set_response_type_url(const char* value, size_t size) { - - response_type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Method.response_type_url) -} -inline ::std::string* Method::mutable_response_type_url() { - +inline std::string* Method::mutable_response_type_url() { + std::string* _s = _internal_mutable_response_type_url(); // @@protoc_insertion_point(field_mutable:google.protobuf.Method.response_type_url) - return response_type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Method::release_response_type_url() { - // @@protoc_insertion_point(field_release:google.protobuf.Method.response_type_url) +inline const std::string& Method::_internal_response_type_url() const { + return response_type_url_.Get(); +} +inline void Method::_internal_set_response_type_url(const std::string& value) { - return response_type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + response_type_url_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Method::set_allocated_response_type_url(::std::string* response_type_url) { - if (response_type_url != NULL) { +inline std::string* Method::_internal_mutable_response_type_url() { + + return response_type_url_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Method::release_response_type_url() { + // @@protoc_insertion_point(field_release:google.protobuf.Method.response_type_url) + return response_type_url_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Method::set_allocated_response_type_url(std::string* response_type_url) { + if (response_type_url != nullptr) { } else { } - response_type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), response_type_url); + response_type_url_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), response_type_url, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (response_type_url_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + response_type_url_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.response_type_url) } @@ -1003,38 +1251,54 @@ inline void Method::set_allocated_response_type_url(::std::string* response_type inline void Method::clear_response_streaming() { response_streaming_ = false; } -inline bool Method::response_streaming() const { - // @@protoc_insertion_point(field_get:google.protobuf.Method.response_streaming) +inline bool Method::_internal_response_streaming() const { return response_streaming_; } -inline void Method::set_response_streaming(bool value) { +inline bool Method::response_streaming() const { + // @@protoc_insertion_point(field_get:google.protobuf.Method.response_streaming) + return _internal_response_streaming(); +} +inline void Method::_internal_set_response_streaming(bool value) { response_streaming_ = value; +} +inline void Method::set_response_streaming(bool value) { + _internal_set_response_streaming(value); // @@protoc_insertion_point(field_set:google.protobuf.Method.response_streaming) } // repeated .google.protobuf.Option options = 6; -inline int Method::options_size() const { +inline int Method::_internal_options_size() const { return options_.size(); } -inline ::google::protobuf::Option* Method::mutable_options(int index) { +inline int Method::options_size() const { + return _internal_options_size(); +} +inline ::PROTOBUF_NAMESPACE_ID::Option* Method::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Method.options) return options_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* Method::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Method.options) return &options_; } -inline const ::google::protobuf::Option& Method::options(int index) const { - // @@protoc_insertion_point(field_get:google.protobuf.Method.options) +inline const ::PROTOBUF_NAMESPACE_ID::Option& Method::_internal_options(int index) const { return options_.Get(index); } -inline ::google::protobuf::Option* Method::add_options() { - // @@protoc_insertion_point(field_add:google.protobuf.Method.options) +inline const ::PROTOBUF_NAMESPACE_ID::Option& Method::options(int index) const { + // @@protoc_insertion_point(field_get:google.protobuf.Method.options) + return _internal_options(index); +} +inline ::PROTOBUF_NAMESPACE_ID::Option* Method::_internal_add_options() { return options_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >& +inline ::PROTOBUF_NAMESPACE_ID::Option* Method::add_options() { + ::PROTOBUF_NAMESPACE_ID::Option* _add = _internal_add_options(); + // @@protoc_insertion_point(field_add:google.protobuf.Method.options) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& Method::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Method.options) return options_; @@ -1044,13 +1308,19 @@ Method::options() const { inline void Method::clear_syntax() { syntax_ = 0; } -inline ::google::protobuf::Syntax Method::syntax() const { - // @@protoc_insertion_point(field_get:google.protobuf.Method.syntax) - return static_cast< ::google::protobuf::Syntax >(syntax_); +inline ::PROTOBUF_NAMESPACE_ID::Syntax Method::_internal_syntax() const { + return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(syntax_); } -inline void Method::set_syntax(::google::protobuf::Syntax value) { +inline ::PROTOBUF_NAMESPACE_ID::Syntax Method::syntax() const { + // @@protoc_insertion_point(field_get:google.protobuf.Method.syntax) + return _internal_syntax(); +} +inline void Method::_internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { syntax_ = value; +} +inline void Method::set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { + _internal_set_syntax(value); // @@protoc_insertion_point(field_set:google.protobuf.Method.syntax) } @@ -1060,107 +1330,103 @@ inline void Method::set_syntax(::google::protobuf::Syntax value) { // string name = 1; inline void Mixin::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.ClearToEmpty(); } -inline const ::std::string& Mixin::name() const { +inline const std::string& Mixin::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Mixin.name) - return name_.GetNoArena(); + return _internal_name(); } -inline void Mixin::set_name(const ::std::string& value) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Mixin::set_name(ArgT0&& arg0, ArgT... args) { + + name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Mixin.name) } -#if LANG_CXX11 -inline void Mixin::set_name(::std::string&& value) { - - name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Mixin.name) -} -#endif -inline void Mixin::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.name) -} -inline void Mixin::set_name(const char* value, size_t size) { - - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.name) -} -inline ::std::string* Mixin::mutable_name() { - +inline std::string* Mixin::mutable_name() { + std::string* _s = _internal_mutable_name(); // @@protoc_insertion_point(field_mutable:google.protobuf.Mixin.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Mixin::release_name() { - // @@protoc_insertion_point(field_release:google.protobuf.Mixin.name) +inline const std::string& Mixin::_internal_name() const { + return name_.Get(); +} +inline void Mixin::_internal_set_name(const std::string& value) { - return name_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Mixin::set_allocated_name(::std::string* name) { - if (name != NULL) { +inline std::string* Mixin::_internal_mutable_name() { + + return name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Mixin::release_name() { + // @@protoc_insertion_point(field_release:google.protobuf.Mixin.name) + return name_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Mixin::set_allocated_name(std::string* name) { + if (name != nullptr) { } else { } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (name_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.name) } // string root = 2; inline void Mixin::clear_root() { - root_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + root_.ClearToEmpty(); } -inline const ::std::string& Mixin::root() const { +inline const std::string& Mixin::root() const { // @@protoc_insertion_point(field_get:google.protobuf.Mixin.root) - return root_.GetNoArena(); + return _internal_root(); } -inline void Mixin::set_root(const ::std::string& value) { - - root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Mixin::set_root(ArgT0&& arg0, ArgT... args) { + + root_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Mixin.root) } -#if LANG_CXX11 -inline void Mixin::set_root(::std::string&& value) { - - root_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.Mixin.root) -} -#endif -inline void Mixin::set_root(const char* value) { - GOOGLE_DCHECK(value != NULL); - - root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.Mixin.root) -} -inline void Mixin::set_root(const char* value, size_t size) { - - root_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.Mixin.root) -} -inline ::std::string* Mixin::mutable_root() { - +inline std::string* Mixin::mutable_root() { + std::string* _s = _internal_mutable_root(); // @@protoc_insertion_point(field_mutable:google.protobuf.Mixin.root) - return root_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Mixin::release_root() { - // @@protoc_insertion_point(field_release:google.protobuf.Mixin.root) +inline const std::string& Mixin::_internal_root() const { + return root_.Get(); +} +inline void Mixin::_internal_set_root(const std::string& value) { - return root_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + root_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); } -inline void Mixin::set_allocated_root(::std::string* root) { - if (root != NULL) { +inline std::string* Mixin::_internal_mutable_root() { + + return root_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Mixin::release_root() { + // @@protoc_insertion_point(field_release:google.protobuf.Mixin.root) + return root_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +} +inline void Mixin::set_allocated_root(std::string* root) { + if (root != nullptr) { } else { } - root_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), root); + root_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), root, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (root_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + root_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root) } @@ -1174,9 +1440,9 @@ inline void Mixin::set_allocated_root(::std::string* root) { // @@protoc_insertion_point(namespace_scope) -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto diff --git a/windows/include/google/protobuf/api.proto b/windows/include/google/protobuf/api.proto index f37ee2fa4..3d598fc85 100644 --- a/windows/include/google/protobuf/api.proto +++ b/windows/include/google/protobuf/api.proto @@ -40,7 +40,7 @@ option java_package = "com.google.protobuf"; option java_outer_classname = "ApiProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; -option go_package = "google.golang.org/genproto/protobuf/api;api"; +option go_package = "google.golang.org/protobuf/types/known/apipb"; // Api is a light-weight descriptor for an API Interface. // @@ -52,7 +52,6 @@ option go_package = "google.golang.org/genproto/protobuf/api;api"; // this message itself. See https://cloud.google.com/apis/design/glossary for // detailed terminology. message Api { - // The fully qualified name of this interface, including package name // followed by the interface's simple name. string name = 1; @@ -99,7 +98,6 @@ message Api { // Method represents a method of an API interface. message Method { - // The simple name of this method. string name = 1; @@ -169,7 +167,7 @@ message Method { // The mixin construct implies that all methods in `AccessControl` are // also declared with same name and request/response types in // `Storage`. A documentation generator or annotation processor will -// see the effective `Storage.GetAcl` method after inherting +// see the effective `Storage.GetAcl` method after inheriting // documentation and annotations as follows: // // service Storage { diff --git a/windows/include/google/protobuf/arena.cc b/windows/include/google/protobuf/arena.cc deleted file mode 100644 index c117c9e52..000000000 --- a/windows/include/google/protobuf/arena.cc +++ /dev/null @@ -1,415 +0,0 @@ -// 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. - -#include - -#include -#include - - -#ifdef ADDRESS_SANITIZER -#include -#endif // ADDRESS_SANITIZER - -#include - -namespace google { -static const size_t kMinCleanupListElements = 8; -static const size_t kMaxCleanupListElements = 64; // 1kB on 64-bit. - -namespace protobuf { -namespace internal { - - -std::atomic ArenaImpl::lifecycle_id_generator_; -#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) -ArenaImpl::ThreadCache& ArenaImpl::thread_cache() { - static internal::ThreadLocalStorage* thread_cache_ = - new internal::ThreadLocalStorage(); - return *thread_cache_->Get(); -} -#elif defined(PROTOBUF_USE_DLLS) -ArenaImpl::ThreadCache& ArenaImpl::thread_cache() { - static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_ = { -1, NULL }; - return thread_cache_; -} -#else -GOOGLE_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1, NULL}; -#endif - -void ArenaImpl::Init() { - lifecycle_id_ = - lifecycle_id_generator_.fetch_add(1, std::memory_order_relaxed); - hint_.store(nullptr, std::memory_order_relaxed); - threads_.store(nullptr, std::memory_order_relaxed); - - if (initial_block_) { - // Thread which calls Init() owns the first block. This allows the - // single-threaded case to allocate on the first block without having to - // perform atomic operations. - new (initial_block_) Block(options_.initial_block_size, NULL); - SerialArena* serial = - SerialArena::New(initial_block_, &thread_cache(), this); - serial->set_next(NULL); - threads_.store(serial, std::memory_order_relaxed); - space_allocated_.store(options_.initial_block_size, - std::memory_order_relaxed); - CacheSerialArena(serial); - } else { - space_allocated_.store(0, std::memory_order_relaxed); - } -} - -ArenaImpl::~ArenaImpl() { - // Have to do this in a first pass, because some of the destructors might - // refer to memory in other blocks. - CleanupList(); - FreeBlocks(); -} - -uint64 ArenaImpl::Reset() { - // Have to do this in a first pass, because some of the destructors might - // refer to memory in other blocks. - CleanupList(); - uint64 space_allocated = FreeBlocks(); - Init(); - - return space_allocated; -} - -ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) { - size_t size; - if (last_block) { - // Double the current block size, up to a limit. - size = std::min(2 * last_block->size(), options_.max_block_size); - } else { - size = options_.start_block_size; - } - // Verify that min_bytes + kBlockHeaderSize won't overflow. - GOOGLE_CHECK_LE(min_bytes, std::numeric_limits::max() - kBlockHeaderSize); - size = std::max(size, kBlockHeaderSize + min_bytes); - - void* mem = options_.block_alloc(size); - Block* b = new (mem) Block(size, last_block); - space_allocated_.fetch_add(size, std::memory_order_relaxed); - return b; -} - -ArenaImpl::Block::Block(size_t size, Block* next) - : next_(next), pos_(kBlockHeaderSize), size_(size) {} - -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE -void ArenaImpl::SerialArena::AddCleanupFallback(void* elem, - void (*cleanup)(void*)) { - size_t size = cleanup_ ? cleanup_->size * 2 : kMinCleanupListElements; - size = std::min(size, kMaxCleanupListElements); - size_t bytes = internal::AlignUpTo8(CleanupChunk::SizeOf(size)); - CleanupChunk* list = reinterpret_cast(AllocateAligned(bytes)); - list->next = cleanup_; - list->size = size; - - cleanup_ = list; - cleanup_ptr_ = &list->nodes[0]; - cleanup_limit_ = &list->nodes[size]; - - AddCleanup(elem, cleanup); -} - -GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32) -void* ArenaImpl::AllocateAligned(size_t n) { - SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { - return arena->AllocateAligned(n); - } else { - return AllocateAlignedFallback(n); - } -} - -void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n, - void (*cleanup)(void*)) { - SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { - return arena->AllocateAlignedAndAddCleanup(n, cleanup); - } else { - return AllocateAlignedAndAddCleanupFallback(n, cleanup); - } -} - -void ArenaImpl::AddCleanup(void* elem, void (*cleanup)(void*)) { - SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { - arena->AddCleanup(elem, cleanup); - } else { - return AddCleanupFallback(elem, cleanup); - } -} - -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE -void* ArenaImpl::AllocateAlignedFallback(size_t n) { - return GetSerialArena()->AllocateAligned(n); -} - -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE -void* ArenaImpl::AllocateAlignedAndAddCleanupFallback(size_t n, - void (*cleanup)(void*)) { - return GetSerialArena()->AllocateAlignedAndAddCleanup(n, cleanup); -} - -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE -void ArenaImpl::AddCleanupFallback(void* elem, void (*cleanup)(void*)) { - GetSerialArena()->AddCleanup(elem, cleanup); -} - -inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE -bool ArenaImpl::GetSerialArenaFast(ArenaImpl::SerialArena** arena) { - // If this thread already owns a block in this arena then try to use that. - // This fast path optimizes the case where multiple threads allocate from the - // same arena. - ThreadCache* tc = &thread_cache(); - if (GOOGLE_PREDICT_TRUE(tc->last_lifecycle_id_seen == lifecycle_id_)) { - *arena = tc->last_serial_arena; - return true; - } - - // Check whether we own the last accessed SerialArena on this arena. This - // fast path optimizes the case where a single thread uses multiple arenas. - SerialArena* serial = hint_.load(std::memory_order_acquire); - if (GOOGLE_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) { - *arena = serial; - return true; - } - - return false; -} - -ArenaImpl::SerialArena* ArenaImpl::GetSerialArena() { - SerialArena* arena; - if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) { - return arena; - } else { - return GetSerialArenaFallback(&thread_cache()); - } -} - -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE -void* ArenaImpl::SerialArena::AllocateAlignedFallback(size_t n) { - // Sync back to current's pos. - head_->set_pos(head_->size() - (limit_ - ptr_)); - - head_ = arena_->NewBlock(head_, n); - ptr_ = head_->Pointer(head_->pos()); - limit_ = head_->Pointer(head_->size()); - -#ifdef ADDRESS_SANITIZER - ASAN_POISON_MEMORY_REGION(ptr_, limit_ - ptr_); -#endif // ADDRESS_SANITIZER - - return AllocateAligned(n); -} - -uint64 ArenaImpl::SpaceAllocated() const { - return space_allocated_.load(std::memory_order_relaxed); -} - -uint64 ArenaImpl::SpaceUsed() const { - SerialArena* serial = threads_.load(std::memory_order_acquire); - uint64 space_used = 0; - for ( ; serial; serial = serial->next()) { - space_used += serial->SpaceUsed(); - } - return space_used; -} - -uint64 ArenaImpl::SerialArena::SpaceUsed() const { - // Get current block's size from ptr_ (since we can't trust head_->pos(). - uint64 space_used = ptr_ - head_->Pointer(kBlockHeaderSize); - // Get subsequent block size from b->pos(). - for (Block* b = head_->next(); b; b = b->next()) { - space_used += (b->pos() - kBlockHeaderSize); - } - // Remove the overhead of the SerialArena itself. - space_used -= kSerialArenaSize; - return space_used; -} - -uint64 ArenaImpl::FreeBlocks() { - uint64 space_allocated = 0; - // By omitting an Acquire barrier we ensure that any user code that doesn't - // properly synchronize Reset() or the destructor will throw a TSAN warning. - SerialArena* serial = threads_.load(std::memory_order_relaxed); - - while (serial) { - // This is inside a block we are freeing, so we need to read it now. - SerialArena* next = serial->next(); - space_allocated += ArenaImpl::SerialArena::Free(serial, initial_block_, - options_.block_dealloc); - // serial is dead now. - serial = next; - } - - return space_allocated; -} - -uint64 ArenaImpl::SerialArena::Free(ArenaImpl::SerialArena* serial, - Block* initial_block, - void (*block_dealloc)(void*, size_t)) { - uint64 space_allocated = 0; - - // We have to be careful in this function, since we will be freeing the Block - // that contains this SerialArena. Be careful about accessing |serial|. - - for (Block* b = serial->head_; b; ) { - // This is inside the block we are freeing, so we need to read it now. - Block* next_block = b->next(); - space_allocated += (b->size()); - -#ifdef ADDRESS_SANITIZER - // This memory was provided by the underlying allocator as unpoisoned, so - // return it in an unpoisoned state. - ASAN_UNPOISON_MEMORY_REGION(b->Pointer(0), b->size()); -#endif // ADDRESS_SANITIZER - - if (b != initial_block) { - block_dealloc(b, b->size()); - } - - b = next_block; - } - - return space_allocated; -} - -void ArenaImpl::CleanupList() { - // By omitting an Acquire barrier we ensure that any user code that doesn't - // properly synchronize Reset() or the destructor will throw a TSAN warning. - SerialArena* serial = threads_.load(std::memory_order_relaxed); - - for ( ; serial; serial = serial->next()) { - serial->CleanupList(); - } -} - -void ArenaImpl::SerialArena::CleanupList() { - if (cleanup_ != NULL) { - CleanupListFallback(); - } -} - -void ArenaImpl::SerialArena::CleanupListFallback() { - // Cleanup newest chunk: ptrs give us length. - size_t n = cleanup_ptr_ - &cleanup_->nodes[0]; - CleanupNode* node = cleanup_ptr_; - for (size_t i = 0; i < n; i++) { - --node; - node->cleanup(node->elem); - } - - // Cleanup older chunks, which are known to be full. - CleanupChunk* list = cleanup_->next; - while (list) { - size_t n = list->size; - CleanupNode* node = &list->nodes[list->size]; - for (size_t i = 0; i < n; i++) { - --node; - node->cleanup(node->elem); - } - list = list->next; - } -} - -ArenaImpl::SerialArena* ArenaImpl::SerialArena::New(Block* b, void* owner, - ArenaImpl* arena) { - GOOGLE_DCHECK_EQ(b->pos(), kBlockHeaderSize); // Should be a fresh block - GOOGLE_DCHECK_LE(kBlockHeaderSize + kSerialArenaSize, b->size()); - SerialArena* serial = - reinterpret_cast(b->Pointer(kBlockHeaderSize)); - b->set_pos(kBlockHeaderSize + kSerialArenaSize); - serial->arena_ = arena; - serial->owner_ = owner; - serial->head_ = b; - serial->ptr_ = b->Pointer(b->pos()); - serial->limit_ = b->Pointer(b->size()); - serial->cleanup_ = NULL; - serial->cleanup_ptr_ = NULL; - serial->cleanup_limit_ = NULL; - return serial; -} - -GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE -ArenaImpl::SerialArena* ArenaImpl::GetSerialArenaFallback(void* me) { - // Look for this SerialArena in our linked list. - SerialArena* serial = threads_.load(std::memory_order_acquire); - for ( ; serial; serial = serial->next()) { - if (serial->owner() == me) { - break; - } - } - - if (!serial) { - // This thread doesn't have any SerialArena, which also means it doesn't - // have any blocks yet. So we'll allocate its first block now. - Block* b = NewBlock(NULL, kSerialArenaSize); - serial = SerialArena::New(b, me, this); - - SerialArena* head = threads_.load(std::memory_order_relaxed); - do { - serial->set_next(head); - } while (!threads_.compare_exchange_weak( - head, serial, std::memory_order_release, std::memory_order_relaxed)); - } - - CacheSerialArena(serial); - return serial; -} - -} // namespace internal - -void Arena::CallDestructorHooks() { - uint64 space_allocated = impl_.SpaceAllocated(); - // Call the reset hook - if (on_arena_reset_ != NULL) { - on_arena_reset_(this, hooks_cookie_, space_allocated); - } - - // Call the destruction hook - if (on_arena_destruction_ != NULL) { - on_arena_destruction_(this, hooks_cookie_, space_allocated); - } -} - -void Arena::OnArenaAllocation(const std::type_info* allocated_type, - size_t n) const { - if (on_arena_allocation_ != NULL) { - on_arena_allocation_(allocated_type, n, hooks_cookie_); - } -} - -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/arena.h b/windows/include/google/protobuf/arena.h index 9928c8e66..6dd6467f5 100644 --- a/windows/include/google/protobuf/arena.h +++ b/windows/include/google/protobuf/arena.h @@ -33,7 +33,10 @@ #ifndef GOOGLE_PROTOBUF_ARENA_H__ #define GOOGLE_PROTOBUF_ARENA_H__ + #include +#include +#include #ifdef max #undef max // Visual Studio defines this macro #endif @@ -48,61 +51,72 @@ using type_info = ::type_info; #include #endif -#include -#include #include +#include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif namespace google { namespace protobuf { struct ArenaOptions; // defined below - -} // namespace protobuf - -namespace quality_webanswers { - -void TempPrivateWorkAround(::google::protobuf::ArenaOptions* arena_options); - -} // namespace quality_webanswers - -namespace protobuf { - -class Arena; // defined below -class Message; // defined in message.h +class Arena; // defined below +class Message; // defined in message.h class MessageLite; +template +class Map; namespace arena_metrics { -void EnableArenaMetrics(::google::protobuf::ArenaOptions* options); +void EnableArenaMetrics(ArenaOptions* options); } // namespace arena_metrics +namespace TestUtil { +class ReflectionTester; // defined in test_util.h +} // namespace TestUtil + namespace internal { -struct ArenaStringPtr; // defined in arenastring.h -class LazyField; // defined in lazy_field.h +struct ArenaStringPtr; // defined in arenastring.h +class InlinedStringField; // defined in inlined_string_field.h +class LazyField; // defined in lazy_field.h +class EpsCopyInputStream; // defined in parse_context.h template class GenericTypeHandler; // defined in repeated_field.h +inline PROTOBUF_ALWAYS_INLINE +void* AlignTo(void* ptr, size_t align) { + return reinterpret_cast( + (reinterpret_cast(ptr) + align - 1) & (~align + 1)); +} + // Templated cleanup methods. template void arena_destruct_object(void* object) { reinterpret_cast(object)->~T(); } + +template +struct ObjectDestructor { + constexpr static void (*destructor)(void*) = &arena_destruct_object; +}; + +template +struct ObjectDestructor { + constexpr static void (*destructor)(void*) = nullptr; +}; + template void arena_delete_object(void* object) { delete reinterpret_cast(object); } -inline void arena_free(void* object, size_t size) { -#if defined(__GXX_DELETE_WITH_SIZE__) || defined(__cpp_sized_deallocation) - ::operator delete(object, size); -#else - (void)size; - ::operator delete(object); -#endif -} - } // namespace internal // ArenaOptions provides optional additional parameters to arena construction @@ -139,53 +153,43 @@ struct ArenaOptions { void (*block_dealloc)(void*, size_t); ArenaOptions() - : start_block_size(kDefaultStartBlockSize), - max_block_size(kDefaultMaxBlockSize), + : start_block_size(internal::AllocationPolicy::kDefaultStartBlockSize), + max_block_size(internal::AllocationPolicy::kDefaultMaxBlockSize), initial_block(NULL), initial_block_size(0), - block_alloc(&::operator new), - block_dealloc(&internal::arena_free), - on_arena_init(NULL), - on_arena_reset(NULL), - on_arena_destruction(NULL), - on_arena_allocation(NULL) {} + block_alloc(nullptr), + block_dealloc(nullptr), + make_metrics_collector(nullptr) {} private: - // Hooks for adding external functionality such as user-specific metrics - // collection, specific debugging abilities, etc. - // Init hook may return a pointer to a cookie to be stored in the arena. - // reset and destruction hooks will then be called with the same cookie - // pointer. This allows us to save an external object per arena instance and - // use it on the other hooks (Note: It is just as legal for init to return - // NULL and not use the cookie feature). - // on_arena_reset and on_arena_destruction also receive the space used in - // the arena just before the reset. - void* (*on_arena_init)(Arena* arena); - void (*on_arena_reset)(Arena* arena, void* cookie, uint64 space_used); - void (*on_arena_destruction)(Arena* arena, void* cookie, uint64 space_used); + // If make_metrics_collector is not nullptr, it will be called at Arena init + // time. It may return a pointer to a collector instance that will be notified + // of interesting events related to the arena. + internal::ArenaMetricsCollector* (*make_metrics_collector)(); - // type_info is promised to be static - its lifetime extends to - // match program's lifetime (It is given by typeid operator). - // Note: typeid(void) will be passed as allocated_type every time we - // intentionally want to avoid monitoring an allocation. (i.e. internal - // allocations for managing the arena) - void (*on_arena_allocation)(const std::type_info* allocated_type, - uint64 alloc_size, void* cookie); + internal::ArenaMetricsCollector* MetricsCollector() const { + return make_metrics_collector ? (*make_metrics_collector)() : nullptr; + } - // Constants define default starting block size and max block size for - // arena allocator behavior -- see descriptions above. - static const size_t kDefaultStartBlockSize = 256; - static const size_t kDefaultMaxBlockSize = 8192; + internal::AllocationPolicy AllocationPolicy() const { + internal::AllocationPolicy res; + res.start_block_size = start_block_size; + res.max_block_size = max_block_size; + res.block_alloc = block_alloc; + res.block_dealloc = block_dealloc; + res.metrics_collector = MetricsCollector(); + return res; + } + + friend void arena_metrics::EnableArenaMetrics(ArenaOptions*); - friend void ::google::protobuf::arena_metrics::EnableArenaMetrics(ArenaOptions*); - friend void quality_webanswers::TempPrivateWorkAround(ArenaOptions*); friend class Arena; friend class ArenaOptionsTestFriend; }; // Support for non-RTTI environments. (The metrics hooks API uses type // information.) -#ifndef GOOGLE_PROTOBUF_NO_RTTI +#if PROTOBUF_RTTI #define RTTI_TYPE_ID(type) (&typeid(type)) #else #define RTTI_TYPE_ID(type) (NULL) @@ -211,14 +215,15 @@ struct ArenaOptions { // any special requirements on the type T, and will invoke the object's // destructor when the arena is destroyed. // -// The arena message allocation protocol, required by CreateMessage, is as -// follows: +// The arena message allocation protocol, required by +// CreateMessage(Arena* arena, Args&&... args), is as follows: // -// - The type T must have (at least) two constructors: a constructor with no -// arguments, called when a T is allocated on the heap; and a constructor with -// a google::protobuf::Arena* argument, called when a T is allocated on an arena. If the -// second constructor is called with a NULL arena pointer, it must be -// equivalent to invoking the first (no-argument) constructor. +// - The type T must have (at least) two constructors: a constructor callable +// with `args` (without `arena`), called when a T is allocated on the heap; +// and a constructor callable with `Arena* arena, Args&&... args`, called when +// a T is allocated on an arena. If the second constructor is called with a +// NULL arena pointer, it must be equivalent to invoking the first +// (`args`-only) constructor. // // - The type T must have a particular type trait: a nested type // |InternalArenaConstructable_|. This is usually a typedef to |void|. If no @@ -231,23 +236,28 @@ struct ArenaOptions { // present on the type, then its destructor is always called when the // containing arena is destroyed. // -// - One- and two-user-argument forms of CreateMessage() also exist that -// forward these constructor arguments to T's constructor: for example, -// CreateMessage(Arena*, arg1, arg2) forwards to a constructor T(Arena*, -// arg1, arg2). -// // This protocol is implemented by all arena-enabled proto2 message classes as -// well as RepeatedPtrField. -// -// Do NOT subclass Arena. This class will be marked as final when C++11 is -// enabled. -class LIBPROTOBUF_EXPORT Arena { +// well as protobuf container types like RepeatedPtrField and Map. The protocol +// is internal to protobuf and is not guaranteed to be stable. Non-proto types +// should not rely on this protocol. +class PROTOBUF_EXPORT PROTOBUF_ALIGNAS(8) Arena final { public: - // Arena constructor taking custom options. See ArenaOptions below for + // Default constructor with sensible default options, tuned for average + // use-cases. + inline Arena() : impl_() {} + + // Construct an arena with default options, except for the supplied + // initial block. It is more efficient to use this constructor + // instead of passing ArenaOptions if the only configuration needed + // by the caller is supplying an initial block. + inline Arena(char* initial_block, size_t initial_block_size) + : impl_(initial_block, initial_block_size) {} + + // Arena constructor taking custom options. See ArenaOptions above for // descriptions of the options available. - explicit Arena(const ArenaOptions& options) : impl_(options) { - Init(options); - } + explicit Arena(const ArenaOptions& options) + : impl_(options.initial_block, options.initial_block_size, + options.AllocationPolicy()) {} // Block overhead. Use this as a guide for how much to over-allocate the // initial block if you want an allocation of size N to fit inside it. @@ -255,30 +265,14 @@ class LIBPROTOBUF_EXPORT Arena { // WARNING: if you allocate multiple objects, it is difficult to guarantee // that a series of allocations will fit in the initial block, especially if // Arena changes its alignment guarantees in the future! - static const size_t kBlockOverhead = internal::ArenaImpl::kBlockHeaderSize + - internal::ArenaImpl::kSerialArenaSize; + static const size_t kBlockOverhead = + internal::ThreadSafeArena::kBlockHeaderSize + + internal::ThreadSafeArena::kSerialArenaSize; - // Default constructor with sensible default options, tuned for average - // use-cases. - Arena() : impl_(ArenaOptions()) { Init(ArenaOptions()); } + inline ~Arena() {} - ~Arena() { - if (hooks_cookie_) { - CallDestructorHooks(); - } - } - - void Init(const ArenaOptions& options) { - on_arena_allocation_ = options.on_arena_allocation; - on_arena_reset_ = options.on_arena_reset; - on_arena_destruction_ = options.on_arena_destruction; - // Call the initialization hook - if (options.on_arena_init != NULL) { - hooks_cookie_ = options.on_arena_init(this); - } else { - hooks_cookie_ = NULL; - } - } + // TODO(protobuf-team): Fix callers to use constructor and delete this method. + void Init(const ArenaOptions&) {} // API to create proto2 message objects on the arena. If the arena passed in // is NULL, then a heap allocated object is returned. Type T must be a message @@ -291,15 +285,14 @@ class LIBPROTOBUF_EXPORT Arena { // This function also accepts any type T that satisfies the arena message // allocation protocol, documented above. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateMessage(Arena* arena, Args&&... args) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); // We must delegate to CreateMaybeMessage() and NOT CreateMessageInternal() // because protobuf generated classes specialize CreateMaybeMessage() and we // need to use that specialization for code size reasons. - return Arena::CreateMaybeMessage(arena, std::forward(args)...); + return Arena::CreateMaybeMessage(arena, static_cast(args)...); } // API to create any objects on the arena. Note that only the object will @@ -318,10 +311,9 @@ class LIBPROTOBUF_EXPORT Arena { // if the object were allocated on the heap (except that the underlying memory // is obtained from the arena). template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena, - Args&&... args) { - return CreateNoMessage(arena, is_arena_constructable(), - std::forward(args)...); + PROTOBUF_NDEBUG_INLINE static T* Create(Arena* arena, Args&&... args) { + return CreateInternal(arena, std::is_convertible(), + static_cast(args)...); } // Create an array of object type T on the arena *without* invoking the @@ -331,9 +323,9 @@ class LIBPROTOBUF_EXPORT Arena { // (when compiled as C++11) that T is trivially default-constructible and // trivially destructible. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateArray( - Arena* arena, size_t num_elements) { - static_assert(std::is_pod::value, + PROTOBUF_NDEBUG_INLINE static T* CreateArray(Arena* arena, + size_t num_elements) { + static_assert(std::is_trivial::value, "CreateArray requires a trivially constructible type"); static_assert(std::is_trivially_destructible::value, "CreateArray requires a trivially destructible type"); @@ -346,42 +338,31 @@ class LIBPROTOBUF_EXPORT Arena { } } + // The following are routines are for monitoring. They will approximate the + // total sum allocated and used memory, but the exact value is an + // implementation deal. For instance allocated space depends on growth + // policies. Do not use these in unit tests. // Returns the total space allocated by the arena, which is the sum of the - // sizes of the underlying blocks. This method is relatively fast; a counter - // is kept as blocks are allocated. - uint64 SpaceAllocated() const { return impl_.SpaceAllocated(); } + // sizes of the underlying blocks. + uint64_t SpaceAllocated() const { return impl_.SpaceAllocated(); } // Returns the total space used by the arena. Similar to SpaceAllocated but // does not include free space and block overhead. The total space returned // may not include space used by other threads executing concurrently with // the call to this method. - uint64 SpaceUsed() const { return impl_.SpaceUsed(); } - // DEPRECATED. Please use SpaceAllocated() and SpaceUsed(). - // - // Combines SpaceAllocated and SpaceUsed. Returns a pair of - // . - PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceAllocated() and SpaceUsed()") - std::pair SpaceAllocatedAndUsed() const { - return std::make_pair(SpaceAllocated(), SpaceUsed()); - } + uint64_t SpaceUsed() const { return impl_.SpaceUsed(); } // Frees all storage allocated by this arena after calling destructors // registered with OwnDestructor() and freeing objects registered with Own(). // Any objects allocated on this arena are unusable after this call. It also // returns the total space used by the arena which is the sums of the sizes // of the allocated blocks. This method is not thread-safe. - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE uint64 Reset() { - // Call the reset hook - if (on_arena_reset_ != NULL) { - on_arena_reset_(this, hooks_cookie_, impl_.SpaceAllocated()); - } - return impl_.Reset(); - } + uint64_t Reset() { return impl_.Reset(); } // Adds |object| to a list of heap-allocated objects to be freed with |delete| // when the arena is destroyed or reset. template - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) { - OwnInternal(object, std::is_convertible()); + PROTOBUF_ALWAYS_INLINE void Own(T* object) { + OwnInternal(object, std::is_convertible()); } // Adds |object| to a list of objects whose destructors will be manually @@ -390,7 +371,7 @@ class LIBPROTOBUF_EXPORT Arena { // normally only used for objects that are placement-newed into // arena-allocated memory. template - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) { + PROTOBUF_ALWAYS_INLINE void OwnDestructor(T* object) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_destruct_object); } @@ -400,23 +381,75 @@ class LIBPROTOBUF_EXPORT Arena { // will be manually called when the arena is destroyed or reset. This differs // from OwnDestructor() in that any member function may be specified, not only // the class destructor. - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnCustomDestructor( - void* object, void (*destruct)(void*)) { + PROTOBUF_ALWAYS_INLINE void OwnCustomDestructor(void* object, + void (*destruct)(void*)) { impl_.AddCleanup(object, destruct); } // Retrieves the arena associated with |value| if |value| is an arena-capable - // message, or NULL otherwise. This differs from value->GetArena() in that the - // latter is a virtual call, while this method is a templated call that - // resolves at compile-time. + // message, or NULL otherwise. If possible, the call resolves at compile time. + // Note that we can often devirtualize calls to `value->GetArena()` so usually + // calling this method is unnecessary. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena( - const T* value) { - return GetArenaInternal(value, is_arena_constructable()); + PROTOBUF_ALWAYS_INLINE static Arena* GetArena(const T* value) { + return GetArenaInternal(value); } template class InternalHelper { + public: + // Provides access to protected GetOwningArena to generated messages. + static Arena* GetOwningArena(const T* p) { return p->GetOwningArena(); } + + // Provides access to protected GetArenaForAllocation to generated messages. + static Arena* GetArenaForAllocation(const T* p) { + return GetArenaForAllocationInternal( + p, std::is_convertible()); + } + + // Creates message-owned arena. + static Arena* CreateMessageOwnedArena() { + return new Arena(internal::MessageOwned{}); + } + + // Checks whether the given arena is message-owned. + static bool IsMessageOwnedArena(Arena* arena) { + return arena->IsMessageOwned(); + } + + private: + static Arena* GetArenaForAllocationInternal( + const T* p, std::true_type /*is_derived_from*/) { + return p->GetArenaForAllocation(); + } + + static Arena* GetArenaForAllocationInternal( + const T* p, std::false_type /*is_derived_from*/) { + return GetArenaForAllocationForNonMessage( + p, typename is_arena_constructable::type()); + } + + static Arena* GetArenaForAllocationForNonMessage( + const T* p, std::true_type /*is_arena_constructible*/) { + return p->GetArena(); + } + + static Arena* GetArenaForAllocationForNonMessage( + const T* p, std::false_type /*is_arena_constructible*/) { + return GetArenaForAllocationForNonMessageNonArenaConstructible( + p, typename has_get_arena::type()); + } + + static Arena* GetArenaForAllocationForNonMessageNonArenaConstructible( + const T* p, std::true_type /*has_get_arena*/) { + return p->GetArena(); + } + + static Arena* GetArenaForAllocationForNonMessageNonArenaConstructible( + const T* /* p */, std::false_type /*has_get_arena*/) { + return nullptr; + } + template static char DestructorSkippable(const typename U::DestructorSkippable_*); template @@ -439,14 +472,32 @@ class LIBPROTOBUF_EXPORT Arena { sizeof(char)> is_arena_constructable; + template () + .GetArena())>::value, + int>::type = 0> + static char HasGetArena(decltype(&U::GetArena)); + template + static double HasGetArena(...); + + typedef std::integral_constant(nullptr)) == + sizeof(char)> + has_get_arena; + template static T* Construct(void* ptr, Args&&... args) { - return new (ptr) T(std::forward(args)...); + return new (ptr) T(static_cast(args)...); } - static Arena* GetArena(const T* p) { return p->GetArenaNoVirtual(); } + static inline PROTOBUF_ALWAYS_INLINE T* New() { + return new T(nullptr); + } + + static Arena* GetArena(const T* p) { return p->GetArena(); } friend class Arena; + friend class TestUtil::ReflectionTester; }; // Helper typetraits that indicates support for arenas in a type T at compile @@ -468,16 +519,29 @@ class LIBPROTOBUF_EXPORT Arena { }; private: + internal::ThreadSafeArena impl_; + + template + struct has_get_arena : InternalHelper::has_get_arena {}; + + // Constructor solely used by message-owned arena. + inline Arena(internal::MessageOwned) : impl_(internal::MessageOwned{}) {} + + // Checks whether this arena is message-owned. + PROTOBUF_ALWAYS_INLINE bool IsMessageOwned() const { + return impl_.IsMessageOwned(); + } + template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( - Arena* arena, Args&&... args) { + PROTOBUF_NDEBUG_INLINE static T* CreateMessageInternal(Arena* arena, + Args&&... args) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); if (arena == NULL) { - return new T(nullptr, std::forward(args)...); + return new T(nullptr, static_cast(args)...); } else { - return arena->DoCreateMessage(std::forward(args)...); + return arena->DoCreateMessage(static_cast(args)...); } } @@ -485,51 +549,40 @@ class LIBPROTOBUF_EXPORT Arena { // slightly different. When the arena pointer is nullptr, it calls T() // instead of T(nullptr). template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal( - Arena* arena) { + PROTOBUF_NDEBUG_INLINE static T* CreateMessageInternal(Arena* arena) { static_assert( InternalHelper::is_arena_constructable::value, "CreateMessage can only construct types that are ArenaConstructable"); if (arena == NULL) { - return new T(); + // Generated arena constructor T(Arena*) is protected. Call via + // InternalHelper. + return InternalHelper::New(); } else { return arena->DoCreateMessage(); } } - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal( - Arena* arena, Args&&... args) { - if (arena == NULL) { - return new T(std::forward(args)...); - } else { - return arena->DoCreate(std::is_trivially_destructible::value, - std::forward(args)...); - } - } - - void CallDestructorHooks(); - void OnArenaAllocation(const std::type_info* allocated_type, size_t n) const; - inline void AllocHook(const std::type_info* allocated_type, size_t n) const { - if (GOOGLE_PREDICT_FALSE(hooks_cookie_ != NULL)) { - OnArenaAllocation(allocated_type, n); - } - } - - // Allocate and also optionally call on_arena_allocation callback with the - // allocated type info when the hooks are in place in ArenaOptions and - // the cookie is not null. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void* AllocateInternal( - bool skip_explicit_ownership) { - const size_t n = internal::AlignUpTo8(sizeof(T)); - AllocHook(RTTI_TYPE_ID(T), n); + // Allocate and also optionally call collector with the allocated type info + // when allocation recording is enabled. + PROTOBUF_NDEBUG_INLINE void* AllocateInternal(size_t size, size_t align, + void (*destructor)(void*), + const std::type_info* type) { // Monitor allocation if needed. - if (skip_explicit_ownership) { - return impl_.AllocateAligned(n); + if (destructor == nullptr) { + return AllocateAlignedWithHook(size, align, type); } else { - return impl_.AllocateAlignedAndAddCleanup( - n, &internal::arena_destruct_object); + if (align <= 8) { + auto res = AllocateAlignedWithCleanup(internal::AlignUpTo8(size), type); + res.second->elem = res.first; + res.second->cleanup = destructor; + return res.first; + } else { + auto res = AllocateAlignedWithCleanup(size + align - 8, type); + auto ptr = internal::AlignTo(res.first, align); + res.second->elem = ptr; + res.second->cleanup = destructor; + return ptr; + } } } @@ -539,89 +592,74 @@ class LIBPROTOBUF_EXPORT Arena { // user code. These are used only internally from LazyField and Repeated // fields, since they are designed to work in all mode combinations. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage( - Arena* arena, std::true_type, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(Arena* arena, + std::true_type, + Args&&... args) { return CreateMessageInternal(arena, std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage( - Arena* arena, std::false_type, Args&&... args) { - return CreateInternal(arena, std::forward(args)...); + PROTOBUF_ALWAYS_INLINE static T* DoCreateMaybeMessage(Arena* arena, + std::false_type, + Args&&... args) { + return Create(arena, std::forward(args)...); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMaybeMessage( - Arena* arena, Args&&... args) { + PROTOBUF_ALWAYS_INLINE static T* CreateMaybeMessage(Arena* arena, + Args&&... args) { return DoCreateMaybeMessage(arena, is_arena_constructable(), std::forward(args)...); } - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( - Arena* arena, std::true_type, Args&&... args) { - // User is constructing with Create() despite the fact that T supports arena - // construction. In this case we have to delegate to CreateInternal(), and - // we can't use any CreateMaybeMessage() specialization that may be defined. - return CreateInternal(arena, std::forward(args)...); - } - - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateNoMessage( - Arena* arena, std::false_type, Args&&... args) { - // User is constructing with Create() and the type does not support arena - // construction. In this case we can delegate to CreateMaybeMessage() and - // use any specialization that may be available for that. - return CreateMaybeMessage(arena, std::forward(args)...); - } - // Just allocate the required size for the given type assuming the // type has a trivial constructor. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray( - size_t num_elements) { + PROTOBUF_NDEBUG_INLINE T* CreateInternalRawArray(size_t num_elements) { GOOGLE_CHECK_LE(num_elements, std::numeric_limits::max() / sizeof(T)) << "Requested size is too large to fit into size_t."; - const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements); - // Monitor allocation if needed. - AllocHook(RTTI_TYPE_ID(T), n); - return static_cast(impl_.AllocateAligned(n)); + // We count on compiler to realize that if sizeof(T) is a multiple of + // 8 AlignUpTo can be elided. + const size_t n = sizeof(T) * num_elements; + return static_cast( + AllocateAlignedWithHook(n, alignof(T), RTTI_TYPE_ID(T))); } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate( - bool skip_explicit_ownership, Args&&... args) { - return new (AllocateInternal(skip_explicit_ownership)) - T(std::forward(args)...); - } - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) { + PROTOBUF_NDEBUG_INLINE T* DoCreateMessage(Args&&... args) { return InternalHelper::Construct( - AllocateInternal(InternalHelper::is_destructor_skippable::value), + AllocateInternal(sizeof(T), alignof(T), + internal::ObjectDestructor< + InternalHelper::is_destructor_skippable::value, + T>::destructor, + RTTI_TYPE_ID(T)), this, std::forward(args)...); } // CreateInArenaStorage is used to implement map field. Without it, - // google::protobuf::Map need to call generated message's protected arena constructor, - // which needs to declare google::protobuf::Map as friend of generated message. - template - static void CreateInArenaStorage(T* ptr, Arena* arena) { + // Map need to call generated message's protected arena constructor, + // which needs to declare Map as friend of generated message. + template + static void CreateInArenaStorage(T* ptr, Arena* arena, Args&&... args) { CreateInArenaStorageInternal(ptr, arena, - typename is_arena_constructable::type()); - RegisterDestructorInternal( - ptr, arena, - typename InternalHelper::is_destructor_skippable::type()); + typename is_arena_constructable::type(), + std::forward(args)...); + if (arena != nullptr) { + RegisterDestructorInternal( + ptr, arena, + typename InternalHelper::is_destructor_skippable::type()); + } } - template + template static void CreateInArenaStorageInternal(T* ptr, Arena* arena, - std::true_type) { - InternalHelper::Construct(ptr, arena); + std::true_type, Args&&... args) { + InternalHelper::Construct(ptr, arena, std::forward(args)...); } - template + template static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */, - std::false_type) { - new (ptr) T(); + std::false_type, Args&&... args) { + new (ptr) T(std::forward(args)...); } template @@ -633,21 +671,52 @@ class LIBPROTOBUF_EXPORT Arena { arena->OwnDestructor(ptr); } + // These implement Create(). The second parameter has type 'true_type' if T is + // a subtype of Message and 'false_type' otherwise. + template + PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, std::true_type, + Args&&... args) { + if (arena == nullptr) { + return new T(std::forward(args)...); + } else { + auto destructor = + internal::ObjectDestructor::value, + T>::destructor; + T* result = + new (arena->AllocateInternal(sizeof(T), alignof(T), destructor, + RTTI_TYPE_ID(T))) + T(std::forward(args)...); + return result; + } + } + template + PROTOBUF_ALWAYS_INLINE static T* CreateInternal(Arena* arena, std::false_type, + Args&&... args) { + if (arena == nullptr) { + return new T(std::forward(args)...); + } else { + auto destructor = + internal::ObjectDestructor::value, + T>::destructor; + return new (arena->AllocateInternal(sizeof(T), alignof(T), destructor, + RTTI_TYPE_ID(T))) + T(std::forward(args)...); + } + } + // These implement Own(), which registers an object for deletion (destructor // call and operator delete()). The second parameter has type 'true_type' if T - // is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing + // is a subtype of Message and 'false_type' otherwise. Collapsing // all template instantiations to one for generic Message reduces code size, // using the virtual destructor instead. template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, - std::true_type) { + PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::true_type) { if (object != NULL) { - impl_.AddCleanup(object, &internal::arena_delete_object); + impl_.AddCleanup(object, &internal::arena_delete_object); } } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object, - std::false_type) { + PROTOBUF_ALWAYS_INLINE void OwnInternal(T* object, std::false_type) { if (object != NULL) { impl_.AddCleanup(object, &internal::arena_delete_object); } @@ -655,40 +724,87 @@ class LIBPROTOBUF_EXPORT Arena { // Implementation for GetArena(). Only message objects with // InternalArenaConstructable_ tags can be associated with an arena, and such - // objects must implement a GetArenaNoVirtual() method. - template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( - const T* value, std::true_type) { + // objects must implement a GetArena() method. + template ::value, int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { return InternalHelper::GetArena(value); } + template ::value && + has_get_arena::value, + int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { + return value->GetArena(); + } + template ::value && + !has_get_arena::value, + int>::type = 0> + PROTOBUF_ALWAYS_INLINE static Arena* GetArenaInternal(const T* value) { + (void)value; + return nullptr; + } template - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal( + PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArena(const T* value) { + return GetOwningArenaInternal( + value, std::is_convertible()); + } + + // Implementation for GetOwningArena(). All and only message objects have + // GetOwningArena() method. + template + PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArenaInternal( + const T* value, std::true_type) { + return InternalHelper::GetOwningArena(value); + } + template + PROTOBUF_ALWAYS_INLINE static Arena* GetOwningArenaInternal( const T* /* value */, std::false_type) { - return NULL; + return nullptr; } // For friends of arena. - void* AllocateAligned(size_t n) { - AllocHook(NULL, n); - return impl_.AllocateAligned(internal::AlignUpTo8(n)); + void* AllocateAligned(size_t n, size_t align = 8) { + if (align <= 8) { + return AllocateAlignedNoHook(internal::AlignUpTo8(n)); + } else { + // We are wasting space by over allocating align - 8 bytes. Compared + // to a dedicated function that takes current alignment in consideration. + // Such a scheme would only waste (align - 8)/2 bytes on average, but + // requires a dedicated function in the outline arena allocation + // functions. Possibly re-evaluate tradeoffs later. + return internal::AlignTo(AllocateAlignedNoHook(n + align - 8), align); + } } - internal::ArenaImpl impl_; + void* AllocateAlignedWithHook(size_t n, size_t align, + const std::type_info* type) { + if (align <= 8) { + return AllocateAlignedWithHook(internal::AlignUpTo8(n), type); + } else { + // We are wasting space by over allocating align - 8 bytes. Compared + // to a dedicated function that takes current alignment in consideration. + // Such a schemee would only waste (align - 8)/2 bytes on average, but + // requires a dedicated function in the outline arena allocation + // functions. Possibly re-evaluate tradeoffs later. + return internal::AlignTo(AllocateAlignedWithHook(n + align - 8, type), + align); + } + } - void (*on_arena_allocation_)(const std::type_info* allocated_type, - uint64 alloc_size, void* cookie); - void (*on_arena_reset_)(Arena* arena, void* cookie, uint64 space_used); - void (*on_arena_destruction_)(Arena* arena, void* cookie, uint64 space_used); - - // The arena may save a cookie it receives from the external on_init hook - // and then use it when calling the on_reset and on_destruction hooks. - void* hooks_cookie_; + void* AllocateAlignedNoHook(size_t n); + void* AllocateAlignedWithHook(size_t n, const std::type_info* type); + std::pair + AllocateAlignedWithCleanup(size_t n, const std::type_info* type); template friend class internal::GenericTypeHandler; friend struct internal::ArenaStringPtr; // For AllocateAligned. + friend class internal::InlinedStringField; // For AllocateAligned. friend class internal::LazyField; // For CreateMaybeMessage. + friend class internal::EpsCopyInputStream; // For parser performance friend class MessageLite; template friend class Map; @@ -698,6 +814,8 @@ class LIBPROTOBUF_EXPORT Arena { #undef RTTI_TYPE_ID } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ARENA_H__ diff --git a/windows/include/google/protobuf/arena_impl.h b/windows/include/google/protobuf/arena_impl.h index f648f1662..2ffac319b 100644 --- a/windows/include/google/protobuf/arena_impl.h +++ b/windows/include/google/protobuf/arena_impl.h @@ -35,87 +35,165 @@ #include #include +#include #include #include -#include - #ifdef ADDRESS_SANITIZER #include #endif // ADDRESS_SANITIZER -namespace google { +#include + +namespace google { namespace protobuf { namespace internal { -inline size_t AlignUpTo8(size_t n) { +inline constexpr size_t AlignUpTo8(size_t n) { // Align n to next multiple of 8 (from Hacker's Delight, Chapter 3.) - return (n + 7) & -8; + return (n + 7) & static_cast(-8); } -// This class provides the core Arena memory allocation library. Different -// implementations only need to implement the public interface below. -// Arena is not a template type as that would only be useful if all protos -// in turn would be templates, which will/cannot happen. However separating -// the memory allocation part from the cruft of the API users expect we can -// use #ifdef the select the best implementation based on hardware / OS. -class LIBPROTOBUF_EXPORT ArenaImpl { +using LifecycleIdAtomic = uint64_t; + +// MetricsCollector collects stats for a particular arena. +class PROTOBUF_EXPORT ArenaMetricsCollector { public: - struct Options { - size_t start_block_size; - size_t max_block_size; - char* initial_block; - size_t initial_block_size; - void* (*block_alloc)(size_t); - void (*block_dealloc)(void*, size_t); + ArenaMetricsCollector(bool record_allocs) : record_allocs_(record_allocs) {} - template - explicit Options(const O& options) - : start_block_size(options.start_block_size), - max_block_size(options.max_block_size), - initial_block(options.initial_block), - initial_block_size(options.initial_block_size), - block_alloc(options.block_alloc), - block_dealloc(options.block_dealloc) {} - }; + // Invoked when the arena is about to be destroyed. This method will + // typically finalize any metric collection and delete the collector. + // space_allocated is the space used by the arena. + virtual void OnDestroy(uint64_t space_allocated) = 0; - template - explicit ArenaImpl(const O& options) : options_(options) { - if (options_.initial_block != NULL && options_.initial_block_size > 0) { - GOOGLE_CHECK_GE(options_.initial_block_size, sizeof(Block)) - << ": Initial block size too small for header."; - initial_block_ = reinterpret_cast(options_.initial_block); - } else { - initial_block_ = NULL; - } + // OnReset() is called when the associated arena is reset. + // space_allocated is the space used by the arena just before the reset. + virtual void OnReset(uint64_t space_allocated) = 0; - Init(); + // OnAlloc is called when an allocation happens. + // type_info is promised to be static - its lifetime extends to + // match program's lifetime (It is given by typeid operator). + // Note: typeid(void) will be passed as allocated_type every time we + // intentionally want to avoid monitoring an allocation. (i.e. internal + // allocations for managing the arena) + virtual void OnAlloc(const std::type_info* allocated_type, + uint64_t alloc_size) = 0; + + // Does OnAlloc() need to be called? If false, metric collection overhead + // will be reduced since we will not do extra work per allocation. + bool RecordAllocs() { return record_allocs_; } + + protected: + // This class is destructed by the call to OnDestroy(). + ~ArenaMetricsCollector() = default; + const bool record_allocs_; +}; + +struct AllocationPolicy { + static constexpr size_t kDefaultStartBlockSize = 256; + static constexpr size_t kDefaultMaxBlockSize = 8192; + + size_t start_block_size = kDefaultStartBlockSize; + size_t max_block_size = kDefaultMaxBlockSize; + void* (*block_alloc)(size_t) = nullptr; + void (*block_dealloc)(void*, size_t) = nullptr; + ArenaMetricsCollector* metrics_collector = nullptr; + + bool IsDefault() const { + return start_block_size == kDefaultMaxBlockSize && + max_block_size == kDefaultMaxBlockSize && block_alloc == nullptr && + block_dealloc == nullptr && metrics_collector == nullptr; + } +}; + +// Tagged pointer to an AllocationPolicy. +class TaggedAllocationPolicyPtr { + public: + constexpr TaggedAllocationPolicyPtr() : policy_(0) {} + + explicit TaggedAllocationPolicyPtr(AllocationPolicy* policy) + : policy_(reinterpret_cast(policy)) {} + + void set_policy(AllocationPolicy* policy) { + auto bits = policy_ & kTagsMask; + policy_ = reinterpret_cast(policy) | bits; } - // Destructor deletes all owned heap allocated objects, and destructs objects - // that have non-trivial destructors, except for proto2 message objects whose - // destructors can be skipped. Also, frees all blocks except the initial block - // if it was passed in. - ~ArenaImpl(); + AllocationPolicy* get() { + return reinterpret_cast(policy_ & kPtrMask); + } + const AllocationPolicy* get() const { + return reinterpret_cast(policy_ & kPtrMask); + } - uint64 Reset(); + AllocationPolicy& operator*() { return *get(); } + const AllocationPolicy& operator*() const { return *get(); } - uint64 SpaceAllocated() const; - uint64 SpaceUsed() const; + AllocationPolicy* operator->() { return get(); } + const AllocationPolicy* operator->() const { return get(); } - void* AllocateAligned(size_t n); + bool is_user_owned_initial_block() const { + return static_cast(get_mask()); + } + void set_is_user_owned_initial_block(bool v) { + set_mask(v); + } - void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*)); + bool should_record_allocs() const { + return static_cast(get_mask()); + } + void set_should_record_allocs(bool v) { set_mask(v); } - // Add object pointer and cleanup function pointer to the list. - void AddCleanup(void* elem, void (*cleanup)(void*)); + uintptr_t get_raw() const { return policy_; } + + inline void RecordAlloc(const std::type_info* allocated_type, + size_t n) const { + get()->metrics_collector->OnAlloc(allocated_type, n); + } private: - void* AllocateAlignedFallback(size_t n); - void* AllocateAlignedAndAddCleanupFallback(size_t n, void (*cleanup)(void*)); - void AddCleanupFallback(void* elem, void (*cleanup)(void*)); + enum : uintptr_t { + kUserOwnedInitialBlock = 1, + kRecordAllocs = 2, + }; + + static constexpr uintptr_t kTagsMask = 7; + static constexpr uintptr_t kPtrMask = ~kTagsMask; + + template + uintptr_t get_mask() const { + return policy_ & kMask; + } + template + void set_mask(bool v) { + if (v) { + policy_ |= kMask; + } else { + policy_ &= ~kMask; + } + } + uintptr_t policy_; +}; + +// 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 +// for ThreadSafeArena, which provides a thread-safe arena allocator. +// +// This class manages +// 1) Arena bump allocation + owning memory blocks. +// 2) Maintaining a cleanup list. +// It delagetes the actual memory allocation back to ThreadSafeArena, which +// contains the information on block growth policy and backing memory allocation +// used. +class PROTOBUF_EXPORT SerialArena { + public: + struct Memory { + void* ptr; + size_t size; + }; // Node contains the ptr of the object to be cleaned up and the associated // cleanup function ptr. @@ -124,190 +202,351 @@ class LIBPROTOBUF_EXPORT ArenaImpl { void (*cleanup)(void*); // Function pointer to the destructor or deleter. }; - // Cleanup uses a chunked linked list, to reduce pointer chasing. - struct CleanupChunk { - static size_t SizeOf(size_t i) { - return sizeof(CleanupChunk) + (sizeof(CleanupNode) * (i - 1)); + void CleanupList(); + uint64_t SpaceAllocated() const { + return space_allocated_.load(std::memory_order_relaxed); + } + uint64_t SpaceUsed() const; + + bool HasSpace(size_t n) { return n <= static_cast(limit_ - ptr_); } + + void* AllocateAligned(size_t n, const AllocationPolicy* policy) { + GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned. + GOOGLE_DCHECK_GE(limit_, ptr_); + if (PROTOBUF_PREDICT_FALSE(!HasSpace(n))) { + return AllocateAlignedFallback(n, policy); } - size_t size; // Total elements in the list. - CleanupChunk* next; // Next node in the list. - CleanupNode nodes[1]; // True length is |size|. - }; + return AllocateFromExisting(n); + } - class Block; - - // A thread-unsafe Arena that can only be used within its owning thread. - class LIBPROTOBUF_EXPORT SerialArena { - public: - // The allocate/free methods here are a little strange, since SerialArena is - // allocated inside a Block which it also manages. This is to avoid doing - // an extra allocation for the SerialArena itself. - - // Creates a new SerialArena inside Block* and returns it. - static SerialArena* New(Block* b, void* owner, ArenaImpl* arena); - - // Destroys this SerialArena, freeing all blocks with the given dealloc - // function, except any block equal to |initial_block|. - static uint64 Free(SerialArena* serial, Block* initial_block, - void (*block_dealloc)(void*, size_t)); - - void CleanupList(); - uint64 SpaceUsed() const; - - void* AllocateAligned(size_t n) { - GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned. - GOOGLE_DCHECK_GE(limit_, ptr_); - if (GOOGLE_PREDICT_FALSE(static_cast(limit_ - ptr_) < n)) { - return AllocateAlignedFallback(n); - } - void* ret = ptr_; - ptr_ += n; + private: + void* AllocateFromExisting(size_t n) { + void* ret = ptr_; + ptr_ += n; #ifdef ADDRESS_SANITIZER - ASAN_UNPOISON_MEMORY_REGION(ret, n); + ASAN_UNPOISON_MEMORY_REGION(ret, n); #endif // ADDRESS_SANITIZER - return ret; + return ret; + } + + public: + // Allocate space if the current region provides enough space. + bool MaybeAllocateAligned(size_t n, void** out) { + GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned. + GOOGLE_DCHECK_GE(limit_, ptr_); + if (PROTOBUF_PREDICT_FALSE(!HasSpace(n))) return false; + *out = AllocateFromExisting(n); + return true; + } + + std::pair AllocateAlignedWithCleanup( + size_t n, const AllocationPolicy* policy) { + GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned. + if (PROTOBUF_PREDICT_FALSE(!HasSpace(n + kCleanupSize))) { + return AllocateAlignedWithCleanupFallback(n, policy); } + return AllocateFromExistingWithCleanupFallback(n); + } - void AddCleanup(void* elem, void (*cleanup)(void*)) { - if (GOOGLE_PREDICT_FALSE(cleanup_ptr_ == cleanup_limit_)) { - AddCleanupFallback(elem, cleanup); - return; - } - cleanup_ptr_->elem = elem; - cleanup_ptr_->cleanup = cleanup; - cleanup_ptr_++; - } + private: + std::pair AllocateFromExistingWithCleanupFallback( + size_t n) { + void* ret = ptr_; + ptr_ += n; + limit_ -= kCleanupSize; +#ifdef ADDRESS_SANITIZER + ASAN_UNPOISON_MEMORY_REGION(ret, n); + ASAN_UNPOISON_MEMORY_REGION(limit_, kCleanupSize); +#endif // ADDRESS_SANITIZER + return CreatePair(ret, reinterpret_cast(limit_)); + } - void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*)) { - void* ret = AllocateAligned(n); - AddCleanup(ret, cleanup); - return ret; - } + public: + void AddCleanup(void* elem, void (*cleanup)(void*), + const AllocationPolicy* policy) { + auto res = AllocateAlignedWithCleanup(0, policy); + res.second->elem = elem; + res.second->cleanup = cleanup; + } - void* owner() const { return owner_; } - SerialArena* next() const { return next_; } - void set_next(SerialArena* next) { next_ = next; } + void* owner() const { return owner_; } + SerialArena* next() const { return next_; } + void set_next(SerialArena* next) { next_ = next; } - private: - void* AllocateAlignedFallback(size_t n); - void AddCleanupFallback(void* elem, void (*cleanup)(void*)); - void CleanupListFallback(); + private: + friend class ThreadSafeArena; + friend class ArenaBenchmark; - ArenaImpl* arena_; // Containing arena. - void* owner_; // &ThreadCache of this thread; - Block* head_; // Head of linked list of blocks. - CleanupChunk* cleanup_; // Head of cleanup list. - SerialArena* next_; // Next SerialArena in this linked list. - - // 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. - char* ptr_; - char* limit_; - - // Next CleanupList members to append to. These point inside cleanup_. - CleanupNode* cleanup_ptr_; - CleanupNode* cleanup_limit_; - }; + // Creates a new SerialArena inside mem using the remaining memory as for + // future allocations. + static SerialArena* New(SerialArena::Memory mem, void* owner); + // Free SerialArena returning the memory passed in to New + template + Memory Free(Deallocator deallocator); // Blocks are variable length malloc-ed objects. The following structure // describes the common header for all blocks. - class LIBPROTOBUF_EXPORT Block { - public: - Block(size_t size, Block* next); + struct Block { + Block(Block* next, size_t size) : next(next), size(size), start(nullptr) {} char* Pointer(size_t n) { - GOOGLE_DCHECK(n <= size_); + GOOGLE_DCHECK(n <= size); return reinterpret_cast(this) + n; } - Block* next() const { return next_; } - size_t pos() const { return pos_; } - size_t size() const { return size_; } - void set_pos(size_t pos) { pos_ = pos; } - - private: - Block* next_; // Next block for this thread. - size_t pos_; - size_t size_; + Block* const next; + const size_t size; + CleanupNode* start; // data follows }; - struct ThreadCache { + void* owner_; // &ThreadCache of this thread; + Block* head_; // Head of linked list of blocks. + SerialArena* next_; // Next SerialArena in this linked list. + size_t space_used_ = 0; // Necessary for metrics. + std::atomic space_allocated_; + + // 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. + char* ptr_; + char* limit_; + + // Constructor is private as only New() should be used. + inline SerialArena(Block* b, void* owner); + void* AllocateAlignedFallback(size_t n, const AllocationPolicy* policy); + std::pair AllocateAlignedWithCleanupFallback( + size_t n, const AllocationPolicy* policy); + void AllocateNewBlock(size_t n, const AllocationPolicy* policy); + + std::pair CreatePair(void* ptr, CleanupNode* node) { + return {ptr, node}; + } + + public: + static constexpr size_t kBlockHeaderSize = AlignUpTo8(sizeof(Block)); + static constexpr size_t kCleanupSize = AlignUpTo8(sizeof(CleanupNode)); +}; + +// Tag type used to invoke the constructor of message-owned arena. +// Only message-owned arenas use this constructor for creation. +// Such constructors are internal implementation details of the library. +struct MessageOwned { + explicit MessageOwned() = default; +}; + +// This class provides the core Arena memory allocation library. Different +// implementations only need to implement the public interface below. +// Arena is not a template type as that would only be useful if all protos +// in turn would be templates, which will/cannot happen. However separating +// the memory allocation part from the cruft of the API users expect we can +// use #ifdef the select the best implementation based on hardware / OS. +class PROTOBUF_EXPORT ThreadSafeArena { + public: + ThreadSafeArena() { Init(); } + + // Constructor solely used by message-owned arena. + ThreadSafeArena(internal::MessageOwned) : tag_and_id_(kMessageOwnedArena) { + Init(); + } + + ThreadSafeArena(char* mem, size_t size) { InitializeFrom(mem, size); } + + explicit ThreadSafeArena(void* mem, size_t size, + const AllocationPolicy& policy) { + InitializeWithPolicy(mem, size, policy); + } + + // Destructor deletes all owned heap allocated objects, and destructs objects + // that have non-trivial destructors, except for proto2 message objects whose + // destructors can be skipped. Also, frees all blocks except the initial block + // if it was passed in. + ~ThreadSafeArena(); + + uint64_t Reset(); + + uint64_t SpaceAllocated() const; + uint64_t SpaceUsed() const; + + void* AllocateAligned(size_t n, const std::type_info* type) { + SerialArena* arena; + if (PROTOBUF_PREDICT_TRUE(!alloc_policy_.should_record_allocs() && + GetSerialArenaFast(&arena))) { + return arena->AllocateAligned(n, AllocPolicy()); + } else { + return AllocateAlignedFallback(n, type); + } + } + + // This function allocates n bytes if the common happy case is true and + // returns true. Otherwise does nothing and returns false. This strange + // semantics is necessary to allow callers to program functions that only + // have fallback function calls in tail position. This substantially improves + // code for the happy path. + PROTOBUF_NDEBUG_INLINE bool MaybeAllocateAligned(size_t n, void** out) { + SerialArena* a; + if (PROTOBUF_PREDICT_TRUE(!alloc_policy_.should_record_allocs() && + GetSerialArenaFromThreadCache(&a))) { + return a->MaybeAllocateAligned(n, out); + } + return false; + } + + std::pair AllocateAlignedWithCleanup( + size_t n, const std::type_info* type); + + // Add object pointer and cleanup function pointer to the list. + void AddCleanup(void* elem, void (*cleanup)(void*)); + + // Checks whether this arena is message-owned. + PROTOBUF_ALWAYS_INLINE bool IsMessageOwned() const { + return tag_and_id_ & kMessageOwnedArena; + } + + private: + // 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. + + // Pointer to a linked list of SerialArena. + std::atomic threads_; + std::atomic hint_; // Fast thread-local block access + + 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* AllocateAlignedFallback(size_t n, const std::type_info* type); + std::pair + AllocateAlignedWithCleanupFallback(size_t n, const std::type_info* type); + + void Init(); + void SetInitialBlock(void* mem, size_t size); + + // Delete or Destruct all objects owned by the arena. + void CleanupList(); + + inline uint64_t LifeCycleId() const { + return tag_and_id_ & ~kMessageOwnedArena; + } + + inline void CacheSerialArena(SerialArena* serial) { + thread_cache().last_serial_arena = serial; + thread_cache().last_lifecycle_id_seen = tag_and_id_; + // TODO(haberman): evaluate whether we would gain efficiency by getting rid + // of hint_. It's the only write we do to ThreadSafeArena in the allocation + // path, which will dirty the cache line. + + hint_.store(serial, std::memory_order_release); + } + + PROTOBUF_NDEBUG_INLINE bool GetSerialArenaFast(SerialArena** arena) { + if (GetSerialArenaFromThreadCache(arena)) return true; + + // Check whether we own the last accessed SerialArena on this arena. This + // fast path optimizes the case where a single thread uses multiple arenas. + ThreadCache* tc = &thread_cache(); + SerialArena* serial = hint_.load(std::memory_order_acquire); + if (PROTOBUF_PREDICT_TRUE(serial != NULL && serial->owner() == tc)) { + *arena = serial; + return true; + } + return false; + } + + PROTOBUF_NDEBUG_INLINE bool GetSerialArenaFromThreadCache( + SerialArena** arena) { + // If this thread already owns a block in this arena then try to use that. + // This fast path optimizes the case where multiple threads allocate from + // the same arena. + ThreadCache* tc = &thread_cache(); + if (PROTOBUF_PREDICT_TRUE(tc->last_lifecycle_id_seen == tag_and_id_)) { + *arena = tc->last_serial_arena; + return true; + } + return false; + } + SerialArena* GetSerialArenaFallback(void* me); + + template + void PerSerialArena(Functor fn) { + // By omitting an Acquire barrier we ensure that any user code that doesn't + // properly synchronize Reset() or the destructor will throw a TSAN warning. + SerialArena* serial = threads_.load(std::memory_order_relaxed); + + for (; serial; serial = serial->next()) fn(serial); + } + + // 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 + // deleting. + SerialArena::Memory Free(size_t* space_allocated); + +#ifdef _MSC_VER +#pragma warning(disable : 4324) +#endif + struct alignas(64) ThreadCache { #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) // If we are using the ThreadLocalStorage class to store the ThreadCache, // then the ThreadCache's default constructor has to be responsible for // initializing it. - ThreadCache() : last_lifecycle_id_seen(-1), last_serial_arena(NULL) {} + ThreadCache() + : next_lifecycle_id(0), + last_lifecycle_id_seen(-1), + last_serial_arena(NULL) {} #endif + // Number of per-thread lifecycle IDs to reserve. Must be power of two. + // To reduce contention on a global atomic, each thread reserves a batch of + // IDs. The following number is calculated based on a stress test with + // ~6500 threads all frequently allocating a new arena. + static constexpr size_t kPerThreadIds = 256; + // Next lifecycle ID available to this thread. We need to reserve a new + // batch, if `next_lifecycle_id & (kPerThreadIds - 1) == 0`. + uint64_t next_lifecycle_id; // The ThreadCache is considered valid as long as this matches the // lifecycle_id of the arena being used. - int64 last_lifecycle_id_seen; + uint64_t last_lifecycle_id_seen; SerialArena* last_serial_arena; }; - static std::atomic lifecycle_id_generator_; + + // Lifecycle_id can be highly contended variable in a situation of lots of + // arena creation. Make sure that other global variables are not sharing the + // cacheline. +#ifdef _MSC_VER +#pragma warning(disable : 4324) +#endif + struct alignas(64) CacheAlignedLifecycleIdGenerator { + std::atomic id; + }; + static CacheAlignedLifecycleIdGenerator lifecycle_id_generator_; #if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL) - // Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread - // local storage class we implemented. - // iOS also does not support the GOOGLE_THREAD_LOCAL keyword. + // iOS does not support __thread keyword so we use a custom thread local + // storage class we implemented. static ThreadCache& thread_cache(); #elif defined(PROTOBUF_USE_DLLS) // Thread local variables cannot be exposed through DLL interface but we can // wrap them in static functions. static ThreadCache& thread_cache(); #else - static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_; + static PROTOBUF_THREAD_LOCAL ThreadCache thread_cache_; static ThreadCache& thread_cache() { return thread_cache_; } #endif - void Init(); - - // Free all blocks and return the total space used which is the sums of sizes - // of the all the allocated blocks. - uint64 FreeBlocks(); - // Delete or Destruct all objects owned by the arena. - void CleanupList(); - - inline void CacheSerialArena(SerialArena* serial) { - thread_cache().last_serial_arena = serial; - thread_cache().last_lifecycle_id_seen = lifecycle_id_; - // TODO(haberman): evaluate whether we would gain efficiency by getting rid - // of hint_. It's the only write we do to ArenaImpl in the allocation path, - // which will dirty the cache line. - - hint_.store(serial, std::memory_order_release); - } - - - std::atomic - threads_; // Pointer to a linked list of SerialArena. - std::atomic hint_; // Fast thread-local block access - std::atomic space_allocated_; // Total size of all allocated blocks. - - Block *initial_block_; // If non-NULL, points to the block that came from - // user data. - - Block* NewBlock(Block* last_block, size_t min_bytes); - - SerialArena* GetSerialArena(); - bool GetSerialArenaFast(SerialArena** arena); - SerialArena* GetSerialArenaFallback(void* me); - int64 lifecycle_id_; // Unique for each arena. Changes on Reset(). - - Options options_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArenaImpl); + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ThreadSafeArena); // All protos have pointers back to the arena hence Arena must have // pointer stability. - ArenaImpl(ArenaImpl&&) = delete; - ArenaImpl& operator=(ArenaImpl&&) = delete; + ThreadSafeArena(ThreadSafeArena&&) = delete; + ThreadSafeArena& operator=(ThreadSafeArena&&) = delete; 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. - static const size_t kBlockHeaderSize = (sizeof(Block) + 7) & -8; - static const size_t kSerialArenaSize = (sizeof(SerialArena) + 7) & -8; + static constexpr size_t kBlockHeaderSize = SerialArena::kBlockHeaderSize; + static constexpr size_t kSerialArenaSize = + (sizeof(SerialArena) + 7) & static_cast(-8); static_assert(kBlockHeaderSize % 8 == 0, "kBlockHeaderSize must be a multiple of 8."); static_assert(kSerialArenaSize % 8 == 0, @@ -316,6 +555,8 @@ class LIBPROTOBUF_EXPORT ArenaImpl { } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ARENA_IMPL_H__ diff --git a/windows/include/google/protobuf/arena_unittest.cc b/windows/include/google/protobuf/arena_unittest.cc deleted file mode 100644 index eaaffce25..000000000 --- a/windows/include/google/protobuf/arena_unittest.cc +++ /dev/null @@ -1,1436 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -using proto2_arena_unittest::ArenaMessage; -using protobuf_unittest::TestAllTypes; -using protobuf_unittest::TestAllExtensions; -using protobuf_unittest::TestOneof2; -using protobuf_unittest::TestEmptyMessage; - -namespace protobuf { - -class Notifier { - public: - Notifier() : count_(0) {} - void Notify() { - count_++; - } - int GetCount() { - return count_; - } - - private: - int count_; -}; - -class SimpleDataType { - public: - SimpleDataType() : notifier_(NULL) {} - void SetNotifier(Notifier* notifier) { - notifier_ = notifier; - } - virtual ~SimpleDataType() { - if (notifier_ != NULL) { - notifier_->Notify(); - } - }; - private: - Notifier* notifier_; -}; - -// A simple class that does not allow copying and so cannot be used as a -// parameter type without "const &". -class PleaseDontCopyMe { - public: - explicit PleaseDontCopyMe(int value) : value_(value) {} - - int value() const { return value_; } - - private: - int value_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PleaseDontCopyMe); -}; - -// A class that takes four different types as constructor arguments. -class MustBeConstructedWithOneThroughFour { - public: - MustBeConstructedWithOneThroughFour( - int one, const char* two, const string& three, - const PleaseDontCopyMe* four) - : one_(one), two_(two), three_(three), four_(four) {} - - int one_; - const char* const two_; - string three_; - const PleaseDontCopyMe* four_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MustBeConstructedWithOneThroughFour); -}; - -// A class that takes eight different types as constructor arguments. -class MustBeConstructedWithOneThroughEight { - public: - MustBeConstructedWithOneThroughEight( - int one, const char* two, const string& three, - const PleaseDontCopyMe* four, int five, const char* six, - const string& seven, const string& eight) - : one_(one), two_(two), three_(three), four_(four), five_(five), - six_(six), seven_(seven), eight_(eight) {} - - int one_; - const char* const two_; - string three_; - const PleaseDontCopyMe* four_; - int five_; - const char* const six_; - string seven_; - string eight_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MustBeConstructedWithOneThroughEight); -}; - -TEST(ArenaTest, ArenaConstructable) { - EXPECT_TRUE(Arena::is_arena_constructable::type::value); - EXPECT_TRUE(Arena::is_arena_constructable::type::value); - EXPECT_FALSE(Arena::is_arena_constructable< - protobuf_unittest_no_arena::TestNoArenaMessage>::type::value); - EXPECT_FALSE(Arena::is_arena_constructable::type::value); -} - -TEST(ArenaTest, DestructorSkippable) { - EXPECT_TRUE(Arena::is_destructor_skippable::type::value); - EXPECT_TRUE(Arena::is_destructor_skippable::type::value); - EXPECT_FALSE(Arena::is_destructor_skippable< - protobuf_unittest_no_arena::TestNoArenaMessage>::type::value); - EXPECT_FALSE(Arena::is_destructor_skippable::type::value); -} - -TEST(ArenaTest, BasicCreate) { - Arena arena; - EXPECT_TRUE(Arena::Create(&arena) != NULL); - EXPECT_TRUE(Arena::Create(&arena) != NULL); - EXPECT_TRUE(Arena::Create(&arena) != NULL); - EXPECT_TRUE(Arena::Create(&arena) != NULL); - EXPECT_TRUE(Arena::Create(&arena) != NULL); - arena.Own(new int32); - arena.Own(new int64); - arena.Own(new float); - arena.Own(new double); - arena.Own(new string); - arena.Own(NULL); - Notifier notifier; - SimpleDataType* data = Arena::Create(&arena); - data->SetNotifier(¬ifier); - data = new SimpleDataType; - data->SetNotifier(¬ifier); - arena.Own(data); - arena.Reset(); - EXPECT_EQ(2, notifier.GetCount()); -} - -TEST(ArenaTest, CreateAndConstCopy) { - Arena arena; - const string s("foo"); - const string* s_copy = Arena::Create(&arena, s); - EXPECT_TRUE(s_copy != NULL); - EXPECT_EQ("foo", s); - EXPECT_EQ("foo", *s_copy); -} - -TEST(ArenaTest, CreateAndNonConstCopy) { - Arena arena; - string s("foo"); - const string* s_copy = Arena::Create(&arena, s); - EXPECT_TRUE(s_copy != NULL); - EXPECT_EQ("foo", s); - EXPECT_EQ("foo", *s_copy); -} - -TEST(ArenaTest, CreateAndMove) { - Arena arena; - string s("foo"); - const string* s_move = Arena::Create(&arena, std::move(s)); - EXPECT_TRUE(s_move != NULL); - EXPECT_TRUE(s.empty()); // NOLINT - EXPECT_EQ("foo", *s_move); -} - -TEST(ArenaTest, CreateWithFourConstructorArguments) { - Arena arena; - const string three("3"); - const PleaseDontCopyMe four(4); - const MustBeConstructedWithOneThroughFour* new_object = - Arena::Create( - &arena, 1, "2", three, &four); - EXPECT_TRUE(new_object != NULL); - ASSERT_EQ(1, new_object->one_); - ASSERT_STREQ("2", new_object->two_); - ASSERT_EQ("3", new_object->three_); - ASSERT_EQ(4, new_object->four_->value()); -} - -TEST(ArenaTest, CreateWithEightConstructorArguments) { - Arena arena; - const string three("3"); - const PleaseDontCopyMe four(4); - const string seven("7"); - const string eight("8"); - const MustBeConstructedWithOneThroughEight* new_object = - Arena::Create( - &arena, 1, "2", three, &four, 5, "6", seven, eight); - EXPECT_TRUE(new_object != NULL); - ASSERT_EQ(1, new_object->one_); - ASSERT_STREQ("2", new_object->two_); - ASSERT_EQ("3", new_object->three_); - ASSERT_EQ(4, new_object->four_->value()); - ASSERT_EQ(5, new_object->five_); - ASSERT_STREQ("6", new_object->six_); - ASSERT_EQ("7", new_object->seven_); - ASSERT_EQ("8", new_object->eight_); -} - -class PleaseMoveMe { - public: - explicit PleaseMoveMe(const string& value) : value_(value) {} - PleaseMoveMe(PleaseMoveMe&&) = default; - PleaseMoveMe(const PleaseMoveMe&) = delete; - - const string& value() const { return value_; } - - private: - string value_; -}; - -TEST(ArenaTest, CreateWithMoveArguments) { - Arena arena; - PleaseMoveMe one("1"); - const PleaseMoveMe* new_object = - Arena::Create(&arena, std::move(one)); - EXPECT_TRUE(new_object); - ASSERT_EQ("1", new_object->value()); -} - -TEST(ArenaTest, InitialBlockTooSmall) { - // Construct a small (64 byte) initial block of memory to be used by the - // arena allocator; then, allocate an object which will not fit in the - // initial block. - std::vector arena_block(96); - ArenaOptions options; - options.initial_block = &arena_block[0]; - options.initial_block_size = arena_block.size(); - Arena arena(options); - - char* p = ::google::protobuf::Arena::CreateArray(&arena, 96); - uintptr_t allocation = reinterpret_cast(p); - - // Ensure that the arena allocator did not return memory pointing into the - // initial block of memory. - uintptr_t arena_start = reinterpret_cast(&arena_block[0]); - uintptr_t arena_end = arena_start + arena_block.size(); - EXPECT_FALSE(allocation >= arena_start && allocation < arena_end); - - // Write to the memory we allocated; this should (but is not guaranteed to) - // trigger a check for heap corruption if the object was allocated from the - // initially-provided block. - memset(p, '\0', 96); -} - -TEST(ArenaTest, Parsing) { - TestAllTypes original; - TestUtil::SetAllFields(&original); - - // Test memory leak. - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - arena_message->ParseFromString(original.SerializeAsString()); - TestUtil::ExpectAllFieldsSet(*arena_message); - - // Test that string fields have nul terminator bytes (earlier bug). - EXPECT_EQ(strlen(original.optional_string().c_str()), - strlen(arena_message->optional_string().c_str())); -} - -TEST(ArenaTest, UnknownFields) { - TestAllTypes original; - TestUtil::SetAllFields(&original); - - // Test basic parsing into (populating) and reading out of unknown fields on - // an arena. - Arena arena; - TestEmptyMessage* arena_message = - Arena::CreateMessage(&arena); - arena_message->ParseFromString(original.SerializeAsString()); - - TestAllTypes copied; - copied.ParseFromString(arena_message->SerializeAsString()); - TestUtil::ExpectAllFieldsSet(copied); - - // Exercise UFS manual manipulation (setters). - arena_message = Arena::CreateMessage(&arena); - arena_message->mutable_unknown_fields()->AddVarint( - TestAllTypes::kOptionalInt32FieldNumber, 42); - copied.Clear(); - copied.ParseFromString(arena_message->SerializeAsString()); - EXPECT_TRUE(copied.has_optional_int32()); - EXPECT_EQ(42, copied.optional_int32()); - - // Exercise UFS swap path. - TestEmptyMessage* arena_message_2 = - Arena::CreateMessage(&arena); - arena_message_2->Swap(arena_message); - copied.Clear(); - copied.ParseFromString(arena_message_2->SerializeAsString()); - EXPECT_TRUE(copied.has_optional_int32()); - EXPECT_EQ(42, copied.optional_int32()); - - // Test field manipulation. - TestEmptyMessage* arena_message_3 = - Arena::CreateMessage(&arena); - arena_message_3->mutable_unknown_fields()->AddVarint(1000, 42); - arena_message_3->mutable_unknown_fields()->AddFixed32(1001, 42); - arena_message_3->mutable_unknown_fields()->AddFixed64(1002, 42); - arena_message_3->mutable_unknown_fields()->AddLengthDelimited(1003); - arena_message_3->mutable_unknown_fields()->DeleteSubrange(0, 2); - arena_message_3->mutable_unknown_fields()->DeleteByNumber(1002); - arena_message_3->mutable_unknown_fields()->DeleteByNumber(1003); - EXPECT_TRUE(arena_message_3->unknown_fields().empty()); -} - -TEST(ArenaTest, Swap) { - Arena arena1; - Arena arena2; - TestAllTypes* arena1_message; - TestAllTypes* arena2_message; - - // Case 1: Swap(), no UFS on either message, both messages on different - // arenas. Arena pointers should remain the same after swap. - arena1_message = Arena::CreateMessage(&arena1); - arena2_message = Arena::CreateMessage(&arena2); - arena1_message->Swap(arena2_message); - EXPECT_EQ(&arena1, arena1_message->GetArena()); - EXPECT_EQ(&arena2, arena2_message->GetArena()); - - // Case 2: Swap(), UFS on one message, both messages on different arenas. - arena1_message = Arena::CreateMessage(&arena1); - arena2_message = Arena::CreateMessage(&arena2); - arena1_message->mutable_unknown_fields()->AddVarint(1, 42); - arena1_message->Swap(arena2_message); - EXPECT_EQ(&arena1, arena1_message->GetArena()); - EXPECT_EQ(&arena2, arena2_message->GetArena()); - EXPECT_EQ(0, arena1_message->unknown_fields().field_count()); - EXPECT_EQ(1, arena2_message->unknown_fields().field_count()); - EXPECT_EQ(42, arena2_message->unknown_fields().field(0).varint()); - - // Case 3: Swap(), UFS on both messages, both messages on different arenas. - arena1_message = Arena::CreateMessage(&arena1); - arena2_message = Arena::CreateMessage(&arena2); - arena1_message->mutable_unknown_fields()->AddVarint(1, 42); - arena2_message->mutable_unknown_fields()->AddVarint(2, 84); - arena1_message->Swap(arena2_message); - EXPECT_EQ(&arena1, arena1_message->GetArena()); - EXPECT_EQ(&arena2, arena2_message->GetArena()); - EXPECT_EQ(1, arena1_message->unknown_fields().field_count()); - EXPECT_EQ(1, arena2_message->unknown_fields().field_count()); - EXPECT_EQ(84, arena1_message->unknown_fields().field(0).varint()); - EXPECT_EQ(42, arena2_message->unknown_fields().field(0).varint()); -} - -TEST(ArenaTest, ReflectionSwapFields) { - Arena arena1; - Arena arena2; - TestAllTypes* arena1_message; - TestAllTypes* arena2_message; - - // Case 1: messages on different arenas, only one message is set. - arena1_message = Arena::CreateMessage(&arena1); - arena2_message = Arena::CreateMessage(&arena2); - TestUtil::SetAllFields(arena1_message); - const Reflection* reflection = arena1_message->GetReflection(); - std::vector fields; - reflection->ListFields(*arena1_message, &fields); - reflection->SwapFields(arena1_message, arena2_message, fields); - EXPECT_EQ(&arena1, arena1_message->GetArena()); - EXPECT_EQ(&arena2, arena2_message->GetArena()); - string output; - arena1_message->SerializeToString(&output); - EXPECT_EQ(0, output.size()); - TestUtil::ExpectAllFieldsSet(*arena2_message); - reflection->SwapFields(arena1_message, arena2_message, fields); - arena2_message->SerializeToString(&output); - EXPECT_EQ(0, output.size()); - TestUtil::ExpectAllFieldsSet(*arena1_message); - - // Case 2: messages on different arenas, both messages are set. - arena1_message = Arena::CreateMessage(&arena1); - arena2_message = Arena::CreateMessage(&arena2); - TestUtil::SetAllFields(arena1_message); - TestUtil::SetAllFields(arena2_message); - reflection->SwapFields(arena1_message, arena2_message, fields); - EXPECT_EQ(&arena1, arena1_message->GetArena()); - EXPECT_EQ(&arena2, arena2_message->GetArena()); - TestUtil::ExpectAllFieldsSet(*arena1_message); - TestUtil::ExpectAllFieldsSet(*arena2_message); - - // Case 3: messages on different arenas with different lifetimes. - arena1_message = Arena::CreateMessage(&arena1); - { - Arena arena3; - TestAllTypes* arena3_message = Arena::CreateMessage(&arena3); - TestUtil::SetAllFields(arena3_message); - reflection->SwapFields(arena1_message, arena3_message, fields); - } - TestUtil::ExpectAllFieldsSet(*arena1_message); - - // Case 4: one message on arena, the other on heap. - arena1_message = Arena::CreateMessage(&arena1); - TestAllTypes message; - TestUtil::SetAllFields(arena1_message); - reflection->SwapFields(arena1_message, &message, fields); - EXPECT_EQ(&arena1, arena1_message->GetArena()); - EXPECT_EQ(nullptr, message.GetArena()); - arena1_message->SerializeToString(&output); - EXPECT_EQ(0, output.size()); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(ArenaTest, SetAllocatedMessage) { - Arena arena; - TestAllTypes *arena_message = Arena::CreateMessage(&arena); - TestAllTypes::NestedMessage* nested = new TestAllTypes::NestedMessage; - nested->set_bb(118); - arena_message->set_allocated_optional_nested_message(nested); - EXPECT_EQ(118, arena_message->optional_nested_message().bb()); - - protobuf_unittest_no_arena::TestNoArenaMessage no_arena_message; - EXPECT_FALSE(no_arena_message.has_arena_message()); - no_arena_message.set_allocated_arena_message(NULL); - EXPECT_FALSE(no_arena_message.has_arena_message()); - no_arena_message.set_allocated_arena_message(new ArenaMessage); - EXPECT_TRUE(no_arena_message.has_arena_message()); -} - -TEST(ArenaTest, ReleaseMessage) { - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - arena_message->mutable_optional_nested_message()->set_bb(118); - std::unique_ptr nested( - arena_message->release_optional_nested_message()); - EXPECT_EQ(118, nested->bb()); - - TestAllTypes::NestedMessage* released_null = - arena_message->release_optional_nested_message(); - EXPECT_EQ(NULL, released_null); -} - -TEST(ArenaTest, SetAllocatedString) { - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - string* allocated_str = new string("hello"); - arena_message->set_allocated_optional_string(allocated_str); - EXPECT_EQ("hello", arena_message->optional_string()); -} - -TEST(ArenaTest, ReleaseString) { - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - arena_message->set_optional_string("hello"); - std::unique_ptr released_str( - arena_message->release_optional_string()); - EXPECT_EQ("hello", *released_str); - - // Test default value. -} - - -TEST(ArenaTest, SwapBetweenArenasWithAllFieldsSet) { - Arena arena1; - TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); - { - Arena arena2; - TestAllTypes* arena2_message = Arena::CreateMessage(&arena2); - TestUtil::SetAllFields(arena2_message); - arena2_message->Swap(arena1_message); - string output; - arena2_message->SerializeToString(&output); - EXPECT_EQ(0, output.size()); - } - TestUtil::ExpectAllFieldsSet(*arena1_message); -} - -TEST(ArenaTest, SwapBetweenArenaAndNonArenaWithAllFieldsSet) { - TestAllTypes non_arena_message; - TestUtil::SetAllFields(&non_arena_message); - { - Arena arena2; - TestAllTypes* arena2_message = Arena::CreateMessage(&arena2); - TestUtil::SetAllFields(arena2_message); - arena2_message->Swap(&non_arena_message); - TestUtil::ExpectAllFieldsSet(*arena2_message); - TestUtil::ExpectAllFieldsSet(non_arena_message); - } -} - -TEST(ArenaTest, UnsafeArenaSwap) { - Arena shared_arena; - TestAllTypes* message1 = Arena::CreateMessage(&shared_arena); - TestAllTypes* message2 = Arena::CreateMessage(&shared_arena); - TestUtil::SetAllFields(message1); - message1->UnsafeArenaSwap(message2); - TestUtil::ExpectAllFieldsSet(*message2); -} - -TEST(ArenaTest, SwapBetweenArenasUsingReflection) { - Arena arena1; - TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); - { - Arena arena2; - TestAllTypes* arena2_message = Arena::CreateMessage(&arena2); - TestUtil::SetAllFields(arena2_message); - const Reflection* r = arena2_message->GetReflection(); - r->Swap(arena1_message, arena2_message); - string output; - arena2_message->SerializeToString(&output); - EXPECT_EQ(0, output.size()); - } - TestUtil::ExpectAllFieldsSet(*arena1_message); -} - -TEST(ArenaTest, SwapBetweenArenaAndNonArenaUsingReflection) { - TestAllTypes non_arena_message; - TestUtil::SetAllFields(&non_arena_message); - { - Arena arena2; - TestAllTypes* arena2_message = Arena::CreateMessage(&arena2); - TestUtil::SetAllFields(arena2_message); - const Reflection* r = arena2_message->GetReflection(); - r->Swap(&non_arena_message, arena2_message); - TestUtil::ExpectAllFieldsSet(*arena2_message); - TestUtil::ExpectAllFieldsSet(non_arena_message); - } -} - -TEST(ArenaTest, ReleaseFromArenaMessageMakesCopy) { - TestAllTypes::NestedMessage* nested_msg = NULL; - string* nested_string = NULL; - { - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - arena_message->mutable_optional_nested_message()->set_bb(42); - *arena_message->mutable_optional_string() = "Hello"; - nested_msg = arena_message->release_optional_nested_message(); - nested_string = arena_message->release_optional_string(); - } - EXPECT_EQ(42, nested_msg->bb()); - EXPECT_EQ("Hello", *nested_string); - delete nested_msg; - delete nested_string; -} - -#ifndef GOOGLE_PROTOBUF_NO_RTTI -TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) { - TestAllTypes::NestedMessage* nested_msg = NULL; - // Note: no string: reflection API only supports releasing submessages. - { - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - arena_message->mutable_optional_nested_message()->set_bb(42); - const Reflection* r = arena_message->GetReflection(); - const FieldDescriptor* f = arena_message->GetDescriptor()->FindFieldByName( - "optional_nested_message"); - nested_msg = static_cast( - r->ReleaseMessage(arena_message, f)); - } - EXPECT_EQ(42, nested_msg->bb()); - delete nested_msg; -} -#endif // !GOOGLE_PROTOBUF_NO_RTTI - -TEST(ArenaTest, SetAllocatedAcrossArenas) { - Arena arena1; - TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); - TestAllTypes::NestedMessage* heap_submessage = - new TestAllTypes::NestedMessage(); - heap_submessage->set_bb(42); - arena1_message->set_allocated_optional_nested_message(heap_submessage); - // Should keep same object and add to arena's Own()-list. - EXPECT_EQ(heap_submessage, - arena1_message->mutable_optional_nested_message()); - { - Arena arena2; - TestAllTypes::NestedMessage* arena2_submessage = - Arena::CreateMessage(&arena2); - arena2_submessage->set_bb(42); - arena1_message->set_allocated_optional_nested_message(arena2_submessage); - EXPECT_NE(arena2_submessage, - arena1_message->mutable_optional_nested_message()); - } - - TestAllTypes::NestedMessage* arena1_submessage = - Arena::CreateMessage(&arena1); - arena1_submessage->set_bb(42); - TestAllTypes* heap_message = new TestAllTypes; - heap_message->set_allocated_optional_nested_message(arena1_submessage); - EXPECT_NE(arena1_submessage, - heap_message->mutable_optional_nested_message()); - delete heap_message; -} - -TEST(ArenaTest, SetAllocatedAcrossArenasWithReflection) { - // Same as above, with reflection. - Arena arena1; - TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); - const Reflection* r = arena1_message->GetReflection(); - const Descriptor* d = arena1_message->GetDescriptor(); - const FieldDescriptor* msg_field = d->FindFieldByName( - "optional_nested_message"); - TestAllTypes::NestedMessage* heap_submessage = - new TestAllTypes::NestedMessage(); - heap_submessage->set_bb(42); - r->SetAllocatedMessage(arena1_message, heap_submessage, msg_field); - // Should keep same object and add to arena's Own()-list. - EXPECT_EQ(heap_submessage, - arena1_message->mutable_optional_nested_message()); - { - Arena arena2; - TestAllTypes::NestedMessage* arena2_submessage = - Arena::CreateMessage(&arena2); - arena2_submessage->set_bb(42); - r->SetAllocatedMessage(arena1_message, arena2_submessage, msg_field); - EXPECT_NE(arena2_submessage, - arena1_message->mutable_optional_nested_message()); - } - - TestAllTypes::NestedMessage* arena1_submessage = - Arena::CreateMessage(&arena1); - arena1_submessage->set_bb(42); - TestAllTypes* heap_message = new TestAllTypes; - r->SetAllocatedMessage(heap_message, arena1_submessage, msg_field); - EXPECT_NE(arena1_submessage, - heap_message->mutable_optional_nested_message()); - delete heap_message; -} - -TEST(ArenaTest, AddAllocatedWithReflection) { - Arena arena1; - ArenaMessage* arena1_message = Arena::CreateMessage(&arena1); - const Reflection* r = arena1_message->GetReflection(); - const Descriptor* d = arena1_message->GetDescriptor(); - const FieldDescriptor* fd = - d->FindFieldByName("repeated_import_no_arena_message"); - // Message with cc_enable_arenas = false; - r->AddMessage(arena1_message, fd); - r->AddMessage(arena1_message, fd); - r->AddMessage(arena1_message, fd); - EXPECT_EQ(3, r->FieldSize(*arena1_message, fd)); - // Message with cc_enable_arenas = true; - fd = d->FindFieldByName("repeated_nested_message"); - r->AddMessage(arena1_message, fd); - r->AddMessage(arena1_message, fd); - r->AddMessage(arena1_message, fd); - EXPECT_EQ(3, r->FieldSize(*arena1_message, fd)); -} - -TEST(ArenaTest, RepeatedPtrFieldAddClearedTest) { - { - RepeatedPtrField repeated_field; - EXPECT_TRUE(repeated_field.empty()); - EXPECT_EQ(0, repeated_field.size()); - // Ownership is passed to repeated_field. - TestAllTypes* cleared = new TestAllTypes(); - repeated_field.AddCleared(cleared); - EXPECT_TRUE(repeated_field.empty()); - EXPECT_EQ(0, repeated_field.size()); - } - { - RepeatedPtrField repeated_field; - EXPECT_TRUE(repeated_field.empty()); - EXPECT_EQ(0, repeated_field.size()); - // Ownership is passed to repeated_field. - TestAllTypes* cleared = new TestAllTypes(); - repeated_field.AddAllocated(cleared); - EXPECT_FALSE(repeated_field.empty()); - EXPECT_EQ(1, repeated_field.size()); - } -} - -TEST(ArenaTest, AddAllocatedToRepeatedField) { - // Heap->arena case. - Arena arena1; - TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); - for (int i = 0; i < 10; i++) { - TestAllTypes::NestedMessage* heap_submessage = - new TestAllTypes::NestedMessage(); - heap_submessage->set_bb(42); - arena1_message->mutable_repeated_nested_message()-> - AddAllocated(heap_submessage); - // Should not copy object -- will use arena_->Own(). - EXPECT_EQ(heap_submessage, - &arena1_message->repeated_nested_message(i)); - EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb()); - } - - // Arena1->Arena2 case. - arena1_message->Clear(); - for (int i = 0; i < 10; i++) { - Arena arena2; - TestAllTypes::NestedMessage* arena2_submessage = - Arena::CreateMessage(&arena2); - arena2_submessage->set_bb(42); - arena1_message->mutable_repeated_nested_message()-> - AddAllocated(arena2_submessage); - // Should copy object. - EXPECT_NE(arena2_submessage, - &arena1_message->repeated_nested_message(i)); - EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb()); - } - - // Arena->heap case. - TestAllTypes* heap_message = new TestAllTypes(); - for (int i = 0; i < 10; i++) { - Arena arena2; - TestAllTypes::NestedMessage* arena2_submessage = - Arena::CreateMessage(&arena2); - arena2_submessage->set_bb(42); - heap_message->mutable_repeated_nested_message()-> - AddAllocated(arena2_submessage); - // Should copy object. - EXPECT_NE(arena2_submessage, - &heap_message->repeated_nested_message(i)); - EXPECT_EQ(42, heap_message->repeated_nested_message(i).bb()); - } - delete heap_message; - - // Heap-arena case for strings (which are not arena-allocated). - arena1_message->Clear(); - for (int i = 0; i < 10; i++) { - string* s = new string("Test"); - arena1_message->mutable_repeated_string()-> - AddAllocated(s); - // Should not copy. - EXPECT_EQ(s, &arena1_message->repeated_string(i)); - EXPECT_EQ("Test", arena1_message->repeated_string(i)); - } -} - -TEST(ArenaTest, AddAllocatedToRepeatedFieldViaReflection) { - // Heap->arena case. - Arena arena1; - TestAllTypes* arena1_message = Arena::CreateMessage(&arena1); - const Reflection* r = arena1_message->GetReflection(); - const Descriptor* d = arena1_message->GetDescriptor(); - const FieldDescriptor* fd = - d->FindFieldByName("repeated_nested_message"); - for (int i = 0; i < 10; i++) { - TestAllTypes::NestedMessage* heap_submessage = - new TestAllTypes::NestedMessage; - heap_submessage->set_bb(42); - r->AddAllocatedMessage(arena1_message, fd, heap_submessage); - // Should not copy object -- will use arena_->Own(). - EXPECT_EQ(heap_submessage, - &arena1_message->repeated_nested_message(i)); - EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb()); - } - - // Arena1->Arena2 case. - arena1_message->Clear(); - for (int i = 0; i < 10; i++) { - Arena arena2; - TestAllTypes::NestedMessage* arena2_submessage = - Arena::CreateMessage(&arena2); - arena2_submessage->set_bb(42); - r->AddAllocatedMessage(arena1_message, fd, arena2_submessage); - // Should copy object. - EXPECT_NE(arena2_submessage, - &arena1_message->repeated_nested_message(i)); - EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb()); - } - - // Arena->heap case. - TestAllTypes* heap_message = new TestAllTypes; - for (int i = 0; i < 10; i++) { - Arena arena2; - TestAllTypes::NestedMessage* arena2_submessage = - Arena::CreateMessage(&arena2); - arena2_submessage->set_bb(42); - r->AddAllocatedMessage(heap_message, fd, arena2_submessage); - // Should copy object. - EXPECT_NE(arena2_submessage, - &heap_message->repeated_nested_message(i)); - EXPECT_EQ(42, heap_message->repeated_nested_message(i).bb()); - } - delete heap_message; -} - -TEST(ArenaTest, ReleaseLastRepeatedField) { - // Release from arena-allocated repeated field and ensure that returned object - // is heap-allocated. - Arena arena; - TestAllTypes* arena_message = Arena::CreateMessage(&arena); - for (int i = 0; i < 10; i++) { - TestAllTypes::NestedMessage* nested = - Arena::CreateMessage(&arena); - nested->set_bb(42); - arena_message->mutable_repeated_nested_message()->AddAllocated(nested); - } - - for (int i = 0; i < 10; i++) { - const TestAllTypes::NestedMessage *orig_submessage = - &arena_message->repeated_nested_message(10 - 1 - i); // last element - TestAllTypes::NestedMessage *released = - arena_message->mutable_repeated_nested_message()->ReleaseLast(); - EXPECT_NE(released, orig_submessage); - EXPECT_EQ(42, released->bb()); - delete released; - } - - // Test UnsafeArenaReleaseLast(). - for (int i = 0; i < 10; i++) { - TestAllTypes::NestedMessage* nested = - Arena::CreateMessage(&arena); - nested->set_bb(42); - arena_message->mutable_repeated_nested_message()->AddAllocated(nested); - } - - for (int i = 0; i < 10; i++) { - const TestAllTypes::NestedMessage *orig_submessage = - &arena_message->repeated_nested_message(10 - 1 - i); // last element - TestAllTypes::NestedMessage *released = - arena_message->mutable_repeated_nested_message()-> - UnsafeArenaReleaseLast(); - EXPECT_EQ(released, orig_submessage); - EXPECT_EQ(42, released->bb()); - // no delete -- |released| is on the arena. - } - - // Test string case as well. ReleaseLast() in this case must copy the string, - // even though it was originally heap-allocated and its pointer was simply - // appended to the repeated field's internal vector, because the string was - // placed on the arena's destructor list and cannot be removed from that list - // (so the arena permanently owns the original instance). - arena_message->Clear(); - for (int i = 0; i < 10; i++) { - string* s = new string("Test"); - arena_message->mutable_repeated_string()->AddAllocated(s); - } - for (int i = 0; i < 10; i++) { - const string* orig_element = &arena_message->repeated_string(10 - 1 - i); - string* released = arena_message->mutable_repeated_string()->ReleaseLast(); - EXPECT_NE(released, orig_element); - EXPECT_EQ("Test", *released); - delete released; - } -} - -TEST(ArenaTest, UnsafeArenaReleaseAdd) { - // Use unsafe_arena_release() and unsafe_arena_set_allocated() to transfer an - // arena-allocated string from one message to another. - const char kContent[] = "Test content"; - - Arena arena; - TestAllTypes* message1 = Arena::CreateMessage(&arena); - TestAllTypes* message2 = Arena::CreateMessage(&arena); - string* arena_string = Arena::Create(&arena); - *arena_string = kContent; - - message1->unsafe_arena_set_allocated_optional_string(arena_string); - message2->unsafe_arena_set_allocated_optional_string( - message1->unsafe_arena_release_optional_string()); - EXPECT_EQ(kContent, message2->optional_string()); -} - -TEST(ArenaTest, UnsafeArenaAddAllocated) { - Arena arena; - TestAllTypes* message = Arena::CreateMessage(&arena); - for (int i = 0; i < 10; i++) { - string* arena_string = Arena::Create(&arena); - message->mutable_repeated_string()->UnsafeArenaAddAllocated(arena_string); - EXPECT_EQ(arena_string, message->mutable_repeated_string(i)); - } -} - -TEST(ArenaTest, UnsafeArenaRelease) { - Arena arena; - TestAllTypes* message = Arena::CreateMessage(&arena); - - string* s = new string("test string"); - message->unsafe_arena_set_allocated_optional_string(s); - EXPECT_TRUE(message->has_optional_string()); - EXPECT_EQ("test string", message->optional_string()); - s = message->unsafe_arena_release_optional_string(); - EXPECT_FALSE(message->has_optional_string()); - delete s; - - s = new string("test string"); - message->unsafe_arena_set_allocated_oneof_string(s); - EXPECT_TRUE(message->has_oneof_string()); - EXPECT_EQ("test string", message->oneof_string()); - s = message->unsafe_arena_release_oneof_string(); - EXPECT_FALSE(message->has_oneof_string()); - delete s; -} - -TEST(ArenaTest, OneofMerge) { - Arena arena; - TestAllTypes* message0 = Arena::CreateMessage(&arena); - TestAllTypes* message1 = Arena::CreateMessage(&arena); - - message0->unsafe_arena_set_allocated_oneof_string(new string("x")); - ASSERT_TRUE(message0->has_oneof_string()); - message1->unsafe_arena_set_allocated_oneof_string(new string("y")); - ASSERT_TRUE(message1->has_oneof_string()); - EXPECT_EQ("x", message0->oneof_string()); - EXPECT_EQ("y", message1->oneof_string()); - message0->MergeFrom(*message1); - EXPECT_EQ("y", message0->oneof_string()); - EXPECT_EQ("y", message1->oneof_string()); - delete message0->unsafe_arena_release_oneof_string(); - delete message1->unsafe_arena_release_oneof_string(); -} - -TEST(ArenaTest, ArenaOneofReflection) { - Arena arena; - TestAllTypes* message = Arena::CreateMessage(&arena); - const Descriptor* desc = message->GetDescriptor(); - const Reflection* refl = message->GetReflection(); - - const FieldDescriptor* string_field = desc->FindFieldByName( - "oneof_string"); - const FieldDescriptor* msg_field = desc->FindFieldByName( - "oneof_nested_message"); - const OneofDescriptor* oneof = desc->FindOneofByName( - "oneof_field"); - - refl->SetString(message, string_field, "Test value"); - EXPECT_TRUE(refl->HasOneof(*message, oneof)); - refl->ClearOneof(message, oneof); - EXPECT_FALSE(refl->HasOneof(*message, oneof)); - - Message* submsg = refl->MutableMessage(message, msg_field); - EXPECT_TRUE(refl->HasOneof(*message, oneof)); - refl->ClearOneof(message, oneof); - EXPECT_FALSE(refl->HasOneof(*message, oneof)); - refl->MutableMessage(message, msg_field); - EXPECT_TRUE(refl->HasOneof(*message, oneof)); - submsg = refl->ReleaseMessage(message, msg_field); - EXPECT_FALSE(refl->HasOneof(*message, oneof)); - EXPECT_TRUE(submsg->GetArena() == NULL); - delete submsg; -} - -void TestSwapRepeatedField(Arena* arena1, Arena* arena2) { - // Test "safe" (copying) semantics for direct Swap() on RepeatedPtrField - // between arenas. - RepeatedPtrField field1(arena1); - RepeatedPtrField field2(arena2); - for (int i = 0; i < 10; i++) { - TestAllTypes* t = Arena::CreateMessage(arena1); - t->set_optional_string("field1"); - t->set_optional_int32(i); - if (arena1 != NULL) { - field1.UnsafeArenaAddAllocated(t); - } else { - field1.AddAllocated(t); - } - } - for (int i = 0; i < 5; i++) { - TestAllTypes* t = Arena::CreateMessage(arena2); - t->set_optional_string("field2"); - t->set_optional_int32(i); - if (arena2 != NULL) { - field2.UnsafeArenaAddAllocated(t); - } else { - field2.AddAllocated(t); - } - } - field1.Swap(&field2); - EXPECT_EQ(5, field1.size()); - EXPECT_EQ(10, field2.size()); - EXPECT_TRUE(string("field1") == field2.Get(0).optional_string()); - EXPECT_TRUE(string("field2") == field1.Get(0).optional_string()); - // Ensure that fields retained their original order: - for (int i = 0; i < field1.size(); i++) { - EXPECT_EQ(i, field1.Get(i).optional_int32()); - } - for (int i = 0; i < field2.size(); i++) { - EXPECT_EQ(i, field2.Get(i).optional_int32()); - } -} - -TEST(ArenaTest, SwapRepeatedField) { - Arena arena; - TestSwapRepeatedField(&arena, &arena); -} - -TEST(ArenaTest, SwapRepeatedFieldWithDifferentArenas) { - Arena arena1; - Arena arena2; - TestSwapRepeatedField(&arena1, &arena2); -} - -TEST(ArenaTest, SwapRepeatedFieldWithNoArenaOnRightHandSide) { - Arena arena; - TestSwapRepeatedField(&arena, NULL); -} - -TEST(ArenaTest, SwapRepeatedFieldWithNoArenaOnLeftHandSide) { - Arena arena; - TestSwapRepeatedField(NULL, &arena); -} - -TEST(ArenaTest, ExtensionsOnArena) { - Arena arena; - // Ensure no leaks. - TestAllExtensions* message_ext = - Arena::CreateMessage(&arena); - message_ext->SetExtension( - protobuf_unittest::optional_int32_extension, 42); - message_ext->SetExtension( - protobuf_unittest::optional_string_extension, string("test")); - message_ext->MutableExtension( - protobuf_unittest::optional_nested_message_extension)->set_bb(42); -} - -TEST(ArenaTest, RepeatedFieldOnArena) { - // Preallocate an initial arena block to avoid mallocs during hooked region. - std::vector arena_block(1024 * 1024); - ArenaOptions options; - options.initial_block = &arena_block[0]; - options.initial_block_size = arena_block.size(); - Arena arena(options); - - { - internal::NoHeapChecker no_heap; - - // Fill some repeated fields on the arena to test for leaks. Also verify no - // memory allocations. - RepeatedField repeated_int32(&arena); - RepeatedPtrField repeated_message(&arena); - for (int i = 0; i < 100; i++) { - repeated_int32.Add(42); - repeated_message.Add()->set_optional_int32(42); - EXPECT_EQ(&arena, repeated_message.Get(0).GetArena()); - const TestAllTypes* msg_in_repeated_field = &repeated_message.Get(0); - TestAllTypes* msg = repeated_message.UnsafeArenaReleaseLast(); - EXPECT_EQ(msg_in_repeated_field, msg); - } - - // UnsafeArenaExtractSubrange (i) should not leak and (ii) should return - // on-arena pointers. - for (int i = 0; i < 10; i++) { - repeated_message.Add()->set_optional_int32(42); - } - TestAllTypes* extracted_messages[5]; - repeated_message.UnsafeArenaExtractSubrange(0, 5, extracted_messages); - EXPECT_EQ(&arena, repeated_message.Get(0).GetArena()); - EXPECT_EQ(5, repeated_message.size()); - } - - // Now, outside the scope of the NoHeapChecker, test ExtractSubrange's copying - // semantics. - { - RepeatedPtrField repeated_message(&arena); - for (int i = 0; i < 100; i++) { - repeated_message.Add()->set_optional_int32(42); - } - - TestAllTypes* extracted_messages[5]; - // ExtractSubrange should copy to the heap. - repeated_message.ExtractSubrange(0, 5, extracted_messages); - EXPECT_EQ(NULL, extracted_messages[0]->GetArena()); - // We need to free the heap-allocated messages to prevent a leak. - for (int i = 0; i < 5; i++) { - delete extracted_messages[i]; - extracted_messages[i] = NULL; - } - } - - // Now check that we can create RepeatedFields/RepeatedPtrFields themselves on - // the arena. They have the necessary type traits so that they can behave like - // messages in this way. This is useful for higher-level generic templated - // code that may allocate messages or repeated fields of messages on an arena. - { - RepeatedPtrField* repeated_ptr_on_arena = - Arena::CreateMessage< RepeatedPtrField >(&arena); - for (int i = 0; i < 10; i++) { - // Add some elements and let the leak-checker ensure that everything is - // freed. - repeated_ptr_on_arena->Add(); - } - - RepeatedField* repeated_int_on_arena = - Arena::CreateMessage< RepeatedField >(&arena); - for (int i = 0; i < 100; i++) { - repeated_int_on_arena->Add(i); - } - - } - - arena.Reset(); -} - - -#ifndef GOOGLE_PROTOBUF_NO_RTTI -TEST(ArenaTest, MutableMessageReflection) { - Arena arena; - TestAllTypes* message = Arena::CreateMessage(&arena); - const Reflection* r = message->GetReflection(); - const Descriptor* d = message->GetDescriptor(); - const FieldDescriptor* field = d->FindFieldByName("optional_nested_message"); - TestAllTypes::NestedMessage* submessage = - static_cast( - r->MutableMessage(message, field)); - TestAllTypes::NestedMessage* submessage_expected = - message->mutable_optional_nested_message(); - - EXPECT_EQ(submessage_expected, submessage); - EXPECT_EQ(&arena, submessage->GetArena()); - - const FieldDescriptor* oneof_field = d->FindFieldByName("oneof_nested_message"); - submessage = static_cast( - r->MutableMessage(message, oneof_field)); - submessage_expected = message->mutable_oneof_nested_message(); - - EXPECT_EQ(submessage_expected, submessage); - EXPECT_EQ(&arena, submessage->GetArena()); -} -#endif // !GOOGLE_PROTOBUF_NO_RTTI - - -void FillArenaAwareFields(TestAllTypes* message) { - string test_string = "hello world"; - message->set_optional_int32(42); - message->set_optional_string(test_string); - message->set_optional_bytes(test_string); - message->mutable_optional_nested_message()->set_bb(42); - - message->set_oneof_uint32(42); - message->mutable_oneof_nested_message()->set_bb(42); - message->set_oneof_string(test_string); - message->set_oneof_bytes(test_string); - - message->add_repeated_int32(42); - // No repeated string: not yet arena-aware. - message->add_repeated_nested_message()->set_bb(42); - message->mutable_optional_lazy_message()->set_bb(42); -} - -// Test: no allocations occur on heap while touching all supported field types. -TEST(ArenaTest, NoHeapAllocationsTest) { - // Allocate a large initial block to avoid mallocs during hooked test. - std::vector arena_block(128 * 1024); - ArenaOptions options; - options.initial_block = &arena_block[0]; - options.initial_block_size = arena_block.size(); - Arena arena(options); - - { - - TestAllTypes* message = Arena::CreateMessage(&arena); - FillArenaAwareFields(message); - } - - arena.Reset(); -} - -TEST(ArenaTest, ParseCorruptedString) { - TestAllTypes message; - TestUtil::SetAllFields(&message); - TestParseCorruptedString(message); - TestParseCorruptedString(message); -} - -#ifndef GOOGLE_PROTOBUF_NO_RTTI -// Test construction on an arena via generic MessageLite interface. We should be -// able to successfully deserialize on the arena without incurring heap -// allocations, i.e., everything should still be arena-allocation-aware. -TEST(ArenaTest, MessageLiteOnArena) { - std::vector arena_block(128 * 1024); - ArenaOptions options; - options.initial_block = &arena_block[0]; - options.initial_block_size = arena_block.size(); - Arena arena(options); - const google::protobuf::MessageLite* prototype = &TestAllTypes::default_instance(); - - TestAllTypes initial_message; - FillArenaAwareFields(&initial_message); - string serialized; - initial_message.SerializeToString(&serialized); - - { - - google::protobuf::MessageLite* generic_message = prototype->New(&arena); - EXPECT_TRUE(generic_message != NULL); - EXPECT_EQ(&arena, generic_message->GetArena()); - EXPECT_TRUE(generic_message->ParseFromString(serialized)); - TestAllTypes* deserialized = static_cast(generic_message); - EXPECT_EQ(42, deserialized->optional_int32()); - } - - arena.Reset(); -} -#endif // !GOOGLE_PROTOBUF_NO_RTTI - - -// RepeatedField should support non-POD types, and invoke constructors and -// destructors appropriately, because it's used this way by lots of other code -// (even if this was not its original intent). -TEST(ArenaTest, RepeatedFieldWithNonPODType) { - { - RepeatedField field_on_heap; - for (int i = 0; i < 100; i++) { - *field_on_heap.Add() = "test string long enough to exceed inline buffer"; - } - } - { - Arena arena; - RepeatedField field_on_arena(&arena); - for (int i = 0; i < 100; i++) { - *field_on_arena.Add() = "test string long enough to exceed inline buffer"; - } - } -} - -// Align n to next multiple of 8 -uint64 Align8(uint64 n) { return (n + 7) & -8; } - -TEST(ArenaTest, SpaceAllocated_and_Used) { - ArenaOptions options; - options.start_block_size = 256; - options.max_block_size = 8192; - Arena arena_1(options); - EXPECT_EQ(0, arena_1.SpaceAllocated()); - EXPECT_EQ(0, arena_1.SpaceUsed()); - EXPECT_EQ(0, arena_1.Reset()); - ::google::protobuf::Arena::CreateArray(&arena_1, 320); - // Arena will allocate slightly more than 320 for the block headers. - EXPECT_LE(320, arena_1.SpaceAllocated()); - EXPECT_EQ(Align8(320), arena_1.SpaceUsed()); - EXPECT_LE(320, arena_1.Reset()); - - // Test with initial block. - std::vector arena_block(1024); - options.initial_block = &arena_block[0]; - options.initial_block_size = arena_block.size(); - Arena arena_2(options); - EXPECT_EQ(1024, arena_2.SpaceAllocated()); - EXPECT_EQ(0, arena_2.SpaceUsed()); - EXPECT_EQ(1024, arena_2.Reset()); - ::google::protobuf::Arena::CreateArray(&arena_2, 55); - EXPECT_EQ(1024, arena_2.SpaceAllocated()); - EXPECT_EQ(Align8(55), arena_2.SpaceUsed()); - EXPECT_EQ(1024, arena_2.Reset()); - - // Reset options to test doubling policy explicitly. - options.initial_block = NULL; - options.initial_block_size = 0; - Arena arena_3(options); - EXPECT_EQ(0, arena_3.SpaceUsed()); - ::google::protobuf::Arena::CreateArray(&arena_3, 160); - EXPECT_EQ(256, arena_3.SpaceAllocated()); - EXPECT_EQ(Align8(160), arena_3.SpaceUsed()); - ::google::protobuf::Arena::CreateArray(&arena_3, 70); - EXPECT_EQ(256 + 512, arena_3.SpaceAllocated()); - EXPECT_EQ(Align8(160) + Align8(70), arena_3.SpaceUsed()); - EXPECT_EQ(256 + 512, arena_3.Reset()); -} - -TEST(ArenaTest, Alignment) { - ::google::protobuf::Arena arena; - for (int i = 0; i < 200; i++) { - void* p = ::google::protobuf::Arena::CreateArray(&arena, i); - GOOGLE_CHECK_EQ(reinterpret_cast(p) % 8, 0) << i << ": " << p; - } -} - -TEST(ArenaTest, BlockSizeSmallerThanAllocation) { - for (size_t i = 0; i <= 8; ++i) { - ::google::protobuf::ArenaOptions opt; - opt.start_block_size = opt.max_block_size = i; - ::google::protobuf::Arena arena(opt); - - *::google::protobuf::Arena::Create(&arena) = 42; - EXPECT_GE(arena.SpaceAllocated(), 8); - EXPECT_EQ(8, arena.SpaceUsed()); - - *::google::protobuf::Arena::Create(&arena) = 42; - EXPECT_GE(arena.SpaceAllocated(), 16); - EXPECT_EQ(16, arena.SpaceUsed()); - } -} - -TEST(ArenaTest, GetArenaShouldReturnTheArenaForArenaAllocatedMessages) { - ::google::protobuf::Arena arena; - ArenaMessage* message = Arena::CreateMessage(&arena); - const ArenaMessage* const_pointer_to_message = message; - EXPECT_EQ(&arena, Arena::GetArena(message)); - EXPECT_EQ(&arena, Arena::GetArena(const_pointer_to_message)); -} - -TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaAllocatedMessages) { - ArenaMessage message; - const ArenaMessage* const_pointer_to_message = &message; - EXPECT_EQ(NULL, Arena::GetArena(&message)); - EXPECT_EQ(NULL, Arena::GetArena(const_pointer_to_message)); -} - -TEST(ArenaTest, AddCleanup) { - ::google::protobuf::Arena arena; - for (int i = 0; i < 100; i++) { - arena.Own(new int); - } -} - -TEST(ArenaTest, UnsafeSetAllocatedOnArena) { - ::google::protobuf::Arena arena; - TestAllTypes* message = Arena::CreateMessage(&arena); - EXPECT_FALSE(message->has_optional_string()); - - string owned_string = "test with long enough content to heap-allocate"; - message->unsafe_arena_set_allocated_optional_string(&owned_string); - EXPECT_TRUE(message->has_optional_string()); - - message->unsafe_arena_set_allocated_optional_string(NULL); - EXPECT_FALSE(message->has_optional_string()); -} - -// A helper utility class to only contain static hook functions, some -// counters to be used to verify the counters have been called and a cookie -// value to be verified. -class ArenaHooksTestUtil { - public: - static void* on_init(::google::protobuf::Arena* arena) { - ++num_init; - int* cookie = new int(kCookieValue); - return static_cast(cookie); - } - - static void on_allocation(const std::type_info* /*unused*/, uint64 alloc_size, - void* cookie) { - ++num_allocations; - int cookie_value = *static_cast(cookie); - EXPECT_EQ(kCookieValue, cookie_value); - } - - static void on_reset(::google::protobuf::Arena* arena, void* cookie, - uint64 space_used) { - ++num_reset; - int cookie_value = *static_cast(cookie); - EXPECT_EQ(kCookieValue, cookie_value); - } - - static void on_destruction(::google::protobuf::Arena* arena, void* cookie, - uint64 space_used) { - ++num_destruct; - int cookie_value = *static_cast(cookie); - EXPECT_EQ(kCookieValue, cookie_value); - delete static_cast(cookie); - } - - static const int kCookieValue = 999; - static uint32 num_init; - static uint32 num_allocations; - static uint32 num_reset; - static uint32 num_destruct; -}; -uint32 ArenaHooksTestUtil::num_init = 0; -uint32 ArenaHooksTestUtil::num_allocations = 0; -uint32 ArenaHooksTestUtil::num_reset = 0; -uint32 ArenaHooksTestUtil::num_destruct = 0; -const int ArenaHooksTestUtil::kCookieValue; - -class ArenaOptionsTestFriend { - public: - static void Set(::google::protobuf::ArenaOptions* options) { - options->on_arena_init = ArenaHooksTestUtil::on_init; - options->on_arena_allocation = ArenaHooksTestUtil::on_allocation; - options->on_arena_reset = ArenaHooksTestUtil::on_reset; - options->on_arena_destruction = ArenaHooksTestUtil::on_destruction; - } -}; - -// Test the hooks are correctly called and that the cookie is passed. -TEST(ArenaTest, ArenaHooksSanity) { - ::google::protobuf::ArenaOptions options; - ArenaOptionsTestFriend::Set(&options); - - // Scope for defining the arena - { - ::google::protobuf::Arena arena(options); - EXPECT_EQ(1, ArenaHooksTestUtil::num_init); - EXPECT_EQ(0, ArenaHooksTestUtil::num_allocations); - ::google::protobuf::Arena::Create(&arena); - if (std::is_trivially_destructible::value) { - EXPECT_EQ(1, ArenaHooksTestUtil::num_allocations); - } else { - EXPECT_EQ(2, ArenaHooksTestUtil::num_allocations); - } - arena.Reset(); - arena.Reset(); - EXPECT_EQ(2, ArenaHooksTestUtil::num_reset); - } - EXPECT_EQ(3, ArenaHooksTestUtil::num_reset); - EXPECT_EQ(1, ArenaHooksTestUtil::num_destruct); -} - - -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/arenastring.cc b/windows/include/google/protobuf/arenastring.cc deleted file mode 100644 index 7f33a0c86..000000000 --- a/windows/include/google/protobuf/arenastring.cc +++ /dev/null @@ -1,43 +0,0 @@ -// 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. - -// The ArenaString implementation is not included in the open-source release. Do -// not include this file in the distribution. - -#include - -namespace google { -namespace protobuf { -namespace internal { - - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/arenastring.h b/windows/include/google/protobuf/arenastring.h index 168fc972b..38c36378c 100644 --- a/windows/include/google/protobuf/arenastring.h +++ b/windows/include/google/protobuf/arenastring.h @@ -32,372 +32,389 @@ #define GOOGLE_PROTOBUF_ARENASTRING_H__ #include +#include +#include -#include -#include -#include #include -#include +#include +#include +#include + +#include + +#ifdef SWIG +#error "You cannot SWIG proto headers" +#endif -// This is the implementation of arena string fields written for the open-source -// release. The ArenaStringPtr struct below is an internal implementation class -// and *should not be used* by user code. It is used to collect string -// operations together into one place and abstract away the underlying -// string-field pointer representation, so that (for example) an alternate -// implementation that knew more about ::std::string's internals could integrate more -// closely with the arena allocator. namespace google { namespace protobuf { namespace internal { template -class TaggedPtr { +class ExplicitlyConstructed; + +class SwapFieldHelper; + +// Lazy string instance to support string fields with non-empty default. +// These are initialized on the first call to .get(). +class PROTOBUF_EXPORT LazyString { public: - void Set(T* p) { ptr_ = reinterpret_cast(p); } - T* Get() const { return reinterpret_cast(ptr_); } + // We explicitly make LazyString an aggregate so that MSVC can do constant + // initialization on it without marking it `constexpr`. + // We do not want to use `constexpr` because it makes it harder to have extern + // storage for it and causes library bloat. + struct InitValue { + const char* ptr; + size_t size; + }; + // We keep a union of the initialization value and the std::string to save on + // space. We don't need the string array after Init() is done. + union { + mutable InitValue init_value_; + alignas(std::string) mutable char string_buf_[sizeof(std::string)]; + }; + mutable std::atomic inited_; - bool IsNull() { return ptr_ == 0; } - - private: - uintptr_t ptr_; -}; - -struct LIBPROTOBUF_EXPORT ArenaStringPtr { - inline void Set(const ::std::string* default_value, - const ::std::string& value, ::google::protobuf::Arena* arena) { - if (ptr_ == default_value) { - CreateInstance(arena, &value); - } else { - *ptr_ = value; - } + const std::string& get() const { + // This check generates less code than a call-once invocation. + auto* res = inited_.load(std::memory_order_acquire); + if (PROTOBUF_PREDICT_FALSE(res == nullptr)) return Init(); + return *res; } - inline void SetLite(const ::std::string* default_value, - const ::std::string& value, - ::google::protobuf::Arena* arena) { - Set(default_value, value, arena); + private: + // Initialize the string in `string_buf_`, update `inited_` and return it. + // We return it here to avoid having to read it again in the inlined code. + const std::string& Init() const; +}; + +template +class TaggedPtr { + public: + TaggedPtr() = default; + explicit constexpr TaggedPtr(const ExplicitlyConstructed* ptr) + : ptr_(const_cast*>(ptr)) {} + + void SetTagged(T* p) { + Set(p); + ptr_ = reinterpret_cast(as_int() | 1); + } + void Set(T* p) { ptr_ = p; } + T* Get() const { return reinterpret_cast(as_int() & -2); } + bool IsTagged() const { return as_int() & 1; } + + // Returned value is only safe to dereference if IsTagged() == false. + // It is safe to compare. + T* UnsafeGet() const { return static_cast(ptr_); } + + bool IsNull() { return ptr_ == nullptr; } + + private: + uintptr_t as_int() const { return reinterpret_cast(ptr_); } + void* ptr_; +}; + +static_assert(std::is_trivial>::value, + "TaggedPtr must be trivial"); + +// This class encapsulates a pointer to a std::string with or without a donated +// buffer, tagged by bottom bit. It is a high-level wrapper that almost directly +// corresponds to the interface required by string fields in generated +// code. It replaces the old std::string* pointer in such cases. +// +// The object has different but similar code paths for when the default value is +// the empty string and when it is a non-empty string. +// The empty string is handled different throughout the library and there is a +// single global instance of it we can share. +// +// For fields with an empty string default value, there are three distinct +// states: +// +// - Pointer set to 'String' tag (LSB is 0), equal to +// &GetEmptyStringAlreadyInited(): field is set to its default value. Points +// to a true std::string*, but we do not own that std::string* (it's a +// globally shared instance). +// +// - Pointer set to 'String' tag (LSB is 0), but not equal to the global empty +// string: field points to a true std::string* instance that we own. This +// instance is either on the heap or on the arena (i.e. registered on +// free()/destructor-call list) as appropriate. +// +// - Pointer set to 'DonatedString' tag (LSB is 1): points to a std::string +// instance with a buffer on the arena (arena is never nullptr in this case). +// +// For fields with a non-empty string default value, there are three distinct +// states: +// +// - Pointer set to 'String' tag (LSB is 0), equal to `nullptr`: +// Field is in "default" mode and does not point to any actual instance. +// Methods that might need to create an instance of the object will pass a +// `const LazyString&` for it. +// +// - Pointer set to 'String' tag (LSB is 0), but not equal to `nullptr`: +// field points to a true std::string* instance that we own. This instance is +// either on the heap or on the arena (i.e. registered on +// free()/destructor-call list) as appropriate. +// +// - Pointer set to 'DonatedString' tag (LSB is 1): points to a std::string +// instance with a buffer on the arena (arena is never nullptr in this case). +// +// Generated code and reflection code both ensure that ptr_ is never null for +// fields with an empty default. +// Because ArenaStringPtr is used in oneof unions, its constructor is a NOP and +// so the field is always manually initialized via method calls. +// +// Side-note: why pass information about the default on every API call? Because +// we don't want to hold it in a member variable, or else this would go into +// every proto message instance. This would be a huge waste of space, since the +// default instance pointer is typically a global (static class field). We want +// the generated code to be as efficient as possible, and if we take +// the default value information as a parameter that's in practice taken from a +// static class field, and compare ptr_ to the default value, we end up with a +// single "cmp %reg, GLOBAL" in the resulting machine code. (Note that this also +// requires the String tag to be 0 so we can avoid the mask before comparing.) +struct PROTOBUF_EXPORT ArenaStringPtr { + ArenaStringPtr() = default; + explicit constexpr ArenaStringPtr( + const ExplicitlyConstructed* default_value) + : tagged_ptr_(default_value) {} + + // Some methods below are overloaded on a `default_value` and on tags. + // The tagged overloads help reduce code size in the callers in generated + // code, while the `default_value` overloads are useful from reflection. + // By-value empty struct arguments are elided in the ABI. + struct EmptyDefault {}; + struct NonEmptyDefault {}; + + void Set(const std::string* default_value, ConstStringParam value, + ::google::protobuf::Arena* arena); + void Set(const std::string* default_value, std::string&& value, + ::google::protobuf::Arena* arena); + void Set(EmptyDefault, ConstStringParam value, ::google::protobuf::Arena* arena); + void Set(EmptyDefault, std::string&& value, ::google::protobuf::Arena* arena); + void Set(NonEmptyDefault, ConstStringParam value, ::google::protobuf::Arena* arena); + void Set(NonEmptyDefault, std::string&& value, ::google::protobuf::Arena* arena); + template + void Set(FirstParam p1, const char* str, ::google::protobuf::Arena* arena) { + Set(p1, ConstStringParam(str), arena); + } + template + void Set(FirstParam p1, const char* str, size_t size, + ::google::protobuf::Arena* arena) { + ConstStringParam sp{str, size}; // for string_view and `const string &` + Set(p1, sp, arena); + } + template + void Set(FirstParam p1, + std::reference_wrapper const_string_ref, + ::google::protobuf::Arena* arena) { + Set(p1, const_string_ref.get(), arena); + } + + template + void SetBytes(FirstParam p1, SecondParam&& p2, ::google::protobuf::Arena* arena) { + Set(p1, static_cast(p2), arena); + } + template + void SetBytes(FirstParam p1, const void* str, size_t size, + ::google::protobuf::Arena* arena) { + // must work whether ConstStringParam is string_view or `const string &` + ConstStringParam sp{static_cast(str), size}; + Set(p1, sp, arena); } // Basic accessors. - inline const ::std::string& Get() const { return *ptr_; } - - inline ::std::string* Mutable(const ::std::string* default_value, - ::google::protobuf::Arena* arena) { - if (ptr_ == default_value) { - CreateInstance(arena, default_value); - } - return ptr_; + PROTOBUF_NDEBUG_INLINE const std::string& Get() const { + // Unconditionally mask away the tag. + return *tagged_ptr_.Get(); + } + PROTOBUF_NDEBUG_INLINE const std::string* GetPointer() const { + // Unconditionally mask away the tag. + return tagged_ptr_.Get(); } - // Release returns a ::std::string* instance that is heap-allocated and is not - // Own()'d by any arena. If the field was not set, it returns NULL. The caller - // retains ownership. Clears this field back to NULL state. Used to implement - // release_() methods on generated classes. - inline ::std::string* Release(const ::std::string* default_value, - ::google::protobuf::Arena* arena) { - if (ptr_ == default_value) { - return NULL; - } - return ReleaseNonDefault(default_value, arena); - } + // For fields with an empty default value. + std::string* Mutable(EmptyDefault, ::google::protobuf::Arena* arena); + // For fields with a non-empty default value. + std::string* Mutable(const LazyString& default_value, ::google::protobuf::Arena* arena); - // Similar to Release, but ptr_ cannot be the default_value. - inline ::std::string* ReleaseNonDefault( - const ::std::string* default_value, ::google::protobuf::Arena* arena) { - GOOGLE_DCHECK(!IsDefault(default_value)); - ::std::string* released = NULL; - if (arena != NULL) { - // ptr_ is owned by the arena. - released = new ::std::string; - released->swap(*ptr_); - } else { - released = ptr_; - } - ptr_ = const_cast< ::std::string* >(default_value); - return released; - } + // Release returns a std::string* instance that is heap-allocated and is not + // Own()'d by any arena. If the field is not set, this returns nullptr. The + // caller retains ownership. Clears this field back to nullptr state. Used to + // implement release_() methods on generated classes. + PROTOBUF_NODISCARD std::string* Release(const std::string* default_value, + ::google::protobuf::Arena* arena); + PROTOBUF_NODISCARD std::string* ReleaseNonDefault( + const std::string* default_value, ::google::protobuf::Arena* arena); - // UnsafeArenaRelease returns a ::std::string*, but it may be arena-owned (i.e. - // have its destructor already registered) if arena != NULL. If the field was - // not set, this returns NULL. This method clears this field back to NULL - // state. Used to implement unsafe_arena_release_() methods on - // generated classes. - inline ::std::string* UnsafeArenaRelease(const ::std::string* default_value, - ::google::protobuf::Arena* /* arena */) { - if (ptr_ == default_value) { - return NULL; - } - ::std::string* released = ptr_; - ptr_ = const_cast< ::std::string* >(default_value); - return released; - } - - // Takes a string that is heap-allocated, and takes ownership. The string's - // destructor is registered with the arena. Used to implement + // Takes a std::string that is heap-allocated, and takes ownership. The + // std::string's destructor is registered with the arena. Used to implement // set_allocated_ in generated classes. - inline void SetAllocated(const ::std::string* default_value, - ::std::string* value, ::google::protobuf::Arena* arena) { - if (arena == NULL && ptr_ != default_value) { - Destroy(default_value, arena); - } - if (value != NULL) { - ptr_ = value; - if (arena != NULL) { - arena->Own(value); - } - } else { - ptr_ = const_cast< ::std::string* >(default_value); - } - } - - // Takes a string that has lifetime equal to the arena's lifetime. The arena - // must be non-null. It is safe only to pass this method a value returned by - // UnsafeArenaRelease() on another field of a message in the same arena. Used - // to implement unsafe_arena_set_allocated_ in generated classes. - inline void UnsafeArenaSetAllocated(const ::std::string* default_value, - ::std::string* value, - ::google::protobuf::Arena* /* arena */) { - if (value != NULL) { - ptr_ = value; - } else { - ptr_ = const_cast< ::std::string* >(default_value); - } - } + void SetAllocated(const std::string* default_value, std::string* value, + ::google::protobuf::Arena* arena); // Swaps internal pointers. Arena-safety semantics: this is guarded by the // logic in Swap()/UnsafeArenaSwap() at the message level, so this method is // 'unsafe' if called directly. - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) { - std::swap(ptr_, other->ptr_); - } - GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap( - ArenaStringPtr* other, const ::std::string* default_value, Arena* arena) { -#ifndef NDEBUG - // For debug builds, we swap the contents of the string, rather than the - // string instances themselves. This invalidates previously taken const - // references that are (per our documentation) invalidated by calling Swap() - // on the message. - // - // If both strings are the default_value, swapping is uninteresting. - // Otherwise, we use ArenaStringPtr::Mutable() to access the string, to - // ensure that we do not try to mutate default_value itself. - if (IsDefault(default_value) && other->IsDefault(default_value)) { - return; - } - - ::std::string* this_ptr = Mutable(default_value, arena); - ::std::string* other_ptr = other->Mutable(default_value, arena); - - this_ptr->swap(*other_ptr); -#else - std::swap(ptr_, other->ptr_); -#endif - } + inline PROTOBUF_NDEBUG_INLINE static void InternalSwap( + const std::string* default_value, ArenaStringPtr* rhs, Arena* rhs_arena, + ArenaStringPtr* lhs, Arena* lhs_arena); // Frees storage (if not on an arena). - inline void Destroy(const ::std::string* default_value, - ::google::protobuf::Arena* arena) { - if (arena == NULL && ptr_ != default_value) { - delete ptr_; - } - } + void Destroy(const std::string* default_value, ::google::protobuf::Arena* arena); + void Destroy(EmptyDefault, ::google::protobuf::Arena* arena); + void Destroy(NonEmptyDefault, ::google::protobuf::Arena* arena); - // Clears content, but keeps allocated string if arena != NULL, to avoid the - // overhead of heap operations. After this returns, the content (as seen by - // the user) will always be the empty string. Assumes that |default_value| - // is an empty string. - inline void ClearToEmpty(const ::std::string* default_value, - ::google::protobuf::Arena* /* arena */) { - if (ptr_ == default_value) { - // Already set to default (which is empty) -- do nothing. - } else { - ptr_->clear(); - } - } + // Clears content, but keeps allocated std::string, to avoid the overhead of + // heap operations. After this returns, the content (as seen by the user) will + // always be the empty std::string. Assumes that |default_value| is an empty + // std::string. + void ClearToEmpty(); - // Clears content, assuming that the current value is not the empty string - // default. - inline void ClearNonDefaultToEmpty() { - ptr_->clear(); - } - inline void ClearNonDefaultToEmptyNoArena() { - ptr_->clear(); - } + // Clears content, assuming that the current value is not the empty + // string default. + void ClearNonDefaultToEmpty(); - // Clears content, but keeps allocated string if arena != NULL, to avoid the - // overhead of heap operations. After this returns, the content (as seen by - // the user) will always be equal to |default_value|. - inline void ClearToDefault(const ::std::string* default_value, - ::google::protobuf::Arena* /* arena */) { - if (ptr_ == default_value) { - // Already set to default -- do nothing. - } else { - // Have another allocated string -- rather than throwing this away and - // resetting ptr_ to the canonical default string instance, we just reuse - // this instance. - *ptr_ = *default_value; - } - } + // Clears content, but keeps allocated std::string if arena != nullptr, to + // avoid the overhead of heap operations. After this returns, the content + // (as seen by the user) will always be equal to |default_value|. + void ClearToDefault(const LazyString& default_value, ::google::protobuf::Arena* arena); // Called from generated code / reflection runtime only. Resets value to point - // to a default string pointer, with the semantics that this ArenaStringPtr - // does not own the pointed-to memory. Disregards initial value of ptr_ (so - // this is the *ONLY* safe method to call after construction or when - // reinitializing after becoming the active field in a oneof union). - inline void UnsafeSetDefault(const ::std::string* default_value) { - // Casting away 'const' is safe here: accessors ensure that ptr_ is only - // returned as a const if it is equal to default_value. - ptr_ = const_cast< ::std::string* >(default_value); - } + // to a default string pointer, with the semantics that this + // ArenaStringPtr does not own the pointed-to memory. Disregards initial value + // of ptr_ (so this is the *ONLY* safe method to call after construction or + // when reinitializing after becoming the active field in a oneof union). + inline void UnsafeSetDefault(const std::string* default_value); - // The 'NoArena' variants of methods below assume arena == NULL and are - // optimized to provide very little overhead relative to a raw string pointer - // (while still being in-memory compatible with other code that assumes - // ArenaStringPtr). Note the invariant that a class instance that has only - // ever been mutated by NoArena methods must *only* be in the String state - // (i.e., tag bits are not used), *NEVER* ArenaString. This allows all - // tagged-pointer manipulations to be avoided. - inline void SetNoArena(const ::std::string* default_value, - const ::std::string& value) { - if (ptr_ == default_value) { - CreateInstanceNoArena(&value); - } else { - *ptr_ = value; - } - } + // Returns a mutable pointer, but doesn't initialize the string to the + // default value. + std::string* MutableNoArenaNoDefault(const std::string* default_value); -#if LANG_CXX11 - void SetNoArena(const ::std::string* default_value, ::std::string&& value) { - if (IsDefault(default_value)) { - ptr_ = new ::std::string(std::move(value)); - } else { - *ptr_ = std::move(value); - } - } -#endif + // Get a mutable pointer with unspecified contents. + // Similar to `MutableNoArenaNoDefault`, but also handles the arena case. + // If the value was donated, the contents are discarded. + std::string* MutableNoCopy(const std::string* default_value, + ::google::protobuf::Arena* arena); - void AssignWithDefault(const ::std::string* default_value, ArenaStringPtr value); + // Destroy the string. Assumes `arena == nullptr`. + void DestroyNoArena(const std::string* default_value); - inline const ::std::string& GetNoArena() const { return *ptr_; } - - inline ::std::string* MutableNoArena(const ::std::string* default_value) { - if (ptr_ == default_value) { - CreateInstanceNoArena(default_value); - } - return ptr_; - } - - inline ::std::string* ReleaseNoArena(const ::std::string* default_value) { - if (ptr_ == default_value) { - return NULL; - } else { - return ReleaseNonDefaultNoArena(default_value); - } - } - - inline ::std::string* ReleaseNonDefaultNoArena( - const ::std::string* default_value) { - GOOGLE_DCHECK(!IsDefault(default_value)); - ::std::string* released = ptr_; - ptr_ = const_cast< ::std::string* >(default_value); - return released; - } - - - inline void SetAllocatedNoArena(const ::std::string* default_value, - ::std::string* value) { - if (ptr_ != default_value) { - delete ptr_; - } - if (value != NULL) { - ptr_ = value; - } else { - ptr_ = const_cast< ::std::string* >(default_value); - } - } - - inline void DestroyNoArena(const ::std::string* default_value) { - if (ptr_ != default_value) { - delete ptr_; - } - } - - inline void ClearToEmptyNoArena(const ::std::string* default_value) { - if (ptr_ == default_value) { - // Nothing: already equal to default (which is the empty string). - } else { - ptr_->clear(); - } - } - - inline void ClearToDefaultNoArena(const ::std::string* default_value) { - if (ptr_ == default_value) { - // Nothing: already set to default. - } else { - // Reuse existing allocated instance. - *ptr_ = *default_value; - } - } - - // Internal accessor used only at parse time to provide direct access to the - // raw pointer from the shared parse routine (in the non-arenas case). The - // parse routine does the string allocation in order to save code size in the - // generated parsing code. - inline ::std::string** UnsafeRawStringPointer() { - return &ptr_; - } - - inline bool IsDefault(const ::std::string* default_value) const { - return ptr_ == default_value; - } - - // Internal accessors!!!! - void UnsafeSetTaggedPointer(TaggedPtr< ::std::string> value) { - ptr_ = value.Get(); + // Internal setter used only at parse time to directly set a donated string + // value. + void UnsafeSetTaggedPointer(TaggedPtr value) { + tagged_ptr_ = value; } // Generated code only! An optimization, in certain cases the generated - // code is certain we can obtain a string with no default checks and + // code is certain we can obtain a std::string with no default checks and // tag tests. - ::std::string* UnsafeMutablePointer() { return ptr_; } + std::string* UnsafeMutablePointer() PROTOBUF_RETURNS_NONNULL; + + inline bool IsDefault(const std::string* default_value) const { + // Relies on the fact that kPtrTagString == 0, so if IsString(), ptr_ is the + // actual std::string pointer (and if !IsString(), ptr_ will never be equal + // to any aligned |default_value| pointer). The key is that we want to avoid + // masking in the fastpath const-pointer Get() case for non-arena code. + return tagged_ptr_.UnsafeGet() == default_value; + } private: - ::std::string* ptr_; + TaggedPtr tagged_ptr_; - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void CreateInstance(::google::protobuf::Arena* arena, - const ::std::string* initial_value) { - GOOGLE_DCHECK(initial_value != NULL); - // uses "new ::std::string" when arena is nullptr - ptr_ = Arena::Create< ::std::string >(arena, *initial_value); - } - GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE - void CreateInstanceNoArena(const ::std::string* initial_value) { - GOOGLE_DCHECK(initial_value != NULL); - ptr_ = new ::std::string(*initial_value); + bool IsDonatedString() const { return false; } + + // Swaps tagged pointer without debug hardening. This is to allow python + // protobuf to maintain pointer stability even in DEBUG builds. + inline PROTOBUF_NDEBUG_INLINE static void UnsafeShallowSwap( + ArenaStringPtr* rhs, ArenaStringPtr* lhs) { + std::swap(lhs->tagged_ptr_, rhs->tagged_ptr_); } + + friend class ::google::protobuf::internal::SwapFieldHelper; + + // Slow paths. + + // MutableSlow requires that !IsString() || IsDefault + // Variadic to support 0 args for EmptyDefault and 1 arg for LazyString. + template + std::string* MutableSlow(::google::protobuf::Arena* arena, const Lazy&... lazy_default); + + // Sets value to a newly allocated string and returns it + std::string* SetAndReturnNewString(); + + // Destroys the non-default string value out-of-line + void DestroyNoArenaSlowPath(); + }; -} // namespace internal -} // namespace protobuf +inline void ArenaStringPtr::UnsafeSetDefault(const std::string* value) { + tagged_ptr_.Set(const_cast(value)); +} +// Make sure rhs_arena allocated rhs, and lhs_arena allocated lhs. +inline PROTOBUF_NDEBUG_INLINE void ArenaStringPtr::InternalSwap( // + const std::string* default_value, // + ArenaStringPtr* rhs, Arena* rhs_arena, // + ArenaStringPtr* lhs, Arena* lhs_arena) { + // Silence unused variable warnings in release buildls. + (void)default_value; + (void)rhs_arena; + (void)lhs_arena; + std::swap(lhs->tagged_ptr_, rhs->tagged_ptr_); +#ifdef PROTOBUF_FORCE_COPY_IN_SWAP + auto force_realloc = [default_value](ArenaStringPtr* p, Arena* arena) { + if (p->IsDefault(default_value)) return; + std::string* old_value = p->tagged_ptr_.Get(); + std::string* new_value = + p->IsDonatedString() + ? Arena::Create(arena, *old_value) + : Arena::Create(arena, std::move(*old_value)); + if (arena == nullptr) delete old_value; + p->tagged_ptr_.Set(new_value); + }; + // Because, at this point, tagged_ptr_ has been swapped, arena should also be + // swapped. + force_realloc(lhs, rhs_arena); + force_realloc(rhs, lhs_arena); +#endif // PROTOBUF_FORCE_COPY_IN_SWAP +} +inline void ArenaStringPtr::ClearNonDefaultToEmpty() { + // Unconditionally mask away the tag. + tagged_ptr_.Get()->clear(); +} -namespace protobuf { -namespace internal { - -inline void ArenaStringPtr::AssignWithDefault(const ::std::string* default_value, - ArenaStringPtr value) { - const ::std::string* me = *UnsafeRawStringPointer(); - const ::std::string* other = *value.UnsafeRawStringPointer(); - // If the pointers are the same then do nothing. - if (me != other) { - SetNoArena(default_value, value.GetNoArena()); +inline std::string* ArenaStringPtr::MutableNoArenaNoDefault( + const std::string* default_value) { + // VERY IMPORTANT for performance and code size: this will reduce to a member + // variable load, a pointer check (against |default_value|, in practice a + // static global) and a branch to the slowpath (which calls operator new and + // the ctor). DO NOT add any tagged-pointer operations here. + if (IsDefault(default_value)) { + return SetAndReturnNewString(); + } else { + return UnsafeMutablePointer(); } } +inline void ArenaStringPtr::DestroyNoArena(const std::string* default_value) { + if (!IsDefault(default_value)) { + DestroyNoArenaSlowPath(); + } +} + +inline std::string* ArenaStringPtr::UnsafeMutablePointer() { + GOOGLE_DCHECK(!tagged_ptr_.IsTagged()); + GOOGLE_DCHECK(tagged_ptr_.UnsafeGet() != nullptr); + return tagged_ptr_.UnsafeGet(); +} + + } // namespace internal } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_ARENASTRING_H__ diff --git a/windows/include/google/protobuf/arenastring_unittest.cc b/windows/include/google/protobuf/arenastring_unittest.cc deleted file mode 100644 index adc44fe25..000000000 --- a/windows/include/google/protobuf/arenastring_unittest.cc +++ /dev/null @@ -1,138 +0,0 @@ -// 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. - -// Based on mvels@'s frankenstring. - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - - -namespace google { -using google::protobuf::internal::ArenaStringPtr; - -namespace protobuf { - - -static string WrapString(const char* value) { - return value; -} - -// Test ArenaStringPtr with arena == NULL. -TEST(ArenaStringPtrTest, ArenaStringPtrOnHeap) { - ArenaStringPtr field; - ::std::string default_value = "default"; - field.UnsafeSetDefault(&default_value); - EXPECT_EQ(string("default"), field.Get()); - field.Set(&default_value, WrapString("Test short"), NULL); - EXPECT_EQ(string("Test short"), field.Get()); - field.Set(&default_value, WrapString("Test long long long long value"), NULL); - EXPECT_EQ(string("Test long long long long value"), field.Get()); - field.Set(&default_value, string(""), NULL); - field.Destroy(&default_value, NULL); - - ArenaStringPtr field2; - field2.UnsafeSetDefault(&default_value); - ::std::string* mut = field2.Mutable(&default_value, NULL); - EXPECT_EQ(mut, field2.Mutable(&default_value, NULL)); - EXPECT_EQ(mut, &field2.Get()); - EXPECT_NE(&default_value, mut); - EXPECT_EQ(string("default"), *mut); - *mut = "Test long long long long value"; // ensure string allocates storage - EXPECT_EQ(string("Test long long long long value"), field2.Get()); - field2.Destroy(&default_value, NULL); -} - -TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) { - google::protobuf::Arena arena; - ArenaStringPtr field; - ::std::string default_value = "default"; - field.UnsafeSetDefault(&default_value); - EXPECT_EQ(string("default"), field.Get()); - field.Set(&default_value, WrapString("Test short"), &arena); - EXPECT_EQ(string("Test short"), field.Get()); - field.Set(&default_value, WrapString("Test long long long long value"), - &arena); - EXPECT_EQ(string("Test long long long long value"), field.Get()); - field.Set(&default_value, string(""), &arena); - field.Destroy(&default_value, &arena); - - ArenaStringPtr field2; - field2.UnsafeSetDefault(&default_value); - ::std::string* mut = field2.Mutable(&default_value, &arena); - EXPECT_EQ(mut, field2.Mutable(&default_value, &arena)); - EXPECT_EQ(mut, &field2.Get()); - EXPECT_NE(&default_value, mut); - EXPECT_EQ(string("default"), *mut); - *mut = "Test long long long long value"; // ensure string allocates storage - EXPECT_EQ(string("Test long long long long value"), field2.Get()); - field2.Destroy(&default_value, &arena); -} - -TEST(ArenaStringPtrTest, ArenaStringPtrOnArenaNoSSO) { - google::protobuf::Arena arena; - ArenaStringPtr field; - ::std::string default_value = "default"; - field.UnsafeSetDefault(&default_value); - EXPECT_EQ(string("default"), field.Get()); - - // Avoid triggering the SSO optimization by setting the string to something - // larger than the internal buffer. - field.Set(&default_value, WrapString("Test long long long long value"), - &arena); - EXPECT_EQ(string("Test long long long long value"), field.Get()); - field.Set(&default_value, string(""), &arena); - field.Destroy(&default_value, &arena); - - ArenaStringPtr field2; - field2.UnsafeSetDefault(&default_value); - ::std::string* mut = field2.Mutable(&default_value, &arena); - EXPECT_EQ(mut, field2.Mutable(&default_value, &arena)); - EXPECT_EQ(mut, &field2.Get()); - EXPECT_NE(&default_value, mut); - EXPECT_EQ(string("default"), *mut); - *mut = "Test long long long long value"; // ensure string allocates storage - EXPECT_EQ(string("Test long long long long value"), field2.Get()); - field2.Destroy(&default_value, &arena); -} - - -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/annotation_test_util.cc b/windows/include/google/protobuf/compiler/annotation_test_util.cc deleted file mode 100644 index a0530b9a6..000000000 --- a/windows/include/google/protobuf/compiler/annotation_test_util.cc +++ /dev/null @@ -1,166 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace annotation_test_util { -namespace { - -// A CodeGenerator that captures the FileDescriptor it's passed as a -// FileDescriptorProto. -class DescriptorCapturingGenerator : public CodeGenerator { - public: - // Does not own file; file must outlive the Generator. - explicit DescriptorCapturingGenerator(FileDescriptorProto* file) - : file_(file) {} - - virtual bool Generate(const FileDescriptor* file, const string& parameter, - GeneratorContext* context, string* error) const { - file->CopyTo(file_); - return true; - } - - private: - FileDescriptorProto* file_; -}; -} // namespace - -void AddFile(const string& filename, const string& data) { - GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/" + filename, data, - true)); -} - -bool RunProtoCompiler(const string& filename, - const string& plugin_specific_args, - CommandLineInterface* cli, FileDescriptorProto* file) { - cli->SetInputsAreProtoPathRelative(true); - - DescriptorCapturingGenerator capturing_generator(file); - cli->RegisterGenerator("--capture_out", &capturing_generator, ""); - - string proto_path = "-I" + TestTempDir(); - string capture_out = "--capture_out=" + TestTempDir(); - - const char* argv[] = {"protoc", proto_path.c_str(), - plugin_specific_args.c_str(), capture_out.c_str(), - filename.c_str()}; - - return cli->Run(5, argv) == 0; -} - -bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) { - string data; - GOOGLE_CHECK_OK(File::GetContents(path, &data, true)); - io::ArrayInputStream input(data.data(), data.size()); - return info->ParseFromZeroCopyStream(&input); -} - -void FindAnnotationsOnPath( - const GeneratedCodeInfo& info, const string& source_file, - const std::vector& path, - std::vector* annotations) { - for (int i = 0; i < info.annotation_size(); ++i) { - const GeneratedCodeInfo::Annotation* annotation = &info.annotation(i); - if (annotation->source_file() != source_file || - annotation->path_size() != path.size()) { - continue; - } - int node = 0; - for (; node < path.size(); ++node) { - if (annotation->path(node) != path[node]) { - break; - } - } - if (node == path.size()) { - annotations->push_back(annotation); - } - } -} - -const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( - const GeneratedCodeInfo& info, const string& source_file, - const std::vector& path) { - std::vector annotations; - FindAnnotationsOnPath(info, source_file, path, &annotations); - if (annotations.empty()) { - return NULL; - } - return annotations[0]; -} - -bool AtLeastOneAnnotationMatchesSubstring( - const string& file_content, - const std::vector& annotations, - const string& expected_text) { - for (std::vector::const_iterator - i = annotations.begin(), - e = annotations.end(); - i != e; ++i) { - const GeneratedCodeInfo::Annotation* annotation = *i; - uint32 begin = annotation->begin(); - uint32 end = annotation->end(); - if (end < begin || end > file_content.size()) { - return false; - } - if (file_content.substr(begin, end - begin) == expected_text) { - return true; - } - } - return false; -} - -bool AnnotationMatchesSubstring(const string& file_content, - const GeneratedCodeInfo::Annotation* annotation, - const string& expected_text) { - std::vector annotations; - annotations.push_back(annotation); - return AtLeastOneAnnotationMatchesSubstring(file_content, annotations, - expected_text); -} -} // namespace annotation_test_util -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/annotation_test_util.h b/windows/include/google/protobuf/compiler/annotation_test_util.h deleted file mode 100644 index 90bd88b37..000000000 --- a/windows/include/google/protobuf/compiler/annotation_test_util.h +++ /dev/null @@ -1,114 +0,0 @@ -// 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_ANNOTATION_TEST_UTIL_H__ -#define GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__ - -#include -#include -#include - -// Utilities that assist in writing tests for generator annotations. -// See java/internal/annotation_unittest.cc for an example. -namespace google { -namespace protobuf { -namespace compiler { -namespace annotation_test_util { - -// Struct that contains the file generated from a .proto file and its -// GeneratedCodeInfo. For example, the Java generator will fill this struct -// (for some 'foo.proto') with: -// file_path = "Foo.java" -// file_content = content of Foo.java -// file_info = parsed content of Foo.java.pb.meta -struct ExpectedOutput { - string file_path; - string file_content; - GeneratedCodeInfo file_info; - explicit ExpectedOutput(const string& file_path) : file_path(file_path) {} -}; - -// Creates a file with name `filename` and content `data` in temp test -// directory. -void AddFile(const string& filename, const string& data); - -// Runs proto compiler. Captures proto file structrue in FileDescriptorProto. -// Files will be generated in TestTempDir() folder. Callers of this -// function must read generated files themselves. -// -// filename: source .proto file used to generate code. -// plugin_specific_args: command line arguments specific to current generator. -// For Java, this value might be "--java_out=annotate_code:test_temp_dir" -// cli: instance of command line interface to run generator. See Java's -// annotation_unittest.cc for an example of how to initialize it. -// file: output parameter, will be set to the descriptor of the proto file -// specified in filename. -bool RunProtoCompiler(const string& filename, - const string& plugin_specific_args, - CommandLineInterface* cli, FileDescriptorProto* file); - -bool DecodeMetadata(const string& path, GeneratedCodeInfo* info); - -// Finds all of the Annotations for a given source file and path. -// See Location.path in http://google/protobuf/descriptor.proto for -// explanation of what path vector is. -void FindAnnotationsOnPath( - const GeneratedCodeInfo& info, const string& source_file, - const std::vector& path, - std::vector* annotations); - -// Finds the Annotation for a given source file and path (or returns null if it -// couldn't). If there are several annotations for given path, returns the first -// one. See Location.path in -// http://google/protobuf/descriptor.proto for explanation of what path -// vector is. -const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( - const GeneratedCodeInfo& info, const string& source_file, - const std::vector& path); - -// Returns true if at least one of the provided annotations covers a given -// substring in file_content. -bool AtLeastOneAnnotationMatchesSubstring( - const string& file_content, - const std::vector& annotations, - const string& expected_text); - -// Returns true if the provided annotation covers a given substring in -// file_content. -bool AnnotationMatchesSubstring(const string& file_content, - const GeneratedCodeInfo::Annotation* annotation, - const string& expected_text); - -} // namespace annotation_test_util -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__ diff --git a/windows/include/google/protobuf/compiler/code_generator.cc b/windows/include/google/protobuf/compiler/code_generator.cc deleted file mode 100644 index aaabd9142..000000000 --- a/windows/include/google/protobuf/compiler/code_generator.cc +++ /dev/null @@ -1,121 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { - -CodeGenerator::~CodeGenerator() {} - -bool CodeGenerator::GenerateAll( - const std::vector& files, - const string& parameter, - GeneratorContext* generator_context, - string* error) const { - // Default implemenation is just to call the per file method, and prefix any - // error string with the file to provide context. - bool succeeded = true; - for (int i = 0; i < files.size(); i++) { - const FileDescriptor* file = files[i]; - succeeded = Generate(file, parameter, generator_context, error); - if (!succeeded && error && error->empty()) { - *error = "Code generator returned false but provided no error " - "description."; - } - if (error && !error->empty()) { - *error = file->name() + ": " + *error; - break; - } - if (!succeeded) { - break; - } - } - return succeeded; -} - -GeneratorContext::~GeneratorContext() {} - -io::ZeroCopyOutputStream* -GeneratorContext::OpenForAppend(const string& filename) { - return NULL; -} - -io::ZeroCopyOutputStream* GeneratorContext::OpenForInsert( - const string& filename, const string& insertion_point) { - GOOGLE_LOG(FATAL) << "This GeneratorContext does not support insertion."; - return NULL; // make compiler happy -} - -void GeneratorContext::ListParsedFiles( - std::vector* output) { - GOOGLE_LOG(FATAL) << "This GeneratorContext does not support ListParsedFiles"; -} - -void GeneratorContext::GetCompilerVersion(Version* version) const { - version->set_major(GOOGLE_PROTOBUF_VERSION / 1000000); - version->set_minor(GOOGLE_PROTOBUF_VERSION / 1000 % 1000); - version->set_patch(GOOGLE_PROTOBUF_VERSION % 1000); - version->set_suffix(GOOGLE_PROTOBUF_VERSION_SUFFIX); -} - -// Parses a set of comma-delimited name/value pairs. -void ParseGeneratorParameter(const string& text, - std::vector >* output) { - std::vector parts = Split(text, ",", true); - - for (int i = 0; i < parts.size(); i++) { - string::size_type equals_pos = parts[i].find_first_of('='); - std::pair value; - if (equals_pos == string::npos) { - value.first = parts[i]; - value.second = ""; - } else { - value.first = parts[i].substr(0, equals_pos); - value.second = parts[i].substr(equals_pos + 1); - } - output->push_back(value); - } -} - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/code_generator.h b/windows/include/google/protobuf/compiler/code_generator.h index 4c2b3ee14..2cbda270b 100644 --- a/windows/include/google/protobuf/compiler/code_generator.h +++ b/windows/include/google/protobuf/compiler/code_generator.h @@ -38,16 +38,21 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__ #define GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__ -#include #include -#include #include +#include +#include + +#include namespace google { namespace protobuf { -namespace io { class ZeroCopyOutputStream; } +namespace io { +class ZeroCopyOutputStream; +} class FileDescriptor; +class GeneratedCodeInfo; namespace compiler { class AccessInfoMap; @@ -61,7 +66,7 @@ class GeneratorContext; // The abstract interface to a class which generates code implementing a // particular proto file in a particular language. A number of these may // be registered with CommandLineInterface to support various languages. -class LIBPROTOC_EXPORT CodeGenerator { +class PROTOC_EXPORT CodeGenerator { public: inline CodeGenerator() {} virtual ~CodeGenerator(); @@ -78,9 +83,9 @@ class LIBPROTOC_EXPORT CodeGenerator { // Returns true if successful. Otherwise, sets *error to a description of // the problem (e.g. "invalid parameter") and returns false. virtual bool Generate(const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const = 0; + std::string* error) const = 0; // Generates code for all given proto files. // @@ -94,9 +99,20 @@ class LIBPROTOC_EXPORT CodeGenerator { // Returns true if successful. Otherwise, sets *error to a description of // the problem (e.g. "invalid parameter") and returns false. virtual bool GenerateAll(const std::vector& files, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const; + std::string* error) const; + + // This must be kept in sync with plugin.proto. See that file for + // documentation on each value. + enum Feature { + FEATURE_PROTO3_OPTIONAL = 1, + }; + + // Implement this to indicate what features this code generator supports. + // + // This must be a bitwise OR of values from the Feature enum above (or zero). + virtual uint64_t GetSupportedFeatures() const { return 0; } // This is no longer used, but this class is part of the opensource protobuf // library, so it has to remain to keep vtables the same for the current @@ -112,7 +128,7 @@ class LIBPROTOC_EXPORT CodeGenerator { // abstract interface represents the directory to which the CodeGenerator is // to write and other information about the context in which the Generator // runs. -class LIBPROTOC_EXPORT GeneratorContext { +class PROTOC_EXPORT GeneratorContext { public: inline GeneratorContext() { } @@ -128,10 +144,10 @@ class LIBPROTOC_EXPORT GeneratorContext { // generate the files "foo/bar.pb.h" and "foo/bar.pb.cc"; note that // "foo/" is included in these filenames. The filename is not allowed to // contain "." or ".." components. - virtual io::ZeroCopyOutputStream* Open(const string& filename) = 0; + virtual io::ZeroCopyOutputStream* Open(const std::string& filename) = 0; // Similar to Open() but the output will be appended to the file if exists - virtual io::ZeroCopyOutputStream* OpenForAppend(const string& filename); + virtual io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename); // Creates a ZeroCopyOutputStream which will insert code into the given file // at the given insertion point. See plugin.proto (plugin.pb.h) for more @@ -140,7 +156,16 @@ class LIBPROTOC_EXPORT GeneratorContext { // // WARNING: This feature is currently EXPERIMENTAL and is subject to change. virtual io::ZeroCopyOutputStream* OpenForInsert( - const string& filename, const string& insertion_point); + const std::string& filename, const std::string& insertion_point); + + // Similar to OpenForInsert, but if `info` is non-empty, will open (or create) + // filename.pb.meta and insert info at the appropriate place with the + // necessary shifts. The default implementation ignores `info`. + // + // WARNING: This feature will be REMOVED in the near future. + virtual io::ZeroCopyOutputStream* OpenForInsertWithGeneratedCodeInfo( + const std::string& filename, const std::string& insertion_point, + const google::protobuf::GeneratedCodeInfo& info); // Returns a vector of FileDescriptors for all the files being compiled // in this run. Useful for languages, such as Go, that treat files @@ -166,11 +191,16 @@ typedef GeneratorContext OutputDirectory; // "foo=bar,baz,qux=corge" // parses to the pairs: // ("foo", "bar"), ("baz", ""), ("qux", "corge") -LIBPROTOC_EXPORT void ParseGeneratorParameter( - const string&, std::vector >*); +PROTOC_EXPORT void ParseGeneratorParameter( + const std::string&, std::vector >*); + +// Strips ".proto" or ".protodevel" from the end of a filename. +PROTOC_EXPORT std::string StripProto(const std::string& filename); } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/command_line_interface.cc b/windows/include/google/protobuf/compiler/command_line_interface.cc deleted file mode 100644 index 8380367fa..000000000 --- a/windows/include/google/protobuf/compiler/command_line_interface.cc +++ /dev/null @@ -1,2250 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - - -#include - -#include -#include -#ifdef major -#undef major -#endif -#ifdef minor -#undef minor -#endif -#include -#include -#ifndef _MSC_VER -#include -#endif -#include -#include -#include -#include - -#include //For PATH_MAX - -#include - -#ifdef __APPLE__ -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { - -#ifndef O_BINARY -#ifdef _O_BINARY -#define O_BINARY _O_BINARY -#else -#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. -#endif -#endif - -namespace { -#if defined(_WIN32) -// DO NOT include , instead create functions in io_win32.{h,cc} and import -// them like we do below. -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::mkdir; -using google::protobuf::internal::win32::open; -using google::protobuf::internal::win32::setmode; -using google::protobuf::internal::win32::write; -#endif - -static const char* kDefaultDirectDependenciesViolationMsg = - "File is imported but not declared in --direct_dependencies: %s"; - -// Returns true if the text looks like a Windows-style absolute path, starting -// with a drive letter. Example: "C:\foo". TODO(kenton): Share this with -// copy in importer.cc? -static bool IsWindowsAbsolutePath(const string& text) { -#if defined(_WIN32) || defined(__CYGWIN__) - return text.size() >= 3 && text[1] == ':' && - isalpha(text[0]) && - (text[2] == '/' || text[2] == '\\') && - text.find_last_of(':') == 1; -#else - return false; -#endif -} - -void SetFdToTextMode(int fd) { -#ifdef _WIN32 - if (setmode(fd, _O_TEXT) == -1) { - // This should never happen, I think. - GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_TEXT): " << strerror(errno); - } -#endif - // (Text and binary are the same on non-Windows platforms.) -} - -void SetFdToBinaryMode(int fd) { -#ifdef _WIN32 - if (setmode(fd, _O_BINARY) == -1) { - // This should never happen, I think. - GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_BINARY): " << strerror(errno); - } -#endif - // (Text and binary are the same on non-Windows platforms.) -} - -void AddTrailingSlash(string* path) { - if (!path->empty() && path->at(path->size() - 1) != '/') { - path->push_back('/'); - } -} - -bool VerifyDirectoryExists(const string& path) { - if (path.empty()) return true; - - if (access(path.c_str(), F_OK) == -1) { - std::cerr << path << ": " << strerror(errno) << std::endl; - return false; - } else { - return true; - } -} - -// Try to create the parent directory of the given file, creating the parent's -// parent if necessary, and so on. The full file name is actually -// (prefix + filename), but we assume |prefix| already exists and only create -// directories listed in |filename|. -bool TryCreateParentDirectory(const string& prefix, const string& filename) { - // Recursively create parent directories to the output file. - std::vector parts = Split(filename, "/", true); - string path_so_far = prefix; - for (int i = 0; i < parts.size() - 1; i++) { - path_so_far += parts[i]; - if (mkdir(path_so_far.c_str(), 0777) != 0) { - if (errno != EEXIST) { - std::cerr << filename << ": while trying to create directory " - << path_so_far << ": " << strerror(errno) << std::endl; - return false; - } - } - path_so_far += '/'; - } - - return true; -} - -// Get the absolute path of this protoc binary. -bool GetProtocAbsolutePath(string* path) { -#ifdef _WIN32 - char buffer[MAX_PATH]; - int len = GetModuleFileNameA(NULL, buffer, MAX_PATH); -#elif __APPLE__ - char buffer[PATH_MAX]; - int len = 0; - - char dirtybuffer[PATH_MAX]; - uint32_t size = sizeof(dirtybuffer); - if (_NSGetExecutablePath(dirtybuffer, &size) == 0) { - realpath(dirtybuffer, buffer); - len = strlen(buffer); - } -#else - char buffer[PATH_MAX]; - int len = readlink("/proc/self/exe", buffer, PATH_MAX); -#endif - if (len > 0) { - path->assign(buffer, len); - return true; - } else { - return false; - } -} - -// Whether a path is where google/protobuf/descriptor.proto and other well-known -// type protos are installed. -bool IsInstalledProtoPath(const string& path) { - // Checking the descriptor.proto file should be good enough. - string file_path = path + "/google/protobuf/descriptor.proto"; - return access(file_path.c_str(), F_OK) != -1; -} - -// Add the paths where google/protobuf/descriptor.proto and other well-known -// type protos are installed. -void AddDefaultProtoPaths(std::vector >* paths) { - // TODO(xiaofeng): The code currently only checks relative paths of where - // the protoc binary is installed. We probably should make it handle more - // cases than that. - string path; - if (!GetProtocAbsolutePath(&path)) { - return; - } - // Strip the binary name. - size_t pos = path.find_last_of("/\\"); - if (pos == string::npos || pos == 0) { - return; - } - path = path.substr(0, pos); - // Check the binary's directory. - if (IsInstalledProtoPath(path)) { - paths->push_back(std::pair("", path)); - return; - } - // Check if there is an include subdirectory. - if (IsInstalledProtoPath(path + "/include")) { - paths->push_back(std::pair("", path + "/include")); - return; - } - // Check if the upper level directory has an "include" subdirectory. - pos = path.find_last_of("/\\"); - if (pos == string::npos || pos == 0) { - return; - } - path = path.substr(0, pos); - if (IsInstalledProtoPath(path + "/include")) { - paths->push_back(std::pair("", path + "/include")); - return; - } -} - -string PluginName(const string& plugin_prefix, const string& directive) { - // Assuming the directive starts with "--" and ends with "_out" or "_opt", - // strip the "--" and "_out/_opt" and add the plugin prefix. - return plugin_prefix + "gen-" + directive.substr(2, directive.size() - 6); -} - -} // namespace - -// A MultiFileErrorCollector that prints errors to stderr. -class CommandLineInterface::ErrorPrinter - : public MultiFileErrorCollector, - public io::ErrorCollector, - public DescriptorPool::ErrorCollector { - public: - ErrorPrinter(ErrorFormat format, DiskSourceTree *tree = NULL) - : format_(format), tree_(tree), found_errors_(false) {} - ~ErrorPrinter() {} - - // implements MultiFileErrorCollector ------------------------------ - void AddError(const string& filename, int line, int column, - const string& message) { - found_errors_ = true; - AddErrorOrWarning(filename, line, column, message, "error", std::cerr); - } - - void AddWarning(const string& filename, int line, int column, - const string& message) { - AddErrorOrWarning(filename, line, column, message, "warning", std::clog); - } - - // implements io::ErrorCollector ----------------------------------- - void AddError(int line, int column, const string& message) { - AddError("input", line, column, message); - } - - void AddWarning(int line, int column, const string& message) { - AddErrorOrWarning("input", line, column, message, "warning", std::clog); - } - - // implements DescriptorPool::ErrorCollector------------------------- - void AddError( - const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { - AddErrorOrWarning(filename, -1, -1, message, "error", std::cerr); - } - - void AddWarning( - const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { - AddErrorOrWarning(filename, -1, -1, message, "warning", std::clog); - } - - bool FoundErrors() const { return found_errors_; } - - private: - void AddErrorOrWarning(const string& filename, int line, int column, - const string& message, const string& type, - std::ostream& out) { - // Print full path when running under MSVS - string dfile; - if (format_ == CommandLineInterface::ERROR_FORMAT_MSVS && - tree_ != NULL && - tree_->VirtualFileToDiskFile(filename, &dfile)) { - out << dfile; - } else { - out << filename; - } - - // Users typically expect 1-based line/column numbers, so we add 1 - // to each here. - if (line != -1) { - // Allow for both GCC- and Visual-Studio-compatible output. - switch (format_) { - case CommandLineInterface::ERROR_FORMAT_GCC: - out << ":" << (line + 1) << ":" << (column + 1); - break; - case CommandLineInterface::ERROR_FORMAT_MSVS: - out << "(" << (line + 1) << ") : " - << type << " in column=" << (column + 1); - break; - } - } - - if (type == "warning") { - out << ": warning: " << message << std::endl; - } else { - out << ": " << message << std::endl; - } - } - - const ErrorFormat format_; - DiskSourceTree *tree_; - bool found_errors_; -}; - -// ------------------------------------------------------------------- - -// A GeneratorContext implementation that buffers files in memory, then dumps -// them all to disk on demand. -class CommandLineInterface::GeneratorContextImpl : public GeneratorContext { - public: - GeneratorContextImpl(const std::vector& parsed_files); - ~GeneratorContextImpl(); - - // Write all files in the directory to disk at the given output location, - // which must end in a '/'. - bool WriteAllToDisk(const string& prefix); - - // Write the contents of this directory to a ZIP-format archive with the - // given name. - bool WriteAllToZip(const string& filename); - - // Add a boilerplate META-INF/MANIFEST.MF file as required by the Java JAR - // format, unless one has already been written. - void AddJarManifest(); - - // Get name of all output files. - void GetOutputFilenames(std::vector* output_filenames); - - // implements GeneratorContext -------------------------------------- - io::ZeroCopyOutputStream* Open(const string& filename); - io::ZeroCopyOutputStream* OpenForAppend(const string& filename); - io::ZeroCopyOutputStream* OpenForInsert( - const string& filename, const string& insertion_point); - void ListParsedFiles(std::vector* output) { - *output = parsed_files_; - } - - private: - friend class MemoryOutputStream; - - // map instead of hash_map so that files are written in order (good when - // writing zips). - std::map files_; - const std::vector& parsed_files_; - bool had_error_; -}; - -class CommandLineInterface::MemoryOutputStream - : public io::ZeroCopyOutputStream { - public: - MemoryOutputStream(GeneratorContextImpl* directory, const string& filename, - bool append_mode); - MemoryOutputStream(GeneratorContextImpl* directory, const string& filename, - const string& insertion_point); - virtual ~MemoryOutputStream(); - - // implements ZeroCopyOutputStream --------------------------------- - virtual bool Next(void** data, int* size) { return inner_->Next(data, size); } - virtual void BackUp(int count) { inner_->BackUp(count); } - virtual int64 ByteCount() const { return inner_->ByteCount(); } - - private: - // Checks to see if "filename_.meta" exists in directory_; if so, fixes the - // offsets in that GeneratedCodeInfo record to reflect bytes inserted in - // filename_ at original offset insertion_offset with length insertion_length. - // We assume that insertions will not occur within any given annotated span - // of text. - void UpdateMetadata(size_t insertion_offset, size_t insertion_length); - - // Where to insert the string when it's done. - GeneratorContextImpl* directory_; - string filename_; - string insertion_point_; - - // The string we're building. - string data_; - - // Whether we should append the output stream to the existing file. - bool append_mode_; - - // StringOutputStream writing to data_. - std::unique_ptr inner_; -}; - -// ------------------------------------------------------------------- - -CommandLineInterface::GeneratorContextImpl::GeneratorContextImpl( - const std::vector& parsed_files) - : parsed_files_(parsed_files), - had_error_(false) {} - -CommandLineInterface::GeneratorContextImpl::~GeneratorContextImpl() { - STLDeleteValues(&files_); -} - -bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk( - const string& prefix) { - if (had_error_) { - return false; - } - - if (!VerifyDirectoryExists(prefix)) { - return false; - } - - for (std::map::const_iterator iter = files_.begin(); - iter != files_.end(); ++iter) { - const string& relative_filename = iter->first; - const char* data = iter->second->data(); - int size = iter->second->size(); - - if (!TryCreateParentDirectory(prefix, relative_filename)) { - return false; - } - string filename = prefix + relative_filename; - - // Create the output file. - int file_descriptor; - do { - file_descriptor = - open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); - } while (file_descriptor < 0 && errno == EINTR); - - if (file_descriptor < 0) { - int error = errno; - std::cerr << filename << ": " << strerror(error); - return false; - } - - // Write the file. - while (size > 0) { - int write_result; - do { - write_result = write(file_descriptor, data, size); - } while (write_result < 0 && errno == EINTR); - - if (write_result <= 0) { - // Write error. - - // FIXME(kenton): According to the man page, if write() returns zero, - // there was no error; write() simply did not write anything. It's - // unclear under what circumstances this might happen, but presumably - // errno won't be set in this case. I am confused as to how such an - // event should be handled. For now I'm treating it as an error, - // since retrying seems like it could lead to an infinite loop. I - // suspect this never actually happens anyway. - - if (write_result < 0) { - int error = errno; - std::cerr << filename << ": write: " << strerror(error); - } else { - std::cerr << filename << ": write() returned zero?" << std::endl; - } - return false; - } - - data += write_result; - size -= write_result; - } - - if (close(file_descriptor) != 0) { - int error = errno; - std::cerr << filename << ": close: " << strerror(error); - return false; - } - } - - return true; -} - -bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip( - const string& filename) { - if (had_error_) { - return false; - } - - // Create the output file. - int file_descriptor; - do { - file_descriptor = - open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); - } while (file_descriptor < 0 && errno == EINTR); - - if (file_descriptor < 0) { - int error = errno; - std::cerr << filename << ": " << strerror(error); - return false; - } - - // Create the ZipWriter - io::FileOutputStream stream(file_descriptor); - ZipWriter zip_writer(&stream); - - for (std::map::const_iterator iter = files_.begin(); - iter != files_.end(); ++iter) { - zip_writer.Write(iter->first, *iter->second); - } - - zip_writer.WriteDirectory(); - - if (stream.GetErrno() != 0) { - std::cerr << filename << ": " << strerror(stream.GetErrno()) << std::endl; - } - - if (!stream.Close()) { - std::cerr << filename << ": " << strerror(stream.GetErrno()) << std::endl; - } - - return true; -} - -void CommandLineInterface::GeneratorContextImpl::AddJarManifest() { - string** map_slot = &files_["META-INF/MANIFEST.MF"]; - if (*map_slot == NULL) { - *map_slot = new string( - "Manifest-Version: 1.0\n" - "Created-By: 1.6.0 (protoc)\n" - "\n"); - } -} - -void CommandLineInterface::GeneratorContextImpl::GetOutputFilenames( - std::vector* output_filenames) { - for (std::map::iterator iter = files_.begin(); - iter != files_.end(); ++iter) { - output_filenames->push_back(iter->first); - } -} - -io::ZeroCopyOutputStream* CommandLineInterface::GeneratorContextImpl::Open( - const string& filename) { - return new MemoryOutputStream(this, filename, false); -} - -io::ZeroCopyOutputStream* -CommandLineInterface::GeneratorContextImpl::OpenForAppend( - const string& filename) { - return new MemoryOutputStream(this, filename, true); -} - -io::ZeroCopyOutputStream* -CommandLineInterface::GeneratorContextImpl::OpenForInsert( - const string& filename, const string& insertion_point) { - return new MemoryOutputStream(this, filename, insertion_point); -} - -// ------------------------------------------------------------------- - -CommandLineInterface::MemoryOutputStream::MemoryOutputStream( - GeneratorContextImpl* directory, const string& filename, bool append_mode) - : directory_(directory), - filename_(filename), - append_mode_(append_mode), - inner_(new io::StringOutputStream(&data_)) { -} - -CommandLineInterface::MemoryOutputStream::MemoryOutputStream( - GeneratorContextImpl* directory, const string& filename, - const string& insertion_point) - : directory_(directory), - filename_(filename), - insertion_point_(insertion_point), - inner_(new io::StringOutputStream(&data_)) { -} - -void CommandLineInterface::MemoryOutputStream::UpdateMetadata( - size_t insertion_offset, size_t insertion_length) { - std::map::iterator meta_file = - directory_->files_.find(filename_ + ".meta"); - if (meta_file == directory_->files_.end() || !meta_file->second) { - // No metadata was recorded for this file. - return; - } - string* encoded_data = meta_file->second; - GeneratedCodeInfo metadata; - bool is_text_format = false; - if (!metadata.ParseFromString(*encoded_data)) { - if (!TextFormat::ParseFromString(*encoded_data, &metadata)) { - // The metadata is invalid. - std::cerr << filename_ - << ".meta: Could not parse metadata as wire or text format." - << std::endl; - return; - } - // Generators that use the public plugin interface emit text-format - // metadata (because in the public plugin protocol, file content must be - // UTF8-encoded strings). - is_text_format = true; - } - for (int i = 0; i < metadata.annotation_size(); ++i) { - GeneratedCodeInfo::Annotation* annotation = metadata.mutable_annotation(i); - if (annotation->begin() >= insertion_offset) { - annotation->set_begin(annotation->begin() + insertion_length); - annotation->set_end(annotation->end() + insertion_length); - } - } - if (is_text_format) { - TextFormat::PrintToString(metadata, encoded_data); - } else { - metadata.SerializeToString(encoded_data); - } -} - -CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() { - // Make sure all data has been written. - inner_.reset(); - - // Insert into the directory. - string** map_slot = &directory_->files_[filename_]; - - if (insertion_point_.empty()) { - // This was just a regular Open(). - if (*map_slot != NULL) { - if (append_mode_) { - (*map_slot)->append(data_); - } else { - std::cerr << filename_ << ": Tried to write the same file twice." - << std::endl; - directory_->had_error_ = true; - } - return; - } - - *map_slot = new string; - (*map_slot)->swap(data_); - } else { - // This was an OpenForInsert(). - - // If the data doesn't end with a clean line break, add one. - if (!data_.empty() && data_[data_.size() - 1] != '\n') { - data_.push_back('\n'); - } - - // Find the file we are going to insert into. - if (*map_slot == NULL) { - std::cerr << filename_ - << ": Tried to insert into file that doesn't exist." - << std::endl; - directory_->had_error_ = true; - return; - } - string* target = *map_slot; - - // Find the insertion point. - string magic_string = strings::Substitute( - "@@protoc_insertion_point($0)", insertion_point_); - string::size_type pos = target->find(magic_string); - - if (pos == string::npos) { - std::cerr << filename_ << ": insertion point \"" << insertion_point_ - << "\" not found." << std::endl; - directory_->had_error_ = true; - return; - } - - if ((pos > 3) && (target->substr(pos - 3, 2) == "/*")) { - // Support for inline "/* @@protoc_insertion_point() */" - pos = pos - 3; - } else { - // Seek backwards to the beginning of the line, which is where we will - // insert the data. Note that this has the effect of pushing the - // insertion point down, so the data is inserted before it. This is - // intentional because it means that multiple insertions at the same point - // will end up in the expected order in the final output. - pos = target->find_last_of('\n', pos); - if (pos == string::npos) { - // Insertion point is on the first line. - pos = 0; - } else { - // Advance to character after '\n'. - ++pos; - } - } - - // Extract indent. - string indent_(*target, pos, target->find_first_not_of(" \t", pos) - pos); - - if (indent_.empty()) { - // No indent. This makes things easier. - target->insert(pos, data_); - UpdateMetadata(pos, data_.size()); - } else { - // Calculate how much space we need. - int indent_size = 0; - for (int i = 0; i < data_.size(); i++) { - if (data_[i] == '\n') indent_size += indent_.size(); - } - - // Make a hole for it. - target->insert(pos, data_.size() + indent_size, '\0'); - UpdateMetadata(pos, data_.size() + indent_size); - - // Now copy in the data. - string::size_type data_pos = 0; - char* target_ptr = string_as_array(target) + pos; - while (data_pos < data_.size()) { - // Copy indent. - memcpy(target_ptr, indent_.data(), indent_.size()); - target_ptr += indent_.size(); - - // Copy line from data_. - // We already guaranteed that data_ ends with a newline (above), so this - // search can't fail. - string::size_type line_length = - data_.find_first_of('\n', data_pos) + 1 - data_pos; - memcpy(target_ptr, data_.data() + data_pos, line_length); - target_ptr += line_length; - data_pos += line_length; - } - - GOOGLE_CHECK_EQ(target_ptr, - string_as_array(target) + pos + data_.size() + indent_size); - } - } -} - -// =================================================================== - -#if defined(_WIN32) && !defined(__CYGWIN__) -const char* const CommandLineInterface::kPathSeparator = ";"; -#else -const char* const CommandLineInterface::kPathSeparator = ":"; -#endif - -CommandLineInterface::CommandLineInterface() - : mode_(MODE_COMPILE), - print_mode_(PRINT_NONE), - error_format_(ERROR_FORMAT_GCC), - direct_dependencies_explicitly_set_(false), - direct_dependencies_violation_msg_( - kDefaultDirectDependenciesViolationMsg), - imports_in_descriptor_set_(false), - source_info_in_descriptor_set_(false), - disallow_services_(false) {} -CommandLineInterface::~CommandLineInterface() {} - -void CommandLineInterface::RegisterGenerator(const string& flag_name, - CodeGenerator* generator, - const string& help_text) { - GeneratorInfo info; - info.flag_name = flag_name; - info.generator = generator; - info.help_text = help_text; - generators_by_flag_name_[flag_name] = info; -} - -void CommandLineInterface::RegisterGenerator(const string& flag_name, - const string& option_flag_name, - CodeGenerator* generator, - const string& help_text) { - GeneratorInfo info; - info.flag_name = flag_name; - info.option_flag_name = option_flag_name; - info.generator = generator; - info.help_text = help_text; - generators_by_flag_name_[flag_name] = info; - generators_by_option_name_[option_flag_name] = info; -} - -void CommandLineInterface::AllowPlugins(const string& exe_name_prefix) { - plugin_prefix_ = exe_name_prefix; -} - -int CommandLineInterface::Run(int argc, const char* const argv[]) { - Clear(); - switch (ParseArguments(argc, argv)) { - case PARSE_ARGUMENT_DONE_AND_EXIT: - return 0; - case PARSE_ARGUMENT_FAIL: - return 1; - case PARSE_ARGUMENT_DONE_AND_CONTINUE: - break; - } - - std::vector parsed_files; - // null unless descriptor_set_in_names_.empty() - std::unique_ptr disk_source_tree; - std::unique_ptr error_collector; - std::unique_ptr descriptor_pool; - std::unique_ptr descriptor_database; - if (descriptor_set_in_names_.empty()) { - disk_source_tree.reset(new DiskSourceTree()); - if (!InitializeDiskSourceTree(disk_source_tree.get())) { - return 1; - } - error_collector.reset( - new ErrorPrinter(error_format_, disk_source_tree.get())); - - SourceTreeDescriptorDatabase* database = - new SourceTreeDescriptorDatabase(disk_source_tree.get()); - database->RecordErrorsTo(error_collector.get()); - descriptor_database.reset(database); - descriptor_pool.reset(new DescriptorPool( - descriptor_database.get(), database->GetValidationErrorCollector())); - } else { - error_collector.reset(new ErrorPrinter(error_format_)); - - SimpleDescriptorDatabase* database = new SimpleDescriptorDatabase(); - descriptor_database.reset(database); - if (!PopulateSimpleDescriptorDatabase(database)) { - return 1; - } - descriptor_pool.reset(new DescriptorPool(database, error_collector.get())); - } - descriptor_pool->EnforceWeakDependencies(true); - if (!ParseInputFiles(descriptor_pool.get(), &parsed_files)) { - return 1; - } - - - // We construct a separate GeneratorContext for each output location. Note - // that two code generators may output to the same location, in which case - // they should share a single GeneratorContext so that OpenForInsert() works. - GeneratorContextMap output_directories; - - // Generate output. - if (mode_ == MODE_COMPILE) { - for (int i = 0; i < output_directives_.size(); i++) { - string output_location = output_directives_[i].output_location; - if (!HasSuffixString(output_location, ".zip") && - !HasSuffixString(output_location, ".jar")) { - AddTrailingSlash(&output_location); - } - GeneratorContextImpl** map_slot = &output_directories[output_location]; - - if (*map_slot == NULL) { - // First time we've seen this output location. - *map_slot = new GeneratorContextImpl(parsed_files); - } - - if (!GenerateOutput(parsed_files, output_directives_[i], *map_slot)) { - STLDeleteValues(&output_directories); - return 1; - } - } - } - - // Write all output to disk. - for (GeneratorContextMap::iterator iter = output_directories.begin(); - iter != output_directories.end(); ++iter) { - const string& location = iter->first; - GeneratorContextImpl* directory = iter->second; - if (HasSuffixString(location, "/")) { - if (!directory->WriteAllToDisk(location)) { - STLDeleteValues(&output_directories); - return 1; - } - } else { - if (HasSuffixString(location, ".jar")) { - directory->AddJarManifest(); - } - - if (!directory->WriteAllToZip(location)) { - STLDeleteValues(&output_directories); - return 1; - } - } - } - - if (!dependency_out_name_.empty()) { - GOOGLE_DCHECK(disk_source_tree.get()); - if (!GenerateDependencyManifestFile(parsed_files, output_directories, - disk_source_tree.get())) { - return 1; - } - } - - STLDeleteValues(&output_directories); - - if (!descriptor_set_out_name_.empty()) { - if (!WriteDescriptorSet(parsed_files)) { - return 1; - } - } - - if (mode_ == MODE_ENCODE || mode_ == MODE_DECODE) { - if (codec_type_.empty()) { - // HACK: Define an EmptyMessage type to use for decoding. - DescriptorPool pool; - FileDescriptorProto file; - file.set_name("empty_message.proto"); - file.add_message_type()->set_name("EmptyMessage"); - GOOGLE_CHECK(pool.BuildFile(file) != NULL); - codec_type_ = "EmptyMessage"; - if (!EncodeOrDecode(&pool)) { - return 1; - } - } else { - if (!EncodeOrDecode(descriptor_pool.get())) { - return 1; - } - } - } - - if (error_collector->FoundErrors()) { - return 1; - } - - if (mode_ == MODE_PRINT) { - switch (print_mode_) { - case PRINT_FREE_FIELDS: - for (int i = 0; i < parsed_files.size(); ++i) { - const FileDescriptor* fd = parsed_files[i]; - for (int j = 0; j < fd->message_type_count(); ++j) { - PrintFreeFieldNumbers(fd->message_type(j)); - } - } - break; - case PRINT_NONE: - GOOGLE_LOG(ERROR) << "If the code reaches here, it usually means a bug of " - "flag parsing in the CommandLineInterface."; - return 1; - - // Do not add a default case. - } - } - - return 0; -} - -bool CommandLineInterface::InitializeDiskSourceTree( - DiskSourceTree* source_tree) { - AddDefaultProtoPaths(&proto_path_); - - // Set up the source tree. - for (int i = 0; i < proto_path_.size(); i++) { - source_tree->MapPath(proto_path_[i].first, proto_path_[i].second); - } - - // Map input files to virtual paths if possible. - if (!MakeInputsBeProtoPathRelative(source_tree)) { - return false; - } - return true; -} - -bool CommandLineInterface::PopulateSimpleDescriptorDatabase( - SimpleDescriptorDatabase* database) { - for (int i = 0; i < descriptor_set_in_names_.size(); i++) { - int fd; - do { - fd = open(descriptor_set_in_names_[i].c_str(), O_RDONLY | O_BINARY); - } while (fd < 0 && errno == EINTR); - if (fd < 0) { - std::cerr << descriptor_set_in_names_[i] << ": " - << strerror(ENOENT) << std::endl; - return false; - } - - FileDescriptorSet file_descriptor_set; - bool parsed = file_descriptor_set.ParseFromFileDescriptor(fd); - if (close(fd) != 0) { - std::cerr << descriptor_set_in_names_[i] << ": close: " - << strerror(errno) - << std::endl; - return false; - } - - if (!parsed) { - std::cerr << descriptor_set_in_names_[i] << ": Unable to parse." - << std::endl; - return false; - } - - for (int j = 0; j < file_descriptor_set.file_size(); j++) { - FileDescriptorProto previously_added_file_descriptor_proto; - if (database->FindFileByName(file_descriptor_set.file(j).name(), - &previously_added_file_descriptor_proto)) { - // already present - skip - continue; - } - if (!database->Add(file_descriptor_set.file(j))) { - return false; - } - } - } - return true; -} - -bool CommandLineInterface::ParseInputFiles( - DescriptorPool* descriptor_pool, - std::vector* parsed_files) { - - // Parse each file. - for (int i = 0; i < input_files_.size(); i++) { - // Import the file. - descriptor_pool->AddUnusedImportTrackFile(input_files_[i]); - const FileDescriptor* parsed_file = - descriptor_pool->FindFileByName(input_files_[i]); - descriptor_pool->ClearUnusedImportTrackFiles(); - if (parsed_file == NULL) { - if (!descriptor_set_in_names_.empty()) { - std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl; - } - return false; - } - parsed_files->push_back(parsed_file); - - // Enforce --disallow_services. - if (disallow_services_ && parsed_file->service_count() > 0) { - std::cerr << parsed_file->name() << ": This file contains services, but " - "--disallow_services was used." << std::endl; - return false; - } - - // Enforce --direct_dependencies - if (direct_dependencies_explicitly_set_) { - bool indirect_imports = false; - for (int i = 0; i < parsed_file->dependency_count(); i++) { - if (direct_dependencies_.find(parsed_file->dependency(i)->name()) == - direct_dependencies_.end()) { - indirect_imports = true; - std::cerr << parsed_file->name() << ": " - << StringReplace(direct_dependencies_violation_msg_, "%s", - parsed_file->dependency(i)->name(), - true /* replace_all */) - << std::endl; - } - } - if (indirect_imports) { - return false; - } - } - } - return true; -} - -void CommandLineInterface::Clear() { - // Clear all members that are set by Run(). Note that we must not clear - // members which are set by other methods before Run() is called. - executable_name_.clear(); - proto_path_.clear(); - input_files_.clear(); - direct_dependencies_.clear(); - direct_dependencies_violation_msg_ = kDefaultDirectDependenciesViolationMsg; - output_directives_.clear(); - codec_type_.clear(); - descriptor_set_in_names_.clear(); - descriptor_set_out_name_.clear(); - dependency_out_name_.clear(); - - mode_ = MODE_COMPILE; - print_mode_ = PRINT_NONE; - imports_in_descriptor_set_ = false; - source_info_in_descriptor_set_ = false; - disallow_services_ = false; - direct_dependencies_explicitly_set_ = false; -} - -bool CommandLineInterface::MakeInputsBeProtoPathRelative( - DiskSourceTree* source_tree) { - for (int i = 0; i < input_files_.size(); i++) { - // If the input file path is not a physical file path, it must be a virtual - // path. - if (access(input_files_[i].c_str(), F_OK) < 0) { - string disk_file; - if (source_tree->VirtualFileToDiskFile(input_files_[i], &disk_file)) { - return true; - } else { - std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl; - return false; - } - } - string virtual_file, shadowing_disk_file; - switch (source_tree->DiskFileToVirtualFile( - input_files_[i], &virtual_file, &shadowing_disk_file)) { - case DiskSourceTree::SUCCESS: - input_files_[i] = virtual_file; - break; - case DiskSourceTree::SHADOWED: - std::cerr << input_files_[i] - << ": Input is shadowed in the --proto_path by \"" - << shadowing_disk_file - << "\". Either use the latter file as your input or reorder " - "the --proto_path so that the former file's location " - "comes first." << std::endl; - return false; - case DiskSourceTree::CANNOT_OPEN: - std::cerr << input_files_[i] << ": " << strerror(errno) << std::endl; - return false; - case DiskSourceTree::NO_MAPPING: { - // Try to interpret the path as a virtual path. - string disk_file; - if (source_tree->VirtualFileToDiskFile(input_files_[i], &disk_file)) { - return true; - } else { - // The input file path can't be mapped to any --proto_path and it also - // can't be interpreted as a virtual path. - std::cerr - << input_files_[i] - << ": File does not reside within any path " - "specified using --proto_path (or -I). You must specify a " - "--proto_path which encompasses this file. Note that the " - "proto_path must be an exact prefix of the .proto file " - "names -- protoc is too dumb to figure out when two paths " - "(e.g. absolute and relative) are equivalent (it's harder " - "than you think)." - << std::endl; - return false; - } - } - } - } - - return true; -} - -bool CommandLineInterface::ExpandArgumentFile(const string& file, - std::vector* arguments) { - // The argument file is searched in the working directory only. We don't - // use the proto import path here. - std::ifstream file_stream(file.c_str()); - if (!file_stream.is_open()) { - return false; - } - string argument; - // We don't support any kind of shell expansion right now. - while (std::getline(file_stream, argument)) { - arguments->push_back(argument); - } - return true; -} - -CommandLineInterface::ParseArgumentStatus -CommandLineInterface::ParseArguments(int argc, const char* const argv[]) { - executable_name_ = argv[0]; - - std::vector arguments; - for (int i = 1; i < argc; ++i) { - if (argv[i][0] == '@') { - if (!ExpandArgumentFile(argv[i] + 1, &arguments)) { - std::cerr << "Failed to open argument file: " << (argv[i] + 1) - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - continue; - } - arguments.push_back(argv[i]); - } - - // if no arguments are given, show help - if (arguments.empty()) { - PrintHelpText(); - return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler. - } - - // Iterate through all arguments and parse them. - for (int i = 0; i < arguments.size(); ++i) { - string name, value; - - if (ParseArgument(arguments[i].c_str(), &name, &value)) { - // Returned true => Use the next argument as the flag value. - if (i + 1 == arguments.size() || arguments[i + 1][0] == '-') { - std::cerr << "Missing value for flag: " << name << std::endl; - if (name == "--decode") { - std::cerr << "To decode an unknown message, use --decode_raw." - << std::endl; - } - return PARSE_ARGUMENT_FAIL; - } else { - ++i; - value = arguments[i]; - } - } - - ParseArgumentStatus status = InterpretArgument(name, value); - if (status != PARSE_ARGUMENT_DONE_AND_CONTINUE) - return status; - } - - // Make sure each plugin option has a matching plugin output. - bool foundUnknownPluginOption = false; - for (std::map::const_iterator i = plugin_parameters_.begin(); - i != plugin_parameters_.end(); ++i) { - if (plugins_.find(i->first) != plugins_.end()) { - continue; - } - bool foundImplicitPlugin = false; - for (std::vector::const_iterator j = output_directives_.begin(); - j != output_directives_.end(); ++j) { - if (j->generator == NULL) { - string plugin_name = PluginName(plugin_prefix_ , j->name); - if (plugin_name == i->first) { - foundImplicitPlugin = true; - break; - } - } - } - if (!foundImplicitPlugin) { - std::cerr << "Unknown flag: " - // strip prefix + "gen-" and add back "_opt" - << "--" + i->first.substr(plugin_prefix_.size() + 4) + "_opt" - << std::endl; - foundUnknownPluginOption = true; - } - } - if (foundUnknownPluginOption) { - return PARSE_ARGUMENT_FAIL; - } - - // If no --proto_path was given, use the current working directory. - if (proto_path_.empty()) { - // Don't use make_pair as the old/default standard library on Solaris - // doesn't support it without explicit template parameters, which are - // incompatible with C++0x's make_pair. - proto_path_.push_back(std::pair("", ".")); - } - - // Check some errror cases. - bool decoding_raw = (mode_ == MODE_DECODE) && codec_type_.empty(); - if (decoding_raw && !input_files_.empty()) { - std::cerr << "When using --decode_raw, no input files should be given." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } else if (!decoding_raw && input_files_.empty()) { - std::cerr << "Missing input file." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (mode_ == MODE_COMPILE && output_directives_.empty() && - descriptor_set_out_name_.empty()) { - std::cerr << "Missing output directives." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (mode_ != MODE_COMPILE && !dependency_out_name_.empty()) { - std::cerr << "Can only use --dependency_out=FILE when generating code." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (!dependency_out_name_.empty() && input_files_.size() > 1) { - std::cerr - << "Can only process one input file when using --dependency_out=FILE." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (imports_in_descriptor_set_ && descriptor_set_out_name_.empty()) { - std::cerr << "--include_imports only makes sense when combined with " - "--descriptor_set_out." << std::endl; - } - if (source_info_in_descriptor_set_ && descriptor_set_out_name_.empty()) { - std::cerr << "--include_source_info only makes sense when combined with " - "--descriptor_set_out." << std::endl; - } - - return PARSE_ARGUMENT_DONE_AND_CONTINUE; -} - -bool CommandLineInterface::ParseArgument(const char* arg, - string* name, string* value) { - bool parsed_value = false; - - if (arg[0] != '-') { - // Not a flag. - name->clear(); - parsed_value = true; - *value = arg; - } else if (arg[1] == '-') { - // Two dashes: Multi-character name, with '=' separating name and - // value. - const char* equals_pos = strchr(arg, '='); - if (equals_pos != NULL) { - *name = string(arg, equals_pos - arg); - *value = equals_pos + 1; - parsed_value = true; - } else { - *name = arg; - } - } else { - // One dash: One-character name, all subsequent characters are the - // value. - if (arg[1] == '\0') { - // arg is just "-". We treat this as an input file, except that at - // present this will just lead to a "file not found" error. - name->clear(); - *value = arg; - parsed_value = true; - } else { - *name = string(arg, 2); - *value = arg + 2; - parsed_value = !value->empty(); - } - } - - // Need to return true iff the next arg should be used as the value for this - // one, false otherwise. - - if (parsed_value) { - // We already parsed a value for this flag. - return false; - } - - if (*name == "-h" || *name == "--help" || - *name == "--disallow_services" || - *name == "--include_imports" || - *name == "--include_source_info" || - *name == "--version" || - *name == "--decode_raw" || - *name == "--print_free_field_numbers") { - // HACK: These are the only flags that don't take a value. - // They probably should not be hard-coded like this but for now it's - // not worth doing better. - return false; - } - - // Next argument is the flag value. - return true; -} - -CommandLineInterface::ParseArgumentStatus -CommandLineInterface::InterpretArgument(const string& name, - const string& value) { - if (name.empty()) { - // Not a flag. Just a filename. - if (value.empty()) { - std::cerr - << "You seem to have passed an empty string as one of the " - "arguments to " << executable_name_ - << ". This is actually " - "sort of hard to do. Congrats. Unfortunately it is not valid " - "input so the program is going to die now." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - input_files_.push_back(value); - - } else if (name == "-I" || name == "--proto_path") { - if (!descriptor_set_in_names_.empty()) { - std::cerr << "Only one of " << name - << " and --descriptor_set_in can be specified." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - // Java's -classpath (and some other languages) delimits path components - // with colons. Let's accept that syntax too just to make things more - // intuitive. - std::vector parts = Split( - value, CommandLineInterface::kPathSeparator, - true); - - for (int i = 0; i < parts.size(); i++) { - string virtual_path; - string disk_path; - - string::size_type equals_pos = parts[i].find_first_of('='); - if (equals_pos == string::npos) { - virtual_path = ""; - disk_path = parts[i]; - } else { - virtual_path = parts[i].substr(0, equals_pos); - disk_path = parts[i].substr(equals_pos + 1); - } - - if (disk_path.empty()) { - std::cerr - << "--proto_path passed empty directory name. (Use \".\" for " - "current directory.)" << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - // Make sure disk path exists, warn otherwise. - if (access(disk_path.c_str(), F_OK) < 0) { - // Try the original path; it may have just happened to have a '=' in it. - if (access(parts[i].c_str(), F_OK) < 0) { - std::cerr << disk_path << ": warning: directory does not exist." - << std::endl; - } else { - virtual_path = ""; - disk_path = parts[i]; - } - } - - // Don't use make_pair as the old/default standard library on Solaris - // doesn't support it without explicit template parameters, which are - // incompatible with C++0x's make_pair. - proto_path_.push_back(std::pair(virtual_path, disk_path)); - } - - } else if (name == "--direct_dependencies") { - if (direct_dependencies_explicitly_set_) { - std::cerr << name << " may only be passed once. To specify multiple " - "direct dependencies, pass them all as a single " - "parameter separated by ':'." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - direct_dependencies_explicitly_set_ = true; - std::vector direct = Split(value, ":", true); - GOOGLE_DCHECK(direct_dependencies_.empty()); - direct_dependencies_.insert(direct.begin(), direct.end()); - - } else if (name == "--direct_dependencies_violation_msg") { - direct_dependencies_violation_msg_ = value; - - } else if (name == "--descriptor_set_in") { - if (!descriptor_set_in_names_.empty()) { - std::cerr << name << " may only be passed once. To specify multiple " - "descriptor sets, pass them all as a single " - "parameter separated by '" - << CommandLineInterface::kPathSeparator << "'." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (value.empty()) { - std::cerr << name << " requires a non-empty value." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (!proto_path_.empty()) { - std::cerr << "Only one of " << name - << " and --proto_path can be specified." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (!dependency_out_name_.empty()) { - std::cerr << name << " cannot be used with --dependency_out." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - descriptor_set_in_names_ = Split( - value, CommandLineInterface::kPathSeparator, - true); - - } else if (name == "-o" || name == "--descriptor_set_out") { - if (!descriptor_set_out_name_.empty()) { - std::cerr << name << " may only be passed once." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (value.empty()) { - std::cerr << name << " requires a non-empty value." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (mode_ != MODE_COMPILE) { - std::cerr - << "Cannot use --encode or --decode and generate descriptors at the " - "same time." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - descriptor_set_out_name_ = value; - - } else if (name == "--dependency_out") { - if (!dependency_out_name_.empty()) { - std::cerr << name << " may only be passed once." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (value.empty()) { - std::cerr << name << " requires a non-empty value." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (!descriptor_set_in_names_.empty()) { - std::cerr << name << " cannot be used with --descriptor_set_in." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - dependency_out_name_ = value; - - } else if (name == "--include_imports") { - if (imports_in_descriptor_set_) { - std::cerr << name << " may only be passed once." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - imports_in_descriptor_set_ = true; - - } else if (name == "--include_source_info") { - if (source_info_in_descriptor_set_) { - std::cerr << name << " may only be passed once." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - source_info_in_descriptor_set_ = true; - - } else if (name == "-h" || name == "--help") { - PrintHelpText(); - return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler. - - } else if (name == "--version") { - if (!version_info_.empty()) { - std::cout << version_info_ << std::endl; - } - std::cout << "libprotoc " - << protobuf::internal::VersionString(GOOGLE_PROTOBUF_VERSION) - << std::endl; - return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler. - - } else if (name == "--disallow_services") { - disallow_services_ = true; - - } else if (name == "--encode" || name == "--decode" || - name == "--decode_raw") { - if (mode_ != MODE_COMPILE) { - std::cerr << "Only one of --encode and --decode can be specified." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (!output_directives_.empty() || !descriptor_set_out_name_.empty()) { - std::cerr << "Cannot use " << name - << " and generate code or descriptors at the same time." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - mode_ = (name == "--encode") ? MODE_ENCODE : MODE_DECODE; - - if (value.empty() && name != "--decode_raw") { - std::cerr << "Type name for " << name << " cannot be blank." << std::endl; - if (name == "--decode") { - std::cerr << "To decode an unknown message, use --decode_raw." - << std::endl; - } - return PARSE_ARGUMENT_FAIL; - } else if (!value.empty() && name == "--decode_raw") { - std::cerr << "--decode_raw does not take a parameter." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - codec_type_ = value; - - } else if (name == "--error_format") { - if (value == "gcc") { - error_format_ = ERROR_FORMAT_GCC; - } else if (value == "msvs") { - error_format_ = ERROR_FORMAT_MSVS; - } else { - std::cerr << "Unknown error format: " << value << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - } else if (name == "--plugin") { - if (plugin_prefix_.empty()) { - std::cerr << "This compiler does not support plugins." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - string plugin_name; - string path; - - string::size_type equals_pos = value.find_first_of('='); - if (equals_pos == string::npos) { - // Use the basename of the file. - string::size_type slash_pos = value.find_last_of('/'); - if (slash_pos == string::npos) { - plugin_name = value; - } else { - plugin_name = value.substr(slash_pos + 1); - } - path = value; - } else { - plugin_name = value.substr(0, equals_pos); - path = value.substr(equals_pos + 1); - } - - plugins_[plugin_name] = path; - - } else if (name == "--print_free_field_numbers") { - if (mode_ != MODE_COMPILE) { - std::cerr << "Cannot use " << name - << " and use --encode, --decode or print " - << "other info at the same time." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - if (!output_directives_.empty() || !descriptor_set_out_name_.empty()) { - std::cerr << "Cannot use " << name - << " and generate code or descriptors at the same time." - << std::endl; - return PARSE_ARGUMENT_FAIL; - } - mode_ = MODE_PRINT; - print_mode_ = PRINT_FREE_FIELDS; - } else { - // Some other flag. Look it up in the generators list. - const GeneratorInfo* generator_info = - FindOrNull(generators_by_flag_name_, name); - if (generator_info == NULL && - (plugin_prefix_.empty() || !HasSuffixString(name, "_out"))) { - // Check if it's a generator option flag. - generator_info = FindOrNull(generators_by_option_name_, name); - if (generator_info != NULL) { - string* parameters = &generator_parameters_[generator_info->flag_name]; - if (!parameters->empty()) { - parameters->append(","); - } - parameters->append(value); - } else if (HasPrefixString(name, "--") && HasSuffixString(name, "_opt")) { - string* parameters = - &plugin_parameters_[PluginName(plugin_prefix_, name)]; - if (!parameters->empty()) { - parameters->append(","); - } - parameters->append(value); - } else { - std::cerr << "Unknown flag: " << name << std::endl; - return PARSE_ARGUMENT_FAIL; - } - } else { - // It's an output flag. Add it to the output directives. - if (mode_ != MODE_COMPILE) { - std::cerr << "Cannot use --encode, --decode or print .proto info and " - "generate code at the same time." << std::endl; - return PARSE_ARGUMENT_FAIL; - } - - OutputDirective directive; - directive.name = name; - if (generator_info == NULL) { - directive.generator = NULL; - } else { - directive.generator = generator_info->generator; - } - - // Split value at ':' to separate the generator parameter from the - // filename. However, avoid doing this if the colon is part of a valid - // Windows-style absolute path. - string::size_type colon_pos = value.find_first_of(':'); - if (colon_pos == string::npos || IsWindowsAbsolutePath(value)) { - directive.output_location = value; - } else { - directive.parameter = value.substr(0, colon_pos); - directive.output_location = value.substr(colon_pos + 1); - } - - output_directives_.push_back(directive); - } - } - - return PARSE_ARGUMENT_DONE_AND_CONTINUE; -} - -void CommandLineInterface::PrintHelpText() { - // Sorry for indentation here; line wrapping would be uglier. - std::cout << -"Usage: " << executable_name_ << " [OPTION] PROTO_FILES\n" -"Parse PROTO_FILES and generate output based on the options given:\n" -" -IPATH, --proto_path=PATH Specify the directory in which to search for\n" -" imports. May be specified multiple times;\n" -" directories will be searched in order. If not\n" -" given, the current working directory is used.\n" -" --version Show version info and exit.\n" -" -h, --help Show this text and exit.\n" -" --encode=MESSAGE_TYPE Read a text-format message of the given type\n" -" from standard input and write it in binary\n" -" to standard output. The message type must\n" -" be defined in PROTO_FILES or their imports.\n" -" --decode=MESSAGE_TYPE Read a binary message of the given type from\n" -" standard input and write it in text format\n" -" to standard output. The message type must\n" -" be defined in PROTO_FILES or their imports.\n" -" --decode_raw Read an arbitrary protocol message from\n" -" standard input and write the raw tag/value\n" -" pairs in text format to standard output. No\n" -" PROTO_FILES should be given when using this\n" -" flag.\n" -" --descriptor_set_in=FILES Specifies a delimited list of FILES\n" -" each containing a FileDescriptorSet (a\n" -" protocol buffer defined in descriptor.proto).\n" -" The FileDescriptor for each of the PROTO_FILES\n" -" provided will be loaded from these\n" -" FileDescriptorSets. If a FileDescriptor\n" -" appears multiple times, the first occurrence\n" -" will be used.\n" -" -oFILE, Writes a FileDescriptorSet (a protocol buffer,\n" -" --descriptor_set_out=FILE defined in descriptor.proto) containing all of\n" -" the input files to FILE.\n" -" --include_imports When using --descriptor_set_out, also include\n" -" all dependencies of the input files in the\n" -" set, so that the set is self-contained.\n" -" --include_source_info When using --descriptor_set_out, do not strip\n" -" SourceCodeInfo from the FileDescriptorProto.\n" -" This results in vastly larger descriptors that\n" -" include information about the original\n" -" location of each decl in the source file as\n" -" well as surrounding comments.\n" -" --dependency_out=FILE Write a dependency output file in the format\n" -" expected by make. This writes the transitive\n" -" set of input file paths to FILE\n" -" --error_format=FORMAT Set the format in which to print errors.\n" -" FORMAT may be 'gcc' (the default) or 'msvs'\n" -" (Microsoft Visual Studio format).\n" -" --print_free_field_numbers Print the free field numbers of the messages\n" -" defined in the given proto files. Groups share\n" -" the same field number space with the parent \n" -" message. Extension ranges are counted as \n" -" occupied fields numbers.\n" - << std::endl; - if (!plugin_prefix_.empty()) { - std::cout << -" --plugin=EXECUTABLE Specifies a plugin executable to use.\n" -" Normally, protoc searches the PATH for\n" -" plugins, but you may specify additional\n" -" executables not in the path using this flag.\n" -" Additionally, EXECUTABLE may be of the form\n" -" NAME=PATH, in which case the given plugin name\n" -" is mapped to the given executable even if\n" -" the executable's own name differs." << std::endl; - } - - for (GeneratorMap::iterator iter = generators_by_flag_name_.begin(); - iter != generators_by_flag_name_.end(); ++iter) { - // FIXME(kenton): If the text is long enough it will wrap, which is ugly, - // but fixing this nicely (e.g. splitting on spaces) is probably more - // trouble than it's worth. - std::cout << " " << iter->first << "=OUT_DIR " - << string(19 - iter->first.size(), ' ') // Spaces for alignment. - << iter->second.help_text << std::endl; - } - std::cerr << -" @ Read options and filenames from file. If a\n" -" relative file path is specified, the file\n" -" will be searched in the working directory.\n" -" The --proto_path option will not affect how\n" -" this argument file is searched. Content of\n" -" the file will be expanded in the position of\n" -" @ as in the argument list. Note\n" -" that shell expansion is not applied to the\n" -" content of the file (i.e., you cannot use\n" -" quotes, wildcards, escapes, commands, etc.).\n" -" Each line corresponds to a single argument,\n" -" even if it contains spaces." - << std::endl; -} - -bool CommandLineInterface::GenerateOutput( - const std::vector& parsed_files, - const OutputDirective& output_directive, - GeneratorContext* generator_context) { - // Call the generator. - string error; - if (output_directive.generator == NULL) { - // This is a plugin. - GOOGLE_CHECK(HasPrefixString(output_directive.name, "--") && - HasSuffixString(output_directive.name, "_out")) - << "Bad name for plugin generator: " << output_directive.name; - - string plugin_name = PluginName(plugin_prefix_ , output_directive.name); - string parameters = output_directive.parameter; - if (!plugin_parameters_[plugin_name].empty()) { - if (!parameters.empty()) { - parameters.append(","); - } - parameters.append(plugin_parameters_[plugin_name]); - } - if (!GeneratePluginOutput(parsed_files, plugin_name, - parameters, - generator_context, &error)) { - std::cerr << output_directive.name << ": " << error << std::endl; - return false; - } - } else { - // Regular generator. - string parameters = output_directive.parameter; - if (!generator_parameters_[output_directive.name].empty()) { - if (!parameters.empty()) { - parameters.append(","); - } - parameters.append(generator_parameters_[output_directive.name]); - } - if (!output_directive.generator->GenerateAll( - parsed_files, parameters, generator_context, &error)) { - // Generator returned an error. - std::cerr << output_directive.name << ": " << error << std::endl; - return false; - } - } - - return true; -} - -bool CommandLineInterface::GenerateDependencyManifestFile( - const std::vector& parsed_files, - const GeneratorContextMap& output_directories, - DiskSourceTree* source_tree) { - FileDescriptorSet file_set; - - std::set already_seen; - for (int i = 0; i < parsed_files.size(); i++) { - GetTransitiveDependencies(parsed_files[i], - false, - false, - &already_seen, - file_set.mutable_file()); - } - - std::vector output_filenames; - for (GeneratorContextMap::const_iterator iter = output_directories.begin(); - iter != output_directories.end(); ++iter) { - const string& location = iter->first; - GeneratorContextImpl* directory = iter->second; - std::vector relative_output_filenames; - directory->GetOutputFilenames(&relative_output_filenames); - for (int i = 0; i < relative_output_filenames.size(); i++) { - string output_filename = location + relative_output_filenames[i]; - if (output_filename.compare(0, 2, "./") == 0) { - output_filename = output_filename.substr(2); - } - output_filenames.push_back(output_filename); - } - } - - int fd; - do { - fd = open(dependency_out_name_.c_str(), - O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); - } while (fd < 0 && errno == EINTR); - - if (fd < 0) { - perror(dependency_out_name_.c_str()); - return false; - } - - io::FileOutputStream out(fd); - io::Printer printer(&out, '$'); - - for (int i = 0; i < output_filenames.size(); i++) { - printer.Print(output_filenames[i].c_str()); - if (i == output_filenames.size() - 1) { - printer.Print(":"); - } else { - printer.Print(" \\\n"); - } - } - - for (int i = 0; i < file_set.file_size(); i++) { - const FileDescriptorProto& file = file_set.file(i); - const string& virtual_file = file.name(); - string disk_file; - if (source_tree && - source_tree->VirtualFileToDiskFile(virtual_file, &disk_file)) { - printer.Print(" $disk_file$", "disk_file", disk_file); - if (i < file_set.file_size() - 1) printer.Print("\\\n"); - } else { - std::cerr << "Unable to identify path for file " << virtual_file - << std::endl; - return false; - } - } - - return true; -} - -bool CommandLineInterface::GeneratePluginOutput( - const std::vector& parsed_files, - const string& plugin_name, - const string& parameter, - GeneratorContext* generator_context, - string* error) { - CodeGeneratorRequest request; - CodeGeneratorResponse response; - string processed_parameter = parameter; - - - // Build the request. - if (!processed_parameter.empty()) { - request.set_parameter(processed_parameter); - } - - - std::set already_seen; - for (int i = 0; i < parsed_files.size(); i++) { - request.add_file_to_generate(parsed_files[i]->name()); - GetTransitiveDependencies(parsed_files[i], - true, // Include json_name for plugins. - true, // Include source code info. - &already_seen, request.mutable_proto_file()); - } - - google::protobuf::compiler::Version* version = - request.mutable_compiler_version(); - version->set_major(GOOGLE_PROTOBUF_VERSION / 1000000); - version->set_minor(GOOGLE_PROTOBUF_VERSION / 1000 % 1000); - version->set_patch(GOOGLE_PROTOBUF_VERSION % 1000); - version->set_suffix(GOOGLE_PROTOBUF_VERSION_SUFFIX); - - // Invoke the plugin. - Subprocess subprocess; - - if (plugins_.count(plugin_name) > 0) { - subprocess.Start(plugins_[plugin_name], Subprocess::EXACT_NAME); - } else { - subprocess.Start(plugin_name, Subprocess::SEARCH_PATH); - } - - string communicate_error; - if (!subprocess.Communicate(request, &response, &communicate_error)) { - *error = strings::Substitute("$0: $1", plugin_name, communicate_error); - return false; - } - - // Write the files. We do this even if there was a generator error in order - // to match the behavior of a compiled-in generator. - std::unique_ptr current_output; - for (int i = 0; i < response.file_size(); i++) { - const CodeGeneratorResponse::File& output_file = response.file(i); - - if (!output_file.insertion_point().empty()) { - string filename = output_file.name(); - // Open a file for insert. - // We reset current_output to NULL first so that the old file is closed - // before the new one is opened. - current_output.reset(); - current_output.reset(generator_context->OpenForInsert( - filename, output_file.insertion_point())); - } else if (!output_file.name().empty()) { - // Starting a new file. Open it. - // We reset current_output to NULL first so that the old file is closed - // before the new one is opened. - current_output.reset(); - current_output.reset(generator_context->Open(output_file.name())); - } else if (current_output == NULL) { - *error = strings::Substitute( - "$0: First file chunk returned by plugin did not specify a file name.", - plugin_name); - return false; - } - - // Use CodedOutputStream for convenience; otherwise we'd need to provide - // our own buffer-copying loop. - io::CodedOutputStream writer(current_output.get()); - writer.WriteString(output_file.content()); - } - - // Check for errors. - if (!response.error().empty()) { - // Generator returned an error. - *error = response.error(); - return false; - } - - return true; -} - -bool CommandLineInterface::EncodeOrDecode(const DescriptorPool* pool) { - // Look up the type. - const Descriptor* type = pool->FindMessageTypeByName(codec_type_); - if (type == NULL) { - std::cerr << "Type not defined: " << codec_type_ << std::endl; - return false; - } - - DynamicMessageFactory dynamic_factory(pool); - std::unique_ptr message(dynamic_factory.GetPrototype(type)->New()); - - if (mode_ == MODE_ENCODE) { - SetFdToTextMode(STDIN_FILENO); - SetFdToBinaryMode(STDOUT_FILENO); - } else { - SetFdToBinaryMode(STDIN_FILENO); - SetFdToTextMode(STDOUT_FILENO); - } - - io::FileInputStream in(STDIN_FILENO); - io::FileOutputStream out(STDOUT_FILENO); - - if (mode_ == MODE_ENCODE) { - // Input is text. - ErrorPrinter error_collector(error_format_); - TextFormat::Parser parser; - parser.RecordErrorsTo(&error_collector); - parser.AllowPartialMessage(true); - - if (!parser.Parse(&in, message.get())) { - std::cerr << "Failed to parse input." << std::endl; - return false; - } - } else { - // Input is binary. - if (!message->ParsePartialFromZeroCopyStream(&in)) { - std::cerr << "Failed to parse input." << std::endl; - return false; - } - } - - if (!message->IsInitialized()) { - std::cerr << "warning: Input message is missing required fields: " - << message->InitializationErrorString() << std::endl; - } - - if (mode_ == MODE_ENCODE) { - // Output is binary. - if (!message->SerializePartialToZeroCopyStream(&out)) { - std::cerr << "output: I/O error." << std::endl; - return false; - } - } else { - // Output is text. - if (!TextFormat::Print(*message, &out)) { - std::cerr << "output: I/O error." << std::endl; - return false; - } - } - - return true; -} - -bool CommandLineInterface::WriteDescriptorSet( - const std::vector& parsed_files) { - FileDescriptorSet file_set; - - std::set already_seen; - if (!imports_in_descriptor_set_) { - // Since we don't want to output transitive dependencies, but we do want - // things to be in dependency order, add all dependencies that aren't in - // parsed_files to already_seen. This will short circuit the recursion - // in GetTransitiveDependencies. - std::set to_output; - to_output.insert(parsed_files.begin(), parsed_files.end()); - for (int i = 0; i < parsed_files.size(); i++) { - const FileDescriptor* file = parsed_files[i]; - for (int i = 0; i < file->dependency_count(); i++) { - const FileDescriptor* dependency = file->dependency(i); - // if the dependency isn't in parsed files, mark it as already seen - if (to_output.find(dependency) == to_output.end()) { - already_seen.insert(dependency); - } - } - } - } - for (int i = 0; i < parsed_files.size(); i++) { - GetTransitiveDependencies(parsed_files[i], - true, // Include json_name - source_info_in_descriptor_set_, - &already_seen, file_set.mutable_file()); - } - - int fd; - do { - fd = open(descriptor_set_out_name_.c_str(), - O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); - } while (fd < 0 && errno == EINTR); - - if (fd < 0) { - perror(descriptor_set_out_name_.c_str()); - return false; - } - - io::FileOutputStream out(fd); - if (!file_set.SerializeToZeroCopyStream(&out)) { - std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno()) - << std::endl; - out.Close(); - return false; - } - if (!out.Close()) { - std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno()) - << std::endl; - return false; - } - - return true; -} - -void CommandLineInterface::GetTransitiveDependencies( - const FileDescriptor* file, - bool include_json_name, - bool include_source_code_info, - std::set* already_seen, - RepeatedPtrField* output) { - if (!already_seen->insert(file).second) { - // Already saw this file. Skip. - return; - } - - // Add all dependencies. - for (int i = 0; i < file->dependency_count(); i++) { - GetTransitiveDependencies(file->dependency(i), - include_json_name, - include_source_code_info, - already_seen, output); - } - - // Add this file. - FileDescriptorProto* new_descriptor = output->Add(); - file->CopyTo(new_descriptor); - if (include_json_name) { - file->CopyJsonNameTo(new_descriptor); - } - if (include_source_code_info) { - file->CopySourceCodeInfoTo(new_descriptor); - } -} - -namespace { - -// Utility function for PrintFreeFieldNumbers. -// Stores occupied ranges into the ranges parameter, and next level of sub -// message types into the nested_messages parameter. The FieldRange is left -// inclusive, right exclusive. i.e. [a, b). -// -// Nested Messages: -// Note that it only stores the nested message type, iff the nested type is -// either a direct child of the given descriptor, or the nested type is a -// decendent of the given descriptor and all the nodes between the -// nested type and the given descriptor are group types. e.g. -// -// message Foo { -// message Bar { -// message NestedBar {} -// } -// group Baz = 1 { -// group NestedBazGroup = 2 { -// message Quz { -// message NestedQuz {} -// } -// } -// message NestedBaz {} -// } -// } -// -// In this case, Bar, Quz and NestedBaz will be added into the nested types. -// Since free field numbers of group types will not be printed, this makes sure -// the nested message types in groups will not be dropped. The nested_messages -// parameter will contain the direct children (when groups are ignored in the -// tree) of the given descriptor for the caller to traverse. The declaration -// order of the nested messages is also preserved. -typedef std::pair FieldRange; -void GatherOccupiedFieldRanges( - const Descriptor* descriptor, std::set* ranges, - std::vector* nested_messages) { - std::set groups; - for (int i = 0; i < descriptor->field_count(); ++i) { - const FieldDescriptor* fd = descriptor->field(i); - ranges->insert(FieldRange(fd->number(), fd->number() + 1)); - if (fd->type() == FieldDescriptor::TYPE_GROUP) { - groups.insert(fd->message_type()); - } - } - for (int i = 0; i < descriptor->extension_range_count(); ++i) { - ranges->insert(FieldRange(descriptor->extension_range(i)->start, - descriptor->extension_range(i)->end)); - } - for (int i = 0; i < descriptor->reserved_range_count(); ++i) { - ranges->insert(FieldRange(descriptor->reserved_range(i)->start, - descriptor->reserved_range(i)->end)); - } - // Handle the nested messages/groups in declaration order to make it - // post-order strict. - for (int i = 0; i < descriptor->nested_type_count(); ++i) { - const Descriptor* nested_desc = descriptor->nested_type(i); - if (groups.find(nested_desc) != groups.end()) { - GatherOccupiedFieldRanges(nested_desc, ranges, nested_messages); - } else { - nested_messages->push_back(nested_desc); - } - } -} - -// Utility function for PrintFreeFieldNumbers. -// Actually prints the formatted free field numbers for given message name and -// occupied ranges. -void FormatFreeFieldNumbers(const string& name, - const std::set& ranges) { - string output; - StringAppendF(&output, "%-35s free:", name.c_str()); - int next_free_number = 1; - for (std::set::const_iterator i = ranges.begin(); - i != ranges.end(); ++i) { - // This happens when groups re-use parent field numbers, in which - // case we skip the FieldRange entirely. - if (next_free_number >= i->second) continue; - - if (next_free_number < i->first) { - if (next_free_number + 1 == i->first) { - // Singleton - StringAppendF(&output, " %d", next_free_number); - } else { - // Range - StringAppendF(&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); - } - std::cout << output << std::endl; -} - -} // namespace - -void CommandLineInterface::PrintFreeFieldNumbers( - const Descriptor* descriptor) { - std::set ranges; - std::vector nested_messages; - GatherOccupiedFieldRanges(descriptor, &ranges, &nested_messages); - - for (int i = 0; i < nested_messages.size(); ++i) { - PrintFreeFieldNumbers(nested_messages[i]); - } - FormatFreeFieldNumbers(descriptor->full_name(), ranges); -} - - - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/command_line_interface.h b/windows/include/google/protobuf/compiler/command_line_interface.h index 7d3037a9f..27178b1be 100644 --- a/windows/include/google/protobuf/compiler/command_line_interface.h +++ b/windows/include/google/protobuf/compiler/command_line_interface.h @@ -38,24 +38,31 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__ #define GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__ -#include -#include -#include -#include +#include #include +#include #include +#include +#include +#include #include +#include + +#include +#include namespace google { namespace protobuf { -class Descriptor; // descriptor.h -class DescriptorPool; // descriptor.h -class FileDescriptor; // descriptor.h -class FileDescriptorSet; // descriptor.h -class FileDescriptorProto; // descriptor.pb.h -template class RepeatedPtrField; // repeated_field.h -class SimpleDescriptorDatabase; // descriptor_database.h +class Descriptor; // descriptor.h +class DescriptorDatabase; // descriptor_database.h +class DescriptorPool; // descriptor.h +class FileDescriptor; // descriptor.h +class FileDescriptorSet; // descriptor.h +class FileDescriptorProto; // descriptor.pb.h +template +class RepeatedPtrField; // repeated_field.h +class SimpleDescriptorDatabase; // descriptor_database.h namespace compiler { @@ -91,17 +98,17 @@ class DiskSourceTree; // importer.h // protoc --cpp_out=outdir --foo_out=outdir --proto_path=src src/foo.proto // // The .proto file to compile can be specified on the command line using either -// its physical file path, or a virtual path relative to a diretory specified +// its physical file path, or a virtual path relative to a directory specified // in --proto_path. For example, for src/foo.proto, the following two protoc // invocations work the same way: // 1. protoc --proto_path=src src/foo.proto (physical file path) // 2. protoc --proto_path=src foo.proto (virtual path relative to src) // // If a file path can be interpreted both as a physical file path and as a -// relative virtual path, the physical file path takes precendence. +// relative virtual path, the physical file path takes precedence. // // For a full description of the command-line syntax, invoke it with --help. -class LIBPROTOC_EXPORT CommandLineInterface { +class PROTOC_EXPORT CommandLineInterface { public: static const char* const kPathSeparator; @@ -124,9 +131,8 @@ class LIBPROTOC_EXPORT CommandLineInterface { // protoc --foo_out=enable_bar:outdir // The text before the colon is passed to CodeGenerator::Generate() as the // "parameter". - void RegisterGenerator(const string& flag_name, - CodeGenerator* generator, - const string& help_text); + void RegisterGenerator(const std::string& flag_name, CodeGenerator* generator, + const std::string& help_text); // Register a code generator for a language. // Besides flag_name you can specify another option_flag_name that could be @@ -136,10 +142,10 @@ class LIBPROTOC_EXPORT CommandLineInterface { // Then you could invoke the compiler with a command like: // protoc --foo_out=enable_bar:outdir --foo_opt=enable_baz // This will pass "enable_bar,enable_baz" as the parameter to the generator. - void RegisterGenerator(const string& flag_name, - const string& option_flag_name, + void RegisterGenerator(const std::string& flag_name, + const std::string& option_flag_name, CodeGenerator* generator, - const string& help_text); + const std::string& help_text); // Enables "plugins". In this mode, if a command-line flag ends with "_out" // but does not match any registered generator, the compiler will attempt to @@ -149,7 +155,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // The compiler determines the executable name to search for by concatenating // exe_name_prefix with the unrecognized flag name, removing "_out". So, for // example, if exe_name_prefix is "protoc-" and you pass the flag --foo_out, - // the compiler will try to run the program "protoc-foo". + // the compiler will try to run the program "protoc-gen-foo". // // The plugin program should implement the following usage: // plugin [--out=OUTDIR] [--parameter=PARAMETER] PROTO_FILES < DESCRIPTORS @@ -177,7 +183,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // protoc --plug_out=enable_bar:outdir --plug_opt=enable_baz // This will pass "enable_bar,enable_baz" as the parameter to the plugin. // - void AllowPlugins(const string& exe_name_prefix); + void AllowPlugins(const std::string& exe_name_prefix); // Run the Protocol Compiler with the given command-line parameters. // Returns the error code which should be returned by main(). @@ -189,15 +195,13 @@ class LIBPROTOC_EXPORT CommandLineInterface { // DEPRECATED. Calling this method has no effect. Protocol compiler now // always try to find the .proto file relative to the current directory // first and if the file is not found, it will then treat the input path - // as a virutal path. + // as a virtual path. void SetInputsAreProtoPathRelative(bool /* enable */) {} // Provides some text which will be printed when the --version flag is // used. The version of libprotoc will also be printed on the next line // after this text. - void SetVersionInfo(const string& text) { - version_info_ = text; - } + void SetVersionInfo(const std::string& text) { version_info_ = text; } private: @@ -206,16 +210,29 @@ class LIBPROTOC_EXPORT CommandLineInterface { class ErrorPrinter; class GeneratorContextImpl; class MemoryOutputStream; - typedef hash_map GeneratorContextMap; + typedef std::unordered_map> + GeneratorContextMap; // Clear state from previous Run(). void Clear(); + // Remaps the proto file so that it is relative to one of the directories + // in proto_path_. Returns false if an error occurred. + bool MakeProtoProtoPathRelative(DiskSourceTree* source_tree, + std::string* proto, + DescriptorDatabase* fallback_database); + // Remaps each file in input_files_ so that it is relative to one of the - // directories in proto_path_. Returns false if an error occurred. This - // is only used if inputs_are_proto_path_relative_ is false. - bool MakeInputsBeProtoPathRelative( - DiskSourceTree* source_tree); + // directories in proto_path_. Returns false if an error occurred. + bool MakeInputsBeProtoPathRelative(DiskSourceTree* source_tree, + DescriptorDatabase* fallback_database); + + // Fails if these files use proto3 optional and the code generator doesn't + // support it. This is a permanent check. + bool EnforceProto3OptionalSupport( + const std::string& codegen_name, uint64_t supported_features, + const std::vector& parsed_files) const; + // Return status for ParseArguments() and InterpretArgument(). enum ParseArgumentStatus { @@ -229,7 +246,8 @@ class LIBPROTOC_EXPORT CommandLineInterface { // Read an argument file and append the file's content to the list of // arguments. Return false if the file cannot be read. - bool ExpandArgumentFile(const string& file, std::vector* arguments); + bool ExpandArgumentFile(const std::string& file, + std::vector* arguments); // Parses a command-line argument into a name/value pair. Returns // true if the next argument in the argv should be used as the value, @@ -242,23 +260,25 @@ class LIBPROTOC_EXPORT CommandLineInterface { // name = "--cpp_out", value = "src/foo.pb2.cc" // "foo.proto" -> // name = "", value = "foo.proto" - bool ParseArgument(const char* arg, string* name, string* value); + bool ParseArgument(const char* arg, std::string* name, std::string* value); // Interprets arguments parsed with ParseArgument. - ParseArgumentStatus InterpretArgument(const string& name, - const string& value); + ParseArgumentStatus InterpretArgument(const std::string& name, + const std::string& value); // Print the --help text to stderr. void PrintHelpText(); // Loads proto_path_ into the provided source_tree. - bool InitializeDiskSourceTree(DiskSourceTree* source_tree); + bool InitializeDiskSourceTree(DiskSourceTree* source_tree, + DescriptorDatabase* fallback_database); - // Loads descriptor_set_in into the provided database - bool PopulateSimpleDescriptorDatabase(SimpleDescriptorDatabase* database); + // Verify that all the input files exist in the given database. + bool VerifyInputFilesInDescriptors(DescriptorDatabase* fallback_database); // Parses input_files_ into parsed_files bool ParseInputFiles(DescriptorPool* descriptor_pool, + DiskSourceTree* source_tree, std::vector* parsed_files); // Generate the given output file from the given input. @@ -268,8 +288,8 @@ class LIBPROTOC_EXPORT CommandLineInterface { GeneratorContext* generator_context); bool GeneratePluginOutput( const std::vector& parsed_files, - const string& plugin_name, const string& parameter, - GeneratorContext* generator_context, string* error); + const std::string& plugin_name, const std::string& parameter, + GeneratorContext* generator_context, std::string* error); // Implements --encode and --decode. bool EncodeOrDecode(const DescriptorPool* pool); @@ -294,8 +314,7 @@ class LIBPROTOC_EXPORT CommandLineInterface { // If include_json_name is true, populate the json_name field of // FieldDescriptorProto for all fields. static void GetTransitiveDependencies( - const FileDescriptor* file, - bool include_json_name, + const FileDescriptor* file, bool include_json_name, bool include_source_code_info, std::set* already_seen, RepeatedPtrField* output); @@ -319,36 +338,36 @@ class LIBPROTOC_EXPORT CommandLineInterface { // ----------------------------------------------------------------- // The name of the executable as invoked (i.e. argv[0]). - string executable_name_; + std::string executable_name_; // Version info set with SetVersionInfo(). - string version_info_; + std::string version_info_; // Registered generators. struct GeneratorInfo { - string flag_name; - string option_flag_name; + std::string flag_name; + std::string option_flag_name; CodeGenerator* generator; - string help_text; + std::string help_text; }; - typedef std::map GeneratorMap; + typedef std::map GeneratorMap; GeneratorMap generators_by_flag_name_; GeneratorMap generators_by_option_name_; // A map from generator names to the parameters specified using the option // flag. For example, if the user invokes the compiler with: // protoc --foo_out=outputdir --foo_opt=enable_bar ... // Then there will be an entry ("--foo_out", "enable_bar") in this map. - std::map generator_parameters_; + std::map generator_parameters_; // Similar to generator_parameters_, but stores the parameters for plugins. - std::map plugin_parameters_; + std::map plugin_parameters_; // See AllowPlugins(). If this is empty, plugins aren't allowed. - string plugin_prefix_; + std::string plugin_prefix_; // Maps specific plugin names to files. When executing a plugin, this map // is searched first to find the plugin executable. If not found here, the // PATH (or other OS-specific search strategy) is searched. - std::map plugins_; + std::map plugins_; // Stuff parsed from command line. enum Mode { @@ -358,60 +377,63 @@ class LIBPROTOC_EXPORT CommandLineInterface { MODE_PRINT, // Print mode: print info of the given .proto files and exit. }; - Mode mode_; + Mode mode_ = MODE_COMPILE; enum PrintMode { - PRINT_NONE, // Not in MODE_PRINT - PRINT_FREE_FIELDS, // --print_free_fields + PRINT_NONE, // Not in MODE_PRINT + PRINT_FREE_FIELDS, // --print_free_fields }; - PrintMode print_mode_; + PrintMode print_mode_ = PRINT_NONE; enum ErrorFormat { - ERROR_FORMAT_GCC, // GCC error output format (default). - ERROR_FORMAT_MSVS // Visual Studio output (--error_format=msvs). + ERROR_FORMAT_GCC, // GCC error output format (default). + ERROR_FORMAT_MSVS // Visual Studio output (--error_format=msvs). }; - ErrorFormat error_format_; + ErrorFormat error_format_ = ERROR_FORMAT_GCC; - std::vector > - proto_path_; // Search path for proto files. - std::vector input_files_; // Names of the input proto files. + // True if we should treat warnings as errors that fail the compilation. + bool fatal_warnings_ = false; + + std::vector > + proto_path_; // Search path for proto files. + std::vector input_files_; // Names of the input proto files. // Names of proto files which are allowed to be imported. Used by build // systems to enforce depend-on-what-you-import. - std::set direct_dependencies_; - bool direct_dependencies_explicitly_set_; + std::set direct_dependencies_; + bool direct_dependencies_explicitly_set_ = false; // If there's a violation of depend-on-what-you-import, this string will be // presented to the user. "%s" will be replaced with the violating import. - string direct_dependencies_violation_msg_; + std::string direct_dependencies_violation_msg_; // output_directives_ lists all the files we are supposed to output and what // generator to use for each. struct OutputDirective { - string name; // E.g. "--foo_out" - CodeGenerator* generator; // NULL for plugins - string parameter; - string output_location; + std::string name; // E.g. "--foo_out" + CodeGenerator* generator; // NULL for plugins + std::string parameter; + std::string output_location; }; std::vector output_directives_; // When using --encode or --decode, this names the type we are encoding or // decoding. (Empty string indicates --decode_raw.) - string codec_type_; + std::string codec_type_; // If --descriptor_set_in was given, these are filenames containing // parsed FileDescriptorSets to be used for loading protos. Otherwise, empty. - std::vector descriptor_set_in_names_; + std::vector descriptor_set_in_names_; // If --descriptor_set_out was given, this is the filename to which the // FileDescriptorSet should be written. Otherwise, empty. - string descriptor_set_out_name_; + std::string descriptor_set_out_name_; // If --dependency_out was given, this is the path to the file where the // dependency file will be written. Otherwise, empty. - string dependency_out_name_; + std::string dependency_out_name_; // True if --include_imports was given, meaning that we should // write all transitive dependencies to the DescriptorSet. Otherwise, only @@ -420,16 +442,21 @@ class LIBPROTOC_EXPORT CommandLineInterface { // True if --include_source_info was given, meaning that we should not strip // SourceCodeInfo from the DescriptorSet. - bool source_info_in_descriptor_set_; + bool source_info_in_descriptor_set_ = false; // Was the --disallow_services flag used? - bool disallow_services_; + bool disallow_services_ = false; + + // When using --encode, this will be passed to SetSerializationDeterministic. + bool deterministic_output_ = false; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CommandLineInterface); }; } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_COMMAND_LINE_INTERFACE_H__ diff --git a/windows/include/google/protobuf/compiler/command_line_interface_unittest.cc b/windows/include/google/protobuf/compiler/command_line_interface_unittest.cc deleted file mode 100644 index 41eb244a2..000000000 --- a/windows/include/google/protobuf/compiler/command_line_interface_unittest.cc +++ /dev/null @@ -1,2439 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include - -#ifndef _MSC_VER -#include -#endif -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { - -#if defined(_WIN32) -// DO NOT include , instead create functions in io_win32.{h,cc} and import -// them like we do below. -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::dup; -using google::protobuf::internal::win32::dup2; -using google::protobuf::internal::win32::close; -using google::protobuf::internal::win32::open; -using google::protobuf::internal::win32::write; -#endif - -// Disable the whole test when we use tcmalloc for "draconian" heap checks, in -// which case tcmalloc will print warnings that fail the plugin tests. -#if !GOOGLE_PROTOBUF_HEAP_CHECK_DRACONIAN - - -namespace { - -bool FileExists(const string& path) { - return File::Exists(path); -} - -class CommandLineInterfaceTest : public testing::Test { - protected: - virtual void SetUp(); - virtual void TearDown(); - - // Runs the CommandLineInterface with the given command line. The - // command is automatically split on spaces, and the string "$tmpdir" - // is replaced with TestTempDir(). - void Run(const string& command); - void RunWithArgs(std::vector args); - - // ----------------------------------------------------------------- - // Methods to set up the test (called before Run()). - - class NullCodeGenerator; - - // Normally plugins are allowed for all tests. Call this to explicitly - // disable them. - void DisallowPlugins() { disallow_plugins_ = true; } - - // Create a temp file within temp_directory_ with the given name. - // The containing directory is also created if necessary. - void CreateTempFile(const string& name, const string& contents); - - // Create a subdirectory within temp_directory_. - void CreateTempDir(const string& name); - -#ifdef PROTOBUF_OPENSOURCE - // Change working directory to temp directory. - void SwitchToTempDirectory() { - File::ChangeWorkingDirectory(temp_directory_); - } -#else // !PROTOBUF_OPENSOURCE - // TODO(teboring): Figure out how to change and get working directory in - // google3. -#endif // !PROTOBUF_OPENSOURCE - - // ----------------------------------------------------------------- - // Methods to check the test results (called after Run()). - - // Checks that no text was written to stderr during Run(), and Run() - // returned 0. - void ExpectNoErrors(); - - // Checks that Run() returned non-zero and the stderr output is exactly - // the text given. expected_test may contain references to "$tmpdir", - // which will be replaced by the temporary directory path. - void ExpectErrorText(const string& expected_text); - - // Checks that Run() returned non-zero and the stderr contains the given - // substring. - void ExpectErrorSubstring(const string& expected_substring); - - // Like ExpectErrorSubstring, but checks that Run() returned zero. - void ExpectErrorSubstringWithZeroReturnCode( - const string& expected_substring); - - // Checks that the captured stdout is the same as the expected_text. - void ExpectCapturedStdout(const string& expected_text); - - // Checks that Run() returned zero and the stdout contains the given - // substring. - void ExpectCapturedStdoutSubstringWithZeroReturnCode( - const string& expected_substring); - - // Returns true if ExpectErrorSubstring(expected_substring) would pass, but - // does not fail otherwise. - bool HasAlternateErrorSubstring(const string& expected_substring); - - // Checks that MockCodeGenerator::Generate() was called in the given - // context (or the generator in test_plugin.cc, which produces the same - // output). That is, this tests if the generator with the given name - // was called with the given parameter and proto file and produced the - // given output file. This is checked by reading the output file and - // checking that it contains the content that MockCodeGenerator would - // generate given these inputs. message_name is the name of the first - // message that appeared in the proto file; this is just to make extra - // sure that the correct file was parsed. - void ExpectGenerated(const string& generator_name, - const string& parameter, - const string& proto_name, - const string& message_name); - void ExpectGenerated(const string& generator_name, - const string& parameter, - const string& proto_name, - const string& message_name, - const string& output_directory); - void ExpectGeneratedWithMultipleInputs(const string& generator_name, - const string& all_proto_names, - const string& proto_name, - const string& message_name); - void ExpectGeneratedWithInsertions(const string& generator_name, - const string& parameter, - const string& insertions, - const string& proto_name, - const string& message_name); - void CheckGeneratedAnnotations(const string& name, const string& file); - - void ExpectNullCodeGeneratorCalled(const string& parameter); - - - void ReadDescriptorSet(const string& filename, - FileDescriptorSet* descriptor_set); - - void WriteDescriptorSet(const string& filename, - const FileDescriptorSet* descriptor_set); - - void ExpectFileContent(const string& filename, - const string& content); - - private: - // The object we are testing. - CommandLineInterface cli_; - - // Was DisallowPlugins() called? - bool disallow_plugins_; - - // We create a directory within TestTempDir() in order to add extra - // protection against accidentally deleting user files (since we recursively - // delete this directory during the test). This is the full path of that - // directory. - string temp_directory_; - - // The result of Run(). - int return_code_; - - // The captured stderr output. - string error_text_; - - // The captured stdout. - string captured_stdout_; - - // Pointers which need to be deleted later. - std::vector mock_generators_to_delete_; - - NullCodeGenerator* null_generator_; -}; - -class CommandLineInterfaceTest::NullCodeGenerator : public CodeGenerator { - public: - NullCodeGenerator() : called_(false) {} - ~NullCodeGenerator() {} - - mutable bool called_; - mutable string parameter_; - - // implements CodeGenerator ---------------------------------------- - bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - called_ = true; - parameter_ = parameter; - return true; - } -}; - -// =================================================================== - -void CommandLineInterfaceTest::SetUp() { - temp_directory_ = TestTempDir() + "/proto2_cli_test_temp"; - - // If the temp directory already exists, it must be left over from a - // previous run. Delete it. - if (FileExists(temp_directory_)) { - File::DeleteRecursively(temp_directory_, NULL, NULL); - } - - // Create the temp directory. - GOOGLE_CHECK_OK(File::CreateDir(temp_directory_, 0777)); - - // Register generators. - CodeGenerator* generator = new MockCodeGenerator("test_generator"); - mock_generators_to_delete_.push_back(generator); - cli_.RegisterGenerator("--test_out", "--test_opt", generator, "Test output."); - cli_.RegisterGenerator("-t", generator, "Test output."); - - generator = new MockCodeGenerator("alt_generator"); - mock_generators_to_delete_.push_back(generator); - cli_.RegisterGenerator("--alt_out", generator, "Alt output."); - - generator = null_generator_ = new NullCodeGenerator(); - mock_generators_to_delete_.push_back(generator); - cli_.RegisterGenerator("--null_out", generator, "Null output."); - - - disallow_plugins_ = false; -} - -void CommandLineInterfaceTest::TearDown() { - // Delete the temp directory. - if (FileExists(temp_directory_)) { - File::DeleteRecursively(temp_directory_, NULL, NULL); - } - - // Delete all the MockCodeGenerators. - for (int i = 0; i < mock_generators_to_delete_.size(); i++) { - delete mock_generators_to_delete_[i]; - } - mock_generators_to_delete_.clear(); -} - -void CommandLineInterfaceTest::Run(const string& command) { - RunWithArgs(Split(command, " ", true)); -} - -void CommandLineInterfaceTest::RunWithArgs(std::vector args) { - if (!disallow_plugins_) { - cli_.AllowPlugins("prefix-"); -#ifndef GOOGLE_THIRD_PARTY_PROTOBUF - string plugin_path; -#ifdef GOOGLE_PROTOBUF_TEST_PLUGIN_PATH - plugin_path = GOOGLE_PROTOBUF_TEST_PLUGIN_PATH; -#else - const char* possible_paths[] = { - // When building with shared libraries, libtool hides the real executable - // in .libs and puts a fake wrapper in the current directory. - // Unfortunately, due to an apparent bug on Cygwin/MinGW, if one program - // wrapped in this way (e.g. protobuf-tests.exe) tries to execute another - // program wrapped in this way (e.g. test_plugin.exe), the latter fails - // with error code 127 and no explanation message. Presumably the problem - // is that the wrapper for protobuf-tests.exe set some environment - // variables that confuse the wrapper for test_plugin.exe. Luckily, it - // turns out that if we simply invoke the wrapped test_plugin.exe - // directly, it works -- I guess the environment variables set by the - // protobuf-tests.exe wrapper happen to be correct for it too. So we do - // that. - ".libs/test_plugin.exe", // Win32 w/autotool (Cygwin / MinGW) - "test_plugin.exe", // Other Win32 (MSVC) - "test_plugin", // Unix - }; - for (int i = 0; i < GOOGLE_ARRAYSIZE(possible_paths); i++) { - if (access(possible_paths[i], F_OK) == 0) { - plugin_path = possible_paths[i]; - break; - } - } -#endif - - if (plugin_path.empty()) { -#else - string plugin_path = "third_party/protobuf/test_plugin"; - - if (access(plugin_path.c_str(), F_OK) != 0) { -#endif // GOOGLE_THIRD_PARTY_PROTOBUF - GOOGLE_LOG(ERROR) - << "Plugin executable not found. Plugin tests are likely to fail."; - } else { - args.push_back("--plugin=prefix-gen-plug=" + plugin_path); - } - } - - std::unique_ptr argv(new const char* [args.size()]); - - for (int i = 0; i < args.size(); i++) { - args[i] = StringReplace(args[i], "$tmpdir", temp_directory_, true); - argv[i] = args[i].c_str(); - } - - // TODO(jieluo): Cygwin doesn't work well if we try to capture stderr and - // stdout at the same time. Need to figure out why and add this capture back - // for Cygwin. -#if !defined(__CYGWIN__) - CaptureTestStdout(); -#endif - CaptureTestStderr(); - - return_code_ = cli_.Run(args.size(), argv.get()); - - error_text_ = GetCapturedTestStderr(); -#if !defined(__CYGWIN__) - captured_stdout_ = GetCapturedTestStdout(); -#endif -} - -// ------------------------------------------------------------------- - -void CommandLineInterfaceTest::CreateTempFile( - const string& name, - const string& contents) { - // Create parent directory, if necessary. - string::size_type slash_pos = name.find_last_of('/'); - if (slash_pos != string::npos) { - string dir = name.substr(0, slash_pos); - if (!FileExists(temp_directory_ + "/" + dir)) { - GOOGLE_CHECK_OK(File::RecursivelyCreateDir(temp_directory_ + "/" + dir, - 0777)); - } - } - - // Write file. - string full_name = temp_directory_ + "/" + name; - GOOGLE_CHECK_OK(File::SetContents( - full_name, StringReplace(contents, "$tmpdir", temp_directory_, true), - true)); -} - -void CommandLineInterfaceTest::CreateTempDir(const string& name) { - GOOGLE_CHECK_OK(File::RecursivelyCreateDir(temp_directory_ + "/" + name, - 0777)); -} - -// ------------------------------------------------------------------- - -void CommandLineInterfaceTest::ExpectNoErrors() { - EXPECT_EQ(0, return_code_); - EXPECT_EQ("", error_text_); -} - -void CommandLineInterfaceTest::ExpectErrorText(const string& expected_text) { - EXPECT_NE(0, return_code_); - EXPECT_EQ(StringReplace(expected_text, "$tmpdir", temp_directory_, true), - error_text_); -} - -void CommandLineInterfaceTest::ExpectErrorSubstring( - const string& expected_substring) { - EXPECT_NE(0, return_code_); - EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, error_text_); -} - -void CommandLineInterfaceTest::ExpectErrorSubstringWithZeroReturnCode( - const string& expected_substring) { - EXPECT_EQ(0, return_code_); - EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, error_text_); -} - -bool CommandLineInterfaceTest::HasAlternateErrorSubstring( - const string& expected_substring) { - EXPECT_NE(0, return_code_); - return error_text_.find(expected_substring) != string::npos; -} - -void CommandLineInterfaceTest::ExpectGenerated( - const string& generator_name, - const string& parameter, - const string& proto_name, - const string& message_name) { - MockCodeGenerator::ExpectGenerated( - generator_name, parameter, "", proto_name, message_name, proto_name, - temp_directory_); -} - -void CommandLineInterfaceTest::ExpectGenerated( - const string& generator_name, - const string& parameter, - const string& proto_name, - const string& message_name, - const string& output_directory) { - MockCodeGenerator::ExpectGenerated( - generator_name, parameter, "", proto_name, message_name, proto_name, - temp_directory_ + "/" + output_directory); -} - -void CommandLineInterfaceTest::ExpectGeneratedWithMultipleInputs( - const string& generator_name, - const string& all_proto_names, - const string& proto_name, - const string& message_name) { - MockCodeGenerator::ExpectGenerated( - generator_name, "", "", proto_name, message_name, - all_proto_names, - temp_directory_); -} - -void CommandLineInterfaceTest::ExpectGeneratedWithInsertions( - const string& generator_name, - const string& parameter, - const string& insertions, - const string& proto_name, - const string& message_name) { - MockCodeGenerator::ExpectGenerated( - generator_name, parameter, insertions, proto_name, message_name, - proto_name, temp_directory_); -} - -void CommandLineInterfaceTest::CheckGeneratedAnnotations(const string& name, - const string& file) { - MockCodeGenerator::CheckGeneratedAnnotations(name, file, temp_directory_); -} - -void CommandLineInterfaceTest::ExpectNullCodeGeneratorCalled( - const string& parameter) { - EXPECT_TRUE(null_generator_->called_); - EXPECT_EQ(parameter, null_generator_->parameter_); -} - - -void CommandLineInterfaceTest::ReadDescriptorSet( - const string& filename, FileDescriptorSet* descriptor_set) { - string path = temp_directory_ + "/" + filename; - string file_contents; - GOOGLE_CHECK_OK(File::GetContents(path, &file_contents, true)); - - if (!descriptor_set->ParseFromString(file_contents)) { - FAIL() << "Could not parse file contents: " << path; - } -} - -void CommandLineInterfaceTest::WriteDescriptorSet( - const string& filename, const FileDescriptorSet* descriptor_set) { - string binary_proto; - GOOGLE_CHECK(descriptor_set->SerializeToString(&binary_proto)); - CreateTempFile(filename, binary_proto); -} - -void CommandLineInterfaceTest::ExpectCapturedStdout( - const string& expected_text) { - EXPECT_EQ(expected_text, captured_stdout_); -} - -void CommandLineInterfaceTest::ExpectCapturedStdoutSubstringWithZeroReturnCode( - const string& expected_substring) { - EXPECT_EQ(0, return_code_); - EXPECT_PRED_FORMAT2( - testing::IsSubstring, expected_substring, captured_stdout_); -} - -void CommandLineInterfaceTest::ExpectFileContent( - const string& filename, const string& content) { - string path = temp_directory_ + "/" + filename; - string file_contents; - GOOGLE_CHECK_OK(File::GetContents(path, &file_contents, true)); - - EXPECT_EQ(StringReplace(content, "$tmpdir", temp_directory_, true), - file_contents); -} - -// =================================================================== - -TEST_F(CommandLineInterfaceTest, BasicOutput) { - // Test that the common case works. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, BasicOutput_DescriptorSetIn) { - // Test that the common case works. - FileDescriptorSet file_descriptor_set; - FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("foo.proto"); - file_descriptor_proto->add_message_type()->set_name("Foo"); - - WriteDescriptorSet("foo.bin", &file_descriptor_set); - - Run("protocol_compiler --test_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo.bin foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, BasicPlugin) { - // Test that basic plugins work. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --plug_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_plugin", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, BasicPlugin_DescriptorSetIn) { - // Test that basic plugins work. - - FileDescriptorSet file_descriptor_set; - FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("foo.proto"); - file_descriptor_proto->add_message_type()->set_name("Foo"); - - WriteDescriptorSet("foo.bin", &file_descriptor_set); - - Run("protocol_compiler --plug_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo.bin foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_plugin", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin) { - // Invoke a generator and a plugin at the same time. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); - ExpectGenerated("test_plugin", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin_DescriptorSetIn) { - // Invoke a generator and a plugin at the same time. - - FileDescriptorSet file_descriptor_set; - FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("foo.proto"); - file_descriptor_proto->add_message_type()->set_name("Foo"); - - WriteDescriptorSet("foo.bin", &file_descriptor_set); - - Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo.bin foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); - ExpectGenerated("test_plugin", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, MultipleInputs) { - // Test parsing multiple input files. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); - - Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " - "--proto_path=$tmpdir foo.proto bar.proto"); - - ExpectNoErrors(); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "bar.proto", "Bar"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "bar.proto", "Bar"); -} - -TEST_F(CommandLineInterfaceTest, MultipleInputs_DescriptorSetIn) { - // Test parsing multiple input files. - FileDescriptorSet file_descriptor_set; - - FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("foo.proto"); - file_descriptor_proto->add_message_type()->set_name("Foo"); - - file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("bar.proto"); - file_descriptor_proto->add_message_type()->set_name("Bar"); - - WriteDescriptorSet("foo.bin", &file_descriptor_set); - - Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo.bin foo.proto bar.proto"); - - ExpectNoErrors(); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "bar.proto", "Bar"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "bar.proto", "Bar"); -} - -TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport) { - // Test parsing multiple input files with an import of a separate file. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"baz.proto\";\n" - "message Bar {\n" - " optional Baz a = 1;\n" - "}\n"); - CreateTempFile("baz.proto", - "syntax = \"proto2\";\n" - "message Baz {}\n"); - - Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " - "--proto_path=$tmpdir foo.proto bar.proto"); - - ExpectNoErrors(); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "bar.proto", "Bar"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "bar.proto", "Bar"); -} - -TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport_DescriptorSetIn) { - // Test parsing multiple input files with an import of a separate file. - FileDescriptorSet file_descriptor_set; - - FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("foo.proto"); - file_descriptor_proto->add_message_type()->set_name("Foo"); - - file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("bar.proto"); - file_descriptor_proto->add_dependency("baz.proto"); - DescriptorProto* message = file_descriptor_proto->add_message_type(); - message->set_name("Bar"); - FieldDescriptorProto* field = message->add_field(); - field->set_type_name("Baz"); - field->set_name("a"); - field->set_number(1); - - WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set); - - file_descriptor_set.clear_file(); - file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("baz.proto"); - file_descriptor_proto->add_message_type()->set_name("Baz"); - - file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("bat.proto"); - file_descriptor_proto->add_dependency("baz.proto"); - message = file_descriptor_proto->add_message_type(); - message->set_name("Bat"); - field = message->add_field(); - field->set_type_name("Baz"); - field->set_name("a"); - field->set_number(1); - - WriteDescriptorSet("baz_and_bat.bin", &file_descriptor_set); - Run(strings::Substitute( - "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir " - "--descriptor_set_in=$0 foo.proto bar.proto", - string("$tmpdir/foo_and_bar.bin") + - CommandLineInterface::kPathSeparator + - "$tmpdir/baz_and_bat.bin")); - - ExpectNoErrors(); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "bar.proto", "Bar"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "bar.proto", "Bar"); - - Run(strings::Substitute( - "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir " - "--descriptor_set_in=$0 baz.proto bat.proto", - string("$tmpdir/foo_and_bar.bin") + - CommandLineInterface::kPathSeparator + - "$tmpdir/baz_and_bat.bin")); - - ExpectNoErrors(); - ExpectGeneratedWithMultipleInputs("test_generator", "baz.proto,bat.proto", - "baz.proto", "Baz"); - ExpectGeneratedWithMultipleInputs("test_generator", "baz.proto,bat.proto", - "bat.proto", "Bat"); - ExpectGeneratedWithMultipleInputs("test_plugin", "baz.proto,bat.proto", - "baz.proto", "Baz"); - ExpectGeneratedWithMultipleInputs("test_plugin", "baz.proto,bat.proto", - "bat.proto", "Bat"); -} - -TEST_F(CommandLineInterfaceTest, - MultipleInputsWithImport_DescriptorSetIn_DuplicateFileDescriptor) { - // Test parsing multiple input files with an import of a separate file. - FileDescriptorSet file_descriptor_set; - - FileDescriptorProto foo_file_descriptor_proto; - foo_file_descriptor_proto.set_name("foo.proto"); - foo_file_descriptor_proto.add_message_type()->set_name("Foo"); - - file_descriptor_set.add_file()->CopyFrom(foo_file_descriptor_proto); - - FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("bar.proto"); - file_descriptor_proto->add_dependency("baz.proto"); - file_descriptor_proto->add_dependency("foo.proto"); - DescriptorProto* message = file_descriptor_proto->add_message_type(); - message->set_name("Bar"); - FieldDescriptorProto* field = message->add_field(); - field->set_type_name("Baz"); - field->set_name("a"); - field->set_number(1); - field = message->add_field(); - field->set_type_name("Foo"); - field->set_name("f"); - field->set_number(2); - WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set); - - file_descriptor_set.clear_file(); - file_descriptor_set.add_file()->CopyFrom(foo_file_descriptor_proto); - - file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("baz.proto"); - file_descriptor_proto->add_dependency("foo.proto"); - message = file_descriptor_proto->add_message_type(); - message->set_name("Baz"); - field = message->add_field(); - field->set_type_name("Foo"); - field->set_name("f"); - field->set_number(1); - WriteDescriptorSet("foo_and_baz.bin", &file_descriptor_set); - - Run(strings::Substitute( - "protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir " - "--descriptor_set_in=$0 bar.proto", - string("$tmpdir/foo_and_bar.bin") + - CommandLineInterface::kPathSeparator + - "$tmpdir/foo_and_baz.bin")); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "bar.proto", "Bar"); - ExpectGenerated("test_plugin", "", "bar.proto", "Bar"); -} - -TEST_F(CommandLineInterfaceTest, - MultipleInputsWithImport_DescriptorSetIn_MissingImport) { - // Test parsing multiple input files with an import of a separate file. - FileDescriptorSet file_descriptor_set; - - FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("foo.proto"); - file_descriptor_proto->add_message_type()->set_name("Foo"); - - file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("bar.proto"); - file_descriptor_proto->add_dependency("baz.proto"); - DescriptorProto* message = file_descriptor_proto->add_message_type(); - message->set_name("Bar"); - FieldDescriptorProto* field = message->add_field(); - field->set_type_name("Baz"); - field->set_name("a"); - field->set_number(1); - - WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set); - - file_descriptor_set.clear_file(); - file_descriptor_proto = file_descriptor_set.add_file(); - file_descriptor_proto->set_name("baz.proto"); - file_descriptor_proto->add_message_type()->set_name("Baz"); - - WriteDescriptorSet("baz.bin", &file_descriptor_set); - Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo_and_bar.bin " - "foo.proto bar.proto"); - ExpectErrorSubstring( - "bar.proto: Import \"baz.proto\" was not found or had errors."); - ExpectErrorSubstring("bar.proto: \"Baz\" is not defined."); -} - -TEST_F(CommandLineInterfaceTest, CreateDirectory) { - // Test that when we output to a sub-directory, it is created. - - CreateTempFile("bar/baz/foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempDir("out"); - CreateTempDir("plugout"); - - Run("protocol_compiler --test_out=$tmpdir/out --plug_out=$tmpdir/plugout " - "--proto_path=$tmpdir bar/baz/foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "bar/baz/foo.proto", "Foo", "out"); - ExpectGenerated("test_plugin", "", "bar/baz/foo.proto", "Foo", "plugout"); -} - -TEST_F(CommandLineInterfaceTest, GeneratorParameters) { - // Test that generator parameters are correctly parsed from the command line. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=TestParameter:$tmpdir " - "--plug_out=TestPluginParameter:$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "TestParameter", "foo.proto", "Foo"); - ExpectGenerated("test_plugin", "TestPluginParameter", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, ExtraGeneratorParameters) { - // Test that generator parameters specified with the option flag are - // correctly passed to the code generator. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - // Create the "a" and "b" sub-directories. - CreateTempDir("a"); - CreateTempDir("b"); - - Run("protocol_compiler " - "--test_opt=foo1 " - "--test_out=bar:$tmpdir/a " - "--test_opt=foo2 " - "--test_out=baz:$tmpdir/b " - "--test_opt=foo3 " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated( - "test_generator", "bar,foo1,foo2,foo3", "foo.proto", "Foo", "a"); - ExpectGenerated( - "test_generator", "baz,foo1,foo2,foo3", "foo.proto", "Foo", "b"); -} - -TEST_F(CommandLineInterfaceTest, ExtraPluginParameters) { - // Test that generator parameters specified with the option flag are - // correctly passed to the code generator. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - // Create the "a" and "b" sub-directories. - CreateTempDir("a"); - CreateTempDir("b"); - - Run("protocol_compiler " - "--plug_opt=foo1 " - "--plug_out=bar:$tmpdir/a " - "--plug_opt=foo2 " - "--plug_out=baz:$tmpdir/b " - "--plug_opt=foo3 " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated( - "test_plugin", "bar,foo1,foo2,foo3", "foo.proto", "Foo", "a"); - ExpectGenerated( - "test_plugin", "baz,foo1,foo2,foo3", "foo.proto", "Foo", "b"); -} - -TEST_F(CommandLineInterfaceTest, UnrecognizedExtraParameters) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --plug_out=TestParameter:$tmpdir " - "--unknown_plug_a_opt=Foo " - "--unknown_plug_b_opt=Bar " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring("Unknown flag: --unknown_plug_a_opt"); - ExpectErrorSubstring("Unknown flag: --unknown_plug_b_opt"); -} - -TEST_F(CommandLineInterfaceTest, ExtraPluginParametersForOutParameters) { - // This doesn't rely on the plugin having been registred and instead that - // the existence of --[name]_out is enough to make the --[name]_opt valid. - // However, running out of process plugins found via the search path (i.e. - - // not pre registered with --plugin) isn't support in this test suite, so we - // list the options pre/post the _out directive, and then include _opt that - // will be unknown, and confirm the failure output is about the expected - // unknown directive, which means the other were accepted. - // NOTE: UnrecognizedExtraParameters confirms that if two unknown _opt - // directives appear, they both are reported. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --plug_out=TestParameter:$tmpdir " - "--xyz_opt=foo=bar --xyz_out=$tmpdir " - "--abc_out=$tmpdir --abc_opt=foo=bar " - "--unknown_plug_opt=Foo " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorText("Unknown flag: --unknown_plug_opt\n"); -} - -TEST_F(CommandLineInterfaceTest, Insert) { - // Test running a generator that inserts code into another's output. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler " - "--test_out=TestParameter:$tmpdir " - "--plug_out=TestPluginParameter:$tmpdir " - "--test_out=insert=test_generator,test_plugin:$tmpdir " - "--plug_out=insert=test_generator,test_plugin:$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGeneratedWithInsertions( - "test_generator", "TestParameter", "test_generator,test_plugin", - "foo.proto", "Foo"); - ExpectGeneratedWithInsertions( - "test_plugin", "TestPluginParameter", "test_generator,test_plugin", - "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, InsertWithAnnotationFixup) { - // Check that annotation spans are updated after insertions. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Annotate {}\n"); - - Run("protocol_compiler " - "--test_out=TestParameter:$tmpdir " - "--plug_out=TestPluginParameter:$tmpdir " - "--test_out=insert=test_generator,test_plugin:$tmpdir " - "--plug_out=insert=test_generator,test_plugin:$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - CheckGeneratedAnnotations("test_generator", "foo.proto"); - CheckGeneratedAnnotations("test_plugin", "foo.proto"); -} - -#if defined(_WIN32) - -TEST_F(CommandLineInterfaceTest, WindowsOutputPath) { - // Test that the output path can be a Windows-style path. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n"); - - Run("protocol_compiler --null_out=C:\\ " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectNullCodeGeneratorCalled(""); -} - -TEST_F(CommandLineInterfaceTest, WindowsOutputPathAndParameter) { - // Test that we can have a windows-style output path and a parameter. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n"); - - Run("protocol_compiler --null_out=bar:C:\\ " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectNullCodeGeneratorCalled("bar"); -} - -TEST_F(CommandLineInterfaceTest, TrailingBackslash) { - // Test that the directories can end in backslashes. Some users claim this - // doesn't work on their system. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=$tmpdir\\ " - "--proto_path=$tmpdir\\ foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, Win32ErrorMessage) { - EXPECT_EQ("The system cannot find the file specified.\r\n", - Subprocess::Win32ErrorMessage(ERROR_FILE_NOT_FOUND)); -} - -#endif // defined(_WIN32) || defined(__CYGWIN__) - -TEST_F(CommandLineInterfaceTest, PathLookup) { - // Test that specifying multiple directories in the proto search path works. - - CreateTempFile("b/bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); - CreateTempFile("a/foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo {\n" - " optional Bar a = 1;\n" - "}\n"); - CreateTempFile("b/foo.proto", "this should not be parsed\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir/a --proto_path=$tmpdir/b foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, ColonDelimitedPath) { - // Same as PathLookup, but we provide the proto_path in a single flag. - - CreateTempFile("b/bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); - CreateTempFile("a/foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo {\n" - " optional Bar a = 1;\n" - "}\n"); - CreateTempFile("b/foo.proto", "this should not be parsed\n"); - - Run(strings::Substitute( - "protocol_compiler --test_out=$$tmpdir --proto_path=$0 foo.proto", - string("$tmpdir/a") + - CommandLineInterface::kPathSeparator + - "$tmpdir/b")); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, NonRootMapping) { - // Test setting up a search path mapping a directory to a non-root location. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=bar=$tmpdir bar/foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "bar/foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, PathWithEqualsSign) { - // Test setting up a search path which happens to have '=' in it. - - CreateTempDir("with=sign"); - CreateTempFile("with=sign/foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir/with=sign foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, MultipleGenerators) { - // Test that we can have multiple generators and use both in one invocation, - // each with a different output directory. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - // Create the "a" and "b" sub-directories. - CreateTempDir("a"); - CreateTempDir("b"); - - Run("protocol_compiler " - "--test_out=$tmpdir/a " - "--alt_out=$tmpdir/b " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo", "a"); - ExpectGenerated("alt_generator", "", "foo.proto", "Foo", "b"); -} - -TEST_F(CommandLineInterfaceTest, DisallowServicesNoServices) { - // Test that --disallow_services doesn't cause a problem when there are no - // services. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --disallow_services --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, DisallowServicesHasService) { - // Test that --disallow_services produces an error when there are services. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n" - "service Bar {}\n"); - - Run("protocol_compiler --disallow_services --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring("foo.proto: This file contains services"); -} - -TEST_F(CommandLineInterfaceTest, AllowServicesHasService) { - // Test that services work fine as long as --disallow_services is not used. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n" - "service Bar {}\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, DirectDependencies_Missing_EmptyList) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo { optional Bar bar = 1; }"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar { optional string text = 1; }"); - - Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir " - "--direct_dependencies= foo.proto"); - - ExpectErrorText( - "foo.proto: File is imported but not declared in --direct_dependencies: " - "bar.proto\n"); -} - -TEST_F(CommandLineInterfaceTest, DirectDependencies_Missing) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "import \"bla.proto\";\n" - "message Foo { optional Bar bar = 1; optional Bla bla = 2; }"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar { optional string text = 1; }"); - CreateTempFile("bla.proto", - "syntax = \"proto2\";\n" - "message Bla { optional int64 number = 1; }"); - - Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir " - "--direct_dependencies=bla.proto foo.proto"); - - ExpectErrorText( - "foo.proto: File is imported but not declared in --direct_dependencies: " - "bar.proto\n"); -} - -TEST_F(CommandLineInterfaceTest, DirectDependencies_NoViolation) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo { optional Bar bar = 1; }"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar { optional string text = 1; }"); - - Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir " - "--direct_dependencies=bar.proto foo.proto"); - - ExpectNoErrors(); -} - -TEST_F(CommandLineInterfaceTest, DirectDependencies_NoViolation_MultiImports) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "import \"bla.proto\";\n" - "message Foo { optional Bar bar = 1; optional Bla bla = 2; }"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar { optional string text = 1; }"); - CreateTempFile("bla.proto", - "syntax = \"proto2\";\n" - "message Bla { optional int64 number = 1; }"); - - Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir " - "--direct_dependencies=bar.proto:bla.proto foo.proto"); - - ExpectNoErrors(); -} - -TEST_F(CommandLineInterfaceTest, DirectDependencies_ProvidedMultipleTimes) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n"); - - Run("protocol_compiler --test_out=$tmpdir --proto_path=$tmpdir " - "--direct_dependencies=bar.proto --direct_dependencies=bla.proto " - "foo.proto"); - - ExpectErrorText( - "--direct_dependencies may only be passed once. To specify multiple " - "direct dependencies, pass them all as a single parameter separated by " - "':'.\n"); -} - -TEST_F(CommandLineInterfaceTest, DirectDependencies_CustomErrorMessage) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo { optional Bar bar = 1; }"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar { optional string text = 1; }"); - - std::vector commands; - commands.push_back("protocol_compiler"); - commands.push_back("--test_out=$tmpdir"); - commands.push_back("--proto_path=$tmpdir"); - commands.push_back("--direct_dependencies="); - commands.push_back("--direct_dependencies_violation_msg=Bla \"%s\" Bla"); - commands.push_back("foo.proto"); - RunWithArgs(commands); - - ExpectErrorText("foo.proto: Bla \"bar.proto\" Bla\n"); -} - -TEST_F(CommandLineInterfaceTest, CwdRelativeInputs) { - // Test that we can accept working-directory-relative input files. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir $tmpdir/foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, WriteDescriptorSet) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); - - Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " - "--proto_path=$tmpdir bar.proto"); - - ExpectNoErrors(); - - FileDescriptorSet descriptor_set; - ReadDescriptorSet("descriptor_set", &descriptor_set); - if (HasFatalFailure()) return; - EXPECT_EQ(1, descriptor_set.file_size()); - EXPECT_EQ("bar.proto", descriptor_set.file(0).name()); - // Descriptor set should not have source code info. - EXPECT_FALSE(descriptor_set.file(0).has_source_code_info()); - // Descriptor set should have json_name. - EXPECT_EQ("Bar", descriptor_set.file(0).message_type(0).name()); - EXPECT_EQ("foo", descriptor_set.file(0).message_type(0).field(0).name()); - EXPECT_TRUE(descriptor_set.file(0).message_type(0).field(0).has_json_name()); -} - -TEST_F(CommandLineInterfaceTest, WriteDescriptorSetWithDuplicates) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); - CreateTempFile("baz.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Baz {\n" - " optional Foo foo = 1;\n" - "}\n"); - - Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " - "--proto_path=$tmpdir bar.proto foo.proto bar.proto baz.proto"); - - ExpectNoErrors(); - - FileDescriptorSet descriptor_set; - ReadDescriptorSet("descriptor_set", &descriptor_set); - if (HasFatalFailure()) return; - EXPECT_EQ(3, descriptor_set.file_size()); - // foo should come first since the output is in dependency order. - // since bar and baz are unordered, they should be in command line order. - EXPECT_EQ("foo.proto", descriptor_set.file(0).name()); - EXPECT_EQ("bar.proto", descriptor_set.file(1).name()); - EXPECT_EQ("baz.proto", descriptor_set.file(2).name()); - // Descriptor set should not have source code info. - EXPECT_FALSE(descriptor_set.file(0).has_source_code_info()); - // Descriptor set should have json_name. - EXPECT_EQ("Bar", descriptor_set.file(1).message_type(0).name()); - EXPECT_EQ("foo", descriptor_set.file(1).message_type(0).field(0).name()); - EXPECT_TRUE(descriptor_set.file(1).message_type(0).field(0).has_json_name()); -} - -TEST_F(CommandLineInterfaceTest, WriteDescriptorSetWithSourceInfo) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); - - Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " - "--include_source_info --proto_path=$tmpdir bar.proto"); - - ExpectNoErrors(); - - FileDescriptorSet descriptor_set; - ReadDescriptorSet("descriptor_set", &descriptor_set); - if (HasFatalFailure()) return; - EXPECT_EQ(1, descriptor_set.file_size()); - EXPECT_EQ("bar.proto", descriptor_set.file(0).name()); - // Source code info included. - EXPECT_TRUE(descriptor_set.file(0).has_source_code_info()); -} - -TEST_F(CommandLineInterfaceTest, WriteTransitiveDescriptorSet) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); - - Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " - "--include_imports --proto_path=$tmpdir bar.proto"); - - ExpectNoErrors(); - - FileDescriptorSet descriptor_set; - ReadDescriptorSet("descriptor_set", &descriptor_set); - if (HasFatalFailure()) return; - EXPECT_EQ(2, descriptor_set.file_size()); - if (descriptor_set.file(0).name() == "bar.proto") { - std::swap(descriptor_set.mutable_file()->mutable_data()[0], - descriptor_set.mutable_file()->mutable_data()[1]); - } - EXPECT_EQ("foo.proto", descriptor_set.file(0).name()); - EXPECT_EQ("bar.proto", descriptor_set.file(1).name()); - // Descriptor set should not have source code info. - EXPECT_FALSE(descriptor_set.file(0).has_source_code_info()); - EXPECT_FALSE(descriptor_set.file(1).has_source_code_info()); -} - -TEST_F(CommandLineInterfaceTest, WriteTransitiveDescriptorSetWithSourceInfo) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); - - Run("protocol_compiler --descriptor_set_out=$tmpdir/descriptor_set " - "--include_imports --include_source_info --proto_path=$tmpdir bar.proto"); - - ExpectNoErrors(); - - FileDescriptorSet descriptor_set; - ReadDescriptorSet("descriptor_set", &descriptor_set); - if (HasFatalFailure()) return; - EXPECT_EQ(2, descriptor_set.file_size()); - if (descriptor_set.file(0).name() == "bar.proto") { - std::swap(descriptor_set.mutable_file()->mutable_data()[0], - descriptor_set.mutable_file()->mutable_data()[1]); - } - EXPECT_EQ("foo.proto", descriptor_set.file(0).name()); - EXPECT_EQ("bar.proto", descriptor_set.file(1).name()); - // Source code info included. - EXPECT_TRUE(descriptor_set.file(0).has_source_code_info()); - EXPECT_TRUE(descriptor_set.file(1).has_source_code_info()); -} - -#ifdef _WIN32 -// TODO(teboring): Figure out how to write test on windows. -#else -TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFileGivenTwoInputs) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); - - Run("protocol_compiler --dependency_out=$tmpdir/manifest " - "--test_out=$tmpdir --proto_path=$tmpdir bar.proto foo.proto"); - - ExpectErrorText( - "Can only process one input file when using --dependency_out=FILE.\n"); -} - -#ifdef PROTOBUF_OPENSOURCE -TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFile) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); - - string current_working_directory = getcwd(NULL, 0); - SwitchToTempDirectory(); - - Run("protocol_compiler --dependency_out=manifest --test_out=. " - "bar.proto"); - - ExpectNoErrors(); - - ExpectFileContent("manifest", - "bar.proto.MockCodeGenerator.test_generator: " - "foo.proto\\\n bar.proto"); - - File::ChangeWorkingDirectory(current_working_directory); -} -#else // !PROTOBUF_OPENSOURCE -// TODO(teboring): Figure out how to change and get working directory in -// google3. -#endif // !PROTOBUF_OPENSOURCE - -TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFileForAbsolutePath) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n" - "message Bar {\n" - " optional Foo foo = 1;\n" - "}\n"); - - Run("protocol_compiler --dependency_out=$tmpdir/manifest " - "--test_out=$tmpdir --proto_path=$tmpdir bar.proto"); - - ExpectNoErrors(); - - ExpectFileContent("manifest", - "$tmpdir/bar.proto.MockCodeGenerator.test_generator: " - "$tmpdir/foo.proto\\\n $tmpdir/bar.proto"); -} -#endif // !_WIN32 - -TEST_F(CommandLineInterfaceTest, TestArgumentFile) { - // Test parsing multiple input files using an argument file. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); - CreateTempFile("arguments.txt", - "--test_out=$tmpdir\n" - "--plug_out=$tmpdir\n" - "--proto_path=$tmpdir\n" - "--direct_dependencies_violation_msg=%s is not imported\n" - "foo.proto\n" - "bar.proto"); - - Run("protocol_compiler @$tmpdir/arguments.txt"); - - ExpectNoErrors(); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto", - "bar.proto", "Bar"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "foo.proto", "Foo"); - ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto", - "bar.proto", "Bar"); -} - - -// ------------------------------------------------------------------- - -TEST_F(CommandLineInterfaceTest, ParseErrors) { - // Test that parse errors are reported. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorText( - "foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n"); -} - -TEST_F(CommandLineInterfaceTest, ParseErrors_DescriptorSetIn) { - // Test that parse errors are reported. - CreateTempFile("foo.bin", "not a FileDescriptorSet"); - - Run("protocol_compiler --test_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo.bin foo.proto"); - - ExpectErrorText( - "$tmpdir/foo.bin: Unable to parse.\n"); -} - -TEST_F(CommandLineInterfaceTest, ParseErrorsMultipleFiles) { - // Test that parse errors are reported from multiple files. - - // We set up files such that foo.proto actually depends on bar.proto in - // two ways: Directly and through baz.proto. bar.proto's errors should - // only be reported once. - CreateTempFile("bar.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); - CreateTempFile("baz.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n"); - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "import \"baz.proto\";\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorText( - "bar.proto:2:1: Expected top-level statement (e.g. \"message\").\n" - "baz.proto: Import \"bar.proto\" was not found or had errors.\n" - "foo.proto: Import \"bar.proto\" was not found or had errors.\n" - "foo.proto: Import \"baz.proto\" was not found or had errors.\n"); -} - -TEST_F(CommandLineInterfaceTest, RecursiveImportFails) { - // Create a proto file that imports itself. - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"foo.proto\";\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring( - "foo.proto: File recursively imports itself: foo.proto -> foo.proto\n"); -} - -TEST_F(CommandLineInterfaceTest, InputNotFoundError) { - // Test what happens if the input file is not found. - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorText("foo.proto: No such file or directory\n"); -} - -TEST_F(CommandLineInterfaceTest, InputNotFoundError_DescriptorSetIn) { - // Test what happens if the input file is not found. - - Run("protocol_compiler --test_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo.bin foo.proto"); - - ExpectErrorText( - "$tmpdir/foo.bin: No such file or directory\n"); -} - -TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundError) { - // Test what happens when a working-directory-relative input file is not - // found. - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir $tmpdir/foo.proto"); - - ExpectErrorText( - "$tmpdir/foo.proto: No such file or directory\n"); -} - -TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotMappedError) { - // Test what happens when a working-directory-relative input file is not - // mapped to a virtual path. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - // Create a directory called "bar" so that we can point --proto_path at it. - CreateTempFile("bar/dummy", ""); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir/bar $tmpdir/foo.proto"); - - ExpectErrorText( - "$tmpdir/foo.proto: File does not reside within any path " - "specified using --proto_path (or -I). You must specify a " - "--proto_path which encompasses this file. Note that the " - "proto_path must be an exact prefix of the .proto file " - "names -- protoc is too dumb to figure out when two paths " - "(e.g. absolute and relative) are equivalent (it's harder " - "than you think).\n"); -} - -TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundAndNotMappedError) { - // Check what happens if the input file is not found *and* is not mapped - // in the proto_path. - - // Create a directory called "bar" so that we can point --proto_path at it. - CreateTempFile("bar/dummy", ""); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir/bar $tmpdir/foo.proto"); - - ExpectErrorText( - "$tmpdir/foo.proto: No such file or directory\n"); -} - -TEST_F(CommandLineInterfaceTest, CwdRelativeInputShadowedError) { - // Test what happens when a working-directory-relative input file is shadowed - // by another file in the virtual path. - - CreateTempFile("foo/foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - CreateTempFile("bar/foo.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir/foo --proto_path=$tmpdir/bar " - "$tmpdir/bar/foo.proto"); - - ExpectErrorText( - "$tmpdir/bar/foo.proto: Input is shadowed in the --proto_path " - "by \"$tmpdir/foo/foo.proto\". Either use the latter " - "file as your input or reorder the --proto_path so that the " - "former file's location comes first.\n"); -} - -TEST_F(CommandLineInterfaceTest, ProtoPathNotFoundError) { - // Test what happens if the input file is not found. - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir/foo foo.proto"); - - ExpectErrorText( - "$tmpdir/foo: warning: directory does not exist.\n" - "foo.proto: No such file or directory\n"); -} - -TEST_F(CommandLineInterfaceTest, ProtoPathAndDescriptorSetIn) { - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir --descriptor_set_in=$tmpdir/foo.bin foo.proto"); - ExpectErrorText( - "Only one of --descriptor_set_in and --proto_path can be specified.\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo.bin --proto_path=$tmpdir foo.proto"); - ExpectErrorText( - "Only one of --proto_path and --descriptor_set_in can be specified.\n"); -} - -TEST_F(CommandLineInterfaceTest, ProtoPathAndDependencyOut) { - Run("protocol_compiler --test_out=$tmpdir " - "--dependency_out=$tmpdir/manifest " - "--descriptor_set_in=$tmpdir/foo.bin foo.proto"); - ExpectErrorText( - "--descriptor_set_in cannot be used with --dependency_out.\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--descriptor_set_in=$tmpdir/foo.bin " - "--dependency_out=$tmpdir/manifest foo.proto"); - ExpectErrorText( - "--dependency_out cannot be used with --descriptor_set_in.\n"); -} - -TEST_F(CommandLineInterfaceTest, MissingInputError) { - // Test that we get an error if no inputs are given. - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir"); - - ExpectErrorText("Missing input file.\n"); -} - -TEST_F(CommandLineInterfaceTest, MissingOutputError) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --proto_path=$tmpdir foo.proto"); - - ExpectErrorText("Missing output directives.\n"); -} - -TEST_F(CommandLineInterfaceTest, OutputWriteError) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - string output_file = - MockCodeGenerator::GetOutputFileName("test_generator", "foo.proto"); - - // Create a directory blocking our output location. - CreateTempDir(output_file); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - // MockCodeGenerator no longer detects an error because we actually write to - // an in-memory location first, then dump to disk at the end. This is no - // big deal. - // ExpectErrorSubstring("MockCodeGenerator detected write error."); - -#if defined(_WIN32) && !defined(__CYGWIN__) - // Windows with MSVCRT.dll produces EPERM instead of EISDIR. - if (HasAlternateErrorSubstring(output_file + ": Permission denied")) { - return; - } -#endif - - ExpectErrorSubstring(output_file + ": Is a directory"); -} - -TEST_F(CommandLineInterfaceTest, PluginOutputWriteError) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - string output_file = - MockCodeGenerator::GetOutputFileName("test_plugin", "foo.proto"); - - // Create a directory blocking our output location. - CreateTempDir(output_file); - - Run("protocol_compiler --plug_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - -#if defined(_WIN32) && !defined(__CYGWIN__) - // Windows with MSVCRT.dll produces EPERM instead of EISDIR. - if (HasAlternateErrorSubstring(output_file + ": Permission denied")) { - return; - } -#endif - - ExpectErrorSubstring(output_file + ": Is a directory"); -} - -TEST_F(CommandLineInterfaceTest, OutputDirectoryNotFoundError) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=$tmpdir/nosuchdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring("nosuchdir/: No such file or directory"); -} - -TEST_F(CommandLineInterfaceTest, PluginOutputDirectoryNotFoundError) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --plug_out=$tmpdir/nosuchdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring("nosuchdir/: No such file or directory"); -} - -TEST_F(CommandLineInterfaceTest, OutputDirectoryIsFileError) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out=$tmpdir/foo.proto " - "--proto_path=$tmpdir foo.proto"); - -#if defined(_WIN32) && !defined(__CYGWIN__) - // Windows with MSVCRT.dll produces EINVAL instead of ENOTDIR. - if (HasAlternateErrorSubstring("foo.proto/: Invalid argument")) { - return; - } -#endif - - ExpectErrorSubstring("foo.proto/: Not a directory"); -} - -TEST_F(CommandLineInterfaceTest, GeneratorError) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Error {}\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring( - "--test_out: foo.proto: Saw message type MockCodeGenerator_Error."); -} - -TEST_F(CommandLineInterfaceTest, GeneratorPluginError) { - // Test a generator plugin that returns an error. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Error {}\n"); - - Run("protocol_compiler --plug_out=TestParameter:$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring( - "--plug_out: foo.proto: Saw message type MockCodeGenerator_Error."); -} - -TEST_F(CommandLineInterfaceTest, GeneratorPluginFail) { - // Test a generator plugin that exits with an error code. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Exit {}\n"); - - Run("protocol_compiler --plug_out=TestParameter:$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring("Saw message type MockCodeGenerator_Exit."); - ExpectErrorSubstring( - "--plug_out: prefix-gen-plug: Plugin failed with status code 123."); -} - -TEST_F(CommandLineInterfaceTest, GeneratorPluginCrash) { - // Test a generator plugin that crashes. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_Abort {}\n"); - - Run("protocol_compiler --plug_out=TestParameter:$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring("Saw message type MockCodeGenerator_Abort."); - -#ifdef _WIN32 - // Windows doesn't have signals. It looks like abort()ing causes the process - // to exit with status code 3, but let's not depend on the exact number here. - ExpectErrorSubstring( - "--plug_out: prefix-gen-plug: Plugin failed with status code"); -#else - // Don't depend on the exact signal number. - ExpectErrorSubstring( - "--plug_out: prefix-gen-plug: Plugin killed by signal"); -#endif -} - -TEST_F(CommandLineInterfaceTest, PluginReceivesSourceCodeInfo) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_HasSourceCodeInfo {}\n"); - - Run("protocol_compiler --plug_out=$tmpdir --proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring( - "Saw message type MockCodeGenerator_HasSourceCodeInfo: 1."); -} - -TEST_F(CommandLineInterfaceTest, PluginReceivesJsonName) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_HasJsonName {\n" - " optional int32 value = 1;\n" - "}\n"); - - Run("protocol_compiler --plug_out=$tmpdir --proto_path=$tmpdir foo.proto"); - - ExpectErrorSubstring("Saw json_name: 1"); -} - -TEST_F(CommandLineInterfaceTest, PluginReceivesCompilerVersion) { - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message MockCodeGenerator_ShowVersionNumber {\n" - " optional int32 value = 1;\n" - "}\n"); - - 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)); -} - -TEST_F(CommandLineInterfaceTest, GeneratorPluginNotFound) { - // Test what happens if the plugin isn't found. - - CreateTempFile("error.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --badplug_out=TestParameter:$tmpdir " - "--plugin=prefix-gen-badplug=no_such_file " - "--proto_path=$tmpdir error.proto"); - -#ifdef _WIN32 - ExpectErrorSubstring("--badplug_out: prefix-gen-badplug: " + - Subprocess::Win32ErrorMessage(ERROR_FILE_NOT_FOUND)); -#else - // Error written to stdout by child process after exec() fails. - ExpectErrorSubstring( - "no_such_file: program not found or is not executable"); - - // Error written by parent process when child fails. - ExpectErrorSubstring( - "--badplug_out: prefix-gen-badplug: Plugin failed with status code 1."); -#endif -} - -TEST_F(CommandLineInterfaceTest, GeneratorPluginNotAllowed) { - // Test what happens if plugins aren't allowed. - - CreateTempFile("error.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - DisallowPlugins(); - Run("protocol_compiler --plug_out=TestParameter:$tmpdir " - "--proto_path=$tmpdir error.proto"); - - ExpectErrorSubstring("Unknown flag: --plug_out"); -} - -TEST_F(CommandLineInterfaceTest, HelpText) { - Run("test_exec_name --help"); - - ExpectCapturedStdoutSubstringWithZeroReturnCode("Usage: test_exec_name "); - ExpectCapturedStdoutSubstringWithZeroReturnCode("--test_out=OUT_DIR"); - ExpectCapturedStdoutSubstringWithZeroReturnCode("Test output."); - ExpectCapturedStdoutSubstringWithZeroReturnCode("--alt_out=OUT_DIR"); - ExpectCapturedStdoutSubstringWithZeroReturnCode("Alt output."); -} - -TEST_F(CommandLineInterfaceTest, GccFormatErrors) { - // Test --error_format=gcc (which is the default, but we want to verify - // that it can be set explicitly). - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir --error_format=gcc foo.proto"); - - ExpectErrorText( - "foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n"); -} - -TEST_F(CommandLineInterfaceTest, MsvsFormatErrors) { - // Test --error_format=msvs - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir --error_format=msvs foo.proto"); - - ExpectErrorText( - "$tmpdir/foo.proto(2) : error in column=1: Expected top-level statement " - "(e.g. \"message\").\n"); -} - -TEST_F(CommandLineInterfaceTest, InvalidErrorFormat) { - // Test --error_format=msvs - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "badsyntax\n"); - - Run("protocol_compiler --test_out=$tmpdir " - "--proto_path=$tmpdir --error_format=invalid foo.proto"); - - ExpectErrorText( - "Unknown error format: invalid\n"); -} - -// ------------------------------------------------------------------- -// Flag parsing tests - -TEST_F(CommandLineInterfaceTest, ParseSingleCharacterFlag) { - // Test that a single-character flag works. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler -t$tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, ParseSpaceDelimitedValue) { - // Test that separating the flag value with a space works. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler --test_out $tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, ParseSingleCharacterSpaceDelimitedValue) { - // Test that separating the flag value with a space works for - // single-character flags. - - CreateTempFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - Run("protocol_compiler -t $tmpdir " - "--proto_path=$tmpdir foo.proto"); - - ExpectNoErrors(); - ExpectGenerated("test_generator", "", "foo.proto", "Foo"); -} - -TEST_F(CommandLineInterfaceTest, MissingValueError) { - // Test that we get an error if a flag is missing its value. - - Run("protocol_compiler --test_out --proto_path=$tmpdir foo.proto"); - - ExpectErrorText("Missing value for flag: --test_out\n"); -} - -TEST_F(CommandLineInterfaceTest, MissingValueAtEndError) { - // Test that we get an error if the last argument is a flag requiring a - // value. - - Run("protocol_compiler --test_out"); - - ExpectErrorText("Missing value for flag: --test_out\n"); -} - -TEST_F(CommandLineInterfaceTest, PrintFreeFieldNumbers) { - CreateTempFile( - "foo.proto", - "syntax = \"proto2\";\n" - "package foo;\n" - "message Foo {\n" - " optional int32 a = 2;\n" - " optional string b = 4;\n" - " optional string c = 5;\n" - " optional int64 d = 8;\n" - " optional double e = 10;\n" - "}\n"); - CreateTempFile( - "bar.proto", - "syntax = \"proto2\";\n" - "message Bar {\n" - " optional int32 a = 2;\n" - " extensions 4 to 5;\n" - " optional int64 d = 8;\n" - " extensions 10;\n" - "}\n"); - CreateTempFile( - "baz.proto", - "syntax = \"proto2\";\n" - "message Baz {\n" - " optional int32 a = 2;\n" - " optional int64 d = 8;\n" - " extensions 15 to max;\n" // unordered. - " extensions 13;\n" - " extensions 10 to 12;\n" - " extensions 5;\n" - " extensions 4;\n" - "}\n"); - CreateTempFile( - "quz.proto", - "syntax = \"proto2\";\n" - "message Quz {\n" - " message Foo {}\n" // nested message - " optional int32 a = 2;\n" - " optional group C = 4 {\n" - " optional int32 d = 5;\n" - " }\n" - " extensions 8 to 10;\n" - " optional group E = 11 {\n" - " optional int32 f = 9;\n" // explicitly reuse extension range 8-10 - " optional group G = 15 {\n" // nested group - " message Foo {}\n" // nested message inside nested group - " }\n" - " }\n" - "}\n"); - - Run("protocol_compiler --print_free_field_numbers --proto_path=$tmpdir " - "foo.proto bar.proto baz.proto quz.proto"); - - ExpectNoErrors(); - - // TODO(jieluo): Cygwin doesn't work well if we try to capture stderr and - // stdout at the same time. Need to figure out why and add this test back - // for Cygwin. -#if !defined(__CYGWIN__) - ExpectCapturedStdout( - "foo.Foo free: 1 3 6-7 9 11-INF\n" - "Bar free: 1 3 6-7 9 11-INF\n" - "Baz free: 1 3 6-7 9 14\n" - "Quz.Foo free: 1-INF\n" - "Quz.E.G.Foo free: 1-INF\n" - "Quz free: 1 3 6-7 12-14 16-INF\n"); -#endif -} - -// =================================================================== - -// Test for --encode and --decode. Note that it would be easier to do this -// test as a shell script, but we'd like to be able to run the test on -// platforms that don't have a Bourne-compatible shell available (especially -// Windows/MSVC). - -enum EncodeDecodeTestMode { - PROTO_PATH, - DESCRIPTOR_SET_IN -}; - -class EncodeDecodeTest : public testing::TestWithParam { - protected: - virtual void SetUp() { - WriteUnittestProtoDescriptorSet(); - duped_stdin_ = dup(STDIN_FILENO); - } - - virtual void TearDown() { - dup2(duped_stdin_, STDIN_FILENO); - close(duped_stdin_); - } - - void RedirectStdinFromText(const string& input) { - string filename = TestTempDir() + "/test_stdin"; - GOOGLE_CHECK_OK(File::SetContents(filename, input, true)); - GOOGLE_CHECK(RedirectStdinFromFile(filename)); - } - - bool RedirectStdinFromFile(const string& filename) { - int fd = open(filename.c_str(), O_RDONLY); - if (fd < 0) return false; - dup2(fd, STDIN_FILENO); - close(fd); - return true; - } - - // Remove '\r' characters from text. - string StripCR(const string& text) { - string result; - - for (int i = 0; i < text.size(); i++) { - if (text[i] != '\r') { - result.push_back(text[i]); - } - } - - return result; - } - - enum Type { TEXT, BINARY }; - enum ReturnCode { SUCCESS, ERROR }; - - bool Run(const string& command) { - std::vector args; - args.push_back("protoc"); - SplitStringUsing(command, " ", &args); - switch (GetParam()) { - case PROTO_PATH: - args.push_back("--proto_path=" + TestSourceDir()); - break; - case DESCRIPTOR_SET_IN: - args.push_back(StrCat( - "--descriptor_set_in=", - unittest_proto_descriptor_set_filename_)); - break; - default: - ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam(); - } - - std::unique_ptr argv(new const char* [args.size()]); - for (int i = 0; i < args.size(); i++) { - argv[i] = args[i].c_str(); - } - - CommandLineInterface cli; - - CaptureTestStdout(); - CaptureTestStderr(); - - int result = cli.Run(args.size(), argv.get()); - - captured_stdout_ = GetCapturedTestStdout(); - captured_stderr_ = GetCapturedTestStderr(); - - return result == 0; - } - - void ExpectStdoutMatchesBinaryFile(const string& filename) { - string expected_output; - GOOGLE_CHECK_OK(File::GetContents(filename, &expected_output, true)); - - // Don't use EXPECT_EQ because we don't want to print raw binary data to - // stdout on failure. - EXPECT_TRUE(captured_stdout_ == expected_output); - } - - void ExpectStdoutMatchesTextFile(const string& filename) { - string expected_output; - GOOGLE_CHECK_OK(File::GetContents(filename, &expected_output, true)); - - ExpectStdoutMatchesText(expected_output); - } - - void ExpectStdoutMatchesText(const string& expected_text) { - EXPECT_EQ(StripCR(expected_text), StripCR(captured_stdout_)); - } - - void ExpectStderrMatchesText(const string& expected_text) { - EXPECT_EQ(StripCR(expected_text), StripCR(captured_stderr_)); - } - - private: - void WriteUnittestProtoDescriptorSet() { - unittest_proto_descriptor_set_filename_ = - TestTempDir() + "/unittest_proto_descriptor_set.bin"; - FileDescriptorSet file_descriptor_set; - protobuf_unittest::TestAllTypes test_all_types; - test_all_types.descriptor()->file()->CopyTo(file_descriptor_set.add_file()); - - protobuf_unittest_import::ImportMessage import_message; - import_message.descriptor()->file()->CopyTo(file_descriptor_set.add_file()); - - - protobuf_unittest_import::PublicImportMessage public_import_message; - public_import_message.descriptor()->file()->CopyTo( - file_descriptor_set.add_file()); - GOOGLE_DCHECK(file_descriptor_set.IsInitialized()); - - string binary_proto; - GOOGLE_CHECK(file_descriptor_set.SerializeToString(&binary_proto)); - GOOGLE_CHECK_OK(File::SetContents( - unittest_proto_descriptor_set_filename_, - binary_proto, - true)); - } - - int duped_stdin_; - string captured_stdout_; - string captured_stderr_; - string unittest_proto_descriptor_set_filename_; -}; - -TEST_P(EncodeDecodeTest, Encode) { - RedirectStdinFromFile(TestSourceDir() + "/google/protobuf/" - "testdata/text_format_unittest_data_oneof_implemented.txt"); - EXPECT_TRUE(Run("google/protobuf/unittest.proto " - "--encode=protobuf_unittest.TestAllTypes")); - ExpectStdoutMatchesBinaryFile(TestSourceDir() + - "/google/protobuf/testdata/golden_message_oneof_implemented"); - ExpectStderrMatchesText(""); -} - -TEST_P(EncodeDecodeTest, Decode) { - RedirectStdinFromFile(TestSourceDir() + - "/google/protobuf/testdata/golden_message_oneof_implemented"); - EXPECT_TRUE(Run("google/protobuf/unittest.proto " - "--decode=protobuf_unittest.TestAllTypes")); - ExpectStdoutMatchesTextFile(TestSourceDir() + - "/google/protobuf/" - "testdata/text_format_unittest_data_oneof_implemented.txt"); - ExpectStderrMatchesText(""); -} - -TEST_P(EncodeDecodeTest, Partial) { - RedirectStdinFromText(""); - EXPECT_TRUE(Run("google/protobuf/unittest.proto " - "--encode=protobuf_unittest.TestRequired")); - ExpectStdoutMatchesText(""); - ExpectStderrMatchesText( - "warning: Input message is missing required fields: a, b, c\n"); -} - -TEST_P(EncodeDecodeTest, DecodeRaw) { - protobuf_unittest::TestAllTypes message; - message.set_optional_int32(123); - message.set_optional_string("foo"); - string data; - message.SerializeToString(&data); - - RedirectStdinFromText(data); - EXPECT_TRUE(Run("--decode_raw")); - ExpectStdoutMatchesText("1: 123\n" - "14: \"foo\"\n"); - ExpectStderrMatchesText(""); -} - -TEST_P(EncodeDecodeTest, UnknownType) { - EXPECT_FALSE(Run("google/protobuf/unittest.proto " - "--encode=NoSuchType")); - ExpectStdoutMatchesText(""); - ExpectStderrMatchesText("Type not defined: NoSuchType\n"); -} - -TEST_P(EncodeDecodeTest, ProtoParseError) { - EXPECT_FALSE(Run("google/protobuf/no_such_file.proto " - "--encode=NoSuchType")); - ExpectStdoutMatchesText(""); - ExpectStderrMatchesText( - "google/protobuf/no_such_file.proto: No such file or directory\n"); -} - -INSTANTIATE_TEST_CASE_P(FileDescriptorSetSource, - EncodeDecodeTest, - testing::Values(PROTO_PATH, DESCRIPTOR_SET_IN)); -} // anonymous namespace - -#endif // !GOOGLE_PROTOBUF_HEAP_CHECK_DRACONIAN - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/windows/include/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc deleted file mode 100644 index 4e150fe3d..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc +++ /dev/null @@ -1,172 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This test insures that google/protobuf/descriptor.pb.{h,cc} match exactly -// what would be generated by the protocol compiler. These files are not -// generated automatically at build time because they are compiled into the -// protocol compiler itself. So, if they were auto-generated, you'd have a -// chicken-and-egg problem. -// -// If this test fails, run the script -// "generate_descriptor_proto.sh" and add -// descriptor.pb.{h,cc} to your changelist. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -namespace { - -class MockErrorCollector : public MultiFileErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - - // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", - filename, line, column, message); - } -}; - -class MockGeneratorContext : public GeneratorContext { - public: - MockGeneratorContext() {} - ~MockGeneratorContext() { - STLDeleteValues(&files_); - } - - void ExpectFileMatches(const string& virtual_filename, - const string& physical_filename) { - string* expected_contents = FindPtrOrNull(files_, virtual_filename); - ASSERT_TRUE(expected_contents != NULL) - << "Generator failed to generate file: " << virtual_filename; - - string actual_contents; - GOOGLE_CHECK_OK( - File::GetContents(TestSourceDir() + "/" + physical_filename, - &actual_contents, true)); - EXPECT_TRUE(actual_contents == *expected_contents) - << physical_filename - << " needs to be regenerated. Please run " - "generate_descriptor_proto.sh. " - "Then add this file to your CL."; - } - - // implements GeneratorContext -------------------------------------- - - virtual io::ZeroCopyOutputStream* Open(const string& filename) { - string** map_slot = &files_[filename]; - delete *map_slot; - *map_slot = new string; - - return new io::StringOutputStream(*map_slot); - } - - private: - std::map files_; -}; - -const char kDescriptorParameter[] = "dllexport_decl=LIBPROTOBUF_EXPORT"; -const char kPluginParameter[] = "dllexport_decl=LIBPROTOC_EXPORT"; -const char kNormalParameter[] = ""; - -const char* test_protos[][2] = { - {"google/protobuf/descriptor", kDescriptorParameter}, - {"google/protobuf/compiler/plugin", kPluginParameter}, -}; - -TEST(BootstrapTest, GeneratedFilesMatch) { - // We need a mapping from the actual file to virtual and actual path - // of the data to compare to. - std::map vpath_map; - std::map rpath_map; - rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto2"] = - "net/proto2/z_generated_example/test_messages_proto2"; - rpath_map["third_party/protobuf/src/google/protobuf/test_messages_proto3"] = - "net/proto2/z_generated_example/test_messages_proto3"; - rpath_map["google/protobuf/proto2_weak"] = - "net/proto2/z_generated_example/proto2_weak"; - - DiskSourceTree source_tree; - source_tree.MapPath("", TestSourceDir()); - - for (auto file_parameter : test_protos) { - MockErrorCollector error_collector; - Importer importer(&source_tree, &error_collector); - const FileDescriptor* file = - importer.Import(file_parameter[0] + string(".proto")); - ASSERT_TRUE(file != nullptr) - << "Can't import file " << file_parameter[0] + string(".proto") << "\n"; - EXPECT_EQ("", error_collector.text_); - CppGenerator generator; - MockGeneratorContext context; - string error; - ASSERT_TRUE(generator.Generate(file, file_parameter[1], &context, &error)); - - string vpath = - FindWithDefault(vpath_map, file_parameter[0], file_parameter[0]); - string rpath = - FindWithDefault(rpath_map, file_parameter[0], file_parameter[0]); - context.ExpectFileMatches(vpath + ".pb.cc", rpath + ".pb.cc"); - context.ExpectFileMatches(vpath + ".pb.h", rpath + ".pb.h"); - } -} - -} // namespace - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_enum.cc b/windows/include/google/protobuf/compiler/cpp/cpp_enum.cc deleted file mode 100644 index 0d6a9e244..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_enum.cc +++ /dev/null @@ -1,327 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -namespace { -// The GOOGLE_ARRAYSIZE constant is the max enum value plus 1. If the max enum value -// is ::google::protobuf::kint32max, GOOGLE_ARRAYSIZE will overflow. In such cases we should omit the -// generation of the GOOGLE_ARRAYSIZE constant. -bool ShouldGenerateArraySize(const EnumDescriptor* descriptor) { - int32 max_value = descriptor->value(0)->number(); - for (int i = 0; i < descriptor->value_count(); i++) { - if (descriptor->value(i)->number() > max_value) { - max_value = descriptor->value(i)->number(); - } - } - return max_value != ::google::protobuf::kint32max; -} -} // namespace - -EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, - const Options& options) - : descriptor_(descriptor), - classname_(ClassName(descriptor, false)), - options_(options), - generate_array_size_(ShouldGenerateArraySize(descriptor)) { -} - -EnumGenerator::~EnumGenerator() {} - -void EnumGenerator::FillForwardDeclaration( - std::map* enum_names) { - if (!options_.proto_h) { - return; - } - (*enum_names)[classname_] = descriptor_; -} - -void EnumGenerator::GenerateDefinition(io::Printer* printer) { - std::map vars; - vars["classname"] = classname_; - vars["short_name"] = descriptor_->name(); - vars["enumbase"] = options_.proto_h ? " : int" : ""; - // These variables are placeholders to pick out the beginning and ends of - // identifiers for annotations (when doing so with existing variables would - // be ambiguous or impossible). They should never be set to anything but the - // empty string. - vars["{"] = ""; - vars["}"] = ""; - - printer->Print(vars, "enum $classname$$enumbase$ {\n"); - printer->Annotate("classname", descriptor_); - printer->Indent(); - - const EnumValueDescriptor* min_value = descriptor_->value(0); - const EnumValueDescriptor* max_value = descriptor_->value(0); - - for (int i = 0; i < descriptor_->value_count(); i++) { - vars["name"] = EnumValueName(descriptor_->value(i)); - // In C++, an value of -2147483648 gets interpreted as the negative of - // 2147483648, and since 2147483648 can't fit in an integer, this produces a - // compiler warning. This works around that issue. - vars["number"] = Int32ToString(descriptor_->value(i)->number()); - vars["prefix"] = (descriptor_->containing_type() == NULL) ? - "" : classname_ + "_"; - vars["deprecation"] = descriptor_->value(i)->options().deprecated() ? - " PROTOBUF_DEPRECATED" : ""; - - if (i > 0) printer->Print(",\n"); - printer->Print(vars, "${$$prefix$$name$$}$$deprecation$ = $number$"); - printer->Annotate("{", "}", descriptor_->value(i)); - - if (descriptor_->value(i)->number() < min_value->number()) { - min_value = descriptor_->value(i); - } - if (descriptor_->value(i)->number() > max_value->number()) { - max_value = descriptor_->value(i); - } - } - - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - // For new enum semantics: generate min and max sentinel values equal to - // INT32_MIN and INT32_MAX - if (descriptor_->value_count() > 0) printer->Print(",\n"); - printer->Print(vars, - "$classname$_$prefix$INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,\n" - "$classname$_$prefix$INT_MAX_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max"); - } - - printer->Outdent(); - printer->Print("\n};\n"); - - vars["min_name"] = EnumValueName(min_value); - vars["max_name"] = EnumValueName(max_value); - - if (options_.dllexport_decl.empty()) { - vars["dllexport"] = ""; - } else { - vars["dllexport"] = options_.dllexport_decl + " "; - } - - printer->Print(vars, - "$dllexport$bool $classname$_IsValid(int value);\n" - "const $classname$ ${$$prefix$$short_name$_MIN$}$ = " - "$prefix$$min_name$;\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(vars, - "const $classname$ ${$$prefix$$short_name$_MAX$}$ = " - "$prefix$$max_name$;\n"); - printer->Annotate("{", "}", descriptor_); - - if (generate_array_size_) { - printer->Print(vars, - "const int ${$$prefix$$short_name$_ARRAYSIZE$}$ = " - "$prefix$$short_name$_MAX + 1;\n\n"); - printer->Annotate("{", "}", descriptor_); - } - - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print(vars, - "$dllexport$const ::google::protobuf::EnumDescriptor* $classname$_descriptor();\n"); - // The _Name and _Parse methods - printer->Print( - vars, - "inline const ::std::string& $classname$_Name($classname$ value) {\n" - " return ::google::protobuf::internal::NameOfEnum(\n" - " $classname$_descriptor(), value);\n" - "}\n"); - printer->Print(vars, - "inline bool $classname$_Parse(\n" - " const ::std::string& name, $classname$* value) {\n" - " return ::google::protobuf::internal::ParseNamedEnum<$classname$>(\n" - " $classname$_descriptor(), name, value);\n" - "}\n"); - } -} - -void EnumGenerator:: -GenerateGetEnumDescriptorSpecializations(io::Printer* printer) { - printer->Print( - "template <> struct is_proto_enum< $classname$> : ::std::true_type " - "{};\n", - "classname", ClassName(descriptor_, true)); - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - "template <>\n" - "inline const EnumDescriptor* GetEnumDescriptor< $classname$>() {\n" - " return $classname$_descriptor();\n" - "}\n", - "classname", ClassName(descriptor_, true)); - } -} - -void EnumGenerator::GenerateSymbolImports(io::Printer* printer) { - std::map vars; - vars["nested_name"] = descriptor_->name(); - vars["classname"] = classname_; - vars["constexpr"] = options_.proto_h ? "constexpr " : ""; - vars["{"] = ""; - vars["}"] = ""; - printer->Print(vars, "typedef $classname$ $nested_name$;\n"); - - for (int j = 0; j < descriptor_->value_count(); j++) { - vars["tag"] = EnumValueName(descriptor_->value(j)); - vars["deprecated_attr"] = descriptor_->value(j)->options().deprecated() ? - "GOOGLE_PROTOBUF_DEPRECATED_ATTR " : ""; - printer->Print(vars, - "$deprecated_attr$static $constexpr$const $nested_name$ ${$$tag$$}$ =\n" - " $classname$_$tag$;\n"); - printer->Annotate("{", "}", descriptor_->value(j)); - } - - printer->Print(vars, - "static inline bool $nested_name$_IsValid(int value) {\n" - " return $classname$_IsValid(value);\n" - "}\n" - "static const $nested_name$ ${$$nested_name$_MIN$}$ =\n" - " $classname$_$nested_name$_MIN;\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(vars, - "static const $nested_name$ ${$$nested_name$_MAX$}$ =\n" - " $classname$_$nested_name$_MAX;\n"); - printer->Annotate("{", "}", descriptor_); - if (generate_array_size_) { - printer->Print(vars, - "static const int ${$$nested_name$_ARRAYSIZE$}$ =\n" - " $classname$_$nested_name$_ARRAYSIZE;\n"); - printer->Annotate("{", "}", descriptor_); - } - - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print(vars, - "static inline const ::google::protobuf::EnumDescriptor*\n" - "$nested_name$_descriptor() {\n" - " return $classname$_descriptor();\n" - "}\n"); - printer->Print(vars, - "static inline const ::std::string& " - "$nested_name$_Name($nested_name$ value) {" - "\n" - " return $classname$_Name(value);\n" - "}\n"); - printer->Print(vars, - "static inline bool $nested_name$_Parse(const ::std::string& name,\n" - " $nested_name$* value) {\n" - " return $classname$_Parse(name, value);\n" - "}\n"); - } -} - -void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) { - std::map vars; - vars["classname"] = classname_; - vars["index_in_metadata"] = SimpleItoa(idx); - vars["constexpr"] = options_.proto_h ? "constexpr " : ""; - vars["file_namespace"] = FileLevelNamespace(descriptor_->file()->name()); - - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - vars, - "const ::google::protobuf::EnumDescriptor* $classname$_descriptor() {\n" - " $file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return " - "$file_namespace$::file_level_enum_descriptors[$index_in_metadata$];\n" - "}\n"); - } - - printer->Print(vars, - "bool $classname$_IsValid(int value) {\n" - " switch (value) {\n"); - - // Multiple values may have the same number. Make sure we only cover - // each number once by first constructing a set containing all valid - // numbers, then printing a case statement for each element. - - std::set numbers; - for (int j = 0; j < descriptor_->value_count(); j++) { - const EnumValueDescriptor* value = descriptor_->value(j); - numbers.insert(value->number()); - } - - for (std::set::iterator iter = numbers.begin(); - iter != numbers.end(); ++iter) { - printer->Print( - " case $number$:\n", - "number", Int32ToString(*iter)); - } - - printer->Print(vars, - " return true;\n" - " default:\n" - " return false;\n" - " }\n" - "}\n" - "\n"); - - if (descriptor_->containing_type() != NULL) { - // We need to "define" the static constants which were declared in the - // header, to give the linker a place to put them. Or at least the C++ - // standard says we have to. MSVC actually insists that we do _not_ define - // them again in the .cc file, prior to VC++ 2015. - printer->Print("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n"); - - vars["parent"] = ClassName(descriptor_->containing_type(), false); - vars["nested_name"] = descriptor_->name(); - for (int i = 0; i < descriptor_->value_count(); i++) { - vars["value"] = EnumValueName(descriptor_->value(i)); - printer->Print(vars, - "$constexpr$const $classname$ $parent$::$value$;\n"); - } - printer->Print(vars, - "const $classname$ $parent$::$nested_name$_MIN;\n" - "const $classname$ $parent$::$nested_name$_MAX;\n"); - if (generate_array_size_) { - printer->Print(vars, - "const int $parent$::$nested_name$_ARRAYSIZE;\n"); - } - - printer->Print("#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n"); - } -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_enum.h b/windows/include/google/protobuf/compiler/cpp/cpp_enum.h deleted file mode 100644 index 0d2488a99..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_enum.h +++ /dev/null @@ -1,110 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__ - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace cpp { - -class EnumGenerator { - public: - // See generator.cc for the meaning of dllexport_decl. - EnumGenerator(const EnumDescriptor* descriptor, const Options& options); - ~EnumGenerator(); - - // Header stuff. - - // Fills the name to use when declaring the enum. This is for use when - // generating other .proto.h files. This code should be placed within the - // enum's package namespace, but NOT within any class, even for nested - // enums. A given key in enum_names will map from an enum class name to the - // EnumDescriptor that was responsible for its inclusion in the map. This can - // be used to associate the descriptor with the code generated for it. - void FillForwardDeclaration( - std::map* enum_names); - - // Generate header code defining the enum. This code should be placed - // within the enum's package namespace, but NOT within any class, even for - // nested enums. - void GenerateDefinition(io::Printer* printer); - - // Generate specialization of GetEnumDescriptor(). - // Precondition: in ::google::protobuf namespace. - void GenerateGetEnumDescriptorSpecializations(io::Printer* printer); - - // For enums nested within a message, generate code to import all the enum's - // symbols (e.g. the enum type name, all its values, etc.) into the class's - // namespace. This should be placed inside the class definition in the - // header. - void GenerateSymbolImports(io::Printer* printer); - - // Source file stuff. - - // Generate non-inline methods related to the enum, such as IsValidValue(). - // Goes in the .cc file. EnumDescriptors are stored in an array, idx is - // the index in this array that corresponds with this enum. - void GenerateMethods(int idx, io::Printer* printer); - - private: - const EnumDescriptor* descriptor_; - const string classname_; - const Options& options_; - // whether to generate the *_ARRAYSIZE constant. - const bool generate_array_size_; - - friend class FileGenerator; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_enum_field.cc b/windows/include/google/protobuf/compiler/cpp/cpp_enum_field.cc deleted file mode 100644 index 50c7b5f3f..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_enum_field.cc +++ /dev/null @@ -1,520 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -namespace { - -void SetEnumVariables(const FieldDescriptor* descriptor, - std::map* variables, - const Options& options) { - SetCommonFieldVariables(descriptor, variables, options); - const EnumValueDescriptor* default_value = descriptor->default_value_enum(); - (*variables)["type"] = ClassName(descriptor->enum_type(), true); - (*variables)["default"] = Int32ToString(default_value->number()); - (*variables)["full_name"] = descriptor->full_name(); -} - -} // namespace - -// =================================================================== - -EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { - SetEnumVariables(descriptor, &variables_, options); -} - -EnumFieldGenerator::~EnumFieldGenerator() {} - -void EnumFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, "int $name$_;\n"); -} - -void EnumFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, "$deprecated_attr$$type$ $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$($type$ value);\n"); - printer->Annotate("{", "}", descriptor_); -} - -void EnumFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return static_cast< $type$ >($name$_);\n" - "}\n" - "inline void $classname$::set_$name$($type$ value) {\n"); - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " assert($type$_IsValid(value));\n"); - } - printer->Print(variables_, - " $set_hasbit$\n" - " $name$_ = value;\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n"); -} - -void EnumFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void EnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "set_$name$(from.$name$());\n"); -} - -void EnumFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "swap($name$_, other->$name$_);\n"); -} - -void EnumFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void EnumFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = from.$name$_;\n"); -} - -void EnumFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "int value;\n" - "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n" - " input, &value)));\n"); - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - "set_$name$(static_cast< $type$ >(value));\n"); - } else { - printer->Print(variables_, - "if ($type$_IsValid(value)) {\n" - " set_$name$(static_cast< $type$ >(value));\n"); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(variables_, - "} else {\n" - " mutable_unknown_fields()->AddVarint(\n" - " $number$, static_cast< ::google::protobuf::uint64>(value));\n"); - } else { - printer->Print( - "} else {\n" - " unknown_fields_stream.WriteVarint32($tag$u);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(value));\n", - "tag", SimpleItoa(internal::WireFormat::MakeTag(descriptor_))); - } - printer->Print(variables_, - "}\n"); - } -} - -void EnumFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::internal::WireFormatLite::WriteEnum(\n" - " $number$, this->$name$(), output);\n"); -} - -void EnumFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n" - " $number$, this->$name$(), target);\n"); -} - -void EnumFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::EnumSize(this->$name$());\n"); -} - -// =================================================================== - -EnumOneofFieldGenerator:: -EnumOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : EnumFieldGenerator(descriptor, options) { - SetCommonOneofFieldVariables(descriptor, &variables_); -} - -EnumOneofFieldGenerator::~EnumOneofFieldGenerator() {} - -void EnumOneofFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " if (has_$name$()) {\n" - " return static_cast< $type$ >($field_member$);\n" - " }\n" - " return static_cast< $type$ >($default$);\n" - "}\n" - "inline void $classname$::set_$name$($type$ value) {\n"); - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " assert($type$_IsValid(value));\n"); - } - printer->Print(variables_, - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " }\n" - " $field_member$ = value;\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n"); -} - -void EnumOneofFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$field_member$ = $default$;\n"); -} - -void EnumOneofFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - // Don't print any swapping code. Swapping the union will swap this field. -} - -void EnumOneofFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, - "$ns$::_$classname$_default_instance_.$name$_ = $default$;\n"); -} - -// =================================================================== - -RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { - SetEnumVariables(descriptor, &variables_, options); -} - -RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {} - -void RepeatedEnumFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::RepeatedField $name$_;\n"); - if (descriptor_->is_packed() && - HasGeneratedMethods(descriptor_->file(), options_)) { - printer->Print(variables_, - "mutable int _$name$_cached_byte_size_;\n"); - } -} - -void RepeatedEnumFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, - "$deprecated_attr$$type$ $name$(int index) const;\n"); - printer->Annotate("name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$set_$name$$}$(int index, $type$ value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$add_$name$$}$($type$ value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$const ::google::protobuf::RepeatedField& $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::RepeatedField* " - "${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedEnumFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return static_cast< $type$ >($name$_.Get(index));\n" - "}\n" - "inline void $classname$::set_$name$(int index, $type$ value) {\n"); - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " assert($type$_IsValid(value));\n"); - } - printer->Print(variables_, - " $name$_.Set(index, value);\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n" - "inline void $classname$::add_$name$($type$ value) {\n"); - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " assert($type$_IsValid(value));\n"); - } - printer->Print(variables_, - " $name$_.Add(value);\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "}\n" - "inline const ::google::protobuf::RepeatedField&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_list:$full_name$)\n" - " return $name$_;\n" - "}\n" - "inline ::google::protobuf::RepeatedField*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" - " return &$name$_;\n" - "}\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Clear();\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - // Not needed for repeated fields. -} - -void RepeatedEnumFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - // Don't use ReadRepeatedPrimitive here so that the enum can be validated. - printer->Print(variables_, - "int value;\n" - "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n" - " input, &value)));\n"); - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - "add_$name$(static_cast< $type$ >(value));\n"); - } else { - printer->Print(variables_, - "if ($type$_IsValid(value)) {\n" - " add_$name$(static_cast< $type$ >(value));\n"); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(variables_, - "} else {\n" - " mutable_unknown_fields()->AddVarint(\n" - " $number$, static_cast< ::google::protobuf::uint64>(value));\n"); - } else { - printer->Print( - "} else {\n" - " unknown_fields_stream.WriteVarint32(tag);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(value));\n"); - } - printer->Print("}\n"); - } -} - -void RepeatedEnumFieldGenerator:: -GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { - if (!descriptor_->is_packed()) { - // This path is rarely executed, so we use a non-inlined implementation. - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - "DO_((::google::protobuf::internal::" - "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n" - " input,\n" - " $number$,\n" - " NULL,\n" - " NULL,\n" - " this->mutable_$name$())));\n"); - } else if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(variables_, - "DO_((::google::protobuf::internal::WireFormat::ReadPackedEnumPreserveUnknowns(\n" - " input,\n" - " $number$,\n" - " $type$_IsValid,\n" - " mutable_unknown_fields(),\n" - " this->mutable_$name$())));\n"); - } else { - printer->Print(variables_, - "DO_((::google::protobuf::internal::" - "WireFormatLite::ReadPackedEnumPreserveUnknowns(\n" - " input,\n" - " $number$,\n" - " $type$_IsValid,\n" - " &unknown_fields_stream,\n" - " this->mutable_$name$())));\n"); - } - } else { - printer->Print(variables_, - "::google::protobuf::uint32 length;\n" - "DO_(input->ReadVarint32(&length));\n" - "::google::protobuf::io::CodedInputStream::Limit limit = " - "input->PushLimit(static_cast(length));\n" - "while (input->BytesUntilLimit() > 0) {\n" - " int value;\n" - " DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(\n" - " input, &value)));\n"); - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - printer->Print(variables_, - " add_$name$(static_cast< $type$ >(value));\n"); - } else { - printer->Print(variables_, - " if ($type$_IsValid(value)) {\n" - " add_$name$(static_cast< $type$ >(value));\n" - " } else {\n"); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(variables_, - " mutable_unknown_fields()->AddVarint(\n" - " $number$, static_cast< ::google::protobuf::uint64>(value));\n"); - } else { - printer->Print(variables_, - " unknown_fields_stream.WriteVarint32(tag);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(value));\n"); - } - printer->Print( - " }\n"); - } - printer->Print(variables_, - "}\n" - "input->PopLimit(limit);\n"); - } -} - -void RepeatedEnumFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - if (descriptor_->is_packed()) { - // Write the tag and the size. - printer->Print(variables_, - "if (this->$name$_size() > 0) {\n" - " ::google::protobuf::internal::WireFormatLite::WriteTag(\n" - " $number$,\n" - " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" - " output);\n" - " output->WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(_$name$_cached_byte_size_));\n" - "}\n"); - } - printer->Print(variables_, - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); - if (descriptor_->is_packed()) { - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag(\n" - " this->$name$(i), output);\n"); - } else { - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::WriteEnum(\n" - " $number$, this->$name$(i), output);\n"); - } - printer->Print("}\n"); -} - -void RepeatedEnumFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - if (descriptor_->is_packed()) { - // Write the tag and the size. - printer->Print(variables_, - "if (this->$name$_size() > 0) {\n" - " target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n" - " $number$,\n" - " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" - " target);\n" - " target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(" - " static_cast< ::google::protobuf::uint32>(\n" - " _$name$_cached_byte_size_), target);\n" - " target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray(\n" - " this->$name$_, target);\n" - "}\n"); - } else { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(\n" - " $number$, this->$name$_, target);\n"); - } -} - -void RepeatedEnumFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " size_t data_size = 0;\n" - " unsigned int count = static_cast(this->$name$_size());"); - printer->Indent(); - printer->Print(variables_, - "for (unsigned int i = 0; i < count; i++) {\n" - " data_size += ::google::protobuf::internal::WireFormatLite::EnumSize(\n" - " this->$name$(static_cast(i)));\n" - "}\n"); - - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (data_size > 0) {\n" - " total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::Int32Size(\n" - " static_cast< ::google::protobuf::int32>(data_size));\n" - "}\n" - "int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - "_$name$_cached_byte_size_ = cached_size;\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - "total_size += data_size;\n"); - } else { - printer->Print(variables_, - "total_size += ($tag_size$UL * count) + data_size;\n"); - } - printer->Outdent(); - printer->Print("}\n"); -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_enum_field.h b/windows/include/google/protobuf/compiler/cpp/cpp_enum_field.h deleted file mode 100644 index d0e87b79c..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_enum_field.h +++ /dev/null @@ -1,123 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -class EnumFieldGenerator : public FieldGenerator { - public: - EnumFieldGenerator(const FieldDescriptor* descriptor, const Options& options); - ~EnumFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateCopyConstructorCode(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); -}; - -class EnumOneofFieldGenerator : public EnumFieldGenerator { - public: - EnumOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~EnumOneofFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumOneofFieldGenerator); -}; - -class RepeatedEnumFieldGenerator : public FieldGenerator { - public: - RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~RepeatedEnumFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateCopyConstructorCode(io::Printer* printer) const {} - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_ENUM_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_extension.cc b/windows/include/google/protobuf/compiler/cpp/cpp_extension.cc deleted file mode 100644 index c416ba107..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_extension.cc +++ /dev/null @@ -1,172 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -namespace { - -// Returns the fully-qualified class name of the message that this field -// extends. This function is used in the Google-internal code to handle some -// legacy cases. -string ExtendeeClassName(const FieldDescriptor* descriptor) { - const Descriptor* extendee = descriptor->containing_type(); - return ClassName(extendee, true); -} - -} // anonymous namespace - -ExtensionGenerator::ExtensionGenerator(const FieldDescriptor* descriptor, - const Options& options) - : descriptor_(descriptor), - options_(options) { - // Construct type_traits_. - if (descriptor_->is_repeated()) { - type_traits_ = "Repeated"; - } - - switch (descriptor_->cpp_type()) { - case FieldDescriptor::CPPTYPE_ENUM: - type_traits_.append("EnumTypeTraits< "); - type_traits_.append(ClassName(descriptor_->enum_type(), true)); - type_traits_.append(", "); - type_traits_.append(ClassName(descriptor_->enum_type(), true)); - type_traits_.append("_IsValid>"); - break; - case FieldDescriptor::CPPTYPE_STRING: - type_traits_.append("StringTypeTraits"); - break; - case FieldDescriptor::CPPTYPE_MESSAGE: - type_traits_.append("MessageTypeTraits< "); - type_traits_.append(ClassName(descriptor_->message_type(), true)); - type_traits_.append(" >"); - break; - default: - type_traits_.append("PrimitiveTypeTraits< "); - type_traits_.append(PrimitiveTypeName(descriptor_->cpp_type())); - type_traits_.append(" >"); - break; - } -} - -ExtensionGenerator::~ExtensionGenerator() {} - -void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) { - std::map vars; - vars["extendee" ] = ExtendeeClassName(descriptor_); - vars["number" ] = SimpleItoa(descriptor_->number()); - vars["type_traits" ] = type_traits_; - vars["name" ] = descriptor_->name(); - vars["field_type" ] = SimpleItoa(static_cast(descriptor_->type())); - vars["packed" ] = descriptor_->options().packed() ? "true" : "false"; - vars["constant_name"] = FieldConstantName(descriptor_); - - // If this is a class member, it needs to be declared "static". Otherwise, - // it needs to be "extern". In the latter case, it also needs the DLL - // export/import specifier. - if (descriptor_->extension_scope() == NULL) { - vars["qualifier"] = "extern"; - if (!options_.dllexport_decl.empty()) { - vars["qualifier"] = options_.dllexport_decl + " " + vars["qualifier"]; - } - } else { - vars["qualifier"] = "static"; - } - - printer->Print(vars, - "static const int $constant_name$ = $number$;\n" - "$qualifier$ ::google::protobuf::internal::ExtensionIdentifier< $extendee$,\n" - " ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n" - " $name$;\n" - ); -} - -void ExtensionGenerator::GenerateDefinition(io::Printer* printer) { - // If this is a class member, it needs to be declared in its class scope. - string scope = (descriptor_->extension_scope() == NULL) ? "" : - ClassName(descriptor_->extension_scope(), false) + "::"; - string name = scope + descriptor_->name(); - - std::map vars; - vars["extendee" ] = ExtendeeClassName(descriptor_); - vars["type_traits" ] = type_traits_; - vars["name" ] = name; - vars["constant_name"] = FieldConstantName(descriptor_); - vars["default" ] = DefaultValue(descriptor_); - vars["field_type" ] = SimpleItoa(static_cast(descriptor_->type())); - vars["packed" ] = descriptor_->options().packed() ? "true" : "false"; - vars["scope" ] = scope; - - if (descriptor_->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { - // We need to declare a global string which will contain the default value. - // We cannot declare it at class scope because that would require exposing - // it in the header which would be annoying for other reasons. So we - // replace :: with _ in the name and declare it as a global. - string global_name = StringReplace(name, "::", "_", true); - vars["global_name"] = global_name; - printer->Print(vars, - "const ::std::string $global_name$_default($default$);\n"); - - // Update the default to refer to the string global. - vars["default"] = global_name + "_default"; - } - - // Likewise, class members need to declare the field constant variable. - if (descriptor_->extension_scope() != NULL) { - printer->Print(vars, - "#if !defined(_MSC_VER) || _MSC_VER >= 1900\n" - "const int $scope$$constant_name$;\n" - "#endif\n"); - } - - printer->Print(vars, - "::google::protobuf::internal::ExtensionIdentifier< $extendee$,\n" - " ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n" - " $name$($constant_name$, $default$);\n"); -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_extension.h b/windows/include/google/protobuf/compiler/cpp/cpp_extension.h deleted file mode 100644 index 30236d71a..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_extension.h +++ /dev/null @@ -1,83 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_EXTENSION_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - class FieldDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace cpp { - -// Generates code for an extension, which may be within the scope of some -// message or may be at file scope. This is much simpler than FieldGenerator -// since extensions are just simple identifiers with interesting types. -class ExtensionGenerator { - public: - // See generator.cc for the meaning of dllexport_decl. - explicit ExtensionGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~ExtensionGenerator(); - - // Header stuff. - void GenerateDeclaration(io::Printer* printer); - - // Source file stuff. - void GenerateDefinition(io::Printer* printer); - - private: - const FieldDescriptor* descriptor_; - string type_traits_; - Options options_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_field.cc b/windows/include/google/protobuf/compiler/cpp/cpp_field.cc deleted file mode 100644 index 0de20f84f..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_field.cc +++ /dev/null @@ -1,195 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -using internal::WireFormat; - -void SetCommonFieldVariables(const FieldDescriptor* descriptor, - std::map* variables, - const Options& options) { - (*variables)["ns"] = Namespace(descriptor); - (*variables)["name"] = FieldName(descriptor); - (*variables)["index"] = SimpleItoa(descriptor->index()); - (*variables)["number"] = SimpleItoa(descriptor->number()); - (*variables)["classname"] = ClassName(FieldScope(descriptor), false); - (*variables)["declared_type"] = DeclaredTypeMethodName(descriptor->type()); - (*variables)["field_member"] = FieldName(descriptor) + "_"; - - (*variables)["tag_size"] = SimpleItoa( - WireFormat::TagSize(descriptor->number(), descriptor->type())); - (*variables)["deprecation"] = descriptor->options().deprecated() - ? " PROTOBUF_DEPRECATED" : ""; - (*variables)["deprecated_attr"] = descriptor->options().deprecated() - ? "GOOGLE_PROTOBUF_DEPRECATED_ATTR " : ""; - - if (HasFieldPresence(descriptor->file())) { - (*variables)["set_hasbit"] = - "set_has_" + FieldName(descriptor) + "();"; - (*variables)["clear_hasbit"] = - "clear_has_" + FieldName(descriptor) + "();"; - } else { - (*variables)["set_hasbit"] = ""; - (*variables)["clear_hasbit"] = ""; - } - - // These variables are placeholders to pick out the beginning and ends of - // identifiers for annotations (when doing so with existing variables would - // be ambiguous or impossible). They should never be set to anything but the - // empty string. - (*variables)["{"] = ""; - (*variables)["}"] = ""; -} - -void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor, - std::map* variables) { - const string prefix = descriptor->containing_oneof()->name() + "_."; - (*variables)["oneof_name"] = descriptor->containing_oneof()->name(); - (*variables)["field_member"] = StrCat(prefix, (*variables)["name"], "_"); -} - -FieldGenerator::~FieldGenerator() {} - -void FieldGenerator:: -GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { - // Reaching here indicates a bug. Cases are: - // - This FieldGenerator should support packing, but this method should be - // overridden. - // - This FieldGenerator doesn't support packing, and this method should - // never have been called. - GOOGLE_LOG(FATAL) << "GenerateMergeFromCodedStreamWithPacking() " - << "called on field generator that does not support packing."; - -} - -FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor, - const Options& options, - SCCAnalyzer* scc_analyzer) - : descriptor_(descriptor), - options_(options), - field_generators_(descriptor->field_count()) { - // Construct all the FieldGenerators. - for (int i = 0; i < descriptor->field_count(); i++) { - field_generators_[i].reset( - MakeGenerator(descriptor->field(i), options, scc_analyzer)); - } -} - -FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field, - const Options& options, - SCCAnalyzer* scc_analyzer) { - if (field->is_repeated()) { - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_MESSAGE: - if (field->is_map()) { - return new MapFieldGenerator(field, options); - } else { - return new RepeatedMessageFieldGenerator(field, options, - scc_analyzer); - } - case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // RepeatedStringFieldGenerator handles unknown ctypes. - case FieldOptions::STRING: - return new RepeatedStringFieldGenerator(field, options); - } - case FieldDescriptor::CPPTYPE_ENUM: - return new RepeatedEnumFieldGenerator(field, options); - default: - return new RepeatedPrimitiveFieldGenerator(field, options); - } - } else if (field->containing_oneof()) { - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_MESSAGE: - return new MessageOneofFieldGenerator(field, options, scc_analyzer); - case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // StringOneofFieldGenerator handles unknown ctypes. - case FieldOptions::STRING: - return new StringOneofFieldGenerator(field, options); - } - case FieldDescriptor::CPPTYPE_ENUM: - return new EnumOneofFieldGenerator(field, options); - default: - return new PrimitiveOneofFieldGenerator(field, options); - } - } else { - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_MESSAGE: - return new MessageFieldGenerator(field, options, scc_analyzer); - case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // StringFieldGenerator handles unknown ctypes. - case FieldOptions::STRING: - return new StringFieldGenerator(field, options); - } - case FieldDescriptor::CPPTYPE_ENUM: - return new EnumFieldGenerator(field, options); - default: - return new PrimitiveFieldGenerator(field, options); - } - } -} - -FieldGeneratorMap::~FieldGeneratorMap() {} - -const FieldGenerator& FieldGeneratorMap::get( - const FieldDescriptor* field) const { - GOOGLE_CHECK_EQ(field->containing_type(), descriptor_); - return *field_generators_[field->index()]; -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_field.h b/windows/include/google/protobuf/compiler/cpp/cpp_field.h deleted file mode 100644 index 8cdbe8863..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_field.h +++ /dev/null @@ -1,220 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__ - -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace cpp { - -// Helper function: set variables in the map that are the same for all -// field code generators. -// ['name', 'index', 'number', 'classname', 'declared_type', 'tag_size', -// 'deprecation']. -void SetCommonFieldVariables(const FieldDescriptor* descriptor, - std::map* variables, - const Options& options); - -void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor, - std::map* variables); - -class FieldGenerator { - public: - explicit FieldGenerator(const Options& options) : options_(options) {} - virtual ~FieldGenerator(); - - // Generate lines of code declaring members fields of the message class - // needed to represent this field. These are placed inside the message - // class. - virtual void GeneratePrivateMembers(io::Printer* printer) const = 0; - - // Generate static default variable for this field. These are placed inside - // the message class. Most field types don't need this, so the default - // implementation is empty. - virtual void GenerateStaticMembers(io::Printer* /*printer*/) const {} - - // Generate prototypes for all of the accessor functions related to this - // field. These are placed inside the class definition. - virtual void GenerateAccessorDeclarations(io::Printer* printer) const = 0; - - // Generate inline definitions of accessor functions for this field. - // These are placed inside the header after all class definitions. - virtual void GenerateInlineAccessorDefinitions( - io::Printer* printer) const = 0; - - // Generate definitions of accessors that aren't inlined. These are - // placed somewhere in the .cc file. - // Most field types don't need this, so the default implementation is empty. - virtual void GenerateNonInlineAccessorDefinitions( - io::Printer* /*printer*/) const {} - - // Generate lines of code (statements, not declarations) which clear the - // field. This is used to define the clear_$name$() method - virtual void GenerateClearingCode(io::Printer* printer) const = 0; - - // Generate lines of code (statements, not declarations) which clear the field - // as part of the Clear() method for the whole message. For message types - // which have field presence bits, MessageGenerator::GenerateClear will have - // already checked the presence bits. - // - // Since most field types can re-use GenerateClearingCode, this method is not - // pure virtual. - virtual void GenerateMessageClearingCode(io::Printer* printer) const { - GenerateClearingCode(printer); - } - - // Generate lines of code (statements, not declarations) which merges the - // contents of the field from the current message to the target message, - // which is stored in the generated code variable "from". - // This is used to fill in the MergeFrom method for the whole message. - // Details of this usage can be found in message.cc under the - // GenerateMergeFrom method. - virtual void GenerateMergingCode(io::Printer* printer) const = 0; - - // Generates a copy constructor - virtual void GenerateCopyConstructorCode(io::Printer* printer) const = 0; - - // Generate lines of code (statements, not declarations) which swaps - // this field and the corresponding field of another message, which - // is stored in the generated code variable "other". This is used to - // define the Swap method. Details of usage can be found in - // message.cc under the GenerateSwap method. - virtual void GenerateSwappingCode(io::Printer* printer) const = 0; - - // Generate initialization code for private members declared by - // GeneratePrivateMembers(). These go into the message class's SharedCtor() - // method, invoked by each of the generated constructors. - virtual void GenerateConstructorCode(io::Printer* printer) const = 0; - - // Generate any code that needs to go in the class's SharedDtor() method, - // invoked by the destructor. - // Most field types don't need this, so the default implementation is empty. - virtual void GenerateDestructorCode(io::Printer* /*printer*/) const {} - - // Generate a manual destructor invocation for use when the message is on an - // arena. The code that this method generates will be executed inside a - // shared-for-the-whole-message-class method registered with OwnDestructor(). - // The method should return |true| if it generated any code that requires a - // call; this allows the message generator to eliminate the OwnDestructor() - // registration if no fields require it. - virtual bool GenerateArenaDestructorCode(io::Printer* printer) const { - return false; - } - - // Generate code that allocates the fields's default instance. - virtual void GenerateDefaultInstanceAllocator(io::Printer* /*printer*/) - const {} - - // Generate lines to decode this field, which will be placed inside the - // message's MergeFromCodedStream() method. - virtual void GenerateMergeFromCodedStream(io::Printer* printer) const = 0; - - // Returns true if this field's "MergeFromCodedStream" code needs the arena - // to be defined as a variable. - virtual bool MergeFromCodedStreamNeedsArena() const { return false; } - - // Generate lines to decode this field from a packed value, which will be - // placed inside the message's MergeFromCodedStream() method. - virtual void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) - const; - - // Generate lines to serialize this field, which are placed within the - // message's SerializeWithCachedSizes() method. - virtual void GenerateSerializeWithCachedSizes(io::Printer* printer) const = 0; - - // Generate lines to serialize this field directly to the array "target", - // which are placed within the message's SerializeWithCachedSizesToArray() - // method. This must also advance "target" past the written bytes. - virtual void GenerateSerializeWithCachedSizesToArray( - io::Printer* printer) const = 0; - - // Generate lines to compute the serialized size of this field, which - // are placed in the message's ByteSize() method. - virtual void GenerateByteSize(io::Printer* printer) const = 0; - - // Any tags about field layout decisions (such as inlining) to embed in the - // offset. - virtual uint32 CalculateFieldTag() const { return 0; } - virtual bool IsInlined() const { return false; } - - protected: - const Options& options_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); -}; - -// Convenience class which constructs FieldGenerators for a Descriptor. -class FieldGeneratorMap { - public: - FieldGeneratorMap(const Descriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer); - ~FieldGeneratorMap(); - - const FieldGenerator& get(const FieldDescriptor* field) const; - - private: - const Descriptor* descriptor_; - const Options& options_; - std::vector> field_generators_; - - static FieldGenerator* MakeGenerator(const FieldDescriptor* field, - const Options& options, - SCCAnalyzer* scc_analyzer); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_file.cc b/windows/include/google/protobuf/compiler/cpp/cpp_file.cc deleted file mode 100644 index 42525687d..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_file.cc +++ /dev/null @@ -1,1411 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options) - : file_(file), - options_(options), - scc_analyzer_(options), - enum_generators_owner_( - new std::unique_ptr[file->enum_type_count()]), - service_generators_owner_( - new std::unique_ptr[file->service_count()]), - extension_generators_owner_( - new std::unique_ptr[file->extension_count()]) { - std::vector msgs = FlattenMessagesInFile(file); - for (int i = 0; i < msgs.size(); i++) { - // Deleted in destructor - MessageGenerator* msg_gen = - new MessageGenerator(msgs[i], i, options, &scc_analyzer_); - message_generators_.push_back(msg_gen); - msg_gen->AddGenerators(&enum_generators_, &extension_generators_); - } - - for (int i = 0; i < file->enum_type_count(); i++) { - enum_generators_owner_[i].reset( - new EnumGenerator(file->enum_type(i), options)); - enum_generators_.push_back(enum_generators_owner_[i].get()); - } - - for (int i = 0; i < file->service_count(); i++) { - service_generators_owner_[i].reset( - new ServiceGenerator(file->service(i), options)); - service_generators_.push_back(service_generators_owner_[i].get()); - } - if (HasGenericServices(file_, options_)) { - for (int i = 0; i < service_generators_.size(); i++) { - service_generators_[i]->index_in_metadata_ = i; - } - } - - for (int i = 0; i < file->extension_count(); i++) { - extension_generators_owner_[i].reset( - new ExtensionGenerator(file->extension(i), options)); - extension_generators_.push_back(extension_generators_owner_[i].get()); - } - - - package_parts_ = Split(file_->package(), ".", true); -} - -FileGenerator::~FileGenerator() { - for (int i = 0; i < message_generators_.size(); i++) { - delete message_generators_[i]; - } -} - -void FileGenerator::GenerateMacroUndefs(io::Printer* printer) { - // Only do this for protobuf's own types. There are some google3 protos using - // macros as field names and the generated code compiles after the macro - // expansion. Undefing these macros actually breaks such code. - if (file_->name() != "google/protobuf/compiler/plugin.proto") { - return; - } - std::vector names_to_undef; - std::vector fields; - ListAllFields(file_, &fields); - for (int i = 0; i < fields.size(); i++) { - const string& name = fields[i]->name(); - static const char* kMacroNames[] = {"major", "minor"}; - for (int i = 0; i < GOOGLE_ARRAYSIZE(kMacroNames); ++i) { - if (name == kMacroNames[i]) { - names_to_undef.push_back(name); - break; - } - } - } - for (int i = 0; i < names_to_undef.size(); ++i) { - printer->Print( - "#ifdef $name$\n" - "#undef $name$\n" - "#endif\n", - "name", names_to_undef[i]); - } -} - -void FileGenerator::GenerateHeader(io::Printer* printer) { - printer->Print( - "// @@protoc_insertion_point(includes)\n"); - - printer->Print("#define PROTOBUF_INTERNAL_EXPORT_$filename$ $export$\n", - "filename", FileLevelNamespace(file_), - "export", options_.dllexport_decl); - GenerateMacroUndefs(printer); - - GenerateGlobalStateFunctionDeclarations(printer); - - GenerateForwardDeclarations(printer); - - { - NamespaceOpener ns(Namespace(file_), printer); - - printer->Print("\n"); - - GenerateEnumDefinitions(printer); - - printer->Print(kThickSeparator); - printer->Print("\n"); - - GenerateMessageDefinitions(printer); - - printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); - - GenerateServiceDefinitions(printer); - - GenerateExtensionIdentifiers(printer); - - printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); - - GenerateInlineFunctionDefinitions(printer); - - printer->Print( - "\n" - "// @@protoc_insertion_point(namespace_scope)\n" - "\n"); - } - - // We need to specialize some templates in the ::google::protobuf namespace: - GenerateProto2NamespaceEnumSpecializations(printer); - - printer->Print( - "\n" - "// @@protoc_insertion_point(global_scope)\n" - "\n"); -} - -void FileGenerator::GenerateProtoHeader(io::Printer* printer, - const string& info_path) { - if (!options_.proto_h) { - return; - } - - string filename_identifier = FilenameIdentifier(file_->name()); - GenerateTopHeaderGuard(printer, filename_identifier); - - - GenerateLibraryIncludes(printer); - - for (int i = 0; i < file_->public_dependency_count(); i++) { - const FileDescriptor* dep = file_->public_dependency(i); - const char* extension = ".proto.h"; - string dependency = StripProto(dep->name()) + extension; - printer->Print( - "#include \"$dependency$\" // IWYU pragma: export\n", - "dependency", dependency); - } - - GenerateMetadataPragma(printer, info_path); - - GenerateHeader(printer); - - GenerateBottomHeaderGuard(printer, filename_identifier); -} - -void FileGenerator::GeneratePBHeader(io::Printer* printer, - const string& info_path) { - string filename_identifier = - FilenameIdentifier(file_->name() + (options_.proto_h ? ".pb.h" : "")); - GenerateTopHeaderGuard(printer, filename_identifier); - - if (options_.proto_h) { - string target_basename = StripProto(file_->name()); - printer->Print("#include \"$basename$.proto.h\" // IWYU pragma: export\n", - "basename", target_basename); - } else { - GenerateLibraryIncludes(printer); - } - - GenerateDependencyIncludes(printer); - GenerateMetadataPragma(printer, info_path); - - if (!options_.proto_h) { - GenerateHeader(printer); - } else { - // This is unfortunately necessary for some plugins. I don't see why we - // need two of the same insertion points. - // TODO(gerbens) remove this. - printer->Print( - "// @@protoc_insertion_point(includes)\n"); - { - NamespaceOpener ns(Namespace(file_), printer); - printer->Print( - "\n" - "// @@protoc_insertion_point(namespace_scope)\n"); - } - printer->Print( - "\n" - "// @@protoc_insertion_point(global_scope)\n" - "\n"); - } - - GenerateBottomHeaderGuard(printer, filename_identifier); -} - -void FileGenerator::GenerateSourceIncludes(io::Printer* printer) { - string target_basename = StripProto(file_->name()); - const bool use_system_include = IsWellKnownMessage(file_); - - string header = target_basename + (options_.proto_h ? ".proto.h" : ".pb.h"); - printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n" - "#include $left$$header$$right$\n" - "\n" - "#include \n" // for swap() - "\n" - "#include \n" - "#include \n" - "#include \n" - "#include \n", - "filename", file_->name(), - "header", header, - "left", use_system_include ? "<" : "\"", - "right", use_system_include ? ">" : "\""); - - // Unknown fields implementation in lite mode uses StringOutputStream - if (!UseUnknownFieldSet(file_, options_) && !message_generators_.empty()) { - printer->Print( - "#include \n"); - } - - if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "#include \n" - "#include \n" - "#include \n" - "#include \n"); - } - - if (options_.proto_h) { - // Use the smaller .proto.h files. - for (int i = 0; i < file_->dependency_count(); i++) { - const FileDescriptor* dep = file_->dependency(i); - const char* extension = ".proto.h"; - string basename = StripProto(dep->name()); - string dependency = basename + extension; - printer->Print( - "#include \"$dependency$\"\n", - "dependency", dependency); - } - } - - // TODO(gerbens) Remove this when all code in google is using the same - // proto library. This is a temporary hack to force build errors if - // the proto library is compiled with GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS - // and is also linking internal proto2. This is to prevent regressions while - // we work cleaning up the code base. After this is completed and we have - // one proto lib all code uses this should be removed. - printer->Print( - "// This is a temporary google only hack\n" - "#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n" - "#include \"third_party/protobuf/version.h\"\n" - "#endif\n"); - - printer->Print( - "// @@protoc_insertion_point(includes)\n"); -} - -void FileGenerator::GenerateSourceDefaultInstance(int idx, - io::Printer* printer) { - printer->Print( - "class $classname$DefaultTypeInternal {\n" - " public:\n" - " ::google::protobuf::internal::ExplicitlyConstructed<$classname$>\n" - " _instance;\n", - "classname", message_generators_[idx]->classname_); - printer->Indent(); - message_generators_[idx]->GenerateExtraDefaultFields(printer); - printer->Outdent(); - printer->Print("} _$classname$_default_instance_;\n", "classname", - message_generators_[idx]->classname_); -} - -namespace { - -// Generates weak symbol declarations for types that are to be considered weakly -// referenced. -void GenerateInternalForwardDeclarations( - const std::vector& fields, const Options& options, - SCCAnalyzer* scc_analyzer, io::Printer* printer) { - // To ensure determinism and minimize the number of namespace statements, - // we output the forward declarations sorted on namespace and type / function - // name. - std::set > messages; - std::set > sccs; - std::set > inits; - for (int i = 0; i < fields.size(); ++i) { - const FieldDescriptor* field = fields[i]; - const Descriptor* msg = field->message_type(); - if (msg == nullptr) continue; - bool is_weak = IsImplicitWeakField(field, options, scc_analyzer); - string flns = FileLevelNamespace(msg); - auto scc = scc_analyzer->GetSCC(msg); - string repr = ClassName(scc->GetRepresentative()); - string weak_attr; - if (is_weak) { - inits.insert(std::make_pair(flns, "AddDescriptors")); - messages.insert(std::make_pair(Namespace(msg), ClassName(msg))); - weak_attr = " __attribute__((weak))"; - } - string dllexport = "PROTOBUF_INTERNAL_EXPORT_" + FileLevelNamespace(msg); - sccs.insert(std::make_pair(flns, "extern " + dllexport + weak_attr + - " ::google::protobuf::internal::SCCInfo<" + - SimpleItoa(scc->children.size()) + - "> scc_info_" + repr + ";\n")); - } - - printer->Print("\n"); - NamespaceOpener ns(printer); - for (std::set >::const_iterator it = - messages.begin(); - it != messages.end(); ++it) { - ns.ChangeTo(it->first); - printer->Print( - "extern __attribute__((weak)) $classname$DefaultTypeInternal " - "_$classname$_default_instance_;\n", - "classname", it->second); - } - for (std::set >::const_iterator it = inits.begin(); - it != inits.end(); ++it) { - ns.ChangeTo(it->first); - printer->Print("void $name$() __attribute__((weak));\n", - "name", it->second); - } - for (const auto& p : sccs) { - ns.ChangeTo(p.first); - printer->Print(p.second.c_str()); - } -} - -} // namespace - -void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) { - GenerateSourceIncludes(printer); - - // Generate weak declarations. We do this for the whole strongly-connected - // component (SCC), because we have a single InitDefaults* function for the - // SCC. - std::vector fields; - for (const Descriptor* message : - scc_analyzer_.GetSCC(message_generators_[idx]->descriptor_) - ->descriptors) { - ListAllFields(message, &fields); - } - GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_, - printer); - - if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) { - NamespaceOpener ns(FileLevelNamespace(file_), printer); - GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer); - } - - { // package namespace - NamespaceOpener ns(Namespace(file_), printer); - - // Define default instances - GenerateSourceDefaultInstance(idx, printer); - if (options_.lite_implicit_weak_fields) { - printer->Print("void $classname$_ReferenceStrong() {}\n", "classname", - message_generators_[idx]->classname_); - } - - // Generate classes. - printer->Print("\n"); - message_generators_[idx]->GenerateClassMethods(printer); - - printer->Print( - "\n" - "// @@protoc_insertion_point(namespace_scope)\n"); - } // end package namespace - - printer->Print( - "namespace google {\nnamespace protobuf {\n"); - message_generators_[idx]->GenerateSourceInProto2Namespace(printer); - printer->Print( - "} // namespace protobuf\n} // namespace google\n"); - - printer->Print( - "\n" - "// @@protoc_insertion_point(global_scope)\n"); -} - -void FileGenerator::GenerateGlobalSource(io::Printer* printer) { - GenerateSourceIncludes(printer); - - { - NamespaceOpener ns(FileLevelNamespace(file_), printer); - GenerateTables(printer); - - // Define the code to initialize reflection. This code uses a global - // constructor to register reflection data with the runtime pre-main. - if (HasDescriptorMethods(file_, options_)) { - GenerateReflectionInitializationCode(printer); - } - } - - NamespaceOpener ns(Namespace(file_), printer); - - // Generate enums. - for (int i = 0; i < enum_generators_.size(); i++) { - enum_generators_[i]->GenerateMethods(i, printer); - } - - // Define extensions. - for (int i = 0; i < extension_generators_.size(); i++) { - extension_generators_[i]->GenerateDefinition(printer); - } - - if (HasGenericServices(file_, options_)) { - // Generate services. - for (int i = 0; i < service_generators_.size(); i++) { - if (i == 0) printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); - service_generators_[i]->GenerateImplementation(printer); - } - } -} - -void FileGenerator::GenerateSource(io::Printer* printer) { - GenerateSourceIncludes(printer); - std::vector fields; - ListAllFields(file_, &fields); - GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_, - printer); - - { - NamespaceOpener ns(Namespace(file_), printer); - - // Define default instances - for (int i = 0; i < message_generators_.size(); i++) { - GenerateSourceDefaultInstance(i, printer); - if (options_.lite_implicit_weak_fields) { - printer->Print("void $classname$_ReferenceStrong() {}\n", "classname", - message_generators_[i]->classname_); - } - } - } - - { - NamespaceOpener ns(FileLevelNamespace(file_), printer); - GenerateTables(printer); - - // Now generate the InitDefaults for each SCC. - for (int i = 0; i < message_generators_.size(); i++) { - if (IsSCCRepresentative(message_generators_[i]->descriptor_)) { - GenerateInitForSCC(GetSCC(message_generators_[i]->descriptor_), - printer); - } - } - - printer->Print("void InitDefaults() {\n"); - for (int i = 0; i < message_generators_.size(); i++) { - if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue; - string scc_name = ClassName(message_generators_[i]->descriptor_); - printer->Print( - " ::google::protobuf::internal::InitSCC(&scc_info_$scc_name$.base);\n", - "scc_name", scc_name); - } - printer->Print("}\n\n"); - - // Define the code to initialize reflection. This code uses a global - // constructor to register reflection data with the runtime pre-main. - if (HasDescriptorMethods(file_, options_)) { - GenerateReflectionInitializationCode(printer); - } - } - - - { - NamespaceOpener ns(Namespace(file_), printer); - - // Actually implement the protos - - // Generate enums. - for (int i = 0; i < enum_generators_.size(); i++) { - enum_generators_[i]->GenerateMethods(i, printer); - } - - // Generate classes. - for (int i = 0; i < message_generators_.size(); i++) { - printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); - message_generators_[i]->GenerateClassMethods(printer); - } - - if (HasGenericServices(file_, options_)) { - // Generate services. - for (int i = 0; i < service_generators_.size(); i++) { - if (i == 0) printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); - service_generators_[i]->GenerateImplementation(printer); - } - } - - // Define extensions. - for (int i = 0; i < extension_generators_.size(); i++) { - extension_generators_[i]->GenerateDefinition(printer); - } - - printer->Print( - "\n" - "// @@protoc_insertion_point(namespace_scope)\n"); - } - - printer->Print( - "namespace google {\nnamespace protobuf {\n"); - for (int i = 0; i < message_generators_.size(); i++) { - message_generators_[i]->GenerateSourceInProto2Namespace(printer); - } - printer->Print( - "} // namespace protobuf\n} // namespace google\n"); - - printer->Print( - "\n" - "// @@protoc_insertion_point(global_scope)\n"); -} - -class FileGenerator::ForwardDeclarations { - public: - ~ForwardDeclarations() { - for (std::map::iterator - it = namespaces_.begin(), - end = namespaces_.end(); - it != end; ++it) { - delete it->second; - } - namespaces_.clear(); - } - - ForwardDeclarations* AddOrGetNamespace(const string& ns_name) { - ForwardDeclarations*& ns = namespaces_[ns_name]; - if (ns == nullptr) { - ns = new ForwardDeclarations; - } - return ns; - } - - std::map& classes() { return classes_; } - std::map& enums() { return enums_; } - - void PrintForwardDeclarations(io::Printer* printer, - const Options& options) const { - PrintNestedDeclarations(printer, options); - PrintTopLevelDeclarations(printer, options); - } - - - private: - void PrintNestedDeclarations(io::Printer* printer, - const Options& options) const { - PrintDeclarationsInsideNamespace(printer, options); - for (std::map::const_iterator - it = namespaces_.begin(), - end = namespaces_.end(); - it != end; ++it) { - printer->Print("namespace $nsname$ {\n", - "nsname", it->first); - it->second->PrintNestedDeclarations(printer, options); - printer->Print("} // namespace $nsname$\n", - "nsname", it->first); - } - } - - void PrintTopLevelDeclarations(io::Printer* printer, - const Options& options) const { - PrintDeclarationsOutsideNamespace(printer, options); - for (std::map::const_iterator - it = namespaces_.begin(), - end = namespaces_.end(); - it != end; ++it) { - it->second->PrintTopLevelDeclarations(printer, options); - } - } - - void PrintDeclarationsInsideNamespace(io::Printer* printer, - const Options& options) const { - for (std::map::const_iterator - it = enums_.begin(), - end = enums_.end(); - it != end; ++it) { - printer->Print("enum $enumname$ : int;\n", "enumname", it->first); - printer->Annotate("enumname", it->second); - printer->Print("bool $enumname$_IsValid(int value);\n", "enumname", - it->first); - } - for (std::map::const_iterator - it = classes_.begin(), - end = classes_.end(); - it != end; ++it) { - printer->Print("class $classname$;\n", "classname", it->first); - printer->Annotate("classname", it->second); - - printer->Print( - "class $classname$DefaultTypeInternal;\n" - "$dllexport_decl$" - "extern $classname$DefaultTypeInternal " - "_$classname$_default_instance_;\n", // NOLINT - "dllexport_decl", - options.dllexport_decl.empty() ? "" : options.dllexport_decl + " ", - "classname", - it->first); - if (options.lite_implicit_weak_fields) { - printer->Print("void $classname$_ReferenceStrong();\n", - "classname", it->first); - } - } - } - - void PrintDeclarationsOutsideNamespace(io::Printer* printer, - const Options& options) const { - if (classes_.size() == 0) return; - - printer->Print( - "namespace google {\nnamespace protobuf {\n"); - for (std::map::const_iterator - it = classes_.begin(), - end = classes_.end(); - it != end; ++it) { - const Descriptor* d = it->second; - printer->Print( - "template<> " - "$dllexport_decl$" - "$classname$* Arena::CreateMaybeMessage<$classname$>" - "(Arena*);\n", - "classname", QualifiedClassName(d), "dllexport_decl", - options.dllexport_decl.empty() ? "" : options.dllexport_decl + " "); - } - printer->Print( - "} // namespace protobuf\n} // namespace google\n"); - } - - std::map namespaces_; - std::map classes_; - std::map enums_; -}; - -void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) { - // AddDescriptors() is a file-level procedure which adds the encoded - // FileDescriptorProto for this .proto file to the global DescriptorPool for - // generated files (DescriptorPool::generated_pool()). It ordinarily runs at - // static initialization time, but is not used at all in LITE_RUNTIME mode. - // - // Its sibling, AssignDescriptors(), actually pulls the compiled - // FileDescriptor from the DescriptorPool and uses it to populate all of - // the global variables which store pointers to the descriptor objects. - // It also constructs the reflection objects. It is called the first time - // anyone calls descriptor() or GetReflection() on one of the types defined - // in the file. - - if (!message_generators_.empty()) { - printer->Print("::google::protobuf::Metadata file_level_metadata[$size$];\n", "size", - SimpleItoa(message_generators_.size())); - } - if (!enum_generators_.empty()) { - printer->Print( - "const ::google::protobuf::EnumDescriptor* " - "file_level_enum_descriptors[$size$];\n", - "size", SimpleItoa(enum_generators_.size())); - } - if (HasGenericServices(file_, options_) && file_->service_count() > 0) { - printer->Print( - "const ::google::protobuf::ServiceDescriptor* " - "file_level_service_descriptors[$size$];\n", - "size", SimpleItoa(file_->service_count())); - } - - if (!message_generators_.empty()) { - printer->Print( - "\n" - "const ::google::protobuf::uint32 TableStruct::offsets[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); - std::vector > pairs; - pairs.reserve(message_generators_.size()); - for (int i = 0; i < message_generators_.size(); i++) { - pairs.push_back(message_generators_[i]->GenerateOffsets(printer)); - } - printer->Outdent(); - printer->Print( - "};\n" - "static const ::google::protobuf::internal::MigrationSchema schemas[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); - { - int offset = 0; - for (int i = 0; i < message_generators_.size(); i++) { - message_generators_[i]->GenerateSchema(printer, offset, - pairs[i].second); - offset += pairs[i].first; - } - } - printer->Outdent(); - printer->Print( - "};\n" - "\nstatic " - "::google::protobuf::Message const * const file_default_instances[] = {\n"); - printer->Indent(); - for (int i = 0; i < message_generators_.size(); i++) { - const Descriptor* descriptor = message_generators_[i]->descriptor_; - printer->Print( - "reinterpret_cast(&$ns$::_$classname$_default_instance_),\n", - "classname", ClassName(descriptor), "ns", Namespace(descriptor)); - } - printer->Outdent(); - printer->Print( - "};\n" - "\n"); - } else { - // we still need these symbols to exist - printer->Print( - // MSVC doesn't like empty arrays, so we add a dummy. - "const ::google::protobuf::uint32 TableStruct::offsets[1] = {};\n" - "static const ::google::protobuf::internal::MigrationSchema* schemas = NULL;\n" - "static const ::google::protobuf::Message* const* " - "file_default_instances = NULL;\n" - "\n"); - } - - // --------------------------------------------------------------- - - // protobuf_AssignDescriptorsOnce(): The first time it is called, calls - // AssignDescriptors(). All later times, waits for the first call to - // complete and then returns. - printer->Print( - "void protobuf_AssignDescriptors() {\n" - // Make sure the file has found its way into the pool. If a descriptor - // is requested *during* static init then AddDescriptors() may not have - // been called yet, so we call it manually. Note that it's fine if - // AddDescriptors() is called multiple times. - " AddDescriptors();\n" - " AssignDescriptors(\n" - " \"$filename$\", schemas, file_default_instances, " - "TableStruct::offsets,\n" - " $metadata$, $enum_descriptors$, $service_descriptors$);\n", - "filename", file_->name(), "metadata", - !message_generators_.empty() ? "file_level_metadata" : "NULL", - "enum_descriptors", - !enum_generators_.empty() ? "file_level_enum_descriptors" : "NULL", - "service_descriptors", - HasGenericServices(file_, options_) && file_->service_count() > 0 - ? "file_level_service_descriptors" - : "NULL"); - printer->Print( - "}\n" - "\n" - "void protobuf_AssignDescriptorsOnce() {\n" - " static ::google::protobuf::internal::once_flag once;\n" - " ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);\n" - "}\n" - "\n", - "filename", file_->name(), "metadata", - !message_generators_.empty() ? "file_level_metadata" : "NULL", - "enum_descriptors", - !enum_generators_.empty() ? "file_level_enum_descriptors" : "NULL", - "service_descriptors", - HasGenericServices(file_, options_) && file_->service_count() > 0 - ? "file_level_service_descriptors" - : "NULL"); - - // Only here because of useless string reference that we don't want in - // protobuf_AssignDescriptorsOnce, because that is called from all the - // GetMetadata member methods. - printer->Print( - "void protobuf_RegisterTypes(const ::std::string&) " - "GOOGLE_PROTOBUF_ATTRIBUTE_COLD;\n" - "void protobuf_RegisterTypes(const ::std::string&) {\n" - " protobuf_AssignDescriptorsOnce();\n"); - printer->Indent(); - - // All normal messages can be done generically - if (!message_generators_.empty()) { - printer->Print( - "::google::protobuf::internal::RegisterAllTypes(file_level_metadata, $size$);\n", - "size", SimpleItoa(message_generators_.size())); - } - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - - // Now generate the AddDescriptors() function. - printer->Print( - "void AddDescriptorsImpl() {\n" - " InitDefaults();\n"); - printer->Indent(); - - // Embed the descriptor. We simply serialize the entire - // FileDescriptorProto - // and embed it as a string literal, which is parsed and built into real - // descriptors at initialization time. - FileDescriptorProto file_proto; - file_->CopyTo(&file_proto); - string file_data; - file_proto.SerializeToString(&file_data); - - printer->Print("static const char descriptor[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) " - "= {\n"); - printer->Indent(); - - if (file_data.size() > 65535) { - // Workaround for MSVC: "Error C1091: compiler limit: string exceeds 65535 - // bytes in length". Declare a static array of characters rather than use - // a string literal. Only write 25 bytes per line. - static const int kBytesPerLine = 25; - for (int i = 0; i < file_data.size();) { - for (int j = 0; j < kBytesPerLine && i < file_data.size(); ++i, ++j) { - printer->Print("'$char$', ", "char", - CEscape(file_data.substr(i, 1))); - } - printer->Print("\n"); - } - } else { - // Only write 40 bytes per line. - static const int kBytesPerLine = 40; - for (int i = 0; i < file_data.size(); i += kBytesPerLine) { - printer->Print(" \"$data$\"\n", "data", - EscapeTrigraphs(CEscape( - file_data.substr(i, kBytesPerLine)))); - } - } - - printer->Outdent(); - printer->Print("};\n"); - printer->Print( - "::google::protobuf::DescriptorPool::InternalAddGeneratedFile(\n" - " descriptor, $size$);\n", - "size", SimpleItoa(file_data.size())); - - // Call MessageFactory::InternalRegisterGeneratedFile(). - printer->Print( - "::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(\n" - " \"$filename$\", &protobuf_RegisterTypes);\n", - "filename", file_->name()); - - // Call the AddDescriptors() methods for all of our dependencies, to make - // sure they get added first. - for (int i = 0; i < file_->dependency_count(); i++) { - const FileDescriptor* dependency = file_->dependency(i); - // Print the namespace prefix for the dependency. - string file_namespace = FileLevelNamespace(dependency); - // Call its AddDescriptors function. - printer->Print("::$file_namespace$::AddDescriptors();\n", "file_namespace", - file_namespace); - } - - printer->Outdent(); - printer->Print( - "}\n" - "\n" - "void AddDescriptors() {\n" - " static ::google::protobuf::internal::once_flag once;\n" - " ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);\n" - "}\n"); - - printer->Print( - "// Force AddDescriptors() to be called at dynamic initialization " - "time.\n" - "struct StaticDescriptorInitializer {\n" - " StaticDescriptorInitializer() {\n" - " AddDescriptors();\n" - " }\n" - "} static_descriptor_initializer;\n"); -} - -void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) { - const string scc_name = ClassName(scc->GetRepresentative()); - // We use static and not anonymous namespace because symbol names are - // substantially shorter. - printer->Print( - "static void InitDefaults$scc_name$() {\n" - " GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n" - , // awkward comma due to macro - "scc_name", scc_name); - - printer->Indent(); - - - // First construct all the necessary default instances. - for (int i = 0; i < message_generators_.size(); i++) { - if (scc_analyzer_.GetSCC(message_generators_[i]->descriptor_) != scc) { - continue; - } - // TODO(gerbens) This requires this function to be friend. Remove - // the need for this. - message_generators_[i]->GenerateFieldDefaultInstances(printer); - printer->Print( - "{\n" - " void* ptr = &$ns$::_$classname$_default_instance_;\n" - " new (ptr) $ns$::$classname$();\n", - "ns", Namespace(message_generators_[i]->descriptor_), - "classname", ClassName(message_generators_[i]->descriptor_)); - if (!IsMapEntryMessage(message_generators_[i]->descriptor_)) { - printer->Print( - " ::google::protobuf::internal::OnShutdownDestroyMessage(ptr);\n"); - } - printer->Print("}\n"); - } - - // TODO(gerbens) make default instances be the same as normal instances. - // Default instances differ from normal instances because they have cross - // linked message fields. - for (int i = 0; i < message_generators_.size(); i++) { - if (scc_analyzer_.GetSCC(message_generators_[i]->descriptor_) != scc) { - continue; - } - printer->Print("$classname$::InitAsDefaultInstance();\n", "classname", - QualifiedClassName(message_generators_[i]->descriptor_)); - } - printer->Outdent(); - printer->Print("}\n\n"); - - printer->Print( - "$dllexport_decl$::google::protobuf::internal::SCCInfo<$size$> " - "scc_info_$scc_name$ =\n" - " {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), " - "$size$, InitDefaults$scc_name$}, {", - "size", SimpleItoa(scc->children.size()), "scc_name", - ClassName(scc->GetRepresentative()), "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); - for (const SCC* child : scc->children) { - auto repr = child->GetRepresentative(); - printer->Print("\n &$ns$::scc_info_$child$.base,", "ns", - FileLevelNamespace(repr), "child", ClassName(repr)); - } - printer->Print("}};\n\n"); -} - -void FileGenerator::GenerateTables(io::Printer* printer) { - if (options_.table_driven_parsing) { - // TODO(ckennelly): Gate this with the same options flag to enable - // table-driven parsing. - printer->Print( - "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField\n" - " const TableStruct::entries[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); - - std::vector entries; - size_t count = 0; - for (int i = 0; i < message_generators_.size(); i++) { - size_t value = message_generators_[i]->GenerateParseOffsets(printer); - entries.push_back(value); - count += value; - } - - // We need these arrays to exist, and MSVC does not like empty arrays. - if (count == 0) { - printer->Print("{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},\n"); - } - - printer->Outdent(); - printer->Print( - "};\n" - "\n" - "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField\n" - " const TableStruct::aux[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); - - std::vector aux_entries; - count = 0; - for (int i = 0; i < message_generators_.size(); i++) { - size_t value = message_generators_[i]->GenerateParseAuxTable(printer); - aux_entries.push_back(value); - count += value; - } - - if (count == 0) { - printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n"); - } - - printer->Outdent(); - printer->Print( - "};\n" - "PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const\n" - " TableStruct::schema[] " - "GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {\n"); - printer->Indent(); - - size_t offset = 0; - size_t aux_offset = 0; - for (int i = 0; i < message_generators_.size(); i++) { - message_generators_[i]->GenerateParseTable(printer, offset, aux_offset); - offset += entries[i]; - aux_offset += aux_entries[i]; - } - - if (message_generators_.empty()) { - printer->Print("{ NULL, NULL, 0, -1, -1, false },\n"); - } - - printer->Outdent(); - printer->Print( - "};\n" - "\n"); - } - - if (!message_generators_.empty() && options_.table_driven_serialization) { - printer->Print( - "const ::google::protobuf::internal::FieldMetadata TableStruct::field_metadata[] " - "= {\n"); - printer->Indent(); - std::vector field_metadata_offsets; - int idx = 0; - for (int i = 0; i < message_generators_.size(); i++) { - field_metadata_offsets.push_back(idx); - idx += message_generators_[i]->GenerateFieldMetadata(printer); - } - field_metadata_offsets.push_back(idx); - printer->Outdent(); - printer->Print( - "};\n" - "const ::google::protobuf::internal::SerializationTable " - "TableStruct::serialization_table[] = {\n"); - printer->Indent(); - // We rely on the order we layout the tables to match the order we - // calculate them with FlattenMessagesInFile, so we check here that - // these match exactly. - std::vector calculated_order = - FlattenMessagesInFile(file_); - GOOGLE_CHECK_EQ(calculated_order.size(), message_generators_.size()); - for (int i = 0; i < message_generators_.size(); i++) { - GOOGLE_CHECK_EQ(calculated_order[i], message_generators_[i]->descriptor_); - printer->Print( - "{$num_fields$, TableStruct::field_metadata + $index$},\n", - "classname", message_generators_[i]->classname_, "num_fields", - SimpleItoa(field_metadata_offsets[i + 1] - field_metadata_offsets[i]), - "index", SimpleItoa(field_metadata_offsets[i])); - } - printer->Outdent(); - printer->Print( - "};\n" - "\n"); - } -} - -void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) { - ForwardDeclarations decls; - FillForwardDeclarations(&decls); - decls.PrintForwardDeclarations(printer, options_); -} - -void FileGenerator::FillForwardDeclarations(ForwardDeclarations* decls) { - for (int i = 0; i < package_parts_.size(); i++) { - decls = decls->AddOrGetNamespace(package_parts_[i]); - } - // Generate enum definitions. - for (int i = 0; i < enum_generators_.size(); i++) { - enum_generators_[i]->FillForwardDeclaration(&decls->enums()); - } - // Generate forward declarations of classes. - for (int i = 0; i < message_generators_.size(); i++) { - message_generators_[i]->FillMessageForwardDeclarations( - &decls->classes()); - } -} - -void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer, - const string& filename_identifier) { - // Generate top of header. - printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n" - "#ifndef PROTOBUF_INCLUDED_$filename_identifier$\n" - "#define PROTOBUF_INCLUDED_$filename_identifier$\n" - "\n" - "#include \n", - "filename", file_->name(), "filename_identifier", filename_identifier); - printer->Print("\n"); -} - -void FileGenerator::GenerateBottomHeaderGuard( - io::Printer* printer, const string& filename_identifier) { - printer->Print( - "#endif // PROTOBUF_INCLUDED_$filename_identifier$\n", - "filename_identifier", filename_identifier); -} - -void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) { - if (UsingImplicitWeakFields(file_, options_)) { - printer->Print("#include \n"); - } - - printer->Print( - "#include \n" - "\n"); - - // Verify the protobuf library header version is compatible with the protoc - // version before going any further. - printer->Print( - "#if GOOGLE_PROTOBUF_VERSION < $min_header_version$\n" - "#error This file was generated by a newer version of protoc which is\n" - "#error incompatible with your Protocol Buffer headers. Please update\n" - "#error your headers.\n" - "#endif\n" - "#if $protoc_version$ < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION\n" - "#error This file was generated by an older version of protoc which is\n" - "#error incompatible with your Protocol Buffer headers. Please\n" - "#error regenerate this file with a newer version of protoc.\n" - "#endif\n" - "\n", - "min_header_version", - SimpleItoa(protobuf::internal::kMinHeaderVersionForProtoc), - "protoc_version", SimpleItoa(GOOGLE_PROTOBUF_VERSION)); - - // OK, it's now safe to #include other files. - printer->Print( - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n" - "#include \n"); - - - if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "#include \n"); - } else { - printer->Print( - "#include \n"); - } - - if (!message_generators_.empty()) { - if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "#include \n"); - } else { - printer->Print( - "#include \n"); - } - } - printer->Print( - "#include " - " // IWYU pragma: export\n" - "#include " - " // IWYU pragma: export\n"); - if (HasMapFields(file_)) { - printer->Print( - "#include " - " // IWYU pragma: export\n"); - if (HasDescriptorMethods(file_, options_)) { - printer->Print("#include \n"); - printer->Print("#include \n"); - } else { - printer->Print("#include \n"); - printer->Print("#include \n"); - } - } - - if (HasEnumDefinitions(file_)) { - if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "#include \n"); - } else { - printer->Print( - "#include \n"); - } - } - - if (HasGenericServices(file_, options_)) { - printer->Print( - "#include \n"); - } - - if (UseUnknownFieldSet(file_, options_) && !message_generators_.empty()) { - printer->Print( - "#include \n"); - } - - - if (IsAnyMessage(file_)) { - printer->Print( - "#include \n"); - } -} - -void FileGenerator::GenerateMetadataPragma(io::Printer* printer, - const string& info_path) { - if (!info_path.empty() && !options_.annotation_pragma_name.empty() && - !options_.annotation_guard_name.empty()) { - printer->Print( - "#ifdef $guard$\n" - "#pragma $pragma$ \"$info_path$\"\n" - "#endif // $guard$\n", - "guard", options_.annotation_guard_name, "pragma", - options_.annotation_pragma_name, "info_path", info_path); - } -} - -void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) { - std::set public_import_names; - for (int i = 0; i < file_->public_dependency_count(); i++) { - public_import_names.insert(file_->public_dependency(i)->name()); - } - - for (int i = 0; i < file_->dependency_count(); i++) { - const bool use_system_include = IsWellKnownMessage(file_->dependency(i)); - const string& name = file_->dependency(i)->name(); - bool public_import = (public_import_names.count(name) != 0); - string basename = StripProto(name); - - - printer->Print( - "#include $left$$dependency$.pb.h$right$$iwyu$\n", - "dependency", basename, - "iwyu", (public_import) ? " // IWYU pragma: export" : "", - "left", use_system_include ? "<" : "\"", - "right", use_system_include ? ">" : "\""); - } -} - -void FileGenerator::GenerateGlobalStateFunctionDeclarations( - io::Printer* printer) { -// Forward-declare the AddDescriptors, InitDefaults because these are called -// by .pb.cc files depending on this file. - printer->Print( - "\n" - "namespace $file_namespace$ {\n" - "// Internal implementation detail -- do not use these members.\n" - "struct $dllexport_decl$TableStruct {\n" - // These tables describe how to serialize and parse messages. Used - // for table driven code. - " static const ::google::protobuf::internal::ParseTableField entries[];\n" - " static const ::google::protobuf::internal::AuxillaryParseTableField aux[];\n" - " static const ::google::protobuf::internal::ParseTable schema[$num$];\n" - " static const ::google::protobuf::internal::FieldMetadata field_metadata[];\n" - " static const ::google::protobuf::internal::SerializationTable " - "serialization_table[];\n" - " static const ::google::protobuf::uint32 offsets[];\n" - "};\n", - "file_namespace", FileLevelNamespace(file_), "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ", - "num", SimpleItoa(std::max(size_t(1), message_generators_.size()))); - if (HasDescriptorMethods(file_, options_)) { - printer->Print( - "void $dllexport_decl$AddDescriptors();\n", "dllexport_decl", - options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " "); - } - printer->Print( - "} // namespace $file_namespace$\n", - "file_namespace", FileLevelNamespace(file_)); -} - -void FileGenerator::GenerateMessageDefinitions(io::Printer* printer) { - // Generate class definitions. - for (int i = 0; i < message_generators_.size(); i++) { - if (i > 0) { - printer->Print("\n"); - printer->Print(kThinSeparator); - printer->Print("\n"); - } - message_generators_[i]->GenerateClassDefinition(printer); - } -} - -void FileGenerator::GenerateEnumDefinitions(io::Printer* printer) { - // Generate enum definitions. - for (int i = 0; i < enum_generators_.size(); i++) { - enum_generators_[i]->GenerateDefinition(printer); - } -} - -void FileGenerator::GenerateServiceDefinitions(io::Printer* printer) { - if (HasGenericServices(file_, options_)) { - // Generate service definitions. - for (int i = 0; i < service_generators_.size(); i++) { - if (i > 0) { - printer->Print("\n"); - printer->Print(kThinSeparator); - printer->Print("\n"); - } - service_generators_[i]->GenerateDeclarations(printer); - } - - printer->Print("\n"); - printer->Print(kThickSeparator); - printer->Print("\n"); - } -} - -void FileGenerator::GenerateExtensionIdentifiers(io::Printer* printer) { - // Declare extension identifiers. These are in global scope and so only - // the global scope extensions. - for (int i = 0; i < file_->extension_count(); i++) { - extension_generators_owner_[i]->GenerateDeclaration(printer); - } -} - -void FileGenerator::GenerateInlineFunctionDefinitions(io::Printer* printer) { - // TODO(gerbens) remove pragmas when gcc is no longer used. Current version - // of gcc fires a bogus error when compiled with strict-aliasing. - printer->Print( - "#ifdef __GNUC__\n" - " #pragma GCC diagnostic push\n" - " #pragma GCC diagnostic ignored \"-Wstrict-aliasing\"\n" - "#endif // __GNUC__\n"); - // Generate class inline methods. - for (int i = 0; i < message_generators_.size(); i++) { - if (i > 0) { - printer->Print(kThinSeparator); - printer->Print("\n"); - } - message_generators_[i]->GenerateInlineMethods(printer); - } - printer->Print( - "#ifdef __GNUC__\n" - " #pragma GCC diagnostic pop\n" - "#endif // __GNUC__\n"); - - for (int i = 0; i < message_generators_.size(); i++) { - if (i > 0) { - printer->Print(kThinSeparator); - printer->Print("\n"); - } - } -} - -void FileGenerator::GenerateProto2NamespaceEnumSpecializations( - io::Printer* printer) { - // Emit GetEnumDescriptor specializations into google::protobuf namespace: - if (HasEnumDefinitions(file_)) { - printer->Print( - "\n" - "namespace google {\nnamespace protobuf {\n" - "\n"); - for (int i = 0; i < enum_generators_.size(); i++) { - enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer); - } - printer->Print( - "\n" - "} // namespace protobuf\n} // namespace google\n"); - } -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_file.h b/windows/include/google/protobuf/compiler/cpp/cpp_file.h index 94da9a145..e8816020d 100644 --- a/windows/include/google/protobuf/compiler/cpp/cpp_file.h +++ b/windows/include/google/protobuf/compiler/cpp/cpp_file.h @@ -44,23 +44,26 @@ #include #include #include +#include namespace google { namespace protobuf { - class FileDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } +class FileDescriptor; // descriptor.h +namespace io { +class Printer; // printer.h } +} // namespace protobuf +} // namespace google +namespace google { namespace protobuf { namespace compiler { namespace cpp { -class EnumGenerator; // enum.h -class MessageGenerator; // message.h -class ServiceGenerator; // service.h -class ExtensionGenerator; // extension.h +class EnumGenerator; // enum.h +class MessageGenerator; // message.h +class ServiceGenerator; // service.h +class ExtensionGenerator; // extension.h class FileGenerator { public: @@ -71,45 +74,67 @@ class FileGenerator { // Shared code between the two header generators below. void GenerateHeader(io::Printer* printer); - // info_path, if non-empty, should be the path (relative to printer's output) - // to the metadata file describing this proto header. - void GenerateProtoHeader(io::Printer* printer, - const string& info_path); - // info_path, if non-empty, should be the path (relative to printer's output) - // to the metadata file describing this PB header. - void GeneratePBHeader(io::Printer* printer, - const string& info_path); + // info_path, if non-empty, should be the path (relative to printer's + // output) to the metadata file describing this proto header. + void GenerateProtoHeader(io::Printer* printer, const std::string& info_path); + // info_path, if non-empty, should be the path (relative to printer's + // output) to the metadata file describing this PB header. + void GeneratePBHeader(io::Printer* printer, const std::string& info_path); void GenerateSource(io::Printer* printer); + // The following member functions are used when the lite_implicit_weak_fields + // option is set. In this mode the code is organized a bit differently to + // promote better linker stripping of unused code. In particular, we generate + // one .cc file per message, one .cc file per extension, and a main pb.cc file + // containing everything else. + int NumMessages() const { return message_generators_.size(); } - // Similar to GenerateSource but generates only one message + int NumExtensions() const { return extension_generators_.size(); } + // Generates the source file for one message. void GenerateSourceForMessage(int idx, io::Printer* printer); + // Generates the source file for one extension. + void GenerateSourceForExtension(int idx, io::Printer* printer); + // Generates a source file containing everything except messages and + // extensions. void GenerateGlobalSource(io::Printer* printer); private: // Internal type used by GenerateForwardDeclarations (defined in file.cc). class ForwardDeclarations; + struct CrossFileReferences; + void IncludeFile(const std::string& google3_name, io::Printer* printer) { + DoIncludeFile(google3_name, false, printer); + } + void IncludeFileAndExport(const std::string& google3_name, + io::Printer* printer) { + DoIncludeFile(google3_name, true, printer); + } + void DoIncludeFile(const std::string& google3_name, bool do_export, + io::Printer* printer); + + std::string CreateHeaderInclude(const std::string& basename, + const FileDescriptor* file); + void GetCrossFileReferencesForField(const FieldDescriptor* field, + CrossFileReferences* refs); + void GetCrossFileReferencesForFile(const FileDescriptor* file, + CrossFileReferences* refs); + void GenerateInternalForwardDeclarations(const CrossFileReferences& refs, + io::Printer* printer); void GenerateSourceIncludes(io::Printer* printer); void GenerateSourceDefaultInstance(int idx, io::Printer* printer); - void GenerateInitForSCC(const SCC* scc, io::Printer* printer); + void GenerateInitForSCC(const SCC* scc, const CrossFileReferences& refs, + io::Printer* printer); void GenerateTables(io::Printer* printer); void GenerateReflectionInitializationCode(io::Printer* printer); // For other imports, generates their forward-declarations. void GenerateForwardDeclarations(io::Printer* printer); - // Internal helper used by GenerateForwardDeclarations: fills 'decls' - // with all necessary forward-declarations for this file and its - // transient depednencies. - void FillForwardDeclarations(ForwardDeclarations* decls); - // Generates top or bottom of a header file. - void GenerateTopHeaderGuard(io::Printer* printer, - const string& filename_identifier); - void GenerateBottomHeaderGuard(io::Printer* printer, - const string& filename_identifier); + void GenerateTopHeaderGuard(io::Printer* printer, bool pb_h); + void GenerateBottomHeaderGuard(io::Printer* printer, bool pb_h); // Generates #include directives. void GenerateLibraryIncludes(io::Printer* printer); @@ -117,7 +142,8 @@ class FileGenerator { // Generate a pragma to pull in metadata using the given info_path (if // non-empty). info_path should be relative to printer's output. - void GenerateMetadataPragma(io::Printer* printer, const string& info_path); + void GenerateMetadataPragma(io::Printer* printer, + const std::string& info_path); // Generates a couple of different pieces before definitions: void GenerateGlobalStateFunctionDeclarations(io::Printer* printer); @@ -133,54 +159,43 @@ class FileGenerator { // Generates extension identifiers. void GenerateExtensionIdentifiers(io::Printer* printer); - // Generates inline function defintions. + // Generates inline function definitions. void GenerateInlineFunctionDefinitions(io::Printer* printer); void GenerateProto2NamespaceEnumSpecializations(io::Printer* printer); - // Sometimes the names we use in a .proto file happen to be defined as macros - // on some platforms (e.g., macro/minor used in plugin.proto are defined as - // macros in sys/types.h on FreeBSD and a few other platforms). To make the - // generated code compile on these platforms, we either have to undef the - // macro for these few platforms, or rename the field name for all platforms. - // Since these names are part of protobuf public API, renaming is generally - // a breaking change so we prefer the #undef approach. + // Sometimes the names we use in a .proto file happen to be defined as + // macros on some platforms (e.g., macro/minor used in plugin.proto are + // defined as macros in sys/types.h on FreeBSD and a few other platforms). + // To make the generated code compile on these platforms, we either have to + // undef the macro for these few platforms, or rename the field name for all + // platforms. Since these names are part of protobuf public API, renaming is + // generally a breaking change so we prefer the #undef approach. void GenerateMacroUndefs(io::Printer* printer); - bool IsSCCRepresentative(const Descriptor* d) { - return GetSCCRepresentative(d) == d; - } - const Descriptor* GetSCCRepresentative(const Descriptor* d) { - return GetSCC(d)->GetRepresentative(); - } - const SCC* GetSCC(const Descriptor* d) { - return scc_analyzer_.GetSCC(d); + bool IsDepWeak(const FileDescriptor* dep) const { + if (weak_deps_.count(dep) != 0) { + GOOGLE_CHECK(!options_.opensource_runtime); + return true; + } + return false; } + std::set weak_deps_; const FileDescriptor* file_; const Options options_; - SCCAnalyzer scc_analyzer_; + MessageSCCAnalyzer scc_analyzer_; + std::map variables_; // Contains the post-order walk of all the messages (and child messages) in // this file. If you need a pre-order walk just reverse iterate. - std::vector message_generators_; - std::vector enum_generators_; - std::vector service_generators_; - std::vector extension_generators_; - - // These members are just for owning (and thus proper deleting). - // Nested (enum/extension)_generators are owned by child messages. - std::unique_ptr []> enum_generators_owner_; - std::unique_ptr []> - service_generators_owner_; - std::unique_ptr []> - extension_generators_owner_; - - // E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}. - std::vector package_parts_; + std::vector> message_generators_; + std::vector> enum_generators_; + std::vector> service_generators_; + std::vector> extension_generators_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); }; @@ -188,6 +203,6 @@ class FileGenerator { } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_generator.cc b/windows/include/google/protobuf/compiler/cpp/cpp_generator.cc deleted file mode 100644 index 20bb8a1a7..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_generator.cc +++ /dev/null @@ -1,207 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -CppGenerator::CppGenerator() {} -CppGenerator::~CppGenerator() {} - -bool CppGenerator::Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* generator_context, - string* error) const { - std::vector > options; - ParseGeneratorParameter(parameter, &options); - - // ----------------------------------------------------------------- - // parse generator options - - // If the dllexport_decl option is passed to the compiler, we need to write - // it in front of every symbol that should be exported if this .proto is - // compiled into a Windows DLL. E.g., if the user invokes the protocol - // compiler as: - // protoc --cpp_out=dllexport_decl=FOO_EXPORT:outdir foo.proto - // then we'll define classes like this: - // class FOO_EXPORT Foo { - // ... - // } - // FOO_EXPORT is a macro which should expand to __declspec(dllexport) or - // __declspec(dllimport) depending on what is being compiled. - // - Options file_options; - for (int i = 0; i < options.size(); i++) { - if (options[i].first == "dllexport_decl") { - file_options.dllexport_decl = options[i].second; - } else if (options[i].first == "safe_boundary_check") { - file_options.safe_boundary_check = true; - } else if (options[i].first == "annotate_headers") { - file_options.annotate_headers = true; - } else if (options[i].first == "annotation_pragma_name") { - file_options.annotation_pragma_name = options[i].second; - } else if (options[i].first == "annotation_guard_name") { - file_options.annotation_guard_name = options[i].second; - } else if (options[i].first == "lite") { - file_options.enforce_lite = true; - } else if (options[i].first == "lite_implicit_weak_fields") { - file_options.lite_implicit_weak_fields = true; - if (!options[i].second.empty()) { - file_options.num_cc_files = strto32(options[i].second.c_str(), - NULL, 10); - } - } else if (options[i].first == "table_driven_parsing") { - file_options.table_driven_parsing = true; - } else if (options[i].first == "table_driven_serialization") { - file_options.table_driven_serialization = true; - } else { - *error = "Unknown generator option: " + options[i].first; - return false; - } - } - - // The safe_boundary_check option controls behavior for Google-internal - // protobuf APIs. - if (file_options.safe_boundary_check) { - *error = - "The safe_boundary_check option is not supported outside of Google."; - return false; - } - - // ----------------------------------------------------------------- - - - string basename = StripProto(file->name()); - - - FileGenerator file_generator(file, file_options); - - // Generate header(s). - if (file_options.proto_h) { - std::unique_ptr output( - generator_context->Open(basename + ".proto.h")); - GeneratedCodeInfo annotations; - io::AnnotationProtoCollector annotation_collector( - &annotations); - string info_path = basename + ".proto.h.meta"; - io::Printer printer(output.get(), '$', file_options.annotate_headers - ? &annotation_collector - : NULL); - file_generator.GenerateProtoHeader( - &printer, file_options.annotate_headers ? info_path : ""); - if (file_options.annotate_headers) { - std::unique_ptr info_output( - generator_context->Open(info_path)); - annotations.SerializeToZeroCopyStream(info_output.get()); - } - } - - { - std::unique_ptr output( - generator_context->Open(basename + ".pb.h")); - GeneratedCodeInfo annotations; - io::AnnotationProtoCollector annotation_collector( - &annotations); - string info_path = basename + ".pb.h.meta"; - io::Printer printer(output.get(), '$', file_options.annotate_headers - ? &annotation_collector - : NULL); - file_generator.GeneratePBHeader( - &printer, file_options.annotate_headers ? info_path : ""); - if (file_options.annotate_headers) { - std::unique_ptr info_output( - generator_context->Open(info_path)); - annotations.SerializeToZeroCopyStream(info_output.get()); - } - } - - // Generate cc file(s). - if (UsingImplicitWeakFields(file, file_options)) { - { - // This is the global .cc file, containing enum/services/tables/reflection - std::unique_ptr output( - generator_context->Open(basename + ".pb.cc")); - io::Printer printer(output.get(), '$'); - file_generator.GenerateGlobalSource(&printer); - } - - int num_cc_files = file_generator.NumMessages(); - - // If we're using implicit weak fields then we allow the user to optionally - // specify how many files to generate, not counting the global pb.cc file. - // If we have more files than messages, then some files will be generated as - // empty placeholders. - if (file_options.num_cc_files > 0) { - GOOGLE_CHECK_LE(file_generator.NumMessages(), file_options.num_cc_files) - << "There must be at least as many numbered .cc files as messages."; - num_cc_files = file_options.num_cc_files; - } - for (int i = 0; i < num_cc_files; i++) { - // TODO(gerbens) Agree on naming scheme. - std::unique_ptr output( - generator_context->Open(basename + "." + SimpleItoa(i) + ".cc")); - io::Printer printer(output.get(), '$'); - if (i < file_generator.NumMessages()) { - file_generator.GenerateSourceForMessage(i, &printer); - } - } - } else { - std::unique_ptr output( - generator_context->Open(basename + ".pb.cc")); - io::Printer printer(output.get(), '$'); - file_generator.GenerateSource(&printer); - } - - return true; -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_generator.h b/windows/include/google/protobuf/compiler/cpp/cpp_generator.h index 3d517cf4a..97e848dc4 100644 --- a/windows/include/google/protobuf/compiler/cpp/cpp_generator.h +++ b/windows/include/google/protobuf/compiler/cpp/cpp_generator.h @@ -40,6 +40,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -49,24 +51,56 @@ namespace cpp { // header. If you create your own protocol compiler binary and you want // it to support C++ output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT CppGenerator : public CodeGenerator { +class PROTOC_EXPORT CppGenerator : public CodeGenerator { public: CppGenerator(); ~CppGenerator(); + enum class Runtime { + kGoogle3, // Use the internal google3 runtime. + kOpensource, // Use the open-source runtime. + + // Use the open-source runtime with google3 #include paths. We make these + // absolute to avoid ambiguity, so the runtime will be #included like: + // #include "third_party/protobuf/.../google/protobuf/message.h" + kOpensourceGoogle3 + }; + + void set_opensource_runtime(bool opensource) { + opensource_runtime_ = opensource; + } + + // If set to a non-empty string, generated code will do: + // #include "/google/protobuf/message.h" + // instead of: + // #include + // This has no effect if opensource_runtime = false. + void set_runtime_include_base(const std::string& base) { + runtime_include_base_ = base; + } + // implements CodeGenerator ---------------------------------------- - bool Generate(const FileDescriptor* file, - const string& parameter, + bool Generate(const FileDescriptor* file, const std::string& parameter, GeneratorContext* generator_context, - string* error) const; + std::string* error) const override; + + uint64_t GetSupportedFeatures() const override { + // We don't fully support this yet, but this is needed to unblock the tests, + // and we will have full support before the experimental flag is removed. + return FEATURE_PROTO3_OPTIONAL; + } private: + bool opensource_runtime_ = true; + std::string runtime_include_base_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CppGenerator); }; } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_helpers.cc b/windows/include/google/protobuf/compiler/cpp/cpp_helpers.cc deleted file mode 100644 index 163dac0aa..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_helpers.cc +++ /dev/null @@ -1,867 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - - - - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -namespace { - -static const char kAnyMessageName[] = "Any"; -static const char kAnyProtoFile[] = "google/protobuf/any.proto"; -static const char kGoogleProtobufPrefix[] = "google/protobuf/"; - -string DotsToUnderscores(const string& name) { - return StringReplace(name, ".", "_", true); -} - -string DotsToColons(const string& name) { - return StringReplace(name, ".", "::", true); -} - -const char* const kKeywordList[] = { - "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", - "bool", "break", "case", "catch", "char", "class", "compl", "const", - "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", - "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", - "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", - "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", - "operator", "or", "or_eq", "private", "protected", "public", "register", - "reinterpret_cast", "return", "short", "signed", "sizeof", "static", - "static_assert", "static_cast", "struct", "switch", "template", "this", - "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", - "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", - "while", "xor", "xor_eq" -}; - -hash_set MakeKeywordsMap() { - hash_set result; - for (int i = 0; i < GOOGLE_ARRAYSIZE(kKeywordList); i++) { - result.insert(kKeywordList[i]); - } - return result; -} - -hash_set kKeywords = MakeKeywordsMap(); - -// Returns whether the provided descriptor has an extension. This includes its -// nested types. -bool HasExtension(const Descriptor* descriptor) { - if (descriptor->extension_count() > 0) { - return true; - } - for (int i = 0; i < descriptor->nested_type_count(); ++i) { - if (HasExtension(descriptor->nested_type(i))) { - return true; - } - } - return false; -} - -// Encode [0..63] as 'A'-'Z', 'a'-'z', '0'-'9', '_' -char Base63Char(int value) { - GOOGLE_CHECK_GE(value, 0); - if (value < 26) return 'A' + value; - value -= 26; - if (value < 26) return 'a' + value; - value -= 26; - if (value < 10) return '0' + value; - GOOGLE_CHECK_EQ(value, 10); - return '_'; -} - -// Given a c identifier has 63 legal characters we can't implement base64 -// encoding. So we return the k least significant "digits" in base 63. -template -string Base63(I n, int k) { - string res; - while (k-- > 0) { - res += Base63Char(static_cast(n % 63)); - n /= 63; - } - return res; -} - -} // namespace - -string UnderscoresToCamelCase(const string& input, bool cap_next_letter) { - string result; - // Note: I distrust ctype.h due to locales. - for (int i = 0; i < input.size(); i++) { - if ('a' <= input[i] && input[i] <= 'z') { - if (cap_next_letter) { - result += input[i] + ('A' - 'a'); - } else { - result += input[i]; - } - cap_next_letter = false; - } else if ('A' <= input[i] && input[i] <= 'Z') { - // Capital letters are left as-is. - result += input[i]; - cap_next_letter = false; - } else if ('0' <= input[i] && input[i] <= '9') { - result += input[i]; - cap_next_letter = true; - } else { - cap_next_letter = true; - } - } - return result; -} - -const char kThickSeparator[] = - "// ===================================================================\n"; -const char kThinSeparator[] = - "// -------------------------------------------------------------------\n"; - -bool CanInitializeByZeroing(const FieldDescriptor* field) { - if (field->is_repeated() || field->is_extension()) return false; - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_ENUM: - return field->default_value_enum()->number() == 0; - case FieldDescriptor::CPPTYPE_INT32: - return field->default_value_int32() == 0; - case FieldDescriptor::CPPTYPE_INT64: - return field->default_value_int64() == 0; - case FieldDescriptor::CPPTYPE_UINT32: - return field->default_value_uint32() == 0; - case FieldDescriptor::CPPTYPE_UINT64: - return field->default_value_uint64() == 0; - case FieldDescriptor::CPPTYPE_FLOAT: - return field->default_value_float() == 0; - case FieldDescriptor::CPPTYPE_DOUBLE: - return field->default_value_double() == 0; - case FieldDescriptor::CPPTYPE_BOOL: - return field->default_value_bool() == false; - default: - return false; - } -} - -string ClassName(const Descriptor* descriptor) { - const Descriptor* parent = descriptor->containing_type(); - string res; - if (parent) res += ClassName(parent) + "_"; - res += descriptor->name(); - if (IsMapEntryMessage(descriptor)) res += "_DoNotUse"; - return res; -} - -string ClassName(const EnumDescriptor* enum_descriptor) { - if (enum_descriptor->containing_type() == NULL) { - return enum_descriptor->name(); - } else { - return ClassName(enum_descriptor->containing_type()) + "_" + - enum_descriptor->name(); - } -} - -string Namespace(const string& package) { - if (package.empty()) return ""; - return "::" + DotsToColons(package); -} - -string DefaultInstanceName(const Descriptor* descriptor) { - string prefix = descriptor->file()->package().empty() ? "" : "::"; - return prefix + DotsToColons(descriptor->file()->package()) + "::_" + - ClassName(descriptor, false) + "_default_instance_"; -} - -string ReferenceFunctionName(const Descriptor* descriptor) { - return QualifiedClassName(descriptor) + "_ReferenceStrong"; -} - -string SuperClassName(const Descriptor* descriptor, const Options& options) { - return HasDescriptorMethods(descriptor->file(), options) - ? "::google::protobuf::Message" - : "::google::protobuf::MessageLite"; -} - -string FieldName(const FieldDescriptor* field) { - string result = field->name(); - LowerString(&result); - if (kKeywords.count(result) > 0) { - result.append("_"); - } - return result; -} - -string EnumValueName(const EnumValueDescriptor* enum_value) { - string result = enum_value->name(); - if (kKeywords.count(result) > 0) { - result.append("_"); - } - return result; -} - -int EstimateAlignmentSize(const FieldDescriptor* field) { - if (field == NULL) return 0; - if (field->is_repeated()) return 8; - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_BOOL: - return 1; - - case FieldDescriptor::CPPTYPE_INT32: - case FieldDescriptor::CPPTYPE_UINT32: - case FieldDescriptor::CPPTYPE_ENUM: - case FieldDescriptor::CPPTYPE_FLOAT: - return 4; - - case FieldDescriptor::CPPTYPE_INT64: - case FieldDescriptor::CPPTYPE_UINT64: - case FieldDescriptor::CPPTYPE_DOUBLE: - case FieldDescriptor::CPPTYPE_STRING: - case FieldDescriptor::CPPTYPE_MESSAGE: - return 8; - } - GOOGLE_LOG(FATAL) << "Can't get here."; - return -1; // Make compiler happy. -} - -string FieldConstantName(const FieldDescriptor *field) { - string field_name = UnderscoresToCamelCase(field->name(), true); - string result = "k" + field_name + "FieldNumber"; - - if (!field->is_extension() && - field->containing_type()->FindFieldByCamelcaseName( - field->camelcase_name()) != field) { - // This field's camelcase name is not unique. As a hack, add the field - // number to the constant name. This makes the constant rather useless, - // but what can we do? - result += "_" + SimpleItoa(field->number()); - } - - return result; -} - -string FieldMessageTypeName(const FieldDescriptor* field) { - // Note: The Google-internal version of Protocol Buffers uses this function - // as a hook point for hacks to support legacy code. - return ClassName(field->message_type(), true); -} - -string StripProto(const string& filename) { - if (HasSuffixString(filename, ".protodevel")) { - return StripSuffixString(filename, ".protodevel"); - } else { - return StripSuffixString(filename, ".proto"); - } -} - -const char* PrimitiveTypeName(FieldDescriptor::CppType type) { - switch (type) { - case FieldDescriptor::CPPTYPE_INT32 : return "::google::protobuf::int32"; - case FieldDescriptor::CPPTYPE_INT64 : return "::google::protobuf::int64"; - case FieldDescriptor::CPPTYPE_UINT32 : return "::google::protobuf::uint32"; - case FieldDescriptor::CPPTYPE_UINT64 : return "::google::protobuf::uint64"; - case FieldDescriptor::CPPTYPE_DOUBLE : return "double"; - case FieldDescriptor::CPPTYPE_FLOAT : return "float"; - case FieldDescriptor::CPPTYPE_BOOL : return "bool"; - case FieldDescriptor::CPPTYPE_ENUM : return "int"; - case FieldDescriptor::CPPTYPE_STRING : return "::std::string"; - case FieldDescriptor::CPPTYPE_MESSAGE: return NULL; - - // No default because we want the compiler to complain if any new - // CppTypes are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -const char* DeclaredTypeMethodName(FieldDescriptor::Type type) { - switch (type) { - case FieldDescriptor::TYPE_INT32 : return "Int32"; - case FieldDescriptor::TYPE_INT64 : return "Int64"; - case FieldDescriptor::TYPE_UINT32 : return "UInt32"; - case FieldDescriptor::TYPE_UINT64 : return "UInt64"; - case FieldDescriptor::TYPE_SINT32 : return "SInt32"; - case FieldDescriptor::TYPE_SINT64 : return "SInt64"; - case FieldDescriptor::TYPE_FIXED32 : return "Fixed32"; - case FieldDescriptor::TYPE_FIXED64 : return "Fixed64"; - case FieldDescriptor::TYPE_SFIXED32: return "SFixed32"; - case FieldDescriptor::TYPE_SFIXED64: return "SFixed64"; - case FieldDescriptor::TYPE_FLOAT : return "Float"; - case FieldDescriptor::TYPE_DOUBLE : return "Double"; - - case FieldDescriptor::TYPE_BOOL : return "Bool"; - case FieldDescriptor::TYPE_ENUM : return "Enum"; - - case FieldDescriptor::TYPE_STRING : return "String"; - case FieldDescriptor::TYPE_BYTES : return "Bytes"; - case FieldDescriptor::TYPE_GROUP : return "Group"; - case FieldDescriptor::TYPE_MESSAGE : return "Message"; - - // No default because we want the compiler to complain if any new - // types are added. - } - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; -} - -string Int32ToString(int number) { - // gcc rejects the decimal form of kint32min. - if (number == kint32min) { - GOOGLE_COMPILE_ASSERT(kint32min == (~0x7fffffff), kint32min_value_error); - return "(~0x7fffffff)"; - } else { - return SimpleItoa(number); - } -} - -string Int64ToString(int64 number) { - // gcc rejects the decimal form of kint64min - if (number == kint64min) { - // Make sure we are in a 2's complement system. - GOOGLE_COMPILE_ASSERT(kint64min == GOOGLE_LONGLONG(~0x7fffffffffffffff), - kint64min_value_error); - return "GOOGLE_LONGLONG(~0x7fffffffffffffff)"; - } - return "GOOGLE_LONGLONG(" + SimpleItoa(number) + ")"; -} - -string DefaultValue(const FieldDescriptor* field) { - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - return Int32ToString(field->default_value_int32()); - case FieldDescriptor::CPPTYPE_UINT32: - return SimpleItoa(field->default_value_uint32()) + "u"; - case FieldDescriptor::CPPTYPE_INT64: - return Int64ToString(field->default_value_int64()); - case FieldDescriptor::CPPTYPE_UINT64: - return "GOOGLE_ULONGLONG(" + SimpleItoa(field->default_value_uint64())+ ")"; - case FieldDescriptor::CPPTYPE_DOUBLE: { - double value = field->default_value_double(); - if (value == std::numeric_limits::infinity()) { - return "::google::protobuf::internal::Infinity()"; - } else if (value == -std::numeric_limits::infinity()) { - return "-::google::protobuf::internal::Infinity()"; - } else if (value != value) { - return "::google::protobuf::internal::NaN()"; - } else { - return SimpleDtoa(value); - } - } - case FieldDescriptor::CPPTYPE_FLOAT: - { - float value = field->default_value_float(); - if (value == std::numeric_limits::infinity()) { - return "static_cast(::google::protobuf::internal::Infinity())"; - } else if (value == -std::numeric_limits::infinity()) { - return "static_cast(-::google::protobuf::internal::Infinity())"; - } else if (value != value) { - return "static_cast(::google::protobuf::internal::NaN())"; - } else { - string float_value = SimpleFtoa(value); - // If floating point value contains a period (.) or an exponent - // (either E or e), then append suffix 'f' to make it a float - // literal. - if (float_value.find_first_of(".eE") != string::npos) { - float_value.push_back('f'); - } - return float_value; - } - } - case FieldDescriptor::CPPTYPE_BOOL: - return field->default_value_bool() ? "true" : "false"; - case FieldDescriptor::CPPTYPE_ENUM: - // Lazy: Generate a static_cast because we don't have a helper function - // that constructs the full name of an enum value. - return strings::Substitute( - "static_cast< $0 >($1)", - ClassName(field->enum_type(), true), - Int32ToString(field->default_value_enum()->number())); - case FieldDescriptor::CPPTYPE_STRING: - return "\"" + EscapeTrigraphs( - CEscape(field->default_value_string())) + - "\""; - case FieldDescriptor::CPPTYPE_MESSAGE: - return "*" + FieldMessageTypeName(field) + - "::internal_default_instance()"; - } - // Can't actually get here; make compiler happy. (We could add a default - // case above but then we wouldn't get the nice compiler warning when a - // new type is added.) - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; -} - -// Convert a file name into a valid identifier. -string FilenameIdentifier(const string& filename) { - string result; - for (int i = 0; i < filename.size(); i++) { - if (ascii_isalnum(filename[i])) { - result.push_back(filename[i]); - } else { - // Not alphanumeric. To avoid any possibility of name conflicts we - // use the hex code for the character. - StrAppend(&result, "_", strings::Hex(static_cast(filename[i]))); - } - } - return result; -} - -string FileLevelNamespace(const string& filename) { - return "protobuf_" + FilenameIdentifier(filename); -} - -// Return the qualified C++ name for a file level symbol. -string QualifiedFileLevelSymbol(const string& package, const string& name) { - if (package.empty()) { - return StrCat("::", name); - } - return StrCat("::", DotsToColons(package), "::", name); -} - -// Escape C++ trigraphs by escaping question marks to \? -string EscapeTrigraphs(const string& to_escape) { - return StringReplace(to_escape, "?", "\\?", true); -} - -// Escaped function name to eliminate naming conflict. -string SafeFunctionName(const Descriptor* descriptor, - const FieldDescriptor* field, - const string& prefix) { - // Do not use FieldName() since it will escape keywords. - string name = field->name(); - LowerString(&name); - string function_name = prefix + name; - if (descriptor->FindFieldByName(function_name)) { - // Single underscore will also make it conflicting with the private data - // member. We use double underscore to escape function names. - function_name.append("__"); - } else if (kKeywords.count(name) > 0) { - // If the field name is a keyword, we append the underscore back to keep it - // consistent with other function names. - function_name.append("_"); - } - return function_name; -} - - -static bool HasMapFields(const Descriptor* descriptor) { - for (int i = 0; i < descriptor->field_count(); ++i) { - if (descriptor->field(i)->is_map()) { - return true; - } - } - for (int i = 0; i < descriptor->nested_type_count(); ++i) { - if (HasMapFields(descriptor->nested_type(i))) return true; - } - return false; -} - -bool HasMapFields(const FileDescriptor* file) { - for (int i = 0; i < file->message_type_count(); ++i) { - if (HasMapFields(file->message_type(i))) return true; - } - return false; -} - -static bool HasEnumDefinitions(const Descriptor* message_type) { - if (message_type->enum_type_count() > 0) return true; - for (int i = 0; i < message_type->nested_type_count(); ++i) { - if (HasEnumDefinitions(message_type->nested_type(i))) return true; - } - return false; -} - -bool HasEnumDefinitions(const FileDescriptor* file) { - if (file->enum_type_count() > 0) return true; - for (int i = 0; i < file->message_type_count(); ++i) { - if (HasEnumDefinitions(file->message_type(i))) return true; - } - return false; -} - -bool IsStringOrMessage(const FieldDescriptor* field) { - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - case FieldDescriptor::CPPTYPE_INT64: - case FieldDescriptor::CPPTYPE_UINT32: - case FieldDescriptor::CPPTYPE_UINT64: - case FieldDescriptor::CPPTYPE_DOUBLE: - case FieldDescriptor::CPPTYPE_FLOAT: - case FieldDescriptor::CPPTYPE_BOOL: - case FieldDescriptor::CPPTYPE_ENUM: - return false; - case FieldDescriptor::CPPTYPE_STRING: - case FieldDescriptor::CPPTYPE_MESSAGE: - return true; - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return false; -} - -FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field) { - GOOGLE_DCHECK(field->cpp_type() == FieldDescriptor::CPPTYPE_STRING); - // Open-source protobuf release only supports STRING ctype. - return FieldOptions::STRING; - -} - -bool IsAnyMessage(const FileDescriptor* descriptor) { - return descriptor->name() == kAnyProtoFile; -} - -bool IsAnyMessage(const Descriptor* descriptor) { - return descriptor->name() == kAnyMessageName && - descriptor->file()->name() == kAnyProtoFile; -} - -bool IsWellKnownMessage(const FileDescriptor* descriptor) { - return !descriptor->name().compare(0, 16, kGoogleProtobufPrefix); -} - -enum Utf8CheckMode { - STRICT = 0, // Parsing will fail if non UTF-8 data is in string fields. - VERIFY = 1, // Only log an error but parsing will succeed. - NONE = 2, // No UTF-8 check. -}; - -// Which level of UTF-8 enforcemant is placed on this file. -static Utf8CheckMode GetUtf8CheckMode(const FieldDescriptor* field, - const Options& options) { - if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) { - return STRICT; - } else if (GetOptimizeFor(field->file(), options) != - FileOptions::LITE_RUNTIME) { - return VERIFY; - } else { - return NONE; - } -} - -static void GenerateUtf8CheckCode(const FieldDescriptor* field, - const Options& options, bool for_parse, - const std::map& variables, - const char* parameters, - const char* strict_function, - const char* verify_function, - io::Printer* printer) { - switch (GetUtf8CheckMode(field, options)) { - case STRICT: { - if (for_parse) { - printer->Print("DO_("); - } - printer->Print( - "::google::protobuf::internal::WireFormatLite::$function$(\n", - "function", strict_function); - printer->Indent(); - printer->Print(variables, parameters); - if (for_parse) { - printer->Print("::google::protobuf::internal::WireFormatLite::PARSE,\n"); - } else { - printer->Print("::google::protobuf::internal::WireFormatLite::SERIALIZE,\n"); - } - printer->Print("\"$full_name$\")", "full_name", field->full_name()); - if (for_parse) { - printer->Print(")"); - } - printer->Print(";\n"); - printer->Outdent(); - break; - } - case VERIFY: { - printer->Print( - "::google::protobuf::internal::WireFormat::$function$(\n", - "function", verify_function); - printer->Indent(); - printer->Print(variables, parameters); - if (for_parse) { - printer->Print("::google::protobuf::internal::WireFormat::PARSE,\n"); - } else { - printer->Print("::google::protobuf::internal::WireFormat::SERIALIZE,\n"); - } - printer->Print("\"$full_name$\");\n", "full_name", field->full_name()); - printer->Outdent(); - break; - } - case NONE: - break; - } -} - -void GenerateUtf8CheckCodeForString(const FieldDescriptor* field, - const Options& options, bool for_parse, - const std::map& variables, - const char* parameters, - io::Printer* printer) { - GenerateUtf8CheckCode(field, options, for_parse, variables, parameters, - "VerifyUtf8String", "VerifyUTF8StringNamedField", - printer); -} - -void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field, - const Options& options, bool for_parse, - const std::map& variables, - const char* parameters, - io::Printer* printer) { - GenerateUtf8CheckCode(field, options, for_parse, variables, parameters, - "VerifyUtf8Cord", "VerifyUTF8CordNamedField", printer); -} - -namespace { - -void Flatten(const Descriptor* descriptor, - std::vector* flatten) { - for (int i = 0; i < descriptor->nested_type_count(); i++) - Flatten(descriptor->nested_type(i), flatten); - flatten->push_back(descriptor); -} - -} // namespace - -void FlattenMessagesInFile(const FileDescriptor* file, - std::vector* result) { - for (int i = 0; i < file->message_type_count(); i++) { - Flatten(file->message_type(i), result); - } -} - -bool HasWeakFields(const Descriptor* descriptor) { - return false; -} - -bool HasWeakFields(const FileDescriptor* file) { - return false; -} - -bool UsingImplicitWeakFields(const FileDescriptor* file, - const Options& options) { - return options.lite_implicit_weak_fields && - GetOptimizeFor(file, options) == FileOptions::LITE_RUNTIME; -} - -bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, - SCCAnalyzer* scc_analyzer) { - return UsingImplicitWeakFields(field->file(), options) && - field->type() == FieldDescriptor::TYPE_MESSAGE && - !field->is_required() && !field->is_map() && - field->containing_oneof() == NULL && - !IsWellKnownMessage(field->message_type()->file()) && - // We do not support implicit weak fields between messages in the same - // strongly-connected component. - scc_analyzer->GetSCC(field->containing_type()) != - scc_analyzer->GetSCC(field->message_type()); -} - -struct CompareDescriptors { - bool operator()(const Descriptor* a, const Descriptor* b) { - return a->full_name() < b->full_name(); - } -}; - -SCCAnalyzer::NodeData SCCAnalyzer::DFS(const Descriptor* descriptor) { - // Must not have visited already. - GOOGLE_DCHECK_EQ(cache_.count(descriptor), 0); - - // Mark visited by inserting in map. - NodeData& result = cache_[descriptor]; - // Initialize data structures. - result.index = result.lowlink = index_++; - stack_.push_back(descriptor); - - // Recurse the fields / nodes in graph - for (int i = 0; i < descriptor->field_count(); i++) { - const Descriptor* child = descriptor->field(i)->message_type(); - if (child) { - if (cache_.count(child) == 0) { - // unexplored node - NodeData child_data = DFS(child); - result.lowlink = std::min(result.lowlink, child_data.lowlink); - } else { - NodeData child_data = cache_[child]; - if (child_data.scc == NULL) { - // Still in the stack_ so we found a back edge - result.lowlink = std::min(result.lowlink, child_data.index); - } - } - } - } - if (result.index == result.lowlink) { - // This is the root of a strongly connected component - SCC* scc = CreateSCC(); - while (true) { - const Descriptor* scc_desc = stack_.back(); - scc->descriptors.push_back(scc_desc); - // Remove from stack - stack_.pop_back(); - cache_[scc_desc].scc = scc; - - if (scc_desc == descriptor) break; - } - - // The order of descriptors is random and depends how this SCC was - // discovered. In-order to ensure maximum stability we sort it by name. - std::sort(scc->descriptors.begin(), scc->descriptors.end(), - CompareDescriptors()); - AddChildren(scc); - } - return result; -} - -void SCCAnalyzer::AddChildren(SCC* scc) { - std::set seen; - for (int i = 0; i < scc->descriptors.size(); i++) { - const Descriptor* descriptor = scc->descriptors[i]; - for (int j = 0; j < descriptor->field_count(); j++) { - const Descriptor* child_msg = descriptor->field(j)->message_type(); - if (child_msg) { - const SCC* child = GetSCC(child_msg); - if (child == scc) continue; - if (seen.insert(child).second) { - scc->children.push_back(child); - } - } - } - } -} - -MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) { - if (analysis_cache_.count(scc)) return analysis_cache_[scc]; - MessageAnalysis result = MessageAnalysis(); - for (int i = 0; i < scc->descriptors.size(); i++) { - const Descriptor* descriptor = scc->descriptors[i]; - if (descriptor->extension_range_count() > 0) { - result.contains_extension = true; - } - for (int i = 0; i < descriptor->field_count(); i++) { - const FieldDescriptor* field = descriptor->field(i); - if (field->is_required()) { - result.contains_required = true; - } - switch (field->type()) { - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_BYTES: { - if (field->options().ctype() == FieldOptions::CORD) { - result.contains_cord = true; - } - break; - } - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_MESSAGE: { - const SCC* child = GetSCC(field->message_type()); - if (child != scc) { - MessageAnalysis analysis = GetSCCAnalysis(child); - result.contains_cord |= analysis.contains_cord; - result.contains_extension |= analysis.contains_extension; - if (!ShouldIgnoreRequiredFieldCheck(field, options_)) { - result.contains_required |= analysis.contains_required; - } - } else { - // This field points back into the same SCC hence the messages - // in the SCC are recursive. Note if SCC contains more than two - // nodes it has to be recursive, however this test also works for - // a single node that is recursive. - result.is_recursive = true; - } - break; - } - default: - break; - } - } - } - // We deliberately only insert the result here. After we contracted the SCC - // in the graph, the graph should be a DAG. Hence we shouldn't need to mark - // nodes visited as we can never return to them. By inserting them here - // we will go in an infinite loop if the SCC is not correct. - return analysis_cache_[scc] = result; -} - -void ListAllFields(const Descriptor* d, - std::vector* fields) { - // Collect sub messages - for (int i = 0; i < d->nested_type_count(); i++) { - ListAllFields(d->nested_type(i), fields); - } - // Collect message level extensions. - for (int i = 0; i < d->extension_count(); i++) { - fields->push_back(d->extension(i)); - } - // Add types of fields necessary - for (int i = 0; i < d->field_count(); i++) { - fields->push_back(d->field(i)); - } -} - -void ListAllFields(const FileDescriptor* d, - std::vector* fields) { - // Collect file level message. - for (int i = 0; i < d->message_type_count(); i++) { - ListAllFields(d->message_type(i), fields); - } - // Collect message level extensions. - for (int i = 0; i < d->extension_count(); i++) { - fields->push_back(d->extension(i)); - } -} - -void ListAllTypesForServices(const FileDescriptor* fd, - std::vector* types) { - for (int i = 0; i < fd->service_count(); i++) { - const ServiceDescriptor* sd = fd->service(i); - for (int j = 0; j < sd->method_count(); j++) { - const MethodDescriptor* method = sd->method(j); - types->push_back(method->input_type()); - types->push_back(method->output_type()); - } - } -} - - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_helpers.h b/windows/include/google/protobuf/compiler/cpp/cpp_helpers.h index eac651245..bd4f48bc8 100644 --- a/windows/include/google/protobuf/compiler/cpp/cpp_helpers.h +++ b/windows/include/google/protobuf/compiler/cpp/cpp_helpers.h @@ -35,48 +35,86 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__ #define GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__ +#include +#include +#include #include #include + #include +#include +#include #include #include #include #include +#include #include +// Must be included last. +#include + namespace google { namespace protobuf { namespace compiler { namespace cpp { +inline std::string ProtobufNamespace(const Options& /* options */) { + return "PROTOBUF_NAMESPACE_ID"; +} + +inline std::string MacroPrefix(const Options& /* options */) { + return "GOOGLE_PROTOBUF"; +} + +inline std::string DeprecatedAttribute(const Options& /* options */, + const FieldDescriptor* d) { + return d->options().deprecated() ? "PROTOBUF_DEPRECATED " : ""; +} + +inline std::string DeprecatedAttribute(const Options& /* options */, + const EnumValueDescriptor* d) { + return d->options().deprecated() ? "PROTOBUF_DEPRECATED_ENUM " : ""; +} + // Commonly-used separator comments. Thick is a line of '=', thin is a line // of '-'. extern const char kThickSeparator[]; extern const char kThinSeparator[]; +void SetCommonVars(const Options& options, + std::map* variables); + +void SetUnknownFieldsVariable(const Descriptor* descriptor, + const Options& options, + std::map* variables); + +bool GetBootstrapBasename(const Options& options, const std::string& basename, + std::string* bootstrap_basename); +bool MaybeBootstrap(const Options& options, GeneratorContext* generator_context, + bool bootstrap_flag, std::string* basename); +bool IsBootstrapProto(const Options& options, const FileDescriptor* file); // Name space of the proto file. This namespace is such that the string // "::some_name" is the correct fully qualified namespace. // This means if the package is empty the namespace is "", and otherwise // the namespace is "::foo::bar::...::baz" without trailing semi-colons. -string Namespace(const string& package); -inline string Namespace(const FileDescriptor* d) { - return Namespace(d->package()); -} -template -string Namespace(const Desc* d) { - return Namespace(d->file()); -} +std::string Namespace(const FileDescriptor* d, const Options& options); +std::string Namespace(const Descriptor* d, const Options& options); +std::string Namespace(const FieldDescriptor* d, const Options& options); +std::string Namespace(const EnumDescriptor* d, const Options& options); // Returns true if it's safe to reset "field" to zero. bool CanInitializeByZeroing(const FieldDescriptor* field); -string ClassName(const Descriptor* descriptor); -string ClassName(const EnumDescriptor* enum_descriptor); -template -string QualifiedClassName(const Desc* d) { - return Namespace(d) + "::" + ClassName(d); -} +std::string ClassName(const Descriptor* descriptor); +std::string ClassName(const EnumDescriptor* enum_descriptor); + +std::string QualifiedClassName(const Descriptor* d, const Options& options); +std::string QualifiedClassName(const EnumDescriptor* d, const Options& options); + +std::string QualifiedClassName(const Descriptor* d); +std::string QualifiedClassName(const EnumDescriptor* d); // DEPRECATED just use ClassName or QualifiedClassName, a boolean is very // unreadable at the callsite. @@ -88,33 +126,65 @@ string QualifiedClassName(const Desc* d) { // ::foo::bar::Baz_Qux // While the non-qualified version would be: // Baz_Qux -inline string ClassName(const Descriptor* descriptor, bool qualified) { - return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor); +inline std::string ClassName(const Descriptor* descriptor, bool qualified) { + return qualified ? QualifiedClassName(descriptor, Options()) + : ClassName(descriptor); } -inline string ClassName(const EnumDescriptor* descriptor, bool qualified) { - return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor); +inline std::string ClassName(const EnumDescriptor* descriptor, bool qualified) { + return qualified ? QualifiedClassName(descriptor, Options()) + : ClassName(descriptor); } +// Returns the extension name prefixed with the class name if nested but without +// the package name. +std::string ExtensionName(const FieldDescriptor* d); + +std::string QualifiedExtensionName(const FieldDescriptor* d, + const Options& options); +std::string QualifiedExtensionName(const FieldDescriptor* d); + +// Type name of default instance. +std::string DefaultInstanceType(const Descriptor* descriptor, + const Options& options); + +// Non-qualified name of the default_instance of this message. +std::string DefaultInstanceName(const Descriptor* descriptor, + const Options& options); + +// Non-qualified name of the default instance pointer. This is used only for +// implicit weak fields, where we need an extra indirection. +std::string DefaultInstancePtr(const Descriptor* descriptor, + const Options& options); + // Fully qualified name of the default_instance of this message. -string DefaultInstanceName(const Descriptor* descriptor); +std::string QualifiedDefaultInstanceName(const Descriptor* descriptor, + const Options& options); -// Returns the name of a no-op function that we can call to introduce a linker -// dependency on the given message type. This is used to implement implicit weak -// fields. -string ReferenceFunctionName(const Descriptor* descriptor); +// Fully qualified name of the default instance pointer. +std::string QualifiedDefaultInstancePtr(const Descriptor* descriptor, + const Options& options); + +// DescriptorTable variable name. +std::string DescriptorTableName(const FileDescriptor* file, + const Options& options); + +// When declaring symbol externs from another file, this macro will supply the +// dllexport needed for the target file, if any. +std::string FileDllExport(const FileDescriptor* file, const Options& options); // Name of the base class: google::protobuf::Message or google::protobuf::MessageLite. -string SuperClassName(const Descriptor* descriptor, const Options& options); +std::string SuperClassName(const Descriptor* descriptor, + const Options& options); + +// Adds an underscore if necessary to prevent conflicting with a keyword. +std::string ResolveKeyword(const std::string& name); // Get the (unqualified) name that should be used for this field in C++ code. // The name is coerced to lower-case to emulate proto1 behavior. People // should be using lowercase-with-underscores style for proto field names // anyway, so normally this just returns field->name(). -string FieldName(const FieldDescriptor* field); - -// Get the sanitized name that should be used for the given enum in C++ code. -string EnumValueName(const EnumValueDescriptor* enum_value); +std::string FieldName(const FieldDescriptor* field); // Returns an estimate of the compiler's alignment for the field. This // can't guarantee to be correct because the generated code could be compiled on @@ -124,75 +194,102 @@ int EstimateAlignmentSize(const FieldDescriptor* field); // Get the unqualified name that should be used for a field's field // number constant. -string FieldConstantName(const FieldDescriptor *field); +std::string FieldConstantName(const FieldDescriptor* field); // Returns the scope where the field was defined (for extensions, this is // different from the message type to which the field applies). inline const Descriptor* FieldScope(const FieldDescriptor* field) { - return field->is_extension() ? - field->extension_scope() : field->containing_type(); + return field->is_extension() ? field->extension_scope() + : field->containing_type(); } // Returns the fully-qualified type name field->message_type(). Usually this // is just ClassName(field->message_type(), true); -string FieldMessageTypeName(const FieldDescriptor* field); - -// Strips ".proto" or ".protodevel" from the end of a filename. -LIBPROTOC_EXPORT string StripProto(const string& filename); +std::string FieldMessageTypeName(const FieldDescriptor* field, + const Options& options); // Get the C++ type name for a primitive type (e.g. "double", "::google::protobuf::int32", etc.). -// Note: non-built-in type names will be qualified, meaning they will start -// with a ::. If you are using the type as a template parameter, you will -// need to insure there is a space between the < and the ::, because the -// ridiculous C++ standard defines "<:" to be a synonym for "[". const char* PrimitiveTypeName(FieldDescriptor::CppType type); +std::string PrimitiveTypeName(const Options& options, + FieldDescriptor::CppType type); // Get the declared type name in CamelCase format, as is used e.g. for the // methods of WireFormat. For example, TYPE_INT32 becomes "Int32". const char* DeclaredTypeMethodName(FieldDescriptor::Type type); // Return the code that evaluates to the number when compiled. -string Int32ToString(int number); - -// Return the code that evaluates to the number when compiled. -string Int64ToString(int64 number); +std::string Int32ToString(int number); // Get code that evaluates to the field's default value. -string DefaultValue(const FieldDescriptor* field); +std::string DefaultValue(const Options& options, const FieldDescriptor* field); + +// Compatibility function for callers outside proto2. +std::string DefaultValue(const FieldDescriptor* field); // Convert a file name into a valid identifier. -string FilenameIdentifier(const string& filename); +std::string FilenameIdentifier(const std::string& filename); -// For each .proto file generates a unique namespace. In this namespace global -// definitions are put to prevent collisions. -string FileLevelNamespace(const string& filename); -inline string FileLevelNamespace(const FileDescriptor* file) { - return FileLevelNamespace(file->name()); +// For each .proto file generates a unique name. To prevent collisions of +// symbols in the global namespace +std::string UniqueName(const std::string& name, const std::string& filename, + const Options& options); +inline std::string UniqueName(const std::string& name, const FileDescriptor* d, + const Options& options) { + return UniqueName(name, d->name(), options); } -inline string FileLevelNamespace(const Descriptor* d) { - return FileLevelNamespace(d->file()); +inline std::string UniqueName(const std::string& name, const Descriptor* d, + const Options& options) { + return UniqueName(name, d->file(), options); +} +inline std::string UniqueName(const std::string& name, const EnumDescriptor* d, + const Options& options) { + return UniqueName(name, d->file(), options); +} +inline std::string UniqueName(const std::string& name, + const ServiceDescriptor* d, + const Options& options) { + return UniqueName(name, d->file(), options); +} + +// Versions for call sites that only support the internal runtime (like proto1 +// support). +inline Options InternalRuntimeOptions() { + Options options; + options.opensource_runtime = false; + return options; +} +inline std::string UniqueName(const std::string& name, + const std::string& filename) { + return UniqueName(name, filename, InternalRuntimeOptions()); +} +inline std::string UniqueName(const std::string& name, + const FileDescriptor* d) { + return UniqueName(name, d->name(), InternalRuntimeOptions()); +} +inline std::string UniqueName(const std::string& name, const Descriptor* d) { + return UniqueName(name, d->file(), InternalRuntimeOptions()); +} +inline std::string UniqueName(const std::string& name, + const EnumDescriptor* d) { + return UniqueName(name, d->file(), InternalRuntimeOptions()); +} +inline std::string UniqueName(const std::string& name, + const ServiceDescriptor* d) { + return UniqueName(name, d->file(), InternalRuntimeOptions()); } // Return the qualified C++ name for a file level symbol. -string QualifiedFileLevelSymbol(const string& package, const string& name); +std::string QualifiedFileLevelSymbol(const FileDescriptor* file, + const std::string& name, + const Options& options); // Escape C++ trigraphs by escaping question marks to \? -string EscapeTrigraphs(const string& to_escape); +std::string EscapeTrigraphs(const std::string& to_escape); // Escaped function name to eliminate naming conflict. -string SafeFunctionName(const Descriptor* descriptor, - const FieldDescriptor* field, - const string& prefix); - -// Returns true if unknown fields are always preserved after parsing. -inline bool AlwaysPreserveUnknownFields(const FileDescriptor* file) { - return file->syntax() != FileDescriptor::SYNTAX_PROTO3; -} - -// Returns true if unknown fields are preserved after parsing. -inline bool AlwaysPreserveUnknownFields(const Descriptor* message) { - return AlwaysPreserveUnknownFields(message->file()); -} +std::string SafeFunctionName(const Descriptor* descriptor, + const FieldDescriptor* field, + const std::string& prefix); // Returns true if generated messages have public unknown fields accessors inline bool PublicUnknownFieldsAccessors(const Descriptor* message) { @@ -200,8 +297,8 @@ inline bool PublicUnknownFieldsAccessors(const Descriptor* message) { } // Returns the optimize mode for , respecting . -::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor( - const FileDescriptor* file, const Options& options); +FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file, + const Options& options); // Determines whether unknown fields will be stored in an UnknownFieldSet or // a string. @@ -210,6 +307,87 @@ inline bool UseUnknownFieldSet(const FileDescriptor* file, return GetOptimizeFor(file, options) != FileOptions::LITE_RUNTIME; } +inline bool IsWeak(const FieldDescriptor* field, const Options& options) { + if (field->options().weak()) { + GOOGLE_CHECK(!options.opensource_runtime); + return true; + } + return false; +} + +bool IsStringInlined(const FieldDescriptor* descriptor, const Options& options); + +// For a string field, returns the effective ctype. If the actual ctype is +// not supported, returns the default of STRING. +FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field, + const Options& options); + +inline bool IsCord(const FieldDescriptor* field, const Options& options) { + return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && + EffectiveStringCType(field, options) == FieldOptions::CORD; +} + +inline bool IsString(const FieldDescriptor* field, const Options& options) { + return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && + EffectiveStringCType(field, options) == FieldOptions::STRING; +} + +inline bool IsStringPiece(const FieldDescriptor* field, + const Options& options) { + return field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && + EffectiveStringCType(field, options) == FieldOptions::STRING_PIECE; +} + +class MessageSCCAnalyzer; + +// Does the given FileDescriptor use lazy fields? +bool HasLazyFields(const FileDescriptor* file, const Options& options, + MessageSCCAnalyzer* scc_analyzer); + +// Is the given field a supported lazy field? +bool IsLazy(const FieldDescriptor* field, const Options& options, + MessageSCCAnalyzer* scc_analyzer); + +inline bool IsLazilyVerifiedLazy(const FieldDescriptor* field, + const Options& options) { + return field->options().lazy() && !field->is_repeated() && + field->type() == FieldDescriptor::TYPE_MESSAGE && + GetOptimizeFor(field->file(), options) != FileOptions::LITE_RUNTIME && + !options.opensource_runtime; +} + +inline bool IsEagerlyVerifiedLazy(const FieldDescriptor* field, + const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + return IsLazy(field, options, scc_analyzer) && !field->options().lazy(); +} + +inline bool IsFieldUsed(const FieldDescriptor* /* field */, + const Options& /* options */) { + return true; +} + +// Returns true if "field" is stripped. +inline bool IsFieldStripped(const FieldDescriptor* /*field*/, + const Options& /*options*/) { + return false; +} + +// Does the file contain any definitions that need extension_set.h? +bool HasExtensionsOrExtendableMessage(const FileDescriptor* file); + +// Does the file have any repeated fields, necessitating the file to include +// repeated_field.h? This does not include repeated extensions, since those are +// all stored internally in an ExtensionSet, not a separate RepeatedField*. +bool HasRepeatedFields(const FileDescriptor* file); + +// Does the file have any string/bytes fields with ctype=STRING_PIECE? This +// does not include extensions, since ctype is ignored for extensions. +bool HasStringPieceFields(const FileDescriptor* file, const Options& options); + +// Does the file have any string/bytes fields with ctype=CORD? This does not +// include extensions, since ctype is ignored for extensions. +bool HasCordFields(const FileDescriptor* file, const Options& options); // Does the file have any map fields, necessitating the file to include // map_field_inl.h and map.h. @@ -239,15 +417,15 @@ inline bool HasGenericServices(const FileDescriptor* file, file->options().cc_generic_services(); } -// Should we generate a separate, super-optimized code path for serializing to -// flat arrays? We don't do this in Lite mode because we'd rather reduce code -// size. -inline bool HasFastArraySerialization(const FileDescriptor* file, - const Options& options) { - return GetOptimizeFor(file, options) == FileOptions::SPEED; +inline bool IsProto2MessageSet(const Descriptor* descriptor, + const Options& options) { + return !options.opensource_runtime && + options.enforce_mode != EnforceOptimizeMode::kLiteRuntime && + !options.lite_implicit_weak_fields && + descriptor->options().message_set_wire_format() && + descriptor->full_name() == "google.protobuf.bridge.MessageSet"; } - inline bool IsMapEntryMessage(const Descriptor* descriptor) { return descriptor->options().map_entry(); } @@ -255,32 +433,33 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) { // Returns true if the field's CPPTYPE is string or message. bool IsStringOrMessage(const FieldDescriptor* field); -// For a string field, returns the effective ctype. If the actual ctype is -// not supported, returns the default of STRING. -FieldOptions::CType EffectiveStringCType(const FieldDescriptor* field); +std::string UnderscoresToCamelCase(const std::string& input, + bool cap_next_letter); -string UnderscoresToCamelCase(const string& input, bool cap_next_letter); +inline bool IsProto3(const FileDescriptor* file) { + return file->syntax() == FileDescriptor::SYNTAX_PROTO3; +} -inline bool HasFieldPresence(const FileDescriptor* file) { - return file->syntax() != FileDescriptor::SYNTAX_PROTO3; +inline bool HasHasbit(const FieldDescriptor* field) { + // This predicate includes proto3 message fields only if they have "optional". + // Foo submsg1 = 1; // HasHasbit() == false + // optional Foo submsg2 = 2; // HasHasbit() == true + // This is slightly odd, as adding "optional" to a singular proto3 field does + // not change the semantics or API. However whenever any field in a message + // has a hasbit, it forces reflection to include hasbit offsets for *all* + // fields, even if almost all of them are set to -1 (no hasbit). So to avoid + // causing a sudden size regression for ~all proto3 messages, we give proto3 + // message fields a hasbit only if "optional" is present. If the user is + // explicitly writing "optional", it is likely they are writing it on + // primitive fields also. + return (field->has_optional_keyword() || field->is_required()) && + !field->options().weak(); } // Returns true if 'enum' semantics are such that unknown values are preserved // in the enum field itself, rather than going to the UnknownFieldSet. -inline bool HasPreservingUnknownEnumSemantics(const FileDescriptor* file) { - return file->syntax() == FileDescriptor::SYNTAX_PROTO3; -} - -inline bool SupportsArenas(const FileDescriptor* file) { - return file->options().cc_enable_arenas(); -} - -inline bool SupportsArenas(const Descriptor* desc) { - return SupportsArenas(desc->file()); -} - -inline bool SupportsArenas(const FieldDescriptor* field) { - return SupportsArenas(field->file()); +inline bool HasPreservingUnknownEnumSemantics(const FieldDescriptor* field) { + return field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3; } inline bool IsCrossFileMessage(const FieldDescriptor* field) { @@ -288,36 +467,67 @@ inline bool IsCrossFileMessage(const FieldDescriptor* field) { field->message_type()->file() != field->file(); } -inline string MessageCreateFunction(const Descriptor* d) { - return SupportsArenas(d) ? "CreateMessage" : "Create"; -} - -inline string MakeDefaultName(const FieldDescriptor* field) { +inline std::string MakeDefaultName(const FieldDescriptor* field) { return "_i_give_permission_to_break_this_code_default_" + FieldName(field) + "_"; } -bool IsAnyMessage(const FileDescriptor* descriptor); -bool IsAnyMessage(const Descriptor* descriptor); +bool IsAnyMessage(const FileDescriptor* descriptor, const Options& options); +bool IsAnyMessage(const Descriptor* descriptor, const Options& options); bool IsWellKnownMessage(const FileDescriptor* descriptor); -void GenerateUtf8CheckCodeForString(const FieldDescriptor* field, - const Options& options, bool for_parse, - const std::map& variables, - const char* parameters, - io::Printer* printer); +inline std::string IncludeGuard(const FileDescriptor* file, bool pb_h, + const Options& options) { + // If we are generating a .pb.h file and the proto_h option is enabled, then + // the .pb.h gets an extra suffix. + std::string filename_identifier = FilenameIdentifier( + file->name() + (pb_h && options.proto_h ? ".pb.h" : "")); -void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field, - const Options& options, bool for_parse, - const std::map& variables, - const char* parameters, io::Printer* printer); + if (IsWellKnownMessage(file)) { + // For well-known messages we need third_party/protobuf and net/proto2 to + // have distinct include guards, because some source files include both and + // both need to be defined (the third_party copies will be in the + // google::protobuf_opensource namespace). + return MacroPrefix(options) + "_INCLUDED_" + filename_identifier; + } else { + // Ideally this case would use distinct include guards for opensource and + // google3 protos also. (The behavior of "first #included wins" is not + // ideal). But unfortunately some legacy code includes both and depends on + // the identical include guards to avoid compile errors. + // + // We should clean this up so that this case can be removed. + return "GOOGLE_PROTOBUF_INCLUDED_" + filename_identifier; + } +} -inline ::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor( - const FileDescriptor* file, const Options& options) { - return options.enforce_lite - ? FileOptions::LITE_RUNTIME - : file->options().optimize_for(); +// Returns the OptimizeMode for this file, furthermore it updates a status +// bool if has_opt_codesize_extension is non-null. If this status bool is true +// it means this file contains an extension that itself is defined as +// optimized_for = CODE_SIZE. +FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file, + const Options& options, + bool* has_opt_codesize_extension); +inline FileOptions_OptimizeMode GetOptimizeFor(const FileDescriptor* file, + const Options& options) { + return GetOptimizeFor(file, options, nullptr); +} +inline bool NeedsEagerDescriptorAssignment(const FileDescriptor* file, + const Options& options) { + bool has_opt_codesize_extension; + if (GetOptimizeFor(file, options, &has_opt_codesize_extension) == + FileOptions::CODE_SIZE && + has_opt_codesize_extension) { + // If this filedescriptor contains an extension from another file which + // is optimized_for = CODE_SIZE. We need to be careful in the ordering so + // we eagerly build the descriptors in the dependencies before building + // the descriptors of this file. + return true; + } else { + // If we have a generated code based parser we never need eager + // initialization of descriptors of our deps. + return false; + } } // This orders the messages in a .pb.cc as it's outputted by file.cc @@ -330,80 +540,45 @@ inline std::vector FlattenMessagesInFile( return result; } -bool HasWeakFields(const Descriptor* desc); -bool HasWeakFields(const FileDescriptor* desc); +template +void ForEachMessage(const Descriptor* descriptor, F&& func) { + for (int i = 0; i < descriptor->nested_type_count(); i++) + ForEachMessage(descriptor->nested_type(i), std::forward(func)); + func(descriptor); +} + +template +void ForEachMessage(const FileDescriptor* descriptor, F&& func) { + for (int i = 0; i < descriptor->message_type_count(); i++) + ForEachMessage(descriptor->message_type(i), std::forward(func)); +} + +bool HasWeakFields(const Descriptor* desc, const Options& options); +bool HasWeakFields(const FileDescriptor* desc, const Options& options); // Returns true if the "required" restriction check should be ignored for the // given field. inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field, const Options& options) { - return false; + // Do not check "required" for lazily verified lazy fields. + return IsLazilyVerifiedLazy(field, options); } -class LIBPROTOC_EXPORT NamespaceOpener { - public: - explicit NamespaceOpener(io::Printer* printer) : printer_(printer) {} - NamespaceOpener(const string& name, io::Printer* printer) - : printer_(printer) { - ChangeTo(name); - } - ~NamespaceOpener() { ChangeTo(""); } - - void ChangeTo(const string& name) { - std::vector new_stack_ = - Split(name, "::", true); - int len = std::min(name_stack_.size(), new_stack_.size()); - int common_idx = 0; - while (common_idx < len) { - if (name_stack_[common_idx] != new_stack_[common_idx]) break; - common_idx++; - } - for (int i = name_stack_.size() - 1; i >= common_idx; i--) { - printer_->Print("} // namespace $ns$\n", "ns", name_stack_[i]); - } - name_stack_.swap(new_stack_); - for (int i = common_idx; i < name_stack_.size(); i++) { - printer_->Print("namespace $ns$ {\n", "ns", name_stack_[i]); - } - } - - private: - io::Printer* printer_; - std::vector name_stack_; -}; - -// Description of each strongly connected component. Note that the order -// of both the descriptors in this SCC and the order of children is -// deterministic. -struct SCC { - std::vector descriptors; - std::vector children; - - const Descriptor* GetRepresentative() const { return descriptors[0]; } -}; - struct MessageAnalysis { - bool is_recursive; - bool contains_cord; - bool contains_extension; - bool contains_required; + bool is_recursive = false; + bool contains_cord = false; + bool contains_extension = false; + bool contains_required = false; + bool contains_weak = false; // Implicit weak as well. }; // This class is used in FileGenerator, to ensure linear instead of // quadratic performance, if we do this per message we would get O(V*(V+E)). // Logically this is just only used in message.cc, but in the header for // FileGenerator to help share it. -class LIBPROTOC_EXPORT SCCAnalyzer { +class PROTOC_EXPORT MessageSCCAnalyzer { public: - explicit SCCAnalyzer(const Options& options) : options_(options), index_(0) {} - ~SCCAnalyzer() { - for (int i = 0; i < garbage_bin_.size(); i++) delete garbage_bin_[i]; - } - - const SCC* GetSCC(const Descriptor* descriptor) { - if (cache_.count(descriptor)) return cache_[descriptor].scc; - return DFS(descriptor).scc; - } + explicit MessageSCCAnalyzer(const Options& options) : options_(options) {} MessageAnalysis GetSCCAnalysis(const SCC* scc); @@ -411,37 +586,59 @@ class LIBPROTOC_EXPORT SCCAnalyzer { MessageAnalysis result = GetSCCAnalysis(GetSCC(descriptor)); return result.contains_required || result.contains_extension; } - - private: - struct NodeData { - const SCC* scc; // if null it means its still on the stack - int index; - int lowlink; - }; - - Options options_; - std::map cache_; - std::map analysis_cache_; - std::vector stack_; - int index_; - std::vector garbage_bin_; - - SCC* CreateSCC() { - garbage_bin_.push_back(new SCC()); - return garbage_bin_.back(); + bool HasWeakField(const Descriptor* descriptor) { + MessageAnalysis result = GetSCCAnalysis(GetSCC(descriptor)); + return result.contains_weak; + } + const SCC* GetSCC(const Descriptor* descriptor) { + return analyzer_.GetSCC(descriptor); } - // Tarjan's Strongly Connected Components algo - NodeData DFS(const Descriptor* descriptor); - - // Add the SCC's that are children of this SCC to its children. - void AddChildren(SCC* scc); + private: + struct DepsGenerator { + std::vector operator()(const Descriptor* desc) const { + std::vector deps; + for (int i = 0; i < desc->field_count(); i++) { + if (desc->field(i)->message_type()) { + deps.push_back(desc->field(i)->message_type()); + } + } + return deps; + } + }; + SCCAnalyzer analyzer_; + Options options_; + std::map analysis_cache_; }; void ListAllFields(const Descriptor* d, std::vector* fields); void ListAllFields(const FileDescriptor* d, std::vector* fields); + +template +void ForEachField(const Descriptor* d, T&& func) { + for (int i = 0; i < d->nested_type_count(); i++) { + ForEachField(d->nested_type(i), std::forward(func)); + } + for (int i = 0; i < d->extension_count(); i++) { + func(d->extension(i)); + } + for (int i = 0; i < d->field_count(); i++) { + func(d->field(i)); + } +} + +template +void ForEachField(const FileDescriptor* d, T&& func) { + for (int i = 0; i < d->message_type_count(); i++) { + ForEachField(d->message_type(i), std::forward(func)); + } + for (int i = 0; i < d->extension_count(); i++) { + func(d->extension(i)); + } +} + void ListAllTypesForServices(const FileDescriptor* fd, std::vector* types); @@ -451,11 +648,324 @@ bool UsingImplicitWeakFields(const FileDescriptor* file, // Indicates whether to treat this field as implicitly weak. bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options, - SCCAnalyzer* scc_analyzer); + MessageSCCAnalyzer* scc_analyzer); +inline bool HasSimpleBaseClass(const Descriptor* desc, const Options& options) { + if (!HasDescriptorMethods(desc->file(), options)) return false; + if (desc->extension_range_count() != 0) return false; + if (desc->field_count() == 0) return true; + // TODO(jorg): Support additional common message types with only one + // or two fields + return false; +} + +inline bool HasSimpleBaseClasses(const FileDescriptor* file, + const Options& options) { + bool v = false; + ForEachMessage(file, [&v, &options](const Descriptor* desc) { + v |= HasSimpleBaseClass(desc, options); + }); + return v; +} + +inline std::string SimpleBaseClass(const Descriptor* desc, + const Options& options) { + if (!HasDescriptorMethods(desc->file(), options)) return ""; + if (desc->extension_range_count() != 0) return ""; + if (desc->field_count() == 0) { + return "ZeroFieldsBase"; + } + // TODO(jorg): Support additional common message types with only one + // or two fields + return ""; +} + +// Formatter is a functor class which acts as a closure around printer and +// the variable map. It's much like printer->Print except it supports both named +// variables that are substituted using a key value map and direct arguments. In +// the format string $1$, $2$, etc... are substituted for the first, second, ... +// direct argument respectively in the format call, it accepts both strings and +// integers. The implementation verifies all arguments are used and are "first" +// used in order of appearance in the argument list. For example, +// +// Format("return array[$1$];", 3) -> "return array[3];" +// Format("array[$2$] = $1$;", "Bla", 3) -> FATAL error (wrong order) +// Format("array[$1$] = $2$;", 3, "Bla") -> "array[3] = Bla;" +// +// The arguments can be used more than once like +// +// Format("array[$1$] = $2$; // Index = $1$", 3, "Bla") -> +// "array[3] = Bla; // Index = 3" +// +// If you use more arguments use the following style to help the reader, +// +// Format("int $1$() {\n" +// " array[$2$] = $3$;\n" +// " return $4$;" +// "}\n", +// funname, // 1 +// idx, // 2 +// varname, // 3 +// retval); // 4 +// +// but consider using named variables. Named variables like $foo$, with some +// identifier foo, are looked up in the map. One additional feature is that +// spaces are accepted between the '$' delimiters, $ foo$ will +// substiture to " bar" if foo stands for "bar", but in case it's empty +// will substitute to "". Hence, for example, +// +// Format(vars, "$dllexport $void fun();") -> "void fun();" +// "__declspec(export) void fun();" +// +// which is convenient to prevent double, leading or trailing spaces. +class PROTOC_EXPORT Formatter { + public: + explicit Formatter(io::Printer* printer) : printer_(printer) {} + Formatter(io::Printer* printer, + const std::map& vars) + : printer_(printer), vars_(vars) {} + + template + void Set(const std::string& key, const T& value) { + vars_[key] = ToString(value); + } + + void AddMap(const std::map& vars) { + for (const auto& keyval : vars) vars_[keyval.first] = keyval.second; + } + + template + void operator()(const char* format, const Args&... args) const { + printer_->FormatInternal({ToString(args)...}, vars_, format); + } + + void Indent() const { printer_->Indent(); } + void Outdent() const { printer_->Outdent(); } + io::Printer* printer() const { return printer_; } + + class PROTOC_EXPORT ScopedIndenter { + public: + explicit ScopedIndenter(Formatter* format) : format_(format) { + format_->Indent(); + } + ~ScopedIndenter() { format_->Outdent(); } + + private: + Formatter* format_; + }; + + PROTOBUF_NODISCARD ScopedIndenter ScopedIndent() { + return ScopedIndenter(this); + } + template + PROTOBUF_NODISCARD ScopedIndenter ScopedIndent(const char* format, + const Args&&... args) { + (*this)(format, static_cast(args)...); + return ScopedIndenter(this); + } + + class PROTOC_EXPORT SaveState { + public: + explicit SaveState(Formatter* format) + : format_(format), vars_(format->vars_) {} + ~SaveState() { format_->vars_.swap(vars_); } + + private: + Formatter* format_; + std::map vars_; + }; + + private: + io::Printer* printer_; + std::map vars_; + + // Convenience overloads to accept different types as arguments. + static std::string ToString(const std::string& s) { return s; } + template ::value>::type> + static std::string ToString(I x) { + return StrCat(x); + } + static std::string ToString(strings::Hex x) { return StrCat(x); } + static std::string ToString(const FieldDescriptor* d) { return Payload(d); } + static std::string ToString(const Descriptor* d) { return Payload(d); } + static std::string ToString(const EnumDescriptor* d) { return Payload(d); } + static std::string ToString(const EnumValueDescriptor* d) { + return Payload(d); + } + static std::string ToString(const OneofDescriptor* d) { return Payload(d); } + + template + static std::string Payload(const Descriptor* descriptor) { + std::vector path; + descriptor->GetLocationPath(&path); + GeneratedCodeInfo::Annotation annotation; + for (int index : path) { + annotation.add_path(index); + } + annotation.set_source_file(descriptor->file()->name()); + return annotation.SerializeAsString(); + } +}; + +template +void PrintFieldComment(const Formatter& format, const T* field) { + // Print the field's (or oneof's) proto-syntax definition as a comment. + // We don't want to print group bodies so we cut off after the first + // line. + DebugStringOptions options; + options.elide_group_body = true; + options.elide_oneof_body = true; + std::string def = field->DebugStringWithOptions(options); + format("// $1$\n", def.substr(0, def.find_first_of('\n'))); +} + +class PROTOC_EXPORT NamespaceOpener { + public: + explicit NamespaceOpener(const Formatter& format) + : printer_(format.printer()) {} + NamespaceOpener(const std::string& name, const Formatter& format) + : NamespaceOpener(format) { + ChangeTo(name); + } + ~NamespaceOpener() { ChangeTo(""); } + + void ChangeTo(const std::string& name) { + std::vector new_stack_ = + Split(name, "::", true); + size_t len = std::min(name_stack_.size(), new_stack_.size()); + size_t common_idx = 0; + while (common_idx < len) { + if (name_stack_[common_idx] != new_stack_[common_idx]) break; + common_idx++; + } + for (auto it = name_stack_.crbegin(); + it != name_stack_.crend() - common_idx; ++it) { + if (*it == "PROTOBUF_NAMESPACE_ID") { + printer_->Print("PROTOBUF_NAMESPACE_CLOSE\n"); + } else { + printer_->Print("} // namespace $ns$\n", "ns", *it); + } + } + name_stack_.swap(new_stack_); + for (size_t i = common_idx; i < name_stack_.size(); ++i) { + if (name_stack_[i] == "PROTOBUF_NAMESPACE_ID") { + printer_->Print("PROTOBUF_NAMESPACE_OPEN\n"); + } else { + printer_->Print("namespace $ns$ {\n", "ns", name_stack_[i]); + } + } + } + + private: + io::Printer* printer_; + std::vector name_stack_; +}; + +enum class Utf8CheckMode { + kStrict = 0, // Parsing will fail if non UTF-8 data is in string fields. + kVerify = 1, // Only log an error but parsing will succeed. + kNone = 2, // No UTF-8 check. +}; + +Utf8CheckMode GetUtf8CheckMode(const FieldDescriptor* field, + const Options& options); + +void GenerateUtf8CheckCodeForString(const FieldDescriptor* field, + const Options& options, bool for_parse, + const char* parameters, + const Formatter& format); + +void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field, + const Options& options, bool for_parse, + const char* parameters, + const Formatter& format); + +template +struct FieldRangeImpl { + struct Iterator { + using iterator_category = std::forward_iterator_tag; + using value_type = const FieldDescriptor*; + using difference_type = int; + + value_type operator*() { return descriptor->field(idx); } + + friend bool operator==(const Iterator& a, const Iterator& b) { + GOOGLE_DCHECK(a.descriptor == b.descriptor); + return a.idx == b.idx; + } + friend bool operator!=(const Iterator& a, const Iterator& b) { + return !(a == b); + } + + Iterator& operator++() { + idx++; + return *this; + } + + int idx; + const T* descriptor; + }; + + Iterator begin() const { return {0, descriptor}; } + Iterator end() const { return {descriptor->field_count(), descriptor}; } + + const T* descriptor; +}; + +template +FieldRangeImpl FieldRange(const T* desc) { + return {desc}; +} + +struct OneOfRangeImpl { + struct Iterator { + using iterator_category = std::forward_iterator_tag; + using value_type = const OneofDescriptor*; + using difference_type = int; + + value_type operator*() { return descriptor->oneof_decl(idx); } + + friend bool operator==(const Iterator& a, const Iterator& b) { + GOOGLE_DCHECK(a.descriptor == b.descriptor); + return a.idx == b.idx; + } + friend bool operator!=(const Iterator& a, const Iterator& b) { + return !(a == b); + } + + Iterator& operator++() { + idx++; + return *this; + } + + int idx; + const Descriptor* descriptor; + }; + + Iterator begin() const { return {0, descriptor}; } + Iterator end() const { + return {descriptor->real_oneof_decl_count(), descriptor}; + } + + const Descriptor* descriptor; +}; + +inline OneOfRangeImpl OneOfRange(const Descriptor* desc) { return {desc}; } + +PROTOC_EXPORT std::string StripProto(const std::string& filename); + +bool EnableMessageOwnedArena(const Descriptor* desc); + +bool ShouldVerify(const Descriptor* descriptor, const Options& options, + MessageSCCAnalyzer* scc_analyzer); +bool ShouldVerify(const FileDescriptor* file, const Options& options, + MessageSCCAnalyzer* scc_analyzer); } // namespace cpp } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CPP_HELPERS_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_map_field.cc b/windows/include/google/protobuf/compiler/cpp/cpp_map_field.cc deleted file mode 100644 index 0e485cacb..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_map_field.cc +++ /dev/null @@ -1,436 +0,0 @@ -// 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. - -#include -#include -#include -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -bool IsProto3Field(const FieldDescriptor* field_descriptor) { - const FileDescriptor* file_descriptor = field_descriptor->file(); - return file_descriptor->syntax() == FileDescriptor::SYNTAX_PROTO3; -} - -void SetMessageVariables(const FieldDescriptor* descriptor, - std::map* variables, - const Options& options) { - SetCommonFieldVariables(descriptor, variables, options); - (*variables)["type"] = ClassName(descriptor->message_type(), false); - (*variables)["file_namespace"] = - FileLevelNamespace(descriptor->file()->name()); - (*variables)["stream_writer"] = - (*variables)["declared_type"] + - (HasFastArraySerialization(descriptor->message_type()->file(), options) - ? "MaybeToArray" - : ""); - (*variables)["full_name"] = descriptor->full_name(); - - const FieldDescriptor* key = - descriptor->message_type()->FindFieldByName("key"); - const FieldDescriptor* val = - descriptor->message_type()->FindFieldByName("value"); - (*variables)["key_cpp"] = PrimitiveTypeName(key->cpp_type()); - switch (val->cpp_type()) { - case FieldDescriptor::CPPTYPE_MESSAGE: - (*variables)["val_cpp"] = FieldMessageTypeName(val); - (*variables)["wrapper"] = "EntryWrapper"; - break; - case FieldDescriptor::CPPTYPE_ENUM: - (*variables)["val_cpp"] = ClassName(val->enum_type(), true); - (*variables)["wrapper"] = "EnumEntryWrapper"; - break; - default: - (*variables)["val_cpp"] = PrimitiveTypeName(val->cpp_type()); - (*variables)["wrapper"] = "EntryWrapper"; - } - (*variables)["key_wire_type"] = - "::google::protobuf::internal::WireFormatLite::TYPE_" + - ToUpper(DeclaredTypeMethodName(key->type())); - (*variables)["val_wire_type"] = - "::google::protobuf::internal::WireFormatLite::TYPE_" + - ToUpper(DeclaredTypeMethodName(val->type())); - (*variables)["map_classname"] = ClassName(descriptor->message_type(), false); - (*variables)["number"] = SimpleItoa(descriptor->number()); - (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor)); - - if (HasDescriptorMethods(descriptor->file(), options)) { - (*variables)["lite"] = ""; - } else { - (*variables)["lite"] = "Lite"; - } - - if (!IsProto3Field(descriptor) && - val->type() == FieldDescriptor::TYPE_ENUM) { - const EnumValueDescriptor* default_value = val->default_value_enum(); - (*variables)["default_enum_value"] = Int32ToString(default_value->number()); - } else { - (*variables)["default_enum_value"] = "0"; - } -} - -MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { - SetMessageVariables(descriptor, &variables_, options); -} - -MapFieldGenerator::~MapFieldGenerator() {} - -void MapFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::internal::MapField$lite$<\n" - " $map_classname$,\n" - " $key_cpp$, $val_cpp$,\n" - " $key_wire_type$,\n" - " $val_wire_type$,\n" - " $default_enum_value$ > $name$_;\n"); -} - -void MapFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print( - variables_, - "$deprecated_attr$const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n" - " $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n" - " ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); -} - -void MapFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_map:$full_name$)\n" - " return $name$_.GetMap();\n" - "}\n" - "inline ::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_map:$full_name$)\n" - " return $name$_.MutableMap();\n" - "}\n"); -} - -void MapFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Clear();\n"); -} - -void MapFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); -} - -void MapFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n"); -} - -void MapFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - GenerateConstructorCode(printer); - GenerateMergingCode(printer); -} - -void MapFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - const FieldDescriptor* key_field = - descriptor_->message_type()->FindFieldByName("key"); - const FieldDescriptor* value_field = - descriptor_->message_type()->FindFieldByName("value"); - bool using_entry = false; - string key; - string value; - if (IsProto3Field(descriptor_) || - value_field->type() != FieldDescriptor::TYPE_ENUM) { - printer->Print( - variables_, - "$map_classname$::Parser< ::google::protobuf::internal::MapField$lite$<\n" - " $map_classname$,\n" - " $key_cpp$, $val_cpp$,\n" - " $key_wire_type$,\n" - " $val_wire_type$,\n" - " $default_enum_value$ >,\n" - " ::google::protobuf::Map< $key_cpp$, $val_cpp$ > >" - " parser(&$name$_);\n" - "DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(\n" - " input, &parser));\n"); - key = "parser.key()"; - value = "parser.value()"; - } else { - using_entry = true; - key = "entry->key()"; - value = "entry->value()"; - printer->Print(variables_, - "::std::unique_ptr<$map_classname$> entry($name$_.NewEntry());\n"); - printer->Print(variables_, - "{\n" - " ::std::string data;\n" - " DO_(::google::protobuf::internal::WireFormatLite::ReadString(input, &data));\n" - " DO_(entry->ParseFromString(data));\n" - " if ($val_cpp$_IsValid(*entry->mutable_value())) {\n" - " (*mutable_$name$())[entry->key()] =\n" - " static_cast< $val_cpp$ >(*entry->mutable_value());\n" - " } else {\n"); - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print(variables_, - " mutable_unknown_fields()" - "->AddLengthDelimited($number$, data);\n"); - } else { - printer->Print(variables_, - " unknown_fields_stream.WriteVarint32($tag$u);\n" - " unknown_fields_stream.WriteVarint32(\n" - " static_cast< ::google::protobuf::uint32>(data.size()));\n" - " unknown_fields_stream.WriteString(data);\n"); - } - - printer->Print(variables_, - " }\n" - "}\n"); - } - - if (key_field->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - key_field, options_, true, variables_, - StrCat(key, ".data(), static_cast(", key, ".length()),\n").data(), - printer); - } - if (value_field->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - value_field, options_, true, variables_, - StrCat(value, ".data(), static_cast(", value, ".length()),\n") - .data(), - printer); - } - - // If entry is allocated by arena, its desctructor should be avoided. - if (using_entry && SupportsArenas(descriptor_)) { - printer->Print(variables_, - "if (entry->GetArena() != NULL) entry.release();\n"); - } -} - -static void GenerateSerializationLoop(io::Printer* printer, - const std::map& variables, - bool supports_arenas, - const string& utf8_check, - const string& loop_header, - const string& ptr, - bool loop_via_iterators) { - printer->Print(variables, - StrCat("::std::unique_ptr<$map_classname$> entry;\n", - loop_header, " {\n").c_str()); - printer->Indent(); - - printer->Print(variables, StrCat( - "entry.reset($name$_.New$wrapper$(\n" - " ", ptr, "->first, ", ptr, "->second));\n" - "$write_entry$;\n").c_str()); - - // If entry is allocated by arena, its desctructor should be avoided. - if (supports_arenas) { - printer->Print( - "if (entry->GetArena() != NULL) {\n" - " entry.release();\n" - "}\n"); - } - - if (!utf8_check.empty()) { - // If loop_via_iterators is true then ptr is actually an iterator, and we - // create a pointer by prefixing it with "&*". - printer->Print( - StrCat(utf8_check, "(", (loop_via_iterators ? "&*" : ""), ptr, ");\n") - .c_str()); - } - - printer->Outdent(); - printer->Print( - "}\n"); -} - -void MapFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - std::map variables(variables_); - variables["write_entry"] = "::google::protobuf::internal::WireFormatLite::Write" + - variables["stream_writer"] + "(\n " + - variables["number"] + ", *entry, output)"; - variables["deterministic"] = "output->IsSerializationDeterministic()"; - GenerateSerializeWithCachedSizes(printer, variables); -} - -void MapFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - std::map variables(variables_); - variables["write_entry"] = - "target = ::google::protobuf::internal::WireFormatLite::\n" - " InternalWrite" + variables["declared_type"] + - "NoVirtualToArray(\n " + variables["number"] + - ", *entry, deterministic, target);\n"; - variables["deterministic"] = "deterministic"; - GenerateSerializeWithCachedSizes(printer, variables); -} - -void MapFieldGenerator::GenerateSerializeWithCachedSizes( - io::Printer* printer, const std::map& variables) const { - printer->Print(variables, - "if (!this->$name$().empty()) {\n"); - printer->Indent(); - const FieldDescriptor* key_field = - descriptor_->message_type()->FindFieldByName("key"); - const FieldDescriptor* value_field = - descriptor_->message_type()->FindFieldByName("value"); - const bool string_key = key_field->type() == FieldDescriptor::TYPE_STRING; - const bool string_value = value_field->type() == FieldDescriptor::TYPE_STRING; - - printer->Print(variables, - "typedef ::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_pointer\n" - " ConstPtr;\n"); - if (string_key) { - printer->Print(variables, - "typedef ConstPtr SortItem;\n" - "typedef ::google::protobuf::internal::" - "CompareByDerefFirst Less;\n"); - } else { - printer->Print(variables, - "typedef ::google::protobuf::internal::SortItem< $key_cpp$, ConstPtr > " - "SortItem;\n" - "typedef ::google::protobuf::internal::CompareByFirstField Less;\n"); - } - string utf8_check; - if (string_key || string_value) { - printer->Print( - "struct Utf8Check {\n" - " static void Check(ConstPtr p) {\n"); - printer->Indent(); - printer->Indent(); - if (string_key) { - GenerateUtf8CheckCodeForString( - key_field, options_, false, variables, - "p->first.data(), static_cast(p->first.length()),\n", printer); - } - if (string_value) { - GenerateUtf8CheckCodeForString( - value_field, options_, false, variables, - "p->second.data(), static_cast(p->second.length()),\n", printer); - } - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" - "};\n"); - utf8_check = "Utf8Check::Check"; - } - - printer->Print(variables, - "\n" - "if ($deterministic$ &&\n" - " this->$name$().size() > 1) {\n" - " ::std::unique_ptr items(\n" - " new SortItem[this->$name$().size()]);\n" - " typedef ::google::protobuf::Map< $key_cpp$, $val_cpp$ >::size_type size_type;\n" - " size_type n = 0;\n" - " for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" - " it = this->$name$().begin();\n" - " it != this->$name$().end(); ++it, ++n) {\n" - " items[static_cast(n)] = SortItem(&*it);\n" - " }\n" - " ::std::sort(&items[0], &items[static_cast(n)], Less());\n"); - printer->Indent(); - GenerateSerializationLoop(printer, variables, SupportsArenas(descriptor_), - utf8_check, "for (size_type i = 0; i < n; i++)", - string_key ? "items[static_cast(i)]" : - "items[static_cast(i)].second", false); - printer->Outdent(); - printer->Print( - "} else {\n"); - printer->Indent(); - GenerateSerializationLoop( - printer, variables, SupportsArenas(descriptor_), utf8_check, - "for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" - " it = this->$name$().begin();\n" - " it != this->$name$().end(); ++it)", - "it", true); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n"); -} - -void MapFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ *\n" - " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n" - "{\n" - " ::std::unique_ptr<$map_classname$> entry;\n" - " for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n" - " it = this->$name$().begin();\n" - " it != this->$name$().end(); ++it) {\n"); - - // If entry is allocated by arena, its desctructor should be avoided. - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - " if (entry.get() != NULL && entry->GetArena() != NULL) {\n" - " entry.release();\n" - " }\n"); - } - - printer->Print(variables_, - " entry.reset($name$_.New$wrapper$(it->first, it->second));\n" - " total_size += ::google::protobuf::internal::WireFormatLite::\n" - " $declared_type$SizeNoVirtual(*entry);\n" - " }\n"); - - // If entry is allocated by arena, its desctructor should be avoided. - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - " if (entry.get() != NULL && entry->GetArena() != NULL) {\n" - " entry.release();\n" - " }\n"); - } - - printer->Print("}\n"); -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_map_field.h b/windows/include/google/protobuf/compiler/cpp/cpp_map_field.h deleted file mode 100644 index 0d54f0ea4..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_map_field.h +++ /dev/null @@ -1,79 +0,0 @@ -// 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_CPP_MAP_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_MAP_FIELD_H__ - -#include -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -class MapFieldGenerator : public FieldGenerator { - public: - MapFieldGenerator(const FieldDescriptor* descriptor, const Options& options); - ~MapFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const {} - void GenerateCopyConstructorCode(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - - private: - // A helper for GenerateSerializeWithCachedSizes{,ToArray}. - void GenerateSerializeWithCachedSizes( - io::Printer* printer, const std::map& variables) const; - - const FieldDescriptor* descriptor_; - std::map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MAP_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_message.cc b/windows/include/google/protobuf/compiler/cpp/cpp_message.cc deleted file mode 100644 index 8c2336af1..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_message.cc +++ /dev/null @@ -1,4385 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -template -void PrintFieldComment(io::Printer* printer, const T* field) { - // Print the field's (or oneof's) proto-syntax definition as a comment. - // We don't want to print group bodies so we cut off after the first - // line. - DebugStringOptions options; - options.elide_group_body = true; - options.elide_oneof_body = true; - string def = field->DebugStringWithOptions(options); - printer->Print("// $def$\n", - "def", def.substr(0, def.find_first_of('\n'))); -} - -struct FieldOrderingByNumber { - inline bool operator()(const FieldDescriptor* a, - const FieldDescriptor* b) const { - return a->number() < b->number(); - } -}; - -// Sort the fields of the given Descriptor by number into a new[]'d array -// and return it. -std::vector SortFieldsByNumber( - const Descriptor* descriptor) { - std::vector fields(descriptor->field_count()); - for (int i = 0; i < descriptor->field_count(); i++) { - fields[i] = descriptor->field(i); - } - std::sort(fields.begin(), fields.end(), FieldOrderingByNumber()); - return fields; -} - -// Functor for sorting extension ranges by their "start" field number. -struct ExtensionRangeSorter { - bool operator()(const Descriptor::ExtensionRange* left, - const Descriptor::ExtensionRange* right) const { - return left->start < right->start; - } -}; - -bool IsPOD(const FieldDescriptor* field) { - if (field->is_repeated() || field->is_extension()) return false; - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_ENUM: - case FieldDescriptor::CPPTYPE_INT32: - case FieldDescriptor::CPPTYPE_INT64: - case FieldDescriptor::CPPTYPE_UINT32: - case FieldDescriptor::CPPTYPE_UINT64: - case FieldDescriptor::CPPTYPE_FLOAT: - case FieldDescriptor::CPPTYPE_DOUBLE: - case FieldDescriptor::CPPTYPE_BOOL: - return true; - case FieldDescriptor::CPPTYPE_STRING: - return false; - default: - return false; - } -} - -// Helper for the code that emits the SharedCtor() method. -bool CanConstructByZeroing(const FieldDescriptor* field, - const Options& options) { - bool ret = CanInitializeByZeroing(field); - - // Non-repeated, non-lazy message fields are simply raw pointers, so we can - // use memset to initialize these in SharedCtor. We cannot use this in - // Clear, as we need to potentially delete the existing value. - ret = ret || - (!field->is_repeated() && - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE); - return ret; -} - -// Emits an if-statement with a condition that evaluates to true if |field| is -// considered non-default (will be sent over the wire), for message types -// without true field presence. Should only be called if -// !HasFieldPresence(message_descriptor). -bool EmitFieldNonDefaultCondition(io::Printer* printer, - const string& prefix, - const FieldDescriptor* field) { - // Merge and serialize semantics: primitive fields are merged/serialized only - // if non-zero (numeric) or non-empty (string). - if (!field->is_repeated() && !field->containing_oneof()) { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { - printer->Print( - "if ($prefix$$name$().size() > 0) {\n", - "prefix", prefix, - "name", FieldName(field)); - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - // Message fields still have has_$name$() methods. - printer->Print( - "if ($prefix$has_$name$()) {\n", - "prefix", prefix, - "name", FieldName(field)); - } else { - printer->Print( - "if ($prefix$$name$() != 0) {\n", - "prefix", prefix, - "name", FieldName(field)); - } - printer->Indent(); - return true; - } else if (field->containing_oneof()) { - printer->Print( - "if (has_$name$()) {\n", - "name", FieldName(field)); - printer->Indent(); - return true; - } - return false; -} - -// Does the given field have a has_$name$() method? -bool HasHasMethod(const FieldDescriptor* field) { - if (HasFieldPresence(field->file())) { - // In proto1/proto2, every field has a has_$name$() method. - return true; - } - // For message types without true field presence, only fields with a message - // type have a has_$name$() method. - return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE; -} - -// Collects map entry message type information. -void CollectMapInfo(const Descriptor* descriptor, - std::map* variables) { - GOOGLE_CHECK(IsMapEntryMessage(descriptor)); - std::map& vars = *variables; - const FieldDescriptor* key = descriptor->FindFieldByName("key"); - const FieldDescriptor* val = descriptor->FindFieldByName("value"); - vars["key_cpp"] = PrimitiveTypeName(key->cpp_type()); - switch (val->cpp_type()) { - case FieldDescriptor::CPPTYPE_MESSAGE: - vars["val_cpp"] = FieldMessageTypeName(val); - break; - case FieldDescriptor::CPPTYPE_ENUM: - vars["val_cpp"] = ClassName(val->enum_type(), true); - break; - default: - vars["val_cpp"] = PrimitiveTypeName(val->cpp_type()); - } - vars["key_wire_type"] = "::google::protobuf::internal::WireFormatLite::TYPE_" + - ToUpper(DeclaredTypeMethodName(key->type())); - vars["val_wire_type"] = "::google::protobuf::internal::WireFormatLite::TYPE_" + - ToUpper(DeclaredTypeMethodName(val->type())); - if (descriptor->file()->syntax() != FileDescriptor::SYNTAX_PROTO3 && - val->type() == FieldDescriptor::TYPE_ENUM) { - const EnumValueDescriptor* default_value = val->default_value_enum(); - vars["default_enum_value"] = Int32ToString(default_value->number()); - } else { - vars["default_enum_value"] = "0"; - } -} - -// Does the given field have a private (internal helper only) has_$name$() -// method? -bool HasPrivateHasMethod(const FieldDescriptor* field) { - // Only for oneofs in message types with no field presence. has_$name$(), - // based on the oneof case, is still useful internally for generated code. - return (!HasFieldPresence(field->file()) && - field->containing_oneof() != NULL); -} - - -bool TableDrivenParsingEnabled( - const Descriptor* descriptor, const Options& options) { - if (!options.table_driven_parsing) { - return false; - } - - // Consider table-driven parsing. We only do this if: - // - We have has_bits for fields. This avoids a check on every field we set - // when are present (the common case). - if (!HasFieldPresence(descriptor->file())) { - return false; - } - - const double table_sparseness = 0.5; - int max_field_number = 0; - for (int i = 0; i < descriptor->field_count(); i++) { - const FieldDescriptor* field = descriptor->field(i); - if (max_field_number < field->number()) { - max_field_number = field->number(); - } - - // - There are no weak fields. - if (field->options().weak()) { - return false; - } - } - - // - There range of field numbers is "small" - if (max_field_number >= (2 << 14)) { - return false; - } - - // - Field numbers are relatively dense within the actual number of fields. - // We check for strictly greater than in the case where there are no fields - // (only extensions) so max_field_number == descriptor->field_count() == 0. - if (max_field_number * table_sparseness > descriptor->field_count()) { - return false; - } - - // - This is not a MapEntryMessage. - if (IsMapEntryMessage(descriptor)) { - return false; - } - - return true; -} - -void SetUnknkownFieldsVariable(const Descriptor* descriptor, - const Options& options, - std::map* variables) { - if (UseUnknownFieldSet(descriptor->file(), options)) { - (*variables)["unknown_fields_type"] = "::google::protobuf::UnknownFieldSet"; - } else { - (*variables)["unknown_fields_type"] = "::std::string"; - } - if (AlwaysPreserveUnknownFields(descriptor)) { - (*variables)["have_unknown_fields"] = - "_internal_metadata_.have_unknown_fields()"; - (*variables)["unknown_fields"] = "_internal_metadata_.unknown_fields()"; - } else { - (*variables)["have_unknown_fields"] = - "(_internal_metadata_.have_unknown_fields() && " - " ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())"; - (*variables)["unknown_fields"] = - "(::google::protobuf::internal::GetProto3PreserveUnknownsDefault()" - " ? _internal_metadata_.unknown_fields()" - " : _internal_metadata_.default_instance())"; - } - (*variables)["mutable_unknown_fields"] = - "_internal_metadata_.mutable_unknown_fields()"; -} - -bool IsCrossFileMapField(const FieldDescriptor* field) { - if (!field->is_map()) { - return false; - } - - const Descriptor* d = field->message_type(); - const FieldDescriptor* value = d->FindFieldByNumber(2); - - return IsCrossFileMessage(value); -} - -bool IsCrossFileMaybeMap(const FieldDescriptor* field) { - if (IsCrossFileMapField(field)) { - return true; - } - - return IsCrossFileMessage(field); -} - -bool IsRequired(const std::vector& v) { - return v.front()->is_required(); -} - -// Allows chunking repeated fields together and non-repeated fields if the -// fields share the same has_byte index. -// TODO(seongkim): use lambda with capture instead of functor. -class MatchRepeatedAndHasByte { - public: - MatchRepeatedAndHasByte(const std::vector* has_bit_indices, - bool has_field_presence) - : has_bit_indices_(*has_bit_indices), - has_field_presence_(has_field_presence) {} - - // Returns true if the following conditions are met: - // --both fields are repeated fields - // --both fields are non-repeated fields with either has_field_presence is - // false or have the same has_byte index. - bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const { - return a->is_repeated() == b->is_repeated() && - (!has_field_presence_ || a->is_repeated() || - has_bit_indices_[a->index()] / 8 == - has_bit_indices_[b->index()] / 8); - } - - private: - const std::vector& has_bit_indices_; - const bool has_field_presence_; -}; - -// Allows chunking required fields separately after chunking with -// MatchRepeatedAndHasByte. -class MatchRepeatedAndHasByteAndRequired : public MatchRepeatedAndHasByte { - public: - MatchRepeatedAndHasByteAndRequired(const std::vector* has_bit_indices, - bool has_field_presence) - : MatchRepeatedAndHasByte(has_bit_indices, has_field_presence) {} - - bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const { - return MatchRepeatedAndHasByte::operator()(a, b) && - a->is_required() == b->is_required(); - } -}; - -// Allows chunking zero-initializable fields separately after chunking with -// MatchRepeatedAndHasByte. -class MatchRepeatedAndHasByteAndZeroInits : public MatchRepeatedAndHasByte { - public: - MatchRepeatedAndHasByteAndZeroInits(const std::vector* has_bit_indices, - bool has_field_presence) - : MatchRepeatedAndHasByte(has_bit_indices, has_field_presence) {} - - bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const { - return MatchRepeatedAndHasByte::operator()(a, b) && - CanInitializeByZeroing(a) == CanInitializeByZeroing(b); - } -}; - -// Collects neighboring fields based on a given criteria (equivalent predicate). -template -std::vector > CollectFields( - const std::vector& fields, - const Predicate& equivalent) { - std::vector > chunks; - if (fields.empty()) { - return chunks; - } - - const FieldDescriptor* last_field = fields.front(); - std::vector chunk; - for (int i = 0; i < fields.size(); i++) { - if (!equivalent(last_field, fields[i]) && !chunk.empty()) { - chunks.push_back(chunk); - chunk.clear(); - } - chunk.push_back(fields[i]); - last_field = fields[i]; - } - if (!chunk.empty()) { - chunks.push_back(chunk); - } - return chunks; -} - -// Returns a bit mask based on has_bit index of "fields" that are typically on -// the same chunk. It is used in a group presence check where _has_bits_ is -// masked to tell if any thing in "fields" is present. -uint32 GenChunkMask(const std::vector& fields, - const std::vector& has_bit_indices) { - GOOGLE_CHECK(!fields.empty()); - int first_index_offset = has_bit_indices[fields.front()->index()] / 32; - uint32 chunk_mask = 0; - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - // "index" defines where in the _has_bits_ the field appears. - int index = has_bit_indices[field->index()]; - GOOGLE_CHECK_EQ(first_index_offset, index / 32); - chunk_mask |= static_cast(1) << (index % 32); - } - GOOGLE_CHECK_NE(0, chunk_mask); - return chunk_mask; -} - -} // anonymous namespace - -// =================================================================== - -MessageGenerator::MessageGenerator(const Descriptor* descriptor, - int index_in_file_messages, - const Options& options, - SCCAnalyzer* scc_analyzer) - : descriptor_(descriptor), - index_in_file_messages_(index_in_file_messages), - classname_(ClassName(descriptor, false)), - options_(options), - field_generators_(descriptor, options, scc_analyzer), - max_has_bit_index_(0), - enum_generators_( - new std::unique_ptr[descriptor->enum_type_count()]), - extension_generators_(new std::unique_ptr< - ExtensionGenerator>[descriptor->extension_count()]), - num_weak_fields_(0), - message_layout_helper_(new PaddingOptimizer()), - scc_analyzer_(scc_analyzer) { - // Compute optimized field order to be used for layout and initialization - // purposes. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->options().weak()) { - num_weak_fields_++; - } else if (!field->containing_oneof()) { - optimized_order_.push_back(field); - } - } - - message_layout_helper_->OptimizeLayout(&optimized_order_, options_); - - if (HasFieldPresence(descriptor_->file())) { - // We use -1 as a sentinel. - has_bit_indices_.resize(descriptor_->field_count(), -1); - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - // Skip fields that do not have has bits. - if (field->is_repeated()) { - continue; - } - - has_bit_indices_[field->index()] = max_has_bit_index_++; - } - } - - for (int i = 0; i < descriptor->enum_type_count(); i++) { - enum_generators_[i].reset( - new EnumGenerator(descriptor->enum_type(i), options)); - } - - for (int i = 0; i < descriptor->extension_count(); i++) { - extension_generators_[i].reset( - new ExtensionGenerator(descriptor->extension(i), options)); - } - - num_required_fields_ = 0; - for (int i = 0; i < descriptor->field_count(); i++) { - if (descriptor->field(i)->is_required()) { - ++num_required_fields_; - } - } - - table_driven_ = TableDrivenParsingEnabled(descriptor_, options_); - - scc_name_ = - ClassName(scc_analyzer_->GetSCC(descriptor_)->GetRepresentative(), false); -} - -MessageGenerator::~MessageGenerator() {} - -size_t MessageGenerator::HasBitsSize() const { - size_t sizeof_has_bits = (max_has_bit_index_ + 31) / 32 * 4; - if (sizeof_has_bits == 0) { - // Zero-size arrays aren't technically allowed, and MSVC in particular - // doesn't like them. We still need to declare these arrays to make - // other code compile. Since this is an uncommon case, we'll just declare - // them with size 1 and waste some space. Oh well. - sizeof_has_bits = 4; - } - - return sizeof_has_bits; -} - -void MessageGenerator::AddGenerators( - std::vector* enum_generators, - std::vector* extension_generators) { - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - enum_generators->push_back(enum_generators_[i].get()); - } - for (int i = 0; i < descriptor_->extension_count(); i++) { - extension_generators->push_back(extension_generators_[i].get()); - } -} - -void MessageGenerator::FillMessageForwardDeclarations( - std::map* class_names) { - (*class_names)[classname_] = descriptor_; -} - -void MessageGenerator:: -GenerateFieldAccessorDeclarations(io::Printer* printer) { - // optimized_fields_ does not contain fields where - // field->containing_oneof() != NULL - // so we need to iterate over those as well. - // - // We place the non-oneof fields in optimized_order_, as that controls the - // order of the _has_bits_ entries and we want GDB's pretty printers to be - // able to infer these indices from the k[FIELDNAME]FieldNumber order. - std::vector ordered_fields; - ordered_fields.reserve(descriptor_->field_count()); - - ordered_fields.insert( - ordered_fields.begin(), optimized_order_.begin(), optimized_order_.end()); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->containing_oneof() == NULL && !field->options().weak()) { - continue; - } - ordered_fields.push_back(field); - } - - for (int i = 0; i < ordered_fields.size(); i++) { - const FieldDescriptor* field = ordered_fields[i]; - - PrintFieldComment(printer, field); - - std::map vars; - SetCommonFieldVariables(field, &vars, options_); - vars["constant_name"] = FieldConstantName(field); - - if (field->is_repeated()) { - printer->Print(vars, "$deprecated_attr$int ${$$name$_size$}$() const;\n"); - printer->Annotate("{", "}", field); - } else if (HasHasMethod(field)) { - printer->Print(vars, "$deprecated_attr$bool ${$has_$name$$}$() const;\n"); - printer->Annotate("{", "}", field); - } else if (HasPrivateHasMethod(field)) { - printer->Print(vars, - "private:\n" - "bool ${$has_$name$$}$() const;\n" - "public:\n"); - printer->Annotate("{", "}", field); - } - - printer->Print(vars, "$deprecated_attr$void ${$clear_$name$$}$();\n"); - printer->Annotate("{", "}", field); - printer->Print(vars, - "$deprecated_attr$static const int $constant_name$ = " - "$number$;\n"); - printer->Annotate("constant_name", field); - - // Generate type-specific accessor declarations. - field_generators_.get(field).GenerateAccessorDeclarations(printer); - - printer->Print("\n"); - } - - if (descriptor_->extension_range_count() > 0) { - // Generate accessors for extensions. We just call a macro located in - // extension_set.h since the accessors about 80 lines of static code. - printer->Print( - "GOOGLE_PROTOBUF_EXTENSION_ACCESSORS($classname$)\n", - "classname", classname_); - } - - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "void clear_$oneof_name$();\n" - "$camel_oneof_name$Case $oneof_name$_case() const;\n", - "camel_oneof_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true), - "oneof_name", descriptor_->oneof_decl(i)->name()); - } -} - -void MessageGenerator:: -GenerateSingularFieldHasBits(const FieldDescriptor* field, - std::map vars, - io::Printer* printer) { - if (field->options().weak()) { - printer->Print( - vars, - "inline bool $classname$::has_$name$() const {\n" - " return _weak_field_map_.Has($number$);\n" - "}\n"); - return; - } - if (HasFieldPresence(descriptor_->file())) { - // N.B.: without field presence, we do not use has-bits or generate - // has_$name$() methods. - int has_bit_index = has_bit_indices_[field->index()]; - GOOGLE_CHECK_GE(has_bit_index, 0); - - vars["has_array_index"] = SimpleItoa(has_bit_index / 32); - vars["has_mask"] = StrCat(strings::Hex(1u << (has_bit_index % 32), - strings::ZERO_PAD_8)); - printer->Print(vars, - "inline bool $classname$::has_$name$() const {\n" - " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n" - "}\n" - "inline void $classname$::set_has_$name$() {\n" - " _has_bits_[$has_array_index$] |= 0x$has_mask$u;\n" - "}\n" - "inline void $classname$::clear_has_$name$() {\n" - " _has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n" - "}\n"); - } else { - // Message fields have a has_$name$() method. - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - bool is_lazy = false; - if (is_lazy) { - printer->Print(vars, - "inline bool $classname$::has_$name$() const {\n" - " return !$name$_.IsCleared();\n" - "}\n"); - } else { - printer->Print( - vars, - "inline bool $classname$::has_$name$() const {\n" - " return this != internal_default_instance() && $name$_ != NULL;\n" - "}\n"); - } - } - } -} - -void MessageGenerator:: -GenerateOneofHasBits(io::Printer* printer) { - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - std::map vars; - vars["oneof_name"] = descriptor_->oneof_decl(i)->name(); - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); - vars["cap_oneof_name"] = - ToUpper(descriptor_->oneof_decl(i)->name()); - vars["classname"] = classname_; - printer->Print( - vars, - "inline bool $classname$::has_$oneof_name$() const {\n" - " return $oneof_name$_case() != $cap_oneof_name$_NOT_SET;\n" - "}\n" - "inline void $classname$::clear_has_$oneof_name$() {\n" - " _oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n" - "}\n"); - } -} - -void MessageGenerator:: -GenerateOneofMemberHasBits(const FieldDescriptor* field, - const std::map& vars, - io::Printer* printer) { - // Singular field in a oneof - // N.B.: Without field presence, we do not use has-bits or generate - // has_$name$() methods, but oneofs still have set_has_$name$(). - // Oneofs also have has_$name$() but only as a private helper - // method, so that generated code is slightly cleaner (vs. comparing - // _oneof_case_[index] against a constant everywhere). - printer->Print(vars, - "inline bool $classname$::has_$name$() const {\n" - " return $oneof_name$_case() == k$field_name$;\n" - "}\n"); - printer->Print(vars, - "inline void $classname$::set_has_$name$() {\n" - " _oneof_case_[$oneof_index$] = k$field_name$;\n" - "}\n"); -} - -void MessageGenerator:: -GenerateFieldClear(const FieldDescriptor* field, - const std::map& vars, - bool is_inline, - io::Printer* printer) { - // Generate clear_$name$(). - if (is_inline) { - printer->Print("inline "); - } - printer->Print(vars, - "void $classname$::clear_$name$() {\n"); - - printer->Indent(); - - if (field->containing_oneof()) { - // Clear this field only if it is the active field in this oneof, - // otherwise ignore - printer->Print(vars, - "if (has_$name$()) {\n"); - printer->Indent(); - field_generators_.get(field) - .GenerateClearingCode(printer); - printer->Print(vars, - "clear_has_$oneof_name$();\n"); - printer->Outdent(); - printer->Print("}\n"); - } else { - field_generators_.get(field) - .GenerateClearingCode(printer); - if (HasFieldPresence(descriptor_->file())) { - if (!field->is_repeated() && !field->options().weak()) { - printer->Print(vars, "clear_has_$name$();\n"); - } - } - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void MessageGenerator:: -GenerateFieldAccessorDefinitions(io::Printer* printer) { - printer->Print("// $classname$\n\n", "classname", classname_); - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - PrintFieldComment(printer, field); - - std::map vars; - SetCommonFieldVariables(field, &vars, options_); - - // Generate has_$name$() or $name$_size(). - if (field->is_repeated()) { - printer->Print(vars, - "inline int $classname$::$name$_size() const {\n" - " return $name$_.size();\n" - "}\n"); - } else if (field->containing_oneof()) { - vars["field_name"] = UnderscoresToCamelCase(field->name(), true); - vars["oneof_name"] = field->containing_oneof()->name(); - vars["oneof_index"] = SimpleItoa(field->containing_oneof()->index()); - GenerateOneofMemberHasBits(field, vars, printer); - } else { - // Singular field. - GenerateSingularFieldHasBits(field, vars, printer); - } - - if (!IsCrossFileMaybeMap(field)) { - GenerateFieldClear(field, vars, true, printer); - } - - // Generate type-specific accessors. - field_generators_.get(field).GenerateInlineAccessorDefinitions(printer); - - printer->Print("\n"); - } - - // Generate has_$name$() and clear_has_$name$() functions for oneofs. - GenerateOneofHasBits(printer); -} - -void MessageGenerator:: -GenerateClassDefinition(io::Printer* printer) { - if (IsMapEntryMessage(descriptor_)) { - std::map vars; - vars["classname"] = classname_; - CollectMapInfo(descriptor_, &vars); - vars["lite"] = - HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite"; - printer->Print( - vars, - "class $classname$ : public " - "::google::protobuf::internal::MapEntry$lite$<$classname$, \n" - " $key_cpp$, $val_cpp$,\n" - " $key_wire_type$,\n" - " $val_wire_type$,\n" - " $default_enum_value$ > {\n" - "public:\n" - " typedef ::google::protobuf::internal::MapEntry$lite$<$classname$, \n" - " $key_cpp$, $val_cpp$,\n" - " $key_wire_type$,\n" - " $val_wire_type$,\n" - " $default_enum_value$ > SuperType;\n" - " $classname$();\n" - " $classname$(::google::protobuf::Arena* arena);\n" - " void MergeFrom(const $classname$& other);\n" - " static const $classname$* internal_default_instance() { return " - "reinterpret_cast(&_$classname$_default_instance_); }\n"); - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - " void MergeFrom(const ::google::protobuf::Message& other) final;\n" - " ::google::protobuf::Metadata GetMetadata() const;\n" - "};\n"); - } else { - printer->Print("};\n"); - } - return; - } - - std::map vars; - vars["classname"] = classname_; - vars["full_name"] = descriptor_->full_name(); - vars["field_count"] = SimpleItoa(descriptor_->field_count()); - vars["oneof_decl_count"] = SimpleItoa(descriptor_->oneof_decl_count()); - if (options_.dllexport_decl.empty()) { - vars["dllexport"] = ""; - } else { - vars["dllexport"] = options_.dllexport_decl + " "; - } - vars["superclass"] = SuperClassName(descriptor_, options_); - printer->Print(vars, - "class $dllexport$$classname$ : public $superclass$ " - "/* @@protoc_insertion_point(class_definition:$full_name$) */ " - "{\n"); - printer->Annotate("classname", descriptor_); - printer->Print(" public:\n"); - printer->Indent(); - - printer->Print( - vars, - "$classname$();\n" - "virtual ~$classname$();\n" - "\n" - "$classname$(const $classname$& from);\n" - "\n" - "inline $classname$& operator=(const $classname$& from) {\n" - " CopyFrom(from);\n" - " return *this;\n" - "}\n"); - - if (options_.table_driven_serialization) { - printer->Print( - "private:\n" - "const void* InternalGetTable() const;\n" - "public:\n" - "\n"); - } - - // Generate move constructor and move assignment operator. - printer->Print(vars, - "#if LANG_CXX11\n" - "$classname$($classname$&& from) noexcept\n" - " : $classname$() {\n" - " *this = ::std::move(from);\n" - "}\n" - "\n" - "inline $classname$& operator=($classname$&& from) noexcept {\n" - " if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {\n" - " if (this != &from) InternalSwap(&from);\n" - " } else {\n" - " CopyFrom(from);\n" - " }\n" - " return *this;\n" - "}\n" - "#endif\n"); - - SetUnknkownFieldsVariable(descriptor_, options_, &vars); - if (PublicUnknownFieldsAccessors(descriptor_)) { - printer->Print(vars, - "inline const $unknown_fields_type$& unknown_fields() const {\n" - " return $unknown_fields$;\n" - "}\n" - "inline $unknown_fields_type$* mutable_unknown_fields() {\n" - " return $mutable_unknown_fields$;\n" - "}\n" - "\n"); - } - - // N.B.: We exclude GetArena() when arena support is disabled, falling back on - // MessageLite's implementation which returns NULL rather than generating our - // own method which returns NULL, in order to reduce code size. - if (SupportsArenas(descriptor_)) { - // virtual method version of GetArenaNoVirtual(), required for generic dispatch given a - // MessageLite* (e.g., in RepeatedField::AddAllocated()). - printer->Print( - "inline ::google::protobuf::Arena* GetArena() const final {\n" - " return GetArenaNoVirtual();\n" - "}\n" - "inline void* GetMaybeArenaPointer() const final {\n" - " return MaybeArenaPtr();\n" - "}\n"); - } - - // Only generate this member if it's not disabled. - if (HasDescriptorMethods(descriptor_->file(), options_) && - !descriptor_->options().no_standard_descriptor_accessor()) { - printer->Print(vars, - "static const ::google::protobuf::Descriptor* descriptor();\n"); - } - - printer->Print(vars, - "static const $classname$& default_instance();\n" - "\n"); - - // Generate enum values for every field in oneofs. One list is generated for - // each oneof with an additional *_NOT_SET value. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "enum $camel_oneof_name$Case {\n", - "camel_oneof_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - printer->Print( - "k$field_name$ = $field_number$,\n", - "field_name", - UnderscoresToCamelCase( - descriptor_->oneof_decl(i)->field(j)->name(), true), - "field_number", - SimpleItoa(descriptor_->oneof_decl(i)->field(j)->number())); - } - printer->Print( - "$cap_oneof_name$_NOT_SET = 0,\n", - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "};\n" - "\n"); - } - - // TODO(gerbens) make this private, while still granting other protos access. - vars["message_index"] = SimpleItoa(index_in_file_messages_); - printer->Print( - vars, - "static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY\n" - "static inline const $classname$* internal_default_instance() {\n" - " return reinterpret_cast(\n" - " &_$classname$_default_instance_);\n" - "}\n" - "static constexpr int kIndexInFileMessages =\n" - " $message_index$;\n" - "\n"); - - if (SupportsArenas(descriptor_)) { - printer->Print(vars, - "void UnsafeArenaSwap($classname$* other);\n"); - } - - if (IsAnyMessage(descriptor_)) { - printer->Print(vars, - "// implements Any -----------------------------------------------\n" - "\n" - "void PackFrom(const ::google::protobuf::Message& message);\n" - "void PackFrom(const ::google::protobuf::Message& message,\n" - " const ::std::string& type_url_prefix);\n" - "bool UnpackTo(::google::protobuf::Message* message) const;\n" - "template bool Is() const {\n" - " return _any_metadata_.Is();\n" - "}\n" - "static bool ParseAnyTypeUrl(const string& type_url,\n" - " string* full_type_name);\n" - "\n"); - } - - vars["new_final"] = " final"; - - printer->Print(vars, - "void Swap($classname$* other);\n" - "friend void swap($classname$& a, $classname$& b) {\n" - " a.Swap(&b);\n" - "}\n" - "\n" - "// implements Message ----------------------------------------------\n" - "\n" - "inline $classname$* New() const$new_final$ {\n" - " return CreateMaybeMessage<$classname$>(NULL);\n" - "}\n" - "\n" - "$classname$* New(::google::protobuf::Arena* arena) const$new_final$ {\n" - " return CreateMaybeMessage<$classname$>(arena);\n" - "}\n"); - - // For instances that derive from Message (rather than MessageLite), some - // methods are virtual and should be marked as final. - string use_final = HasDescriptorMethods(descriptor_->file(), options_) ? - " final" : ""; - - if (HasGeneratedMethods(descriptor_->file(), options_)) { - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print(vars, - "void CopyFrom(const ::google::protobuf::Message& from) final;\n" - "void MergeFrom(const ::google::protobuf::Message& from) final;\n"); - } else { - printer->Print(vars, - "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)\n" - " final;\n"); - } - - vars["clear_final"] = " final"; - vars["is_initialized_final"] = " final"; - vars["merge_partial_final"] = " final"; - - printer->Print( - vars, - "void CopyFrom(const $classname$& from);\n" - "void MergeFrom(const $classname$& from);\n" - "void Clear()$clear_final$;\n" - "bool IsInitialized() const$is_initialized_final$;\n" - "\n" - "size_t ByteSizeLong() const final;\n" - "bool MergePartialFromCodedStream(\n" - " ::google::protobuf::io::CodedInputStream* input)$merge_partial_final$;\n"); - if (!options_.table_driven_serialization || - descriptor_->options().message_set_wire_format()) { - printer->Print( - "void SerializeWithCachedSizes(\n" - " ::google::protobuf::io::CodedOutputStream* output) const " - "final;\n"); - } - // DiscardUnknownFields() is implemented in message.cc using reflections. We - // need to implement this function in generated code for messages. - if (!UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print( - "void DiscardUnknownFields()$final$;\n", - "final", use_final); - } - if (HasFastArraySerialization(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(\n" - " bool deterministic, ::google::protobuf::uint8* target) const final;\n"); - } - } - - printer->Print( - "int GetCachedSize() const final { return _cached_size_.Get(); }" - "\n\nprivate:\n" - "void SharedCtor();\n" - "void SharedDtor();\n" - "void SetCachedSize(int size) const$final$;\n" - "void InternalSwap($classname$* other);\n", - "classname", classname_, "final", use_final); - if (SupportsArenas(descriptor_)) { - printer->Print( - // TODO(gerbens) Make this private! Currently people are deriving from - // protos to give access to this constructor, breaking the invariants - // we rely on. - "protected:\n" - "explicit $classname$(::google::protobuf::Arena* arena);\n" - "private:\n" - "static void ArenaDtor(void* object);\n" - "inline void RegisterArenaDtor(::google::protobuf::Arena* arena);\n", - "classname", classname_); - } - - if (SupportsArenas(descriptor_)) { - printer->Print( - "private:\n" - "inline ::google::protobuf::Arena* GetArenaNoVirtual() const {\n" - " return _internal_metadata_.arena();\n" - "}\n" - "inline void* MaybeArenaPtr() const {\n" - " return _internal_metadata_.raw_arena_ptr();\n" - "}\n"); - } else { - printer->Print( - "private:\n" - "inline ::google::protobuf::Arena* GetArenaNoVirtual() const {\n" - " return NULL;\n" - "}\n" - "inline void* MaybeArenaPtr() const {\n" - " return NULL;\n" - "}\n"); - } - - printer->Print( - "public:\n" - "\n"); - - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::Metadata GetMetadata() const final;\n" - "\n"); - } else { - printer->Print( - "::std::string GetTypeName() const final;\n" - "\n"); - } - - printer->Print( - "// nested types ----------------------------------------------------\n" - "\n"); - - // Import all nested message classes into this class's scope with typedefs. - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - const Descriptor* nested_type = descriptor_->nested_type(i); - if (!IsMapEntryMessage(nested_type)) { - printer->Print("typedef $nested_full_name$ $nested_name$;\n", - "nested_name", nested_type->name(), - "nested_full_name", ClassName(nested_type, false)); - printer->Annotate("nested_full_name", nested_type); - printer->Annotate("nested_name", nested_type); - } - } - - if (descriptor_->nested_type_count() > 0) { - printer->Print("\n"); - } - - // Import all nested enums and their values into this class's scope with - // typedefs and constants. - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - enum_generators_[i]->GenerateSymbolImports(printer); - printer->Print("\n"); - } - - printer->Print( - "// accessors -------------------------------------------------------\n" - "\n"); - - // Generate accessor methods for all fields. - GenerateFieldAccessorDeclarations(printer); - - // Declare extension identifiers. - for (int i = 0; i < descriptor_->extension_count(); i++) { - extension_generators_[i]->GenerateDeclaration(printer); - } - - - printer->Print( - "// @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - - // Generate private members. - printer->Outdent(); - printer->Print(" private:\n"); - printer->Indent(); - - - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->is_repeated() && - !descriptor_->field(i)->options().weak()) { - // set_has_***() generated in all proto1/2 code and in oneofs (only) for - // messages without true field presence. - if (HasFieldPresence(descriptor_->file()) || - descriptor_->field(i)->containing_oneof()) { - printer->Print("void set_has_$name$();\n", "name", - FieldName(descriptor_->field(i))); - } - // clear_has_***() generated only for non-oneof fields - // in proto1/2. - if (!descriptor_->field(i)->containing_oneof() && - HasFieldPresence(descriptor_->file())) { - printer->Print("void clear_has_$name$();\n", "name", - FieldName(descriptor_->field(i))); - } - } - } - printer->Print("\n"); - - // Generate oneof function declarations - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "inline bool has_$oneof_name$() const;\n" - "inline void clear_has_$oneof_name$();\n\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); - } - - if (HasGeneratedMethods(descriptor_->file(), options_) && - !descriptor_->options().message_set_wire_format() && - num_required_fields_ > 1) { - printer->Print( - "// helper for ByteSizeLong()\n" - "size_t RequiredFieldsByteSizeFallback() const;\n\n"); - } - - // Prepare decls for _cached_size_ and _has_bits_. Their position in the - // output will be determined later. - - bool need_to_emit_cached_size = true; - // TODO(kenton): Make _cached_size_ an atomic when C++ supports it. - const string cached_size_decl = - "mutable ::google::protobuf::internal::CachedSize _cached_size_;\n"; - - const size_t sizeof_has_bits = HasBitsSize(); - const string has_bits_decl = sizeof_has_bits == 0 ? "" : - "::google::protobuf::internal::HasBits<" + SimpleItoa(sizeof_has_bits / 4) + - "> _has_bits_;\n"; - - // To minimize padding, data members are divided into three sections: - // (1) members assumed to align to 8 bytes - // (2) members corresponding to message fields, re-ordered to optimize - // alignment. - // (3) members assumed to align to 4 bytes. - - // Members assumed to align to 8 bytes: - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "::google::protobuf::internal::ExtensionSet _extensions_;\n" - "\n"); - } - - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;\n"); - } else { - printer->Print( - "::google::protobuf::internal::InternalMetadataWithArenaLite " - "_internal_metadata_;\n"); - } - - if (SupportsArenas(descriptor_)) { - printer->Print( - "template friend class ::google::protobuf::Arena::InternalHelper;\n" - "typedef void InternalArenaConstructable_;\n" - "typedef void DestructorSkippable_;\n"); - } - - if (HasFieldPresence(descriptor_->file())) { - // _has_bits_ is frequently accessed, so to reduce code size and improve - // speed, it should be close to the start of the object. But, try not to - // waste space:_has_bits_ by itself always makes sense if its size is a - // multiple of 8, but, otherwise, maybe _has_bits_ and cached_size_ together - // will work well. - printer->Print(has_bits_decl.c_str()); - if ((sizeof_has_bits % 8) != 0) { - printer->Print(cached_size_decl.c_str()); - need_to_emit_cached_size = false; - } - } - - // Field members: - - // Emit some private and static members - for (int i = 0; i < optimized_order_.size(); ++i) { - const FieldDescriptor* field = optimized_order_[i]; - const FieldGenerator& generator = field_generators_.get(field); - generator.GenerateStaticMembers(printer); - generator.GeneratePrivateMembers(printer); - } - - // For each oneof generate a union - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "union $camel_oneof_name$Union {\n" - // explicit empty constructor is needed when union contains - // ArenaStringPtr members for string fields. - " $camel_oneof_name$Union() {}\n", - "camel_oneof_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - field_generators_.get(descriptor_->oneof_decl(i)-> - field(j)).GeneratePrivateMembers(printer); - } - printer->Outdent(); - printer->Print( - "} $oneof_name$_;\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - field_generators_.get(descriptor_->oneof_decl(i)-> - field(j)).GenerateStaticMembers(printer); - } - } - - // Members assumed to align to 4 bytes: - - if (need_to_emit_cached_size) { - printer->Print(cached_size_decl.c_str()); - need_to_emit_cached_size = false; - } - - // Generate _oneof_case_. - if (descriptor_->oneof_decl_count() > 0) { - printer->Print(vars, - "::google::protobuf::uint32 _oneof_case_[$oneof_decl_count$];\n" - "\n"); - } - - if (num_weak_fields_) { - printer->Print( - "::google::protobuf::internal::WeakFieldMap _weak_field_map_;\n"); - } - // Generate _any_metadata_ for the Any type. - if (IsAnyMessage(descriptor_)) { - printer->Print(vars, - "::google::protobuf::internal::AnyMetadata _any_metadata_;\n"); - } - - // The TableStruct struct needs access to the private parts, in order to - // construct the offsets of all members. - printer->Print("friend struct ::$file_namespace$::TableStruct;\n", - // Vars. - "scc_name", scc_name_, "file_namespace", - FileLevelNamespace(descriptor_)); - - printer->Outdent(); - printer->Print("};"); - GOOGLE_DCHECK(!need_to_emit_cached_size); -} - -void MessageGenerator:: -GenerateInlineMethods(io::Printer* printer) { - if (IsMapEntryMessage(descriptor_)) return; - GenerateFieldAccessorDefinitions(printer); - - // Generate oneof_case() functions. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - std::map vars; - vars["class_name"] = classname_; - vars["camel_oneof_name"] = UnderscoresToCamelCase( - descriptor_->oneof_decl(i)->name(), true); - vars["oneof_name"] = descriptor_->oneof_decl(i)->name(); - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); - printer->Print( - vars, - "inline $class_name$::$camel_oneof_name$Case $class_name$::" - "$oneof_name$_case() const {\n" - " return $class_name$::$camel_oneof_name$Case(" - "_oneof_case_[$oneof_index$]);\n" - "}\n"); - } -} - -void MessageGenerator:: -GenerateExtraDefaultFields(io::Printer* printer) { - // Generate oneof default instance and weak field instances for reflection - // usage. - if (descriptor_->oneof_decl_count() > 0 || num_weak_fields_ > 0) { - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE || - (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING && - EffectiveStringCType(field) != FieldOptions::STRING)) { - printer->Print("const "); - } - field_generators_.get(field).GeneratePrivateMembers(printer); - } - } - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->options().weak()) { - printer->Print( - " const ::google::protobuf::Message* $name$_;\n", "name", FieldName(field)); - } - } - } -} - -bool MessageGenerator::GenerateParseTable(io::Printer* printer, size_t offset, - size_t aux_offset) { - if (!table_driven_) { - printer->Print("{ NULL, NULL, 0, -1, -1, -1, -1, NULL, false },\n"); - return false; - } - - std::map vars; - - vars["classname"] = ClassName(descriptor_); - vars["classtype"] = QualifiedClassName(descriptor_); - vars["offset"] = SimpleItoa(offset); - vars["aux_offset"] = SimpleItoa(aux_offset); - - int max_field_number = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (max_field_number < field->number()) { - max_field_number = field->number(); - } - } - - vars["max_field_number"] = SimpleItoa(max_field_number); - - printer->Print("{\n"); - printer->Indent(); - - printer->Print(vars, - "TableStruct::entries + $offset$,\n" - "TableStruct::aux + $aux_offset$,\n" - "$max_field_number$,\n"); - - if (!HasFieldPresence(descriptor_->file())) { - // If we don't have field presence, then _has_bits_ does not exist. - printer->Print(vars, "-1,\n"); - } else { - printer->Print(vars, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _has_bits_),\n"); - } - - if (descriptor_->oneof_decl_count() > 0) { - printer->Print(vars, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _oneof_case_),\n"); - } else { - printer->Print("-1, // no _oneof_case_\n"); - } - - if (descriptor_->extension_range_count() > 0) { - printer->Print(vars, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classtype$, " - "_extensions_),\n"); - } else { - printer->Print("-1, // no _extensions_\n"); - } - - // TODO(ckennelly): Consolidate this with the calculation for - // AuxillaryParseTableField. - vars["ns"] = Namespace(descriptor_); - - printer->Print(vars, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classtype$, _internal_metadata_),\n" - "&$ns$::_$classname$_default_instance_,\n"); - - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, "true,\n"); - } else { - printer->Print(vars, "false,\n"); - } - - printer->Outdent(); - printer->Print("},\n"); - return true; -} - -void MessageGenerator::GenerateSchema(io::Printer* printer, int offset, - int has_offset) { - std::map vars; - - vars["classname"] = QualifiedClassName(descriptor_); - vars["offset"] = SimpleItoa(offset); - vars["has_bits_offsets"] = - HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_) - ? SimpleItoa(offset + has_offset) - : "-1"; - - printer->Print(vars, - "{ $offset$, $has_bits_offsets$, sizeof($classname$)},\n"); -} - -namespace { - -// TODO(gerbens) remove this after the next sync with GitHub code base. -// Then the opensource testing has gained the functionality to compile -// the CalcFieldNum given the symbols defined in generated-message-util. -#ifdef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP -// We need a clean version of CalcFieldNum that doesn't use new functionality -// in the runtime, because this functionality is not yet in the opensource -// runtime - -uint32 CalculateType(uint32 type, uint32 type_class) { - return (type - 1) + type_class * 20; -} - -uint32 CalcFieldNum(const FieldGenerator&, const FieldDescriptor* field, - const Options& options) { - bool is_a_map = IsMapEntryMessage(field->containing_type()); - int type = field->type(); - if (field->containing_oneof()) { - return CalculateType(type, 4); - } - if (field->is_packed()) { - return CalculateType(type, 3); - } else if (field->is_repeated()) { - return CalculateType(type, 2); - } else if (!HasFieldPresence(field->file()) && - field->containing_oneof() == NULL && !is_a_map) { - return CalculateType(type, 1); - } else { - return CalculateType(type, 0); - } -} - -#else -// We need to calculate for each field what function the table driven code -// should use to serialize it. This returns the index in a lookup table. -uint32 CalcFieldNum(const FieldGenerator& generator, - const FieldDescriptor* field, const Options& options) { - bool is_a_map = IsMapEntryMessage(field->containing_type()); - int type = field->type(); - if (type == FieldDescriptor::TYPE_STRING || - type == FieldDescriptor::TYPE_BYTES) { - if (generator.IsInlined()) { - type = internal::FieldMetadata::kInlinedType; - } - } - if (field->containing_oneof()) { - return internal::FieldMetadata::CalculateType( - type, internal::FieldMetadata::kOneOf); - } - if (field->is_packed()) { - return internal::FieldMetadata::CalculateType( - type, internal::FieldMetadata::kPacked); - } else if (field->is_repeated()) { - return internal::FieldMetadata::CalculateType( - type, internal::FieldMetadata::kRepeated); - } else if (!HasFieldPresence(field->file()) && - field->containing_oneof() == NULL && !is_a_map) { - return internal::FieldMetadata::CalculateType( - type, internal::FieldMetadata::kNoPresence); - } else { - return internal::FieldMetadata::CalculateType( - type, internal::FieldMetadata::kPresence); - } -} -#endif - -int FindMessageIndexInFile(const Descriptor* descriptor) { - std::vector flatten = - FlattenMessagesInFile(descriptor->file()); - return std::find(flatten.begin(), flatten.end(), descriptor) - - flatten.begin(); -} - -} // namespace - -int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) { - if (!options_.table_driven_serialization) { - return 0; - } - - string full_classname = QualifiedClassName(descriptor_); - - std::vector sorted = SortFieldsByNumber(descriptor_); - if (IsMapEntryMessage(descriptor_)) { - for (int i = 0; i < 2; i++) { - const FieldDescriptor* field = sorted[i]; - const FieldGenerator& generator = field_generators_.get(field); - - uint32 tag = internal::WireFormatLite::MakeTag( - field->number(), WireFormat::WireTypeForFieldType(field->type())); - - std::map vars; - vars["classname"] = QualifiedClassName(descriptor_); - vars["field_name"] = FieldName(field); - vars["tag"] = SimpleItoa(tag); - vars["hasbit"] = SimpleItoa(i); - vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_)); - vars["ptr"] = "NULL"; - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - GOOGLE_CHECK(!IsMapEntryMessage(field->message_type())); - { - vars["ptr"] = - "::" + FileLevelNamespace(field->message_type()) + - "::TableStruct::serialization_table + " + - SimpleItoa(FindMessageIndexInFile(field->message_type())); - } - } - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(" - "::google::protobuf::internal::MapEntryHelper<$classname$::" - "SuperType>, $field_name$_), $tag$," - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(" - "::google::protobuf::internal::MapEntryHelper<$classname$::" - "SuperType>, _has_bits_) * 8 + $hasbit$, $type$, " - "$ptr$},\n"); - } - return 2; - } - printer->Print( - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_cached_size_), 0, 0, 0, NULL},\n", - "classname", full_classname); - std::vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); - } - std::sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeSorter()); - for (int i = 0, extension_idx = 0; /* no range */; i++) { - for (; extension_idx < sorted_extensions.size() && - (i == sorted.size() || - sorted_extensions[extension_idx]->start < sorted[i]->number()); - extension_idx++) { - const Descriptor::ExtensionRange* range = - sorted_extensions[extension_idx]; - printer->Print( - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_extensions_), $start$, $end$, " - "::google::protobuf::internal::FieldMetadata::kSpecial, " - "reinterpret_cast(::google::protobuf::internal::ExtensionSerializer)},\n", - "classname", full_classname, "start", SimpleItoa(range->start), "end", - SimpleItoa(range->end)); - } - if (i == sorted.size()) break; - const FieldDescriptor* field = sorted[i]; - - uint32 tag = internal::WireFormatLite::MakeTag( - field->number(), WireFormat::WireTypeForFieldType(field->type())); - if (field->is_packed()) { - tag = internal::WireFormatLite::MakeTag( - field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - } - - string classfieldname = FieldName(field); - if (field->containing_oneof()) { - classfieldname = field->containing_oneof()->name(); - } - std::map vars; - vars["classname"] = full_classname; - vars["field_name"] = classfieldname; - vars["tag"] = SimpleItoa(tag); - vars["ptr"] = "NULL"; - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (IsMapEntryMessage(field->message_type())) { - vars["idx"] = SimpleItoa(FindMessageIndexInFile(field->message_type())); - vars["fieldclassname"] = QualifiedClassName(field->message_type()); - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, $field_name$_), $tag$, $idx$, " - "::google::protobuf::internal::FieldMetadata::kSpecial, " - "reinterpret_cast(static_cast< " - "::google::protobuf::internal::SpecialSerializer>(" - "::google::protobuf::internal::MapFieldSerializer< " - "::google::protobuf::internal::MapEntryToMapField<" - "$fieldclassname$>::MapFieldType, " - "TableStruct::serialization_table>))},\n"); - continue; - } else { - vars["ptr"] = - "::" + FileLevelNamespace(field->message_type()) + - "::TableStruct::serialization_table + " + - SimpleItoa(FindMessageIndexInFile(field->message_type())); - } - } - - const FieldGenerator& generator = field_generators_.get(field); - vars["type"] = SimpleItoa(CalcFieldNum(generator, field, options_)); - - - if (field->options().weak()) { - // TODO(gerbens) merge weak fields into ranges - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, _weak_field_map_), $tag$, $tag$, " - "::google::protobuf::internal::FieldMetadata::kSpecial, " - "reinterpret_cast(::google::protobuf::internal::WeakFieldSerializer)},\n"); - } else if (field->containing_oneof()) { - vars["oneofoffset"] = - SimpleItoa(sizeof(uint32) * field->containing_oneof()->index()); - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, $field_name$_), $tag$, " - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, _oneof_case_) + $oneofoffset$, " - "$type$, $ptr$},\n"); - } else if (HasFieldPresence(descriptor_->file()) && - has_bit_indices_[field->index()] != -1) { - vars["hasbitsoffset"] = SimpleItoa(has_bit_indices_[field->index()]); - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, $field_name$_), $tag$, " - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, _has_bits_) * 8 + $hasbitsoffset$, $type$, " - "$ptr$},\n"); - } else { - printer->Print(vars, - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($" - "classname$, $field_name$_), $tag$, ~0u, $type$, " - "$ptr$},\n"); - } - } - int num_field_metadata = 1 + sorted.size() + sorted_extensions.size(); - num_field_metadata++; - string serializer = UseUnknownFieldSet(descriptor_->file(), options_) - ? "::google::protobuf::internal::UnknownFieldSetSerializer" - : "::google::protobuf::internal::UnknownFieldSerializerLite"; - printer->Print( - "{GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_internal_metadata_), 0, ~0u, " - "::google::protobuf::internal::FieldMetadata::kSpecial, reinterpret_cast($serializer$)},\n", - "classname", full_classname, "serializer", serializer); - return num_field_metadata; -} - -void MessageGenerator::GenerateFieldDefaultInstances(io::Printer* printer) { - // Construct the default instances for all fields that need one. - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)) - .GenerateDefaultInstanceAllocator(printer); - } -} - -void MessageGenerator:: -GenerateDefaultInstanceInitializer(io::Printer* printer) { - // The default instance needs all of its embedded message pointers - // cross-linked to other default instances. We can't do this initialization - // in the constructor because some other default instances may not have been - // constructed yet at that time. - // TODO(kenton): Maybe all message fields (even for non-default messages) - // should be initialized to point at default instances rather than NULL? - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - if (!field->is_repeated() && - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - (field->containing_oneof() == NULL || - HasDescriptorMethods(descriptor_->file(), options_))) { - string name; - if (field->containing_oneof() || field->options().weak()) { - name = "_" + classname_ + "_default_instance_."; - } else { - name = - "_" + classname_ + "_default_instance_._instance.get_mutable()->"; - } - name += FieldName(field); - printer->Print( - "$ns$::$name$_ = const_cast< $type$*>(\n" - " $type$::internal_default_instance());\n", - // Vars. - "name", name, "type", FieldMessageTypeName(field), "ns", - Namespace(descriptor_)); - } else if (field->containing_oneof() && - HasDescriptorMethods(descriptor_->file(), options_)) { - field_generators_.get(descriptor_->field(i)) - .GenerateConstructorCode(printer); - } - } -} - -void MessageGenerator:: -GenerateClassMethods(io::Printer* printer) { - if (IsMapEntryMessage(descriptor_)) { - printer->Print( - "$classname$::$classname$() {}\n" - "$classname$::$classname$(::google::protobuf::Arena* arena) : " - "SuperType(arena) {}\n" - "void $classname$::MergeFrom(const $classname$& other) {\n" - " MergeFromInternal(other);\n" - "}\n", - "classname", classname_); - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::Metadata $classname$::GetMetadata() const {\n" - " ::$file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return ::$file_namespace$::file_level_metadata[$index$];\n" - "}\n" - "void $classname$::MergeFrom(\n" - " const ::google::protobuf::Message& other) {\n" - " ::google::protobuf::Message::MergeFrom(other);\n" - "}\n" - "\n", - "file_namespace", FileLevelNamespace(descriptor_), - "classname", classname_, "index", - SimpleItoa(index_in_file_messages_)); - } - return; - } - - // TODO(gerbens) Remove this function. With a little bit of cleanup and - // refactoring this is superfluous. - printer->Print("void $classname$::InitAsDefaultInstance() {\n", "classname", - classname_); - printer->Indent(); - GenerateDefaultInstanceInitializer(printer); - printer->Outdent(); - printer->Print("}\n"); - - if (IsAnyMessage(descriptor_)) { - printer->Print( - "void $classname$::PackFrom(const ::google::protobuf::Message& message) {\n" - " _any_metadata_.PackFrom(message);\n" - "}\n" - "\n" - "void $classname$::PackFrom(const ::google::protobuf::Message& message,\n" - " const ::std::string& type_url_prefix) {\n" - " _any_metadata_.PackFrom(message, type_url_prefix);\n" - "}\n" - "\n" - "bool $classname$::UnpackTo(::google::protobuf::Message* message) const {\n" - " return _any_metadata_.UnpackTo(message);\n" - "}\n" - "bool $classname$::ParseAnyTypeUrl(const string& type_url,\n" - " string* full_type_name) {\n" - " return ::google::protobuf::internal::ParseAnyTypeUrl(type_url,\n" - " full_type_name);\n" - "}\n" - "\n", - "classname", classname_); - } - - // Generate non-inline field definitions. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - field_generators_.get(field) - .GenerateNonInlineAccessorDefinitions(printer); - if (IsCrossFileMaybeMap(field)) { - std::map vars; - SetCommonFieldVariables(field, &vars, options_); - if (field->containing_oneof()) { - SetCommonOneofFieldVariables(field, &vars); - } - GenerateFieldClear(field, vars, false, printer); - } - } - - // Generate field number constants. - printer->Print("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor *field = descriptor_->field(i); - printer->Print( - "const int $classname$::$constant_name$;\n", - "classname", ClassName(FieldScope(field), false), - "constant_name", FieldConstantName(field)); - } - printer->Print( - "#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n" - "\n"); - - GenerateStructors(printer); - printer->Print("\n"); - - if (descriptor_->oneof_decl_count() > 0) { - GenerateOneofClear(printer); - printer->Print("\n"); - } - - if (HasGeneratedMethods(descriptor_->file(), options_)) { - GenerateClear(printer); - printer->Print("\n"); - - GenerateMergeFromCodedStream(printer); - printer->Print("\n"); - - GenerateSerializeWithCachedSizes(printer); - printer->Print("\n"); - - if (HasFastArraySerialization(descriptor_->file(), options_)) { - GenerateSerializeWithCachedSizesToArray(printer); - printer->Print("\n"); - } - - GenerateByteSize(printer); - printer->Print("\n"); - - GenerateMergeFrom(printer); - printer->Print("\n"); - - GenerateCopyFrom(printer); - printer->Print("\n"); - - GenerateIsInitialized(printer); - printer->Print("\n"); - } - - GenerateSwap(printer); - printer->Print("\n"); - - if (options_.table_driven_serialization) { - printer->Print( - "const void* $classname$::InternalGetTable() const {\n" - " return ::$file_namespace$::TableStruct::serialization_table + " - "$index$;\n" - "}\n" - "\n", - "classname", classname_, "index", SimpleItoa(index_in_file_messages_), - "file_namespace", FileLevelNamespace(descriptor_)); - } - if (HasDescriptorMethods(descriptor_->file(), options_)) { - printer->Print( - "::google::protobuf::Metadata $classname$::GetMetadata() const {\n" - " $file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return ::" - "$file_namespace$::file_level_metadata[kIndexInFileMessages];\n" - "}\n" - "\n", - "classname", classname_, "file_namespace", - FileLevelNamespace(descriptor_)); - } else { - printer->Print( - "::std::string $classname$::GetTypeName() const {\n" - " return \"$type_name$\";\n" - "}\n" - "\n", - "classname", classname_, - "type_name", descriptor_->full_name()); - } - -} - -size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) { - if (!table_driven_) { - return 0; - } - - // Field "0" is special: We use it in our switch statement of processing - // types to handle the successful end tag case. - printer->Print("{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},\n"); - int last_field_number = 1; - - std::vector ordered_fields = - SortFieldsByNumber(descriptor_); - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = ordered_fields[i]; - GOOGLE_CHECK_GE(field->number(), last_field_number); - - for (; last_field_number < field->number(); last_field_number++) { - printer->Print( - "{ 0, 0, ::google::protobuf::internal::kInvalidMask,\n" - " ::google::protobuf::internal::kInvalidMask, 0, 0 },\n"); - } - last_field_number++; - - unsigned char normal_wiretype, packed_wiretype, processing_type; - normal_wiretype = WireFormat::WireTypeForFieldType(field->type()); - - if (field->is_packable()) { - packed_wiretype = WireFormatLite::WIRETYPE_LENGTH_DELIMITED; - } else { - packed_wiretype = internal::kNotPackedMask; - } - - processing_type = static_cast(field->type()); - const FieldGenerator& generator = field_generators_.get(field); - if (field->type() == FieldDescriptor::TYPE_STRING) { - switch (EffectiveStringCType(field)) { - case FieldOptions::STRING: - default: { - if (generator.IsInlined()) { - processing_type = internal::TYPE_STRING_INLINED; - break; - } - break; - } - } - } else if (field->type() == FieldDescriptor::TYPE_BYTES) { - switch (EffectiveStringCType(field)) { - case FieldOptions::STRING: - default: - if (generator.IsInlined()) { - processing_type = internal::TYPE_BYTES_INLINED; - break; - } - break; - } - } - - processing_type |= static_cast( - field->is_repeated() ? internal::kRepeatedMask : 0); - processing_type |= static_cast( - field->containing_oneof() ? internal::kOneofMask : 0); - - if (field->is_map()) { - processing_type = internal::TYPE_MAP; - } - - const unsigned char tag_size = - WireFormat::TagSize(field->number(), field->type()); - - std::map vars; - vars["classname"] = QualifiedClassName(descriptor_); - if (field->containing_oneof() != NULL) { - vars["name"] = field->containing_oneof()->name(); - vars["presence"] = SimpleItoa(field->containing_oneof()->index()); - } else { - vars["name"] = FieldName(field); - vars["presence"] = SimpleItoa(has_bit_indices_[field->index()]); - } - vars["nwtype"] = SimpleItoa(normal_wiretype); - vars["pwtype"] = SimpleItoa(packed_wiretype); - vars["ptype"] = SimpleItoa(processing_type); - vars["tag_size"] = SimpleItoa(tag_size); - - printer->Print(vars, - "{\n" - " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(\n" - " $classname$, $name$_),\n" - " static_cast<::google::protobuf::uint32>($presence$),\n" - " $nwtype$, $pwtype$, $ptype$, $tag_size$\n" - "},\n"); - } - - return last_field_number; -} - -size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) { - if (!table_driven_) { - return 0; - } - - std::vector ordered_fields = - SortFieldsByNumber(descriptor_); - - printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n"); - int last_field_number = 1; - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = ordered_fields[i]; - - GOOGLE_CHECK_GE(field->number(), last_field_number); - for (; last_field_number < field->number(); last_field_number++) { - printer->Print("::google::protobuf::internal::AuxillaryParseTableField(),\n"); - } - - std::map vars; - SetCommonFieldVariables(field, &vars, options_); - - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_ENUM: - vars["type"] = ClassName(field->enum_type(), true); - printer->Print( - vars, - "{::google::protobuf::internal::AuxillaryParseTableField::enum_aux{" - "$type$_IsValid}},\n"); - last_field_number++; - break; - case FieldDescriptor::CPPTYPE_MESSAGE: { - if (field->is_map()) { - vars["classname"] = QualifiedClassName(field->message_type()); - printer->Print(vars, - "{::google::protobuf::internal::AuxillaryParseTableField::map_" - "aux{&::google::protobuf::internal::ParseMap<$classname$>}},\n"); - last_field_number++; - break; - } else { - vars["classname"] = ClassName(field->message_type(), false); - } - vars["ns"] = Namespace(field->message_type()); - vars["type"] = FieldMessageTypeName(field); - vars["file_namespace"] = - FileLevelNamespace(field->message_type()); - - printer->Print( - vars, - "{::google::protobuf::internal::AuxillaryParseTableField::message_aux{\n" - " &$ns$::_$classname$_default_instance_}},\n"); - last_field_number++; - break; - } - case FieldDescriptor::CPPTYPE_STRING: - switch (EffectiveStringCType(field)) { - case FieldOptions::STRING: - vars["default"] = - field->default_value_string().empty() - ? "&::google::protobuf::internal::fixed_address_empty_string" - : "&" + Namespace(field) + " ::" + classname_ + - "::" + MakeDefaultName(field); - break; - case FieldOptions::CORD: - case FieldOptions::STRING_PIECE: - vars["default"] = - "\"" + CEscape(field->default_value_string()) + "\""; - break; - } - vars["full_name"] = field->full_name(); - printer->Print(vars, - "{::google::protobuf::internal::AuxillaryParseTableField::string_aux{\n" - " $default$,\n" - " \"$full_name$\"\n" - "}},\n"); - last_field_number++; - break; - default: - break; - } - } - - return last_field_number; -} - -std::pair MessageGenerator::GenerateOffsets( - io::Printer* printer) { - std::map variables; - string full_classname = QualifiedClassName(descriptor_); - variables["classname"] = full_classname; - - if (HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)) { - printer->Print( - variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_has_bits_),\n"); - } else { - printer->Print("~0u, // no _has_bits_\n"); - } - printer->Print(variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_internal_metadata_),\n"); - if (descriptor_->extension_range_count() > 0) { - printer->Print( - variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, " - "_extensions_),\n"); - } else { - printer->Print("~0u, // no _extensions_\n"); - } - if (descriptor_->oneof_decl_count() > 0) { - printer->Print(variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(" - "$classname$, _oneof_case_[0]),\n"); - } else { - printer->Print("~0u, // no _oneof_case_\n"); - } - if (num_weak_fields_ > 0) { - printer->Print(variables, - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$," - " _weak_field_map_),\n"); - } else { - printer->Print("~0u, // no _weak_field_map_\n"); - } - const int kNumGenericOffsets = 5; // the number of fixed offsets above - const size_t offsets = kNumGenericOffsets + - descriptor_->field_count() + - descriptor_->oneof_decl_count(); - size_t entries = offsets; - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->containing_oneof() || field->options().weak()) { - printer->Print("offsetof($classname$DefaultTypeInternal, $name$_)", - "classname", full_classname, "name", FieldName(field)); - } else { - printer->Print( - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_)", - "classname", full_classname, "name", FieldName(field)); - } - - uint32 tag = field_generators_.get(field).CalculateFieldTag(); - if (tag != 0) { - printer->Print(" | $tag$", "tag", SimpleItoa(tag)); - } - - printer->Print(",\n"); - } - - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = descriptor_->oneof_decl(i); - printer->Print( - "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n", - "classname", full_classname, "name", oneof->name()); - } - - if (IsMapEntryMessage(descriptor_)) { - entries += 2; - printer->Print( - "0,\n" - "1,\n"); - } else if (HasFieldPresence(descriptor_->file())) { - entries += has_bit_indices_.size(); - for (int i = 0; i < has_bit_indices_.size(); i++) { - const string index = has_bit_indices_[i] >= 0 ? - SimpleItoa(has_bit_indices_[i]) : "~0u"; - printer->Print("$index$,\n", "index", index); - } - } - - return std::make_pair(entries, offsets); -} - -void MessageGenerator:: -GenerateSharedConstructorCode(io::Printer* printer) { - printer->Print( - "void $classname$::SharedCtor() {\n", - "classname", classname_); - printer->Indent(); - - std::vector processed(optimized_order_.size(), false); - GenerateConstructorBody(printer, processed, false); - - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "clear_has_$oneof_name$();\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); - } - - printer->Outdent(); - printer->Print("}\n\n"); -} - -void MessageGenerator:: -GenerateSharedDestructorCode(io::Printer* printer) { - printer->Print( - "void $classname$::SharedDtor() {\n", - "classname", classname_); - printer->Indent(); - if (SupportsArenas(descriptor_)) { - printer->Print( - "GOOGLE_DCHECK(GetArenaNoVirtual() == NULL);\n"); - } - // Write the destructors for each field except oneof members. - // optimized_order_ does not contain oneof fields. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - field_generators_.get(field).GenerateDestructorCode(printer); - } - - // Generate code to destruct oneofs. Clearing should do the work. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "if (has_$oneof_name$()) {\n" - " clear_$oneof_name$();\n" - "}\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); - } - - if (num_weak_fields_) { - printer->Print("_weak_field_map_.ClearAll();\n"); - } - printer->Outdent(); - printer->Print( - "}\n" - "\n"); -} - -void MessageGenerator:: -GenerateArenaDestructorCode(io::Printer* printer) { - // Generate the ArenaDtor() method. Track whether any fields actually produced - // code that needs to be called. - printer->Print( - "void $classname$::ArenaDtor(void* object) {\n", - "classname", classname_); - printer->Indent(); - - // This code is placed inside a static method, rather than an ordinary one, - // since that simplifies Arena's destructor list (ordinary function pointers - // rather than member function pointers). _this is the object being - // destructed. - printer->Print( - "$classname$* _this = reinterpret_cast< $classname$* >(object);\n" - // avoid an "unused variable" warning in case no fields have dtor code. - "(void)_this;\n", - "classname", classname_); - - bool need_registration = false; - // Process non-oneof fields first. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (field_generators_.get(field) - .GenerateArenaDestructorCode(printer)) { - need_registration = true; - } - } - - // Process oneof fields. - // - // Note: As of 10/5/2016, GenerateArenaDestructorCode does not emit anything - // and returns false for oneof fields. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = descriptor_->oneof_decl(i); - - for (int j = 0; j < oneof->field_count(); j++) { - const FieldDescriptor* field = oneof->field(j); - if (field_generators_.get(field) - .GenerateArenaDestructorCode(printer)) { - need_registration = true; - } - } - } - if (num_weak_fields_) { - // _this is the object being destructed (we are inside a static method - // here). - printer->Print("_this->_weak_field_map_.ClearAll();\n"); - need_registration = true; - } - - printer->Outdent(); - printer->Print( - "}\n"); - - if (need_registration) { - printer->Print( - "inline void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n" - " if (arena != NULL) {\n" - " arena->OwnCustomDestructor(this, &$classname$::ArenaDtor);\n" - " }\n" - "}\n", - "classname", classname_); - } else { - printer->Print( - "void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n" - "}\n", - "classname", classname_); - } -} - -void MessageGenerator::GenerateConstructorBody(io::Printer* printer, - std::vector processed, - bool copy_constructor) const { - const FieldDescriptor* last_start = NULL; - // RunMap maps from fields that start each run to the number of fields in that - // run. This is optimized for the common case that there are very few runs in - // a message and that most of the eligible fields appear together. - typedef hash_map RunMap; - RunMap runs; - - for (int i = 0; i < optimized_order_.size(); ++i) { - const FieldDescriptor* field = optimized_order_[i]; - if ((copy_constructor && IsPOD(field)) || - (!copy_constructor && CanConstructByZeroing(field, options_))) { - if (last_start == NULL) { - last_start = field; - } - - runs[last_start]++; - } else { - last_start = NULL; - } - } - - string pod_template; - if (copy_constructor) { - pod_template = - "::memcpy(&$first$_, &from.$first$_,\n" - " static_cast(reinterpret_cast(&$last$_) -\n" - " reinterpret_cast(&$first$_)) + sizeof($last$_));\n"; - } else { - pod_template = - "::memset(&$first$_, 0, static_cast(\n" - " reinterpret_cast(&$last$_) -\n" - " reinterpret_cast(&$first$_)) + sizeof($last$_));\n"; - } - - for (int i = 0; i < optimized_order_.size(); ++i) { - if (processed[i]) { - continue; - } - - const FieldDescriptor* field = optimized_order_[i]; - RunMap::const_iterator it = runs.find(field); - - // We only apply the memset technique to runs of more than one field, as - // assignment is better than memset for generated code clarity. - if (it != runs.end() && it->second > 1) { - // Use a memset, then skip run_length fields. - const size_t run_length = it->second; - const string first_field_name = FieldName(field); - const string last_field_name = - FieldName(optimized_order_[i + run_length - 1]); - - printer->Print(pod_template.c_str(), - "first", first_field_name, - "last", last_field_name); - - i += run_length - 1; - // ++i at the top of the loop. - } else { - if (copy_constructor) { - field_generators_.get(field).GenerateCopyConstructorCode(printer); - } else { - field_generators_.get(field).GenerateConstructorCode(printer); - } - } - } -} - -void MessageGenerator:: -GenerateStructors(io::Printer* printer) { - string superclass; - superclass = SuperClassName(descriptor_, options_); - string initializer_with_arena = superclass + "()"; - - if (descriptor_->extension_range_count() > 0) { - initializer_with_arena += ",\n _extensions_(arena)"; - } - - initializer_with_arena += ",\n _internal_metadata_(arena)"; - - // Initialize member variables with arena constructor. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - - bool has_arena_constructor = field->is_repeated(); - if (has_arena_constructor) { - initializer_with_arena += string(",\n ") + - FieldName(field) + string("_(arena)"); - } - } - - if (IsAnyMessage(descriptor_)) { - initializer_with_arena += ",\n _any_metadata_(&type_url_, &value_)"; - } - if (num_weak_fields_ > 0) { - initializer_with_arena += ", _weak_field_map_(arena)"; - } - - string initializer_null = superclass + "(), _internal_metadata_(NULL)"; - if (IsAnyMessage(descriptor_)) { - initializer_null += ", _any_metadata_(&type_url_, &value_)"; - } - if (num_weak_fields_ > 0) { - initializer_null += ", _weak_field_map_(nullptr)"; - } - - printer->Print( - "$classname$::$classname$()\n" - " : $initializer$ {\n" - " ::google::protobuf::internal::InitSCC(\n" - " &$file_namespace$::scc_info_$scc_name$.base);\n" - " SharedCtor();\n" - " // @@protoc_insertion_point(constructor:$full_name$)\n" - "}\n", - "classname", classname_, "full_name", descriptor_->full_name(), - "scc_name", scc_name_, "initializer", initializer_null, "file_namespace", - FileLevelNamespace(descriptor_)); - - if (SupportsArenas(descriptor_)) { - printer->Print( - "$classname$::$classname$(::google::protobuf::Arena* arena)\n" - " : $initializer$ {\n" - " " - "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$." - "base);\n" - " SharedCtor();\n" - " RegisterArenaDtor(arena);\n" - " // @@protoc_insertion_point(arena_constructor:$full_name$)\n" - "}\n", - "initializer", initializer_with_arena, "classname", classname_, - "superclass", superclass, "full_name", descriptor_->full_name(), - "scc_name", scc_name_, "file_namespace", - FileLevelNamespace(descriptor_)); - } - - // Generate the copy constructor. - if (UsingImplicitWeakFields(descriptor_->file(), options_)) { - // If we are in lite mode and using implicit weak fields, we generate a - // one-liner copy constructor that delegates to MergeFrom. This saves some - // code size and also cuts down on the complexity of implicit weak fields. - // We might eventually want to do this for all lite protos. - printer->Print( - "$classname$::$classname$(const $classname$& from)\n" - " : $classname$() {\n" - " MergeFrom(from);\n" - "}\n", - "classname", classname_); - } else { - printer->Print( - "$classname$::$classname$(const $classname$& from)\n" - " : $superclass$()", - "classname", classname_, - "superclass", superclass, - "full_name", descriptor_->full_name()); - printer->Indent(); - printer->Indent(); - printer->Indent(); - - printer->Print( - ",\n_internal_metadata_(NULL)"); - - if (HasFieldPresence(descriptor_->file())) { - printer->Print(",\n_has_bits_(from._has_bits_)"); - } - - std::vector processed(optimized_order_.size(), false); - for (int i = 0; i < optimized_order_.size(); ++i) { - const FieldDescriptor* field = optimized_order_[i]; - - if (!(field->is_repeated() && !(field->is_map())) - ) { - continue; - } - - processed[i] = true; - printer->Print(",\n$name$_(from.$name$_)", - "name", FieldName(field)); - } - - if (IsAnyMessage(descriptor_)) { - printer->Print(",\n_any_metadata_(&type_url_, &value_)"); - } - if (num_weak_fields_ > 0) { - printer->Print(",\n_weak_field_map_(from._weak_field_map_)"); - } - - printer->Outdent(); - printer->Outdent(); - printer->Print(" {\n"); - - printer->Print( - "_internal_metadata_.MergeFrom(from._internal_metadata_);\n"); - - if (descriptor_->extension_range_count() > 0) { - printer->Print("_extensions_.MergeFrom(from._extensions_);\n"); - } - - GenerateConstructorBody(printer, processed, true); - - // Copy oneof fields. Oneof field requires oneof case check. - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - printer->Print( - "clear_has_$oneofname$();\n" - "switch (from.$oneofname$_case()) {\n", - "oneofname", descriptor_->oneof_decl(i)->name()); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); - field_generators_.get(field).GenerateMergingCode(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); - } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " break;\n" - "}\n", - "oneof_index", - SimpleItoa(descriptor_->oneof_decl(i)->index()), - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "}\n"); - } - - printer->Outdent(); - printer->Print( - " // @@protoc_insertion_point(copy_constructor:$full_name$)\n" - "}\n" - "\n", - "full_name", descriptor_->full_name()); - } - - // Generate the shared constructor code. - GenerateSharedConstructorCode(printer); - - // Generate the destructor. - printer->Print( - "$classname$::~$classname$() {\n" - " // @@protoc_insertion_point(destructor:$full_name$)\n" - " SharedDtor();\n" - "}\n" - "\n", - "classname", classname_, - "full_name", descriptor_->full_name()); - - // Generate the shared destructor code. - GenerateSharedDestructorCode(printer); - - // Generate the arena-specific destructor code. - if (SupportsArenas(descriptor_)) { - GenerateArenaDestructorCode(printer); - } - - // Generate SetCachedSize. - printer->Print( - "void $classname$::SetCachedSize(int size) const {\n" - " _cached_size_.Set(size);\n" - "}\n", - "classname", classname_); - - // Only generate this member if it's not disabled. - if (HasDescriptorMethods(descriptor_->file(), options_) && - !descriptor_->options().no_standard_descriptor_accessor()) { - printer->Print( - "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n" - " ::$file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return ::" - "$file_namespace$::file_level_metadata[kIndexInFileMessages]." - "descriptor;\n" - "}\n" - "\n", - "classname", classname_, "file_namespace", - FileLevelNamespace(descriptor_)); - } - - printer->Print( - "const $classname$& $classname$::default_instance() {\n" - " " - "::google::protobuf::internal::InitSCC(&$file_namespace$::scc_info_$scc_name$.base)" - ";\n" - " return *internal_default_instance();\n" - "}\n\n", - "classname", classname_, "scc_name", scc_name_, "file_namespace", - FileLevelNamespace(descriptor_)); -} - -void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) { - printer->Print( - "template<> " - "GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE " - "$classname$* Arena::CreateMaybeMessage< $classname$ >(Arena* arena) {\n" - " return Arena::$create_func$Internal< $classname$ >(arena);\n" - "}\n", - "classname", QualifiedClassName(descriptor_), - "create_func", MessageCreateFunction(descriptor_)); -} - -// Return the number of bits set in n, a non-negative integer. -static int popcnt(uint32 n) { - int result = 0; - while (n != 0) { - result += (n & 1); - n = n / 2; - } - return result; -} - -bool MessageGenerator::MaybeGenerateOptionalFieldCondition( - io::Printer* printer, const FieldDescriptor* field, - int expected_has_bits_index) { - int has_bit_index = has_bit_indices_[field->index()]; - if (!field->options().weak() && - expected_has_bits_index == has_bit_index / 32) { - const string mask = - StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8)); - printer->Print( - "if (cached_has_bits & 0x$mask$u) {\n", - "mask", mask); - return true; - } - return false; -} - -void MessageGenerator:: -GenerateClear(io::Printer* printer) { - // Performance tuning parameters - const int kMaxUnconditionalPrimitiveBytesClear = 4; - - printer->Print( - "void $classname$::Clear() {\n" - "// @@protoc_insertion_point(message_clear_start:$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - - printer->Print( - // TODO(jwb): It would be better to avoid emitting this if it is not used, - // rather than emitting a workaround for the resulting warning. - "::google::protobuf::uint32 cached_has_bits = 0;\n" - "// Prevent compiler warnings about cached_has_bits being unused\n" - "(void) cached_has_bits;\n\n"); - - int cached_has_bit_index = -1; - - // Step 1: Extensions - if (descriptor_->extension_range_count() > 0) { - printer->Print("_extensions_.Clear();\n"); - } - - int unconditional_budget = kMaxUnconditionalPrimitiveBytesClear; - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - - if (!CanInitializeByZeroing(field)) { - continue; - } - - unconditional_budget -= EstimateAlignmentSize(field); - } - - std::vector > chunks_frag = CollectFields( - optimized_order_, - MatchRepeatedAndHasByteAndZeroInits( - &has_bit_indices_, HasFieldPresence(descriptor_->file()))); - - // Merge next non-zero initializable chunk if it has the same has_byte index - // and not meeting unconditional clear condition. - std::vector > chunks; - if (!HasFieldPresence(descriptor_->file())) { - // Don't bother with merging without has_bit field. - chunks = chunks_frag; - } else { - // Note that only the next chunk is considered for merging. - for (int i = 0; i < chunks_frag.size(); i++) { - chunks.push_back(chunks_frag[i]); - const FieldDescriptor* field = chunks_frag[i].front(); - const FieldDescriptor* next_field = - (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : nullptr; - if (CanInitializeByZeroing(field) && - (chunks_frag[i].size() == 1 || unconditional_budget < 0) && - next_field != nullptr && - has_bit_indices_[field->index()] / 8 == - has_bit_indices_[next_field->index()] / 8) { - GOOGLE_CHECK(!CanInitializeByZeroing(next_field)); - // Insert next chunk to the current one and skip next chunk. - chunks.back().insert(chunks.back().end(), chunks_frag[i + 1].begin(), - chunks_frag[i + 1].end()); - i++; - } - } - } - - for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { - std::vector& chunk = chunks[chunk_index]; - GOOGLE_CHECK(!chunk.empty()); - - // Step 2: Repeated fields don't use _has_bits_; emit code to clear them - // here. - if (chunk.front()->is_repeated()) { - for (int i = 0; i < chunk.size(); i++) { - const FieldDescriptor* field = chunk[i]; - const FieldGenerator& generator = field_generators_.get(field); - - generator.GenerateMessageClearingCode(printer); - } - continue; - } - - // Step 3: Non-repeated fields that can be cleared by memset-to-0, then - // non-repeated, non-zero initializable fields. - int last_chunk = HasFieldPresence(descriptor_->file()) - ? has_bit_indices_[chunk.front()->index()] / 8 - : 0; - int last_chunk_start = 0; - int memset_run_start = -1; - int memset_run_end = -1; - - for (int i = 0; i < chunk.size(); i++) { - const FieldDescriptor* field = chunk[i]; - if (CanInitializeByZeroing(field)) { - if (memset_run_start == -1) { - memset_run_start = i; - } - memset_run_end = i; - } - } - - const bool have_outer_if = - HasFieldPresence(descriptor_->file()) && chunk.size() > 1 && - (memset_run_end != chunk.size() - 1 || unconditional_budget < 0); - - if (have_outer_if) { - uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_); - const int count = popcnt(last_chunk_mask); - - // Check (up to) 8 has_bits at a time if we have more than one field in - // this chunk. Due to field layout ordering, we may check - // _has_bits_[last_chunk * 8 / 32] multiple times. - GOOGLE_DCHECK_LE(2, count); - GOOGLE_DCHECK_GE(8, count); - - if (cached_has_bit_index != last_chunk / 4) { - cached_has_bit_index = last_chunk / 4; - printer->Print("cached_has_bits = _has_bits_[$idx$];\n", "idx", - SimpleItoa(cached_has_bit_index)); - } - printer->Print("if (cached_has_bits & $mask$u) {\n", "mask", - SimpleItoa(last_chunk_mask)); - printer->Indent(); - } - - if (memset_run_start != -1) { - if (memset_run_start == memset_run_end) { - // For clarity, do not memset a single field. - const FieldGenerator& generator = - field_generators_.get(chunk[memset_run_start]); - generator.GenerateMessageClearingCode(printer); - } else { - const string first_field_name = FieldName(chunk[memset_run_start]); - const string last_field_name = FieldName(chunk[memset_run_end]); - - printer->Print( - "::memset(&$first$_, 0, static_cast(\n" - " reinterpret_cast(&$last$_) -\n" - " reinterpret_cast(&$first$_)) + sizeof($last$_));\n", - "first", first_field_name, "last", last_field_name); - } - - // Advance last_chunk_start to skip over the fields we zeroed/memset. - last_chunk_start = memset_run_end + 1; - } - - // Go back and emit clears for each of the fields we processed. - for (int j = last_chunk_start; j < chunk.size(); j++) { - const FieldDescriptor* field = chunk[j]; - const string fieldname = FieldName(field); - const FieldGenerator& generator = field_generators_.get(field); - - // It's faster to just overwrite primitive types, but we should only - // clear strings and messages if they were set. - // - // TODO(kenton): Let the CppFieldGenerator decide this somehow. - bool should_check_bit = - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE || - field->cpp_type() == FieldDescriptor::CPPTYPE_STRING; - - bool have_enclosing_if = false; - if (should_check_bit && - // If no field presence, then always clear strings/messages as well. - HasFieldPresence(descriptor_->file())) { - if (!field->options().weak() && - cached_has_bit_index != (has_bit_indices_[field->index()] / 32)) { - cached_has_bit_index = (has_bit_indices_[field->index()] / 32); - printer->Print("cached_has_bits = _has_bits_[$new_index$];\n", - "new_index", SimpleItoa(cached_has_bit_index)); - } - if (!MaybeGenerateOptionalFieldCondition(printer, field, - cached_has_bit_index)) { - printer->Print("if (has_$name$()) {\n", "name", fieldname); - } - printer->Indent(); - have_enclosing_if = true; - } - - generator.GenerateMessageClearingCode(printer); - - if (have_enclosing_if) { - printer->Outdent(); - printer->Print("}\n"); - } - } - - if (have_outer_if) { - printer->Outdent(); - printer->Print("}\n"); - } - } - - // Step 4: Unions. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "clear_$oneof_name$();\n", - "oneof_name", descriptor_->oneof_decl(i)->name()); - } - - if (num_weak_fields_) { - printer->Print("_weak_field_map_.ClearAll();\n"); - } - - if (HasFieldPresence(descriptor_->file())) { - // Step 5: Everything else. - printer->Print("_has_bits_.Clear();\n"); - } - - printer->Print("_internal_metadata_.Clear();\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -void MessageGenerator:: -GenerateOneofClear(io::Printer* printer) { - // Generated function clears the active field and union case (e.g. foo_case_). - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - std::map oneof_vars; - oneof_vars["classname"] = classname_; - oneof_vars["oneofname"] = descriptor_->oneof_decl(i)->name(); - oneof_vars["full_name"] = descriptor_->full_name(); - string message_class; - - printer->Print(oneof_vars, - "void $classname$::clear_$oneofname$() {\n" - "// @@protoc_insertion_point(one_of_clear_start:" - "$full_name$)\n"); - printer->Indent(); - printer->Print(oneof_vars, - "switch ($oneofname$_case()) {\n"); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); - // We clear only allocated objects in oneofs - if (!IsStringOrMessage(field)) { - printer->Print( - "// No need to clear\n"); - } else { - field_generators_.get(field).GenerateClearingCode(printer); - } - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); - } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " break;\n" - "}\n", - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "}\n" - "_oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n", - "oneof_index", SimpleItoa(i), - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - } -} - -void MessageGenerator:: -GenerateSwap(io::Printer* printer) { - if (SupportsArenas(descriptor_)) { - // Generate the Swap member function. This is a lightweight wrapper around - // UnsafeArenaSwap() / MergeFrom() with temporaries, depending on the memory - // ownership situation: swapping across arenas or between an arena and a - // heap requires copying. - printer->Print( - "void $classname$::Swap($classname$* other) {\n" - " if (other == this) return;\n" - " if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {\n" - " InternalSwap(other);\n" - " } else {\n" - " $classname$* temp = New(GetArenaNoVirtual());\n" - " temp->MergeFrom(*other);\n" - " other->CopyFrom(*this);\n" - " InternalSwap(temp);\n" - " if (GetArenaNoVirtual() == NULL) {\n" - " delete temp;\n" - " }\n" - " }\n" - "}\n" - "void $classname$::UnsafeArenaSwap($classname$* other) {\n" - " if (other == this) return;\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());\n" - " InternalSwap(other);\n" - "}\n", - "classname", classname_); - } else { - printer->Print( - "void $classname$::Swap($classname$* other) {\n" - " if (other == this) return;\n" - " InternalSwap(other);\n" - "}\n", - "classname", classname_); - } - - // Generate the UnsafeArenaSwap member function. - printer->Print("void $classname$::InternalSwap($classname$* other) {\n", - "classname", classname_); - printer->Indent(); - printer->Print("using std::swap;\n"); - - if (HasGeneratedMethods(descriptor_->file(), options_)) { - for (int i = 0; i < optimized_order_.size(); i++) { - // optimized_order_ does not contain oneof fields, but the field - // generators for these fields do not emit swapping code on their own. - const FieldDescriptor* field = optimized_order_[i]; - field_generators_.get(field).GenerateSwappingCode(printer); - } - - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "swap($oneof_name$_, other->$oneof_name$_);\n" - "swap(_oneof_case_[$i$], other->_oneof_case_[$i$]);\n", - "oneof_name", descriptor_->oneof_decl(i)->name(), - "i", SimpleItoa(i)); - } - - if (HasFieldPresence(descriptor_->file())) { - for (int i = 0; i < HasBitsSize() / 4; ++i) { - printer->Print("swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n", - "i", SimpleItoa(i)); - } - } - - printer->Print("_internal_metadata_.Swap(&other->_internal_metadata_);\n"); - - if (descriptor_->extension_range_count() > 0) { - printer->Print("_extensions_.Swap(&other->_extensions_);\n"); - } - if (num_weak_fields_) { - printer->Print( - "_weak_field_map_.UnsafeArenaSwap(&other->_weak_field_map_);\n"); - } - } else { - printer->Print("GetReflection()->Swap(this, other);"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void MessageGenerator:: -GenerateMergeFrom(io::Printer* printer) { - if (HasDescriptorMethods(descriptor_->file(), options_)) { - // Generate the generalized MergeFrom (aka that which takes in the Message - // base class as a parameter). - printer->Print( - "void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n" - "// @@protoc_insertion_point(generalized_merge_from_start:" - "$full_name$)\n" - " GOOGLE_DCHECK_NE(&from, this);\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - - // Cast the message to the proper type. If we find that the message is - // *not* of the proper type, we can still call Merge via the reflection - // system, as the GOOGLE_CHECK above ensured that we have the same descriptor - // for each message. - printer->Print( - "const $classname$* source =\n" - " ::google::protobuf::internal::DynamicCastToGenerated(\n" - " &from);\n" - "if (source == NULL) {\n" - "// @@protoc_insertion_point(generalized_merge_from_cast_fail:" - "$full_name$)\n" - " ::google::protobuf::internal::ReflectionOps::Merge(from, this);\n" - "} else {\n" - "// @@protoc_insertion_point(generalized_merge_from_cast_success:" - "$full_name$)\n" - " MergeFrom(*source);\n" - "}\n", - "classname", classname_, "full_name", descriptor_->full_name()); - - printer->Outdent(); - printer->Print("}\n\n"); - } else { - // Generate CheckTypeAndMergeFrom(). - printer->Print( - "void $classname$::CheckTypeAndMergeFrom(\n" - " const ::google::protobuf::MessageLite& from) {\n" - " MergeFrom(*::google::protobuf::down_cast(&from));\n" - "}\n" - "\n", - "classname", classname_); - } - - // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast. - printer->Print( - "void $classname$::MergeFrom(const $classname$& from) {\n" - "// @@protoc_insertion_point(class_specific_merge_from_start:" - "$full_name$)\n" - " GOOGLE_DCHECK_NE(&from, this);\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - - if (descriptor_->extension_range_count() > 0) { - printer->Print("_extensions_.MergeFrom(from._extensions_);\n"); - } - - printer->Print( - "_internal_metadata_.MergeFrom(from._internal_metadata_);\n" - "::google::protobuf::uint32 cached_has_bits = 0;\n" - "(void) cached_has_bits;\n\n"); - - // cached_has_bit_index maintains that: - // cached_has_bits = from._has_bits_[cached_has_bit_index] - // for cached_has_bit_index >= 0 - int cached_has_bit_index = -1; - - int last_i = -1; - for (int i = 0; i < optimized_order_.size(); ) { - // Detect infinite loops. - GOOGLE_CHECK_NE(i, last_i); - last_i = i; - - // Merge Repeated fields. These fields do not require a - // check as we can simply iterate over them. - for (; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (!field->is_repeated()) { - break; - } - - const FieldGenerator& generator = field_generators_.get(field); - generator.GenerateMergingCode(printer); - } - - // Merge Optional and Required fields (after a _has_bit_ check). - int last_chunk = -1; - int last_chunk_start = -1; - int last_chunk_end = -1; - uint32 last_chunk_mask = 0; - for (; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (field->is_repeated()) { - break; - } - - // "index" defines where in the _has_bits_ the field appears. - // "i" is our loop counter within optimized_order_. - int index = HasFieldPresence(descriptor_->file()) ? - has_bit_indices_[field->index()] : 0; - int chunk = index / 8; - - if (last_chunk == -1) { - last_chunk = chunk; - last_chunk_start = i; - } else if (chunk != last_chunk) { - // Emit the fields for this chunk so far. - break; - } - - last_chunk_end = i; - last_chunk_mask |= static_cast(1) << (index % 32); - } - - if (last_chunk != -1) { - GOOGLE_DCHECK_NE(-1, last_chunk_start); - GOOGLE_DCHECK_NE(-1, last_chunk_end); - GOOGLE_DCHECK_NE(0, last_chunk_mask); - - const int count = popcnt(last_chunk_mask); - const bool have_outer_if = HasFieldPresence(descriptor_->file()) && - (last_chunk_start != last_chunk_end); - - if (have_outer_if) { - // Check (up to) 8 has_bits at a time if we have more than one field in - // this chunk. Due to field layout ordering, we may check - // _has_bits_[last_chunk * 8 / 32] multiple times. - GOOGLE_DCHECK_LE(2, count); - GOOGLE_DCHECK_GE(8, count); - - if (cached_has_bit_index != last_chunk / 4) { - int new_index = last_chunk / 4; - printer->Print("cached_has_bits = from._has_bits_[$new_index$];\n", - "new_index", SimpleItoa(new_index)); - cached_has_bit_index = new_index; - } - - printer->Print( - "if (cached_has_bits & $mask$u) {\n", - "mask", SimpleItoa(last_chunk_mask)); - printer->Indent(); - } - - // Go back and emit clears for each of the fields we processed. - bool deferred_has_bit_changes = false; - for (int j = last_chunk_start; j <= last_chunk_end; j++) { - const FieldDescriptor* field = optimized_order_[j]; - const FieldGenerator& generator = field_generators_.get(field); - - bool have_enclosing_if = false; - if (HasFieldPresence(descriptor_->file())) { - // Attempt to use the state of cached_has_bits, if possible. - int has_bit_index = has_bit_indices_[field->index()]; - if (!field->options().weak() && - cached_has_bit_index == has_bit_index / 32) { - const string mask = StrCat( - strings::Hex(1u << (has_bit_index % 32), - strings::ZERO_PAD_8)); - - printer->Print( - "if (cached_has_bits & 0x$mask$u) {\n", "mask", mask); - } else { - printer->Print( - "if (from.has_$name$()) {\n", - "name", FieldName(field)); - } - - printer->Indent(); - have_enclosing_if = true; - } else { - // Merge semantics without true field presence: primitive fields are - // merged only if non-zero (numeric) or non-empty (string). - have_enclosing_if = EmitFieldNonDefaultCondition( - printer, "from.", field); - } - - if (have_outer_if && IsPOD(field)) { - // GenerateCopyConstructorCode for enum and primitive scalar fields - // does not do _has_bits_ modifications. We defer _has_bits_ - // manipulation until the end of the outer if. - // - // This can reduce the number of loads/stores by up to 7 per 8 fields. - deferred_has_bit_changes = true; - generator.GenerateCopyConstructorCode(printer); - } else { - generator.GenerateMergingCode(printer); - } - - if (have_enclosing_if) { - printer->Outdent(); - printer->Print("}\n"); - } - } - - if (have_outer_if) { - if (deferred_has_bit_changes) { - // Flush the has bits for the primitives we deferred. - GOOGLE_CHECK_LE(0, cached_has_bit_index); - printer->Print( - "_has_bits_[$index$] |= cached_has_bits;\n", - "index", SimpleItoa(cached_has_bit_index)); - } - - printer->Outdent(); - printer->Print("}\n"); - } - } - } - - // Merge oneof fields. Oneof field requires oneof case check. - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - printer->Print( - "switch (from.$oneofname$_case()) {\n", - "oneofname", descriptor_->oneof_decl(i)->name()); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); - field_generators_.get(field).GenerateMergingCode(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); - } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " break;\n" - "}\n", - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "}\n"); - } - if (num_weak_fields_) { - printer->Print("_weak_field_map_.MergeFrom(from._weak_field_map_);\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void MessageGenerator:: -GenerateCopyFrom(io::Printer* printer) { - if (HasDescriptorMethods(descriptor_->file(), options_)) { - // Generate the generalized CopyFrom (aka that which takes in the Message - // base class as a parameter). - printer->Print( - "void $classname$::CopyFrom(const ::google::protobuf::Message& from) {\n" - "// @@protoc_insertion_point(generalized_copy_from_start:" - "$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - - printer->Print( - "if (&from == this) return;\n" - "Clear();\n" - "MergeFrom(from);\n"); - - printer->Outdent(); - printer->Print("}\n\n"); - } - - // Generate the class-specific CopyFrom. - printer->Print( - "void $classname$::CopyFrom(const $classname$& from) {\n" - "// @@protoc_insertion_point(class_specific_copy_from_start:" - "$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - - printer->Print( - "if (&from == this) return;\n" - "Clear();\n" - "MergeFrom(from);\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -void MessageGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) { - std::map vars; - SetUnknkownFieldsVariable(descriptor_, options_, &vars); - if (descriptor_->options().message_set_wire_format()) { - // Special-case MessageSet. - vars["classname"] = classname_; - printer->Print(vars, - "bool $classname$::MergePartialFromCodedStream(\n" - " ::google::protobuf::io::CodedInputStream* input) {\n" - " return _extensions_.ParseMessageSet(input,\n" - " internal_default_instance(), $mutable_unknown_fields$);\n" - "}\n"); - return; - } - std::vector ordered_fields = - SortFieldsByNumber(descriptor_); - - printer->Print( - "bool $classname$::MergePartialFromCodedStream(\n" - " ::google::protobuf::io::CodedInputStream* input) {\n", - "classname", classname_); - - if (table_driven_) { - printer->Indent(); - - const string lite = UseUnknownFieldSet(descriptor_->file(), options_) ? - "" : "Lite"; - - printer->Print( - "return ::google::protobuf::internal::MergePartialFromCodedStream$lite$(\n" - " this,\n" - " ::$file_namespace$::TableStruct::schema[\n" - " $classname$::kIndexInFileMessages],\n" - " input);\n", - "classname", classname_, "file_namespace", - FileLevelNamespace(descriptor_), "lite", lite); - - printer->Outdent(); - - printer->Print("}\n"); - return; - } - - if (SupportsArenas(descriptor_)) { - for (int i = 0; i < ordered_fields.size(); i++) { - const FieldDescriptor* field = ordered_fields[i]; - const FieldGenerator& field_generator = field_generators_.get(field); - if (field_generator.MergeFromCodedStreamNeedsArena()) { - printer->Print( - " ::google::protobuf::Arena* arena = GetArenaNoVirtual();\n"); - break; - } - } - } - - printer->Print( - "#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto " - "failure\n" - " ::google::protobuf::uint32 tag;\n"); - - if (!UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print( - " ::google::protobuf::internal::LiteUnknownFieldSetter unknown_fields_setter(\n" - " &_internal_metadata_);\n" - " ::google::protobuf::io::StringOutputStream unknown_fields_output(\n" - " unknown_fields_setter.buffer());\n" - " ::google::protobuf::io::CodedOutputStream unknown_fields_stream(\n" - " &unknown_fields_output, false);\n", - "classname", classname_); - } - - printer->Print( - " // @@protoc_insertion_point(parse_start:$full_name$)\n", - "full_name", descriptor_->full_name()); - - printer->Indent(); - printer->Print("for (;;) {\n"); - printer->Indent(); - - // To calculate the maximum tag to expect, we look at the highest-numbered - // field. We need to be prepared to handle more than one wire type if that - // field is a packable repeated field, so to simplify things we assume the - // highest possible wire type of 5. - uint32 maxtag = - ordered_fields.empty() ? 0 : ordered_fields.back()->number() * 8 + 5; - const int kCutoff0 = 127; // fits in 1-byte varint - const int kCutoff1 = (127 << 7) + 127; // fits in 2-byte varint - - // We need to capture the last tag when parsing if this is a Group type, as - // our caller will verify (via CodedInputStream::LastTagWas) that the correct - // closing tag was received. - bool capture_last_tag = false; - const Descriptor* parent = descriptor_->containing_type(); - if (parent) { - for (int i = 0; i < parent->field_count(); i++) { - const FieldDescriptor* field = parent->field(i); - if (field->type() == FieldDescriptor::TYPE_GROUP && - field->message_type() == descriptor_) { - capture_last_tag = true; - break; - } - } - - for (int i = 0; i < parent->extension_count(); i++) { - const FieldDescriptor* field = parent->extension(i); - if (field->type() == FieldDescriptor::TYPE_GROUP && - field->message_type() == descriptor_) { - capture_last_tag = true; - break; - } - } - } - - for (int i = 0; i < descriptor_->file()->extension_count(); i++) { - const FieldDescriptor* field = descriptor_->file()->extension(i); - if (field->type() == FieldDescriptor::TYPE_GROUP && - field->message_type() == descriptor_) { - capture_last_tag = true; - break; - } - } - - printer->Print("::std::pair<::google::protobuf::uint32, bool> p = " - "input->ReadTagWithCutoffNoLastTag($max$u);\n" - "tag = p.first;\n" - "if (!p.second) goto handle_unusual;\n", - "max", SimpleItoa(maxtag <= kCutoff0 ? kCutoff0 : - (maxtag <= kCutoff1 ? kCutoff1 : - maxtag))); - - if (descriptor_->field_count() > 0) { - // We don't even want to print the switch() if we have no fields because - // MSVC dislikes switch() statements that contain only a default value. - - // Note: If we just switched on the tag rather than the field number, we - // could avoid the need for the if() to check the wire type at the beginning - // of each case. However, this is actually a bit slower in practice as it - // creates a jump table that is 8x larger and sparser, and meanwhile the - // if()s are highly predictable. - // - // Historically, we inserted checks to peek at the next tag on the wire and - // jump directly to the next case statement. While this avoids the jump - // table that the switch uses, it greatly increases code size (20-60%) and - // inserts branches that may fail (especially for real world protos that - // interleave--in field number order--hot and cold fields). Loadtests - // confirmed that removing this optimization is performance neutral. - printer->Print("switch (::google::protobuf::internal::WireFormatLite::" - "GetTagFieldNumber(tag)) {\n"); - - printer->Indent(); - - for (int i = 0; i < ordered_fields.size(); i++) { - const FieldDescriptor* field = ordered_fields[i]; - - PrintFieldComment(printer, field); - - printer->Print( - "case $number$: {\n", - "number", SimpleItoa(field->number())); - printer->Indent(); - const FieldGenerator& field_generator = field_generators_.get(field); - - // Emit code to parse the common, expected case. - printer->Print( - "if (static_cast< ::google::protobuf::uint8>(tag) ==\n" - " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n", - "truncated", SimpleItoa(WireFormat::MakeTag(field) & 0xFF), - "full", SimpleItoa(WireFormat::MakeTag(field))); - - printer->Indent(); - if (field->is_packed()) { - field_generator.GenerateMergeFromCodedStreamWithPacking(printer); - } else { - field_generator.GenerateMergeFromCodedStream(printer); - } - printer->Outdent(); - - // Emit code to parse unexpectedly packed or unpacked values. - if (field->is_packed()) { - internal::WireFormatLite::WireType wiretype = - WireFormat::WireTypeForFieldType(field->type()); - const uint32 tag = internal::WireFormatLite::MakeTag( - field->number(), wiretype); - printer->Print( - "} else if (\n" - " static_cast< ::google::protobuf::uint8>(tag) ==\n" - " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n", - "truncated", SimpleItoa(tag & 0xFF), - "full", SimpleItoa(tag)); - - printer->Indent(); - field_generator.GenerateMergeFromCodedStream(printer); - printer->Outdent(); - } else if (field->is_packable() && !field->is_packed()) { - internal::WireFormatLite::WireType wiretype = - internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED; - const uint32 tag = internal::WireFormatLite::MakeTag( - field->number(), wiretype); - - printer->Print( - "} else if (\n" - " static_cast< ::google::protobuf::uint8>(tag) ==\n" - " static_cast< ::google::protobuf::uint8>($truncated$u /* $full$ & 0xFF */)) {\n", - "truncated", SimpleItoa(tag & 0xFF), - "full", SimpleItoa(tag)); - printer->Indent(); - field_generator.GenerateMergeFromCodedStreamWithPacking(printer); - printer->Outdent(); - } - - printer->Print( - "} else {\n" - " goto handle_unusual;\n" - "}\n"); - - printer->Print( - "break;\n"); - - printer->Outdent(); - printer->Print("}\n\n"); - } - printer->Print("default: {\n"); - printer->Indent(); - } - - printer->Outdent(); - printer->Print("handle_unusual:\n"); - printer->Indent(); - // If tag is 0 or an end-group tag then this must be the end of the message. - if (capture_last_tag) { - printer->Print( - "if (tag == 0 ||\n" - " ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n" - " ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n" - " input->SetLastTag(tag);\n" - " goto success;\n" - "}\n"); - } else { - printer->Print( - "if (tag == 0) {\n" - " goto success;\n" - "}\n"); - } - - // Handle extension ranges. - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if ("); - for (int i = 0; i < descriptor_->extension_range_count(); i++) { - const Descriptor::ExtensionRange* range = - descriptor_->extension_range(i); - if (i > 0) printer->Print(" ||\n "); - - uint32 start_tag = WireFormatLite::MakeTag( - range->start, static_cast(0)); - uint32 end_tag = WireFormatLite::MakeTag( - range->end, static_cast(0)); - - if (range->end > FieldDescriptor::kMaxNumber) { - printer->Print( - "($start$u <= tag)", - "start", SimpleItoa(start_tag)); - } else { - printer->Print( - "($start$u <= tag && tag < $end$u)", - "start", SimpleItoa(start_tag), - "end", SimpleItoa(end_tag)); - } - } - printer->Print(") {\n"); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, - " DO_(_extensions_.ParseField(tag, input,\n" - " internal_default_instance(),\n" - " $mutable_unknown_fields$));\n"); - } else { - printer->Print( - " DO_(_extensions_.ParseField(tag, input,\n" - " internal_default_instance(),\n" - " &unknown_fields_stream));\n"); - } - printer->Print( - " continue;\n" - "}\n"); - } - - // We really don't recognize this tag. Skip it. - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, - "DO_(::google::protobuf::internal::WireFormat::SkipField(\n" - " input, tag, $mutable_unknown_fields$));\n"); - } else { - printer->Print( - "DO_(::google::protobuf::internal::WireFormatLite::SkipField(\n" - " input, tag, &unknown_fields_stream));\n"); - } - - if (descriptor_->field_count() > 0) { - printer->Print("break;\n"); - printer->Outdent(); - printer->Print("}\n"); // default: - printer->Outdent(); - printer->Print("}\n"); // switch - } - - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" // for (;;) - "success:\n" - " // @@protoc_insertion_point(parse_success:$full_name$)\n" - " return true;\n" - "failure:\n" - " // @@protoc_insertion_point(parse_failure:$full_name$)\n" - " return false;\n" - "#undef DO_\n" - "}\n", "full_name", descriptor_->full_name()); -} - -void MessageGenerator::GenerateSerializeOneofFields( - io::Printer* printer, const std::vector& fields, - bool to_array) { - GOOGLE_CHECK(!fields.empty()); - if (fields.size() == 1) { - GenerateSerializeOneField(printer, fields[0], to_array, -1); - return; - } - // We have multiple mutually exclusive choices. Emit a switch statement. - const OneofDescriptor* oneof = fields[0]->containing_oneof(); - printer->Print( - "switch ($oneofname$_case()) {\n", - "oneofname", oneof->name()); - printer->Indent(); - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - printer->Print( - "case k$field_name$:\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); - if (to_array) { - field_generators_.get(field).GenerateSerializeWithCachedSizesToArray( - printer); - } else { - field_generators_.get(field).GenerateSerializeWithCachedSizes(printer); - } - printer->Print( - "break;\n"); - printer->Outdent(); - } - printer->Outdent(); - // Doing nothing is an option. - printer->Print( - " default: ;\n" - "}\n"); -} - -void MessageGenerator::GenerateSerializeOneField( - io::Printer* printer, const FieldDescriptor* field, bool to_array, - int cached_has_bits_index) { - if (!field->options().weak()) { - // For weakfields, PrintFieldComment is called during iteration. - PrintFieldComment(printer, field); - } - - bool have_enclosing_if = false; - if (field->options().weak()) { - } else if (!field->is_repeated() && HasFieldPresence(descriptor_->file())) { - // Attempt to use the state of cached_has_bits, if possible. - int has_bit_index = has_bit_indices_[field->index()]; - if (cached_has_bits_index == has_bit_index / 32) { - const string mask = StrCat( - strings::Hex(1u << (has_bit_index % 32), - strings::ZERO_PAD_8)); - - printer->Print( - "if (cached_has_bits & 0x$mask$u) {\n", "mask", mask); - } else { - printer->Print( - "if (has_$name$()) {\n", - "name", FieldName(field)); - } - - printer->Indent(); - have_enclosing_if = true; - } else if (!HasFieldPresence(descriptor_->file())) { - have_enclosing_if = EmitFieldNonDefaultCondition(printer, "this->", field); - } - - if (to_array) { - field_generators_.get(field).GenerateSerializeWithCachedSizesToArray( - printer); - } else { - field_generators_.get(field).GenerateSerializeWithCachedSizes(printer); - } - - if (have_enclosing_if) { - printer->Outdent(); - printer->Print("}\n"); - } - printer->Print("\n"); -} - -void MessageGenerator::GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* range, - bool to_array) { - std::map vars; - vars["start"] = SimpleItoa(range->start); - vars["end"] = SimpleItoa(range->end); - printer->Print(vars, - "// Extension range [$start$, $end$)\n"); - if (to_array) { - printer->Print(vars, - "target = _extensions_.InternalSerializeWithCachedSizesToArray(\n" - " $start$, $end$, deterministic, target);\n\n"); - } else { - printer->Print(vars, - "_extensions_.SerializeWithCachedSizes(\n" - " $start$, $end$, output);\n\n"); - } -} - -void MessageGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) { - if (descriptor_->options().message_set_wire_format()) { - // Special-case MessageSet. - printer->Print( - "void $classname$::SerializeWithCachedSizes(\n" - " ::google::protobuf::io::CodedOutputStream* output) const {\n" - " _extensions_.SerializeMessageSetWithCachedSizes(output);\n", - "classname", classname_); - GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_)); - std::map vars; - SetUnknkownFieldsVariable(descriptor_, options_, &vars); - printer->Print(vars, - " ::google::protobuf::internal::WireFormat::SerializeUnknownMessageSetItems(\n" - " $unknown_fields$, output);\n"); - printer->Print( - "}\n"); - return; - } - if (options_.table_driven_serialization) return; - - printer->Print( - "void $classname$::SerializeWithCachedSizes(\n" - " ::google::protobuf::io::CodedOutputStream* output) const {\n", - "classname", classname_); - printer->Indent(); - - printer->Print( - "// @@protoc_insertion_point(serialize_start:$full_name$)\n", - "full_name", descriptor_->full_name()); - - GenerateSerializeWithCachedSizesBody(printer, false); - - printer->Print( - "// @@protoc_insertion_point(serialize_end:$full_name$)\n", - "full_name", descriptor_->full_name()); - - printer->Outdent(); - printer->Print( - "}\n"); -} - -void MessageGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) { - if (descriptor_->options().message_set_wire_format()) { - // Special-case MessageSet. - printer->Print( - "::google::protobuf::uint8* $classname$::InternalSerializeWithCachedSizesToArray(\n" - " bool deterministic, ::google::protobuf::uint8* target) const {\n" - " target = _extensions_." - "InternalSerializeMessageSetWithCachedSizesToArray(\n" - " deterministic, target);\n", - "classname", classname_); - GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_)); - std::map vars; - SetUnknkownFieldsVariable(descriptor_, options_, &vars); - printer->Print(vars, - " target = ::google::protobuf::internal::WireFormat::\n" - " SerializeUnknownMessageSetItemsToArray(\n" - " $unknown_fields$, target);\n"); - printer->Print( - " return target;\n" - "}\n"); - return; - } - - printer->Print( - "::google::protobuf::uint8* $classname$::InternalSerializeWithCachedSizesToArray(\n" - " bool deterministic, ::google::protobuf::uint8* target) const {\n", - "classname", classname_); - printer->Indent(); - - printer->Print("(void)deterministic; // Unused\n"); - printer->Print( - "// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n", - "full_name", descriptor_->full_name()); - - GenerateSerializeWithCachedSizesBody(printer, true); - - printer->Print( - "// @@protoc_insertion_point(serialize_to_array_end:$full_name$)\n", - "full_name", descriptor_->full_name()); - - printer->Outdent(); - printer->Print( - " return target;\n" - "}\n"); -} - -void MessageGenerator:: -GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) { - // If there are multiple fields in a row from the same oneof then we - // coalesce them and emit a switch statement. This is more efficient - // because it lets the C++ compiler know this is a "at most one can happen" - // situation. If we emitted "if (has_x()) ...; if (has_y()) ..." the C++ - // compiler's emitted code might check has_y() even when has_x() is true. - class LazySerializerEmitter { - public: - LazySerializerEmitter(MessageGenerator* mg, io::Printer* printer, - bool to_array) - : mg_(mg), - printer_(printer), - to_array_(to_array), - eager_(!HasFieldPresence(mg->descriptor_->file())), - cached_has_bit_index_(-1) {} - - ~LazySerializerEmitter() { Flush(); } - - // If conditions allow, try to accumulate a run of fields from the same - // oneof, and handle them at the next Flush(). - void Emit(const FieldDescriptor* field) { - if (eager_ || MustFlush(field)) { - Flush(); - } - if (field->containing_oneof() == NULL) { - // TODO(ckennelly): Defer non-oneof fields similarly to oneof fields. - - if (!field->options().weak() && !field->is_repeated() && !eager_) { - // We speculatively load the entire _has_bits_[index] contents, even - // if it is for only one field. Deferring non-oneof emitting would - // allow us to determine whether this is going to be useful. - int has_bit_index = mg_->has_bit_indices_[field->index()]; - if (cached_has_bit_index_ != has_bit_index / 32) { - // Reload. - int new_index = has_bit_index / 32; - - printer_->Print( - "cached_has_bits = _has_bits_[$new_index$];\n", - "new_index", SimpleItoa(new_index)); - - cached_has_bit_index_ = new_index; - } - } - - mg_->GenerateSerializeOneField( - printer_, field, to_array_, cached_has_bit_index_); - } else { - v_.push_back(field); - } - } - - void Flush() { - if (!v_.empty()) { - mg_->GenerateSerializeOneofFields(printer_, v_, to_array_); - v_.clear(); - } - } - - private: - // If we have multiple fields in v_ then they all must be from the same - // oneof. Would adding field to v_ break that invariant? - bool MustFlush(const FieldDescriptor* field) { - return !v_.empty() && - v_[0]->containing_oneof() != field->containing_oneof(); - } - - MessageGenerator* mg_; - io::Printer* printer_; - const bool to_array_; - const bool eager_; - std::vector v_; - - // cached_has_bit_index_ maintains that: - // cached_has_bits = from._has_bits_[cached_has_bit_index_] - // for cached_has_bit_index_ >= 0 - int cached_has_bit_index_; - }; - - std::vector ordered_fields = - SortFieldsByNumber(descriptor_); - - std::vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); - } - std::sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeSorter()); - if (num_weak_fields_) { - printer->Print( - "::google::protobuf::internal::WeakFieldMap::FieldWriter field_writer(" - "_weak_field_map_);\n"); - } - - printer->Print( - "::google::protobuf::uint32 cached_has_bits = 0;\n" - "(void) cached_has_bits;\n\n"); - - // Merge the fields and the extension ranges, both sorted by field number. - { - LazySerializerEmitter e(this, printer, to_array); - const FieldDescriptor* last_weak_field = nullptr; - int i, j; - for (i = 0, j = 0; - i < ordered_fields.size() || j < sorted_extensions.size();) { - if ((j == sorted_extensions.size()) || - (i < descriptor_->field_count() && - ordered_fields[i]->number() < sorted_extensions[j]->start)) { - const FieldDescriptor* field = ordered_fields[i++]; - if (field->options().weak()) { - last_weak_field = field; - PrintFieldComment(printer, field); - } else { - if (last_weak_field != nullptr) { - e.Emit(last_weak_field); - last_weak_field = nullptr; - } - e.Emit(field); - } - } else { - if (last_weak_field != nullptr) { - e.Emit(last_weak_field); - last_weak_field = nullptr; - } - e.Flush(); - GenerateSerializeOneExtensionRange(printer, - sorted_extensions[j++], - to_array); - } - } - if (last_weak_field != nullptr) { - e.Emit(last_weak_field); - } - } - - std::map vars; - SetUnknkownFieldsVariable(descriptor_, options_, &vars); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, - "if ($have_unknown_fields$) {\n"); - printer->Indent(); - if (to_array) { - printer->Print(vars, - "target = " - "::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(\n" - " $unknown_fields$, target);\n"); - } else { - printer->Print(vars, - "::google::protobuf::internal::WireFormat::SerializeUnknownFields(\n" - " $unknown_fields$, output);\n"); - } - printer->Outdent(); - - printer->Print("}\n"); - } else { - printer->Print(vars, - "output->WriteRaw($unknown_fields$.data(),\n" - " static_cast($unknown_fields$.size()));\n"); - } -} - -std::vector MessageGenerator::RequiredFieldsBitMask() const { - const int array_size = HasBitsSize(); - std::vector masks(array_size, 0); - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (!field->is_required()) { - continue; - } - - const int has_bit_index = has_bit_indices_[field->index()]; - masks[has_bit_index / 32] |= - static_cast(1) << (has_bit_index % 32); - } - return masks; -} - -// Create an expression that evaluates to -// "for all i, (_has_bits_[i] & masks[i]) == masks[i]" -// masks is allowed to be shorter than _has_bits_, but at least one element of -// masks must be non-zero. -static string ConditionalToCheckBitmasks(const std::vector& masks) { - std::vector parts; - for (int i = 0; i < masks.size(); i++) { - if (masks[i] == 0) continue; - string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8)); - // Each xor evaluates to 0 if the expected bits are present. - parts.push_back(StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")")); - } - GOOGLE_CHECK(!parts.empty()); - // If we have multiple parts, each expected to be 0, then bitwise-or them. - string result = parts.size() == 1 - ? parts[0] - : StrCat("(", Join(parts, "\n | "), ")"); - return result + " == 0"; -} - -void MessageGenerator:: -GenerateByteSize(io::Printer* printer) { - if (descriptor_->options().message_set_wire_format()) { - // Special-case MessageSet. - GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_)); - std::map vars; - SetUnknkownFieldsVariable(descriptor_, options_, &vars); - vars["classname"] = classname_; - vars["full_name"] = descriptor_->full_name(); - printer->Print( - vars, - "size_t $classname$::ByteSizeLong() const {\n" - "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n" - " size_t total_size = _extensions_.MessageSetByteSize();\n" - " if ($have_unknown_fields$) {\n" - " total_size += ::google::protobuf::internal::WireFormat::\n" - " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n" - " }\n" - " int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" - " SetCachedSize(cached_size);\n" - " return total_size;\n" - "}\n"); - return; - } - - if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) { - // Emit a function (rarely used, we hope) that handles the required fields - // by checking for each one individually. - printer->Print( - "size_t $classname$::RequiredFieldsByteSizeFallback() const {\n" - "// @@protoc_insertion_point(required_fields_byte_size_fallback_start:" - "$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - printer->Print("size_t total_size = 0;\n"); - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (field->is_required()) { - printer->Print("\n" - "if (has_$name$()) {\n", - "name", FieldName(field)); - printer->Indent(); - PrintFieldComment(printer, field); - field_generators_.get(field).GenerateByteSize(printer); - printer->Outdent(); - printer->Print("}\n"); - } - } - printer->Print("\n" - "return total_size;\n"); - printer->Outdent(); - printer->Print("}\n"); - } - - printer->Print( - "size_t $classname$::ByteSizeLong() const {\n" - "// @@protoc_insertion_point(message_byte_size_start:$full_name$)\n", - "classname", classname_, "full_name", descriptor_->full_name()); - printer->Indent(); - printer->Print( - "size_t total_size = 0;\n" - "\n"); - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "total_size += _extensions_.ByteSize();\n" - "\n"); - } - - std::map vars; - SetUnknkownFieldsVariable(descriptor_, options_, &vars); - if (UseUnknownFieldSet(descriptor_->file(), options_)) { - printer->Print(vars, - "if ($have_unknown_fields$) {\n" - " total_size +=\n" - " ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(\n" - " $unknown_fields$);\n" - "}\n"); - } else { - printer->Print(vars, - "total_size += $unknown_fields$.size();\n" - "\n"); - } - - // Handle required fields (if any). We expect all of them to be - // present, so emit one conditional that checks for that. If they are all - // present then the fast path executes; otherwise the slow path executes. - if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) { - // The fast path works if all required fields are present. - const std::vector masks_for_has_bits = RequiredFieldsBitMask(); - printer->Print((string("if (") + - ConditionalToCheckBitmasks(masks_for_has_bits) + - ") { // All required fields are present.\n").c_str()); - printer->Indent(); - // Oneof fields cannot be required, so optimized_order_ contains all of the - // fields that we need to potentially emit. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (!field->is_required()) continue; - PrintFieldComment(printer, field); - field_generators_.get(field).GenerateByteSize(printer); - printer->Print("\n"); - } - printer->Outdent(); - printer->Print("} else {\n" // the slow path - " total_size += RequiredFieldsByteSizeFallback();\n" - "}\n"); - } else { - // num_required_fields_ <= 1: no need to be tricky - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - if (!field->is_required()) continue; - PrintFieldComment(printer, field); - printer->Print("if (has_$name$()) {\n", - "name", FieldName(field)); - printer->Indent(); - field_generators_.get(field).GenerateByteSize(printer); - printer->Outdent(); - printer->Print("}\n"); - } - } - - std::vector > chunks = CollectFields( - optimized_order_, - MatchRepeatedAndHasByteAndRequired( - &has_bit_indices_, HasFieldPresence(descriptor_->file()))); - - // Remove chunks with required fields. - chunks.erase(std::remove_if(chunks.begin(), chunks.end(), IsRequired), - chunks.end()); - - for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { - const std::vector& chunk = chunks[chunk_index]; - GOOGLE_CHECK(!chunk.empty()); - - // Handle repeated fields. - if (chunk.front()->is_repeated()) { - for (int i = 0; i < chunk.size(); i++) { - const FieldDescriptor* field = chunk[i]; - - PrintFieldComment(printer, field); - const FieldGenerator& generator = field_generators_.get(field); - generator.GenerateByteSize(printer); - printer->Print("\n"); - } - continue; - } - - // Handle optional (non-repeated/oneof) fields. - // - // These are handled in chunks of 8. The first chunk is - // the non-requireds-non-repeateds-non-unions-non-extensions in - // descriptor_->field(0), descriptor_->field(1), ... descriptor_->field(7), - // and the second chunk is the same for - // descriptor_->field(8), descriptor_->field(9), ... - // descriptor_->field(15), - // etc. - int last_chunk = HasFieldPresence(descriptor_->file()) - ? has_bit_indices_[chunk.front()->index()] / 8 - : 0; - GOOGLE_DCHECK_NE(-1, last_chunk); - - const bool have_outer_if = - HasFieldPresence(descriptor_->file()) && chunk.size() > 1; - - if (have_outer_if) { - uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_); - const int count = popcnt(last_chunk_mask); - - // Check (up to) 8 has_bits at a time if we have more than one field in - // this chunk. Due to field layout ordering, we may check - // _has_bits_[last_chunk * 8 / 32] multiple times. - GOOGLE_DCHECK_LE(2, count); - GOOGLE_DCHECK_GE(8, count); - - printer->Print("if (_has_bits_[$index$ / 32] & $mask$u) {\n", "index", - SimpleItoa(last_chunk * 8), "mask", - SimpleItoa(last_chunk_mask)); - printer->Indent(); - } - - // Go back and emit checks for each of the fields we processed. - for (int j = 0; j < chunk.size(); j++) { - const FieldDescriptor* field = chunk[j]; - const FieldGenerator& generator = field_generators_.get(field); - - PrintFieldComment(printer, field); - - bool have_enclosing_if = false; - if (HasFieldPresence(descriptor_->file())) { - printer->Print("if (has_$name$()) {\n", "name", FieldName(field)); - printer->Indent(); - have_enclosing_if = true; - } else { - // Without field presence: field is serialized only if it has a - // non-default value. - have_enclosing_if = - EmitFieldNonDefaultCondition(printer, "this->", field); - } - - generator.GenerateByteSize(printer); - - if (have_enclosing_if) { - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - } - } - - if (have_outer_if) { - printer->Outdent(); - printer->Print("}\n"); - } - } - - // Fields inside a oneof don't use _has_bits_ so we count them in a separate - // pass. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "switch ($oneofname$_case()) {\n", - "oneofname", descriptor_->oneof_decl(i)->name()); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - PrintFieldComment(printer, field); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); - field_generators_.get(field).GenerateByteSize(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); - } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " break;\n" - "}\n", - "cap_oneof_name", - ToUpper(descriptor_->oneof_decl(i)->name())); - printer->Outdent(); - printer->Print( - "}\n"); - } - - if (num_weak_fields_) { - // TagSize + MessageSize - printer->Print("total_size += _weak_field_map_.ByteSizeLong();\n"); - } - - // We update _cached_size_ even though this is a const method. Because - // const methods might be called concurrently this needs to be atomic - // operations or the program is undefined. In practice, since any concurrent - // writes will be writing the exact same value, normal writes will work on - // all common processors. We use a dedicated wrapper class to abstract away - // the underlying atomic. This makes it easier on platforms where even relaxed - // memory order might have perf impact to replace it with ordinary loads and - // stores. - printer->Print( - "int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);\n" - "SetCachedSize(cached_size);\n" - "return total_size;\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -void MessageGenerator:: -GenerateIsInitialized(io::Printer* printer) { - printer->Print( - "bool $classname$::IsInitialized() const {\n", - "classname", classname_); - printer->Indent(); - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if (!_extensions_.IsInitialized()) {\n" - " return false;\n" - "}\n\n"); - } - - if (HasFieldPresence(descriptor_->file())) { - // Check that all required fields in this message are set. We can do this - // most efficiently by checking 32 "has bits" at a time. - const std::vector masks = RequiredFieldsBitMask(); - - for (int i = 0; i < masks.size(); i++) { - uint32 mask = masks[i]; - if (mask == 0) { - continue; - } - - // TODO(ckennelly): Consider doing something similar to ByteSizeLong(), - // where we check all of the required fields in a single branch (assuming - // that we aren't going to benefit from early termination). - printer->Print( - "if ((_has_bits_[$i$] & 0x$mask$) != 0x$mask$) return false;\n", - "i", SimpleItoa(i), - "mask", StrCat(strings::Hex(mask, strings::ZERO_PAD_8))); - } - } - - // Now check that all non-oneof embedded messages are initialized. - for (int i = 0; i < optimized_order_.size(); i++) { - const FieldDescriptor* field = optimized_order_[i]; - // TODO(ckennelly): Push this down into a generator? - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !ShouldIgnoreRequiredFieldCheck(field, options_) && - scc_analyzer_->HasRequiredFields(field->message_type())) { - if (field->is_repeated()) { - if (IsImplicitWeakField(field, options_, scc_analyzer_)) { - printer->Print( - "if (!::google::protobuf::internal::AllAreInitializedWeak(this->$name$_))" - " return false;\n", - "name", FieldName(field)); - } else { - printer->Print( - "if (!::google::protobuf::internal::AllAreInitialized(this->$name$()))" - " return false;\n", - "name", FieldName(field)); - } - } else if (field->options().weak()) { - continue; - } else { - GOOGLE_CHECK(!field->containing_oneof()); - printer->Print( - "if (has_$name$()) {\n" - " if (!this->$name$_->IsInitialized()) return false;\n" - "}\n", - "name", FieldName(field)); - } - } - } - if (num_weak_fields_) { - // For Weak fields. - printer->Print("if (!_weak_field_map_.IsInitialized()) return false;\n"); - } - // Go through the oneof fields, emitting a switch if any might have required - // fields. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = descriptor_->oneof_decl(i); - - bool has_required_fields = false; - for (int j = 0; j < oneof->field_count(); j++) { - const FieldDescriptor* field = oneof->field(j); - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !ShouldIgnoreRequiredFieldCheck(field, options_) && - scc_analyzer_->HasRequiredFields(field->message_type())) { - has_required_fields = true; - break; - } - } - - if (!has_required_fields) { - continue; - } - - printer->Print( - "switch ($oneofname$_case()) {\n", - "oneofname", oneof->name()); - printer->Indent(); - for (int j = 0; j < oneof->field_count(); j++) { - const FieldDescriptor* field = oneof->field(j); - printer->Print( - "case k$field_name$: {\n", - "field_name", UnderscoresToCamelCase(field->name(), true)); - printer->Indent(); - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !ShouldIgnoreRequiredFieldCheck(field, options_) && - scc_analyzer_->HasRequiredFields(field->message_type())) { - GOOGLE_CHECK(!(field->options().weak() || !field->containing_oneof())); - if (field->options().weak()) { - // Just skip. - } else { - printer->Print( - "if (has_$name$()) {\n" - " if (!this->$name$().IsInitialized()) return false;\n" - "}\n", - "name", FieldName(field)); - } - } - - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); - } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " break;\n" - "}\n", - "cap_oneof_name", - ToUpper(oneof->name())); - printer->Outdent(); - printer->Print( - "}\n"); - } - - printer->Outdent(); - printer->Print( - " return true;\n" - "}\n"); -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_message.h b/windows/include/google/protobuf/compiler/cpp/cpp_message.h deleted file mode 100644 index ca2ca2c90..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_message.h +++ /dev/null @@ -1,237 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__ - -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace cpp { - -class EnumGenerator; // enum.h -class ExtensionGenerator; // extension.h - -class MessageGenerator { - public: - // See generator.cc for the meaning of dllexport_decl. - MessageGenerator(const Descriptor* descriptor, int index_in_file_messages, - const Options& options, SCCAnalyzer* scc_analyzer); - ~MessageGenerator(); - - // Append the two types of nested generators to the corresponding vector. - void AddGenerators(std::vector* enum_generators, - std::vector* extension_generators); - - // Header stuff. - - // Return names for forward declarations of this class and all its nested - // types. A given key in {class,enum}_names will map from a class name to the - // descriptor that was responsible for its inclusion in the map. This can be - // used to associate the descriptor with the code generated for it. - void FillMessageForwardDeclarations( - std::map* class_names); - - // Generate definitions for this class and all its nested types. - void GenerateClassDefinition(io::Printer* printer); - - // Generate definitions of inline methods (placed at the end of the header - // file). - void GenerateInlineMethods(io::Printer* printer); - - // Source file stuff. - - // Generate extra fields - void GenerateExtraDefaultFields(io::Printer* printer); - - // Generates code that creates default instances for fields. - void GenerateFieldDefaultInstances(io::Printer* printer); - - // Generates code that initializes the message's default instance. This - // is separate from allocating because all default instances must be - // allocated before any can be initialized. - void GenerateDefaultInstanceInitializer(io::Printer* printer); - - // Generate all non-inline methods for this class. - void GenerateClassMethods(io::Printer* printer); - - // Generate source file code that should go outside any namespace. - void GenerateSourceInProto2Namespace(io::Printer* printer); - - private: - // Generate declarations and definitions of accessors for fields. - void GenerateFieldAccessorDeclarations(io::Printer* printer); - void GenerateFieldAccessorDefinitions(io::Printer* printer); - - // Generate the table-driven parsing array. Returns the number of entries - // generated. - size_t GenerateParseOffsets(io::Printer* printer); - size_t GenerateParseAuxTable(io::Printer* printer); - // Generates a ParseTable entry. Returns whether the proto uses table-driven - // parsing. - bool GenerateParseTable(io::Printer* printer, size_t offset, - size_t aux_offset); - - // Generate the field offsets array. Returns the a pair of the total numer - // of entries generated and the index of the first has_bit entry. - std::pair GenerateOffsets(io::Printer* printer); - void GenerateSchema(io::Printer* printer, int offset, int has_offset); - // For each field generates a table entry describing the field for the - // table driven serializer. - int GenerateFieldMetadata(io::Printer* printer); - - // Generate constructors and destructor. - void GenerateStructors(io::Printer* printer); - - // The compiler typically generates multiple copies of each constructor and - // destructor: http://gcc.gnu.org/bugs.html#nonbugs_cxx - // Placing common code in a separate method reduces the generated code size. - // - // Generate the shared constructor code. - void GenerateSharedConstructorCode(io::Printer* printer); - // Generate the shared destructor code. - void GenerateSharedDestructorCode(io::Printer* printer); - // Generate the arena-specific destructor code. - void GenerateArenaDestructorCode(io::Printer* printer); - - // Helper for GenerateClear and others. Optionally emits a condition that - // assumes the existence of the cached_has_bits variable, and returns true if - // the condition was printed. - bool MaybeGenerateOptionalFieldCondition(io::Printer* printer, - const FieldDescriptor* field, - int expected_has_bits_index); - - // Generate standard Message methods. - void GenerateClear(io::Printer* printer); - void GenerateOneofClear(io::Printer* printer); - void GenerateMergeFromCodedStream(io::Printer* printer); - void GenerateSerializeWithCachedSizes(io::Printer* printer); - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer); - void GenerateSerializeWithCachedSizesBody(io::Printer* printer, - bool to_array); - void GenerateByteSize(io::Printer* printer); - void GenerateMergeFrom(io::Printer* printer); - void GenerateCopyFrom(io::Printer* printer); - void GenerateSwap(io::Printer* printer); - void GenerateIsInitialized(io::Printer* printer); - - // Helpers for GenerateSerializeWithCachedSizes(). - // - // cached_has_bit_index maintains that: - // cached_has_bits = _has_bits_[cached_has_bit_index] - // for cached_has_bit_index >= 0 - void GenerateSerializeOneField(io::Printer* printer, - const FieldDescriptor* field, - bool unbounded, - int cached_has_bits_index); - // Generate a switch statement to serialize 2+ fields from the same oneof. - // Or, if fields.size() == 1, just call GenerateSerializeOneField(). - void GenerateSerializeOneofFields( - io::Printer* printer, const std::vector& fields, - bool to_array); - void GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* range, - bool unbounded); - - // Generates has_foo() functions and variables for singular field has-bits. - void GenerateSingularFieldHasBits(const FieldDescriptor* field, - std::map vars, - io::Printer* printer); - // Generates has_foo() functions and variables for oneof field has-bits. - void GenerateOneofHasBits(io::Printer* printer); - // Generates has_foo_bar() functions for oneof members. - void GenerateOneofMemberHasBits(const FieldDescriptor* field, - const std::map& vars, - io::Printer* printer); - // Generates the clear_foo() method for a field. - void GenerateFieldClear(const FieldDescriptor* field, - const std::map& vars, - bool is_inline, - io::Printer* printer); - - void GenerateConstructorBody(io::Printer* printer, - std::vector already_processed, - bool copy_constructor) const; - - size_t HasBitsSize() const; - std::vector RequiredFieldsBitMask() const; - - const Descriptor* descriptor_; - int index_in_file_messages_; - string classname_; - Options options_; - FieldGeneratorMap field_generators_; - // optimized_order_ is the order we layout the message's fields in the class. - // This is reused to initialize the fields in-order for cache efficiency. - // - // optimized_order_ excludes oneof fields and weak fields. - std::vector optimized_order_; - std::vector has_bit_indices_; - int max_has_bit_index_; - std::unique_ptr []> enum_generators_; - std::unique_ptr []> extension_generators_; - int num_required_fields_; - int num_weak_fields_; - // table_driven_ indicates the generated message uses table-driven parsing. - bool table_driven_; - - std::unique_ptr message_layout_helper_; - - SCCAnalyzer* scc_analyzer_; - string scc_name_; - - friend class FileGenerator; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_message_field.cc b/windows/include/google/protobuf/compiler/cpp/cpp_message_field.cc deleted file mode 100644 index c1e15c523..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_message_field.cc +++ /dev/null @@ -1,836 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -namespace { - -// When we are generating code for implicit weak fields, we need to insert some -// additional casts. These functions return the casted expression if -// implicit_weak_field is true but otherwise return the original expression. -// Ordinarily a static_cast is enough to cast google::protobuf::MessageLite* to a class -// deriving from it, but we need a reinterpret_cast in cases where the generated -// message is forward-declared but its full definition is not visible. -string StaticCast(const string& type, const string& expression, - bool implicit_weak_field) { - if (implicit_weak_field) { - return "static_cast< " + type + " >(" + expression + ")"; - } else { - return expression; - } -} - -string ReinterpretCast(const string& type, const string& expression, - bool implicit_weak_field) { - if (implicit_weak_field) { - return "reinterpret_cast< " + type + " >(" + expression + ")"; - } else { - return expression; - } -} - -void SetMessageVariables(const FieldDescriptor* descriptor, - const Options& options, bool implicit_weak, - std::map* variables) { - SetCommonFieldVariables(descriptor, variables, options); - (*variables)["type"] = FieldMessageTypeName(descriptor); - (*variables)["casted_member"] = ReinterpretCast( - (*variables)["type"] + "*", (*variables)["name"] + "_", implicit_weak); - (*variables)["type_default_instance"] = - DefaultInstanceName(descriptor->message_type()); - (*variables)["type_reference_function"] = - implicit_weak - ? (" " + ReferenceFunctionName(descriptor->message_type()) + "();\n") - : ""; - (*variables)["stream_writer"] = - (*variables)["declared_type"] + - (HasFastArraySerialization(descriptor->message_type()->file(), options) - ? "MaybeToArray" - : ""); - // NOTE: Escaped here to unblock proto1->proto2 migration. - // TODO(liujisi): Extend this to apply for other conflicting methods. - (*variables)["release_name"] = - SafeFunctionName(descriptor->containing_type(), - descriptor, "release_"); - (*variables)["full_name"] = descriptor->full_name(); -} - -} // namespace - -// =================================================================== - -MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options, - SCCAnalyzer* scc_analyzer) - : FieldGenerator(options), - descriptor_(descriptor), - implicit_weak_field_( - IsImplicitWeakField(descriptor, options, scc_analyzer)) { - SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_); -} - -MessageFieldGenerator::~MessageFieldGenerator() {} - -void MessageFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - if (implicit_weak_field_) { - printer->Print(variables_, "::google::protobuf::MessageLite* $name$_;\n"); - } else { - printer->Print(variables_, "$type$* $name$_;\n"); - } -} - -void MessageFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - if (implicit_weak_field_) { - // These private accessors are used by MergeFrom and - // MergePartialFromCodedStream, and their purpose is to provide access to - // the field without creating a strong dependency on the message type. - printer->Print(variables_, - "private:\n" - "const ::google::protobuf::MessageLite& _internal_$name$() const;\n" - "::google::protobuf::MessageLite* _internal_mutable_$name$();\n" - "public:\n"); - } else { - // This inline accessor directly returns member field and is used in - // Serialize such that AFDO profile correctly captures access information to - // message fields under serialize. - printer->Print(variables_, - "private:\n" - "const $type$& _internal_$name$() const;\n" - "public:\n"); - } - printer->Print(variables_, - "$deprecated_attr$const $type$& $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, "$deprecated_attr$$type$* $release_name$();\n"); - printer->Annotate("release_name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$$type$* ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_allocated_$name$$}$" - "($type$* $name$);\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "$deprecated_attr$void " - "${$unsafe_arena_set_allocated_$name$$}$(\n" - " $type$* $name$);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$$type$* ${$unsafe_arena_release_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( - io::Printer* printer) const { - if (implicit_weak_field_) { - printer->Print(variables_, - "const ::google::protobuf::MessageLite& $classname$::_internal_$name$() const {\n" - " if ($name$_ != NULL) {\n" - " return *$name$_;\n" - " } else if (&$type_default_instance$ != NULL) {\n" - " return *reinterpret_cast(\n" - " &$type_default_instance$);\n" - " } else {\n" - " return " - "*::google::protobuf::internal::ImplicitWeakMessage::default_instance();\n" - " }\n" - "}\n"); - } - if (SupportsArenas(descriptor_)) { - if (implicit_weak_field_) { - printer->Print(variables_, - "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" - " $set_hasbit$\n" - " if ($name$_ == NULL) {\n" - " if (&$type_default_instance$ == NULL) {\n" - " $name$_ = ::google::protobuf::Arena::CreateMessage<\n" - " ::google::protobuf::internal::ImplicitWeakMessage>(\n" - " GetArenaNoVirtual());\n" - " } else {\n" - " $name$_ = reinterpret_cast(\n" - " &$type_default_instance$)->New(GetArenaNoVirtual());\n" - " }\n" - " }\n" - " return $name$_;\n" - "}\n"); - } - - printer->Print(variables_, - "void $classname$::unsafe_arena_set_allocated_$name$(\n" - " $type$* $name$) {\n" - // If we're not on an arena, free whatever we were holding before. - // (If we are on arena, we can just forget the earlier pointer.) - " if (GetArenaNoVirtual() == NULL) {\n" - " delete $name$_;\n" - " }\n" - " $name$_ = $name$;\n" - " if ($name$) {\n" - " $set_hasbit$\n" - " } else {\n" - " $clear_hasbit$\n" - " }\n" - " // @@protoc_insertion_point(field_unsafe_arena_set_allocated" - ":$full_name$)\n" - "}\n"); - } else if (implicit_weak_field_) { - printer->Print(variables_, - "::google::protobuf::MessageLite* $classname$::_internal_mutable_$name$() {\n" - " $set_hasbit$\n" - " if ($name$_ == NULL) {\n" - " if (&$type_default_instance$ == NULL) {\n" - " $name$_ = new ::google::protobuf::internal::ImplicitWeakMessage;\n" - " } else {\n" - " $name$_ = reinterpret_cast(\n" - " &$type_default_instance$)->New();\n" - " }\n" - " }\n" - " return $name$_;\n" - "}\n"); - } -} - -void MessageFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - if (!implicit_weak_field_) { - printer->Print(variables_, - "inline const $type$& $classname$::_internal_$name$() const {\n" - " return *$field_member$;\n" - "}\n"); - } - printer->Print(variables_, - "inline const $type$& $classname$::$name$() const {\n" - " const $type$* p = $casted_member$;\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return p != NULL ? *p : *reinterpret_cast(\n" - " &$type_default_instance$);\n" - "}\n"); - - printer->Print(variables_, - "inline $type$* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" - "$type_reference_function$" - " $clear_hasbit$\n" - " $type$* temp = $casted_member$;\n"); - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - " if (GetArenaNoVirtual() != NULL) {\n" - " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n" - " }\n"); - } - printer->Print(variables_, - " $name$_ = NULL;\n" - " return temp;\n" - "}\n"); - - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "inline $type$* $classname$::unsafe_arena_release_$name$() {\n" - " // @@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" - "$type_reference_function$" - " $clear_hasbit$\n" - " $type$* temp = $casted_member$;\n" - " $name$_ = NULL;\n" - " return temp;\n" - "}\n"); - } - - printer->Print(variables_, - "inline $type$* $classname$::mutable_$name$() {\n" - " $set_hasbit$\n" - " if ($name$_ == NULL) {\n" - " auto* p = CreateMaybeMessage<$type$>(GetArenaNoVirtual());\n"); - if (implicit_weak_field_) { - printer->Print(variables_, - " $name$_ = reinterpret_cast<::google::protobuf::MessageLite*>(p);\n"); - } else { - printer->Print(variables_, - " $name$_ = p;\n"); - } - printer->Print(variables_, - " }\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $casted_member$;\n" - "}\n"); - - // We handle the most common case inline, and delegate less common cases to - // the slow fallback function. - printer->Print(variables_, - "inline void $classname$::set_allocated_$name$($type$* $name$) {\n" - " ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n"); - printer->Print(variables_, - " if (message_arena == NULL) {\n"); - if (IsCrossFileMessage(descriptor_)) { - printer->Print(variables_, - " delete reinterpret_cast< ::google::protobuf::MessageLite*>($name$_);\n"); - } else { - printer->Print(variables_, - " delete $name$_;\n"); - } - printer->Print(variables_, - " }\n" - " if ($name$) {\n"); - if (SupportsArenas(descriptor_->message_type()) && - IsCrossFileMessage(descriptor_)) { - // We have to read the arena through the virtual method, because the type - // isn't defined in this file. - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena =\n" - " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n"); - } else if (!SupportsArenas(descriptor_->message_type())) { - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena = NULL;\n"); - } else { - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena =\n" - " ::google::protobuf::Arena::GetArena($name$);\n"); - } - printer->Print(variables_, - " if (message_arena != submessage_arena) {\n" - " $name$ = ::google::protobuf::internal::GetOwnedMessage(\n" - " message_arena, $name$, submessage_arena);\n" - " }\n" - " $set_hasbit$\n" - " } else {\n" - " $clear_hasbit$\n" - " }\n"); - if (implicit_weak_field_) { - printer->Print(variables_, - " $name$_ = reinterpret_cast($name$);\n"); - } else { - printer->Print(variables_, - " $name$_ = $name$;\n"); - } - printer->Print(variables_, - " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n"); -} - -void MessageFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - if (!HasFieldPresence(descriptor_->file())) { - // If we don't have has-bits, message presence is indicated only by ptr != - // NULL. Thus on clear, we need to delete the object. - printer->Print(variables_, - "if (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n" - " delete $name$_;\n" - "}\n" - "$name$_ = NULL;\n"); - } else { - printer->Print(variables_, - "if ($name$_ != NULL) $name$_->Clear();\n"); - } -} - -void MessageFieldGenerator:: -GenerateMessageClearingCode(io::Printer* printer) const { - if (!HasFieldPresence(descriptor_->file())) { - // If we don't have has-bits, message presence is indicated only by ptr != - // NULL. Thus on clear, we need to delete the object. - printer->Print(variables_, - "if (GetArenaNoVirtual() == NULL && $name$_ != NULL) {\n" - " delete $name$_;\n" - "}\n" - "$name$_ = NULL;\n"); - } else { - printer->Print(variables_, - "GOOGLE_DCHECK($name$_ != NULL);\n" - "$name$_->Clear();\n"); - } -} - -void MessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - if (implicit_weak_field_) { - printer->Print(variables_, - "_internal_mutable_$name$()->CheckTypeAndMergeFrom(\n" - " from._internal_$name$());\n"); - } else { - printer->Print(variables_, - "mutable_$name$()->$type$::MergeFrom(from.$name$());\n"); - } -} - -void MessageFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "swap($name$_, other->$name$_);\n"); -} - -void MessageFieldGenerator:: -GenerateDestructorCode(io::Printer* printer) const { - // TODO(gerbens) Remove this when we don't need to destruct default instances. - // In google3 a default instance will never get deleted so we don't need to - // worry about that but in opensource protobuf default instances are deleted - // in shutdown process and we need to take special care when handling them. - printer->Print(variables_, - "if (this != internal_default_instance()) "); - printer->Print(variables_, "delete $name$_;\n"); -} - -void MessageFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = NULL;\n"); -} - -void MessageFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, - "if (from.has_$name$()) {\n" - " $name$_ = new $type$(*from.$name$_);\n" - "} else {\n" - " $name$_ = NULL;\n" - "}\n"); -} - -void MessageFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - if (implicit_weak_field_) { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(\n" - " input, _internal_mutable_$name$()));\n"); - } else if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(\n" - " input, mutable_$name$()));\n"); - } else { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::ReadGroup(\n" - " $number$, input, mutable_$name$()));\n"); - } -} - -void MessageFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n" - " $number$, this->_internal_$name$(), output);\n"); -} - -void MessageFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::\n" - " InternalWrite$declared_type$ToArray(\n" - " $number$, this->_internal_$name$(), deterministic, target);\n"); -} - -void MessageFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" - " *$field_member$);\n"); -} - -// =================================================================== - -MessageOneofFieldGenerator::MessageOneofFieldGenerator( - const FieldDescriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer) - : MessageFieldGenerator(descriptor, options, scc_analyzer) { - SetCommonOneofFieldVariables(descriptor, &variables_); -} - -MessageOneofFieldGenerator::~MessageOneofFieldGenerator() {} - -void MessageOneofFieldGenerator::GenerateNonInlineAccessorDefinitions( - io::Printer* printer) const { - printer->Print(variables_, - "void $classname$::set_allocated_$name$($type$* $name$) {\n" - " ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();\n" - " clear_$oneof_name$();\n" - " if ($name$) {\n"); - if (SupportsArenas(descriptor_->message_type()) && - descriptor_->file() != descriptor_->message_type()->file()) { - // We have to read the arena through the virtual method, because the type - // isn't defined in this file. - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena =\n" - " reinterpret_cast<::google::protobuf::MessageLite*>($name$)->GetArena();\n"); - } else if (!SupportsArenas(descriptor_->message_type())) { - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena = NULL;\n"); - } else { - printer->Print(variables_, - " ::google::protobuf::Arena* submessage_arena =\n" - " ::google::protobuf::Arena::GetArena($name$);\n"); - } - printer->Print(variables_, - " if (message_arena != submessage_arena) {\n" - " $name$ = ::google::protobuf::internal::GetOwnedMessage(\n" - " message_arena, $name$, submessage_arena);\n" - " }\n" - " set_has_$name$();\n" - " $field_member$ = $name$;\n" - " }\n" - " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n"); -} - -void MessageOneofFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - if (!implicit_weak_field_) { - printer->Print(variables_, - "inline const $type$& $classname$::_internal_$name$() const {\n" - " return *$field_member$;\n" - "}\n"); - } - printer->Print(variables_, - "inline $type$* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" - " if (has_$name$()) {\n" - " clear_has_$oneof_name$();\n" - " $type$* temp = $field_member$;\n"); - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - " if (GetArenaNoVirtual() != NULL) {\n" - " temp = ::google::protobuf::internal::DuplicateIfNonNull(temp);\n" - " }\n"); - } - printer->Print(variables_, - " $field_member$ = NULL;\n" - " return temp;\n" - " } else {\n" - " return NULL;\n" - " }\n" - "}\n"); - - printer->Print(variables_, - "inline const $type$& $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return has_$name$()\n" - " ? *$field_member$\n" - " : *reinterpret_cast< $type$*>(&$type_default_instance$);\n" - "}\n"); - - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "inline $type$* $classname$::unsafe_arena_release_$name$() {\n" - " // @@protoc_insertion_point(field_unsafe_arena_release" - ":$full_name$)\n" - " if (has_$name$()) {\n" - " clear_has_$oneof_name$();\n" - " $type$* temp = $field_member$;\n" - " $field_member$ = NULL;\n" - " return temp;\n" - " } else {\n" - " return NULL;\n" - " }\n" - "}\n" - "inline void $classname$::unsafe_arena_set_allocated_$name$" - "($type$* $name$) {\n" - // We rely on the oneof clear method to free the earlier contents of this - // oneof. We can directly use the pointer we're given to set the new - // value. - " clear_$oneof_name$();\n" - " if ($name$) {\n" - " set_has_$name$();\n" - " $field_member$ = $name$;\n" - " }\n" - " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" - "$full_name$)\n" - "}\n"); - } - - printer->Print(variables_, - "inline $type$* $classname$::mutable_$name$() {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$ = CreateMaybeMessage< $type$ >(\n" - " GetArenaNoVirtual());\n" - " }\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $field_member$;\n" - "}\n"); -} - -void MessageOneofFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "if (GetArenaNoVirtual() == NULL) {\n" - " delete $field_member$;\n" - "}\n"); - } else { - printer->Print(variables_, - "delete $field_member$;\n"); - } -} - -void MessageOneofFieldGenerator:: -GenerateMessageClearingCode(io::Printer* printer) const { - GenerateClearingCode(printer); -} - -void MessageOneofFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - // Don't print any swapping code. Swapping the union will swap this field. -} - -void MessageOneofFieldGenerator:: -GenerateDestructorCode(io::Printer* printer) const { - // We inherit from MessageFieldGenerator, so we need to override the default - // behavior. -} - -void MessageOneofFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - // Don't print any constructor code. The field is in a union. We allocate - // space only when this field is used. -} - -// =================================================================== - -RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( - const FieldDescriptor* descriptor, const Options& options, - SCCAnalyzer* scc_analyzer) - : FieldGenerator(options), - descriptor_(descriptor), - implicit_weak_field_( - IsImplicitWeakField(descriptor, options, scc_analyzer)) { - SetMessageVariables(descriptor, options, implicit_weak_field_, &variables_); -} - -RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {} - -void RepeatedMessageFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::RepeatedPtrField< $type$ > $name$_;\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, - "$deprecated_attr$$type$* ${$mutable_$name$$}$(int index);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::RepeatedPtrField< $type$ >*\n" - " ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - - printer->Print(variables_, - "$deprecated_attr$const $type$& $name$(int index) const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, "$deprecated_attr$$type$* ${$add_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< $type$ >&\n" - " $name$() const;\n"); - printer->Annotate("name", descriptor_); -} - -void RepeatedMessageFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$* $classname$::mutable_$name$(int index) {\n" - // TODO(dlj): move insertion points - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - "$type_reference_function$" - " return $name$_.Mutable(index);\n" - "}\n" - "inline ::google::protobuf::RepeatedPtrField< $type$ >*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" - "$type_reference_function$" - " return &$name$_;\n" - "}\n"); - - if (options_.safe_boundary_check) { - printer->Print(variables_, - "inline const $type$& $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.InternalCheckedGet(index,\n" - " *reinterpret_cast(&$type_default_instance$));\n" - "}\n"); - } else { - printer->Print(variables_, - "inline const $type$& $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - "$type_reference_function$" - " return $name$_.Get(index);\n" - "}\n"); - } - - printer->Print(variables_, - "inline $type$* $classname$::add_$name$() {\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - " return $name$_.Add();\n" - "}\n"); - - printer->Print(variables_, - "inline const ::google::protobuf::RepeatedPtrField< $type$ >&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_list:$full_name$)\n" - "$type_reference_function$" - " return $name$_;\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - if (implicit_weak_field_) { - printer->Print( - variables_, - "CastToBase(&$name$_)->Clear<" - "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>();\n"); - } else { - printer->Print(variables_, "$name$_.Clear();\n"); - } -} - -void RepeatedMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - if (implicit_weak_field_) { - printer->Print( - variables_, - "CastToBase(&$name$_)->MergeFrom<" - "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>(CastToBase(" - "from.$name$_));\n"); - } else { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); - } -} - -void RepeatedMessageFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print( - variables_, - "CastToBase(&$name$_)->InternalSwap(CastToBase(&other->$name$_));\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - // Not needed for repeated fields. -} - -void RepeatedMessageFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE) { - if (implicit_weak_field_) { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::" - "ReadMessage(input, CastToBase(&$name$_)->AddWeak(\n" - " reinterpret_cast(\n" - " &$type_default_instance$))));\n"); - } else { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::" - "ReadMessage(\n" - " input, add_$name$()));\n"); - } - } else { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::" - "ReadGroup($number$, input, add_$name$()));\n"); - } -} - -void RepeatedMessageFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "for (unsigned int i = 0,\n" - " n = static_cast(this->$name$_size()); i < n; i++) {\n" - " ::google::protobuf::internal::WireFormatLite::Write$stream_writer$(\n" - " $number$,\n"); - if (implicit_weak_field_) { - printer->Print( - variables_, - " CastToBase($name$_).Get<" - "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>(" - "static_cast(i)),\n"); - } else { - printer->Print(variables_, - " this->$name$(static_cast(i)),\n"); - } - printer->Print(variables_, - " output);\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "for (unsigned int i = 0,\n" - " n = static_cast(this->$name$_size()); i < n; i++) {\n" - " target = ::google::protobuf::internal::WireFormatLite::\n" - " InternalWrite$declared_type$ToArray(\n" - " $number$, this->$name$(static_cast(i)), deterministic, target);\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " unsigned int count = static_cast(this->$name$_size());\n"); - printer->Indent(); - printer->Print(variables_, - "total_size += $tag_size$UL * count;\n" - "for (unsigned int i = 0; i < count; i++) {\n" - " total_size +=\n" - " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n"); - if (implicit_weak_field_) { - printer->Print( - variables_, - " CastToBase($name$_).Get<" - "::google::protobuf::internal::ImplicitWeakTypeHandler<$type$>>(" - "static_cast(i)));\n"); - } else { - printer->Print(variables_, - " this->$name$(static_cast(i)));\n"); - } - printer->Print(variables_, "}\n"); - printer->Outdent(); - printer->Print("}\n"); -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_message_field.h b/windows/include/google/protobuf/compiler/cpp/cpp_message_field.h deleted file mode 100644 index 6879539c7..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_message_field.h +++ /dev/null @@ -1,136 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__ - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -class MessageFieldGenerator : public FieldGenerator { - public: - MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options, SCCAnalyzer* scc_analyzer); - ~MessageFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMessageClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateDestructorCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateCopyConstructorCode(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - - protected: - const FieldDescriptor* descriptor_; - const bool implicit_weak_field_; - std::map variables_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); -}; - -class MessageOneofFieldGenerator : public MessageFieldGenerator { - public: - MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options, SCCAnalyzer* scc_analyzer); - ~MessageOneofFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - - // MessageFieldGenerator, from which we inherit, overrides this so we need to - // override it as well. - void GenerateMessageClearingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateDestructorCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator); -}; - -class RepeatedMessageFieldGenerator : public FieldGenerator { - public: - RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options, - SCCAnalyzer* scc_analyzer); - ~RepeatedMessageFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateCopyConstructorCode(io::Printer* printer) const {} - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - const bool implicit_weak_field_; - std::map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_message_layout_helper.h b/windows/include/google/protobuf/compiler/cpp/cpp_message_layout_helper.h deleted file mode 100644 index d502a6f0d..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_message_layout_helper.h +++ /dev/null @@ -1,61 +0,0 @@ -// 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. - -// Author: seongkim@google.com (Seong Beom Kim) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__ - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -// Provides an abstract interface to optimize message layout -// by rearranging the fields of a message. -class MessageLayoutHelper { - public: - virtual ~MessageLayoutHelper() {} - - virtual void OptimizeLayout(std::vector* fields, - const Options& options) = 0; -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_move_unittest.cc b/windows/include/google/protobuf/compiler/cpp/cpp_move_unittest.cc deleted file mode 100644 index eb7cd1c77..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_move_unittest.cc +++ /dev/null @@ -1,169 +0,0 @@ -// 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. - -#include -#include -#include -#include - -#if LANG_CXX11 -#include -#endif - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -// Can't use an anonymous namespace here due to brokenness of Tru64 compiler. -namespace cpp_unittest { - -// Moves are enabled only when compiling with a C++11 compiler or newer. -#if LANG_CXX11 - -TEST(MovableMessageTest, MoveConstructor) { - protobuf_unittest::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - const auto* nested = &message1.optional_nested_message(); - - protobuf_unittest::TestAllTypes message2(std::move(message1)); - TestUtil::ExpectAllFieldsSet(message2); - - // Check if the optional_nested_message was actually moved (and not just - // copied). - EXPECT_EQ(nested, &message2.optional_nested_message()); - EXPECT_NE(nested, &message1.optional_nested_message()); -} - -TEST(MovableMessageTest, MoveAssignmentOperator) { - protobuf_unittest::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - const auto* nested = &message1.optional_nested_message(); - - protobuf_unittest::TestAllTypes message2; - message2 = std::move(message1); - TestUtil::ExpectAllFieldsSet(message2); - - // Check if the optional_nested_message was actually moved (and not just - // copied). - EXPECT_EQ(nested, &message2.optional_nested_message()); - EXPECT_NE(nested, &message1.optional_nested_message()); -} - -TEST(MovableMessageTest, SelfMoveAssignment) { - // The `self` reference is necessary to defeat -Wself-move. - protobuf_unittest::TestAllTypes message, &self = message; - TestUtil::SetAllFields(&message); - message = std::move(self); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(MovableMessageTest, MoveSameArena) { - Arena arena; - - auto* message1_on_arena = - Arena::CreateMessage(&arena); - TestUtil::SetAllFields(message1_on_arena); - const auto* nested = &message1_on_arena->optional_nested_message(); - - auto* message2_on_arena = - Arena::CreateMessage(&arena); - - // Moving messages on the same arena should lead to swapped pointers. - *message2_on_arena = std::move(*message1_on_arena); - EXPECT_EQ(nested, &message2_on_arena->optional_nested_message()); -} - -TEST(MovableMessageTest, MoveDifferentArenas) { - Arena arena1, arena2; - - auto* message1_on_arena = - Arena::CreateMessage(&arena1); - TestUtil::SetAllFields(message1_on_arena); - const auto* nested = &message1_on_arena->optional_nested_message(); - - auto* message2_on_arena = - Arena::CreateMessage(&arena2); - - // Moving messages on two different arenas should lead to a copy. - *message2_on_arena = std::move(*message1_on_arena); - EXPECT_NE(nested, &message2_on_arena->optional_nested_message()); - TestUtil::ExpectAllFieldsSet(*message1_on_arena); - TestUtil::ExpectAllFieldsSet(*message2_on_arena); -} - -TEST(MovableMessageTest, MoveFromArena) { - Arena arena; - - auto* message1_on_arena = - Arena::CreateMessage(&arena); - TestUtil::SetAllFields(message1_on_arena); - const auto* nested = &message1_on_arena->optional_nested_message(); - - protobuf_unittest::TestAllTypes message2; - - // Moving from a message on the arena should lead to a copy. - message2 = std::move(*message1_on_arena); - EXPECT_NE(nested, &message2.optional_nested_message()); - TestUtil::ExpectAllFieldsSet(*message1_on_arena); - TestUtil::ExpectAllFieldsSet(message2); -} - -TEST(MovableMessageTest, MoveToArena) { - Arena arena; - - protobuf_unittest::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - const auto* nested = &message1.optional_nested_message(); - - auto* message2_on_arena = - Arena::CreateMessage(&arena); - - // Moving to a message on the arena should lead to a copy. - *message2_on_arena = std::move(message1); - EXPECT_NE(nested, &message2_on_arena->optional_nested_message()); - TestUtil::ExpectAllFieldsSet(message1); - TestUtil::ExpectAllFieldsSet(*message2_on_arena); -} - -TEST(MovableMessageTest, Noexcept) { - EXPECT_TRUE( - std::is_nothrow_move_constructible()); - EXPECT_TRUE(std::is_nothrow_move_assignable()); -} - -#endif // LANG_CXX11 - -} // namespace cpp_unittest - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_names.h b/windows/include/google/protobuf/compiler/cpp/cpp_names.h new file mode 100644 index 000000000..6bcbff061 --- /dev/null +++ b/windows/include/google/protobuf/compiler/cpp/cpp_names.h @@ -0,0 +1,96 @@ +// 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_CPP_NAMES_H__ +#define GOOGLE_PROTOBUF_COMPILER_CPP_NAMES_H__ + +#include + +#include + +namespace google { +namespace protobuf { + +class Descriptor; +class EnumDescriptor; +class EnumValueDescriptor; +class FieldDescriptor; + +namespace compiler { +namespace cpp { + +// Returns the unqualified C++ name. +// +// For example, if you had: +// package foo.bar; +// message Baz { message Qux {} } +// Then the non-qualified version would be: +// Baz_Qux +std::string ClassName(const Descriptor* descriptor); +std::string ClassName(const EnumDescriptor* enum_descriptor); + +// Returns the fully qualified C++ name. +// +// For example, if you had: +// package foo.bar; +// message Baz { message Qux {} } +// Then the qualified ClassName for Qux would be: +// ::foo::bar::Baz_Qux +std::string QualifiedClassName(const Descriptor* d); +std::string QualifiedClassName(const EnumDescriptor* d); +std::string QualifiedExtensionName(const FieldDescriptor* d); + +// Get the (unqualified) name that should be used for this field in C++ code. +// The name is coerced to lower-case to emulate proto1 behavior. People +// should be using lowercase-with-underscores style for proto field names +// anyway, so normally this just returns field->name(). +std::string FieldName(const FieldDescriptor* field); + +// Requires that this field is in a oneof. Returns the (unqualified) case +// constant for this field. +std::string OneofCaseConstantName(const FieldDescriptor* field); +// Returns the quafilied case constant for this field. +std::string QualifiedOneofCaseConstantName(const FieldDescriptor* field); + +// Get the (unqualified) name that should be used for this enum value in C++ +// code. +std::string EnumValueName(const EnumValueDescriptor* enum_value); + +// Strips ".proto" or ".protodevel" from the end of a filename. +PROTOC_EXPORT std::string StripProto(const std::string& filename); + +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google + +#include + +#endif // GOOGLE_PROTOBUF_COMPILER_CPP_NAMES_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_options.h b/windows/include/google/protobuf/compiler/cpp/cpp_options.h deleted file mode 100644 index f09885beb..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_options.h +++ /dev/null @@ -1,83 +0,0 @@ -// 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. - -// Author: rennie@google.com (Jeffrey Rennie) - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_OPTIONS_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_OPTIONS_H__ - -#include - -#include -namespace google { -namespace protobuf { -namespace compiler { -class AccessInfoMap; - -namespace cpp { - -// Generator options (see generator.cc for a description of each): -struct Options { - Options() - : safe_boundary_check(false), - proto_h(false), - transitive_pb_h(true), - annotate_headers(false), - enforce_lite(false), - table_driven_parsing(false), - table_driven_serialization(false), - lite_implicit_weak_fields(false), - bootstrap(false), - num_cc_files(0), - access_info_map(NULL) {} - - string dllexport_decl; - bool safe_boundary_check; - bool proto_h; - bool transitive_pb_h; - bool annotate_headers; - bool enforce_lite; - bool table_driven_parsing; - bool table_driven_serialization; - bool lite_implicit_weak_fields; - bool bootstrap; - int num_cc_files; - string annotation_pragma_name; - string annotation_guard_name; - const AccessInfoMap* access_info_map; -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_OPTIONS_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc b/windows/include/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc deleted file mode 100644 index e9303865c..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc +++ /dev/null @@ -1,220 +0,0 @@ -// 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. - -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -namespace { - -// FieldGroup is just a helper for PaddingOptimizer below. It holds a vector of -// fields that are grouped together because they have compatible alignment, and -// a preferred location in the final field ordering. -class FieldGroup { - public: - FieldGroup() : preferred_location_(0) {} - - // A group with a single field. - FieldGroup(float preferred_location, const FieldDescriptor* field) - : preferred_location_(preferred_location), fields_(1, field) {} - - // Append the fields in 'other' to this group. - void Append(const FieldGroup& other) { - if (other.fields_.empty()) { - return; - } - // Preferred location is the average among all the fields, so we weight by - // the number of fields on each FieldGroup object. - preferred_location_ = (preferred_location_ * fields_.size() + - (other.preferred_location_ * other.fields_.size())) / - (fields_.size() + other.fields_.size()); - fields_.insert(fields_.end(), other.fields_.begin(), other.fields_.end()); - } - - void SetPreferredLocation(float location) { preferred_location_ = location; } - const std::vector& fields() const { return fields_; } - - // FieldGroup objects sort by their preferred location. - bool operator<(const FieldGroup& other) const { - return preferred_location_ < other.preferred_location_; - } - - private: - // "preferred_location_" is an estimate of where this group should go in the - // final list of fields. We compute this by taking the average index of each - // field in this group in the original ordering of fields. This is very - // approximate, but should put this group close to where its member fields - // originally went. - float preferred_location_; - std::vector fields_; - // We rely on the default copy constructor and operator= so this type can be - // used in a vector. -}; - -} // namespace - -// Reorder 'fields' so that if the fields are output into a c++ class in the new -// order, fields of similar family (see below) are together and within each -// family, alignment padding is minimized. -// -// We try to do this while keeping each field as close as possible to its field -// number order so that we don't reduce cache locality much for function that -// access each field in order. Originally, OptimizePadding used declaration -// order for its decisions, but generated code minus the serializer/parsers uses -// the output of OptimizePadding as well (stored in -// MessageGenerator::optimized_order_). Since the serializers use field number -// order, we use that as a tie-breaker. -// -// We classify each field into a particular "family" of fields, that we perform -// the same operation on in our generated functions. -// -// REPEATED is placed first, as the C++ compiler automatically initializes -// these fields in layout order. -// -// STRING is grouped next, as our Clear/SharedCtor/SharedDtor walks it and -// calls ArenaStringPtr::Destroy on each. -// -// -// MESSAGE is grouped next, as our Clear/SharedDtor code walks it and calls -// delete on each. We initialize these fields with a NULL pointer (see -// MessageFieldGenerator::GenerateConstructorCode), which allows them to be -// memset. -// -// ZERO_INITIALIZABLE is memset in Clear/SharedCtor -// -// OTHER these fields are initialized one-by-one. -void PaddingOptimizer::OptimizeLayout( - std::vector* fields, const Options& options) { - // The sorted numeric order of Family determines the declaration order in the - // memory layout. - enum Family { - REPEATED = 0, - STRING = 1, - MESSAGE = 3, - ZERO_INITIALIZABLE = 4, - OTHER = 5, - kMaxFamily - }; - - // First divide fields into those that align to 1 byte, 4 bytes or 8 bytes. - std::vector aligned_to_1[kMaxFamily]; - std::vector aligned_to_4[kMaxFamily]; - std::vector aligned_to_8[kMaxFamily]; - for (int i = 0; i < fields->size(); ++i) { - const FieldDescriptor* field = (*fields)[i]; - - Family f = OTHER; - if (field->is_repeated()) { - f = REPEATED; - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { - f = STRING; - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - f = MESSAGE; - - } else if (CanInitializeByZeroing(field)) { - f = ZERO_INITIALIZABLE; - } - - const int j = field->number(); - switch (EstimateAlignmentSize(field)) { - case 1: - aligned_to_1[f].push_back(FieldGroup(j, field)); - break; - case 4: - aligned_to_4[f].push_back(FieldGroup(j, field)); - break; - case 8: - aligned_to_8[f].push_back(FieldGroup(j, field)); - break; - default: - GOOGLE_LOG(FATAL) << "Unknown alignment size " << EstimateAlignmentSize(field) - << "for a field " << field->full_name() << "."; - } - } - - // For each family, group fields to optimize padding. - for (int f = 0; f < kMaxFamily; f++) { - // Now group fields aligned to 1 byte into sets of 4, and treat those like a - // single field aligned to 4 bytes. - for (int i = 0; i < aligned_to_1[f].size(); i += 4) { - FieldGroup field_group; - for (int j = i; j < aligned_to_1[f].size() && j < i + 4; ++j) { - field_group.Append(aligned_to_1[f][j]); - } - aligned_to_4[f].push_back(field_group); - } - // Sort by preferred location to keep fields as close to their field number - // order as possible. Using stable_sort ensures that the output is - // consistent across runs. - std::stable_sort(aligned_to_4[f].begin(), aligned_to_4[f].end()); - - // Now group fields aligned to 4 bytes (or the 4-field groups created above) - // into pairs, and treat those like a single field aligned to 8 bytes. - for (int i = 0; i < aligned_to_4[f].size(); i += 2) { - FieldGroup field_group; - for (int j = i; j < aligned_to_4[f].size() && j < i + 2; ++j) { - field_group.Append(aligned_to_4[f][j]); - } - if (i == aligned_to_4[f].size() - 1) { - if (f == OTHER) { - // Move incomplete 4-byte block to the beginning. This is done to - // pair with the (possible) leftover blocks from the - // ZERO_INITIALIZABLE family. - field_group.SetPreferredLocation(-1); - } else { - // Move incomplete 4-byte block to the end. - field_group.SetPreferredLocation(fields->size() + 1); - } - } - aligned_to_8[f].push_back(field_group); - } - // Sort by preferred location. - std::stable_sort(aligned_to_8[f].begin(), aligned_to_8[f].end()); - } - - // Now pull out all the FieldDescriptors in order. - fields->clear(); - for (int f = 0; f < kMaxFamily; ++f) { - for (int i = 0; i < aligned_to_8[f].size(); ++i) { - fields->insert(fields->end(), aligned_to_8[f][i].fields().begin(), - aligned_to_8[f][i].fields().end()); - } - } -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_padding_optimizer.h b/windows/include/google/protobuf/compiler/cpp/cpp_padding_optimizer.h deleted file mode 100644 index 42a3b5cdf..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_padding_optimizer.h +++ /dev/null @@ -1,64 +0,0 @@ -// 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. - -// Author: seongkim@google.com (Seong Beom Kim) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__ - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -// Rearranges the fields of a message to minimize padding. -// Fields are grouped by the type and the size. -// For example, grouping four boolean fields and one int32 -// field results in zero padding overhead. See OptimizeLayout's -// comment for details. -class PaddingOptimizer : public MessageLayoutHelper { - public: - PaddingOptimizer() {} - ~PaddingOptimizer() override {} - - void OptimizeLayout(std::vector* fields, - const Options& options) override; -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc b/windows/include/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc deleted file mode 100644 index ff6ba0f81..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc +++ /dev/null @@ -1,249 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// -// TODO(kenton): Share code with the versions of this test in other languages? -// It seemed like parameterizing it would add more complexity than it is -// worth. - -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { -namespace { - -class TestGenerator : public CodeGenerator { - public: - TestGenerator() {} - ~TestGenerator() {} - - virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - TryInsert("test.pb.h", "includes", context); - TryInsert("test.pb.h", "namespace_scope", context); - TryInsert("test.pb.h", "global_scope", context); - TryInsert("test.pb.h", "class_scope:foo.Bar", context); - TryInsert("test.pb.h", "class_scope:foo.Bar.Baz", context); - - TryInsert("test.pb.cc", "includes", context); - TryInsert("test.pb.cc", "namespace_scope", context); - TryInsert("test.pb.cc", "global_scope", context); - - // Check field accessors for an optional int32: - TryInsert("test.pb.h", "field_get:foo.Bar.optInt", context); - TryInsert("test.pb.h", "field_set:foo.Bar.optInt", context); - - // Check field accessors for a repeated int32: - TryInsert("test.pb.h", "field_get:foo.Bar.repeatedInt", context); - TryInsert("test.pb.h", "field_set:foo.Bar.repeatedInt", context); - - // Check field accessors for a required string: - TryInsert("test.pb.h", "field_get:foo.Bar.requiredString", context); - TryInsert("test.pb.h", "field_set:foo.Bar.requiredString", context); - TryInsert("test.pb.h", "field_set_char:foo.Bar.requiredString", context); - TryInsert("test.pb.h", "field_set_pointer:foo.Bar.requiredString", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.requiredString", context); - TryInsert("test.pb.h", "field_set_allocated:foo.Bar.requiredString", - context); - TryInsert("test.pb.h", "field_set_char:foo.Bar.requiredString", context); - TryInsert("test.pb.h", "field_set_pointer:foo.Bar.requiredString", context); - - // Check field accessors for a repeated string: - TryInsert("test.pb.h", "field_get:foo.Bar.repeatedString", context); - TryInsert("test.pb.h", "field_set:foo.Bar.repeatedString", context); - TryInsert("test.pb.h", "field_set_char:foo.Bar.repeatedString", context); - TryInsert("test.pb.h", "field_set_pointer:foo.Bar.repeatedString", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.repeatedString", context); - TryInsert("test.pb.h", "field_set_char:foo.Bar.repeatedString", context); - TryInsert("test.pb.h", "field_set_pointer:foo.Bar.repeatedString", context); - - // Check field accessors for an int inside oneof{}: - TryInsert("test.pb.h", "field_get:foo.Bar.oneOfInt", context); - TryInsert("test.pb.h", "field_set:foo.Bar.oneOfInt", context); - - // Check field accessors for a string inside oneof{}: - TryInsert("test.pb.h", "field_get:foo.Bar.oneOfString", context); - TryInsert("test.pb.h", "field_set:foo.Bar.oneOfString", context); - TryInsert("test.pb.h", "field_set_char:foo.Bar.oneOfString", context); - TryInsert("test.pb.h", "field_set_pointer:foo.Bar.oneOfString", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.oneOfString", context); - TryInsert("test.pb.h", "field_set_allocated:foo.Bar.oneOfString", context); - TryInsert("test.pb.h", "field_set_char:foo.Bar.oneOfString", context); - TryInsert("test.pb.h", "field_set_pointer:foo.Bar.oneOfString", context); - - // Check field accessors for an optional message: - TryInsert("test.pb.h", "field_get:foo.Bar.optMessage", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.optMessage", context); - TryInsert("test.pb.h", "field_set_allocated:foo.Bar.optMessage", context); - - // Check field accessors for a repeated message: - TryInsert("test.pb.h", "field_add:foo.Bar.repeatedMessage", context); - TryInsert("test.pb.h", "field_get:foo.Bar.repeatedMessage", context); - TryInsert("test.pb.h", "field_list:foo.Bar.repeatedMessage", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.repeatedMessage", context); - TryInsert("test.pb.h", "field_mutable_list:foo.Bar.repeatedMessage", - context); - - // Check field accessors for a message inside oneof{}: - TryInsert("test.pb.h", "field_get:foo.Bar.oneOfMessage", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.oneOfMessage", context); - TryInsert("test.pb.cc", "field_set_allocated:foo.Bar.oneOfMessage", context); - - // Check field accessors for an optional enum: - TryInsert("test.pb.h", "field_get:foo.Bar.optEnum", context); - TryInsert("test.pb.h", "field_set:foo.Bar.optEnum", context); - - // Check field accessors for a repeated enum: - TryInsert("test.pb.h", "field_get:foo.Bar.repeatedEnum", context); - TryInsert("test.pb.h", "field_set:foo.Bar.repeatedEnum", context); - TryInsert("test.pb.h", "field_add:foo.Bar.repeatedEnum", context); - TryInsert("test.pb.h", "field_list:foo.Bar.repeatedEnum", context); - TryInsert("test.pb.h", "field_mutable_list:foo.Bar.repeatedEnum", context); - - // Check field accessors for an enum inside oneof{}: - TryInsert("test.pb.h", "field_get:foo.Bar.oneOfEnum", context); - TryInsert("test.pb.h", "field_set:foo.Bar.oneOfEnum", context); - - // Check field accessors for a required cord: - TryInsert("test.pb.h", "field_get:foo.Bar.requiredCord", context); - TryInsert("test.pb.h", "field_set:foo.Bar.requiredCord", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.requiredCord", context); - - // Check field accessors for a repeated cord: - TryInsert("test.pb.h", "field_get:foo.Bar.repeatedCord", context); - TryInsert("test.pb.h", "field_set:foo.Bar.repeatedCord", context); - TryInsert("test.pb.h", "field_add:foo.Bar.repeatedCord", context); - TryInsert("test.pb.h", "field_list:foo.Bar.repeatedCord", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.repeatedCord", context); - TryInsert("test.pb.h", "field_mutable_list:foo.Bar.repeatedCord", context); - - // Check field accessors for a cord inside oneof{}: - TryInsert("test.pb.h", "field_get:foo.Bar.oneOfCord", context); - TryInsert("test.pb.h", "field_set:foo.Bar.oneOfCord", context); - TryInsert("test.pb.h", "field_mutable:foo.Bar.oneOfCord", context); - - return true; - } - - void TryInsert(const string& filename, const string& insertion_point, - GeneratorContext* context) const { - std::unique_ptr output( - context->OpenForInsert(filename, insertion_point)); - io::Printer printer(output.get(), '$'); - printer.Print("// inserted $name$\n", "name", insertion_point); - } -}; - -// This test verifies that all the expected insertion points exist. It does -// not verify that they are correctly-placed; that would require actually -// compiling the output which is a bit more than I care to do for this test. -TEST(CppPluginTest, PluginTest) { - GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/test.proto", - "syntax = \"proto2\";\n" - "package foo;\n" - "\n" - "enum Thud { VALUE = 0; }\n" - "\n" - "message Bar {\n" - " message Baz {}\n" - " optional int32 optInt = 1;\n" - " repeated int32 repeatedInt = 2;\n" - "\n" - " required string requiredString = 3;\n" - " repeated string repeatedString = 4;\n" - "\n" - " optional Baz optMessage = 6;\n" - " repeated Baz repeatedMessage = 7;\n" - "\n" - " optional Thud optEnum = 8;\n" - " repeated Thud repeatedEnum = 9;\n" - "\n" - " required string requiredCord = 10 [\n" - " ctype = CORD\n" - " ];\n" - " repeated string repeatedCord = 11 [\n" - " ctype = CORD\n" - " ];\n" - "\n" - " oneof Qux {\n" - " int64 oneOfInt = 20;\n" - " string oneOfString = 21;\n" - " Baz oneOfMessage = 22;\n" - " Thud oneOfEnum = 23;" - " string oneOfCord = 24 [\n" - " ctype = CORD\n" - " ];\n" - " }\n" - "}\n", - true)); - - google::protobuf::compiler::CommandLineInterface cli; - cli.SetInputsAreProtoPathRelative(true); - - CppGenerator cpp_generator; - TestGenerator test_generator; - cli.RegisterGenerator("--cpp_out", &cpp_generator, ""); - cli.RegisterGenerator("--test_out", &test_generator, ""); - - string proto_path = "-I" + TestTempDir(); - string cpp_out = "--cpp_out=" + TestTempDir(); - string test_out = "--test_out=" + TestTempDir(); - - const char* argv[] = { - "protoc", - proto_path.c_str(), - cpp_out.c_str(), - test_out.c_str(), - "test.proto" - }; - - EXPECT_EQ(0, cli.Run(5, argv)); -} - -} // namespace -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_primitive_field.cc b/windows/include/google/protobuf/compiler/cpp/cpp_primitive_field.cc deleted file mode 100644 index 701f9d2dc..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_primitive_field.cc +++ /dev/null @@ -1,481 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -using internal::WireFormatLite; - -namespace { - -// For encodings with fixed sizes, returns that size in bytes. Otherwise -// returns -1. -int FixedSize(FieldDescriptor::Type type) { - switch (type) { - case FieldDescriptor::TYPE_INT32 : return -1; - case FieldDescriptor::TYPE_INT64 : return -1; - case FieldDescriptor::TYPE_UINT32 : return -1; - case FieldDescriptor::TYPE_UINT64 : return -1; - case FieldDescriptor::TYPE_SINT32 : return -1; - case FieldDescriptor::TYPE_SINT64 : return -1; - case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size; - case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size; - case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size; - case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size; - case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize; - case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize; - - case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize; - case FieldDescriptor::TYPE_ENUM : return -1; - - case FieldDescriptor::TYPE_STRING : return -1; - case FieldDescriptor::TYPE_BYTES : return -1; - case FieldDescriptor::TYPE_GROUP : return -1; - case FieldDescriptor::TYPE_MESSAGE : return -1; - - // No default because we want the compiler to complain if any new - // types are added. - } - GOOGLE_LOG(FATAL) << "Can't get here."; - return -1; -} - -void SetPrimitiveVariables(const FieldDescriptor* descriptor, - std::map* variables, - const Options& options) { - SetCommonFieldVariables(descriptor, variables, options); - (*variables)["type"] = PrimitiveTypeName(descriptor->cpp_type()); - (*variables)["default"] = DefaultValue(descriptor); - (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor)); - int fixed_size = FixedSize(descriptor->type()); - if (fixed_size != -1) { - (*variables)["fixed_size"] = SimpleItoa(fixed_size); - } - (*variables)["wire_format_field_type"] = - "::google::protobuf::internal::WireFormatLite::" + FieldDescriptorProto_Type_Name( - static_cast(descriptor->type())); - (*variables)["full_name"] = descriptor->full_name(); -} - -} // namespace - -// =================================================================== - -PrimitiveFieldGenerator::PrimitiveFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { - SetPrimitiveVariables(descriptor, &variables_, options); -} - -PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {} - -void PrimitiveFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, "$type$ $name$_;\n"); -} - -void PrimitiveFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, "$deprecated_attr$$type$ $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$($type$ value);\n"); - printer->Annotate("{", "}", descriptor_); -} - -void PrimitiveFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_;\n" - "}\n" - "inline void $classname$::set_$name$($type$ value) {\n" - " $set_hasbit$\n" - " $name$_ = value;\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n"); -} - -void PrimitiveFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void PrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "set_$name$(from.$name$());\n"); -} - -void PrimitiveFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "swap($name$_, other->$name$_);\n"); -} - -void PrimitiveFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void PrimitiveFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = from.$name$_;\n"); -} - -void PrimitiveFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "$set_hasbit$\n" - "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " $type$, $wire_format_field_type$>(\n" - " input, &$name$_)));\n"); -} - -void PrimitiveFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::internal::WireFormatLite::Write$declared_type$(" - "$number$, this->$name$(), output);\n"); -} - -void PrimitiveFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray(" - "$number$, this->$name$(), target);\n"); -} - -void PrimitiveFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - int fixed_size = FixedSize(descriptor_->type()); - if (fixed_size == -1) { - printer->Print(variables_, - "total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" - " this->$name$());\n"); - } else { - printer->Print(variables_, - "total_size += $tag_size$ + $fixed_size$;\n"); - } -} - -// =================================================================== - -PrimitiveOneofFieldGenerator:: -PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : PrimitiveFieldGenerator(descriptor, options) { - SetCommonOneofFieldVariables(descriptor, &variables_); -} - -PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {} - -void PrimitiveOneofFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " if (has_$name$()) {\n" - " return $field_member$;\n" - " }\n" - " return $default$;\n" - "}\n" - "inline void $classname$::set_$name$($type$ value) {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " }\n" - " $field_member$ = value;\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n"); -} - -void PrimitiveOneofFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$field_member$ = $default$;\n"); -} - -void PrimitiveOneofFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - // Don't print any swapping code. Swapping the union will swap this field. -} - -void PrimitiveOneofFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print(variables_, - "$ns$::_$classname$_default_instance_.$name$_ = $default$;\n"); -} - -void PrimitiveOneofFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "clear_$oneof_name$();\n" - "DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n" - " $type$, $wire_format_field_type$>(\n" - " input, &$field_member$)));\n" - "set_has_$name$();\n"); -} - -// =================================================================== - -RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { - SetPrimitiveVariables(descriptor, &variables_, options); - - if (descriptor->is_packed()) { - variables_["packed_reader"] = "ReadPackedPrimitive"; - variables_["repeated_reader"] = "ReadRepeatedPrimitiveNoInline"; - } else { - variables_["packed_reader"] = "ReadPackedPrimitiveNoInline"; - variables_["repeated_reader"] = "ReadRepeatedPrimitive"; - } -} - -RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {} - -void RepeatedPrimitiveFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::RepeatedField< $type$ > $name$_;\n"); - if (descriptor_->is_packed() && - HasGeneratedMethods(descriptor_->file(), options_)) { - printer->Print(variables_, - "mutable int _$name$_cached_byte_size_;\n"); - } -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - printer->Print(variables_, - "$deprecated_attr$$type$ $name$(int index) const;\n"); - printer->Annotate("name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$set_$name$$}$(int index, $type$ value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$add_$name$$}$($type$ value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$const ::google::protobuf::RepeatedField< $type$ >&\n" - " $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::RepeatedField< $type$ >*\n" - " ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - printer->Print(variables_, - "inline $type$ $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.Get(index);\n" - "}\n" - "inline void $classname$::set_$name$(int index, $type$ value) {\n" - " $name$_.Set(index, value);\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n" - "inline void $classname$::add_$name$($type$ value) {\n" - " $name$_.Add(value);\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "}\n" - "inline const ::google::protobuf::RepeatedField< $type$ >&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_list:$full_name$)\n" - " return $name$_;\n" - "}\n" - "inline ::google::protobuf::RepeatedField< $type$ >*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" - " return &$name$_;\n" - "}\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Clear();\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - // Not needed for repeated fields. -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.CopyFrom(from.$name$_);\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "DO_((::google::protobuf::internal::WireFormatLite::$repeated_reader$<\n" - " $type$, $wire_format_field_type$>(\n" - " $tag_size$, $tag$u, input, this->mutable_$name$())));\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const { - printer->Print(variables_, - "DO_((::google::protobuf::internal::WireFormatLite::$packed_reader$<\n" - " $type$, $wire_format_field_type$>(\n" - " input, this->mutable_$name$())));\n"); -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - bool array_written = false; - if (descriptor_->is_packed()) { - // Write the tag and the size. - printer->Print(variables_, - "if (this->$name$_size() > 0) {\n" - " ::google::protobuf::internal::WireFormatLite::WriteTag(" - "$number$, " - "::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, " - "output);\n" - " output->WriteVarint32(static_cast< ::google::protobuf::uint32>(\n" - " _$name$_cached_byte_size_));\n"); - - if (FixedSize(descriptor_->type()) > 0) { - // TODO(ckennelly): Use RepeatedField::unsafe_data() via - // WireFormatLite to access the contents of this->$name$_ to save a branch - // here. - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$Array(\n" - " this->$name$().data(), this->$name$_size(), output);\n"); - array_written = true; // Wrote array all at once - } - printer->Print(variables_, "}\n"); - } - if (!array_written) { - printer->Print(variables_, - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); - if (descriptor_->is_packed()) { - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$NoTag(\n" - " this->$name$(i), output);\n"); - } else { - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n" - " $number$, this->$name$(i), output);\n"); - } - printer->Print("}\n"); - } -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - if (descriptor_->is_packed()) { - // Write the tag and the size. - printer->Print(variables_, - "if (this->$name$_size() > 0) {\n" - " target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(\n" - " $number$,\n" - " ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n" - " target);\n" - " target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(\n" - " static_cast< ::google::protobuf::int32>(\n" - " _$name$_cached_byte_size_), target);\n" - " target = ::google::protobuf::internal::WireFormatLite::\n" - " Write$declared_type$NoTagToArray(this->$name$_, target);\n" - "}\n"); - } else { - printer->Print(variables_, - "target = ::google::protobuf::internal::WireFormatLite::\n" - " Write$declared_type$ToArray($number$, this->$name$_, target);\n"); - } -} - -void RepeatedPrimitiveFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, "{\n"); - printer->Indent(); - int fixed_size = FixedSize(descriptor_->type()); - if (fixed_size == -1) { - printer->Print(variables_, - "size_t data_size = ::google::protobuf::internal::WireFormatLite::\n" - " $declared_type$Size(this->$name$_);\n"); - } else { - printer->Print(variables_, - "unsigned int count = static_cast(this->$name$_size());\n" - "size_t data_size = $fixed_size$UL * count;\n"); - } - - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (data_size > 0) {\n" - " total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::Int32Size(\n" - " static_cast< ::google::protobuf::int32>(data_size));\n" - "}\n" - "int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n" - "_$name$_cached_byte_size_ = cached_size;\n" - "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n" - "total_size += data_size;\n"); - } else { - printer->Print(variables_, - "total_size += $tag_size$ *\n" - " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n" - "total_size += data_size;\n"); - } - printer->Outdent(); - printer->Print("}\n"); -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_primitive_field.h b/windows/include/google/protobuf/compiler/cpp/cpp_primitive_field.h deleted file mode 100644 index d52228e96..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_primitive_field.h +++ /dev/null @@ -1,125 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -class PrimitiveFieldGenerator : public FieldGenerator { - public: - PrimitiveFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~PrimitiveFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateCopyConstructorCode(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); -}; - -class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator { - public: - PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~PrimitiveOneofFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveOneofFieldGenerator); -}; - -class RepeatedPrimitiveFieldGenerator : public FieldGenerator { - public: - RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~RepeatedPrimitiveFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateCopyConstructorCode(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_PRIMITIVE_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_service.cc b/windows/include/google/protobuf/compiler/cpp/cpp_service.cc deleted file mode 100644 index 95357d9f4..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_service.cc +++ /dev/null @@ -1,340 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor, - const Options& options) - : descriptor_(descriptor) { - vars_["classname"] = descriptor_->name(); - vars_["file_namespace"] = FileLevelNamespace(descriptor_->file()->name()); - vars_["full_name"] = descriptor_->full_name(); - if (options.dllexport_decl.empty()) { - vars_["dllexport"] = ""; - } else { - vars_["dllexport"] = options.dllexport_decl + " "; - } -} - -ServiceGenerator::~ServiceGenerator() {} - -void ServiceGenerator::GenerateDeclarations(io::Printer* printer) { - // Forward-declare the stub type. - printer->Print(vars_, - "class $classname$_Stub;\n" - "\n"); - - GenerateInterface(printer); - GenerateStubDefinition(printer); -} - -void ServiceGenerator::GenerateInterface(io::Printer* printer) { - printer->Print(vars_, - "class $dllexport$$classname$ : public ::google::protobuf::Service {\n" - " protected:\n" - " // This class should be treated as an abstract interface.\n" - " inline $classname$() {};\n" - " public:\n" - " virtual ~$classname$();\n"); - printer->Indent(); - - printer->Print(vars_, - "\n" - "typedef $classname$_Stub Stub;\n" - "\n" - "static const ::google::protobuf::ServiceDescriptor* descriptor();\n" - "\n"); - - GenerateMethodSignatures(VIRTUAL, printer); - - printer->Print( - "\n" - "// implements Service ----------------------------------------------\n" - "\n" - "const ::google::protobuf::ServiceDescriptor* GetDescriptor();\n" - "void CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" - " ::google::protobuf::RpcController* controller,\n" - " const ::google::protobuf::Message* request,\n" - " ::google::protobuf::Message* response,\n" - " ::google::protobuf::Closure* done);\n" - "const ::google::protobuf::Message& GetRequestPrototype(\n" - " const ::google::protobuf::MethodDescriptor* method) const;\n" - "const ::google::protobuf::Message& GetResponsePrototype(\n" - " const ::google::protobuf::MethodDescriptor* method) const;\n"); - - printer->Outdent(); - printer->Print(vars_, - "\n" - " private:\n" - " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n" - "};\n" - "\n"); -} - -void ServiceGenerator::GenerateStubDefinition(io::Printer* printer) { - printer->Print(vars_, - "class $dllexport$$classname$_Stub : public $classname$ {\n" - " public:\n"); - - printer->Indent(); - - printer->Print(vars_, - "$classname$_Stub(::google::protobuf::RpcChannel* channel);\n" - "$classname$_Stub(::google::protobuf::RpcChannel* channel,\n" - " ::google::protobuf::Service::ChannelOwnership ownership);\n" - "~$classname$_Stub();\n" - "\n" - "inline ::google::protobuf::RpcChannel* channel() { return channel_; }\n" - "\n" - "// implements $classname$ ------------------------------------------\n" - "\n"); - - GenerateMethodSignatures(NON_VIRTUAL, printer); - - printer->Outdent(); - printer->Print(vars_, - " private:\n" - " ::google::protobuf::RpcChannel* channel_;\n" - " bool owns_channel_;\n" - " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n" - "};\n" - "\n"); -} - -void ServiceGenerator::GenerateMethodSignatures( - VirtualOrNon virtual_or_non, io::Printer* printer) { - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - std::map sub_vars; - sub_vars["name"] = method->name(); - sub_vars["input_type"] = ClassName(method->input_type(), true); - sub_vars["output_type"] = ClassName(method->output_type(), true); - sub_vars["virtual"] = virtual_or_non == VIRTUAL ? "virtual " : ""; - - printer->Print(sub_vars, - "$virtual$void $name$(::google::protobuf::RpcController* controller,\n" - " const $input_type$* request,\n" - " $output_type$* response,\n" - " ::google::protobuf::Closure* done);\n"); - } -} - -// =================================================================== - -void ServiceGenerator::GenerateDescriptorInitializer( - io::Printer* printer, int index) { - std::map vars; - vars["classname"] = descriptor_->name(); - vars["index"] = SimpleItoa(index); - - printer->Print(vars, - "$classname$_descriptor_ = file->service($index$);\n"); -} - -// =================================================================== - -void ServiceGenerator::GenerateImplementation(io::Printer* printer) { - vars_["index"] = SimpleItoa(index_in_metadata_); - printer->Print( - vars_, - "$classname$::~$classname$() {}\n" - "\n" - "const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\n" - " $file_namespace$::protobuf_AssignDescriptorsOnce();\n" - " return $file_namespace$::file_level_service_descriptors[$index$];\n" - "}\n" - "\n" - "const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\n" - " return descriptor();\n" - "}\n" - "\n"); - - // Generate methods of the interface. - GenerateNotImplementedMethods(printer); - GenerateCallMethod(printer); - GenerateGetPrototype(REQUEST, printer); - GenerateGetPrototype(RESPONSE, printer); - - // Generate stub implementation. - printer->Print(vars_, - "$classname$_Stub::$classname$_Stub(::google::protobuf::RpcChannel* channel)\n" - " : channel_(channel), owns_channel_(false) {}\n" - "$classname$_Stub::$classname$_Stub(\n" - " ::google::protobuf::RpcChannel* channel,\n" - " ::google::protobuf::Service::ChannelOwnership ownership)\n" - " : channel_(channel),\n" - " owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\n" - "$classname$_Stub::~$classname$_Stub() {\n" - " if (owns_channel_) delete channel_;\n" - "}\n" - "\n"); - - GenerateStubMethods(printer); -} - -void ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) { - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - std::map sub_vars; - sub_vars["classname"] = descriptor_->name(); - sub_vars["name"] = method->name(); - sub_vars["index"] = SimpleItoa(i); - sub_vars["input_type"] = ClassName(method->input_type(), true); - sub_vars["output_type"] = ClassName(method->output_type(), true); - - printer->Print(sub_vars, - "void $classname$::$name$(::google::protobuf::RpcController* controller,\n" - " const $input_type$*,\n" - " $output_type$*,\n" - " ::google::protobuf::Closure* done) {\n" - " controller->SetFailed(\"Method $name$() not implemented.\");\n" - " done->Run();\n" - "}\n" - "\n"); - } -} - -void ServiceGenerator::GenerateCallMethod(io::Printer* printer) { - printer->Print( - vars_, - "void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" - " ::google::protobuf::RpcController* controller,\n" - " const ::google::protobuf::Message* request,\n" - " ::google::protobuf::Message* response,\n" - " ::google::protobuf::Closure* done) {\n" - " GOOGLE_DCHECK_EQ(method->service(), " - "$file_namespace$::file_level_service_descriptors[$index$]);\n" - " switch(method->index()) {\n"); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - std::map sub_vars; - sub_vars["name"] = method->name(); - sub_vars["index"] = SimpleItoa(i); - sub_vars["input_type"] = ClassName(method->input_type(), true); - sub_vars["output_type"] = ClassName(method->output_type(), true); - - // Note: down_cast does not work here because it only works on pointers, - // not references. - printer->Print(sub_vars, - " case $index$:\n" - " $name$(controller,\n" - " ::google::protobuf::down_cast(request),\n" - " ::google::protobuf::down_cast< $output_type$*>(response),\n" - " done);\n" - " break;\n"); - } - - printer->Print(vars_, - " default:\n" - " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" - " break;\n" - " }\n" - "}\n" - "\n"); -} - -void ServiceGenerator::GenerateGetPrototype(RequestOrResponse which, - io::Printer* printer) { - if (which == REQUEST) { - printer->Print(vars_, - "const ::google::protobuf::Message& $classname$::GetRequestPrototype(\n"); - } else { - printer->Print(vars_, - "const ::google::protobuf::Message& $classname$::GetResponsePrototype(\n"); - } - - printer->Print(vars_, - " const ::google::protobuf::MethodDescriptor* method) const {\n" - " GOOGLE_DCHECK_EQ(method->service(), descriptor());\n" - " switch(method->index()) {\n"); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - const Descriptor* type = - (which == REQUEST) ? method->input_type() : method->output_type(); - - std::map sub_vars; - sub_vars["index"] = SimpleItoa(i); - sub_vars["type"] = ClassName(type, true); - - printer->Print(sub_vars, - " case $index$:\n" - " return $type$::default_instance();\n"); - } - - printer->Print( - " default:\n" - " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" - " return *::google::protobuf::MessageFactory::generated_factory()\n" - " ->GetPrototype(method->$input_or_output$_type());\n" - " }\n" - "}\n" - "\n", - "input_or_output", which == REQUEST ? "input" : "output"); -} - -void ServiceGenerator::GenerateStubMethods(io::Printer* printer) { - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - std::map sub_vars; - sub_vars["classname"] = descriptor_->name(); - sub_vars["name"] = method->name(); - sub_vars["index"] = SimpleItoa(i); - sub_vars["input_type"] = ClassName(method->input_type(), true); - sub_vars["output_type"] = ClassName(method->output_type(), true); - - printer->Print(sub_vars, - "void $classname$_Stub::$name$(::google::protobuf::RpcController* controller,\n" - " const $input_type$* request,\n" - " $output_type$* response,\n" - " ::google::protobuf::Closure* done) {\n" - " channel_->CallMethod(descriptor()->method($index$),\n" - " controller, request, response, done);\n" - "}\n"); - } -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_service.h b/windows/include/google/protobuf/compiler/cpp/cpp_service.h deleted file mode 100644 index 33c025476..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_service.h +++ /dev/null @@ -1,121 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__ - -#include -#include -#include -#include - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace cpp { - -class ServiceGenerator { - public: - // See generator.cc for the meaning of dllexport_decl. - explicit ServiceGenerator(const ServiceDescriptor* descriptor, - const Options& options); - ~ServiceGenerator(); - - // Header stuff. - - // Generate the class definitions for the service's interface and the - // stub implementation. - void GenerateDeclarations(io::Printer* printer); - - // Source file stuff. - - // Generate code that initializes the global variable storing the service's - // descriptor. - void GenerateDescriptorInitializer(io::Printer* printer, int index); - - // Generate implementations of everything declared by GenerateDeclarations(). - void GenerateImplementation(io::Printer* printer); - - private: - enum RequestOrResponse { REQUEST, RESPONSE }; - enum VirtualOrNon { VIRTUAL, NON_VIRTUAL }; - - // Header stuff. - - // Generate the service abstract interface. - void GenerateInterface(io::Printer* printer); - - // Generate the stub class definition. - void GenerateStubDefinition(io::Printer* printer); - - // Prints signatures for all methods in the - void GenerateMethodSignatures(VirtualOrNon virtual_or_non, - io::Printer* printer); - - // Source file stuff. - - // Generate the default implementations of the service methods, which - // produce a "not implemented" error. - void GenerateNotImplementedMethods(io::Printer* printer); - - // Generate the CallMethod() method of the service. - void GenerateCallMethod(io::Printer* printer); - - // Generate the Get{Request,Response}Prototype() methods. - void GenerateGetPrototype(RequestOrResponse which, io::Printer* printer); - - // Generate the stub's implementations of the service methods. - void GenerateStubMethods(io::Printer* printer); - - const ServiceDescriptor* descriptor_; - std::map vars_; - - int index_in_metadata_; - - friend class FileGenerator; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_SERVICE_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_string_field.cc b/windows/include/google/protobuf/compiler/cpp/cpp_string_field.cc deleted file mode 100644 index cf6c4b33a..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_string_field.cc +++ /dev/null @@ -1,1186 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -namespace { - -void SetStringVariables(const FieldDescriptor* descriptor, - std::map* variables, - const Options& options) { - SetCommonFieldVariables(descriptor, variables, options); - (*variables)["default"] = DefaultValue(descriptor); - (*variables)["default_length"] = - SimpleItoa(descriptor->default_value_string().length()); - string default_variable_string = MakeDefaultName(descriptor); - (*variables)["default_variable_name"] = default_variable_string; - (*variables)["default_variable"] = - descriptor->default_value_string().empty() - ? "&::google::protobuf::internal::GetEmptyStringAlreadyInited()" - : "&" + Namespace(descriptor) + "::" + (*variables)["classname"] + - "::" + default_variable_string + ".get()"; - (*variables)["pointer_type"] = - descriptor->type() == FieldDescriptor::TYPE_BYTES ? "void" : "char"; - (*variables)["null_check"] = "GOOGLE_DCHECK(value != NULL);\n"; - // NOTE: Escaped here to unblock proto1->proto2 migration. - // TODO(liujisi): Extend this to apply for other conflicting methods. - (*variables)["release_name"] = - SafeFunctionName(descriptor->containing_type(), - descriptor, "release_"); - (*variables)["full_name"] = descriptor->full_name(); - - (*variables)["string_piece"] = "::std::string"; - - (*variables)["lite"] = - HasDescriptorMethods(descriptor->file(), options) ? "" : "Lite"; -} - -} // namespace - -// =================================================================== - -StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : FieldGenerator(options), - descriptor_(descriptor), - lite_(!HasDescriptorMethods(descriptor->file(), options)), - inlined_(false) { - - // TODO(ckennelly): Handle inlining for any.proto. - if (IsAnyMessage(descriptor_->containing_type())) { - inlined_ = false; - } - if (descriptor_->containing_type()->options().map_entry()) { - inlined_ = false; - } - - // Limit to proto2, as we rely on has bits to distinguish field presence for - // release_$name$. On proto3, we cannot use the address of the string - // instance when the field has been inlined. - inlined_ = inlined_ && HasFieldPresence(descriptor_->file()); - - SetStringVariables(descriptor, &variables_, options); -} - -StringFieldGenerator::~StringFieldGenerator() {} - -void StringFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - if (inlined_) { - printer->Print(variables_, - "::google::protobuf::internal::InlinedStringField $name$_;\n"); - } else { - // N.B. that we continue to use |ArenaStringPtr| instead of |string*| for - // string fields, even when SupportArenas(descriptor_) == false. Why? The - // simple answer is to avoid unmaintainable complexity. The reflection code - // assumes ArenaStringPtrs. These are *almost* in-memory-compatible with - // string*, except for the pointer tags and related ownership semantics. We - // could modify the runtime code to use string* for the - // not-supporting-arenas case, but this would require a way to detect which - // type of class was generated (adding overhead and complexity to - // GeneratedMessageReflection) and littering the runtime code paths with - // conditionals. It's simpler to stick with this but use lightweight - // accessors that assume arena == NULL. There should be very little - // overhead anyway because it's just a tagged pointer in-memory. - printer->Print(variables_, "::google::protobuf::internal::ArenaStringPtr $name$_;\n"); - } -} - -void StringFieldGenerator:: -GenerateStaticMembers(io::Printer* printer) const { - if (!descriptor_->default_value_string().empty()) { - // We make the default instance public, so it can be initialized by - // non-friend code. - printer->Print(variables_, - "public:\n" - "static ::google::protobuf::internal::ExplicitlyConstructed< ::std::string>" - " $default_variable_name$;\n" - "private:\n"); - } -} - -void StringFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - // If we're using StringFieldGenerator for a field with a ctype, it's - // because that ctype isn't actually implemented. In particular, this is - // true of ctype=CORD and ctype=STRING_PIECE in the open source release. - // We aren't releasing Cord because it has too many Google-specific - // dependencies and we aren't releasing StringPiece because it's hardly - // useful outside of Google and because it would get confusing to have - // multiple instances of the StringPiece class in different libraries (PCRE - // already includes it for their C++ bindings, which came from Google). - // - // In any case, we make all the accessors private while still actually - // using a string to represent the field internally. This way, we can - // guarantee that if we do ever implement the ctype, it won't break any - // existing users who might be -- for whatever reason -- already using .proto - // files that applied the ctype. The field can still be accessed via the - // reflection interface since the reflection interface is independent of - // the string's underlying representation. - - bool unknown_ctype = - descriptor_->options().ctype() != EffectiveStringCType(descriptor_); - - if (unknown_ctype) { - printer->Outdent(); - printer->Print( - " private:\n" - " // Hidden due to unknown ctype option.\n"); - printer->Indent(); - } - - printer->Print(variables_, - "$deprecated_attr$const ::std::string& $name$() const;\n"); - printer->Annotate("name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$set_$name$$}$(const ::std::string& value);\n"); - printer->Annotate("{", "}", descriptor_); - - printer->Print(variables_, - "#if LANG_CXX11\n" - "$deprecated_attr$void ${$set_$name$$}$(::std::string&& value);\n" - "#endif\n"); - printer->Annotate("{", "}", descriptor_); - - printer->Print( - variables_, - "$deprecated_attr$void ${$set_$name$$}$(const char* value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$(const $pointer_type$* " - "value, size_t size)" - ";\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::std::string* ${$mutable_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, "$deprecated_attr$::std::string* $release_name$();\n"); - printer->Annotate("release_name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$set_allocated_$name$$}$(::std::string* $name$);\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportsArenas(descriptor_)) { - printer->Print( - variables_, - "PROTOBUF_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors for\"\n" - "\" string fields are deprecated and will be removed in a\"\n" - "\" future release.\")\n" - "::std::string* ${$unsafe_arena_release_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "PROTOBUF_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors for\"\n" - "\" string fields are deprecated and will be removed in a\"\n" - "\" future release.\")\n" - "void ${$unsafe_arena_set_allocated_$name$$}$(\n" - " ::std::string* $name$);\n"); - printer->Annotate("{", "}", descriptor_); - } - - if (unknown_ctype) { - printer->Outdent(); - printer->Print(" public:\n"); - printer->Indent(); - } -} - -void StringFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - if (SupportsArenas(descriptor_)) { - printer->Print( - variables_, - "inline const ::std::string& $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.Get();\n" - "}\n" - "inline void $classname$::set_$name$(const ::std::string& value) {\n" - " $set_hasbit$\n" - " $name$_.Set$lite$($default_variable$, value, GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(::std::string&& value) {\n" - " $set_hasbit$\n" - " $name$_.Set$lite$(\n" - " $default_variable$, ::std::move(value), GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n" - "}\n" - "#endif\n" - "inline void $classname$::set_$name$(const char* value) {\n" - " $null_check$" - " $set_hasbit$\n" - " $name$_.Set$lite$($default_variable$, $string_piece$(value),\n" - " GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" - "inline " - "void $classname$::set_$name$(const $pointer_type$* value,\n" - " size_t size) {\n" - " $set_hasbit$\n" - " $name$_.Set$lite$($default_variable$, $string_piece$(\n" - " reinterpret_cast(value), size), " - "GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::mutable_$name$() {\n" - " $set_hasbit$\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n" - "}\n" - "inline ::std::string* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n"); - - if (HasFieldPresence(descriptor_->file())) { - printer->Print(variables_, - " if (!has_$name$()) {\n" - " return NULL;\n" - " }\n" - " $clear_hasbit$\n" - " return $name$_.ReleaseNonDefault(" - "$default_variable$, GetArenaNoVirtual());\n"); - } else { - printer->Print(variables_, - " $clear_hasbit$\n" - " return $name$_.Release($default_variable$, GetArenaNoVirtual());\n"); - } - - printer->Print(variables_, - "}\n" - "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" - " if ($name$ != NULL) {\n" - " $set_hasbit$\n" - " } else {\n" - " $clear_hasbit$\n" - " }\n" - " $name$_.SetAllocated($default_variable$, $name$,\n" - " GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::unsafe_arena_release_$name$() {\n" - " // " - "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n" - " $clear_hasbit$\n" - " return $name$_.UnsafeArenaRelease($default_variable$,\n" - " GetArenaNoVirtual());\n" - "}\n" - "inline void $classname$::unsafe_arena_set_allocated_$name$(\n" - " ::std::string* $name$) {\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n" - " if ($name$ != NULL) {\n" - " $set_hasbit$\n" - " } else {\n" - " $clear_hasbit$\n" - " }\n" - " $name$_.UnsafeArenaSetAllocated($default_variable$,\n" - " $name$, GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" - "$full_name$)\n" - "}\n"); - } else { - // No-arena case. - printer->Print( - variables_, - "inline const ::std::string& $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.GetNoArena();\n" - "}\n" - "inline void $classname$::set_$name$(const ::std::string& value) {\n" - " $set_hasbit$\n" - " $name$_.SetNoArena($default_variable$, value);\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(::std::string&& value) {\n" - " $set_hasbit$\n" - " $name$_.SetNoArena(\n" - " $default_variable$, ::std::move(value));\n" - " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n" - "}\n" - "#endif\n" - "inline void $classname$::set_$name$(const char* value) {\n" - " $null_check$" - " $set_hasbit$\n" - " $name$_.SetNoArena($default_variable$, $string_piece$(value));\n" - " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" - "inline " - "void $classname$::set_$name$(const $pointer_type$* value, " - "size_t size) {\n" - " $set_hasbit$\n" - " $name$_.SetNoArena($default_variable$,\n" - " $string_piece$(reinterpret_cast(value), size));\n" - " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::mutable_$name$() {\n" - " $set_hasbit$\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $name$_.MutableNoArena($default_variable$);\n" - "}\n" - "inline ::std::string* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n"); - - if (HasFieldPresence(descriptor_->file())) { - printer->Print(variables_, - " if (!has_$name$()) {\n" - " return NULL;\n" - " }\n" - " $clear_hasbit$\n" - " return $name$_.ReleaseNonDefaultNoArena($default_variable$);\n"); - } else { - printer->Print(variables_, - " $clear_hasbit$\n" - " return $name$_.ReleaseNoArena($default_variable$);\n"); - } - - printer->Print(variables_, - "}\n" - "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" - " if ($name$ != NULL) {\n" - " $set_hasbit$\n" - " } else {\n" - " $clear_hasbit$\n" - " }\n" - " $name$_.SetAllocatedNoArena($default_variable$, $name$);\n" - " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n"); - } -} - -void StringFieldGenerator:: -GenerateNonInlineAccessorDefinitions(io::Printer* printer) const { - if (!descriptor_->default_value_string().empty()) { - // Initialized in GenerateDefaultInstanceAllocator. - printer->Print(variables_, - "::google::protobuf::internal::ExplicitlyConstructed<::std::string> " - "$classname$::$default_variable_name$;\n"); - } -} - -void StringFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - // Two-dimension specialization here: supporting arenas or not, and default - // value is the empty string or not. Complexity here ensures the minimal - // number of branches / amount of extraneous code at runtime (given that the - // below methods are inlined one-liners)! - if (SupportsArenas(descriptor_)) { - if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, - "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); - } else { - printer->Print(variables_, - "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n"); - } - } else { - if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, - "$name$_.ClearToEmptyNoArena($default_variable$);\n"); - } else { - printer->Print(variables_, - "$name$_.ClearToDefaultNoArena($default_variable$);\n"); - } - } -} - -void StringFieldGenerator:: -GenerateMessageClearingCode(io::Printer* printer) const { - // Two-dimension specialization here: supporting arenas, field presence, or - // not, and default value is the empty string or not. Complexity here ensures - // the minimal number of branches / amount of extraneous code at runtime - // (given that the below methods are inlined one-liners)! - - // If we have field presence, then the Clear() method of the protocol buffer - // will have checked that this field is set. If so, we can avoid redundant - // checks against default_variable. - const bool must_be_present = - HasFieldPresence(descriptor_->file()); - - if (inlined_ && must_be_present) { - // Calling mutable_$name$() gives us a string reference and sets the has bit - // for $name$ (in proto2). We may get here when the string field is inlined - // but the string's contents have not been changed by the user, so we cannot - // make an assertion about the contents of the string and could never make - // an assertion about the string instance. - // - // For non-inlined strings, we distinguish from non-default by comparing - // instances, rather than contents. - printer->Print(variables_, - "GOOGLE_DCHECK(!$name$_.IsDefault($default_variable$));\n"); - } - - if (SupportsArenas(descriptor_)) { - if (descriptor_->default_value_string().empty()) { - if (must_be_present) { - printer->Print(variables_, - "$name$_.ClearNonDefaultToEmpty();\n"); - } else { - printer->Print(variables_, - "$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n"); - } - } else { - // Clear to a non-empty default is more involved, as we try to use the - // Arena if one is present and may need to reallocate the string. - printer->Print(variables_, - "$name$_.ClearToDefault($default_variable$, GetArenaNoVirtual());\n"); - } - } else if (must_be_present) { - // When Arenas are disabled and field presence has been checked, we can - // safely treat the ArenaStringPtr as a string*. - if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, "$name$_.ClearNonDefaultToEmptyNoArena();\n"); - } else { - printer->Print( - variables_, - "$name$_.UnsafeMutablePointer()->assign(*$default_variable$);\n"); - } - } else { - if (descriptor_->default_value_string().empty()) { - printer->Print(variables_, - "$name$_.ClearToEmptyNoArena($default_variable$);\n"); - } else { - printer->Print(variables_, - "$name$_.ClearToDefaultNoArena($default_variable$);\n"); - } - } -} - -void StringFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) { - // TODO(gpike): improve this - printer->Print(variables_, "set_$name$(from.$name$());\n"); - } else { - printer->Print(variables_, - "$set_hasbit$\n" - "$name$_.AssignWithDefault($default_variable$, from.$name$_);\n"); - } -} - -void StringFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - if (inlined_) { - printer->Print( - variables_, - "$name$_.Swap(&other->$name$_);\n"); - } else { - printer->Print( - variables_, - "$name$_.Swap(&other->$name$_, $default_variable$,\n" - " GetArenaNoVirtual());\n"); - } -} - -void StringFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - // TODO(ckennelly): Construct non-empty strings as part of the initializer - // list. - if (inlined_ && descriptor_->default_value_string().empty()) { - // Automatic initialization will construct the string. - return; - } - - printer->Print(variables_, - "$name$_.UnsafeSetDefault($default_variable$);\n"); -} - -void StringFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - GenerateConstructorCode(printer); - - if (HasFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if (from.has_$name$()) {\n"); - } else { - printer->Print(variables_, - "if (from.$name$().size() > 0) {\n"); - } - - printer->Indent(); - - if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) { - // TODO(gpike): improve this - printer->Print(variables_, - "$name$_.Set$lite$($default_variable$, from.$name$(),\n" - " GetArenaNoVirtual());\n"); - } else { - printer->Print(variables_, - "$name$_.AssignWithDefault($default_variable$, from.$name$_);\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void StringFieldGenerator:: -GenerateDestructorCode(io::Printer* printer) const { - if (inlined_) { - // The destructor is automatically invoked. - return; - } - - printer->Print(variables_, "$name$_.DestroyNoArena($default_variable$);\n"); -} - -bool StringFieldGenerator::GenerateArenaDestructorCode( - io::Printer* printer) const { - if (!inlined_) { - return false; - } - - printer->Print(variables_, - "_this->$name$_.DestroyNoArena($default_variable$);\n"); - return true; -} - -void StringFieldGenerator:: -GenerateDefaultInstanceAllocator(io::Printer* printer) const { - if (!descriptor_->default_value_string().empty()) { - printer->Print( - variables_, - "$ns$::$classname$::$default_variable_name$.DefaultConstruct();\n" - "*$ns$::$classname$::$default_variable_name$.get_mutable() = " - "::std::string($default$, $default_length$);\n" - "::google::protobuf::internal::OnShutdownDestroyString(\n" - " $ns$::$classname$::$default_variable_name$.get_mutable());\n" - ); - } -} - -void StringFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n" - " input, this->mutable_$name$()));\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - descriptor_, options_, true, variables_, - "this->$name$().data(), static_cast(this->$name$().length()),\n", - printer); - } -} - -bool StringFieldGenerator:: -MergeFromCodedStreamNeedsArena() const { - return false; -} - -void StringFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - descriptor_, options_, false, variables_, - "this->$name$().data(), static_cast(this->$name$().length()),\n", - printer); - } - printer->Print(variables_, - "::google::protobuf::internal::WireFormatLite::Write$declared_type$MaybeAliased(\n" - " $number$, this->$name$(), output);\n"); -} - -void StringFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - descriptor_, options_, false, variables_, - "this->$name$().data(), static_cast(this->$name$().length()),\n", - printer); - } - printer->Print(variables_, - "target =\n" - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$ToArray(\n" - " $number$, this->$name$(), target);\n"); -} - -void StringFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ +\n" - " ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" - " this->$name$());\n"); -} - -uint32 StringFieldGenerator::CalculateFieldTag() const { - return inlined_ ? 1 : 0; -} - -// =================================================================== - -StringOneofFieldGenerator::StringOneofFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : StringFieldGenerator(descriptor, options) { - inlined_ = false; - - SetCommonOneofFieldVariables(descriptor, &variables_); -} - -StringOneofFieldGenerator::~StringOneofFieldGenerator() {} - -void StringOneofFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - if (SupportsArenas(descriptor_)) { - printer->Print( - variables_, - "inline const ::std::string& $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " if (has_$name$()) {\n" - " return $field_member$.Get();\n" - " }\n" - " return *$default_variable$;\n" - "}\n" - "inline void $classname$::set_$name$(const ::std::string& value) {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " $field_member$.Set$lite$($default_variable$, value,\n" - " GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(::std::string&& value) {\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " $field_member$.Set$lite$(\n" - " $default_variable$, ::std::move(value), GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n" - "}\n" - "#endif\n" - "inline void $classname$::set_$name$(const char* value) {\n" - " $null_check$" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " $field_member$.Set$lite$($default_variable$,\n" - " $string_piece$(value), GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" - "inline " - "void $classname$::set_$name$(const $pointer_type$* value,\n" - " size_t size) {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " $field_member$.Set$lite$(\n" - " $default_variable$, $string_piece$(\n" - " reinterpret_cast(value), size),\n" - " GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::mutable_$name$() {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " return $field_member$.Mutable($default_variable$,\n" - " GetArenaNoVirtual());\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" - " if (has_$name$()) {\n" - " clear_has_$oneof_name$();\n" - " return $field_member$.Release($default_variable$,\n" - " GetArenaNoVirtual());\n" - " } else {\n" - " return NULL;\n" - " }\n" - "}\n" - "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" - " if (!has_$name$()) {\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " clear_$oneof_name$();\n" - " if ($name$ != NULL) {\n" - " set_has_$name$();\n" - " $field_member$.SetAllocated($default_variable$, $name$,\n" - " GetArenaNoVirtual());\n" - " }\n" - " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::unsafe_arena_release_$name$() {\n" - " // " - "@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n" - " if (has_$name$()) {\n" - " clear_has_$oneof_name$();\n" - " return $field_member$.UnsafeArenaRelease(\n" - " $default_variable$, GetArenaNoVirtual());\n" - " } else {\n" - " return NULL;\n" - " }\n" - "}\n" - "inline void $classname$::unsafe_arena_set_allocated_$name$(" - "::std::string* $name$) {\n" - " GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n" - " if (!has_$name$()) {\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " clear_$oneof_name$();\n" - " if ($name$) {\n" - " set_has_$name$();\n" - " $field_member$.UnsafeArenaSetAllocated($default_variable$, " - "$name$, GetArenaNoVirtual());\n" - " }\n" - " // @@protoc_insertion_point(field_unsafe_arena_set_allocated:" - "$full_name$)\n" - "}\n"); - } else { - // No-arena case. - printer->Print( - variables_, - "inline const ::std::string& $classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " if (has_$name$()) {\n" - " return $field_member$.GetNoArena();\n" - " }\n" - " return *$default_variable$;\n" - "}\n" - "inline void $classname$::set_$name$(const ::std::string& value) {\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " $field_member$.SetNoArena($default_variable$, value);\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(::std::string&& value) {\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " $field_member$.SetNoArena($default_variable$, ::std::move(value));\n" - " // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n" - "}\n" - "#endif\n" - "inline void $classname$::set_$name$(const char* value) {\n" - " $null_check$" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " $field_member$.SetNoArena($default_variable$,\n" - " $string_piece$(value));\n" - " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" - "inline " - "void $classname$::set_$name$(const $pointer_type$* value, size_t " - "size) {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " $field_member$.SetNoArena($default_variable$, $string_piece$(\n" - " reinterpret_cast(value), size));\n" - " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::mutable_$name$() {\n" - " if (!has_$name$()) {\n" - " clear_$oneof_name$();\n" - " set_has_$name$();\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $field_member$.MutableNoArena($default_variable$);\n" - "}\n" - "inline ::std::string* $classname$::$release_name$() {\n" - " // @@protoc_insertion_point(field_release:$full_name$)\n" - " if (has_$name$()) {\n" - " clear_has_$oneof_name$();\n" - " return $field_member$.ReleaseNoArena($default_variable$);\n" - " } else {\n" - " return NULL;\n" - " }\n" - "}\n" - "inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n" - " if (!has_$name$()) {\n" - " $field_member$.UnsafeSetDefault($default_variable$);\n" - " }\n" - " clear_$oneof_name$();\n" - " if ($name$ != NULL) {\n" - " set_has_$name$();\n" - " $field_member$.SetAllocatedNoArena($default_variable$, $name$);\n" - " }\n" - " // @@protoc_insertion_point(field_set_allocated:$full_name$)\n" - "}\n"); - } -} - -void StringOneofFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - if (SupportsArenas(descriptor_)) { - printer->Print(variables_, - "$field_member$.Destroy($default_variable$,\n" - " GetArenaNoVirtual());\n"); - } else { - printer->Print(variables_, - "$field_member$.DestroyNoArena($default_variable$);\n"); - } -} - -void StringOneofFieldGenerator:: -GenerateMessageClearingCode(io::Printer* printer) const { - return GenerateClearingCode(printer); -} - -void StringOneofFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - // Don't print any swapping code. Swapping the union will swap this field. -} - -void StringOneofFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - printer->Print( - variables_, - "$ns$::_$classname$_default_instance_.$name$_.UnsafeSetDefault(\n" - " $default_variable$);\n"); -} - -void StringOneofFieldGenerator:: -GenerateDestructorCode(io::Printer* printer) const { - printer->Print(variables_, - "if (has_$name$()) {\n" - " $field_member$.DestroyNoArena($default_variable$);\n" - "}\n"); -} - -void StringOneofFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n" - " input, this->mutable_$name$()));\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - descriptor_, options_, true, variables_, - "this->$name$().data(), static_cast(this->$name$().length()),\n", - printer); - } -} - - -// =================================================================== - -RepeatedStringFieldGenerator::RepeatedStringFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : FieldGenerator(options), descriptor_(descriptor) { - SetStringVariables(descriptor, &variables_, options); -} - -RepeatedStringFieldGenerator::~RepeatedStringFieldGenerator() {} - -void RepeatedStringFieldGenerator:: -GeneratePrivateMembers(io::Printer* printer) const { - printer->Print(variables_, - "::google::protobuf::RepeatedPtrField< ::std::string> $name$_;\n"); -} - -void RepeatedStringFieldGenerator:: -GenerateAccessorDeclarations(io::Printer* printer) const { - // See comment above about unknown ctypes. - bool unknown_ctype = - descriptor_->options().ctype() != EffectiveStringCType(descriptor_); - - if (unknown_ctype) { - printer->Outdent(); - printer->Print( - " private:\n" - " // Hidden due to unknown ctype option.\n"); - printer->Indent(); - } - - printer->Print(variables_, - "$deprecated_attr$const ::std::string& $name$(int index) const;\n"); - printer->Annotate("name", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$::std::string* ${$mutable_$name$$}$(int index);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$(int index, const " - "::std::string& value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "#if LANG_CXX11\n" - "$deprecated_attr$void ${$set_$name$$}$(int index, ::std::string&& value);\n" - "#endif\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$set_$name$$}$(int index, const " - "char* value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "" - "$deprecated_attr$void ${$set_$name$$}$(" - "int index, const $pointer_type$* value, size_t size);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::std::string* ${$add_$name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$add_$name$$}$(const ::std::string& value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "#if LANG_CXX11\n" - "$deprecated_attr$void ${$add_$name$$}$(::std::string&& value);\n" - "#endif\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$void ${$add_$name$$}$(const char* value);\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print(variables_, - "$deprecated_attr$void ${$add_$name$$}$(const $pointer_type$* " - "value, size_t size)" - ";\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecated_attr$const ::google::protobuf::RepeatedPtrField< ::std::string>& $name$() " - "const;\n"); - printer->Annotate("name", descriptor_); - printer->Print(variables_, - "$deprecated_attr$::google::protobuf::RepeatedPtrField< ::std::string>* " - "${$mutable_$name$$}$()" - ";\n"); - printer->Annotate("{", "}", descriptor_); - - if (unknown_ctype) { - printer->Outdent(); - printer->Print(" public:\n"); - printer->Indent(); - } -} - -void RepeatedStringFieldGenerator:: -GenerateInlineAccessorDefinitions(io::Printer* printer) const { - if (options_.safe_boundary_check) { - printer->Print(variables_, - "inline const ::std::string& $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.InternalCheckedGet(\n" - " index, ::google::protobuf::internal::GetEmptyStringAlreadyInited());\n" - "}\n"); - } else { - printer->Print(variables_, - "inline const ::std::string& $classname$::$name$(int index) const {\n" - " // @@protoc_insertion_point(field_get:$full_name$)\n" - " return $name$_.Get(index);\n" - "}\n"); - } - printer->Print(variables_, - "inline ::std::string* $classname$::mutable_$name$(int index) {\n" - " // @@protoc_insertion_point(field_mutable:$full_name$)\n" - " return $name$_.Mutable(index);\n" - "}\n" - "inline void $classname$::set_$name$(int index, const ::std::string& value) {\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - " $name$_.Mutable(index)->assign(value);\n" - "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::set_$name$(int index, ::std::string&& value) {\n" - " // @@protoc_insertion_point(field_set:$full_name$)\n" - " $name$_.Mutable(index)->assign(std::move(value));\n" - "}\n" - "#endif\n" - "inline void $classname$::set_$name$(int index, const char* value) {\n" - " $null_check$" - " $name$_.Mutable(index)->assign(value);\n" - " // @@protoc_insertion_point(field_set_char:$full_name$)\n" - "}\n" - "inline void " - "$classname$::set_$name$" - "(int index, const $pointer_type$* value, size_t size) {\n" - " $name$_.Mutable(index)->assign(\n" - " reinterpret_cast(value), size);\n" - " // @@protoc_insertion_point(field_set_pointer:$full_name$)\n" - "}\n" - "inline ::std::string* $classname$::add_$name$() {\n" - " // @@protoc_insertion_point(field_add_mutable:$full_name$)\n" - " return $name$_.Add();\n" - "}\n" - "inline void $classname$::add_$name$(const ::std::string& value) {\n" - " $name$_.Add()->assign(value);\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "}\n" - "#if LANG_CXX11\n" - "inline void $classname$::add_$name$(::std::string&& value) {\n" - " $name$_.Add(std::move(value));\n" - " // @@protoc_insertion_point(field_add:$full_name$)\n" - "}\n" - "#endif\n" - "inline void $classname$::add_$name$(const char* value) {\n" - " $null_check$" - " $name$_.Add()->assign(value);\n" - " // @@protoc_insertion_point(field_add_char:$full_name$)\n" - "}\n" - "inline void " - "$classname$::add_$name$(const $pointer_type$* value, size_t size) {\n" - " $name$_.Add()->assign(reinterpret_cast(value), size);\n" - " // @@protoc_insertion_point(field_add_pointer:$full_name$)\n" - "}\n" - "inline const ::google::protobuf::RepeatedPtrField< ::std::string>&\n" - "$classname$::$name$() const {\n" - " // @@protoc_insertion_point(field_list:$full_name$)\n" - " return $name$_;\n" - "}\n" - "inline ::google::protobuf::RepeatedPtrField< ::std::string>*\n" - "$classname$::mutable_$name$() {\n" - " // @@protoc_insertion_point(field_mutable_list:$full_name$)\n" - " return &$name$_;\n" - "}\n"); -} - -void RepeatedStringFieldGenerator:: -GenerateClearingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.Clear();\n"); -} - -void RepeatedStringFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.MergeFrom(from.$name$_);\n"); -} - -void RepeatedStringFieldGenerator:: -GenerateSwappingCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.InternalSwap(CastToBase(&other->$name$_));\n"); -} - -void RepeatedStringFieldGenerator:: -GenerateConstructorCode(io::Printer* printer) const { - // Not needed for repeated fields. -} - -void RepeatedStringFieldGenerator:: -GenerateCopyConstructorCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.CopyFrom(from.$name$_);"); -} - -void RepeatedStringFieldGenerator:: -GenerateMergeFromCodedStream(io::Printer* printer) const { - printer->Print(variables_, - "DO_(::google::protobuf::internal::WireFormatLite::Read$declared_type$(\n" - " input, this->add_$name$()));\n"); - if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - descriptor_, options_, true, variables_, - "this->$name$(this->$name$_size() - 1).data(),\n" - "static_cast(this->$name$(this->$name$_size() - 1).length()),\n", - printer); - } -} - -void RepeatedStringFieldGenerator:: -GenerateSerializeWithCachedSizes(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); - printer->Indent(); - if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - descriptor_, options_, false, variables_, - "this->$name$(i).data(), static_cast(this->$name$(i).length()),\n", - printer); - } - printer->Outdent(); - printer->Print(variables_, - " ::google::protobuf::internal::WireFormatLite::Write$declared_type$(\n" - " $number$, this->$name$(i), output);\n" - "}\n"); -} - -void RepeatedStringFieldGenerator:: -GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n"); - printer->Indent(); - if (descriptor_->type() == FieldDescriptor::TYPE_STRING) { - GenerateUtf8CheckCodeForString( - descriptor_, options_, false, variables_, - "this->$name$(i).data(), static_cast(this->$name$(i).length()),\n", - printer); - } - printer->Outdent(); - printer->Print(variables_, - " target = ::google::protobuf::internal::WireFormatLite::\n" - " Write$declared_type$ToArray($number$, this->$name$(i), target);\n" - "}\n"); -} - -void RepeatedStringFieldGenerator:: -GenerateByteSize(io::Printer* printer) const { - printer->Print(variables_, - "total_size += $tag_size$ *\n" - " ::google::protobuf::internal::FromIntSize(this->$name$_size());\n" - "for (int i = 0, n = this->$name$_size(); i < n; i++) {\n" - " total_size += ::google::protobuf::internal::WireFormatLite::$declared_type$Size(\n" - " this->$name$(i));\n" - "}\n"); -} - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_string_field.h b/windows/include/google/protobuf/compiler/cpp/cpp_string_field.h deleted file mode 100644 index 6cbf722fc..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_string_field.h +++ /dev/null @@ -1,141 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -class StringFieldGenerator : public FieldGenerator { - public: - StringFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~StringFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateStaticMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMessageClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateCopyConstructorCode(io::Printer* printer) const; - void GenerateDestructorCode(io::Printer* printer) const; - bool GenerateArenaDestructorCode(io::Printer* printer) const; - void GenerateDefaultInstanceAllocator(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - uint32 CalculateFieldTag() const; - bool IsInlined() const { return inlined_; } - - bool MergeFromCodedStreamNeedsArena() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const bool lite_; - bool inlined_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator); -}; - -class StringOneofFieldGenerator : public StringFieldGenerator { - public: - StringOneofFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~StringOneofFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - - // StringFieldGenerator, from which we inherit, overrides this so we need to - // override it as well. - void GenerateMessageClearingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateDestructorCode(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOneofFieldGenerator); -}; - -class RepeatedStringFieldGenerator : public FieldGenerator { - public: - RepeatedStringFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - ~RepeatedStringFieldGenerator(); - - // implements FieldGenerator --------------------------------------- - void GeneratePrivateMembers(io::Printer* printer) const; - void GenerateAccessorDeclarations(io::Printer* printer) const; - void GenerateInlineAccessorDefinitions(io::Printer* printer) const; - void GenerateClearingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateSwappingCode(io::Printer* printer) const; - void GenerateConstructorCode(io::Printer* printer) const; - void GenerateCopyConstructorCode(io::Printer* printer) const; - void GenerateMergeFromCodedStream(io::Printer* printer) const; - void GenerateSerializeWithCachedSizes(io::Printer* printer) const; - void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const; - void GenerateByteSize(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedStringFieldGenerator); -}; - -} // namespace cpp -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_STRING_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto b/windows/include/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto deleted file mode 100644 index 7fe987597..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto +++ /dev/null @@ -1,160 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file tests that various identifiers work as field and type names even -// though the same identifiers are used internally by the C++ code generator. - -syntax = "proto2"; - -// Some generic_services option(s) added automatically. -// See: http://go/proto2-generic-services-default -option cc_generic_services = true; // auto-added - -// We don't put this in a package within proto2 because we need to make sure -// that the generated code doesn't depend on being in the proto2 namespace. -package protobuf_unittest; - -// Test that fields can have names like "input" and "i" which are also used -// internally by the code generator for local variables. -message TestConflictingSymbolNames { - message BuildDescriptors {} - message TypeTraits {} - - optional int32 input = 1; - optional int32 output = 2; - optional string length = 3; - repeated int32 i = 4; - repeated string new_element = 5 [ctype=STRING_PIECE]; - optional int32 total_size = 6; - optional int32 tag = 7; - - enum TestEnum { FOO = 0; } - message Data1 { repeated int32 data = 1; } - message Data2 { repeated TestEnum data = 1; } - message Data3 { repeated string data = 1; } - message Data4 { repeated Data4 data = 1; } - message Data5 { repeated string data = 1 [ctype=STRING_PIECE]; } - message Data6 { repeated string data = 1 [ctype=CORD]; } - - optional int32 source = 8; - optional int32 value = 9; - optional int32 file = 10; - optional int32 from = 11; - optional int32 handle_uninterpreted = 12; - repeated int32 index = 13; - optional int32 controller = 14; - optional int32 already_here = 15; - - optional uint32 uint32 = 16; - optional uint64 uint64 = 17; - optional string string = 18; - optional int32 memset = 19; - optional int32 int32 = 20; - optional int64 int64 = 21; - - optional uint32 cached_size = 22; - optional uint32 extensions = 23; - optional uint32 bit = 24; - optional uint32 bits = 25; - optional uint32 offsets = 26; - optional uint32 reflection = 27; - - message Cord {} - optional string some_cord = 28 [ctype=CORD]; - - message StringPiece {} - optional string some_string_piece = 29 [ctype=STRING_PIECE]; - - // Some keywords. - optional uint32 int = 30; - optional uint32 friend = 31; - optional uint32 class = 37; - optional uint32 typedecl = 39; - optional uint32 auto = 40; - - // The generator used to #define a macro called "DO" inside the .cc file. - message DO {} - optional DO do = 32; - - // Some template parameter names for extensions. - optional int32 field_type = 33; - optional bool is_packed = 34; - - // test conflicting release_$name$. "length" and "do" field in this message - // must remain string or message fields to make the test valid. - optional string release_length = 35; - // A more extreme case, the field name "do" here is a keyword, which will be - // escaped to "do_" already. Test there is no conflict even with escaped field - // names. - optional DO release_do = 36; - - // For clashing local variables in Serialize and ByteSize calculation. - optional string target = 38; - - extensions 1000 to max; // NO_PROTO3 -} - -message TestConflictingSymbolNamesExtension { // NO_PROTO3 - extend TestConflictingSymbolNames { // NO_PROTO3 - repeated int32 repeated_int32_ext = 20423638 [packed=true]; // NO_PROTO3 - } // NO_PROTO3 -} // NO_PROTO3 - -message TestConflictingEnumNames { // NO_PROTO3 - enum NestedConflictingEnum { // NO_PROTO3 - and = 1; // NO_PROTO3 - class = 2; // NO_PROTO3 - int = 3; // NO_PROTO3 - typedef = 4; // NO_PROTO3 - XOR = 5; // NO_PROTO3 - } // NO_PROTO3 - - optional NestedConflictingEnum conflicting_enum = 1; // NO_PROTO3 -} // NO_PROTO3 - -enum ConflictingEnum { // NO_PROTO3 - NOT_EQ = 1; // NO_PROTO3 - volatile = 2; // NO_PROTO3 - return = 3; // NO_PROTO3 -} // NO_PROTO3 - -message DummyMessage {} - -// Message names that could conflict. -message Shutdown {} -message TableStruct {} - -service TestConflictingMethodNames { - rpc Closure(DummyMessage) returns (DummyMessage); -} diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto b/windows/include/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto deleted file mode 100644 index cb6ca1b15..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto +++ /dev/null @@ -1,43 +0,0 @@ -// 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. - -// Test that proto2 compiler can generate valid code when the enum value -// is INT_MAX. Note that this is a compile-only test and this proto is not -// referenced in any C++ code. -syntax = "proto2"; - -package protobuf_unittest; - -message TestLargeEnumValue { - enum EnumWithLargeValue { - VALUE_1 = 1; - VALUE_MAX = 0x7fffffff; - } -} diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_unittest.cc b/windows/include/google/protobuf/compiler/cpp/cpp_unittest.cc deleted file mode 100644 index 22b759a92..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_unittest.cc +++ /dev/null @@ -1,122 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// To test the code generator, we actually use it to generate code for -// google/protobuf/unittest.proto, then test that. This means that we -// are actually testing the parser and other parts of the system at the same -// time, and that problems in the generator may show up as compile-time errors -// rather than unittest failures, which may be surprising. However, testing -// the output of the C++ generator directly would be very hard. We can't very -// well just check it against golden files since those files would have to be -// updated for any small change; such a test would be very brittle and probably -// not very helpful. What we really want to test is that the code compiles -// correctly and produces the interfaces we expect, which is why this test -// is written this way. - -#include - -#include -#include -#include - -#include - -#define MESSAGE_TEST_NAME MessageTest -#define GENERATED_DESCRIPTOR_TEST_NAME GeneratedDescriptorTest -#define GENERATED_MESSAGE_TEST_NAME GeneratedMessageTest -#define GENERATED_ENUM_TEST_NAME GeneratedEnumTest -#define GENERATED_SERVICE_TEST_NAME GeneratedServiceTest -#define HELPERS_TEST_NAME HelpersTest -#define DESCRIPTOR_INIT_TEST_NAME DescriptorInitializationTest - -#define UNITTEST_PROTO_PATH "google/protobuf/unittest.proto" -#define UNITTEST ::protobuf_unittest -#define UNITTEST_IMPORT ::protobuf_unittest_import - -// Must include after the above macros. -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -// Can't use an anonymous namespace here due to brokenness of Tru64 compiler. -namespace cpp_unittest { - -namespace protobuf_unittest = ::protobuf_unittest; - -TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingSymbolNames) { - // test_bad_identifiers.proto successfully compiled, then it works. The - // following is just a token usage to insure that the code is, in fact, - // being compiled and linked. - - protobuf_unittest::TestConflictingSymbolNames message; - message.set_uint32(1); - EXPECT_EQ(3, message.ByteSizeLong()); - - message.set_friend_(5); - EXPECT_EQ(5, message.friend_()); - - message.set_class_(6); - EXPECT_EQ(6, message.class_()); - - // Instantiate extension template functions to test conflicting template - // parameter names. - typedef protobuf_unittest::TestConflictingSymbolNamesExtension ExtensionMessage; - message.AddExtension(ExtensionMessage::repeated_int32_ext, 123); - EXPECT_EQ(123, - message.GetExtension(ExtensionMessage::repeated_int32_ext, 0)); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, TestConflictingEnumNames) { - protobuf_unittest::TestConflictingEnumNames message; - message.set_conflicting_enum(protobuf_unittest::TestConflictingEnumNames_NestedConflictingEnum_and_); - EXPECT_EQ(1, message.conflicting_enum()); - message.set_conflicting_enum(protobuf_unittest::TestConflictingEnumNames_NestedConflictingEnum_XOR); - EXPECT_EQ(5, message.conflicting_enum()); - - - protobuf_unittest::ConflictingEnum conflicting_enum; - conflicting_enum = protobuf_unittest::NOT_EQ; - EXPECT_EQ(1, conflicting_enum); - conflicting_enum = protobuf_unittest::return_; - EXPECT_EQ(3, conflicting_enum); -} - -} // namespace cpp_unittest -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_unittest.h b/windows/include/google/protobuf/compiler/cpp/cpp_unittest.h deleted file mode 100644 index 69c8f44c1..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_unittest.h +++ /dev/null @@ -1,51 +0,0 @@ -// 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. - -// This header declares the namespace google::protobuf::protobuf_unittest in order to expose -// any problems with the generated class names. We use this header to ensure -// unittest.cc will declare the namespace prior to other includes, while obeying -// normal include ordering. -// -// When generating a class name of "foo.Bar" we must ensure we prefix the class -// name with "::", in case the namespace google::protobuf::foo exists. We intentionally -// trigger that case here by declaring google::protobuf::protobuf_unittest. -// -// See ClassName in helpers.h for more details. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_UNITTEST_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_UNITTEST_H__ - -namespace google { -namespace protobuf { -namespace protobuf_unittest {} -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_UNITTEST_H__ diff --git a/windows/include/google/protobuf/compiler/cpp/cpp_unittest.inc b/windows/include/google/protobuf/compiler/cpp/cpp_unittest.inc deleted file mode 100644 index ff6354f81..000000000 --- a/windows/include/google/protobuf/compiler/cpp/cpp_unittest.inc +++ /dev/null @@ -1,2281 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// To test the code generator, we actually use it to generate code for -// google/protobuf/unittest.proto, then test that. This means that we -// are actually testing the parser and other parts of the system at the same -// time, and that problems in the generator may show up as compile-time errors -// rather than unittest failures, which may be surprising. However, testing -// the output of the C++ generator directly would be very hard. We can't very -// well just check it against golden files since those files would have to be -// updated for any small change; such a test would be very brittle and probably -// not very helpful. What we really want to test is that the code compiles -// correctly and produces the interfaces we expect, which is why this test -// is written this way. - -#include - -#include -#include - -#include -#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) -// We exclude this large proto from cmake build because it's too large for -// visual studio to compile (report internal errors). -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace cpp { - -// Can't use an anonymous namespace here due to brokenness of Tru64 compiler. -namespace cpp_unittest { - - -class MockErrorCollector : public MultiFileErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - - // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", - filename, line, column, message); - } -}; - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -// Test that generated code has proper descriptors: -// Parse a descriptor directly (using google::protobuf::compiler::Importer) and -// compare it to the one that was produced by generated code. -TEST(GENERATED_DESCRIPTOR_TEST_NAME, IdenticalDescriptors) { - const FileDescriptor* generated_descriptor = - UNITTEST::TestAllTypes::descriptor()->file(); - - // Set up the Importer. - MockErrorCollector error_collector; - DiskSourceTree source_tree; - source_tree.MapPath("", TestSourceDir()); - Importer importer(&source_tree, &error_collector); - - // Import (parse) unittest.proto. - const FileDescriptor* parsed_descriptor = - importer.Import(UNITTEST_PROTO_PATH); - EXPECT_EQ("", error_collector.text_); - ASSERT_TRUE(parsed_descriptor != NULL); - - // Test that descriptors are generated correctly by converting them to - // FileDescriptorProtos and comparing. - FileDescriptorProto generated_descriptor_proto, parsed_descriptor_proto; - generated_descriptor->CopyTo(&generated_descriptor_proto); - parsed_descriptor->CopyTo(&parsed_descriptor_proto); - - EXPECT_EQ(parsed_descriptor_proto.DebugString(), - generated_descriptor_proto.DebugString()); -} - -#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) -// Test that generated code has proper descriptors: -// Touch a descriptor generated from an enormous message to validate special -// handling for descriptors exceeding the C++ standard's recommended minimum -// limit for string literal size -TEST(GENERATED_DESCRIPTOR_TEST_NAME, EnormousDescriptor) { - const Descriptor* generated_descriptor = - TestEnormousDescriptor::descriptor(); - - EXPECT_TRUE(generated_descriptor != NULL); -} -#endif - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -TEST(GENERATED_MESSAGE_TEST_NAME, Defaults) { - // Check that all default values are set correctly in the initial message. - UNITTEST::TestAllTypes message; - - TestUtil::ExpectClear(message); - - // Messages should return pointers to default instances until first use. - // (This is not checked by ExpectClear() since it is not actually true after - // the fields have been set and then cleared.) - EXPECT_EQ(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(), - &message.optionalgroup()); - EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - EXPECT_EQ(&UNITTEST::ForeignMessage::default_instance(), - &message.optional_foreign_message()); - EXPECT_EQ(&UNITTEST_IMPORT::ImportMessage::default_instance(), - &message.optional_import_message()); -} - -#ifndef PROTOBUF_USE_DLLS -TEST(GENERATED_MESSAGE_TEST_NAME, Int32StringConversion) { - EXPECT_EQ("971", Int32ToString(971)); - EXPECT_EQ("(~0x7fffffff)", Int32ToString(kint32min)); - EXPECT_EQ("2147483647", Int32ToString(kint32max)); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, Int64StringConversion) { - EXPECT_EQ("GOOGLE_LONGLONG(971)", Int64ToString(971)); - EXPECT_EQ("GOOGLE_LONGLONG(-2147483648)", Int64ToString(kint32min)); - EXPECT_EQ("GOOGLE_LONGLONG(~0x7fffffffffffffff)", Int64ToString(kint64min)); - EXPECT_EQ("GOOGLE_LONGLONG(9223372036854775807)", Int64ToString(kint64max)); -} -#endif // !PROTOBUF_USE_DLLS - -TEST(GENERATED_MESSAGE_TEST_NAME, FloatingPointDefaults) { - const UNITTEST::TestExtremeDefaultValues& extreme_default = - UNITTEST::TestExtremeDefaultValues::default_instance(); - - EXPECT_EQ(0.0f, extreme_default.zero_float()); - EXPECT_EQ(1.0f, extreme_default.one_float()); - EXPECT_EQ(1.5f, extreme_default.small_float()); - EXPECT_EQ(-1.0f, extreme_default.negative_one_float()); - EXPECT_EQ(-1.5f, extreme_default.negative_float()); - EXPECT_EQ(2.0e8f, extreme_default.large_float()); - EXPECT_EQ(-8e-28f, extreme_default.small_negative_float()); - EXPECT_EQ(std::numeric_limits::infinity(), - extreme_default.inf_double()); - EXPECT_EQ(-std::numeric_limits::infinity(), - extreme_default.neg_inf_double()); - EXPECT_TRUE(extreme_default.nan_double() != extreme_default.nan_double()); - EXPECT_EQ(std::numeric_limits::infinity(), - extreme_default.inf_float()); - EXPECT_EQ(-std::numeric_limits::infinity(), - extreme_default.neg_inf_float()); - EXPECT_TRUE(extreme_default.nan_float() != extreme_default.nan_float()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, Trigraph) { - const UNITTEST::TestExtremeDefaultValues& extreme_default = - UNITTEST::TestExtremeDefaultValues::default_instance(); - - EXPECT_EQ("? ? ?? ?? ??? ?\?/ ?\?-", extreme_default.cpp_trigraph()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ExtremeSmallIntegerDefault) { - const UNITTEST::TestExtremeDefaultValues& extreme_default = - UNITTEST::TestExtremeDefaultValues::default_instance(); - EXPECT_EQ(~0x7fffffff, kint32min); - EXPECT_EQ(GOOGLE_LONGLONG(~0x7fffffffffffffff), kint64min); - EXPECT_EQ(kint32min, extreme_default.really_small_int32()); - EXPECT_EQ(kint64min, extreme_default.really_small_int64()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, Accessors) { - // Set every field to a unique value then go back and check all those - // values. - UNITTEST::TestAllTypes message; - - TestUtil::SetAllFields(&message); - TestUtil::ExpectAllFieldsSet(message); - - TestUtil::ModifyRepeatedFields(&message); - TestUtil::ExpectRepeatedFieldsModified(message); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, MutableStringDefault) { - // mutable_foo() for a string should return a string initialized to its - // default value. - UNITTEST::TestAllTypes message; - - EXPECT_EQ("hello", *message.mutable_default_string()); - - // Note that the first time we call mutable_foo(), we get a newly-allocated - // string, but if we clear it and call it again, we get the same object again. - // We should verify that it has its default value in both cases. - message.set_default_string("blah"); - message.Clear(); - - EXPECT_EQ("hello", *message.mutable_default_string()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, StringDefaults) { - UNITTEST::TestExtremeDefaultValues message; - // Check if '\000' can be used in default string value. - EXPECT_EQ(string("hel\000lo", 6), message.string_with_zero()); - EXPECT_EQ(string("wor\000ld", 6), message.bytes_with_zero()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseString) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - UNITTEST::TestAllTypes message; - - EXPECT_EQ(NULL, message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - EXPECT_EQ("hello", message.default_string()); - - message.set_default_string("blah"); - EXPECT_TRUE(message.has_default_string()); - std::unique_ptr str(message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - ASSERT_TRUE(str != NULL); - EXPECT_EQ("blah", *str); - - EXPECT_EQ(NULL, message.release_default_string()); - EXPECT_FALSE(message.has_default_string()); - EXPECT_EQ("hello", message.default_string()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ReleaseMessage) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - UNITTEST::TestAllTypes message; - - EXPECT_EQ(NULL, message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - std::unique_ptr nest( - message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); - ASSERT_TRUE(nest != NULL); - EXPECT_EQ(1, nest->bb()); - - EXPECT_EQ(NULL, message.release_optional_nested_message()); - EXPECT_FALSE(message.has_optional_nested_message()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedString) { - // Check that set_allocated_foo() works for strings. - UNITTEST::TestAllTypes message; - - EXPECT_FALSE(message.has_optional_string()); - const string kHello("hello"); - message.set_optional_string(kHello); - EXPECT_TRUE(message.has_optional_string()); - - message.set_allocated_optional_string(NULL); - EXPECT_FALSE(message.has_optional_string()); - EXPECT_EQ("", message.optional_string()); - - message.set_allocated_optional_string(new string(kHello)); - EXPECT_TRUE(message.has_optional_string()); - EXPECT_EQ(kHello, message.optional_string()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, SetAllocatedMessage) { - // Check that set_allocated_foo() can be called in all cases. - UNITTEST::TestAllTypes message; - - EXPECT_FALSE(message.has_optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - EXPECT_TRUE(message.has_optional_nested_message()); - - message.set_allocated_optional_nested_message(NULL); - EXPECT_FALSE(message.has_optional_nested_message()); - EXPECT_EQ(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - - message.mutable_optional_nested_message()->set_bb(1); - UNITTEST::TestAllTypes::NestedMessage* nest = - message.release_optional_nested_message(); - ASSERT_TRUE(nest != NULL); - EXPECT_FALSE(message.has_optional_nested_message()); - - message.set_allocated_optional_nested_message(nest); - EXPECT_TRUE(message.has_optional_nested_message()); - EXPECT_EQ(1, message.optional_nested_message().bb()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, Clear) { - // Set every field to a unique value, clear the message, then check that - // it is cleared. - UNITTEST::TestAllTypes message; - - TestUtil::SetAllFields(&message); - message.Clear(); - TestUtil::ExpectClear(message); - - // Unlike with the defaults test, we do NOT expect that requesting embedded - // messages will return a pointer to the default instance. Instead, they - // should return the objects that were created when mutable_blah() was - // called. - EXPECT_NE(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(), - &message.optionalgroup()); - EXPECT_NE(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - EXPECT_NE(&UNITTEST::ForeignMessage::default_instance(), - &message.optional_foreign_message()); - EXPECT_NE(&UNITTEST_IMPORT::ImportMessage::default_instance(), - &message.optional_import_message()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, EmbeddedNullsInBytesCharStar) { - UNITTEST::TestAllTypes message; - - const char* value = "\0lalala\0\0"; - message.set_optional_bytes(value, 9); - ASSERT_EQ(9, message.optional_bytes().size()); - EXPECT_EQ(0, memcmp(value, message.optional_bytes().data(), 9)); - - message.add_repeated_bytes(value, 9); - ASSERT_EQ(9, message.repeated_bytes(0).size()); - EXPECT_EQ(0, memcmp(value, message.repeated_bytes(0).data(), 9)); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ClearOneField) { - // Set every field to a unique value, then clear one value and insure that - // only that one value is cleared. - UNITTEST::TestAllTypes message; - - TestUtil::SetAllFields(&message); - int64 original_value = message.optional_int64(); - - // Clear the field and make sure it shows up as cleared. - message.clear_optional_int64(); - EXPECT_FALSE(message.has_optional_int64()); - EXPECT_EQ(0, message.optional_int64()); - - // Other adjacent fields should not be cleared. - EXPECT_TRUE(message.has_optional_int32()); - EXPECT_TRUE(message.has_optional_uint32()); - - // Make sure if we set it again, then all fields are set. - message.set_optional_int64(original_value); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, StringCharStarLength) { - // Verify that we can use a char*,length to set one of the string fields. - UNITTEST::TestAllTypes message; - message.set_optional_string("abcdef", 3); - EXPECT_EQ("abc", message.optional_string()); - - // Verify that we can use a char*,length to add to a repeated string field. - message.add_repeated_string("abcdef", 3); - EXPECT_EQ(1, message.repeated_string_size()); - EXPECT_EQ("abc", message.repeated_string(0)); - - // Verify that we can use a char*,length to set a repeated string field. - message.set_repeated_string(0, "wxyz", 2); - EXPECT_EQ("wx", message.repeated_string(0)); -} - -#if LANG_CXX11 -TEST(GENERATED_MESSAGE_TEST_NAME, StringMove) { - // Verify that we trigger the move behavior on a scalar setter. - protobuf_unittest_no_arena::TestAllTypes message; - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.set_optional_string(std::move(tmp)); - const char* new_data = message.optional_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.optional_string()); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_optional_string(std::move(tmp2)); - new_data = message.optional_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.optional_string()); - } - - // Verify that we trigger the move behavior on a oneof setter. - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.set_oneof_string(std::move(tmp)); - const char* new_data = message.oneof_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.oneof_string()); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_oneof_string(std::move(tmp2)); - new_data = message.oneof_string().data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.oneof_string()); - } - - // Verify that we trigger the move behavior on a repeated setter. - { - string tmp(32, 'a'); - - const char* old_data = tmp.data(); - message.add_repeated_string(std::move(tmp)); - const char* new_data = message.repeated_string(0).data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'a'), message.repeated_string(0)); - - string tmp2(32, 'b'); - old_data = tmp2.data(); - message.set_repeated_string(0, std::move(tmp2)); - new_data = message.repeated_string(0).data(); - - EXPECT_EQ(old_data, new_data); - EXPECT_EQ(string(32, 'b'), message.repeated_string(0)); - } -} -#endif - - -TEST(GENERATED_MESSAGE_TEST_NAME, CopyFrom) { - UNITTEST::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - message2.CopyFrom(message1); - TestUtil::ExpectAllFieldsSet(message2); - - // Copying from self should be a no-op. - message2.CopyFrom(message2); - TestUtil::ExpectAllFieldsSet(message2); -} - - -TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithEmpty) { - UNITTEST::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - - TestUtil::ExpectAllFieldsSet(message1); - TestUtil::ExpectClear(message2); - message1.Swap(&message2); - TestUtil::ExpectAllFieldsSet(message2); - TestUtil::ExpectClear(message1); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithSelf) { - UNITTEST::TestAllTypes message; - TestUtil::SetAllFields(&message); - TestUtil::ExpectAllFieldsSet(message); - message.Swap(&message); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithOther) { - UNITTEST::TestAllTypes message1, message2; - - message1.set_optional_int32(123); - message1.set_optional_string("abc"); - message1.mutable_optional_nested_message()->set_bb(1); - message1.set_optional_nested_enum(UNITTEST::TestAllTypes::FOO); - message1.add_repeated_int32(1); - message1.add_repeated_int32(2); - message1.add_repeated_string("a"); - message1.add_repeated_string("b"); - message1.add_repeated_nested_message()->set_bb(7); - message1.add_repeated_nested_message()->set_bb(8); - message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::FOO); - message1.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAR); - - message2.set_optional_int32(456); - message2.set_optional_string("def"); - message2.mutable_optional_nested_message()->set_bb(2); - message2.set_optional_nested_enum(UNITTEST::TestAllTypes::BAR); - message2.add_repeated_int32(3); - message2.add_repeated_string("c"); - message2.add_repeated_nested_message()->set_bb(9); - message2.add_repeated_nested_enum(UNITTEST::TestAllTypes::BAZ); - - message1.Swap(&message2); - - EXPECT_EQ(456, message1.optional_int32()); - EXPECT_EQ("def", message1.optional_string()); - EXPECT_EQ(2, message1.optional_nested_message().bb()); - EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message1.optional_nested_enum()); - ASSERT_EQ(1, message1.repeated_int32_size()); - EXPECT_EQ(3, message1.repeated_int32(0)); - ASSERT_EQ(1, message1.repeated_string_size()); - EXPECT_EQ("c", message1.repeated_string(0)); - ASSERT_EQ(1, message1.repeated_nested_message_size()); - EXPECT_EQ(9, message1.repeated_nested_message(0).bb()); - ASSERT_EQ(1, message1.repeated_nested_enum_size()); - EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message1.repeated_nested_enum(0)); - - EXPECT_EQ(123, message2.optional_int32()); - EXPECT_EQ("abc", message2.optional_string()); - EXPECT_EQ(1, message2.optional_nested_message().bb()); - EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.optional_nested_enum()); - ASSERT_EQ(2, message2.repeated_int32_size()); - EXPECT_EQ(1, message2.repeated_int32(0)); - EXPECT_EQ(2, message2.repeated_int32(1)); - ASSERT_EQ(2, message2.repeated_string_size()); - EXPECT_EQ("a", message2.repeated_string(0)); - EXPECT_EQ("b", message2.repeated_string(1)); - ASSERT_EQ(2, message2.repeated_nested_message_size()); - EXPECT_EQ(7, message2.repeated_nested_message(0).bb()); - EXPECT_EQ(8, message2.repeated_nested_message(1).bb()); - ASSERT_EQ(2, message2.repeated_nested_enum_size()); - EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message2.repeated_nested_enum(0)); - EXPECT_EQ(UNITTEST::TestAllTypes::BAR, message2.repeated_nested_enum(1)); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ADLSwap) { - UNITTEST::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - - // Note the address of one of the repeated fields, to verify it was swapped - // rather than copied. - const int32* addr = &message1.repeated_int32().Get(0); - - using std::swap; - swap(message1, message2); - - TestUtil::ExpectAllFieldsSet(message2); - TestUtil::ExpectClear(message1); - - EXPECT_EQ(addr, &message2.repeated_int32().Get(0)); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructor) { - // All set. - { - UNITTEST::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - - UNITTEST::TestAllTypes message2(message1); - TestUtil::ExpectAllFieldsSet(message2); - } - - // None set. - { - UNITTEST::TestAllTypes message1; - UNITTEST::TestAllTypes message2(message1); - - EXPECT_FALSE(message1.has_optional_string()); - EXPECT_FALSE(message2.has_optional_string()); - EXPECT_EQ(message1.optional_string(), message2.optional_string()); - - EXPECT_FALSE(message1.has_optional_bytes()); - EXPECT_FALSE(message2.has_optional_bytes()); - EXPECT_EQ(message1.optional_bytes(), message2.optional_bytes()); - - EXPECT_FALSE(message1.has_optional_nested_message()); - EXPECT_FALSE(message2.has_optional_nested_message()); - EXPECT_EQ(&message1.optional_nested_message(), - &message2.optional_nested_message()); - - EXPECT_FALSE(message1.has_optional_foreign_message()); - EXPECT_FALSE(message2.has_optional_foreign_message()); - EXPECT_EQ(&message1.optional_foreign_message(), - &message2.optional_foreign_message()); - - EXPECT_FALSE(message1.has_optional_import_message()); - EXPECT_FALSE(message2.has_optional_import_message()); - EXPECT_EQ(&message1.optional_import_message(), - &message2.optional_import_message()); - - EXPECT_FALSE(message1.has_optional_public_import_message()); - EXPECT_FALSE(message2.has_optional_public_import_message()); - EXPECT_EQ(&message1.optional_public_import_message(), - &message2.optional_public_import_message()); - - EXPECT_FALSE(message1.has_optional_lazy_message()); - EXPECT_FALSE(message2.has_optional_lazy_message()); - EXPECT_EQ(&message1.optional_lazy_message(), - &message2.optional_lazy_message()); - } -} - -TEST(GENERATED_MESSAGE_TEST_NAME, CopyConstructorWithArenas) { - Arena arena; - UNITTEST::TestAllTypes* message1 = - Arena::CreateMessage(&arena); - TestUtil::SetAllFields(message1); - - UNITTEST::TestAllTypes message2_stack(*message1); - TestUtil::ExpectAllFieldsSet(message2_stack); - - std::unique_ptr message2_heap( - new UNITTEST::TestAllTypes(*message1)); - TestUtil::ExpectAllFieldsSet(*message2_heap); - - arena.Reset(); - - // Verify that the copies are still intact. - TestUtil::ExpectAllFieldsSet(message2_stack); - TestUtil::ExpectAllFieldsSet(*message2_heap); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) { - UNITTEST::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - - UNITTEST::TestAllTypes message2; - message2 = message1; - TestUtil::ExpectAllFieldsSet(message2); - - // Make sure that self-assignment does something sane. - message2.operator=(message2); - TestUtil::ExpectAllFieldsSet(message2); -} - -#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \ - !defined(GOOGLE_PROTOBUF_NO_RTTI) -TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) { - // Test the CopyFrom method that takes in the generic const Message& - // parameter. - UNITTEST::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - - const Message* source = implicit_cast(&message1); - message2.CopyFrom(*source); - - TestUtil::ExpectAllFieldsSet(message2); -} -#endif - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GENERATED_MESSAGE_TEST_NAME, DynamicMessageCopyFrom) { - // Test copying from a DynamicMessage, which must fall back to using - // reflection. - UNITTEST::TestAllTypes message2; - - // Construct a new version of the dynamic message via the factory. - DynamicMessageFactory factory; - std::unique_ptr message1; - message1.reset(factory.GetPrototype( - UNITTEST::TestAllTypes::descriptor())->New()); - - TestUtil::ReflectionTester reflection_tester( - UNITTEST::TestAllTypes::descriptor()); - reflection_tester.SetAllFieldsViaReflection(message1.get()); - - message2.CopyFrom(*message1); - - TestUtil::ExpectAllFieldsSet(message2); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GENERATED_MESSAGE_TEST_NAME, NonEmptyMergeFrom) { - // Test merging with a non-empty message. Code is a modified form - // of that found in google/protobuf/reflection_ops_unittest.cc. - UNITTEST::TestAllTypes message1, message2; - - TestUtil::SetAllFields(&message1); - - // This field will test merging into an empty spot. - message2.set_optional_int32(message1.optional_int32()); - message1.clear_optional_int32(); - - // This tests overwriting. - message2.set_optional_string(message1.optional_string()); - message1.set_optional_string("something else"); - - // This tests concatenating. - message2.add_repeated_int32(message1.repeated_int32(1)); - int32 i = message1.repeated_int32(0); - message1.clear_repeated_int32(); - message1.add_repeated_int32(i); - - message1.MergeFrom(message2); - - TestUtil::ExpectAllFieldsSet(message1); -} - - -// Test the generated SerializeWithCachedSizesToArray(), -TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToArray) { - UNITTEST::TestAllTypes message1, message2; - string data; - TestUtil::SetAllFields(&message1); - int size = message1.ByteSizeLong(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(message2); - -} - -TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToArray) { - UNITTEST::TestPackedTypes packed_message1, packed_message2; - string packed_data; - TestUtil::SetPackedFields(&packed_message1); - int packed_size = packed_message1.ByteSizeLong(); - packed_data.resize(packed_size); - uint8* start = reinterpret_cast(string_as_array(&packed_data)); - uint8* end = packed_message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(packed_size, end - start); - EXPECT_TRUE(packed_message2.ParseFromString(packed_data)); - TestUtil::ExpectPackedFieldsSet(packed_message2); -} - -// Test the generated SerializeWithCachedSizes() by forcing the buffer to write -// one byte at a time. -TEST(GENERATED_MESSAGE_TEST_NAME, SerializationToStream) { - UNITTEST::TestAllTypes message1, message2; - TestUtil::SetAllFields(&message1); - int size = message1.ByteSizeLong(); - string data; - data.resize(size); - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - EXPECT_TRUE(message2.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(message2); - -} - -TEST(GENERATED_MESSAGE_TEST_NAME, PackedFieldsSerializationToStream) { - UNITTEST::TestPackedTypes message1, message2; - TestUtil::SetPackedFields(&message1); - int size = message1.ByteSizeLong(); - string data; - data.resize(size); - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - EXPECT_TRUE(message2.ParseFromString(data)); - TestUtil::ExpectPackedFieldsSet(message2); -} - - -TEST(GENERATED_MESSAGE_TEST_NAME, Required) { - // Test that IsInitialized() returns false if required fields are missing. - UNITTEST::TestRequired message; - - EXPECT_FALSE(message.IsInitialized()); - message.set_a(1); - EXPECT_FALSE(message.IsInitialized()); - message.set_b(2); - EXPECT_FALSE(message.IsInitialized()); - message.set_c(3); - EXPECT_TRUE(message.IsInitialized()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, RequiredForeign) { - // Test that IsInitialized() returns false if required fields in nested - // messages are missing. - UNITTEST::TestRequiredForeign message; - - EXPECT_TRUE(message.IsInitialized()); - - message.mutable_optional_message(); - EXPECT_FALSE(message.IsInitialized()); - - message.mutable_optional_message()->set_a(1); - message.mutable_optional_message()->set_b(2); - message.mutable_optional_message()->set_c(3); - EXPECT_TRUE(message.IsInitialized()); - - message.add_repeated_message(); - EXPECT_FALSE(message.IsInitialized()); - - message.mutable_repeated_message(0)->set_a(1); - message.mutable_repeated_message(0)->set_b(2); - message.mutable_repeated_message(0)->set_c(3); - EXPECT_TRUE(message.IsInitialized()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ForeignNested) { - // Test that TestAllTypes::NestedMessage can be embedded directly into - // another message. - UNITTEST::TestForeignNested message; - - // If this compiles and runs without crashing, it must work. We have - // nothing more to test. - UNITTEST::TestAllTypes::NestedMessage* nested = - message.mutable_foreign_nested(); - nested->set_bb(1); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ReallyLargeTagNumber) { - // Test that really large tag numbers don't break anything. - UNITTEST::TestReallyLargeTagNumber message1, message2; - string data; - - // For the most part, if this compiles and runs then we're probably good. - // (The most likely cause for failure would be if something were attempting - // to allocate a lookup table of some sort using tag numbers as the index.) - // We'll try serializing just for fun. - message1.set_a(1234); - message1.set_bb(5678); - message1.SerializeToString(&data); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(1234, message2.a()); - EXPECT_EQ(5678, message2.bb()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, MutualRecursion) { - // Test that mutually-recursive message types work. - UNITTEST::TestMutualRecursionA message; - UNITTEST::TestMutualRecursionA* nested = message.mutable_bb()->mutable_a(); - UNITTEST::TestMutualRecursionA* nested2 = nested->mutable_bb()->mutable_a(); - - // Again, if the above compiles and runs, that's all we really have to - // test, but just for run we'll check that the system didn't somehow come - // up with a pointer loop... - EXPECT_NE(&message, nested); - EXPECT_NE(&message, nested2); - EXPECT_NE(nested, nested2); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, CamelCaseFieldNames) { - // This test is mainly checking that the following compiles, which verifies - // that the field names were coerced to lower-case. - // - // Protocol buffers standard style is to use lowercase-with-underscores for - // field names. Some old proto1 .protos unfortunately used camel-case field - // names. In proto1, these names were forced to lower-case. So, we do the - // same thing in proto2. - - UNITTEST::TestCamelCaseFieldNames message; - - message.set_primitivefield(2); - message.set_stringfield("foo"); - message.set_enumfield(UNITTEST::FOREIGN_FOO); - message.mutable_messagefield()->set_c(6); - - message.add_repeatedprimitivefield(8); - message.add_repeatedstringfield("qux"); - message.add_repeatedenumfield(UNITTEST::FOREIGN_BAR); - message.add_repeatedmessagefield()->set_c(15); - - EXPECT_EQ(2, message.primitivefield()); - EXPECT_EQ("foo", message.stringfield()); - EXPECT_EQ(UNITTEST::FOREIGN_FOO, message.enumfield()); - EXPECT_EQ(6, message.messagefield().c()); - - EXPECT_EQ(8, message.repeatedprimitivefield(0)); - EXPECT_EQ("qux", message.repeatedstringfield(0)); - EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeatedenumfield(0)); - EXPECT_EQ(15, message.repeatedmessagefield(0).c()); -} - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GENERATED_MESSAGE_TEST_NAME, TestOptimizedForSize) { - // We rely on the tests in reflection_ops_unittest and wire_format_unittest - // to really test that reflection-based methods work. Here we are mostly - // just making sure that TestOptimizedForSize actually builds and seems to - // function. - - UNITTEST::TestOptimizedForSize message, message2; - message.set_i(1); - message.mutable_msg()->set_c(2); - message2.CopyFrom(message); - EXPECT_EQ(1, message2.i()); - EXPECT_EQ(2, message2.msg().c()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, TestEmbedOptimizedForSize) { - // Verifies that something optimized for speed can contain something optimized - // for size. - - UNITTEST::TestEmbedOptimizedForSize message, message2; - message.mutable_optional_message()->set_i(1); - message.add_repeated_message()->mutable_msg()->set_c(2); - string data; - message.SerializeToString(&data); - ASSERT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(1, message2.optional_message().i()); - EXPECT_EQ(2, message2.repeated_message(0).msg().c()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, TestSpaceUsed) { - UNITTEST::TestAllTypes message1; - // sizeof provides a lower bound on SpaceUsedLong(). - EXPECT_LE(sizeof(UNITTEST::TestAllTypes), message1.SpaceUsedLong()); - const size_t empty_message_size = message1.SpaceUsedLong(); - - // Setting primitive types shouldn't affect the space used. - message1.set_optional_int32(123); - message1.set_optional_int64(12345); - message1.set_optional_uint32(123); - message1.set_optional_uint64(12345); - EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); - - // On some STL implementations, setting the string to a small value should - // only increase SpaceUsedLong() by the size of a string object, though this - // is not true everywhere. - message1.set_optional_string("abc"); - EXPECT_LE(empty_message_size + message1.optional_string().size(), - message1.SpaceUsedLong()); - - // Setting a string to a value larger than the string object itself should - // increase SpaceUsedLong(), because it cannot store the value internally. - message1.set_optional_string(string(sizeof(string) + 1, 'x')); - int min_expected_increase = message1.optional_string().capacity(); - EXPECT_LE(empty_message_size + min_expected_increase, - message1.SpaceUsedLong()); - - size_t previous_size = message1.SpaceUsedLong(); - // Adding an optional message should increase the size by the size of the - // nested message type. NestedMessage is simple enough (1 int field) that it - // is equal to sizeof(NestedMessage) - message1.mutable_optional_nested_message(); - ASSERT_EQ(sizeof(UNITTEST::TestAllTypes::NestedMessage), - message1.optional_nested_message().SpaceUsedLong()); - EXPECT_EQ(previous_size + - sizeof(UNITTEST::TestAllTypes::NestedMessage), - message1.SpaceUsedLong()); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, TestOneofSpaceUsed) { - UNITTEST::TestOneof2 message1; - EXPECT_LE(sizeof(UNITTEST::TestOneof2), message1.SpaceUsedLong()); - - const size_t empty_message_size = message1.SpaceUsedLong(); - // Setting primitive types shouldn't affect the space used. - message1.set_foo_int(123); - message1.set_bar_int(12345); - EXPECT_EQ(empty_message_size, message1.SpaceUsedLong()); - - // Setting a string in oneof to a small value should only increase - // SpaceUsedLong() by the size of a string object. - message1.set_foo_string("abc"); - EXPECT_LE(empty_message_size + sizeof(string), message1.SpaceUsedLong()); - - // Setting a string in oneof to a value larger than the string object itself - // should increase SpaceUsedLong(), because it cannot store the value - // internally. - message1.set_foo_string(string(sizeof(string) + 1, 'x')); - int min_expected_increase = message1.foo_string().capacity() + - sizeof(string); - EXPECT_LE(empty_message_size + min_expected_increase, - message1.SpaceUsedLong()); - - // Setting a message in oneof should delete the other fields and increase the - // size by the size of the nested message type. NestedMessage is simple enough - // that it is equal to sizeof(NestedMessage) - message1.mutable_foo_message(); - ASSERT_EQ(sizeof(UNITTEST::TestOneof2::NestedMessage), - message1.foo_message().SpaceUsedLong()); - EXPECT_EQ(empty_message_size + - sizeof(UNITTEST::TestOneof2::NestedMessage), - message1.SpaceUsedLong()); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - - -TEST(GENERATED_MESSAGE_TEST_NAME, FieldConstantValues) { - UNITTEST::TestRequired message; - EXPECT_EQ(UNITTEST::TestAllTypes_NestedMessage::kBbFieldNumber, 1); - EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalInt32FieldNumber, 1); - EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalgroupFieldNumber, 16); - EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedMessageFieldNumber, 18); - EXPECT_EQ(UNITTEST::TestAllTypes::kOptionalNestedEnumFieldNumber, 21); - EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedInt32FieldNumber, 31); - EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedgroupFieldNumber, 46); - EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedMessageFieldNumber, 48); - EXPECT_EQ(UNITTEST::TestAllTypes::kRepeatedNestedEnumFieldNumber, 51); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ExtensionConstantValues) { - EXPECT_EQ(UNITTEST::TestRequired::kSingleFieldNumber, 1000); - EXPECT_EQ(UNITTEST::TestRequired::kMultiFieldNumber, 1001); - EXPECT_EQ(UNITTEST::kOptionalInt32ExtensionFieldNumber, 1); - EXPECT_EQ(UNITTEST::kOptionalgroupExtensionFieldNumber, 16); - EXPECT_EQ(UNITTEST::kOptionalNestedMessageExtensionFieldNumber, 18); - EXPECT_EQ(UNITTEST::kOptionalNestedEnumExtensionFieldNumber, 21); - EXPECT_EQ(UNITTEST::kRepeatedInt32ExtensionFieldNumber, 31); - EXPECT_EQ(UNITTEST::kRepeatedgroupExtensionFieldNumber, 46); - EXPECT_EQ(UNITTEST::kRepeatedNestedMessageExtensionFieldNumber, 48); - EXPECT_EQ(UNITTEST::kRepeatedNestedEnumExtensionFieldNumber, 51); -} - -TEST(GENERATED_MESSAGE_TEST_NAME, ParseFromTruncated) { - const string long_string = string(128, 'q'); - FileDescriptorProto p; - p.add_extension()->set_name(long_string); - const string msg = p.SerializeAsString(); - int successful_count = 0; - for (int i = 0; i <= msg.size(); i++) { - if (p.ParseFromArray(msg.c_str(), i)) { - ++successful_count; - } - } - // We don't really care about how often we succeeded. - // As long as we didn't crash, we're happy. - EXPECT_GE(successful_count, 1); -} - -// =================================================================== - -TEST(GENERATED_ENUM_TEST_NAME, EnumValuesAsSwitchCases) { - // Test that our nested enum values can be used as switch cases. This test - // doesn't actually do anything, the proof that it works is that it - // compiles. - int i =0; - UNITTEST::TestAllTypes::NestedEnum a = UNITTEST::TestAllTypes::BAR; - switch (a) { - case UNITTEST::TestAllTypes::FOO: - i = 1; - break; - case UNITTEST::TestAllTypes::BAR: - i = 2; - break; - case UNITTEST::TestAllTypes::BAZ: - i = 3; - break; - case UNITTEST::TestAllTypes::NEG: - i = -1; - break; - // no default case: We want to make sure the compiler recognizes that - // all cases are covered. (GCC warns if you do not cover all cases of - // an enum in a switch.) - } - - // Token check just for fun. - EXPECT_EQ(2, i); -} - -TEST(GENERATED_ENUM_TEST_NAME, IsValidValue) { - // Test enum IsValidValue. - EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(1)); - EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(2)); - EXPECT_TRUE(UNITTEST::TestAllTypes::NestedEnum_IsValid(3)); - - EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(0)); - EXPECT_FALSE(UNITTEST::TestAllTypes::NestedEnum_IsValid(4)); - - // Make sure it also works when there are dups. - EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(1)); - EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(2)); - EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_IsValid(3)); - - EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(0)); - EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_IsValid(4)); -} - -TEST(GENERATED_ENUM_TEST_NAME, MinAndMax) { - EXPECT_EQ(UNITTEST::TestAllTypes::NEG, - UNITTEST::TestAllTypes::NestedEnum_MIN); - EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, - UNITTEST::TestAllTypes::NestedEnum_MAX); - EXPECT_EQ(4, UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE); - - EXPECT_EQ(UNITTEST::FOREIGN_FOO, UNITTEST::ForeignEnum_MIN); - EXPECT_EQ(UNITTEST::FOREIGN_BAZ, UNITTEST::ForeignEnum_MAX); - EXPECT_EQ(7, UNITTEST::ForeignEnum_ARRAYSIZE); - - EXPECT_EQ(1, UNITTEST::TestEnumWithDupValue_MIN); - EXPECT_EQ(3, UNITTEST::TestEnumWithDupValue_MAX); - EXPECT_EQ(4, UNITTEST::TestEnumWithDupValue_ARRAYSIZE); - - EXPECT_EQ(UNITTEST::SPARSE_E, UNITTEST::TestSparseEnum_MIN); - EXPECT_EQ(UNITTEST::SPARSE_C, UNITTEST::TestSparseEnum_MAX); - EXPECT_EQ(12589235, UNITTEST::TestSparseEnum_ARRAYSIZE); - - // Make sure we can take the address of _MIN, _MAX and _ARRAYSIZE. - void* null_pointer = 0; // NULL may be integer-type, not pointer-type. - EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MIN); - EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_MAX); - EXPECT_NE(null_pointer, &UNITTEST::TestAllTypes::NestedEnum_ARRAYSIZE); - - EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MIN); - EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_MAX); - EXPECT_NE(null_pointer, &UNITTEST::ForeignEnum_ARRAYSIZE); - - // Make sure we can use _MIN and _MAX as switch cases. - switch (UNITTEST::SPARSE_A) { - case UNITTEST::TestSparseEnum_MIN: - case UNITTEST::TestSparseEnum_MAX: - break; - default: - break; - } -} - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -TEST(GENERATED_ENUM_TEST_NAME, Name) { - // "Names" in the presence of dup values are a bit arbitrary. - EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO1)); - EXPECT_EQ("FOO1", UNITTEST::TestEnumWithDupValue_Name(UNITTEST::FOO2)); - - EXPECT_EQ("SPARSE_A", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_A)); - EXPECT_EQ("SPARSE_B", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_B)); - EXPECT_EQ("SPARSE_C", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_C)); - EXPECT_EQ("SPARSE_D", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_D)); - EXPECT_EQ("SPARSE_E", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_E)); - EXPECT_EQ("SPARSE_F", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_F)); - EXPECT_EQ("SPARSE_G", UNITTEST::TestSparseEnum_Name(UNITTEST::SPARSE_G)); -} - -TEST(GENERATED_ENUM_TEST_NAME, Parse) { - UNITTEST::TestEnumWithDupValue dup_value = UNITTEST::FOO1; - EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO1", &dup_value)); - EXPECT_EQ(UNITTEST::FOO1, dup_value); - EXPECT_TRUE(UNITTEST::TestEnumWithDupValue_Parse("FOO2", &dup_value)); - EXPECT_EQ(UNITTEST::FOO2, dup_value); - EXPECT_FALSE(UNITTEST::TestEnumWithDupValue_Parse("FOO", &dup_value)); -} - -TEST(GENERATED_ENUM_TEST_NAME, GetEnumDescriptor) { - EXPECT_EQ(UNITTEST::TestAllTypes::NestedEnum_descriptor(), - GetEnumDescriptor()); - EXPECT_EQ(UNITTEST::ForeignEnum_descriptor(), - GetEnumDescriptor()); - EXPECT_EQ(UNITTEST::TestEnumWithDupValue_descriptor(), - GetEnumDescriptor()); - EXPECT_EQ(UNITTEST::TestSparseEnum_descriptor(), - GetEnumDescriptor()); -} - -enum NonProtoEnum { - kFoo = 1, -}; - -TEST(GENERATED_ENUM_TEST_NAME, IsProtoEnumTypeTrait) { - EXPECT_TRUE(is_proto_enum::value); - EXPECT_TRUE(is_proto_enum::value); - EXPECT_TRUE(is_proto_enum::value); - EXPECT_TRUE(is_proto_enum::value); - - EXPECT_FALSE(is_proto_enum::value); - EXPECT_FALSE(is_proto_enum::value); -} - -#endif // PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - -// Support code for testing services. -class GENERATED_SERVICE_TEST_NAME : public testing::Test { - protected: - class MockTestService : public UNITTEST::TestService { - public: - MockTestService() - : called_(false), - method_(""), - controller_(NULL), - request_(NULL), - response_(NULL), - done_(NULL) {} - - ~MockTestService() {} - - void Reset() { called_ = false; } - - // implements TestService ---------------------------------------- - - void Foo(RpcController* controller, - const UNITTEST::FooRequest* request, - UNITTEST::FooResponse* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = "Foo"; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - void Bar(RpcController* controller, - const UNITTEST::BarRequest* request, - UNITTEST::BarResponse* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = "Bar"; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - // --------------------------------------------------------------- - - bool called_; - string method_; - RpcController* controller_; - const Message* request_; - Message* response_; - Closure* done_; - }; - - class MockRpcChannel : public RpcChannel { - public: - MockRpcChannel() - : called_(false), - method_(NULL), - controller_(NULL), - request_(NULL), - response_(NULL), - done_(NULL), - destroyed_(NULL) {} - - ~MockRpcChannel() { - if (destroyed_ != NULL) *destroyed_ = true; - } - - void Reset() { called_ = false; } - - // implements TestService ---------------------------------------- - - void CallMethod(const MethodDescriptor* method, - RpcController* controller, - const Message* request, - Message* response, - Closure* done) { - ASSERT_FALSE(called_); - called_ = true; - method_ = method; - controller_ = controller; - request_ = request; - response_ = response; - done_ = done; - } - - // --------------------------------------------------------------- - - bool called_; - const MethodDescriptor* method_; - RpcController* controller_; - const Message* request_; - Message* response_; - Closure* done_; - bool* destroyed_; - }; - - class MockController : public RpcController { - public: - void Reset() { - ADD_FAILURE() << "Reset() not expected during this test."; - } - bool Failed() const { - ADD_FAILURE() << "Failed() not expected during this test."; - return false; - } - string ErrorText() const { - ADD_FAILURE() << "ErrorText() not expected during this test."; - return ""; - } - void StartCancel() { - ADD_FAILURE() << "StartCancel() not expected during this test."; - } - void SetFailed(const string& reason) { - ADD_FAILURE() << "SetFailed() not expected during this test."; - } - bool IsCanceled() const { - ADD_FAILURE() << "IsCanceled() not expected during this test."; - return false; - } - void NotifyOnCancel(Closure* callback) { - ADD_FAILURE() << "NotifyOnCancel() not expected during this test."; - } - }; - - GENERATED_SERVICE_TEST_NAME() - : descriptor_(UNITTEST::TestService::descriptor()), - foo_(descriptor_->FindMethodByName("Foo")), - bar_(descriptor_->FindMethodByName("Bar")), - stub_(&mock_channel_), - done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {} - - virtual void SetUp() { - ASSERT_TRUE(foo_ != NULL); - ASSERT_TRUE(bar_ != NULL); - } - - const ServiceDescriptor* descriptor_; - const MethodDescriptor* foo_; - const MethodDescriptor* bar_; - - MockTestService mock_service_; - MockController mock_controller_; - - MockRpcChannel mock_channel_; - UNITTEST::TestService::Stub stub_; - - // Just so we don't have to re-define these with every test. - UNITTEST::FooRequest foo_request_; - UNITTEST::FooResponse foo_response_; - UNITTEST::BarRequest bar_request_; - UNITTEST::BarResponse bar_response_; - std::unique_ptr done_; -}; - -TEST_F(GENERATED_SERVICE_TEST_NAME, GetDescriptor) { - // Test that GetDescriptor() works. - - EXPECT_EQ(descriptor_, mock_service_.GetDescriptor()); -} - -TEST_F(GENERATED_SERVICE_TEST_NAME, GetChannel) { - EXPECT_EQ(&mock_channel_, stub_.channel()); -} - -TEST_F(GENERATED_SERVICE_TEST_NAME, OwnsChannel) { - MockRpcChannel* channel = new MockRpcChannel; - bool destroyed = false; - channel->destroyed_ = &destroyed; - - { - UNITTEST::TestService::Stub owning_stub(channel, - Service::STUB_OWNS_CHANNEL); - EXPECT_FALSE(destroyed); - } - - EXPECT_TRUE(destroyed); -} - -TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethod) { - // Test that CallMethod() works. - - // Call Foo() via CallMethod(). - mock_service_.CallMethod(foo_, &mock_controller_, - &foo_request_, &foo_response_, done_.get()); - - ASSERT_TRUE(mock_service_.called_); - - EXPECT_EQ("Foo" , mock_service_.method_ ); - EXPECT_EQ(&mock_controller_, mock_service_.controller_); - EXPECT_EQ(&foo_request_ , mock_service_.request_ ); - EXPECT_EQ(&foo_response_ , mock_service_.response_ ); - EXPECT_EQ(done_.get() , mock_service_.done_ ); - - // Try again, but call Bar() instead. - mock_service_.Reset(); - mock_service_.CallMethod(bar_, &mock_controller_, - &bar_request_, &bar_response_, done_.get()); - - ASSERT_TRUE(mock_service_.called_); - EXPECT_EQ("Bar", mock_service_.method_); -} - -TEST_F(GENERATED_SERVICE_TEST_NAME, CallMethodTypeFailure) { - // Verify death if we call Foo() with Bar's message types. - -#ifdef PROTOBUF_HAS_DEATH_TEST // death tests do not work on Windows yet - EXPECT_DEBUG_DEATH( - mock_service_.CallMethod(foo_, &mock_controller_, - &foo_request_, &bar_response_, done_.get()), - "dynamic_cast"); - - mock_service_.Reset(); - EXPECT_DEBUG_DEATH( - mock_service_.CallMethod(foo_, &mock_controller_, - &bar_request_, &foo_response_, done_.get()), - "dynamic_cast"); -#endif // PROTOBUF_HAS_DEATH_TEST -} - -TEST_F(GENERATED_SERVICE_TEST_NAME, GetPrototypes) { - // Test Get{Request,Response}Prototype() methods. - - EXPECT_EQ(&UNITTEST::FooRequest::default_instance(), - &mock_service_.GetRequestPrototype(foo_)); - EXPECT_EQ(&UNITTEST::BarRequest::default_instance(), - &mock_service_.GetRequestPrototype(bar_)); - - EXPECT_EQ(&UNITTEST::FooResponse::default_instance(), - &mock_service_.GetResponsePrototype(foo_)); - EXPECT_EQ(&UNITTEST::BarResponse::default_instance(), - &mock_service_.GetResponsePrototype(bar_)); -} - -TEST_F(GENERATED_SERVICE_TEST_NAME, Stub) { - // Test that the stub class works. - - // Call Foo() via the stub. - stub_.Foo(&mock_controller_, &foo_request_, &foo_response_, done_.get()); - - ASSERT_TRUE(mock_channel_.called_); - - EXPECT_EQ(foo_ , mock_channel_.method_ ); - EXPECT_EQ(&mock_controller_, mock_channel_.controller_); - EXPECT_EQ(&foo_request_ , mock_channel_.request_ ); - EXPECT_EQ(&foo_response_ , mock_channel_.response_ ); - EXPECT_EQ(done_.get() , mock_channel_.done_ ); - - // Call Bar() via the stub. - mock_channel_.Reset(); - stub_.Bar(&mock_controller_, &bar_request_, &bar_response_, done_.get()); - - ASSERT_TRUE(mock_channel_.called_); - EXPECT_EQ(bar_, mock_channel_.method_); -} - -TEST_F(GENERATED_SERVICE_TEST_NAME, NotImplemented) { - // Test that failing to implement a method of a service causes it to fail - // with a "not implemented" error message. - - // A service which doesn't implement any methods. - class UnimplementedService : public UNITTEST::TestService { - public: - UnimplementedService() {} - }; - - UnimplementedService unimplemented_service; - - // And a controller which expects to get a "not implemented" error. - class ExpectUnimplementedController : public MockController { - public: - ExpectUnimplementedController() : called_(false) {} - - void SetFailed(const string& reason) { - EXPECT_FALSE(called_); - called_ = true; - EXPECT_EQ("Method Foo() not implemented.", reason); - } - - bool called_; - }; - - ExpectUnimplementedController controller; - - // Call Foo. - unimplemented_service.Foo(&controller, &foo_request_, &foo_response_, - done_.get()); - - EXPECT_TRUE(controller.called_); -} - -// =================================================================== - -class OneofTest : public testing::Test { - protected: - virtual void SetUp() { - } - - void ExpectEnumCasesWork(const UNITTEST::TestOneof2 &message) { - switch (message.foo_case()) { - case UNITTEST::TestOneof2::kFooInt: - EXPECT_TRUE(message.has_foo_int()); - break; - case UNITTEST::TestOneof2::kFooString: - EXPECT_TRUE(message.has_foo_string()); - break; - case UNITTEST::TestOneof2::kFooCord: - EXPECT_TRUE(message.has_foo_cord()); - break; - case UNITTEST::TestOneof2::kFooStringPiece: - EXPECT_TRUE(message.has_foo_string_piece()); - break; - case UNITTEST::TestOneof2::kFooBytes: - EXPECT_TRUE(message.has_foo_bytes()); - break; - case UNITTEST::TestOneof2::kFooEnum: - EXPECT_TRUE(message.has_foo_enum()); - break; - case UNITTEST::TestOneof2::kFooMessage: - EXPECT_TRUE(message.has_foo_message()); - break; - case UNITTEST::TestOneof2::kFoogroup: - EXPECT_TRUE(message.has_foogroup()); - break; - case UNITTEST::TestOneof2::kFooLazyMessage: - EXPECT_TRUE(message.has_foo_lazy_message()); - break; - case UNITTEST::TestOneof2::FOO_NOT_SET: - break; - } - } -}; - -TEST_F(OneofTest, SettingOneFieldClearsOthers) { - UNITTEST::TestOneof2 message; - - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.set_foo_string("foo"); - EXPECT_TRUE(message.has_foo_string()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - - message.set_foo_bytes("qux"); - EXPECT_TRUE(message.has_foo_bytes()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.set_foo_enum(UNITTEST::TestOneof2::FOO); - EXPECT_TRUE(message.has_foo_enum()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.mutable_foo_message()->set_qux_int(234); - EXPECT_TRUE(message.has_foo_message()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - message.mutable_foogroup()->set_a(345); - EXPECT_TRUE(message.has_foogroup()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); - - - // we repeat this because we didn't test if this properly clears other fields - // at the beginning. - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - TestUtil::ExpectAtMostOneFieldSetInOneof(message); -} - -TEST_F(OneofTest, EnumCases) { - UNITTEST::TestOneof2 message; - - message.set_foo_int(123); - ExpectEnumCasesWork(message); - message.set_foo_string("foo"); - ExpectEnumCasesWork(message); - message.set_foo_bytes("qux"); - ExpectEnumCasesWork(message); - message.set_foo_enum(UNITTEST::TestOneof2::FOO); - ExpectEnumCasesWork(message); - message.mutable_foo_message()->set_qux_int(234); - ExpectEnumCasesWork(message); - message.mutable_foogroup()->set_a(345); - ExpectEnumCasesWork(message); -} - -TEST_F(OneofTest, PrimitiveType) { - UNITTEST::TestOneof2 message; - // Unset field returns default value - EXPECT_EQ(message.foo_int(), 0); - - message.set_foo_int(123); - EXPECT_TRUE(message.has_foo_int()); - EXPECT_EQ(message.foo_int(), 123); - message.clear_foo_int(); - EXPECT_FALSE(message.has_foo_int()); -} - -TEST_F(OneofTest, EnumType) { - UNITTEST::TestOneof2 message; - // Unset field returns default value - EXPECT_EQ(message.foo_enum(), 1); - - message.set_foo_enum(UNITTEST::TestOneof2::FOO); - EXPECT_TRUE(message.has_foo_enum()); - EXPECT_EQ(message.foo_enum(), UNITTEST::TestOneof2::FOO); - message.clear_foo_enum(); - EXPECT_FALSE(message.has_foo_enum()); -} - -TEST_F(OneofTest, SetString) { - // Check that setting a string field in various ways works - UNITTEST::TestOneof2 message; - - // Unset field returns default value - EXPECT_EQ(message.foo_string(), ""); - - message.set_foo_string("foo"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "foo"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string(string("bar")); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "bar"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - - message.set_foo_string("qux", 3); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "qux"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.mutable_foo_string()->assign("quux"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "quux"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string("corge"); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "corge"); - message.clear_foo_string(); - EXPECT_FALSE(message.has_foo_string()); -} - -TEST_F(OneofTest, ReleaseString) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - UNITTEST::TestOneof2 message; - - EXPECT_EQ(NULL, message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); - - message.set_foo_string("blah"); - EXPECT_TRUE(message.has_foo_string()); - std::unique_ptr str(message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); - ASSERT_TRUE(str != NULL); - EXPECT_EQ("blah", *str); - - EXPECT_EQ(NULL, message.release_foo_string()); - EXPECT_FALSE(message.has_foo_string()); -} - -TEST_F(OneofTest, SetAllocatedString) { - // Check that set_allocated_foo() works for strings. - UNITTEST::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_string()); - const string kHello("hello"); - message.set_foo_string(kHello); - EXPECT_TRUE(message.has_foo_string()); - - message.set_allocated_foo_string(NULL); - EXPECT_FALSE(message.has_foo_string()); - EXPECT_EQ("", message.foo_string()); - - message.set_allocated_foo_string(new string(kHello)); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(kHello, message.foo_string()); -} - - -TEST_F(OneofTest, SetMessage) { - // Check that setting a message field works - UNITTEST::TestOneof2 message; - - // Unset field returns default instance - EXPECT_EQ(&message.foo_message(), - &UNITTEST::TestOneof2_NestedMessage::default_instance()); - EXPECT_EQ(message.foo_message().qux_int(), 0); - - message.mutable_foo_message()->set_qux_int(234); - EXPECT_TRUE(message.has_foo_message()); - EXPECT_EQ(message.foo_message().qux_int(), 234); - message.clear_foo_message(); - EXPECT_FALSE(message.has_foo_message()); -} - -TEST_F(OneofTest, ReleaseMessage) { - // Check that release_foo() starts out NULL, and gives us a value - // that we can delete after it's been set. - UNITTEST::TestOneof2 message; - - EXPECT_EQ(NULL, message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); - - message.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message.has_foo_message()); - std::unique_ptr mes( - message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); - ASSERT_TRUE(mes != NULL); - EXPECT_EQ(1, mes->qux_int()); - - EXPECT_EQ(NULL, message.release_foo_message()); - EXPECT_FALSE(message.has_foo_message()); -} - -TEST_F(OneofTest, SetAllocatedMessage) { - // Check that set_allocated_foo() works for messages. - UNITTEST::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_message()); - - message.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message.has_foo_message()); - - message.set_allocated_foo_message(NULL); - EXPECT_FALSE(message.has_foo_message()); - EXPECT_EQ(&message.foo_message(), - &UNITTEST::TestOneof2_NestedMessage::default_instance()); - - message.mutable_foo_message()->set_qux_int(1); - UNITTEST::TestOneof2_NestedMessage* mes = message.release_foo_message(); - ASSERT_TRUE(mes != NULL); - EXPECT_FALSE(message.has_foo_message()); - - message.set_allocated_foo_message(mes); - EXPECT_TRUE(message.has_foo_message()); - EXPECT_EQ(1, message.foo_message().qux_int()); -} - - -TEST_F(OneofTest, Clear) { - UNITTEST::TestOneof2 message; - - message.set_foo_int(1); - EXPECT_TRUE(message.has_foo_int()); - message.clear_foo_int(); - EXPECT_FALSE(message.has_foo_int()); -} - -TEST_F(OneofTest, Defaults) { - UNITTEST::TestOneof2 message; - - EXPECT_FALSE(message.has_foo_int()); - EXPECT_EQ(message.foo_int(), 0); - - EXPECT_FALSE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), ""); - - - EXPECT_FALSE(message.has_foo_bytes()); - EXPECT_EQ(message.foo_bytes(), ""); - - EXPECT_FALSE(message.has_foo_enum()); - EXPECT_EQ(message.foo_enum(), 1); - - EXPECT_FALSE(message.has_foo_message()); - EXPECT_EQ(message.foo_message().qux_int(), 0); - - EXPECT_FALSE(message.has_foogroup()); - EXPECT_EQ(message.foogroup().a(), 0); - - - EXPECT_FALSE(message.has_bar_int()); - EXPECT_EQ(message.bar_int(), 5); - - EXPECT_FALSE(message.has_bar_string()); - EXPECT_EQ(message.bar_string(), "STRING"); - - - EXPECT_FALSE(message.has_bar_bytes()); - EXPECT_EQ(message.bar_bytes(), "BYTES"); - - EXPECT_FALSE(message.has_bar_enum()); - EXPECT_EQ(message.bar_enum(), 2); -} - -TEST_F(OneofTest, SwapWithEmpty) { - UNITTEST::TestOneof2 message1, message2; - message1.set_foo_string("FOO"); - EXPECT_TRUE(message1.has_foo_string()); - message1.Swap(&message2); - EXPECT_FALSE(message1.has_foo_string()); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "FOO"); -} - -TEST_F(OneofTest, SwapWithSelf) { - UNITTEST::TestOneof2 message; - message.set_foo_string("FOO"); - EXPECT_TRUE(message.has_foo_string()); - message.Swap(&message); - EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "FOO"); -} - -TEST_F(OneofTest, SwapBothHasFields) { - UNITTEST::TestOneof2 message1, message2; - - message1.set_foo_string("FOO"); - EXPECT_TRUE(message1.has_foo_string()); - message2.mutable_foo_message()->set_qux_int(1); - EXPECT_TRUE(message2.has_foo_message()); - - message1.Swap(&message2); - EXPECT_FALSE(message1.has_foo_string()); - EXPECT_FALSE(message2.has_foo_message()); - EXPECT_TRUE(message1.has_foo_message()); - EXPECT_EQ(message1.foo_message().qux_int(), 1); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "FOO"); -} - -TEST_F(OneofTest, CopyConstructor) { - UNITTEST::TestOneof2 message1; - message1.set_foo_bytes("FOO"); - - UNITTEST::TestOneof2 message2(message1); - EXPECT_TRUE(message2.has_foo_bytes()); - EXPECT_EQ(message2.foo_bytes(), "FOO"); -} - -TEST_F(OneofTest, CopyFrom) { - UNITTEST::TestOneof2 message1, message2; - message1.set_foo_enum(UNITTEST::TestOneof2::BAR); - EXPECT_TRUE(message1.has_foo_enum()); - - message2.CopyFrom(message1); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR); - - // Copying from self should be a no-op. - message2.CopyFrom(message2); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::BAR); -} - -TEST_F(OneofTest, CopyAssignmentOperator) { - UNITTEST::TestOneof2 message1; - message1.mutable_foo_message()->set_qux_int(123); - EXPECT_TRUE(message1.has_foo_message()); - - UNITTEST::TestOneof2 message2; - message2 = message1; - EXPECT_EQ(message2.foo_message().qux_int(), 123); - - // Make sure that self-assignment does something sane. - message2 = message2; - EXPECT_EQ(message2.foo_message().qux_int(), 123); -} - -TEST_F(OneofTest, UpcastCopyFrom) { - // Test the CopyFrom method that takes in the generic const Message& - // parameter. - UNITTEST::TestOneof2 message1, message2; - message1.mutable_foogroup()->set_a(123); - EXPECT_TRUE(message1.has_foogroup()); - - const Message* source = implicit_cast(&message1); - message2.CopyFrom(*source); - - EXPECT_TRUE(message2.has_foogroup()); - EXPECT_EQ(message2.foogroup().a(), 123); -} - -// Test the generated SerializeWithCachedSizesToArray(), -// This indirectly tests MergePartialFromCodedStream() -// We have to test each field type separately because we cannot set them at the -// same time -TEST_F(OneofTest, SerializationToArray) { - // Primitive type - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_int(123); - int size = message1.ByteSizeLong(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_int(), 123); - } - - // String - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_string("foo"); - int size = message1.ByteSizeLong(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_string(), "foo"); - } - - - // Bytes - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_bytes("qux"); - int size = message1.ByteSizeLong(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_bytes(), "qux"); - } - - // Enum - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_enum(UNITTEST::TestOneof2::FOO); - int size = message1.ByteSizeLong(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); - } - - // Message - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.mutable_foo_message()->set_qux_int(234); - int size = message1.ByteSizeLong(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - } - - // Group - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.mutable_foogroup()->set_a(345); - int size = message1.ByteSizeLong(); - data.resize(size); - uint8* start = reinterpret_cast(string_as_array(&data)); - uint8* end = message1.SerializeWithCachedSizesToArray(start); - EXPECT_EQ(size, end - start); - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foogroup().a(), 345); - } - -} - -// Test the generated SerializeWithCachedSizes() by forcing the buffer to write -// one byte at a time. -// This indirectly tests MergePartialFromCodedStream() -// We have to test each field type separately because we cannot set them at the -// same time -TEST_F(OneofTest, SerializationToStream) { - // Primitive type - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_int(123); - int size = message1.ByteSizeLong(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_int(), 123); - } - - // String - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_string("foo"); - int size = message1.ByteSizeLong(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_string(), "foo"); - } - - - // Bytes - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_bytes("qux"); - int size = message1.ByteSizeLong(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_bytes(), "qux"); - } - - // Enum - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.set_foo_enum(UNITTEST::TestOneof2::FOO); - int size = message1.ByteSizeLong(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); - } - - // Message - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.mutable_foo_message()->set_qux_int(234); - int size = message1.ByteSizeLong(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - } - - // Group - { - UNITTEST::TestOneof2 message1, message2; - string data; - message1.mutable_foogroup()->set_a(345); - int size = message1.ByteSizeLong(); - data.resize(size); - - { - // Allow the output stream to buffer only one byte at a time. - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message1.SerializeWithCachedSizes(&output_stream); - EXPECT_FALSE(output_stream.HadError()); - EXPECT_EQ(size, output_stream.ByteCount()); - } - - EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foogroup().a(), 345); - } - -} - -TEST_F(OneofTest, MergeFrom) { - UNITTEST::TestOneof2 message1, message2; - - message1.set_foo_int(123); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_int()); - EXPECT_EQ(message2.foo_int(), 123); - - message1.set_foo_string("foo"); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_string()); - EXPECT_EQ(message2.foo_string(), "foo"); - - - message1.set_foo_bytes("qux"); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_bytes()); - EXPECT_EQ(message2.foo_bytes(), "qux"); - - message1.set_foo_enum(UNITTEST::TestOneof2::FOO); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_enum()); - EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); - - message1.mutable_foo_message()->set_qux_int(234); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foo_message()); - EXPECT_EQ(message2.foo_message().qux_int(), 234); - - message1.mutable_foogroup()->set_a(345); - message2.MergeFrom(message1); - TestUtil::ExpectAtMostOneFieldSetInOneof(message2); - EXPECT_TRUE(message2.has_foogroup()); - EXPECT_EQ(message2.foogroup().a(), 345); - -} - -TEST(HELPERS_TEST_NAME, TestSCC) { - UNITTEST::TestMutualRecursionA a; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(a.GetDescriptor()); - std::vector names; - for (int i = 0; i < scc->descriptors.size(); i++) { - names.push_back(scc->descriptors[i]->full_name()); - } - string package = a.GetDescriptor()->file()->package(); - ASSERT_EQ(names.size(), 4); - std::sort(names.begin(), names.end()); - EXPECT_EQ(names[0], package + ".TestMutualRecursionA"); - EXPECT_EQ(names[1], package + ".TestMutualRecursionA.SubGroup"); - EXPECT_EQ(names[2], package + ".TestMutualRecursionA.SubMessage"); - EXPECT_EQ(names[3], package + ".TestMutualRecursionB"); - - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, true); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, true); // TestAllTypes - EXPECT_EQ(result.contains_extension, false); // TestAllTypes -} - -TEST(HELPERS_TEST_NAME, TestSCCAnalysis) { - { - UNITTEST::TestRecursiveMessage msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, true); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, false); - } - { - UNITTEST::TestAllExtensions msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, false); - EXPECT_EQ(result.contains_required, false); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, true); - } - { - UNITTEST::TestRequired msg; - SCCAnalyzer scc_analyzer((Options())); - const SCC* scc = scc_analyzer.GetSCC(msg.GetDescriptor()); - MessageAnalysis result = scc_analyzer.GetSCCAnalysis(scc); - EXPECT_EQ(result.is_recursive, false); - EXPECT_EQ(result.contains_required, true); - EXPECT_EQ(result.contains_cord, false); - EXPECT_EQ(result.contains_extension, false); - } -} - -} // namespace cpp_unittest -} // namespace cpp -} // namespace compiler - -namespace no_generic_services_test { - // Verify that no class called "TestService" was defined in - // unittest_no_generic_services.pb.h by defining a different type by the same - // name. If such a service was generated, this will not compile. - struct TestService { - int i; - }; -} - -namespace compiler { -namespace cpp { -namespace cpp_unittest { - -TEST_F(GENERATED_SERVICE_TEST_NAME, NoGenericServices) { - // Verify that non-services in unittest_no_generic_services.proto were - // generated. - no_generic_services_test::TestMessage message; - message.set_a(1); - message.SetExtension(no_generic_services_test::test_extension, 123); - no_generic_services_test::TestEnum e = no_generic_services_test::FOO; - EXPECT_EQ(e, 1); - - // Verify that a ServiceDescriptor is generated for the service even if the - // class itself is not. - const FileDescriptor* file = - no_generic_services_test::TestMessage::descriptor()->file(); - - ASSERT_EQ(1, file->service_count()); - EXPECT_EQ("TestService", file->service(0)->name()); - ASSERT_EQ(1, file->service(0)->method_count()); - EXPECT_EQ("Foo", file->service(0)->method(0)->name()); -} - -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - -// =================================================================== - -// This test must run last. It verifies that descriptors were or were not -// initialized depending on whether PROTOBUF_TEST_NO_DESCRIPTORS was defined. -// When this is defined, we skip all tests which are expected to trigger -// descriptor initialization. This verifies that everything else still works -// if descriptors are not initialized. -TEST(DESCRIPTOR_INIT_TEST_NAME, Initialized) { -#ifdef PROTOBUF_TEST_NO_DESCRIPTORS - bool should_have_descriptors = false; -#else - bool should_have_descriptors = true; -#endif - - EXPECT_EQ(should_have_descriptors, - DescriptorPool::generated_pool()->InternalIsFileLoaded( - UNITTEST_PROTO_PATH)); -} - -} // namespace cpp_unittest - -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/cpp/metadata_test.cc b/windows/include/google/protobuf/compiler/cpp/metadata_test.cc deleted file mode 100644 index 2ad4edd24..000000000 --- a/windows/include/google/protobuf/compiler/cpp/metadata_test.cc +++ /dev/null @@ -1,162 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace atu = ::google::protobuf::compiler::annotation_test_util; - -namespace protobuf { -namespace compiler { -namespace cpp { -namespace { - -class CppMetadataTest : public ::testing::Test { - public: - // Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output - // code from the previously added file with name `filename`. Returns true on - // success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to - // pb_h and pb_h_info respecfively); similarly for proto_h and proto_h_info. - bool CaptureMetadata(const string& filename, FileDescriptorProto* file, - string* pb_h, GeneratedCodeInfo* pb_h_info, - string* proto_h, GeneratedCodeInfo* proto_h_info, - string* pb_cc) { - google::protobuf::compiler::CommandLineInterface cli; - CppGenerator cpp_generator; - cli.RegisterGenerator("--cpp_out", &cpp_generator, ""); - string cpp_out = - "--cpp_out=annotate_headers=true," - "annotation_pragma_name=pragma_name," - "annotation_guard_name=guard_name:" + - TestTempDir(); - - const bool result = - atu::RunProtoCompiler(filename, cpp_out, &cli, file); - - if (!result) { - return result; - } - - string output_base = TestTempDir() + "/" + StripProto(filename); - - if (pb_cc != NULL) { - GOOGLE_CHECK_OK( - File::GetContents(output_base + ".pb.cc", pb_cc, true)); - } - - if (pb_h != NULL && pb_h_info != NULL) { - GOOGLE_CHECK_OK( - File::GetContents(output_base + ".pb.h", pb_h, true)); - if (!atu::DecodeMetadata(output_base + ".pb.h.meta", pb_h_info)) { - return false; - } - } - - if (proto_h != NULL && proto_h_info != NULL) { - GOOGLE_CHECK_OK(File::GetContents(output_base + ".proto.h", proto_h, - true)); - if (!atu::DecodeMetadata(output_base + ".proto.h.meta", proto_h_info)) { - return false; - } - } - - return true; - } -}; - -const char kSmallTestFile[] = - "syntax = \"proto2\";\n" - "package foo;\n" - "enum Enum { VALUE = 0; }\n" - "message Message { }\n"; - -TEST_F(CppMetadataTest, CapturesEnumNames) { - FileDescriptorProto file; - GeneratedCodeInfo info; - string pb_h; - atu::AddFile("test.proto", kSmallTestFile); - EXPECT_TRUE( - CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); - EXPECT_EQ("Enum", file.enum_type(0).name()); - std::vector enum_path; - enum_path.push_back(FileDescriptorProto::kEnumTypeFieldNumber); - enum_path.push_back(0); - const GeneratedCodeInfo::Annotation* enum_annotation = - atu::FindAnnotationOnPath(info, "test.proto", enum_path); - EXPECT_TRUE(NULL != enum_annotation); - EXPECT_TRUE(atu::AnnotationMatchesSubstring(pb_h, enum_annotation, "Enum")); -} - -TEST_F(CppMetadataTest, AddsPragma) { - FileDescriptorProto file; - GeneratedCodeInfo info; - string pb_h; - atu::AddFile("test.proto", kSmallTestFile); - EXPECT_TRUE( - CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); - EXPECT_TRUE(pb_h.find("#ifdef guard_name") != string::npos); - EXPECT_TRUE(pb_h.find("#pragma pragma_name \"test.pb.h.meta\"") != - string::npos); -} - -TEST_F(CppMetadataTest, CapturesMessageNames) { - FileDescriptorProto file; - GeneratedCodeInfo info; - string pb_h; - atu::AddFile("test.proto", kSmallTestFile); - EXPECT_TRUE( - CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); - EXPECT_EQ("Message", file.message_type(0).name()); - std::vector message_path; - message_path.push_back(FileDescriptorProto::kMessageTypeFieldNumber); - message_path.push_back(0); - const GeneratedCodeInfo::Annotation* message_annotation = - atu::FindAnnotationOnPath(info, "test.proto", message_path); - EXPECT_TRUE(NULL != message_annotation); - EXPECT_TRUE( - atu::AnnotationMatchesSubstring(pb_h, message_annotation, "Message")); -} - -} // namespace -} // namespace cpp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc b/windows/include/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc deleted file mode 100644 index 8c38e52fe..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc +++ /dev/null @@ -1,200 +0,0 @@ -// 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. - -// This test insures that -// csharp/src/Google.Protobuf/Reflection/Descriptor.cs match exactly -// what would be generated by the protocol compiler. The file is not -// generated automatically at build time. -// -// If this test fails, run the script -// "generate_descriptor_proto.sh" and add the changed files under -// csharp/src/ to your changelist. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -namespace { - -class MockErrorCollector : public MultiFileErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - - // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", - filename, line, column, message); - } -}; - -class MockGeneratorContext : public GeneratorContext { - public: - MockGeneratorContext() {} - ~MockGeneratorContext() { - STLDeleteValues(&files_); - } - - void ExpectFileMatches(const string& virtual_filename, - const string& physical_filename) { - string* expected_contents = FindPtrOrNull(files_, virtual_filename); - ASSERT_TRUE(expected_contents != NULL) - << "Generator failed to generate file: " << virtual_filename; - - string actual_contents; - GOOGLE_CHECK_OK( - File::GetContents(TestSourceDir() + "/" + physical_filename, - &actual_contents, true)) - << "Unable to get " << physical_filename; - EXPECT_TRUE(actual_contents == *expected_contents) - << physical_filename << " needs to be regenerated. Please run " - "generate_descriptor_proto.sh. Then add this file " - "to your CL."; - } - - // implements GeneratorContext -------------------------------------- - - virtual io::ZeroCopyOutputStream* Open(const string& filename) { - string** map_slot = &files_[filename]; - delete *map_slot; - *map_slot = new string; - - return new io::StringOutputStream(*map_slot); - } - - private: - std::map files_; -}; - -class GenerateAndTest { - public: - GenerateAndTest() {} - void Run(const FileDescriptor* proto_file, string file1, string file2) { - ASSERT_TRUE(proto_file != NULL) << TestSourceDir(); - ASSERT_TRUE(generator_.Generate(proto_file, parameter_, - &context_, &error_)); - context_.ExpectFileMatches(file1, file2); - } - void SetParameter(string parameter) { - parameter_ = parameter; - } - - private: - Generator generator_; - MockGeneratorContext context_; - string error_; - string parameter_; -}; - -TEST(CsharpBootstrapTest, GeneratedCsharpDescriptorMatches) { - // Skip this whole test if the csharp directory doesn't exist (i.e., a C++11 - // only distribution). - string descriptor_file_name = - "../csharp/src/Google.Protobuf/Reflection/Descriptor.cs"; - if (!File::Exists(TestSourceDir() + "/" + descriptor_file_name)) { - return; - } - - MockErrorCollector error_collector; - DiskSourceTree source_tree; - Importer importer(&source_tree, &error_collector); - GenerateAndTest generate_test; - - generate_test.SetParameter("base_namespace=Google.Protobuf"); - source_tree.MapPath("", TestSourceDir()); - generate_test.Run(importer.Import("google/protobuf/descriptor.proto"), - "Reflection/Descriptor.cs", - "../csharp/src/Google.Protobuf/Reflection/Descriptor.cs"); - generate_test.Run(importer.Import("google/protobuf/any.proto"), - "WellKnownTypes/Any.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/Any.cs"); - generate_test.Run(importer.Import("google/protobuf/api.proto"), - "WellKnownTypes/Api.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/Api.cs"); - generate_test.Run(importer.Import("google/protobuf/duration.proto"), - "WellKnownTypes/Duration.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs"); - generate_test.Run(importer.Import("google/protobuf/empty.proto"), - "WellKnownTypes/Empty.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs"); - generate_test.Run(importer.Import("google/protobuf/field_mask.proto"), - "WellKnownTypes/FieldMask.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs"); - generate_test.Run(importer.Import("google/protobuf/source_context.proto"), - "WellKnownTypes/SourceContext.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs"); - generate_test.Run(importer.Import("google/protobuf/struct.proto"), - "WellKnownTypes/Struct.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs"); - generate_test.Run(importer.Import("google/protobuf/timestamp.proto"), - "WellKnownTypes/Timestamp.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs"); - generate_test.Run(importer.Import("google/protobuf/type.proto"), - "WellKnownTypes/Type.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/Type.cs"); - generate_test.Run(importer.Import("google/protobuf/wrappers.proto"), - "WellKnownTypes/Wrappers.cs", - "../csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs"); - - generate_test.SetParameter(""); - source_tree.MapPath("", TestSourceDir() + "/../conformance"); - generate_test.Run(importer.Import("conformance.proto"), - "Conformance.cs", - "../csharp/src/Google.Protobuf.Conformance/Conformance.cs"); - - EXPECT_EQ("", error_collector.text_); -} - -} // namespace - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_doc_comment.cc b/windows/include/google/protobuf/compiler/csharp/csharp_doc_comment.cc deleted file mode 100644 index a21dc0a49..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_doc_comment.cc +++ /dev/null @@ -1,114 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -// Functions to create C# XML documentation comments. -// Currently this only includes documentation comments containing text specified as comments -// in the .proto file; documentation comments generated just from field/message/enum/proto names -// is inlined in the relevant code. If more control is required, that code can be moved here. - -void WriteDocCommentBodyImpl(io::Printer* printer, SourceLocation location) { - string comments = location.leading_comments.empty() ? - location.trailing_comments : location.leading_comments; - if (comments.empty()) { - return; - } - // XML escaping... no need for apostrophes etc as the whole text is going to be a child - // node of a summary element, not part of an attribute. - comments = StringReplace(comments, "&", "&", true); - comments = StringReplace(comments, "<", "<", true); - std::vector lines = Split(comments, "\n", false /* skip_empty */); - // TODO: We really should work out which part to put in the summary and which to put in the remarks... - // but that needs to be part of a bigger effort to understand the markdown better anyway. - printer->Print("/// \n"); - bool last_was_empty = false; - // We squash multiple blank lines down to one, and remove any trailing blank lines. We need - // to preserve the blank lines themselves, as this is relevant in the markdown. - // Note that we can't remove leading or trailing whitespace as *that's* relevant in markdown too. - // (We don't skip "just whitespace" lines, either.) - for (std::vector::iterator it = lines.begin(); it != lines.end(); ++it) { - string line = *it; - if (line.empty()) { - last_was_empty = true; - } else { - if (last_was_empty) { - printer->Print("///\n"); - } - last_was_empty = false; - printer->Print("///$line$\n", "line", *it); - } - } - printer->Print("/// \n"); -} - -template -static void WriteDocCommentBody( - io::Printer* printer, const DescriptorType* descriptor) { - SourceLocation location; - if (descriptor->GetSourceLocation(&location)) { - WriteDocCommentBodyImpl(printer, location); - } -} - -void WriteMessageDocComment(io::Printer* printer, const Descriptor* message) { - WriteDocCommentBody(printer, message); -} - -void WritePropertyDocComment(io::Printer* printer, const FieldDescriptor* field) { - WriteDocCommentBody(printer, field); -} - -void WriteEnumDocComment(io::Printer* printer, const EnumDescriptor* enumDescriptor) { - WriteDocCommentBody(printer, enumDescriptor); -} -void WriteEnumValueDocComment(io::Printer* printer, const EnumValueDescriptor* value) { - WriteDocCommentBody(printer, value); -} - -void WriteMethodDocComment(io::Printer* printer, const MethodDescriptor* method) { - WriteDocCommentBody(printer, method); -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_enum.cc b/windows/include/google/protobuf/compiler/csharp/csharp_enum.cc deleted file mode 100644 index 32c719907..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_enum.cc +++ /dev/null @@ -1,99 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, const Options* options) : - SourceGeneratorBase(descriptor->file(), options), - descriptor_(descriptor) { -} - -EnumGenerator::~EnumGenerator() { -} - -void EnumGenerator::Generate(io::Printer* printer) { - WriteEnumDocComment(printer, descriptor_); - printer->Print("$access_level$ enum $name$ {\n", - "access_level", class_access_level(), - "name", descriptor_->name()); - printer->Indent(); - std::set used_names; - std::set used_number; - for (int i = 0; i < descriptor_->value_count(); i++) { - WriteEnumValueDocComment(printer, descriptor_->value(i)); - string original_name = descriptor_->value(i)->name(); - string name = GetEnumValueName(descriptor_->name(), descriptor_->value(i)->name()); - // Make sure we don't get any duplicate names due to prefix removal. - while (!used_names.insert(name).second) { - // It's possible we'll end up giving this warning multiple times, but that's better than not at all. - GOOGLE_LOG(WARNING) << "Duplicate enum value " << name << " (originally " << original_name - << ") in " << descriptor_->name() << "; adding underscore to distinguish"; - name += "_"; - } - int number = descriptor_->value(i)->number(); - if (!used_number.insert(number).second) { - printer->Print("[pbr::OriginalName(\"$original_name$\", PreferredAlias = false)] $name$ = $number$,\n", - "original_name", original_name, - "name", name, - "number", SimpleItoa(number)); - } else { - printer->Print("[pbr::OriginalName(\"$original_name$\")] $name$ = $number$,\n", - "original_name", original_name, - "name", name, - "number", SimpleItoa(number)); - } - } - printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_enum.h b/windows/include/google/protobuf/compiler/csharp/csharp_enum.h deleted file mode 100644 index 8925cdf2b..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_enum.h +++ /dev/null @@ -1,63 +0,0 @@ -// 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_CSHARP_ENUM_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_ENUM_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -class EnumGenerator : public SourceGeneratorBase { - public: - EnumGenerator(const EnumDescriptor* descriptor, const Options* options); - ~EnumGenerator(); - - void Generate(io::Printer* printer); - - private: - const EnumDescriptor* descriptor_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_ENUM_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_enum_field.cc b/windows/include/google/protobuf/compiler/csharp/csharp_enum_field.cc deleted file mode 100644 index 9ceffa8ca..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ /dev/null @@ -1,124 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, const Options *options) - : PrimitiveFieldGenerator(descriptor, fieldOrdinal, options) { -} - -EnumFieldGenerator::~EnumFieldGenerator() { -} - -void EnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print(variables_, - "$name$_ = ($type_name$) input.ReadEnum();\n"); -} - -void EnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print(variables_, - "if ($has_property_check$) {\n" - " output.WriteRawTag($tag_bytes$);\n" - " output.WriteEnum((int) $property_name$);\n" - "}\n"); -} - -void EnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " size += $tag_size$ + pb::CodedOutputStream.ComputeEnumSize((int) $property_name$);\n" - "}\n"); -} - -void EnumFieldGenerator::GenerateCodecCode(io::Printer* printer) { - printer->Print( - variables_, - "pb::FieldCodec.ForEnum($tag$, x => (int) x, x => ($type_name$) x)"); -} - -EnumOneofFieldGenerator::EnumOneofFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : PrimitiveOneofFieldGenerator(descriptor, fieldOrdinal, options) { -} - -EnumOneofFieldGenerator::~EnumOneofFieldGenerator() { -} - -void EnumOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print(variables_, "$property_name$ = other.$property_name$;\n"); -} - -void EnumOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { - // TODO(jonskeet): What about if we read the default value? - printer->Print( - variables_, - "$oneof_name$_ = input.ReadEnum();\n" - "$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); -} - -void EnumOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " output.WriteRawTag($tag_bytes$);\n" - " output.WriteEnum((int) $property_name$);\n" - "}\n"); -} - -void EnumOneofFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " size += $tag_size$ + pb::CodedOutputStream.ComputeEnumSize((int) $property_name$);\n" - "}\n"); -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_enum_field.h b/windows/include/google/protobuf/compiler/csharp/csharp_enum_field.h deleted file mode 100644 index 631632bcb..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_enum_field.h +++ /dev/null @@ -1,82 +0,0 @@ -// 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_CSHARP_ENUM_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_ENUM_FIELD_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -class EnumFieldGenerator : public PrimitiveFieldGenerator { - public: - EnumFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~EnumFieldGenerator(); - - virtual void GenerateCodecCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); -}; - -class EnumOneofFieldGenerator : public PrimitiveOneofFieldGenerator { - public: - EnumOneofFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~EnumOneofFieldGenerator(); - - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumOneofFieldGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_ENUM_FIELD_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_field_base.cc b/windows/include/google/protobuf/compiler/csharp/csharp_field_base.cc deleted file mode 100644 index 7e737e47f..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_field_base.cc +++ /dev/null @@ -1,430 +0,0 @@ -// 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. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -void FieldGeneratorBase::SetCommonFieldVariables( - std::map* variables) { - // Note: this will be valid even though the tag emitted for packed and unpacked versions of - // repeated fields varies by wire format. The wire format is encoded in the bottom 3 bits, which - // never effects the tag size. - int tag_size = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); - uint tag = internal::WireFormat::MakeTag(descriptor_); - uint8 tag_array[5]; - io::CodedOutputStream::WriteTagToArray(tag, tag_array); - string tag_bytes = SimpleItoa(tag_array[0]); - for (int i = 1; i < tag_size; i++) { - tag_bytes += ", " + SimpleItoa(tag_array[i]); - } - - (*variables)["access_level"] = "public"; - (*variables)["tag"] = SimpleItoa(tag); - (*variables)["tag_size"] = SimpleItoa(tag_size); - (*variables)["tag_bytes"] = tag_bytes; - - (*variables)["property_name"] = property_name(); - (*variables)["type_name"] = type_name(); - (*variables)["name"] = name(); - (*variables)["descriptor_name"] = descriptor_->name(); - (*variables)["default_value"] = default_value(); - if (has_default_value()) { - (*variables)["name_def_message"] = - (*variables)["name"] + "_ = " + (*variables)["default_value"]; - } else { - (*variables)["name_def_message"] = (*variables)["name"] + "_"; - } - (*variables)["capitalized_type_name"] = capitalized_type_name(); - (*variables)["number"] = number(); - (*variables)["has_property_check"] = - (*variables)["property_name"] + " != " + (*variables)["default_value"]; - (*variables)["other_has_property_check"] = "other." + - (*variables)["property_name"] + " != " + (*variables)["default_value"]; -} - -void FieldGeneratorBase::SetCommonOneofFieldVariables( - std::map* variables) { - (*variables)["oneof_name"] = oneof_name(); - (*variables)["has_property_check"] = - oneof_name() + "Case_ == " + oneof_property_name() + - "OneofCase." + property_name(); - (*variables)["oneof_property_name"] = oneof_property_name(); -} - -FieldGeneratorBase::FieldGeneratorBase(const FieldDescriptor* descriptor, - int fieldOrdinal, const Options* options) - : SourceGeneratorBase(descriptor->file(), options), - descriptor_(descriptor), - fieldOrdinal_(fieldOrdinal) { - SetCommonFieldVariables(&variables_); -} - -FieldGeneratorBase::~FieldGeneratorBase() { -} - -void FieldGeneratorBase::GenerateFreezingCode(io::Printer* printer) { - // No-op: only message fields and repeated fields need - // special handling for freezing, so default to not generating any code. -} - -void FieldGeneratorBase::GenerateCodecCode(io::Printer* printer) { - // No-op: expect this to be overridden by appropriate types. - // Could fail if we get called here though... -} - -void FieldGeneratorBase::AddDeprecatedFlag(io::Printer* printer) { - if (descriptor_->options().deprecated()) { - printer->Print("[global::System.ObsoleteAttribute]\n"); - } else if (descriptor_->type() == FieldDescriptor::TYPE_MESSAGE && - descriptor_->message_type()->options().deprecated()) { - printer->Print("[global::System.ObsoleteAttribute]\n"); - } -} - -void FieldGeneratorBase::AddPublicMemberAttributes(io::Printer* printer) { - AddDeprecatedFlag(printer); - WriteGeneratedCodeAttributes(printer); -} - -std::string FieldGeneratorBase::oneof_property_name() { - return UnderscoresToCamelCase(descriptor_->containing_oneof()->name(), true); -} - -std::string FieldGeneratorBase::oneof_name() { - return UnderscoresToCamelCase(descriptor_->containing_oneof()->name(), false); -} - -std::string FieldGeneratorBase::property_name() { - return GetPropertyName(descriptor_); -} - -std::string FieldGeneratorBase::name() { - return UnderscoresToCamelCase(GetFieldName(descriptor_), false); -} - -std::string FieldGeneratorBase::type_name() { - return type_name(descriptor_); -} - -std::string FieldGeneratorBase::type_name(const FieldDescriptor* descriptor) { - switch (descriptor->type()) { - case FieldDescriptor::TYPE_ENUM: - return GetClassName(descriptor->enum_type()); - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_GROUP: - if (IsWrapperType(descriptor)) { - const FieldDescriptor* wrapped_field = - descriptor->message_type()->field(0); - string wrapped_field_type_name = type_name(wrapped_field); - // String and ByteString go to the same type; other wrapped types - // go to the nullable equivalent. - if (wrapped_field->type() == FieldDescriptor::TYPE_STRING || - wrapped_field->type() == FieldDescriptor::TYPE_BYTES) { - return wrapped_field_type_name; - } else { - return wrapped_field_type_name + "?"; - } - } - return GetClassName(descriptor->message_type()); - case FieldDescriptor::TYPE_DOUBLE: - return "double"; - case FieldDescriptor::TYPE_FLOAT: - return "float"; - case FieldDescriptor::TYPE_INT64: - return "long"; - case FieldDescriptor::TYPE_UINT64: - return "ulong"; - case FieldDescriptor::TYPE_INT32: - return "int"; - case FieldDescriptor::TYPE_FIXED64: - return "ulong"; - case FieldDescriptor::TYPE_FIXED32: - return "uint"; - case FieldDescriptor::TYPE_BOOL: - return "bool"; - case FieldDescriptor::TYPE_STRING: - return "string"; - case FieldDescriptor::TYPE_BYTES: - return "pb::ByteString"; - case FieldDescriptor::TYPE_UINT32: - return "uint"; - case FieldDescriptor::TYPE_SFIXED32: - return "int"; - case FieldDescriptor::TYPE_SFIXED64: - return "long"; - case FieldDescriptor::TYPE_SINT32: - return "int"; - case FieldDescriptor::TYPE_SINT64: - return "long"; - default: - GOOGLE_LOG(FATAL)<< "Unknown field type."; - return ""; - } -} - -bool FieldGeneratorBase::has_default_value() { - switch (descriptor_->type()) { - case FieldDescriptor::TYPE_ENUM: - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_GROUP: - return true; - case FieldDescriptor::TYPE_DOUBLE: - return descriptor_->default_value_double() != 0.0; - case FieldDescriptor::TYPE_FLOAT: - return descriptor_->default_value_float() != 0.0; - case FieldDescriptor::TYPE_INT64: - return descriptor_->default_value_int64() != 0L; - case FieldDescriptor::TYPE_UINT64: - return descriptor_->default_value_uint64() != 0L; - case FieldDescriptor::TYPE_INT32: - return descriptor_->default_value_int32() != 0; - case FieldDescriptor::TYPE_FIXED64: - return descriptor_->default_value_uint64() != 0L; - case FieldDescriptor::TYPE_FIXED32: - return descriptor_->default_value_uint32() != 0; - case FieldDescriptor::TYPE_BOOL: - return descriptor_->default_value_bool(); - case FieldDescriptor::TYPE_STRING: - return true; - case FieldDescriptor::TYPE_BYTES: - return true; - case FieldDescriptor::TYPE_UINT32: - return descriptor_->default_value_uint32() != 0; - case FieldDescriptor::TYPE_SFIXED32: - return descriptor_->default_value_int32() != 0; - case FieldDescriptor::TYPE_SFIXED64: - return descriptor_->default_value_int64() != 0L; - case FieldDescriptor::TYPE_SINT32: - return descriptor_->default_value_int32() != 0; - case FieldDescriptor::TYPE_SINT64: - return descriptor_->default_value_int64() != 0L; - default: - GOOGLE_LOG(FATAL)<< "Unknown field type."; - return true; - } -} - -bool FieldGeneratorBase::is_nullable_type() { - switch (descriptor_->type()) { - case FieldDescriptor::TYPE_ENUM: - case FieldDescriptor::TYPE_DOUBLE: - case FieldDescriptor::TYPE_FLOAT: - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_BOOL: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_SFIXED32: - case FieldDescriptor::TYPE_SFIXED64: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_SINT64: - return false; - - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_BYTES: - return true; - - default: - GOOGLE_LOG(FATAL)<< "Unknown field type."; - return true; - } -} - -bool AllPrintableAscii(const std::string& text) { - for(int i = 0; i < text.size(); i++) { - if (text[i] < 0x20 || text[i] > 0x7e) { - return false; - } - } - return true; -} - -std::string FieldGeneratorBase::GetStringDefaultValueInternal() { - // No other default values needed for proto3... - return "\"\""; -} - -std::string FieldGeneratorBase::GetBytesDefaultValueInternal() { - // No other default values needed for proto3... - return "pb::ByteString.Empty"; -} - -std::string FieldGeneratorBase::default_value() { - return default_value(descriptor_); -} - -std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor) { - switch (descriptor->type()) { - case FieldDescriptor::TYPE_ENUM: - // All proto3 enums have a default value of 0, and there's an implicit conversion from the constant 0 to - // any C# enum. This means we don't need to work out what we actually mapped the enum value name to. - return "0"; - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_GROUP: - if (IsWrapperType(descriptor)) { - const FieldDescriptor* wrapped_field = descriptor->message_type()->field(0); - return default_value(wrapped_field); - } else { - return "null"; - } - case FieldDescriptor::TYPE_DOUBLE: { - double value = descriptor->default_value_double(); - if (value == std::numeric_limits::infinity()) { - return "double.PositiveInfinity"; - } else if (value == -std::numeric_limits::infinity()) { - return "double.NegativeInfinity"; - } else if (MathLimits::IsNaN(value)) { - return "double.NaN"; - } - return SimpleDtoa(value) + "D"; - } - case FieldDescriptor::TYPE_FLOAT: { - float value = descriptor->default_value_float(); - if (value == std::numeric_limits::infinity()) { - return "float.PositiveInfinity"; - } else if (value == -std::numeric_limits::infinity()) { - return "float.NegativeInfinity"; - } else if (MathLimits::IsNaN(value)) { - return "float.NaN"; - } - return SimpleFtoa(value) + "F"; - } - case FieldDescriptor::TYPE_INT64: - return SimpleItoa(descriptor->default_value_int64()) + "L"; - case FieldDescriptor::TYPE_UINT64: - return SimpleItoa(descriptor->default_value_uint64()) + "UL"; - case FieldDescriptor::TYPE_INT32: - return SimpleItoa(descriptor->default_value_int32()); - case FieldDescriptor::TYPE_FIXED64: - return SimpleItoa(descriptor->default_value_uint64()) + "UL"; - case FieldDescriptor::TYPE_FIXED32: - return SimpleItoa(descriptor->default_value_uint32()); - case FieldDescriptor::TYPE_BOOL: - if (descriptor->default_value_bool()) { - return "true"; - } else { - return "false"; - } - case FieldDescriptor::TYPE_STRING: - return GetStringDefaultValueInternal(); - case FieldDescriptor::TYPE_BYTES: - return GetBytesDefaultValueInternal(); - case FieldDescriptor::TYPE_UINT32: - return SimpleItoa(descriptor->default_value_uint32()); - case FieldDescriptor::TYPE_SFIXED32: - return SimpleItoa(descriptor->default_value_int32()); - case FieldDescriptor::TYPE_SFIXED64: - return SimpleItoa(descriptor->default_value_int64()) + "L"; - case FieldDescriptor::TYPE_SINT32: - return SimpleItoa(descriptor->default_value_int32()); - case FieldDescriptor::TYPE_SINT64: - return SimpleItoa(descriptor->default_value_int64()) + "L"; - default: - GOOGLE_LOG(FATAL)<< "Unknown field type."; - return ""; - } -} - -std::string FieldGeneratorBase::number() { - return SimpleItoa(descriptor_->number()); -} - -std::string FieldGeneratorBase::capitalized_type_name() { - switch (descriptor_->type()) { - case FieldDescriptor::TYPE_ENUM: - return "Enum"; - case FieldDescriptor::TYPE_MESSAGE: - return "Message"; - case FieldDescriptor::TYPE_GROUP: - return "Group"; - case FieldDescriptor::TYPE_DOUBLE: - return "Double"; - case FieldDescriptor::TYPE_FLOAT: - return "Float"; - case FieldDescriptor::TYPE_INT64: - return "Int64"; - case FieldDescriptor::TYPE_UINT64: - return "UInt64"; - case FieldDescriptor::TYPE_INT32: - return "Int32"; - case FieldDescriptor::TYPE_FIXED64: - return "Fixed64"; - case FieldDescriptor::TYPE_FIXED32: - return "Fixed32"; - case FieldDescriptor::TYPE_BOOL: - return "Bool"; - case FieldDescriptor::TYPE_STRING: - return "String"; - case FieldDescriptor::TYPE_BYTES: - return "Bytes"; - case FieldDescriptor::TYPE_UINT32: - return "UInt32"; - case FieldDescriptor::TYPE_SFIXED32: - return "SFixed32"; - case FieldDescriptor::TYPE_SFIXED64: - return "SFixed64"; - case FieldDescriptor::TYPE_SINT32: - return "SInt32"; - case FieldDescriptor::TYPE_SINT64: - return "SInt64"; - default: - GOOGLE_LOG(FATAL)<< "Unknown field type."; - return ""; - } -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_field_base.h b/windows/include/google/protobuf/compiler/csharp/csharp_field_base.h deleted file mode 100644 index df26853b1..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_field_base.h +++ /dev/null @@ -1,105 +0,0 @@ -// 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_CSHARP_FIELD_BASE_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_FIELD_BASE_H__ - -#include -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -class FieldGeneratorBase : public SourceGeneratorBase { - public: - FieldGeneratorBase(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options* options); - ~FieldGeneratorBase(); - - virtual void GenerateCloningCode(io::Printer* printer) = 0; - virtual void GenerateFreezingCode(io::Printer* printer); - virtual void GenerateCodecCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer) = 0; - virtual void GenerateMergingCode(io::Printer* printer) = 0; - virtual void GenerateParsingCode(io::Printer* printer) = 0; - virtual void GenerateSerializationCode(io::Printer* printer) = 0; - virtual void GenerateSerializedSizeCode(io::Printer* printer) = 0; - - virtual void WriteHash(io::Printer* printer) = 0; - virtual void WriteEquals(io::Printer* printer) = 0; - // Currently unused, as we use reflection to generate JSON - virtual void WriteToString(io::Printer* printer) = 0; - - protected: - const FieldDescriptor* descriptor_; - const int fieldOrdinal_; - std::map variables_; - - void AddDeprecatedFlag(io::Printer* printer); - void AddNullCheck(io::Printer* printer); - void AddNullCheck(io::Printer* printer, const std::string& name); - - void AddPublicMemberAttributes(io::Printer* printer); - void SetCommonOneofFieldVariables(std::map* variables); - - std::string oneof_property_name(); - std::string oneof_name(); - std::string property_name(); - std::string name(); - std::string type_name(); - std::string type_name(const FieldDescriptor* descriptor); - bool has_default_value(); - bool is_nullable_type(); - std::string default_value(); - std::string default_value(const FieldDescriptor* descriptor); - std::string number(); - std::string capitalized_type_name(); - - private: - void SetCommonFieldVariables(std::map* variables); - std::string GetStringDefaultValueInternal(); - std::string GetBytesDefaultValueInternal(); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorBase); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_FIELD_BASE_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_generator.cc b/windows/include/google/protobuf/compiler/csharp/csharp_generator.cc deleted file mode 100644 index 0c93fc292..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_generator.cc +++ /dev/null @@ -1,113 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -void GenerateFile(const google::protobuf::FileDescriptor* file, - io::Printer* printer, - const Options* options) { - ReflectionClassGenerator reflectionClassGenerator(file, options); - reflectionClassGenerator.Generate(printer); -} - -bool Generator::Generate( - const FileDescriptor* file, - const string& parameter, - GeneratorContext* generator_context, - string* error) const { - - std::vector > options; - ParseGeneratorParameter(parameter, &options); - - // We only support proto3 - but we make an exception for descriptor.proto. - if (file->syntax() != FileDescriptor::SYNTAX_PROTO3 && !IsDescriptorProto(file)) { - *error = "C# code generation only supports proto3 syntax"; - return false; - } - - struct Options cli_options; - - for (int i = 0; i < options.size(); i++) { - if (options[i].first == "file_extension") { - cli_options.file_extension = options[i].second; - } else if (options[i].first == "base_namespace") { - cli_options.base_namespace = options[i].second; - cli_options.base_namespace_specified = true; - } else if (options[i].first == "internal_access") { - cli_options.internal_access = true; - } else { - *error = "Unknown generator option: " + options[i].first; - return false; - } - } - - string filename_error = ""; - std::string filename = GetOutputFile(file, - cli_options.file_extension, - cli_options.base_namespace_specified, - cli_options.base_namespace, - &filename_error); - - if (filename.empty()) { - *error = filename_error; - return false; - } - std::unique_ptr output( - generator_context->Open(filename)); - io::Printer printer(output.get(), '$'); - - GenerateFile(file, &printer, &cli_options); - - return true; -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_generator.h b/windows/include/google/protobuf/compiler/csharp/csharp_generator.h index c8b195291..f41f9b835 100644 --- a/windows/include/google/protobuf/compiler/csharp/csharp_generator.h +++ b/windows/include/google/protobuf/compiler/csharp/csharp_generator.h @@ -37,6 +37,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -46,14 +48,16 @@ namespace csharp { // header. If you create your own protocol compiler binary and you want // it to support C# output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator - : public google::protobuf::compiler::CodeGenerator { -public: - virtual bool Generate( - const FileDescriptor* file, - const string& parameter, - GeneratorContext* generator_context, - string* error) const; +class PROTOC_EXPORT Generator : public CodeGenerator { + public: + Generator(); + ~Generator(); + bool Generate( + const FileDescriptor* file, + const std::string& parameter, + GeneratorContext* generator_context, + std::string* error) const override; + uint64_t GetSupportedFeatures() const override; }; } // namespace csharp @@ -61,4 +65,6 @@ public: } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_generator_unittest.cc b/windows/include/google/protobuf/compiler/csharp/csharp_generator_unittest.cc deleted file mode 100644 index 5755fee00..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_generator_unittest.cc +++ /dev/null @@ -1,70 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2014 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. - -#include - -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { -namespace { - -TEST(CSharpEnumValue, PascalCasedPrefixStripping) { - EXPECT_EQ("Bar", GetEnumValueName("Foo", "BAR")); - EXPECT_EQ("BarBaz", GetEnumValueName("Foo", "BAR_BAZ")); - EXPECT_EQ("Bar", GetEnumValueName("Foo", "FOO_BAR")); - EXPECT_EQ("Bar", GetEnumValueName("Foo", "FOO__BAR")); - EXPECT_EQ("BarBaz", GetEnumValueName("Foo", "FOO_BAR_BAZ")); - EXPECT_EQ("BarBaz", GetEnumValueName("Foo", "Foo_BarBaz")); - EXPECT_EQ("Bar", GetEnumValueName("FO_O", "FOO_BAR")); - EXPECT_EQ("Bar", GetEnumValueName("FOO", "F_O_O_BAR")); - EXPECT_EQ("Bar", GetEnumValueName("Foo", "BAR")); - EXPECT_EQ("BarBaz", GetEnumValueName("Foo", "BAR_BAZ")); - EXPECT_EQ("Foo", GetEnumValueName("Foo", "FOO")); - EXPECT_EQ("Foo", GetEnumValueName("Foo", "FOO___")); - // Identifiers can't start with digits - EXPECT_EQ("_2Bar", GetEnumValueName("Foo", "FOO_2_BAR")); - EXPECT_EQ("_2", GetEnumValueName("Foo", "FOO___2")); -} - -} // namespace -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_helpers.cc b/windows/include/google/protobuf/compiler/csharp/csharp_helpers.cc deleted file mode 100644 index 5bca1ffa7..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_helpers.cc +++ /dev/null @@ -1,507 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -CSharpType GetCSharpType(FieldDescriptor::Type type) { - switch (type) { - case FieldDescriptor::TYPE_INT32: - return CSHARPTYPE_INT32; - case FieldDescriptor::TYPE_INT64: - return CSHARPTYPE_INT64; - case FieldDescriptor::TYPE_UINT32: - return CSHARPTYPE_UINT32; - case FieldDescriptor::TYPE_UINT64: - return CSHARPTYPE_UINT32; - case FieldDescriptor::TYPE_SINT32: - return CSHARPTYPE_INT32; - case FieldDescriptor::TYPE_SINT64: - return CSHARPTYPE_INT64; - case FieldDescriptor::TYPE_FIXED32: - return CSHARPTYPE_UINT32; - case FieldDescriptor::TYPE_FIXED64: - return CSHARPTYPE_UINT64; - case FieldDescriptor::TYPE_SFIXED32: - return CSHARPTYPE_INT32; - case FieldDescriptor::TYPE_SFIXED64: - return CSHARPTYPE_INT64; - case FieldDescriptor::TYPE_FLOAT: - return CSHARPTYPE_FLOAT; - case FieldDescriptor::TYPE_DOUBLE: - return CSHARPTYPE_DOUBLE; - case FieldDescriptor::TYPE_BOOL: - return CSHARPTYPE_BOOL; - case FieldDescriptor::TYPE_ENUM: - return CSHARPTYPE_ENUM; - case FieldDescriptor::TYPE_STRING: - return CSHARPTYPE_STRING; - case FieldDescriptor::TYPE_BYTES: - return CSHARPTYPE_BYTESTRING; - case FieldDescriptor::TYPE_GROUP: - return CSHARPTYPE_MESSAGE; - case FieldDescriptor::TYPE_MESSAGE: - return CSHARPTYPE_MESSAGE; - - // No default because we want the compiler to complain if any new - // types are added. - } - GOOGLE_LOG(FATAL)<< "Can't get here."; - return (CSharpType) -1; -} - -std::string StripDotProto(const std::string& proto_file) { - int lastindex = proto_file.find_last_of("."); - return proto_file.substr(0, lastindex); -} - -std::string GetFileNamespace(const FileDescriptor* descriptor) { - if (descriptor->options().has_csharp_namespace()) { - return descriptor->options().csharp_namespace(); - } - return UnderscoresToCamelCase(descriptor->package(), true, true); -} - -// Returns the Pascal-cased last part of the proto file. For example, -// input of "google/protobuf/foo_bar.proto" would result in "FooBar". -std::string GetFileNameBase(const FileDescriptor* descriptor) { - std::string proto_file = descriptor->name(); - int lastslash = proto_file.find_last_of("/"); - std::string base = proto_file.substr(lastslash + 1); - return UnderscoresToPascalCase(StripDotProto(base)); -} - -std::string GetReflectionClassUnqualifiedName(const FileDescriptor* descriptor) { - // TODO: Detect collisions with existing messages, - // and append an underscore if necessary. - return GetFileNameBase(descriptor) + "Reflection"; -} - -// TODO(jtattermusch): can we reuse a utility function? -std::string UnderscoresToCamelCase(const std::string& input, - bool cap_next_letter, - bool preserve_period) { - string result; - // Note: I distrust ctype.h due to locales. - for (int i = 0; i < input.size(); i++) { - if ('a' <= input[i] && input[i] <= 'z') { - if (cap_next_letter) { - result += input[i] + ('A' - 'a'); - } else { - result += input[i]; - } - cap_next_letter = false; - } else if ('A' <= input[i] && input[i] <= 'Z') { - if (i == 0 && !cap_next_letter) { - // Force first letter to lower-case unless explicitly told to - // capitalize it. - result += input[i] + ('a' - 'A'); - } else { - // Capital letters after the first are left as-is. - result += input[i]; - } - cap_next_letter = false; - } else if ('0' <= input[i] && input[i] <= '9') { - result += input[i]; - cap_next_letter = true; - } else { - cap_next_letter = true; - if (input[i] == '.' && preserve_period) { - result += '.'; - } - } - } - // Add a trailing "_" if the name should be altered. - if (input[input.size() - 1] == '#') { - result += '_'; - } - return result; -} - -std::string UnderscoresToPascalCase(const std::string& input) { - return UnderscoresToCamelCase(input, true); -} - -// Convert a string which is expected to be SHOUTY_CASE (but may not be *precisely* shouty) -// into a PascalCase string. Precise rules implemented: - -// Previous input character Current character Case -// Any Non-alphanumeric Skipped -// None - first char of input Alphanumeric Upper -// Non-letter (e.g. _ or 1) Alphanumeric Upper -// Numeric Alphanumeric Upper -// Lower letter Alphanumeric Same as current -// Upper letter Alphanumeric Lower -std::string ShoutyToPascalCase(const std::string& input) { - string result; - // Simple way of implementing "always start with upper" - char previous = '_'; - for (int i = 0; i < input.size(); i++) { - char current = input[i]; - if (!ascii_isalnum(current)) { - previous = current; - continue; - } - if (!ascii_isalnum(previous)) { - result += ascii_toupper(current); - } else if (ascii_isdigit(previous)) { - result += ascii_toupper(current); - } else if (ascii_islower(previous)) { - result += current; - } else { - result += ascii_tolower(current); - } - previous = current; - } - return result; -} - -// Attempt to remove a prefix from a value, ignoring casing and skipping underscores. -// (foo, foo_bar) => bar - underscore after prefix is skipped -// (FOO, foo_bar) => bar - casing is ignored -// (foo_bar, foobarbaz) => baz - underscore in prefix is ignored -// (foobar, foo_barbaz) => baz - underscore in value is ignored -// (foo, bar) => bar - prefix isn't matched; return original value -std::string TryRemovePrefix(const std::string& prefix, const std::string& value) { - // First normalize to a lower-case no-underscores prefix to match against - std::string prefix_to_match = ""; - for (size_t i = 0; i < prefix.size(); i++) { - if (prefix[i] != '_') { - prefix_to_match += ascii_tolower(prefix[i]); - } - } - - // This keeps track of how much of value we've consumed - size_t prefix_index, value_index; - for (prefix_index = 0, value_index = 0; - prefix_index < prefix_to_match.size() && value_index < value.size(); - value_index++) { - // Skip over underscores in the value - if (value[value_index] == '_') { - continue; - } - if (ascii_tolower(value[value_index]) != prefix_to_match[prefix_index++]) { - // Failed to match the prefix - bail out early. - return value; - } - } - - // If we didn't finish looking through the prefix, we can't strip it. - if (prefix_index < prefix_to_match.size()) { - return value; - } - - // Step over any underscores after the prefix - while (value_index < value.size() && value[value_index] == '_') { - value_index++; - } - - // If there's nothing left (e.g. it was a prefix with only underscores afterwards), don't strip. - if (value_index == value.size()) { - return value; - } - - return value.substr(value_index); -} - -// Format the enum value name in a pleasant way for C#: -// - Strip the enum name as a prefix if possible -// - Convert to PascalCase. -// For example, an enum called Color with a value of COLOR_BLUE should -// result in an enum value in C# called just Blue -std::string GetEnumValueName(const std::string& enum_name, const std::string& enum_value_name) { - std::string stripped = TryRemovePrefix(enum_name, enum_value_name); - std::string result = ShoutyToPascalCase(stripped); - // Just in case we have an enum name of FOO and a value of FOO_2... make sure the returned - // string is a valid identifier. - if (ascii_isdigit(result[0])) { - result = "_" + result; - } - return result; -} - -std::string ToCSharpName(const std::string& name, const FileDescriptor* file) { - std::string result = GetFileNamespace(file); - if (result != "") { - result += '.'; - } - string classname; - if (file->package().empty()) { - classname = name; - } else { - // Strip the proto package from full_name since we've replaced it with - // the C# namespace. - classname = name.substr(file->package().size() + 1); - } - result += StringReplace(classname, ".", ".Types.", true); - return "global::" + result; -} - -std::string GetReflectionClassName(const FileDescriptor* descriptor) { - std::string result = GetFileNamespace(descriptor); - if (!result.empty()) { - result += '.'; - } - result += GetReflectionClassUnqualifiedName(descriptor); - return "global::" + result; -} - -std::string GetClassName(const Descriptor* descriptor) { - return ToCSharpName(descriptor->full_name(), descriptor->file()); -} - -std::string GetClassName(const EnumDescriptor* descriptor) { - return ToCSharpName(descriptor->full_name(), descriptor->file()); -} - -// Groups are hacky: The name of the field is just the lower-cased name -// of the group type. In C#, though, we would like to retain the original -// capitalization of the type name. -std::string GetFieldName(const FieldDescriptor* descriptor) { - if (descriptor->type() == FieldDescriptor::TYPE_GROUP) { - return descriptor->message_type()->name(); - } else { - return descriptor->name(); - } -} - -std::string GetFieldConstantName(const FieldDescriptor* field) { - return GetPropertyName(field) + "FieldNumber"; -} - -std::string GetPropertyName(const FieldDescriptor* descriptor) { - // TODO(jtattermusch): consider introducing csharp_property_name field option - std::string property_name = UnderscoresToPascalCase(GetFieldName(descriptor)); - // Avoid either our own type name or reserved names. Note that not all names - // are reserved - a field called to_string, write_to etc would still cause a problem. - // There are various ways of ending up with naming collisions, but we try to avoid obvious - // ones. - if (property_name == descriptor->containing_type()->name() - || property_name == "Types" - || property_name == "Descriptor") { - property_name += "_"; - } - return property_name; -} - -std::string GetOutputFile( - const google::protobuf::FileDescriptor* descriptor, - const std::string file_extension, - const bool generate_directories, - const std::string base_namespace, - string* error) { - string relative_filename = GetFileNameBase(descriptor) + file_extension; - if (!generate_directories) { - return relative_filename; - } - string ns = GetFileNamespace(descriptor); - string namespace_suffix = ns; - if (!base_namespace.empty()) { - // Check that the base_namespace is either equal to or a leading part of - // the file namespace. This isn't just a simple prefix; "Foo.B" shouldn't - // be regarded as a prefix of "Foo.Bar". The simplest option is to add "." - // to both. - string extended_ns = ns + "."; - if (extended_ns.find(base_namespace + ".") != 0) { - *error = "Namespace " + ns + " is not a prefix namespace of base namespace " + base_namespace; - return ""; // This will be ignored, because we've set an error. - } - namespace_suffix = ns.substr(base_namespace.length()); - if (namespace_suffix.find(".") == 0) { - namespace_suffix = namespace_suffix.substr(1); - } - } - - string namespace_dir = StringReplace(namespace_suffix, ".", "/", true); - if (!namespace_dir.empty()) { - namespace_dir += "/"; - } - return namespace_dir + relative_filename; -} - -// TODO: c&p from Java protoc plugin -// For encodings with fixed sizes, returns that size in bytes. Otherwise -// returns -1. -int GetFixedSize(FieldDescriptor::Type type) { - switch (type) { - case FieldDescriptor::TYPE_INT32 : return -1; - case FieldDescriptor::TYPE_INT64 : return -1; - case FieldDescriptor::TYPE_UINT32 : return -1; - case FieldDescriptor::TYPE_UINT64 : return -1; - case FieldDescriptor::TYPE_SINT32 : return -1; - case FieldDescriptor::TYPE_SINT64 : return -1; - case FieldDescriptor::TYPE_FIXED32 : return internal::WireFormatLite::kFixed32Size; - case FieldDescriptor::TYPE_FIXED64 : return internal::WireFormatLite::kFixed64Size; - case FieldDescriptor::TYPE_SFIXED32: return internal::WireFormatLite::kSFixed32Size; - case FieldDescriptor::TYPE_SFIXED64: return internal::WireFormatLite::kSFixed64Size; - case FieldDescriptor::TYPE_FLOAT : return internal::WireFormatLite::kFloatSize; - case FieldDescriptor::TYPE_DOUBLE : return internal::WireFormatLite::kDoubleSize; - - case FieldDescriptor::TYPE_BOOL : return internal::WireFormatLite::kBoolSize; - case FieldDescriptor::TYPE_ENUM : return -1; - - case FieldDescriptor::TYPE_STRING : return -1; - case FieldDescriptor::TYPE_BYTES : return -1; - case FieldDescriptor::TYPE_GROUP : return -1; - case FieldDescriptor::TYPE_MESSAGE : return -1; - - // No default because we want the compiler to complain if any new - // types are added. - } - GOOGLE_LOG(FATAL) << "Can't get here."; - return -1; -} - -static const char base64_chars[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -std::string StringToBase64(const std::string& input) { - std::string result; - size_t remaining = input.size(); - const unsigned char *src = (const unsigned char*) input.c_str(); - while (remaining > 2) { - result += base64_chars[src[0] >> 2]; - result += base64_chars[((src[0] & 0x3) << 4) | (src[1] >> 4)]; - result += base64_chars[((src[1] & 0xf) << 2) | (src[2] >> 6)]; - result += base64_chars[src[2] & 0x3f]; - remaining -= 3; - src += 3; - } - switch (remaining) { - case 2: - result += base64_chars[src[0] >> 2]; - result += base64_chars[((src[0] & 0x3) << 4) | (src[1] >> 4)]; - result += base64_chars[(src[1] & 0xf) << 2]; - result += '='; - src += 2; - break; - case 1: - result += base64_chars[src[0] >> 2]; - result += base64_chars[((src[0] & 0x3) << 4)]; - result += '='; - result += '='; - src += 1; - break; - } - return result; -} - -std::string FileDescriptorToBase64(const FileDescriptor* descriptor) { - std::string fdp_bytes; - FileDescriptorProto fdp; - descriptor->CopyTo(&fdp); - fdp.SerializeToString(&fdp_bytes); - return StringToBase64(fdp_bytes); -} - -FieldGeneratorBase* CreateFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options* options) { - switch (descriptor->type()) { - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_MESSAGE: - if (descriptor->is_repeated()) { - if (descriptor->is_map()) { - return new MapFieldGenerator(descriptor, fieldOrdinal, options); - } else { - return new RepeatedMessageFieldGenerator(descriptor, fieldOrdinal, options); - } - } else { - if (IsWrapperType(descriptor)) { - if (descriptor->containing_oneof()) { - return new WrapperOneofFieldGenerator(descriptor, fieldOrdinal, options); - } else { - return new WrapperFieldGenerator(descriptor, fieldOrdinal, options); - } - } else { - if (descriptor->containing_oneof()) { - return new MessageOneofFieldGenerator(descriptor, fieldOrdinal, options); - } else { - return new MessageFieldGenerator(descriptor, fieldOrdinal, options); - } - } - } - case FieldDescriptor::TYPE_ENUM: - if (descriptor->is_repeated()) { - return new RepeatedEnumFieldGenerator(descriptor, fieldOrdinal, options); - } else { - if (descriptor->containing_oneof()) { - return new EnumOneofFieldGenerator(descriptor, fieldOrdinal, options); - } else { - return new EnumFieldGenerator(descriptor, fieldOrdinal, options); - } - } - default: - if (descriptor->is_repeated()) { - return new RepeatedPrimitiveFieldGenerator(descriptor, fieldOrdinal, options); - } else { - if (descriptor->containing_oneof()) { - return new PrimitiveOneofFieldGenerator(descriptor, fieldOrdinal, options); - } else { - return new PrimitiveFieldGenerator(descriptor, fieldOrdinal, options); - } - } - } -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_helpers.h b/windows/include/google/protobuf/compiler/csharp/csharp_helpers.h deleted file mode 100644 index c317ad0e5..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_helpers.h +++ /dev/null @@ -1,148 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CSHARP_HELPERS_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_HELPERS_H__ - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -struct Options; -class FieldGeneratorBase; - -// TODO: start using this enum. -enum CSharpType { - CSHARPTYPE_INT32 = 1, - CSHARPTYPE_INT64 = 2, - CSHARPTYPE_UINT32 = 3, - CSHARPTYPE_UINT64 = 4, - CSHARPTYPE_FLOAT = 5, - CSHARPTYPE_DOUBLE = 6, - CSHARPTYPE_BOOL = 7, - CSHARPTYPE_STRING = 8, - CSHARPTYPE_BYTESTRING = 9, - CSHARPTYPE_MESSAGE = 10, - CSHARPTYPE_ENUM = 11, - MAX_CSHARPTYPE = 11 -}; - -// Converts field type to corresponding C# type. -CSharpType GetCSharpType(FieldDescriptor::Type type); - -std::string StripDotProto(const std::string& proto_file); - -// Gets unqualified name of the reflection class -std::string GetReflectionClassUnqualifiedName(const FileDescriptor* descriptor); - -std::string GetClassName(const EnumDescriptor* descriptor); - -std::string GetFieldName(const FieldDescriptor* descriptor); - -std::string GetFieldConstantName(const FieldDescriptor* field); - -std::string GetPropertyName(const FieldDescriptor* descriptor); - -int GetFixedSize(FieldDescriptor::Type type); - -std::string UnderscoresToCamelCase(const std::string& input, - bool cap_next_letter, - bool preserve_period); - -inline std::string UnderscoresToCamelCase(const std::string& input, bool cap_next_letter) { - return UnderscoresToCamelCase(input, cap_next_letter, false); -} - -std::string UnderscoresToPascalCase(const std::string& input); - -// Note that we wouldn't normally want to export this (we're not expecting -// it to be used outside libprotoc itself) but this exposes it for testing. -std::string LIBPROTOBUF_EXPORT GetEnumValueName(const std::string& enum_name, const std::string& enum_value_name); - -// TODO(jtattermusch): perhaps we could move this to strutil -std::string StringToBase64(const std::string& input); - -std::string FileDescriptorToBase64(const FileDescriptor* descriptor); - -FieldGeneratorBase* CreateFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options* options); - -// Determines whether the given message is a map entry message, -// i.e. one implicitly created by protoc due to a map field. -inline bool IsMapEntryMessage(const Descriptor* descriptor) { - return descriptor->options().map_entry(); -} - -// Determines whether we're generating code for the proto representation of -// descriptors etc, for use in the runtime. This is the only type which is -// allowed to use proto2 syntax, and it generates internal classes. -inline bool IsDescriptorProto(const FileDescriptor* descriptor) { - return descriptor->name() == "google/protobuf/descriptor.proto"; -} - -// Determines whether the given message is an options message within descriptor.proto. -inline bool IsDescriptorOptionMessage(const Descriptor* descriptor) { - if (!IsDescriptorProto(descriptor->file())) { - return false; - } - const string name = descriptor->full_name(); - return name == "google.protobuf.FileOptions" || - name == "google.protobuf.MessageOptions" || - name == "google.protobuf.FieldOptions" || - name == "google.protobuf.OneofOptions" || - name == "google.protobuf.EnumOptions" || - name == "google.protobuf.EnumValueOptions" || - name == "google.protobuf.ServiceOptions" || - name == "google.protobuf.MethodOptions"; -} - -inline bool IsWrapperType(const FieldDescriptor* descriptor) { - return descriptor->type() == FieldDescriptor::TYPE_MESSAGE && - descriptor->message_type()->file()->name() == "google/protobuf/wrappers.proto"; -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_HELPERS_H__ diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_map_field.cc b/windows/include/google/protobuf/compiler/csharp/csharp_map_field.cc deleted file mode 100644 index d58514ce4..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_map_field.cc +++ /dev/null @@ -1,141 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2015 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options* options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { -} - -MapFieldGenerator::~MapFieldGenerator() { -} - -void MapFieldGenerator::GenerateMembers(io::Printer* printer) { - const FieldDescriptor* key_descriptor = - descriptor_->message_type()->FindFieldByName("key"); - const FieldDescriptor* value_descriptor = - descriptor_->message_type()->FindFieldByName("value"); - variables_["key_type_name"] = type_name(key_descriptor); - variables_["value_type_name"] = type_name(value_descriptor); - std::unique_ptr key_generator( - CreateFieldGenerator(key_descriptor, 1, this->options())); - std::unique_ptr value_generator( - CreateFieldGenerator(value_descriptor, 2, this->options())); - - printer->Print( - variables_, - "private static readonly pbc::MapField<$key_type_name$, $value_type_name$>.Codec _map_$name$_codec\n" - " = new pbc::MapField<$key_type_name$, $value_type_name$>.Codec("); - key_generator->GenerateCodecCode(printer); - printer->Print(", "); - value_generator->GenerateCodecCode(printer); - printer->Print( - variables_, - ", $tag$);\n" - "private readonly pbc::MapField<$key_type_name$, $value_type_name$> $name$_ = new pbc::MapField<$key_type_name$, $value_type_name$>();\n"); - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ pbc::MapField<$key_type_name$, $value_type_name$> $property_name$ {\n" - " get { return $name$_; }\n" - "}\n"); -} - -void MapFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.Add(other.$name$_);\n"); -} - -void MapFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.AddEntriesFrom(input, _map_$name$_codec);\n"); -} - -void MapFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.WriteTo(output, _map_$name$_codec);\n"); -} - -void MapFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "size += $name$_.CalculateSize(_map_$name$_codec);\n"); -} - -void MapFieldGenerator::WriteHash(io::Printer* printer) { - printer->Print( - variables_, - "hash ^= $property_name$.GetHashCode();\n"); -} -void MapFieldGenerator::WriteEquals(io::Printer* printer) { - printer->Print( - variables_, - "if (!$property_name$.Equals(other.$property_name$)) return false;\n"); -} - -void MapFieldGenerator::WriteToString(io::Printer* printer) { - // TODO: If we ever actually use ToString, we'll need to impleme this... -} - -void MapFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$name$_ = other.$name$_.Clone();\n"); -} - -void MapFieldGenerator::GenerateFreezingCode(io::Printer* printer) { -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_map_field.h b/windows/include/google/protobuf/compiler/csharp/csharp_map_field.h deleted file mode 100644 index 84a33a036..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_map_field.h +++ /dev/null @@ -1,73 +0,0 @@ -// 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_CSHARP_MAP_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_MAP_FIELD_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -class MapFieldGenerator : public FieldGeneratorBase { - public: - MapFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options* options); - ~MapFieldGenerator(); - - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateFreezingCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - virtual void WriteHash(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_MAP_FIELD_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_message.cc b/windows/include/google/protobuf/compiler/csharp/csharp_message.cc deleted file mode 100644 index 8a4307f15..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_message.cc +++ /dev/null @@ -1,580 +0,0 @@ -// 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. - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -bool CompareFieldNumbers(const FieldDescriptor* d1, const FieldDescriptor* d2) { - return d1->number() < d2->number(); -} - -MessageGenerator::MessageGenerator(const Descriptor* descriptor, - const Options* options) - : SourceGeneratorBase(descriptor->file(), options), - descriptor_(descriptor) { - - // sorted field names - for (int i = 0; i < descriptor_->field_count(); i++) { - field_names_.push_back(descriptor_->field(i)->name()); - } - std::sort(field_names_.begin(), field_names_.end()); - - // fields by number - for (int i = 0; i < descriptor_->field_count(); i++) { - fields_by_number_.push_back(descriptor_->field(i)); - } - std::sort(fields_by_number_.begin(), fields_by_number_.end(), - CompareFieldNumbers); -} - -MessageGenerator::~MessageGenerator() { -} - -std::string MessageGenerator::class_name() { - return descriptor_->name(); -} - -std::string MessageGenerator::full_class_name() { - return GetClassName(descriptor_); -} - -const std::vector& MessageGenerator::field_names() { - return field_names_; -} - -const std::vector& MessageGenerator::fields_by_number() { - return fields_by_number_; -} - -void MessageGenerator::AddDeprecatedFlag(io::Printer* printer) { - if (descriptor_->options().deprecated()) { - printer->Print("[global::System.ObsoleteAttribute]\n"); - } -} - -void MessageGenerator::Generate(io::Printer* printer) { - std::map vars; - vars["class_name"] = class_name(); - vars["access_level"] = class_access_level(); - - WriteMessageDocComment(printer, descriptor_); - AddDeprecatedFlag(printer); - - printer->Print( - vars, - "$access_level$ sealed partial class $class_name$ : pb::IMessage<$class_name$> {\n"); - printer->Indent(); - - // All static fields and properties - printer->Print( - vars, - "private static readonly pb::MessageParser<$class_name$> _parser = new pb::MessageParser<$class_name$>(() => new $class_name$());\n"); - - printer->Print( - "private pb::UnknownFieldSet _unknownFields;\n"); - - WriteGeneratedCodeAttributes(printer); - - printer->Print( - vars, - "public static pb::MessageParser<$class_name$> Parser { get { return _parser; } }\n\n"); - - // Access the message descriptor via the relevant file descriptor or containing message descriptor. - if (!descriptor_->containing_type()) { - vars["descriptor_accessor"] = GetReflectionClassName(descriptor_->file()) - + ".Descriptor.MessageTypes[" + SimpleItoa(descriptor_->index()) + "]"; - } else { - vars["descriptor_accessor"] = GetClassName(descriptor_->containing_type()) - + ".Descriptor.NestedTypes[" + SimpleItoa(descriptor_->index()) + "]"; - } - - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "public static pbr::MessageDescriptor Descriptor {\n" - " get { return $descriptor_accessor$; }\n" - "}\n" - "\n"); - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "pbr::MessageDescriptor pb::IMessage.Descriptor {\n" - " get { return Descriptor; }\n" - "}\n" - "\n"); - // CustomOptions property, only for options messages - if (IsDescriptorOptionMessage(descriptor_)) { - printer->Print( - "internal CustomOptions CustomOptions{ get; private set; } = CustomOptions.Empty;\n" - "\n"); - } - - // Parameterless constructor and partial OnConstruction method. - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "public $class_name$() {\n" - " OnConstruction();\n" - "}\n\n" - "partial void OnConstruction();\n\n"); - - GenerateCloningCode(printer); - GenerateFreezingCode(printer); - - // Fields/properties - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* fieldDescriptor = descriptor_->field(i); - - // Rats: we lose the debug comment here :( - printer->Print( - "/// Field number for the \"$field_name$\" field.\n" - "public const int $field_constant_name$ = $index$;\n", - "field_name", fieldDescriptor->name(), - "field_constant_name", GetFieldConstantName(fieldDescriptor), - "index", SimpleItoa(fieldDescriptor->number())); - std::unique_ptr generator( - CreateFieldGeneratorInternal(fieldDescriptor)); - generator->GenerateMembers(printer); - printer->Print("\n"); - } - - // oneof properties - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false); - vars["property_name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true); - vars["original_name"] = descriptor_->oneof_decl(i)->name(); - printer->Print( - vars, - "private object $name$_;\n" - "/// Enum of possible cases for the \"$original_name$\" oneof.\n" - "public enum $property_name$OneofCase {\n"); - printer->Indent(); - printer->Print("None = 0,\n"); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print("$field_property_name$ = $index$,\n", - "field_property_name", GetPropertyName(field), - "index", SimpleItoa(field->number())); - } - printer->Outdent(); - printer->Print("}\n"); - // TODO: Should we put the oneof .proto comments here? - // It's unclear exactly where they should go. - printer->Print( - vars, - "private $property_name$OneofCase $name$Case_ = $property_name$OneofCase.None;\n"); - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "public $property_name$OneofCase $property_name$Case {\n" - " get { return $name$Case_; }\n" - "}\n\n"); - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "public void Clear$property_name$() {\n" - " $name$Case_ = $property_name$OneofCase.None;\n" - " $name$_ = null;\n" - "}\n\n"); - } - - // Standard methods - GenerateFrameworkMethods(printer); - GenerateMessageSerializationMethods(printer); - GenerateMergingMethods(printer); - - // Nested messages and enums - if (HasNestedGeneratedTypes()) { - printer->Print( - vars, - "#region Nested types\n" - "/// Container for nested types declared in the $class_name$ message type.\n"); - WriteGeneratedCodeAttributes(printer); - printer->Print("public static partial class Types {\n"); - printer->Indent(); - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - EnumGenerator enumGenerator(descriptor_->enum_type(i), this->options()); - enumGenerator.Generate(printer); - } - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // Don't generate nested types for maps... - if (!IsMapEntryMessage(descriptor_->nested_type(i))) { - MessageGenerator messageGenerator( - descriptor_->nested_type(i), this->options()); - messageGenerator.Generate(printer); - } - } - printer->Outdent(); - printer->Print("}\n" - "#endregion\n" - "\n"); - } - - printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); -} - -// Helper to work out whether we need to generate a class to hold nested types/enums. -// Only tricky because we don't want to generate map entry types. -bool MessageGenerator::HasNestedGeneratedTypes() -{ - if (descriptor_->enum_type_count() > 0) { - return true; - } - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - if (!IsMapEntryMessage(descriptor_->nested_type(i))) { - return true; - } - } - return false; -} - -void MessageGenerator::GenerateCloningCode(io::Printer* printer) { - std::map vars; - WriteGeneratedCodeAttributes(printer); - vars["class_name"] = class_name(); - printer->Print( - vars, - "public $class_name$($class_name$ other) : this() {\n"); - printer->Indent(); - // Clone non-oneof fields first - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - std::unique_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - generator->GenerateCloningCode(printer); - } - } - // Clone just the right field for each oneof - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false); - vars["property_name"] = UnderscoresToCamelCase( - descriptor_->oneof_decl(i)->name(), true); - printer->Print(vars, "switch (other.$property_name$Case) {\n"); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - std::unique_ptr generator(CreateFieldGeneratorInternal(field)); - vars["field_property_name"] = GetPropertyName(field); - printer->Print( - vars, - "case $property_name$OneofCase.$field_property_name$:\n"); - printer->Indent(); - generator->GenerateCloningCode(printer); - printer->Print("break;\n"); - printer->Outdent(); - } - printer->Outdent(); - printer->Print("}\n\n"); - } - // Clone unknown fields - printer->Print( - "_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);\n"); - - printer->Outdent(); - printer->Print("}\n\n"); - - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "public $class_name$ Clone() {\n" - " return new $class_name$(this);\n" - "}\n\n"); -} - -void MessageGenerator::GenerateFreezingCode(io::Printer* printer) { -} - -void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) { - std::map vars; - vars["class_name"] = class_name(); - - // Equality - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "public override bool Equals(object other) {\n" - " return Equals(other as $class_name$);\n" - "}\n\n"); - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "public bool Equals($class_name$ other) {\n" - " if (ReferenceEquals(other, null)) {\n" - " return false;\n" - " }\n" - " if (ReferenceEquals(other, this)) {\n" - " return true;\n" - " }\n"); - printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - std::unique_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - generator->WriteEquals(printer); - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print("if ($property_name$Case != other.$property_name$Case) return false;\n", - "property_name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); - } - printer->Outdent(); - printer->Print( - " return Equals(_unknownFields, other._unknownFields);\n" - "}\n\n"); - - // GetHashCode - // Start with a non-zero value to easily distinguish between null and "empty" messages. - WriteGeneratedCodeAttributes(printer); - printer->Print( - "public override int GetHashCode() {\n" - " int hash = 1;\n"); - printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - std::unique_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - generator->WriteHash(printer); - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print("hash ^= (int) $name$Case_;\n", - "name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false)); - } - printer->Print( - "if (_unknownFields != null) {\n" - " hash ^= _unknownFields.GetHashCode();\n" - "}\n" - "return hash;\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - WriteGeneratedCodeAttributes(printer); - printer->Print( - "public override string ToString() {\n" - " return pb::JsonFormatter.ToDiagnosticString(this);\n" - "}\n\n"); -} - -void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) { - WriteGeneratedCodeAttributes(printer); - printer->Print( - "public void WriteTo(pb::CodedOutputStream output) {\n"); - printer->Indent(); - - // Serialize all the fields - for (int i = 0; i < fields_by_number().size(); i++) { - std::unique_ptr generator( - CreateFieldGeneratorInternal(fields_by_number()[i])); - generator->GenerateSerializationCode(printer); - } - - // Serialize unknown fields - printer->Print( - "if (_unknownFields != null) {\n" - " _unknownFields.WriteTo(output);\n" - "}\n"); - - // TODO(jonskeet): Memoize size of frozen messages? - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - WriteGeneratedCodeAttributes(printer); - printer->Print( - "public int CalculateSize() {\n"); - printer->Indent(); - printer->Print("int size = 0;\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - std::unique_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - generator->GenerateSerializedSizeCode(printer); - } - - printer->Print( - "if (_unknownFields != null) {\n" - " size += _unknownFields.CalculateSize();\n" - "}\n"); - - printer->Print("return size;\n"); - printer->Outdent(); - printer->Print("}\n\n"); -} - -void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { - // Note: These are separate from GenerateMessageSerializationMethods() - // because they need to be generated even for messages that are optimized - // for code size. - std::map vars; - vars["class_name"] = class_name(); - - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "public void MergeFrom($class_name$ other) {\n"); - printer->Indent(); - printer->Print( - "if (other == null) {\n" - " return;\n" - "}\n"); - // Merge non-oneof fields - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - std::unique_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - generator->GenerateMergingCode(printer); - } - } - // Merge oneof fields - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false); - vars["property_name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true); - printer->Print(vars, "switch (other.$property_name$Case) {\n"); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - vars["field_property_name"] = GetPropertyName(field); - printer->Print( - vars, - "case $property_name$OneofCase.$field_property_name$:\n"); - printer->Indent(); - std::unique_ptr generator(CreateFieldGeneratorInternal(field)); - generator->GenerateMergingCode(printer); - printer->Print("break;\n"); - printer->Outdent(); - } - printer->Outdent(); - printer->Print("}\n\n"); - } - // Merge unknown fields. - printer->Print( - "_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);\n"); - - printer->Outdent(); - printer->Print("}\n\n"); - - - WriteGeneratedCodeAttributes(printer); - printer->Print("public void MergeFrom(pb::CodedInputStream input) {\n"); - printer->Indent(); - printer->Print( - "uint tag;\n" - "while ((tag = input.ReadTag()) != 0) {\n" - " switch(tag) {\n"); - printer->Indent(); - printer->Indent(); - // Option messages need to store unknown fields so that options can be parsed later. - if (IsDescriptorOptionMessage(descriptor_)) { - printer->Print( - "default:\n" - " CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);\n" - " break;\n"); - } else { - printer->Print( - "default:\n" - " _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n" - " break;\n"); - } - for (int i = 0; i < fields_by_number().size(); i++) { - const FieldDescriptor* field = fields_by_number()[i]; - internal::WireFormatLite::WireType wt = - internal::WireFormat::WireTypeForFieldType(field->type()); - uint32 tag = internal::WireFormatLite::MakeTag(field->number(), wt); - // Handle both packed and unpacked repeated fields with the same Read*Array call; - // the two generated cases are the packed and unpacked tags. - // TODO(jonskeet): Check that is_packable is equivalent to - // is_repeated && wt in { VARINT, FIXED32, FIXED64 }. - // It looks like it is... - if (field->is_packable()) { - printer->Print( - "case $packed_tag$:\n", - "packed_tag", - SimpleItoa( - internal::WireFormatLite::MakeTag( - field->number(), - internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED))); - } - - printer->Print("case $tag$: {\n", "tag", SimpleItoa(tag)); - printer->Indent(); - std::unique_ptr generator( - CreateFieldGeneratorInternal(field)); - generator->GenerateParsingCode(printer); - printer->Print("break;\n"); - printer->Outdent(); - printer->Print("}\n"); - } - printer->Outdent(); - printer->Print("}\n"); // switch - printer->Outdent(); - printer->Print("}\n"); // while - printer->Outdent(); - printer->Print("}\n\n"); // method -} - -int MessageGenerator::GetFieldOrdinal(const FieldDescriptor* descriptor) { - for (int i = 0; i < field_names().size(); i++) { - if (field_names()[i] == descriptor->name()) { - return i; - } - } - GOOGLE_LOG(DFATAL)<< "Could not find ordinal for field " << descriptor->name(); - return -1; -} - -FieldGeneratorBase* MessageGenerator::CreateFieldGeneratorInternal( - const FieldDescriptor* descriptor) { - return CreateFieldGenerator(descriptor, GetFieldOrdinal(descriptor), this->options()); -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_message.h b/windows/include/google/protobuf/compiler/csharp/csharp_message.h deleted file mode 100644 index e7f3b4d00..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_message.h +++ /dev/null @@ -1,91 +0,0 @@ -// 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_CSHARP_MESSAGE_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_MESSAGE_H__ - -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -class FieldGeneratorBase; - -class MessageGenerator : public SourceGeneratorBase { - public: - MessageGenerator(const Descriptor* descriptor, const Options* options); - ~MessageGenerator(); - - void GenerateCloningCode(io::Printer* printer); - void GenerateFreezingCode(io::Printer* printer); - void GenerateFrameworkMethods(io::Printer* printer); - void Generate(io::Printer* printer); - - private: - const Descriptor* descriptor_; - std::vector field_names_; - std::vector fields_by_number_; - - void GenerateMessageSerializationMethods(io::Printer* printer); - void GenerateMergingMethods(io::Printer* printer); - - int GetFieldOrdinal(const FieldDescriptor* descriptor); - FieldGeneratorBase* CreateFieldGeneratorInternal( - const FieldDescriptor* descriptor); - - bool HasNestedGeneratedTypes(); - - void AddDeprecatedFlag(io::Printer* printer); - - std::string class_name(); - std::string full_class_name(); - - // field names sorted alphabetically - const std::vector& field_names(); - - // field descriptors sorted by number - const std::vector& fields_by_number(); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_MESSAGE_H__ diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_message_field.cc b/windows/include/google/protobuf/compiler/csharp/csharp_message_field.cc deleted file mode 100644 index cf1b4dbfe..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_message_field.cc +++ /dev/null @@ -1,208 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { - variables_["has_property_check"] = name() + "_ != null"; - variables_["has_not_property_check"] = name() + "_ == null"; -} - -MessageFieldGenerator::~MessageFieldGenerator() { - -} - -void MessageFieldGenerator::GenerateMembers(io::Printer* printer) { - printer->Print( - variables_, - "private $type_name$ $name$_;\n"); - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ $type_name$ $property_name$ {\n" - " get { return $name$_; }\n" - " set {\n" - " $name$_ = value;\n" - " }\n" - "}\n"); -} - -void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print( - variables_, - "if (other.$has_property_check$) {\n" - " if ($has_not_property_check$) {\n" - " $name$_ = new $type_name$();\n" - " }\n" - " $property_name$.MergeFrom(other.$property_name$);\n" - "}\n"); -} - -void MessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_not_property_check$) {\n" - " $name$_ = new $type_name$();\n" - "}\n" - // TODO(jonskeet): Do we really need merging behaviour like this? - "input.ReadMessage($name$_);\n"); // No need to support TYPE_GROUP... -} - -void MessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " output.WriteRawTag($tag_bytes$);\n" - " output.WriteMessage($property_name$);\n" - "}\n"); -} - -void MessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " size += $tag_size$ + pb::CodedOutputStream.ComputeMessageSize($property_name$);\n" - "}\n"); -} - -void MessageFieldGenerator::WriteHash(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"); -} -void MessageFieldGenerator::WriteEquals(io::Printer* printer) { - printer->Print( - variables_, - "if (!object.Equals($property_name$, other.$property_name$)) return false;\n"); -} -void MessageFieldGenerator::WriteToString(io::Printer* printer) { - variables_["field_name"] = GetFieldName(descriptor_); - printer->Print( - variables_, - "PrintField(\"$field_name$\", has$property_name$, $name$_, writer);\n"); -} - -void MessageFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$name$_ = other.$has_property_check$ ? other.$name$_.Clone() : null;\n"); -} - -void MessageFieldGenerator::GenerateFreezingCode(io::Printer* printer) { -} - -void MessageFieldGenerator::GenerateCodecCode(io::Printer* printer) { - printer->Print( - variables_, - "pb::FieldCodec.ForMessage($tag$, $type_name$.Parser)"); -} - -MessageOneofFieldGenerator::MessageOneofFieldGenerator( - const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options) - : MessageFieldGenerator(descriptor, fieldOrdinal, options) { - SetCommonOneofFieldVariables(&variables_); -} - -MessageOneofFieldGenerator::~MessageOneofFieldGenerator() { - -} - -void MessageOneofFieldGenerator::GenerateMembers(io::Printer* printer) { - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ $type_name$ $property_name$ {\n" - " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : null; }\n" - " set {\n" - " $oneof_name$_ = value;\n" - " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" - " }\n" - "}\n"); -} - -void MessageOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print(variables_, - "if ($property_name$ == null) {\n" - " $property_name$ = new $type_name$();\n" - "}\n" - "$property_name$.MergeFrom(other.$property_name$);\n"); -} - -void MessageOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { - // TODO(jonskeet): We may be able to do better than this - printer->Print( - variables_, - "$type_name$ subBuilder = new $type_name$();\n" - "if ($has_property_check$) {\n" - " subBuilder.MergeFrom($property_name$);\n" - "}\n" - "input.ReadMessage(subBuilder);\n" // No support of TYPE_GROUP - "$property_name$ = subBuilder;\n"); -} - -void MessageOneofFieldGenerator::WriteToString(io::Printer* printer) { - printer->Print( - variables_, - "PrintField(\"$descriptor_name$\", $has_property_check$, $oneof_name$_, writer);\n"); -} - -void MessageOneofFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$property_name$ = other.$property_name$.Clone();\n"); -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_message_field.h b/windows/include/google/protobuf/compiler/csharp/csharp_message_field.h deleted file mode 100644 index c41ee88a7..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_message_field.h +++ /dev/null @@ -1,91 +0,0 @@ -// 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_CSHARP_MESSAGE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_MESSAGE_FIELD_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -class MessageFieldGenerator : public FieldGeneratorBase { - public: - MessageFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~MessageFieldGenerator(); - - virtual void GenerateCodecCode(io::Printer* printer); - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateFreezingCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - virtual void WriteHash(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); -}; - -class MessageOneofFieldGenerator : public MessageFieldGenerator { - public: - MessageOneofFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~MessageOneofFieldGenerator(); - - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_MESSAGE_FIELD_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_names.h b/windows/include/google/protobuf/compiler/csharp/csharp_names.h index 21758f288..67e53b640 100644 --- a/windows/include/google/protobuf/compiler/csharp/csharp_names.h +++ b/windows/include/google/protobuf/compiler/csharp/csharp_names.h @@ -39,7 +39,10 @@ #define GOOGLE_PROTOBUF_COMPILER_CSHARP_NAMES_H__ #include -#include +#include +#include + +#include namespace google { namespace protobuf { @@ -57,14 +60,14 @@ namespace csharp { // // Returns: // The namespace to use for given file descriptor. -string LIBPROTOC_EXPORT GetFileNamespace(const FileDescriptor* descriptor); +std::string PROTOC_EXPORT GetFileNamespace(const FileDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified C# class name. -string LIBPROTOC_EXPORT GetClassName(const Descriptor* descriptor); +std::string PROTOC_EXPORT GetClassName(const Descriptor* descriptor); // Requires: // descriptor != NULL @@ -73,7 +76,8 @@ string LIBPROTOC_EXPORT GetClassName(const Descriptor* descriptor); // The fully-qualified name of the C# class that provides // access to the file descriptor. Proto compiler generates // such class for each .proto file processed. -string LIBPROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor); +std::string PROTOC_EXPORT +GetReflectionClassName(const FileDescriptor* descriptor); // Generates output file name for given file descriptor. If generate_directories // is true, the output file will be put under directory corresponding to file's @@ -89,16 +93,17 @@ string LIBPROTOC_EXPORT GetReflectionClassName(const FileDescriptor* descriptor) // The file name to use as output file for given file descriptor. In case // of failure, this function will return empty string and error parameter // will contain the error message. -string LIBPROTOC_EXPORT GetOutputFile( - const google::protobuf::FileDescriptor* descriptor, - const string file_extension, - const bool generate_directories, - const string base_namespace, - string* error); +std::string PROTOC_EXPORT GetOutputFile(const FileDescriptor* descriptor, + const std::string file_extension, + const bool generate_directories, + const std::string base_namespace, + std::string* error); } // namespace csharp } // namespace compiler } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_NAMES_H__ diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_options.h b/windows/include/google/protobuf/compiler/csharp/csharp_options.h index 426fb3b50..42ff6d866 100644 --- a/windows/include/google/protobuf/compiler/csharp/csharp_options.h +++ b/windows/include/google/protobuf/compiler/csharp/csharp_options.h @@ -33,7 +33,6 @@ #include -#include namespace google { namespace protobuf { namespace compiler { @@ -45,10 +44,11 @@ struct Options { file_extension(".cs"), base_namespace(""), base_namespace_specified(false), - internal_access(false) { + internal_access(false), + serializable(false) { } // Extension of the generated file. Defaults to ".cs" - string file_extension; + std::string file_extension; // Base namespace to use to create directory hierarchy. Defaults to "". // This option allows the simple creation of a conventional C# file layout, // where directories are created relative to a project-specific base @@ -59,7 +59,7 @@ struct Options { // // If no base namespace is specified, all files are generated in the // --csharp_out directory, with no subdirectories created automatically. - string base_namespace; + std::string base_namespace; // Whether the base namespace has been explicitly specified by the user. // This is required as the base namespace can be explicitly set to the empty // string, meaning "create a full directory hierarchy, starting from the first @@ -68,12 +68,14 @@ struct Options { // Whether the generated classes should have accessibility level of "internal". // Defaults to false that generates "public" classes. bool internal_access; + // Whether the generated classes should have a global::System.Serializable attribute added + // Defaults to false + bool serializable; }; } // namespace csharp } // namespace compiler } // namespace protobuf - - } // namespace google + #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_OPTIONS_H__ diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/windows/include/google/protobuf/compiler/csharp/csharp_primitive_field.cc deleted file mode 100644 index c3003e3d8..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ /dev/null @@ -1,230 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -PrimitiveFieldGenerator::PrimitiveFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { - // TODO(jonskeet): Make this cleaner... - is_value_type = descriptor->type() != FieldDescriptor::TYPE_STRING - && descriptor->type() != FieldDescriptor::TYPE_BYTES; - if (!is_value_type) { - variables_["has_property_check"] = variables_["property_name"] + ".Length != 0"; - variables_["other_has_property_check"] = "other." + variables_["property_name"] + ".Length != 0"; - } -} - -PrimitiveFieldGenerator::~PrimitiveFieldGenerator() { -} - -void PrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) { - // TODO(jonskeet): Work out whether we want to prevent the fields from ever being - // null, or whether we just handle it, in the cases of bytes and string. - // (Basically, should null-handling code be in the getter or the setter?) - printer->Print( - variables_, - "private $type_name$ $name_def_message$;\n"); - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ $type_name$ $property_name$ {\n" - " get { return $name$_; }\n" - " set {\n"); - if (is_value_type) { - printer->Print( - variables_, - " $name$_ = value;\n"); - } else { - printer->Print( - variables_, - " $name$_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n"); - } - printer->Print( - " }\n" - "}\n"); -} - -void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($other_has_property_check$) {\n" - " $property_name$ = other.$property_name$;\n" - "}\n"); -} - -void PrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { - // Note: invoke the property setter rather than writing straight to the field, - // so that we can normalize "null to empty" for strings and bytes. - printer->Print( - variables_, - "$property_name$ = input.Read$capitalized_type_name$();\n"); -} - -void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " output.WriteRawTag($tag_bytes$);\n" - " output.Write$capitalized_type_name$($property_name$);\n" - "}\n"); -} - -void PrimitiveFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n"); - printer->Indent(); - int fixedSize = GetFixedSize(descriptor_->type()); - if (fixedSize == -1) { - printer->Print( - variables_, - "size += $tag_size$ + pb::CodedOutputStream.Compute$capitalized_type_name$Size($property_name$);\n"); - } else { - printer->Print( - "size += $tag_size$ + $fixed_size$;\n", - "fixed_size", SimpleItoa(fixedSize), - "tag_size", variables_["tag_size"]); - } - printer->Outdent(); - printer->Print("}\n"); -} - -void PrimitiveFieldGenerator::WriteHash(io::Printer* printer) { - const char *text = "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"; - if (descriptor_->type() == FieldDescriptor::TYPE_FLOAT) { - text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode($property_name$);\n"; - } else if (descriptor_->type() == FieldDescriptor::TYPE_DOUBLE) { - text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode($property_name$);\n"; - } - printer->Print(variables_, text); -} -void PrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { - const char *text = "if ($property_name$ != other.$property_name$) return false;\n"; - if (descriptor_->type() == FieldDescriptor::TYPE_FLOAT) { - text = "if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n"; - } else if (descriptor_->type() == FieldDescriptor::TYPE_DOUBLE) { - text = "if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n"; - } - printer->Print(variables_, text); -} -void PrimitiveFieldGenerator::WriteToString(io::Printer* printer) { - printer->Print( - variables_, - "PrintField(\"$descriptor_name$\", $has_property_check$, $property_name$, writer);\n"); -} - -void PrimitiveFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$name$_ = other.$name$_;\n"); -} - -void PrimitiveFieldGenerator::GenerateCodecCode(io::Printer* printer) { - printer->Print( - variables_, - "pb::FieldCodec.For$capitalized_type_name$($tag$)"); -} - -PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : PrimitiveFieldGenerator(descriptor, fieldOrdinal, options) { - SetCommonOneofFieldVariables(&variables_); -} - -PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() { -} - -void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ $type_name$ $property_name$ {\n" - " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : $default_value$; }\n" - " set {\n"); - if (is_value_type) { - printer->Print( - variables_, - " $oneof_name$_ = value;\n"); - } else { - printer->Print( - variables_, - " $oneof_name$_ = pb::ProtoPreconditions.CheckNotNull(value, \"value\");\n"); - } - printer->Print( - variables_, - " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" - " }\n" - "}\n"); -} - -void PrimitiveOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print(variables_, "$property_name$ = other.$property_name$;\n"); -} - -void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) { - printer->Print(variables_, - "PrintField(\"$descriptor_name$\", $has_property_check$, $oneof_name$_, writer);\n"); -} - -void PrimitiveOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print( - variables_, - "$property_name$ = input.Read$capitalized_type_name$();\n"); -} - -void PrimitiveOneofFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$property_name$ = other.$property_name$;\n"); -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_primitive_field.h b/windows/include/google/protobuf/compiler/csharp/csharp_primitive_field.h deleted file mode 100644 index ca7b8b3da..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_primitive_field.h +++ /dev/null @@ -1,95 +0,0 @@ -// 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_CSHARP_PRIMITIVE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_PRIMITIVE_FIELD_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -struct Options; - -class PrimitiveFieldGenerator : public FieldGeneratorBase { - public: - PrimitiveFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~PrimitiveFieldGenerator(); - - virtual void GenerateCodecCode(io::Printer* printer); - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - virtual void WriteHash(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - - protected: - bool is_value_type; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); -}; - -class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator { - public: - PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~PrimitiveOneofFieldGenerator(); - - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveOneofFieldGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_PRIMITIVE_FIELD_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_reflection_class.cc b/windows/include/google/protobuf/compiler/csharp/csharp_reflection_class.cc deleted file mode 100644 index 5ddd616e1..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_reflection_class.cc +++ /dev/null @@ -1,292 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -ReflectionClassGenerator::ReflectionClassGenerator(const FileDescriptor* file, - const Options* options) - : SourceGeneratorBase(file, options), - file_(file) { - namespace_ = GetFileNamespace(file); - reflectionClassname_ = GetReflectionClassUnqualifiedName(file); -} - -ReflectionClassGenerator::~ReflectionClassGenerator() { -} - -void ReflectionClassGenerator::Generate(io::Printer* printer) { - WriteIntroduction(printer); - - WriteDescriptor(printer); - // Close the class declaration. - printer->Outdent(); - printer->Print("}\n"); - - // write children: Enums - if (file_->enum_type_count() > 0) { - printer->Print("#region Enums\n"); - for (int i = 0; i < file_->enum_type_count(); i++) { - EnumGenerator enumGenerator(file_->enum_type(i), this->options()); - enumGenerator.Generate(printer); - } - printer->Print("#endregion\n"); - printer->Print("\n"); - } - - // write children: Messages - if (file_->message_type_count() > 0) { - printer->Print("#region Messages\n"); - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator messageGenerator(file_->message_type(i), this->options()); - messageGenerator.Generate(printer); - } - printer->Print("#endregion\n"); - printer->Print("\n"); - } - - // TODO(jtattermusch): add insertion point for services. - - if (!namespace_.empty()) { - printer->Outdent(); - printer->Print("}\n"); - } - printer->Print("\n"); - printer->Print("#endregion Designer generated code\n"); -} - -void ReflectionClassGenerator::WriteIntroduction(io::Printer* printer) { - printer->Print( - "// \n" - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $file_name$\n" - "// \n" - "#pragma warning disable 1591, 0612, 3021\n" - "#region Designer generated code\n" - "\n" - "using pb = global::Google.Protobuf;\n" - "using pbc = global::Google.Protobuf.Collections;\n" - "using pbr = global::Google.Protobuf.Reflection;\n" - "using scg = global::System.Collections.Generic;\n", - "file_name", file_->name()); - - if (!namespace_.empty()) { - printer->Print("namespace $namespace$ {\n", "namespace", namespace_); - printer->Indent(); - printer->Print("\n"); - } - - printer->Print( - "/// Holder for reflection information generated from $file_name$\n" - "$access_level$ static partial class $reflection_class_name$ {\n" - "\n", - "file_name", file_->name(), - "access_level", class_access_level(), - "reflection_class_name", reflectionClassname_); - printer->Indent(); -} - -void ReflectionClassGenerator::WriteDescriptor(io::Printer* printer) { - printer->Print( - "#region Descriptor\n" - "/// File descriptor for $file_name$\n" - "public static pbr::FileDescriptor Descriptor {\n" - " get { return descriptor; }\n" - "}\n" - "private static pbr::FileDescriptor descriptor;\n" - "\n" - "static $reflection_class_name$() {\n", - "file_name", file_->name(), - "reflection_class_name", reflectionClassname_); - printer->Indent(); - printer->Print( - "byte[] descriptorData = global::System.Convert.FromBase64String(\n"); - printer->Indent(); - printer->Indent(); - printer->Print("string.Concat(\n"); - printer->Indent(); - - // TODO(jonskeet): Consider a C#-escaping format here instead of just Base64. - std::string base64 = FileDescriptorToBase64(file_); - while (base64.size() > 60) { - printer->Print("\"$base64$\",\n", "base64", base64.substr(0, 60)); - base64 = base64.substr(60); - } - printer->Print("\"$base64$\"));\n", "base64", base64); - printer->Outdent(); - printer->Outdent(); - printer->Outdent(); - - // ----------------------------------------------------------------- - // Invoke InternalBuildGeneratedFileFrom() to build the file. - printer->Print( - "descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,\n"); - printer->Print(" new pbr::FileDescriptor[] { "); - for (int i = 0; i < file_->dependency_count(); i++) { - // descriptor.proto is special: we don't allow access to the generated code, but there's - // a separately-exposed property to get at the file descriptor, specifically to allow this - // kind of dependency. - if (IsDescriptorProto(file_->dependency(i))) { - printer->Print("pbr::FileDescriptor.DescriptorProtoFileDescriptor, "); - } else { - printer->Print( - "$full_reflection_class_name$.Descriptor, ", - "full_reflection_class_name", - GetReflectionClassName(file_->dependency(i))); - } - } - printer->Print("},\n" - " new pbr::GeneratedClrTypeInfo("); - // Specify all the generated code information, recursively. - if (file_->enum_type_count() > 0) { - printer->Print("new[] {"); - for (int i = 0; i < file_->enum_type_count(); i++) { - printer->Print("typeof($type_name$), ", "type_name", GetClassName(file_->enum_type(i))); - } - printer->Print("}, "); - } - else { - printer->Print("null, "); - } - if (file_->message_type_count() > 0) { - printer->Print("new pbr::GeneratedClrTypeInfo[] {\n"); - printer->Indent(); - printer->Indent(); - printer->Indent(); - for (int i = 0; i < file_->message_type_count(); i++) { - WriteGeneratedCodeInfo(file_->message_type(i), printer, i == file_->message_type_count() - 1); - } - printer->Outdent(); - printer->Print("\n}));\n"); - printer->Outdent(); - printer->Outdent(); - } - else { - printer->Print("null));\n"); - } - - printer->Outdent(); - printer->Print("}\n"); - printer->Print("#endregion\n\n"); -} - -// Write out the generated code for a particular message. This consists of the CLR type, property names -// corresponding to fields, names corresponding to oneofs, nested enums, and nested types. Each array part -// can be specified as null if it would be empty, to make the generated code somewhat simpler to read. -// We write a line break at the end of each generated code info, so that in the final file we'll see all -// the types, pre-ordered depth first, one per line. The indentation will be slightly unusual, -// in that it will look like a single array when it's actually constructing a tree, but it'll be easy to -// read even with multiple levels of nesting. -// The "last" parameter indicates whether this message descriptor is the last one being printed in this immediate -// context. It governs whether or not a trailing comma and newline is written after the constructor, effectively -// just controlling the formatting in the generated code. -void ReflectionClassGenerator::WriteGeneratedCodeInfo(const Descriptor* descriptor, io::Printer* printer, bool last) { - if (IsMapEntryMessage(descriptor)) { - printer->Print("null, "); - return; - } - // Generated message type - printer->Print("new pbr::GeneratedClrTypeInfo(typeof($type_name$), $type_name$.Parser, ", "type_name", GetClassName(descriptor)); - - // Fields - if (descriptor->field_count() > 0) { - std::vector fields; - for (int i = 0; i < descriptor->field_count(); i++) { - fields.push_back(GetPropertyName(descriptor->field(i))); - } - printer->Print("new[]{ \"$fields$\" }, ", "fields", JoinStrings(fields, "\", \"")); - } - else { - printer->Print("null, "); - } - - // Oneofs - if (descriptor->oneof_decl_count() > 0) { - std::vector oneofs; - for (int i = 0; i < descriptor->oneof_decl_count(); i++) { - oneofs.push_back(UnderscoresToCamelCase(descriptor->oneof_decl(i)->name(), true)); - } - printer->Print("new[]{ \"$oneofs$\" }, ", "oneofs", JoinStrings(oneofs, "\", \"")); - } - else { - printer->Print("null, "); - } - - // Nested enums - if (descriptor->enum_type_count() > 0) { - std::vector enums; - for (int i = 0; i < descriptor->enum_type_count(); i++) { - enums.push_back(GetClassName(descriptor->enum_type(i))); - } - printer->Print("new[]{ typeof($enums$) }, ", "enums", JoinStrings(enums, "), typeof(")); - } - else { - printer->Print("null, "); - } - - // Nested types - if (descriptor->nested_type_count() > 0) { - // Need to specify array type explicitly here, as all elements may be null. - printer->Print("new pbr::GeneratedClrTypeInfo[] { "); - for (int i = 0; i < descriptor->nested_type_count(); i++) { - WriteGeneratedCodeInfo(descriptor->nested_type(i), printer, i == descriptor->nested_type_count() - 1); - } - printer->Print("}"); - } - else { - printer->Print("null"); - } - printer->Print(last ? ")" : "),\n"); -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/windows/include/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc deleted file mode 100644 index 683c4b0b7..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ /dev/null @@ -1,127 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { -} - -RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() { - -} - -void RepeatedEnumFieldGenerator::GenerateMembers(io::Printer* printer) { - printer->Print( - variables_, - "private static readonly pb::FieldCodec<$type_name$> _repeated_$name$_codec\n" - " = pb::FieldCodec.ForEnum($tag$, x => (int) x, x => ($type_name$) x);\n"); - printer->Print(variables_, - "private readonly pbc::RepeatedField<$type_name$> $name$_ = new pbc::RepeatedField<$type_name$>();\n"); - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ pbc::RepeatedField<$type_name$> $property_name$ {\n" - " get { return $name$_; }\n" - "}\n"); -} - -void RepeatedEnumFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.Add(other.$name$_);\n"); -} - -void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.AddEntriesFrom(input, _repeated_$name$_codec);\n"); -} - -void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.WriteTo(output, _repeated_$name$_codec);\n"); -} - -void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "size += $name$_.CalculateSize(_repeated_$name$_codec);\n"); -} - -void RepeatedEnumFieldGenerator::WriteHash(io::Printer* printer) { - printer->Print( - variables_, - "hash ^= $name$_.GetHashCode();\n"); -} - -void RepeatedEnumFieldGenerator::WriteEquals(io::Printer* printer) { - printer->Print( - variables_, - "if(!$name$_.Equals(other.$name$_)) return false;\n"); -} - -void RepeatedEnumFieldGenerator::WriteToString(io::Printer* printer) { - printer->Print(variables_, - "PrintField(\"$descriptor_name$\", $name$_, writer);\n"); -} - -void RepeatedEnumFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$name$_ = other.$name$_.Clone();\n"); -} - -void RepeatedEnumFieldGenerator::GenerateFreezingCode(io::Printer* printer) { -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h b/windows/include/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h deleted file mode 100644 index 819b58326..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h +++ /dev/null @@ -1,75 +0,0 @@ -// 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_CSHARP_REPEATED_ENUM_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_REPEATED_ENUM_FIELD_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -// TODO(jonskeet): Refactor repeated field support; all the implementations are *really* similar. We -// should probably have a RepeatedFieldGeneratorBase. -class RepeatedEnumFieldGenerator : public FieldGeneratorBase { - public: - RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~RepeatedEnumFieldGenerator(); - - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateFreezingCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - virtual void WriteHash(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_REPEATED_ENUM_FIELD_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/windows/include/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc deleted file mode 100644 index 90af569c4..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ /dev/null @@ -1,144 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { -} - -RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() { - -} - -void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) { - printer->Print( - variables_, - "private static readonly pb::FieldCodec<$type_name$> _repeated_$name$_codec\n" - " = "); - // Don't want to duplicate the codec code here... maybe we should have a - // "create single field generator for this repeated field" - // function, but it doesn't seem worth it for just this. - if (IsWrapperType(descriptor_)) { - std::unique_ptr single_generator( - new WrapperFieldGenerator(descriptor_, fieldOrdinal_, this->options())); - single_generator->GenerateCodecCode(printer); - } else { - std::unique_ptr single_generator( - new MessageFieldGenerator(descriptor_, fieldOrdinal_, this->options())); - single_generator->GenerateCodecCode(printer); - } - printer->Print(";\n"); - printer->Print( - variables_, - "private readonly pbc::RepeatedField<$type_name$> $name$_ = new pbc::RepeatedField<$type_name$>();\n"); - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ pbc::RepeatedField<$type_name$> $property_name$ {\n" - " get { return $name$_; }\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.Add(other.$name$_);\n"); -} - -void RepeatedMessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.AddEntriesFrom(input, _repeated_$name$_codec);\n"); -} - -void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.WriteTo(output, _repeated_$name$_codec);\n"); -} - -void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "size += $name$_.CalculateSize(_repeated_$name$_codec);\n"); -} - -void RepeatedMessageFieldGenerator::WriteHash(io::Printer* printer) { - printer->Print( - variables_, - "hash ^= $name$_.GetHashCode();\n"); -} - -void RepeatedMessageFieldGenerator::WriteEquals(io::Printer* printer) { - printer->Print( - variables_, - "if(!$name$_.Equals(other.$name$_)) return false;\n"); -} - -void RepeatedMessageFieldGenerator::WriteToString(io::Printer* printer) { - variables_["field_name"] = GetFieldName(descriptor_); - printer->Print( - variables_, - "PrintField(\"$field_name$\", $name$_, writer);\n"); -} - -void RepeatedMessageFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$name$_ = other.$name$_.Clone();\n"); -} - -void RepeatedMessageFieldGenerator::GenerateFreezingCode(io::Printer* printer) { -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_message_field.h b/windows/include/google/protobuf/compiler/csharp/csharp_repeated_message_field.h deleted file mode 100644 index 6e33648b6..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_message_field.h +++ /dev/null @@ -1,75 +0,0 @@ -// 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_CSHARP_REPEATED_MESSAGE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_REPEATED_MESSAGE_FIELD_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -struct Options; - -class RepeatedMessageFieldGenerator : public FieldGeneratorBase { - public: - RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~RepeatedMessageFieldGenerator(); - - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateFreezingCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - virtual void WriteHash(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_REPEATED_MESSAGE_FIELD_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/windows/include/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc deleted file mode 100644 index cd91506ff..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ /dev/null @@ -1,125 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { -} - -RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() { - -} - -void RepeatedPrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) { - printer->Print( - variables_, - "private static readonly pb::FieldCodec<$type_name$> _repeated_$name$_codec\n" - " = pb::FieldCodec.For$capitalized_type_name$($tag$);\n"); - printer->Print(variables_, - "private readonly pbc::RepeatedField<$type_name$> $name$_ = new pbc::RepeatedField<$type_name$>();\n"); - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ pbc::RepeatedField<$type_name$> $property_name$ {\n" - " get { return $name$_; }\n" - "}\n"); -} - -void RepeatedPrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.Add(other.$name$_);\n"); -} - -void RepeatedPrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.AddEntriesFrom(input, _repeated_$name$_codec);\n"); -} - -void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "$name$_.WriteTo(output, _repeated_$name$_codec);\n"); -} - -void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "size += $name$_.CalculateSize(_repeated_$name$_codec);\n"); -} - -void RepeatedPrimitiveFieldGenerator::WriteHash(io::Printer* printer) { - printer->Print( - variables_, - "hash ^= $name$_.GetHashCode();\n"); -} -void RepeatedPrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { - printer->Print( - variables_, - "if(!$name$_.Equals(other.$name$_)) return false;\n"); -} -void RepeatedPrimitiveFieldGenerator::WriteToString(io::Printer* printer) { - printer->Print(variables_, - "PrintField(\"$descriptor_name$\", $name$_, writer);\n"); -} - -void RepeatedPrimitiveFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$name$_ = other.$name$_.Clone();\n"); -} - -void RepeatedPrimitiveFieldGenerator::GenerateFreezingCode(io::Printer* printer) { -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h b/windows/include/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h deleted file mode 100644 index a59348a95..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h +++ /dev/null @@ -1,71 +0,0 @@ -// 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_CSHARP_REPEATED_PRIMITIVE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_REPEATED_PRIMITIVE_FIELD_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -class RepeatedPrimitiveFieldGenerator : public FieldGeneratorBase { - public: - RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options); - ~RepeatedPrimitiveFieldGenerator(); - - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateFreezingCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - virtual void WriteHash(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_REPEATED_PRIMITIVE_FIELD_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_source_generator_base.cc b/windows/include/google/protobuf/compiler/csharp/csharp_source_generator_base.cc deleted file mode 100644 index 1fda7ddf3..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_source_generator_base.cc +++ /dev/null @@ -1,73 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -SourceGeneratorBase::SourceGeneratorBase(const FileDescriptor* descriptor, - const Options *options) - : descriptor_(descriptor), options_(options) { -} - -SourceGeneratorBase::~SourceGeneratorBase() { -} - -void SourceGeneratorBase::WriteGeneratedCodeAttributes(io::Printer* printer) { - printer->Print("[global::System.Diagnostics.DebuggerNonUserCodeAttribute]\n"); -} - -std::string SourceGeneratorBase::class_access_level() { - return (IsDescriptorProto(descriptor_) || this->options()->internal_access) ? "internal" : "public"; -} - -const Options* SourceGeneratorBase::options() { - return this->options_; -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_source_generator_base.h b/windows/include/google/protobuf/compiler/csharp/csharp_source_generator_base.h deleted file mode 100644 index c741080ed..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_source_generator_base.h +++ /dev/null @@ -1,70 +0,0 @@ -// 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_CSHARP_SOURCE_GENERATOR_BASE_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_SOURCE_GENERATOR_BASE_H__ - -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -struct Options; - -class SourceGeneratorBase { - protected: - SourceGeneratorBase(const FileDescriptor* descriptor, const Options* options); - virtual ~SourceGeneratorBase(); - - std::string class_access_level(); - const Options* options(); - - // Write any attributes used to decorate generated function members (methods and properties). - // Should not be used to decorate types. - void WriteGeneratedCodeAttributes(io::Printer* printer); - - private: - const FileDescriptor* descriptor_; - const Options *options_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceGeneratorBase); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_SOURCE_GENERATOR_BASE_H__ - diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_wrapper_field.cc b/windows/include/google/protobuf/compiler/csharp/csharp_wrapper_field.cc deleted file mode 100644 index 047edf734..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_wrapper_field.cc +++ /dev/null @@ -1,225 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -WrapperFieldGenerator::WrapperFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, const Options *options) - : FieldGeneratorBase(descriptor, fieldOrdinal, options) { - variables_["has_property_check"] = name() + "_ != null"; - variables_["has_not_property_check"] = name() + "_ == null"; - const FieldDescriptor* wrapped_field = descriptor->message_type()->field(0); - is_value_type = wrapped_field->type() != FieldDescriptor::TYPE_STRING && - wrapped_field->type() != FieldDescriptor::TYPE_BYTES; - if (is_value_type) { - variables_["nonnullable_type_name"] = type_name(wrapped_field); - } -} - -WrapperFieldGenerator::~WrapperFieldGenerator() { -} - -void WrapperFieldGenerator::GenerateMembers(io::Printer* printer) { - printer->Print( - variables_, - "private static readonly pb::FieldCodec<$type_name$> _single_$name$_codec = "); - GenerateCodecCode(printer); - printer->Print( - variables_, - ";\n" - "private $type_name$ $name$_;\n"); - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ $type_name$ $property_name$ {\n" - " get { return $name$_; }\n" - " set {\n" - " $name$_ = value;\n" - " }\n" - "}\n"); -} - -void WrapperFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print( - variables_, - "if (other.$has_property_check$) {\n" - " if ($has_not_property_check$ || other.$property_name$ != $default_value$) {\n" - " $property_name$ = other.$property_name$;\n" - " }\n" - "}\n"); -} - -void WrapperFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print( - variables_, - "$type_name$ value = _single_$name$_codec.Read(input);\n" - "if ($has_not_property_check$ || value != $default_value$) {\n" - " $property_name$ = value;\n" - "}\n"); -} - -void WrapperFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " _single_$name$_codec.WriteTagAndValue(output, $property_name$);\n" - "}\n"); -} - -void WrapperFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " size += _single_$name$_codec.CalculateSizeWithTag($property_name$);\n" - "}\n"); -} - -void WrapperFieldGenerator::WriteHash(io::Printer* printer) { - const char *text = "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"; - if (descriptor_->message_type()->field(0)->type() == FieldDescriptor::TYPE_FLOAT) { - text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseNullableSingleEqualityComparer.GetHashCode($property_name$);\n"; - } - else if (descriptor_->message_type()->field(0)->type() == FieldDescriptor::TYPE_DOUBLE) { - text = "if ($has_property_check$) hash ^= pbc::ProtobufEqualityComparers.BitwiseNullableDoubleEqualityComparer.GetHashCode($property_name$);\n"; - } - printer->Print(variables_, text); -} - -void WrapperFieldGenerator::WriteEquals(io::Printer* printer) { - const char *text = "if ($property_name$ != other.$property_name$) return false;\n"; - if (descriptor_->message_type()->field(0)->type() == FieldDescriptor::TYPE_FLOAT) { - text = "if (!pbc::ProtobufEqualityComparers.BitwiseNullableSingleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n"; - } - else if (descriptor_->message_type()->field(0)->type() == FieldDescriptor::TYPE_DOUBLE) { - text = "if (!pbc::ProtobufEqualityComparers.BitwiseNullableDoubleEqualityComparer.Equals($property_name$, other.$property_name$)) return false;\n"; - } - printer->Print(variables_, text); -} - -void WrapperFieldGenerator::WriteToString(io::Printer* printer) { - // TODO: Implement if we ever actually need it... -} - -void WrapperFieldGenerator::GenerateCloningCode(io::Printer* printer) { - printer->Print(variables_, - "$property_name$ = other.$property_name$;\n"); -} - -void WrapperFieldGenerator::GenerateCodecCode(io::Printer* printer) { - if (is_value_type) { - printer->Print( - variables_, - "pb::FieldCodec.ForStructWrapper<$nonnullable_type_name$>($tag$)"); - } else { - printer->Print( - variables_, - "pb::FieldCodec.ForClassWrapper<$type_name$>($tag$)"); - } -} - -WrapperOneofFieldGenerator::WrapperOneofFieldGenerator( - const FieldDescriptor* descriptor, int fieldOrdinal, const Options *options) - : WrapperFieldGenerator(descriptor, fieldOrdinal, options) { - SetCommonOneofFieldVariables(&variables_); -} - -WrapperOneofFieldGenerator::~WrapperOneofFieldGenerator() { -} - -void WrapperOneofFieldGenerator::GenerateMembers(io::Printer* printer) { - // Note: deliberately _oneof_$name$_codec, not _$oneof_name$_codec... we have one codec per field. - printer->Print( - variables_, - "private static readonly pb::FieldCodec<$type_name$> _oneof_$name$_codec = "); - GenerateCodecCode(printer); - printer->Print(";\n"); - WritePropertyDocComment(printer, descriptor_); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "$access_level$ $type_name$ $property_name$ {\n" - " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : ($type_name$) null; }\n" - " set {\n" - " $oneof_name$_ = value;\n" - " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" - " }\n" - "}\n"); -} - -void WrapperOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) { - printer->Print(variables_, "$property_name$ = other.$property_name$;\n"); -} - -void WrapperOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { - printer->Print( - variables_, - "$property_name$ = _oneof_$name$_codec.Read(input);\n"); -} - -void WrapperOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - // TODO: I suspect this is wrong... - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " _oneof_$name$_codec.WriteTagAndValue(output, ($type_name$) $oneof_name$_);\n" - "}\n"); -} - -void WrapperOneofFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - // TODO: I suspect this is wrong... - printer->Print( - variables_, - "if ($has_property_check$) {\n" - " size += _oneof_$name$_codec.CalculateSizeWithTag($property_name$);\n" - "}\n"); -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_wrapper_field.h b/windows/include/google/protobuf/compiler/csharp/csharp_wrapper_field.h deleted file mode 100644 index 452531fbf..000000000 --- a/windows/include/google/protobuf/compiler/csharp/csharp_wrapper_field.h +++ /dev/null @@ -1,92 +0,0 @@ -// 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_CSHARP_WRAPPER_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_WRAPPER_FIELD_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -struct Options; - -class WrapperFieldGenerator : public FieldGeneratorBase { - public: - WrapperFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~WrapperFieldGenerator(); - - virtual void GenerateCodecCode(io::Printer* printer); - virtual void GenerateCloningCode(io::Printer* printer); - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - virtual void WriteHash(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - - private: - bool is_value_type; // True for int32 etc; false for bytes and string - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(WrapperFieldGenerator); -}; - -class WrapperOneofFieldGenerator : public WrapperFieldGenerator { - public: - WrapperOneofFieldGenerator(const FieldDescriptor* descriptor, - int fieldOrdinal, - const Options *options); - ~WrapperOneofFieldGenerator(); - - virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateParsingCode(io::Printer* printer); - virtual void GenerateSerializationCode(io::Printer* printer); - virtual void GenerateSerializedSizeCode(io::Printer* printer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(WrapperOneofFieldGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_WRAPPER_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/importer.cc b/windows/include/google/protobuf/compiler/importer.cc deleted file mode 100644 index c3831e72a..000000000 --- a/windows/include/google/protobuf/compiler/importer.cc +++ /dev/null @@ -1,498 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifdef _MSC_VER -#include -#else -#include -#endif -#include -#include -#include -#include - -#include -#include - -#include - -#include -#include -#include -#include - - -#include - -#ifdef _WIN32 -#include -#endif - -namespace google { -namespace protobuf { -namespace compiler { - -#ifdef _WIN32 -// DO NOT include , instead create functions in io_win32.{h,cc} and import -// them like we do below. -using google::protobuf::internal::win32::access; -using google::protobuf::internal::win32::open; -#endif - -// Returns true if the text looks like a Windows-style absolute path, starting -// with a drive letter. Example: "C:\foo". TODO(kenton): Share this with -// copy in command_line_interface.cc? -static bool IsWindowsAbsolutePath(const string& text) { -#if defined(_WIN32) || defined(__CYGWIN__) - return text.size() >= 3 && text[1] == ':' && - isalpha(text[0]) && - (text[2] == '/' || text[2] == '\\') && - text.find_last_of(':') == 1; -#else - return false; -#endif -} - -MultiFileErrorCollector::~MultiFileErrorCollector() {} - -// This class serves two purposes: -// - It implements the ErrorCollector interface (used by Tokenizer and Parser) -// in terms of MultiFileErrorCollector, using a particular filename. -// - It lets us check if any errors have occurred. -class SourceTreeDescriptorDatabase::SingleFileErrorCollector - : public io::ErrorCollector { - public: - SingleFileErrorCollector(const string& filename, - MultiFileErrorCollector* multi_file_error_collector) - : filename_(filename), - multi_file_error_collector_(multi_file_error_collector), - had_errors_(false) {} - ~SingleFileErrorCollector() {} - - bool had_errors() { return had_errors_; } - - // implements ErrorCollector --------------------------------------- - void AddError(int line, int column, const string& message) { - if (multi_file_error_collector_ != NULL) { - multi_file_error_collector_->AddError(filename_, line, column, message); - } - had_errors_ = true; - } - - private: - string filename_; - MultiFileErrorCollector* multi_file_error_collector_; - bool had_errors_; -}; - -// =================================================================== - -SourceTreeDescriptorDatabase::SourceTreeDescriptorDatabase( - SourceTree* source_tree) - : source_tree_(source_tree), - error_collector_(NULL), - using_validation_error_collector_(false), - validation_error_collector_(this) {} - -SourceTreeDescriptorDatabase::~SourceTreeDescriptorDatabase() {} - -bool SourceTreeDescriptorDatabase::FindFileByName( - const string& filename, FileDescriptorProto* output) { - std::unique_ptr input(source_tree_->Open(filename)); - if (input == NULL) { - if (error_collector_ != NULL) { - error_collector_->AddError(filename, -1, 0, - source_tree_->GetLastErrorMessage()); - } - return false; - } - - // Set up the tokenizer and parser. - SingleFileErrorCollector file_error_collector(filename, error_collector_); - io::Tokenizer tokenizer(input.get(), &file_error_collector); - - Parser parser; - if (error_collector_ != NULL) { - parser.RecordErrorsTo(&file_error_collector); - } - if (using_validation_error_collector_) { - parser.RecordSourceLocationsTo(&source_locations_); - } - - // Parse it. - output->set_name(filename); - return parser.Parse(&tokenizer, output) && - !file_error_collector.had_errors(); -} - -bool SourceTreeDescriptorDatabase::FindFileContainingSymbol( - const string& symbol_name, FileDescriptorProto* output) { - return false; -} - -bool SourceTreeDescriptorDatabase::FindFileContainingExtension( - const string& containing_type, int field_number, - FileDescriptorProto* output) { - return false; -} - -// ------------------------------------------------------------------- - -SourceTreeDescriptorDatabase::ValidationErrorCollector:: -ValidationErrorCollector(SourceTreeDescriptorDatabase* owner) - : owner_(owner) {} - -SourceTreeDescriptorDatabase::ValidationErrorCollector:: -~ValidationErrorCollector() {} - -void SourceTreeDescriptorDatabase::ValidationErrorCollector::AddError( - const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { - if (owner_->error_collector_ == NULL) return; - - int line, column; - owner_->source_locations_.Find(descriptor, location, &line, &column); - owner_->error_collector_->AddError(filename, line, column, message); -} - -void SourceTreeDescriptorDatabase::ValidationErrorCollector::AddWarning( - const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { - if (owner_->error_collector_ == NULL) return; - - int line, column; - owner_->source_locations_.Find(descriptor, location, &line, &column); - owner_->error_collector_->AddWarning(filename, line, column, message); -} - -// =================================================================== - -Importer::Importer(SourceTree* source_tree, - MultiFileErrorCollector* error_collector) - : database_(source_tree), - pool_(&database_, database_.GetValidationErrorCollector()) { - pool_.EnforceWeakDependencies(true); - database_.RecordErrorsTo(error_collector); -} - -Importer::~Importer() {} - -const FileDescriptor* Importer::Import(const string& filename) { - return pool_.FindFileByName(filename); -} - -void Importer::AddUnusedImportTrackFile(const string& file_name) { - pool_.AddUnusedImportTrackFile(file_name); -} - -void Importer::ClearUnusedImportTrackFiles() { - pool_.ClearUnusedImportTrackFiles(); -} - - -// =================================================================== - -SourceTree::~SourceTree() {} - -string SourceTree::GetLastErrorMessage() { - return "File not found."; -} - -DiskSourceTree::DiskSourceTree() {} - -DiskSourceTree::~DiskSourceTree() {} - -static inline char LastChar(const string& str) { - return str[str.size() - 1]; -} - -// Given a path, returns an equivalent path with these changes: -// - On Windows, any backslashes are replaced with forward slashes. -// - Any instances of the directory "." are removed. -// - Any consecutive '/'s are collapsed into a single slash. -// Note that the resulting string may be empty. -// -// TODO(kenton): It would be nice to handle "..", e.g. so that we can figure -// out that "foo/bar.proto" is inside "baz/../foo". However, if baz is a -// symlink or doesn't exist, then things get complicated, and we can't -// actually determine this without investigating the filesystem, probably -// in non-portable ways. So, we punt. -// -// TODO(kenton): It would be nice to use realpath() here except that it -// resolves symbolic links. This could cause problems if people place -// symbolic links in their source tree. For example, if you executed: -// protoc --proto_path=foo foo/bar/baz.proto -// then if foo/bar is a symbolic link, foo/bar/baz.proto will canonicalize -// to a path which does not appear to be under foo, and thus the compiler -// will complain that baz.proto is not inside the --proto_path. -static string CanonicalizePath(string path) { -#ifdef _WIN32 - // The Win32 API accepts forward slashes as a path delimiter even though - // backslashes are standard. Let's avoid confusion and use only forward - // slashes. - if (HasPrefixString(path, "\\\\")) { - // Avoid converting two leading backslashes. - path = "\\\\" + StringReplace(path.substr(2), "\\", "/", true); - } else { - path = StringReplace(path, "\\", "/", true); - } -#endif - - std::vector canonical_parts; - std::vector parts = Split( - path, "/", true); // Note: Removes empty parts. - for (int i = 0; i < parts.size(); i++) { - if (parts[i] == ".") { - // Ignore. - } else { - canonical_parts.push_back(parts[i]); - } - } - string result = Join(canonical_parts, "/"); - if (!path.empty() && path[0] == '/') { - // Restore leading slash. - result = '/' + result; - } - if (!path.empty() && LastChar(path) == '/' && - !result.empty() && LastChar(result) != '/') { - // Restore trailing slash. - result += '/'; - } - return result; -} - -static inline bool ContainsParentReference(const string& path) { - return path == ".." || HasPrefixString(path, "../") || - HasSuffixString(path, "/..") || path.find("/../") != string::npos; -} - -// Maps a file from an old location to a new one. Typically, old_prefix is -// a virtual path and new_prefix is its corresponding disk path. Returns -// false if the filename did not start with old_prefix, otherwise replaces -// old_prefix with new_prefix and stores the result in *result. Examples: -// string result; -// assert(ApplyMapping("foo/bar", "", "baz", &result)); -// assert(result == "baz/foo/bar"); -// -// assert(ApplyMapping("foo/bar", "foo", "baz", &result)); -// assert(result == "baz/bar"); -// -// assert(ApplyMapping("foo", "foo", "bar", &result)); -// assert(result == "bar"); -// -// assert(!ApplyMapping("foo/bar", "baz", "qux", &result)); -// assert(!ApplyMapping("foo/bar", "baz", "qux", &result)); -// assert(!ApplyMapping("foobar", "foo", "baz", &result)); -static bool ApplyMapping(const string& filename, - const string& old_prefix, - const string& new_prefix, - string* result) { - if (old_prefix.empty()) { - // old_prefix matches any relative path. - if (ContainsParentReference(filename)) { - // We do not allow the file name to use "..". - return false; - } - if (HasPrefixString(filename, "/") || IsWindowsAbsolutePath(filename)) { - // This is an absolute path, so it isn't matched by the empty string. - return false; - } - result->assign(new_prefix); - if (!result->empty()) result->push_back('/'); - result->append(filename); - return true; - } else if (HasPrefixString(filename, old_prefix)) { - // old_prefix is a prefix of the filename. Is it the whole filename? - if (filename.size() == old_prefix.size()) { - // Yep, it's an exact match. - *result = new_prefix; - return true; - } else { - // Not an exact match. Is the next character a '/'? Otherwise, - // this isn't actually a match at all. E.g. the prefix "foo/bar" - // does not match the filename "foo/barbaz". - int after_prefix_start = -1; - if (filename[old_prefix.size()] == '/') { - after_prefix_start = old_prefix.size() + 1; - } else if (filename[old_prefix.size() - 1] == '/') { - // old_prefix is never empty, and canonicalized paths never have - // consecutive '/' characters. - after_prefix_start = old_prefix.size(); - } - if (after_prefix_start != -1) { - // Yep. So the prefixes are directories and the filename is a file - // inside them. - string after_prefix = filename.substr(after_prefix_start); - if (ContainsParentReference(after_prefix)) { - // We do not allow the file name to use "..". - return false; - } - result->assign(new_prefix); - if (!result->empty()) result->push_back('/'); - result->append(after_prefix); - return true; - } - } - } - - return false; -} - -void DiskSourceTree::MapPath(const string& virtual_path, - const string& disk_path) { - mappings_.push_back(Mapping(virtual_path, CanonicalizePath(disk_path))); -} - -DiskSourceTree::DiskFileToVirtualFileResult -DiskSourceTree::DiskFileToVirtualFile( - const string& disk_file, - string* virtual_file, - string* shadowing_disk_file) { - int mapping_index = -1; - string canonical_disk_file = CanonicalizePath(disk_file); - - for (int i = 0; i < mappings_.size(); i++) { - // Apply the mapping in reverse. - if (ApplyMapping(canonical_disk_file, mappings_[i].disk_path, - mappings_[i].virtual_path, virtual_file)) { - // Success. - mapping_index = i; - break; - } - } - - if (mapping_index == -1) { - return NO_MAPPING; - } - - // Iterate through all mappings with higher precedence and verify that none - // of them map this file to some other existing file. - for (int i = 0; i < mapping_index; i++) { - if (ApplyMapping(*virtual_file, mappings_[i].virtual_path, - mappings_[i].disk_path, shadowing_disk_file)) { - if (access(shadowing_disk_file->c_str(), F_OK) >= 0) { - // File exists. - return SHADOWED; - } - } - } - shadowing_disk_file->clear(); - - // Verify that we can open the file. Note that this also has the side-effect - // of verifying that we are not canonicalizing away any non-existent - // directories. - std::unique_ptr stream(OpenDiskFile(disk_file)); - if (stream == NULL) { - return CANNOT_OPEN; - } - - return SUCCESS; -} - -bool DiskSourceTree::VirtualFileToDiskFile(const string& virtual_file, - string* disk_file) { - std::unique_ptr stream( - OpenVirtualFile(virtual_file, disk_file)); - return stream != NULL; -} - -io::ZeroCopyInputStream* DiskSourceTree::Open(const string& filename) { - return OpenVirtualFile(filename, NULL); -} - -string DiskSourceTree::GetLastErrorMessage() { - return last_error_message_; -} - -io::ZeroCopyInputStream* DiskSourceTree::OpenVirtualFile( - const string& virtual_file, - string* disk_file) { - if (virtual_file != CanonicalizePath(virtual_file) || - ContainsParentReference(virtual_file)) { - // We do not allow importing of paths containing things like ".." or - // consecutive slashes since the compiler expects files to be uniquely - // identified by file name. - last_error_message_ = "Backslashes, consecutive slashes, \".\", or \"..\" " - "are not allowed in the virtual path"; - return NULL; - } - - for (int i = 0; i < mappings_.size(); i++) { - string temp_disk_file; - if (ApplyMapping(virtual_file, mappings_[i].virtual_path, - mappings_[i].disk_path, &temp_disk_file)) { - io::ZeroCopyInputStream* stream = OpenDiskFile(temp_disk_file); - if (stream != NULL) { - if (disk_file != NULL) { - *disk_file = temp_disk_file; - } - return stream; - } - - if (errno == EACCES) { - // The file exists but is not readable. - last_error_message_ = "Read access is denied for file: " + - temp_disk_file; - return NULL; - } - } - } - last_error_message_ = "File not found."; - return NULL; -} - -io::ZeroCopyInputStream* DiskSourceTree::OpenDiskFile( - const string& filename) { - int file_descriptor; - do { - file_descriptor = open(filename.c_str(), O_RDONLY); - } while (file_descriptor < 0 && errno == EINTR); - if (file_descriptor >= 0) { - io::FileInputStream* result = new io::FileInputStream(file_descriptor); - result->SetCloseOnDelete(true); - return result; - } else { - return NULL; - } -} - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/importer.h b/windows/include/google/protobuf/compiler/importer.h index a4ffcf87d..08a49c552 100644 --- a/windows/include/google/protobuf/compiler/importer.h +++ b/windows/include/google/protobuf/compiler/importer.h @@ -37,18 +37,22 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__ #define GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__ -#include -#include #include +#include #include +#include +#include #include #include -#include + +#include namespace google { namespace protobuf { -namespace io { class ZeroCopyInputStream; } +namespace io { +class ZeroCopyInputStream; +} namespace compiler { @@ -73,9 +77,14 @@ class DiskSourceTree; // // Note: This class does not implement FindFileContainingSymbol() or // FindFileContainingExtension(); these will always return false. -class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase { +class PROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabase { public: SourceTreeDescriptorDatabase(SourceTree* source_tree); + + // If non-NULL, fallback_database will be checked if a file doesn't exist in + // the specified source_tree. + SourceTreeDescriptorDatabase(SourceTree* source_tree, + DescriptorDatabase* fallback_database); ~SourceTreeDescriptorDatabase(); // Instructs the SourceTreeDescriptorDatabase to report any parse errors @@ -96,36 +105,36 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas } // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, + bool FindFileByName(const std::string& filename, + FileDescriptorProto* output) override; + bool FindFileContainingSymbol(const std::string& symbol_name, + FileDescriptorProto* output) override; + bool FindFileContainingExtension(const std::string& containing_type, int field_number, - FileDescriptorProto* output); + FileDescriptorProto* output) override; private: class SingleFileErrorCollector; SourceTree* source_tree_; + DescriptorDatabase* fallback_database_; MultiFileErrorCollector* error_collector_; - class LIBPROTOBUF_EXPORT ValidationErrorCollector : public DescriptorPool::ErrorCollector { + class PROTOBUF_EXPORT ValidationErrorCollector + : public DescriptorPool::ErrorCollector { public: ValidationErrorCollector(SourceTreeDescriptorDatabase* owner); ~ValidationErrorCollector(); // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message); + void AddError(const std::string& filename, const std::string& element_name, + const Message* descriptor, ErrorLocation location, + const std::string& message) override; - virtual void AddWarning(const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message); + void AddWarning(const std::string& filename, + const std::string& element_name, const Message* descriptor, + ErrorLocation location, + const std::string& message) override; private: SourceTreeDescriptorDatabase* owner_; @@ -145,10 +154,9 @@ class LIBPROTOBUF_EXPORT SourceTreeDescriptorDatabase : public DescriptorDatabas // You may find that SourceTreeDescriptorDatabase is more flexible. // // TODO(kenton): I feel like this class is not well-named. -class LIBPROTOBUF_EXPORT Importer { +class PROTOBUF_EXPORT Importer { public: - Importer(SourceTree* source_tree, - MultiFileErrorCollector* error_collector); + Importer(SourceTree* source_tree, MultiFileErrorCollector* error_collector); ~Importer(); // Import the given file and build a FileDescriptor representing it. If @@ -164,15 +172,14 @@ class LIBPROTOBUF_EXPORT Importer { // you want to see errors for the same files repeatedly, you can use a // separate Importer object to import each one (but use the same // DescriptorPool so that they can be cross-linked). - const FileDescriptor* Import(const string& filename); + const FileDescriptor* Import(const std::string& filename); // The DescriptorPool in which all imported FileDescriptors and their // contents are stored. - inline const DescriptorPool* pool() const { - return &pool_; - } + inline const DescriptorPool* pool() const { return &pool_; } - void AddUnusedImportTrackFile(const string& file_name); + void AddUnusedImportTrackFile(const std::string& file_name, + bool is_error = false); void ClearUnusedImportTrackFiles(); @@ -185,18 +192,18 @@ class LIBPROTOBUF_EXPORT Importer { // If the importer encounters problems while trying to import the proto files, // it reports them to a MultiFileErrorCollector. -class LIBPROTOBUF_EXPORT MultiFileErrorCollector { +class PROTOBUF_EXPORT MultiFileErrorCollector { public: inline MultiFileErrorCollector() {} virtual ~MultiFileErrorCollector(); // Line and column numbers are zero-based. A line number of -1 indicates // an error with the entire file (e.g. "not found"). - virtual void AddError(const string& filename, int line, int column, - const string& message) = 0; + virtual void AddError(const std::string& filename, int line, int column, + const std::string& message) = 0; - virtual void AddWarning(const string& filename, int line, int column, - const string& message) {} + virtual void AddWarning(const std::string& /* filename */, int /* line */, + int /* column */, const std::string& /* message */) {} private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MultiFileErrorCollector); @@ -206,7 +213,7 @@ class LIBPROTOBUF_EXPORT MultiFileErrorCollector { // Used by the default implementation of Importer to resolve import statements // Most users will probably want to use the DiskSourceTree implementation, // below. -class LIBPROTOBUF_EXPORT SourceTree { +class PROTOBUF_EXPORT SourceTree { public: inline SourceTree() {} virtual ~SourceTree(); @@ -215,14 +222,14 @@ class LIBPROTOBUF_EXPORT SourceTree { // found. The caller takes ownership of the returned object. The filename // must be a path relative to the root of the source tree and must not // contain "." or ".." components. - virtual io::ZeroCopyInputStream* Open(const string& filename) = 0; + virtual io::ZeroCopyInputStream* Open(const std::string& filename) = 0; // If Open() returns NULL, calling this method immediately will return an // description of the error. // Subclasses should implement this method and return a meaningful value for // better error reporting. // TODO(xiaofeng): change this to a pure virtual function. - virtual string GetLastErrorMessage(); + virtual std::string GetLastErrorMessage(); private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceTree); @@ -231,7 +238,7 @@ class LIBPROTOBUF_EXPORT SourceTree { // An implementation of SourceTree which loads files from locations on disk. // Multiple mappings can be set up to map locations in the DiskSourceTree to // locations in the physical filesystem. -class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { +class PROTOBUF_EXPORT DiskSourceTree : public SourceTree { public: DiskSourceTree(); ~DiskSourceTree(); @@ -248,11 +255,11 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { // and then you do: // Open("bar/qux"); // the DiskSourceTree will first try to open foo/bar/qux, then baz/bar/qux, - // returning the first one that opens successfuly. + // returning the first one that opens successfully. // // disk_path may be an absolute path or relative to the current directory, // just like a path you'd pass to open(). - void MapPath(const string& virtual_path, const string& disk_path); + void MapPath(const std::string& virtual_path, const std::string& disk_path); // Return type for DiskFileToVirtualFile(). enum DiskFileToVirtualFileResult { @@ -282,46 +289,48 @@ class LIBPROTOBUF_EXPORT DiskSourceTree : public SourceTree { // it is not useful. // * NO_MAPPING: Indicates that no mapping was found which contains this // file. - DiskFileToVirtualFileResult - DiskFileToVirtualFile(const string& disk_file, - string* virtual_file, - string* shadowing_disk_file); + DiskFileToVirtualFileResult DiskFileToVirtualFile( + const std::string& disk_file, std::string* virtual_file, + std::string* shadowing_disk_file); // Given a virtual path, find the path to the file on disk. // Return true and update disk_file with the on-disk path if the file exists. // Return false and leave disk_file untouched if the file doesn't exist. - bool VirtualFileToDiskFile(const string& virtual_file, string* disk_file); + bool VirtualFileToDiskFile(const std::string& virtual_file, + std::string* disk_file); // implements SourceTree ------------------------------------------- - virtual io::ZeroCopyInputStream* Open(const string& filename); + io::ZeroCopyInputStream* Open(const std::string& filename) override; - virtual string GetLastErrorMessage(); + std::string GetLastErrorMessage() override; private: struct Mapping { - string virtual_path; - string disk_path; + std::string virtual_path; + std::string disk_path; - inline Mapping(const string& virtual_path_param, - const string& disk_path_param) - : virtual_path(virtual_path_param), disk_path(disk_path_param) {} + inline Mapping(const std::string& virtual_path_param, + const std::string& disk_path_param) + : virtual_path(virtual_path_param), disk_path(disk_path_param) {} }; std::vector mappings_; - string last_error_message_; + std::string last_error_message_; // Like Open(), but returns the on-disk path in disk_file if disk_file is // non-NULL and the file could be successfully opened. - io::ZeroCopyInputStream* OpenVirtualFile(const string& virtual_file, - string* disk_file); + io::ZeroCopyInputStream* OpenVirtualFile(const std::string& virtual_file, + std::string* disk_file); // Like Open() but given the actual on-disk path. - io::ZeroCopyInputStream* OpenDiskFile(const string& filename); + io::ZeroCopyInputStream* OpenDiskFile(const std::string& filename); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DiskSourceTree); }; } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_IMPORTER_H__ diff --git a/windows/include/google/protobuf/compiler/importer_unittest.cc b/windows/include/google/protobuf/compiler/importer_unittest.cc deleted file mode 100644 index 73bef3f4b..000000000 --- a/windows/include/google/protobuf/compiler/importer_unittest.cc +++ /dev/null @@ -1,520 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { - -namespace { - -bool FileExists(const string& path) { - return File::Exists(path); -} - -#define EXPECT_SUBSTRING(needle, haystack) \ - EXPECT_PRED_FORMAT2(testing::IsSubstring, (needle), (haystack)) - -class MockErrorCollector : public MultiFileErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - string warning_text_; - - // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1:$2: $3\n", - filename, line, column, message); - } - - void AddWarning(const string& filename, int line, int column, - const string& message) { - strings::SubstituteAndAppend(&warning_text_, "$0:$1:$2: $3\n", - filename, line, column, message); - } -}; - -// ------------------------------------------------------------------- - -// A dummy implementation of SourceTree backed by a simple map. -class MockSourceTree : public SourceTree { - public: - MockSourceTree() {} - ~MockSourceTree() {} - - void AddFile(const string& name, const char* contents) { - files_[name] = contents; - } - - // implements SourceTree ------------------------------------------- - io::ZeroCopyInputStream* Open(const string& filename) { - const char* contents = FindPtrOrNull(files_, filename); - if (contents == NULL) { - return NULL; - } else { - return new io::ArrayInputStream(contents, strlen(contents)); - } - } - - string GetLastErrorMessage() { - return "File not found."; - } - - private: - hash_map files_; -}; - -// =================================================================== - -class ImporterTest : public testing::Test { - protected: - ImporterTest() - : importer_(&source_tree_, &error_collector_) {} - - void AddFile(const string& filename, const char* text) { - source_tree_.AddFile(filename, text); - } - - // Return the collected error text - string error() const { return error_collector_.text_; } - string warning() const { return error_collector_.warning_text_; } - - MockErrorCollector error_collector_; - MockSourceTree source_tree_; - Importer importer_; -}; - -TEST_F(ImporterTest, Import) { - // Test normal importing. - AddFile("foo.proto", - "syntax = \"proto2\";\n" - "message Foo {}\n"); - - const FileDescriptor* file = importer_.Import("foo.proto"); - EXPECT_EQ("", error_collector_.text_); - ASSERT_TRUE(file != NULL); - - ASSERT_EQ(1, file->message_type_count()); - EXPECT_EQ("Foo", file->message_type(0)->name()); - - // Importing again should return same object. - EXPECT_EQ(file, importer_.Import("foo.proto")); -} - -TEST_F(ImporterTest, ImportNested) { - // Test that importing a file which imports another file works. - AddFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n" - "message Foo {\n" - " optional Bar bar = 1;\n" - "}\n"); - AddFile("bar.proto", - "syntax = \"proto2\";\n" - "message Bar {}\n"); - - // Note that both files are actually parsed by the first call to Import() - // here, since foo.proto imports bar.proto. The second call just returns - // the same ProtoFile for bar.proto which was constructed while importing - // foo.proto. We test that this is the case below by checking that bar - // is among foo's dependencies (by pointer). - const FileDescriptor* foo = importer_.Import("foo.proto"); - const FileDescriptor* bar = importer_.Import("bar.proto"); - EXPECT_EQ("", error_collector_.text_); - ASSERT_TRUE(foo != NULL); - ASSERT_TRUE(bar != NULL); - - // Check that foo's dependency is the same object as bar. - ASSERT_EQ(1, foo->dependency_count()); - EXPECT_EQ(bar, foo->dependency(0)); - - // Check that foo properly cross-links bar. - ASSERT_EQ(1, foo->message_type_count()); - ASSERT_EQ(1, bar->message_type_count()); - ASSERT_EQ(1, foo->message_type(0)->field_count()); - ASSERT_EQ(FieldDescriptor::TYPE_MESSAGE, - foo->message_type(0)->field(0)->type()); - EXPECT_EQ(bar->message_type(0), - foo->message_type(0)->field(0)->message_type()); -} - -TEST_F(ImporterTest, FileNotFound) { - // Error: Parsing a file that doesn't exist. - EXPECT_TRUE(importer_.Import("foo.proto") == NULL); - EXPECT_EQ( - "foo.proto:-1:0: File not found.\n", - error_collector_.text_); -} - -TEST_F(ImporterTest, ImportNotFound) { - // Error: Importing a file that doesn't exist. - AddFile("foo.proto", - "syntax = \"proto2\";\n" - "import \"bar.proto\";\n"); - - EXPECT_TRUE(importer_.Import("foo.proto") == NULL); - EXPECT_EQ( - "bar.proto:-1:0: File not found.\n" - "foo.proto:-1:0: Import \"bar.proto\" was not found or had errors.\n", - error_collector_.text_); -} - -TEST_F(ImporterTest, RecursiveImport) { - // Error: Recursive import. - AddFile("recursive1.proto", - "syntax = \"proto2\";\n" - "import \"recursive2.proto\";\n"); - AddFile("recursive2.proto", - "syntax = \"proto2\";\n" - "import \"recursive1.proto\";\n"); - - EXPECT_TRUE(importer_.Import("recursive1.proto") == NULL); - EXPECT_EQ( - "recursive1.proto:-1:0: File recursively imports itself: recursive1.proto " - "-> recursive2.proto -> recursive1.proto\n" - "recursive2.proto:-1:0: Import \"recursive1.proto\" was not found " - "or had errors.\n" - "recursive1.proto:-1:0: Import \"recursive2.proto\" was not found " - "or had errors.\n", - error_collector_.text_); -} - - -// =================================================================== - -class DiskSourceTreeTest : public testing::Test { - protected: - virtual void SetUp() { - dirnames_.push_back(TestTempDir() + "/test_proto2_import_path_1"); - dirnames_.push_back(TestTempDir() + "/test_proto2_import_path_2"); - - for (int i = 0; i < dirnames_.size(); i++) { - if (FileExists(dirnames_[i])) { - File::DeleteRecursively(dirnames_[i], NULL, NULL); - } - GOOGLE_CHECK_OK(File::CreateDir(dirnames_[i], 0777)); - } - } - - virtual void TearDown() { - for (int i = 0; i < dirnames_.size(); i++) { - if (FileExists(dirnames_[i])) { - File::DeleteRecursively(dirnames_[i], NULL, NULL); - } - } - } - - void AddFile(const string& filename, const char* contents) { - GOOGLE_CHECK_OK(File::SetContents(filename, contents, true)); - } - - void AddSubdir(const string& dirname) { - GOOGLE_CHECK_OK(File::CreateDir(dirname, 0777)); - } - - void ExpectFileContents(const string& filename, - const char* expected_contents) { - std::unique_ptr input(source_tree_.Open(filename)); - - ASSERT_FALSE(input == NULL); - - // Read all the data from the file. - string file_contents; - const void* data; - int size; - while (input->Next(&data, &size)) { - file_contents.append(reinterpret_cast(data), size); - } - - EXPECT_EQ(expected_contents, file_contents); - } - - void ExpectCannotOpenFile(const string& filename, - const string& error_message) { - std::unique_ptr input(source_tree_.Open(filename)); - EXPECT_TRUE(input == NULL); - EXPECT_EQ(error_message, source_tree_.GetLastErrorMessage()); - } - - DiskSourceTree source_tree_; - - // Paths of two on-disk directories to use during the test. - std::vector dirnames_; -}; - -TEST_F(DiskSourceTreeTest, MapRoot) { - // Test opening a file in a directory that is mapped to the root of the - // source tree. - AddFile(dirnames_[0] + "/foo", "Hello World!"); - source_tree_.MapPath("", dirnames_[0]); - - ExpectFileContents("foo", "Hello World!"); - ExpectCannotOpenFile("bar", "File not found."); -} - -TEST_F(DiskSourceTreeTest, MapDirectory) { - // Test opening a file in a directory that is mapped to somewhere other - // than the root of the source tree. - - AddFile(dirnames_[0] + "/foo", "Hello World!"); - source_tree_.MapPath("baz", dirnames_[0]); - - ExpectFileContents("baz/foo", "Hello World!"); - ExpectCannotOpenFile("baz/bar", "File not found."); - ExpectCannotOpenFile("foo", "File not found."); - ExpectCannotOpenFile("bar", "File not found."); - - // Non-canonical file names should not work. - ExpectCannotOpenFile("baz//foo", - "Backslashes, consecutive slashes, \".\", or \"..\" are " - "not allowed in the virtual path"); - ExpectCannotOpenFile("baz/../baz/foo", - "Backslashes, consecutive slashes, \".\", or \"..\" are " - "not allowed in the virtual path"); - ExpectCannotOpenFile("baz/./foo", - "Backslashes, consecutive slashes, \".\", or \"..\" are " - "not allowed in the virtual path"); - ExpectCannotOpenFile("baz/foo/", "File not found."); -} - -TEST_F(DiskSourceTreeTest, NoParent) { - // Test that we cannot open files in a parent of a mapped directory. - - AddFile(dirnames_[0] + "/foo", "Hello World!"); - AddSubdir(dirnames_[0] + "/bar"); - AddFile(dirnames_[0] + "/bar/baz", "Blah."); - source_tree_.MapPath("", dirnames_[0] + "/bar"); - - ExpectFileContents("baz", "Blah."); - ExpectCannotOpenFile("../foo", - "Backslashes, consecutive slashes, \".\", or \"..\" are " - "not allowed in the virtual path"); - ExpectCannotOpenFile("../bar/baz", - "Backslashes, consecutive slashes, \".\", or \"..\" are " - "not allowed in the virtual path"); -} - -TEST_F(DiskSourceTreeTest, MapFile) { - // Test opening a file that is mapped directly into the source tree. - - AddFile(dirnames_[0] + "/foo", "Hello World!"); - source_tree_.MapPath("foo", dirnames_[0] + "/foo"); - - ExpectFileContents("foo", "Hello World!"); - ExpectCannotOpenFile("bar", "File not found."); -} - -TEST_F(DiskSourceTreeTest, SearchMultipleDirectories) { - // Test mapping and searching multiple directories. - - AddFile(dirnames_[0] + "/foo", "Hello World!"); - AddFile(dirnames_[1] + "/foo", "This file should be hidden."); - AddFile(dirnames_[1] + "/bar", "Goodbye World!"); - source_tree_.MapPath("", dirnames_[0]); - source_tree_.MapPath("", dirnames_[1]); - - ExpectFileContents("foo", "Hello World!"); - ExpectFileContents("bar", "Goodbye World!"); - ExpectCannotOpenFile("baz", "File not found."); -} - -TEST_F(DiskSourceTreeTest, OrderingTrumpsSpecificity) { - // Test that directories are always searched in order, even when a latter - // directory is more-specific than a former one. - - // Create the "bar" directory so we can put a file in it. - GOOGLE_CHECK_OK(File::CreateDir(dirnames_[0] + "/bar", 0777)); - - // Add files and map paths. - AddFile(dirnames_[0] + "/bar/foo", "Hello World!"); - AddFile(dirnames_[1] + "/foo", "This file should be hidden."); - source_tree_.MapPath("", dirnames_[0]); - source_tree_.MapPath("bar", dirnames_[1]); - - // Check. - ExpectFileContents("bar/foo", "Hello World!"); -} - -TEST_F(DiskSourceTreeTest, DiskFileToVirtualFile) { - // Test DiskFileToVirtualFile. - - AddFile(dirnames_[0] + "/foo", "Hello World!"); - AddFile(dirnames_[1] + "/foo", "This file should be hidden."); - source_tree_.MapPath("bar", dirnames_[0]); - source_tree_.MapPath("bar", dirnames_[1]); - - string virtual_file; - string shadowing_disk_file; - - EXPECT_EQ(DiskSourceTree::NO_MAPPING, - source_tree_.DiskFileToVirtualFile( - "/foo", &virtual_file, &shadowing_disk_file)); - - EXPECT_EQ(DiskSourceTree::SHADOWED, - source_tree_.DiskFileToVirtualFile( - dirnames_[1] + "/foo", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("bar/foo", virtual_file); - EXPECT_EQ(dirnames_[0] + "/foo", shadowing_disk_file); - - EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - dirnames_[1] + "/baz", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("bar/baz", virtual_file); - - EXPECT_EQ(DiskSourceTree::SUCCESS, - source_tree_.DiskFileToVirtualFile( - dirnames_[0] + "/foo", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("bar/foo", virtual_file); -} - -TEST_F(DiskSourceTreeTest, DiskFileToVirtualFileCanonicalization) { - // Test handling of "..", ".", etc. in DiskFileToVirtualFile(). - - source_tree_.MapPath("dir1", ".."); - source_tree_.MapPath("dir2", "../../foo"); - source_tree_.MapPath("dir3", "./foo/bar/."); - source_tree_.MapPath("dir4", "."); - source_tree_.MapPath("", "/qux"); - source_tree_.MapPath("dir5", "/quux/"); - - string virtual_file; - string shadowing_disk_file; - - // "../.." should not be considered to be under "..". - EXPECT_EQ(DiskSourceTree::NO_MAPPING, - source_tree_.DiskFileToVirtualFile( - "../../baz", &virtual_file, &shadowing_disk_file)); - - // "/foo" is not mapped (it should not be misintepreted as being under "."). - EXPECT_EQ(DiskSourceTree::NO_MAPPING, - source_tree_.DiskFileToVirtualFile( - "/foo", &virtual_file, &shadowing_disk_file)); - -#ifdef WIN32 - // "C:\foo" is not mapped (it should not be misintepreted as being under "."). - EXPECT_EQ(DiskSourceTree::NO_MAPPING, - source_tree_.DiskFileToVirtualFile( - "C:\\foo", &virtual_file, &shadowing_disk_file)); -#endif // WIN32 - - // But "../baz" should be. - EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "../baz", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("dir1/baz", virtual_file); - - // "../../foo/baz" is under "../../foo". - EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "../../foo/baz", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("dir2/baz", virtual_file); - - // "foo/./bar/baz" is under "./foo/bar/.". - EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "foo/bar/baz", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("dir3/baz", virtual_file); - - // "bar" is under ".". - EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "bar", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("dir4/bar", virtual_file); - - // "/qux/baz" is under "/qux". - EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "/qux/baz", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("baz", virtual_file); - - // "/quux/bar" is under "/quux". - EXPECT_EQ(DiskSourceTree::CANNOT_OPEN, - source_tree_.DiskFileToVirtualFile( - "/quux/bar", &virtual_file, &shadowing_disk_file)); - EXPECT_EQ("dir5/bar", virtual_file); -} - -TEST_F(DiskSourceTreeTest, VirtualFileToDiskFile) { - // Test VirtualFileToDiskFile. - - AddFile(dirnames_[0] + "/foo", "Hello World!"); - AddFile(dirnames_[1] + "/foo", "This file should be hidden."); - AddFile(dirnames_[1] + "/quux", "This file should not be hidden."); - source_tree_.MapPath("bar", dirnames_[0]); - source_tree_.MapPath("bar", dirnames_[1]); - - // Existent files, shadowed and non-shadowed case. - string disk_file; - EXPECT_TRUE(source_tree_.VirtualFileToDiskFile("bar/foo", &disk_file)); - EXPECT_EQ(dirnames_[0] + "/foo", disk_file); - EXPECT_TRUE(source_tree_.VirtualFileToDiskFile("bar/quux", &disk_file)); - EXPECT_EQ(dirnames_[1] + "/quux", disk_file); - - // Nonexistent file in existent directory and vice versa. - string not_touched = "not touched"; - EXPECT_FALSE(source_tree_.VirtualFileToDiskFile("bar/baz", ¬_touched)); - EXPECT_EQ("not touched", not_touched); - EXPECT_FALSE(source_tree_.VirtualFileToDiskFile("baz/foo", ¬_touched)); - EXPECT_EQ("not touched", not_touched); - - // Accept NULL as output parameter. - EXPECT_TRUE(source_tree_.VirtualFileToDiskFile("bar/foo", NULL)); - EXPECT_FALSE(source_tree_.VirtualFileToDiskFile("baz/foo", NULL)); -} - -} // namespace - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_context.cc b/windows/include/google/protobuf/compiler/java/java_context.cc deleted file mode 100644 index 2528c2d13..000000000 --- a/windows/include/google/protobuf/compiler/java/java_context.cc +++ /dev/null @@ -1,202 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -Context::Context(const FileDescriptor* file, const Options& options) - : name_resolver_(new ClassNameResolver), options_(options) { - InitializeFieldGeneratorInfo(file); -} - -Context::~Context() { -} - -ClassNameResolver* Context::GetNameResolver() const { - return name_resolver_.get(); -} - -namespace { -// Whether two fields have conflicting accessors (assuming name1 and name2 -// are different). name1 and name2 are field1 and field2's camel-case name -// respectively. -bool IsConflicting(const FieldDescriptor* field1, const string& name1, - const FieldDescriptor* field2, const string& name2, - string* info) { - if (field1->is_repeated()) { - if (field2->is_repeated()) { - // Both fields are repeated. - return false; - } else { - // field1 is repeated, and field2 is not. - if (name1 + "Count" == name2) { - *info = "both repeated field \"" + field1->name() + "\" and singular " + - "field \"" + field2->name() + "\" generate the method \"" + - "get" + name1 + "Count()\""; - return true; - } - if (name1 + "List" == name2) { - *info = "both repeated field \"" + field1->name() + "\" and singular " + - "field \"" + field2->name() + "\" generate the method \"" + - "get" + name1 + "List()\""; - return true; - } - // Well, there are obviously many more conflicting cases, but it probably - // doesn't worth the effort to exhaust all of them because they rarely - // happen and as we are continuing adding new methods/changing existing - // methods the number of different conflicting cases will keep growing. - // We can just add more cases here when they are found in the real world. - return false; - } - } else { - if (field2->is_repeated()) { - return IsConflicting(field2, name2, field1, name1, info); - } else { - // None of the two fields are repeated. - return false; - } - } -} -} // namespace - -void Context::InitializeFieldGeneratorInfo(const FileDescriptor* file) { - for (int i = 0; i < file->message_type_count(); ++i) { - InitializeFieldGeneratorInfoForMessage(file->message_type(i)); - } -} - -void Context::InitializeFieldGeneratorInfoForMessage( - const Descriptor* message) { - for (int i = 0; i < message->nested_type_count(); ++i) { - InitializeFieldGeneratorInfoForMessage(message->nested_type(i)); - } - std::vector fields; - for (int i = 0; i < message->field_count(); ++i) { - fields.push_back(message->field(i)); - } - InitializeFieldGeneratorInfoForFields(fields); - - for (int i = 0; i < message->oneof_decl_count(); ++i) { - const OneofDescriptor* oneof = message->oneof_decl(i); - OneofGeneratorInfo info; - info.name = UnderscoresToCamelCase(oneof->name(), false); - info.capitalized_name = UnderscoresToCamelCase(oneof->name(), true); - oneof_generator_info_map_[oneof] = info; - } -} - -void Context::InitializeFieldGeneratorInfoForFields( - const std::vector& fields) { - // Find out all fields that conflict with some other field in the same - // message. - std::vector is_conflict(fields.size()); - std::vector conflict_reason(fields.size()); - for (int i = 0; i < fields.size(); ++i) { - const FieldDescriptor* field = fields[i]; - const string& name = UnderscoresToCapitalizedCamelCase(field); - for (int j = i + 1; j < fields.size(); ++j) { - const FieldDescriptor* other = fields[j]; - const string& other_name = UnderscoresToCapitalizedCamelCase(other); - if (name == other_name) { - is_conflict[i] = is_conflict[j] = true; - conflict_reason[i] = conflict_reason[j] = - "capitalized name of field \"" + field->name() + - "\" conflicts with field \"" + other->name() + "\""; - } else if (IsConflicting(field, name, other, other_name, - &conflict_reason[j])) { - is_conflict[i] = is_conflict[j] = true; - conflict_reason[i] = conflict_reason[j]; - } - } - if (is_conflict[i]) { - GOOGLE_LOG(WARNING) << "field \"" << field->full_name() << "\" is conflicting " - << "with another field: " << conflict_reason[i]; - } - } - for (int i = 0; i < fields.size(); ++i) { - const FieldDescriptor* field = fields[i]; - FieldGeneratorInfo info; - info.name = CamelCaseFieldName(field); - info.capitalized_name = UnderscoresToCapitalizedCamelCase(field); - // For fields conflicting with some other fields, we append the field - // number to their field names in generated code to avoid conflicts. - if (is_conflict[i]) { - info.name += SimpleItoa(field->number()); - info.capitalized_name += SimpleItoa(field->number()); - info.disambiguated_reason = conflict_reason[i]; - } - field_generator_info_map_[field] = info; - } -} - -const FieldGeneratorInfo* Context::GetFieldGeneratorInfo( - const FieldDescriptor* field) const { - const FieldGeneratorInfo* result = - FindOrNull(field_generator_info_map_, field); - if (result == NULL) { - GOOGLE_LOG(FATAL) << "Can not find FieldGeneratorInfo for field: " - << field->full_name(); - } - return result; -} - -const OneofGeneratorInfo* Context::GetOneofGeneratorInfo( - const OneofDescriptor* oneof) const { - const OneofGeneratorInfo* result = - FindOrNull(oneof_generator_info_map_, oneof); - if (result == NULL) { - GOOGLE_LOG(FATAL) << "Can not find OneofGeneratorInfo for oneof: " - << oneof->name(); - } - return result; -} - -// Does this message class have generated parsing, serialization, and other -// standard methods for which reflection-based fallback implementations exist? -bool Context::HasGeneratedMethods(const Descriptor* descriptor) const { - return options_.enforce_lite || - descriptor->file()->options().optimize_for() != FileOptions::CODE_SIZE; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_context.h b/windows/include/google/protobuf/compiler/java/java_context.h deleted file mode 100644 index 9de7415ad..000000000 --- a/windows/include/google/protobuf/compiler/java/java_context.h +++ /dev/null @@ -1,111 +0,0 @@ -// 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_JAVA_CONTEXT_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_CONTEXT_H__ - -#include -#include -#include - -#include -#include - -namespace google { -namespace protobuf { - class FileDescriptor; - class FieldDescriptor; - class OneofDescriptor; - class Descriptor; - class EnumDescriptor; - namespace compiler { - namespace java { - class ClassNameResolver; // name_resolver.h - } - } -} // namespace protobuf - -namespace protobuf { -namespace compiler { -namespace java { - -struct FieldGeneratorInfo; -struct OneofGeneratorInfo; -// A context object holds the information that is shared among all code -// generators. -class Context { - public: - Context(const FileDescriptor* file, const Options& options); - ~Context(); - - // Get the name resolver associated with this context. The resolver - // can be used to map descriptors to Java class names. - ClassNameResolver* GetNameResolver() const; - - // Get the FieldGeneratorInfo for a given field. - const FieldGeneratorInfo* GetFieldGeneratorInfo( - const FieldDescriptor* field) const; - - // Get the OneofGeneratorInfo for a given oneof. - const OneofGeneratorInfo* GetOneofGeneratorInfo( - const OneofDescriptor* oneof) const; - - const Options& options() const { return options_; } - - // Enforces all the files (including transitive dependencies) to use - // LiteRuntime. - - bool EnforceLite() const { return options_.enforce_lite; } - - // Does this message class have generated parsing, serialization, and other - // standard methods for which reflection-based fallback implementations exist? - bool HasGeneratedMethods(const Descriptor* descriptor) const; - - private: - void InitializeFieldGeneratorInfo(const FileDescriptor* file); - void InitializeFieldGeneratorInfoForMessage(const Descriptor* message); - void InitializeFieldGeneratorInfoForFields( - const std::vector& fields); - - std::unique_ptr name_resolver_; - std::map - field_generator_info_map_; - std::map - oneof_generator_info_map_; - Options options_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Context); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_CONTEXT_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_doc_comment.cc b/windows/include/google/protobuf/compiler/java/java_doc_comment.cc deleted file mode 100644 index 59c04ad41..000000000 --- a/windows/include/google/protobuf/compiler/java/java_doc_comment.cc +++ /dev/null @@ -1,233 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -string EscapeJavadoc(const string& input) { - string result; - result.reserve(input.size() * 2); - - char prev = '*'; - - for (string::size_type i = 0; i < input.size(); i++) { - char c = input[i]; - switch (c) { - case '*': - // Avoid "/*". - if (prev == '/') { - result.append("*"); - } else { - result.push_back(c); - } - break; - case '/': - // Avoid "*/". - if (prev == '*') { - result.append("/"); - } else { - result.push_back(c); - } - break; - case '@': - // '@' starts javadoc tags including the @deprecated tag, which will - // cause a compile-time error if inserted before a declaration that - // does not have a corresponding @Deprecated annotation. - result.append("@"); - break; - case '<': - // Avoid interpretation as HTML. - result.append("<"); - break; - case '>': - // Avoid interpretation as HTML. - result.append(">"); - break; - case '&': - // Avoid interpretation as HTML. - result.append("&"); - break; - case '\\': - // Java interprets Unicode escape sequences anywhere! - result.append("\"); - break; - default: - result.push_back(c); - break; - } - - prev = c; - } - - return result; -} - -static void WriteDocCommentBodyForLocation( - io::Printer* printer, const SourceLocation& location) { - string comments = location.leading_comments.empty() ? - location.trailing_comments : location.leading_comments; - if (!comments.empty()) { - // TODO(kenton): Ideally we should parse the comment text as Markdown and - // write it back as HTML, but this requires a Markdown parser. For now - // we just use
 to get fixed-width text formatting.
-
-    // If the comment itself contains block comment start or end markers,
-    // HTML-escape them so that they don't accidentally close the doc comment.
-    comments = EscapeJavadoc(comments);
-
-    std::vector lines = Split(comments, "\n");
-    while (!lines.empty() && lines.back().empty()) {
-      lines.pop_back();
-    }
-
-    printer->Print(" * 
\n");
-    for (int i = 0; i < lines.size(); i++) {
-      // Most lines should start with a space.  Watch out for lines that start
-      // with a /, since putting that right after the leading asterisk will
-      // close the comment.
-      if (!lines[i].empty() && lines[i][0] == '/') {
-        printer->Print(" * $line$\n", "line", lines[i]);
-      } else {
-        printer->Print(" *$line$\n", "line", lines[i]);
-      }
-    }
-    printer->Print(
-        " * 
\n" - " *\n"); - } -} - -template -static void WriteDocCommentBody( - io::Printer* printer, const DescriptorType* descriptor) { - SourceLocation location; - if (descriptor->GetSourceLocation(&location)) { - WriteDocCommentBodyForLocation(printer, location); - } -} - -static string FirstLineOf(const string& value) { - string result = value; - - string::size_type pos = result.find_first_of('\n'); - if (pos != string::npos) { - result.erase(pos); - } - - // If line ends in an opening brace, make it "{ ... }" so it looks nice. - if (!result.empty() && result[result.size() - 1] == '{') { - result.append(" ... }"); - } - - return result; -} - -void WriteMessageDocComment(io::Printer* printer, const Descriptor* message) { - printer->Print("/**\n"); - WriteDocCommentBody(printer, message); - printer->Print( - " * Protobuf type {@code $fullname$}\n" - " */\n", - "fullname", EscapeJavadoc(message->full_name())); -} - -void WriteFieldDocComment(io::Printer* printer, const FieldDescriptor* field) { - // In theory we should have slightly different comments for setters, getters, - // etc., but in practice everyone already knows the difference between these - // so it's redundant information. - - // We start the comment with the main body based on the comments from the - // .proto file (if present). We then end with the field declaration, e.g.: - // optional string foo = 5; - // If the field is a group, the debug string might end with {. - printer->Print("/**\n"); - WriteDocCommentBody(printer, field); - printer->Print( - " * $def$\n", - "def", EscapeJavadoc(FirstLineOf(field->DebugString()))); - printer->Print(" */\n"); -} - -void WriteEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_) { - printer->Print("/**\n"); - WriteDocCommentBody(printer, enum_); - printer->Print( - " * Protobuf enum {@code $fullname$}\n" - " */\n", - "fullname", EscapeJavadoc(enum_->full_name())); -} - -void WriteEnumValueDocComment(io::Printer* printer, - const EnumValueDescriptor* value) { - printer->Print("/**\n"); - WriteDocCommentBody(printer, value); - printer->Print( - " * $def$\n" - " */\n", - "def", EscapeJavadoc(FirstLineOf(value->DebugString()))); -} - -void WriteServiceDocComment(io::Printer* printer, - const ServiceDescriptor* service) { - printer->Print("/**\n"); - WriteDocCommentBody(printer, service); - printer->Print( - " * Protobuf service {@code $fullname$}\n" - " */\n", - "fullname", EscapeJavadoc(service->full_name())); -} - -void WriteMethodDocComment(io::Printer* printer, - const MethodDescriptor* method) { - printer->Print("/**\n"); - WriteDocCommentBody(printer, method); - printer->Print( - " * $def$\n" - " */\n", - "def", EscapeJavadoc(FirstLineOf(method->DebugString()))); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_doc_comment.h b/windows/include/google/protobuf/compiler/java/java_doc_comment.h deleted file mode 100644 index 7d9535c95..000000000 --- a/windows/include/google/protobuf/compiler/java/java_doc_comment.h +++ /dev/null @@ -1,69 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_DOC_COMMENT_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_DOC_COMMENT_H__ - -#include - -namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -void WriteMessageDocComment(io::Printer* printer, const Descriptor* message); -void WriteFieldDocComment(io::Printer* printer, const FieldDescriptor* field); -void WriteEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_); -void WriteEnumValueDocComment(io::Printer* printer, - const EnumValueDescriptor* value); -void WriteServiceDocComment(io::Printer* printer, - const ServiceDescriptor* service); -void WriteMethodDocComment(io::Printer* printer, - const MethodDescriptor* method); - -// Exposed for testing only. -LIBPROTOC_EXPORT string EscapeJavadoc(const string& input); - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_DOC_COMMENT_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_doc_comment_unittest.cc b/windows/include/google/protobuf/compiler/java/java_doc_comment_unittest.cc deleted file mode 100644 index ae582ea64..000000000 --- a/windows/include/google/protobuf/compiler/java/java_doc_comment_unittest.cc +++ /dev/null @@ -1,67 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) - -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { -namespace { - -TEST(JavaDocCommentTest, Escaping) { - EXPECT_EQ("foo /* bar */ baz", EscapeJavadoc("foo /* bar */ baz")); - EXPECT_EQ("foo /*/ baz", EscapeJavadoc("foo /*/ baz")); - EXPECT_EQ("{@foo}", EscapeJavadoc("{@foo}")); - EXPECT_EQ("<i>&</i>", EscapeJavadoc("&")); - EXPECT_EQ("foo\u1234bar", EscapeJavadoc("foo\\u1234bar")); - EXPECT_EQ("@deprecated", EscapeJavadoc("@deprecated")); -} - -// TODO(kenton): It's hard to write a robust test of the doc comments -- we -// can only really compare the output against a golden value, which is a -// fairly tedious and fragile testing strategy. If we want to go that route, -// it probably makes sense to bite the bullet and write a test that compares -// the whole generated output for unittest.proto against a golden value, with -// a very simple script that can be run to regenerate it with the latest code. -// This would mean that updates to the golden file would have to be included -// in any change to the code generator, which would actually be fairly useful -// as it allows the reviewer to see clearly how the generated code is -// changing. - -} // namespace -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_enum.cc b/windows/include/google/protobuf/compiler/java/java_enum.cc deleted file mode 100644 index bef69f1a1..000000000 --- a/windows/include/google/protobuf/compiler/java/java_enum.cc +++ /dev/null @@ -1,357 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, - bool immutable_api, - Context* context) - : descriptor_(descriptor), immutable_api_(immutable_api), - context_(context), - name_resolver_(context->GetNameResolver()) { - for (int i = 0; i < descriptor_->value_count(); i++) { - const EnumValueDescriptor* value = descriptor_->value(i); - const EnumValueDescriptor* canonical_value = - descriptor_->FindValueByNumber(value->number()); - - if (value == canonical_value) { - canonical_values_.push_back(value); - } else { - Alias alias; - alias.value = value; - alias.canonical_value = canonical_value; - aliases_.push_back(alias); - } - } -} - -EnumGenerator::~EnumGenerator() {} - -void EnumGenerator::Generate(io::Printer* printer) { - WriteEnumDocComment(printer, descriptor_); - MaybePrintGeneratedAnnotation(context_, printer, descriptor_, immutable_api_); - printer->Print( - "public enum $classname$\n" - " implements com.google.protobuf.ProtocolMessageEnum {\n", - "classname", descriptor_->name()); - printer->Annotate("classname", descriptor_); - printer->Indent(); - - bool ordinal_is_index = true; - string index_text = "ordinal()"; - for (int i = 0; i < canonical_values_.size(); i++) { - if (canonical_values_[i]->index() != i) { - ordinal_is_index = false; - index_text = "index"; - break; - } - } - - for (int i = 0; i < canonical_values_.size(); i++) { - std::map vars; - vars["name"] = canonical_values_[i]->name(); - vars["index"] = SimpleItoa(canonical_values_[i]->index()); - vars["number"] = SimpleItoa(canonical_values_[i]->number()); - WriteEnumValueDocComment(printer, canonical_values_[i]); - if (canonical_values_[i]->options().deprecated()) { - printer->Print("@java.lang.Deprecated\n"); - } - if (ordinal_is_index) { - printer->Print(vars, - "$name$($number$),\n"); - } else { - printer->Print(vars, - "$name$($index$, $number$),\n"); - } - printer->Annotate("name", canonical_values_[i]); - } - - if (SupportUnknownEnumValue(descriptor_->file())) { - if (ordinal_is_index) { - printer->Print("${$UNRECOGNIZED$}$(-1),\n", "{", "", "}", ""); - } else { - printer->Print("${$UNRECOGNIZED$}$(-1, -1),\n", "{", "", "}", ""); - } - printer->Annotate("{", "}", descriptor_); - } - - printer->Print( - ";\n" - "\n"); - - // ----------------------------------------------------------------- - - for (int i = 0; i < aliases_.size(); i++) { - std::map vars; - vars["classname"] = descriptor_->name(); - vars["name"] = aliases_[i].value->name(); - vars["canonical_name"] = aliases_[i].canonical_value->name(); - WriteEnumValueDocComment(printer, aliases_[i].value); - printer->Print(vars, - "public static final $classname$ $name$ = $canonical_name$;\n"); - printer->Annotate("name", aliases_[i].value); - } - - for (int i = 0; i < descriptor_->value_count(); i++) { - std::map vars; - vars["name"] = descriptor_->value(i)->name(); - vars["number"] = SimpleItoa(descriptor_->value(i)->number()); - vars["{"] = ""; - vars["}"] = ""; - WriteEnumValueDocComment(printer, descriptor_->value(i)); - printer->Print(vars, - "public static final int ${$$name$_VALUE$}$ = $number$;\n"); - printer->Annotate("{", "}", descriptor_->value(i)); - } - printer->Print("\n"); - - // ----------------------------------------------------------------- - - printer->Print( - "\n" - "public final int getNumber() {\n"); - if (SupportUnknownEnumValue(descriptor_->file())) { - if (ordinal_is_index) { - printer->Print( - " if (this == UNRECOGNIZED) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Can't get the number of an unknown enum value.\");\n" - " }\n"); - } else { - printer->Print( - " if (index == -1) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Can't get the number of an unknown enum value.\");\n" - " }\n"); - } - } - printer->Print( - " return value;\n" - "}\n" - "\n" - "/**\n" - " * @deprecated Use {@link #forNumber(int)} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public static $classname$ valueOf(int value) {\n" - " return forNumber(value);\n" - "}\n" - "\n" - "public static $classname$ forNumber(int value) {\n" - " switch (value) {\n", - "classname", descriptor_->name()); - printer->Indent(); - printer->Indent(); - - for (int i = 0; i < canonical_values_.size(); i++) { - printer->Print( - "case $number$: return $name$;\n", - "name", canonical_values_[i]->name(), - "number", SimpleItoa(canonical_values_[i]->number())); - } - - printer->Outdent(); - printer->Outdent(); - printer->Print( - " default: return null;\n" - " }\n" - "}\n" - "\n" - "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n" - " internalGetValueMap() {\n" - " return internalValueMap;\n" - "}\n" - "private static final com.google.protobuf.Internal.EnumLiteMap<\n" - " $classname$> internalValueMap =\n" - " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n" - " public $classname$ findValueByNumber(int number) {\n" - " return $classname$.forNumber(number);\n" - " }\n" - " };\n" - "\n", - "classname", descriptor_->name()); - - // ----------------------------------------------------------------- - // Reflection - - if (HasDescriptorMethods(descriptor_, context_->EnforceLite())) { - printer->Print( - "public final com.google.protobuf.Descriptors.EnumValueDescriptor\n" - " getValueDescriptor() {\n" - " return getDescriptor().getValues().get($index_text$);\n" - "}\n" - "public final com.google.protobuf.Descriptors.EnumDescriptor\n" - " getDescriptorForType() {\n" - " return getDescriptor();\n" - "}\n" - "public static final com.google.protobuf.Descriptors.EnumDescriptor\n" - " getDescriptor() {\n", - "index_text", index_text); - - // TODO(kenton): Cache statically? Note that we can't access descriptors - // at module init time because it wouldn't work with descriptor.proto, but - // we can cache the value the first time getDescriptor() is called. - if (descriptor_->containing_type() == NULL) { - // The class generated for the File fully populates the descriptor with - // extensions in both the mutable and immutable cases. (In the mutable api - // this is accomplished by attempting to load the immutable outer class). - printer->Print( - " return $file$.getDescriptor().getEnumTypes().get($index$);\n", - "file", name_resolver_->GetClassName(descriptor_->file(), - immutable_api_), - "index", SimpleItoa(descriptor_->index())); - } else { - printer->Print( - " return $parent$.$descriptor$.getEnumTypes().get($index$);\n", - "parent", name_resolver_->GetClassName(descriptor_->containing_type(), - immutable_api_), - "descriptor", descriptor_->containing_type()->options() - .no_standard_descriptor_accessor() - ? "getDefaultInstance().getDescriptorForType()" - : "getDescriptor()", - "index", SimpleItoa(descriptor_->index())); - } - - printer->Print( - "}\n" - "\n" - "private static final $classname$[] VALUES = ", - "classname", descriptor_->name()); - - if (CanUseEnumValues()) { - // If the constants we are going to output are exactly the ones we - // have declared in the Java enum in the same order, then we can use - // the values() method that the Java compiler automatically generates - // for every enum. - printer->Print("values();\n"); - } else { - printer->Print( - "{\n" - " "); - for (int i = 0; i < descriptor_->value_count(); i++) { - printer->Print("$name$, ", - "name", descriptor_->value(i)->name()); - } - printer->Print( - "\n" - "};\n"); - } - - printer->Print( - "\n" - "public static $classname$ valueOf(\n" - " com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n" - " if (desc.getType() != getDescriptor()) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"EnumValueDescriptor is not for this type.\");\n" - " }\n", - "classname", descriptor_->name()); - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print( - " if (desc.getIndex() == -1) {\n" - " return UNRECOGNIZED;\n" - " }\n"); - } - printer->Print( - " return VALUES[desc.getIndex()];\n" - "}\n" - "\n"); - - if (!ordinal_is_index) { - printer->Print("private final int index;\n"); - } - } - - // ----------------------------------------------------------------- - - printer->Print( - "private final int value;\n\n"); - - if (ordinal_is_index) { - printer->Print( - "private $classname$(int value) {\n", - "classname", descriptor_->name()); - } else { - printer->Print( - "private $classname$(int index, int value) {\n", - "classname", descriptor_->name()); - } - if (HasDescriptorMethods(descriptor_, context_->EnforceLite()) && - !ordinal_is_index) { - printer->Print(" this.index = index;\n"); - } - printer->Print( - " this.value = value;\n" - "}\n"); - - printer->Print( - "\n" - "// @@protoc_insertion_point(enum_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - - printer->Outdent(); - printer->Print("}\n\n"); -} - -bool EnumGenerator::CanUseEnumValues() { - if (canonical_values_.size() != descriptor_->value_count()) { - return false; - } - for (int i = 0; i < descriptor_->value_count(); i++) { - if (descriptor_->value(i)->name() != canonical_values_[i]->name()) { - return false; - } - } - return true; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_enum.h b/windows/include/google/protobuf/compiler/java/java_enum.h deleted file mode 100644 index 13dfc32d4..000000000 --- a/windows/include/google/protobuf/compiler/java/java_enum.h +++ /dev/null @@ -1,98 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class EnumGenerator { - public: - EnumGenerator(const EnumDescriptor* descriptor, bool immutable_api, - Context* context); - ~EnumGenerator(); - - void Generate(io::Printer* printer); - - private: - const EnumDescriptor* descriptor_; - - // The proto language allows multiple enum constants to have the same numeric - // value. Java, however, does not allow multiple enum constants to be - // considered equivalent. We treat the first defined constant for any - // given numeric value as "canonical" and the rest as aliases of that - // canonical value. - std::vector canonical_values_; - - struct Alias { - const EnumValueDescriptor* value; - const EnumValueDescriptor* canonical_value; - }; - std::vector aliases_; - - bool immutable_api_; - - Context* context_; - ClassNameResolver* name_resolver_; - - bool CanUseEnumValues(); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_enum_field.cc b/windows/include/google/protobuf/compiler/java/java_enum_field.cc deleted file mode 100644 index 0686ea0f6..000000000 --- a/windows/include/google/protobuf/compiler/java/java_enum_field.cc +++ /dev/null @@ -1,1005 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { - -void SetEnumVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - ClassNameResolver* name_resolver, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - - (*variables)["type"] = - name_resolver->GetImmutableClassName(descriptor->enum_type()); - (*variables)["mutable_type"] = - name_resolver->GetMutableClassName(descriptor->enum_type()); - (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["default_number"] = SimpleItoa( - descriptor->default_value_enum()->number()); - (*variables)["tag"] = - SimpleItoa(static_cast(internal::WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( - internal::WireFormat::TagSize(descriptor->number(), GetType(descriptor))); - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - (*variables)["on_changed"] = "onChanged();"; - // Use deprecated valueOf() method to be compatible with old generated code - // for v2.5.0/v2.6.1. - // TODO(xiaofeng): Use "forNumber" when we no longer support compatibility - // with v2.5.0/v2.6.1, and remove the @SuppressWarnings annotations. - (*variables)["for_number"] = "valueOf"; - - if (SupportFieldPresence(descriptor->file())) { - // For singular messages and builders, one bit is used for the hasField bit. - (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); - (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex); - - // Note that these have a trailing ";". - (*variables)["set_has_field_bit_message"] = - GenerateSetBit(messageBitIndex) + ";"; - (*variables)["set_has_field_bit_builder"] = - GenerateSetBit(builderBitIndex) + ";"; - (*variables)["clear_has_field_bit_builder"] = - GenerateClearBit(builderBitIndex) + ";"; - - (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); - } else { - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["set_has_field_bit_builder"] = ""; - (*variables)["clear_has_field_bit_builder"] = ""; - - (*variables)["is_field_present_message"] = - (*variables)["name"] + "_ != " + - (*variables)["default"] + ".getNumber()"; - } - - // For repated builders, one bit is used for whether the array is immutable. - (*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex); - (*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex); - (*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex); - - // For repeated fields, one bit is used for whether the array is immutable - // in the parsing constructor. - (*variables)["get_mutable_bit_parser"] = - GenerateGetBitMutableLocal(builderBitIndex); - (*variables)["set_mutable_bit_parser"] = - GenerateSetBitMutableLocal(builderBitIndex); - - (*variables)["get_has_field_bit_from_local"] = - GenerateGetBitFromLocal(builderBitIndex); - (*variables)["set_has_field_bit_to_local"] = - GenerateSetBitToLocal(messageBitIndex); - - if (SupportUnknownEnumValue(descriptor->file())) { - (*variables)["unknown"] = (*variables)["type"] + ".UNRECOGNIZED"; - } else { - (*variables)["unknown"] = (*variables)["default"]; - } -} - -} // namespace - -// =================================================================== - -ImmutableEnumFieldGenerator:: -ImmutableEnumFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), - name_resolver_(context->GetNameResolver()) { - SetEnumVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -ImmutableEnumFieldGenerator::~ImmutableEnumFieldGenerator() {} - -int ImmutableEnumFieldGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutableEnumFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -void ImmutableEnumFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value();\n"); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); -} - -void ImmutableEnumFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private int $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$($name$_);\n" - " return result == null ? $unknown$ : result;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableEnumFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print(variables_, - "private int $name$_ = $default_number$;\n"); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$set$capitalized_name$Value$}$(int value) {\n" - " $name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$($name$_);\n" - " return result == null ? $unknown$ : result;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $set_has_field_bit_builder$\n" - " $name$_ = value.getNumber();\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $clear_has_field_bit_builder$\n" - " $name$_ = $default_number$;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableEnumFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for enums -} - -void ImmutableEnumFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default_number$;\n"); -} - -void ImmutableEnumFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = $default_number$;\n" - "$clear_has_field_bit_builder$\n"); -} - -void ImmutableEnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " set$capitalized_name$(other.get$capitalized_name$());\n" - "}\n"); - } else if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "if (other.$name$_ != $default_number$) {\n" - " set$capitalized_name$Value(other.get$capitalized_name$Value());\n" - "}\n"); - } else { - GOOGLE_LOG(FATAL) << "Can't reach here."; - } -} - -void ImmutableEnumFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); - } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); -} - -void ImmutableEnumFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$set_has_field_bit_message$\n" - "$name$_ = rawValue;\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - " @SuppressWarnings(\"deprecation\")\n" - "$type$ value = $type$.$for_number$(rawValue);\n" - "if (value == null) {\n" - " unknownFields.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $set_has_field_bit_message$\n" - " $name$_ = rawValue;\n" - "}\n"); - } -} - -void ImmutableEnumFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for enums -} - -void ImmutableEnumFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.writeEnum($number$, $name$_);\n" - "}\n"); -} - -void ImmutableEnumFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSize($number$, $name$_);\n" - "}\n"); -} - -void ImmutableEnumFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && $name$_ == other.$name$_;\n"); -} - -void ImmutableEnumFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + $name$_;\n"); -} - -string ImmutableEnumFieldGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->enum_type()); -} - -// =================================================================== - -ImmutableEnumOneofFieldGenerator:: -ImmutableEnumOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableEnumFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); -} - -ImmutableEnumOneofFieldGenerator:: -~ImmutableEnumOneofFieldGenerator() {} - -void ImmutableEnumOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return (java.lang.Integer) $oneof_name$_;\n" - " }\n" - " return $default_number$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$(\n" - " (java.lang.Integer) $oneof_name$_);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " return $default$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ((java.lang.Integer) $oneof_name$_).intValue();\n" - " }\n" - " return $default_number$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$set$capitalized_name$Value$}$(int value) {\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$(\n" - " (java.lang.Integer) $oneof_name$_);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " return $default$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value.getNumber();\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - " }\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " result.$oneof_name$_ = $oneof_name$_;\n" - "}\n"); -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "set$capitalized_name$Value(other.get$capitalized_name$Value());\n"); - } else { - printer->Print(variables_, - "set$capitalized_name$(other.get$capitalized_name$());\n"); - } -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = rawValue;\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "@SuppressWarnings(\"deprecation\")\n" - "$type$ value = $type$.$for_number$(rawValue);\n" - "if (value == null) {\n" - " unknownFields.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = rawValue;\n" - "}\n"); - } -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeEnum($number$, ((java.lang.Integer) $oneof_name$_));\n" - "}\n"); -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSize($number$, ((java.lang.Integer) $oneof_name$_));\n" - "}\n"); -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "result = result && get$capitalized_name$Value()\n" - " == other.get$capitalized_name$Value();\n"); - } else { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); - } -} - -void ImmutableEnumOneofFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$Value();\n"); - } else { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$().getNumber();\n"); - } -} - -// =================================================================== - -RepeatedImmutableEnumFieldGenerator:: -RepeatedImmutableEnumFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetEnumVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -RepeatedImmutableEnumFieldGenerator::~RepeatedImmutableEnumFieldGenerator() {} - -int RepeatedImmutableEnumFieldGenerator::GetNumBitsForMessage() const { - return 0; -} - -int RepeatedImmutableEnumFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List<$type$> get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List\n" - "get$capitalized_name$ValueList();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value(int index);\n"); - } -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.util.List $name$_;\n" - "private static final com.google.protobuf.Internal.ListAdapter.Converter<\n" - " java.lang.Integer, $type$> $name$_converter_ =\n" - " new com.google.protobuf.Internal.ListAdapter.Converter<\n" - " java.lang.Integer, $type$>() {\n" - " public $type$ convert(java.lang.Integer from) {\n" - " @SuppressWarnings(\"deprecation\")\n" - " $type$ result = $type$.$for_number$(from);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " };\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return new com.google.protobuf.Internal.ListAdapter<\n" - " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_converter_.convert($name$_.get(index));\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List\n" - "${$get$capitalized_name$ValueList$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - if (descriptor_->is_packed()) { - printer->Print(variables_, - "private int $name$MemoizedSerializedSize;\n"); - } -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print(variables_, - // One field is the list and the other field keeps track of whether the - // list is immutable. If it's immutable, the invariant is that it must - // either an instance of Collections.emptyList() or it's an ArrayList - // wrapped in a Collections.unmodifiableList() wrapper and nobody else has - // a refererence to the underlying ArrayList. This invariant allows us to - // share instances of lists between protocol buffers avoiding expensive - // memory allocations. Note, immutable is a strong guarantee here -- not - // just that the list cannot be modified via the reference but that the - // list can never be modified. - "private java.util.List $name$_ =\n" - " java.util.Collections.emptyList();\n" - - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ = new java.util.ArrayList($name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - // Note: We return an unmodifiable list because otherwise the caller - // could hold on to the returned list and modify it after the message - // has been built, thus mutating the message which is supposed to be - // immutable. - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return new com.google.protobuf.Internal.ListAdapter<\n" - " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_converter_.convert($name$_.get(index));\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value.getNumber());\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value.getNumber());\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for ($type$ value : values) {\n" - " $name$_.add(value.getNumber());\n" - " }\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $name$_ = java.util.Collections.emptyList();\n" - " $clear_mutable_bit_builder$;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List\n" - "${$get$capitalized_name$ValueList$}$() {\n" - " return java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n" - " int index, int value) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$add$capitalized_name$Value$}$(int value) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for (int value : values) {\n" - " $name$_.add(value);\n" - " }\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for enums -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = java.util.Collections.emptyList();\n"); -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = java.util.Collections.emptyList();\n" - "$clear_mutable_bit_builder$;\n"); -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - // The code below does two optimizations: - // 1. If the other list is empty, there's nothing to do. This ensures we - // don't allocate a new array if we already have an immutable one. - // 2. If the other list is non-empty and our current list is empty, we can - // reuse the other list which is guaranteed to be immutable. - printer->Print(variables_, - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$_.isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " } else {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addAll(other.$name$_);\n" - " }\n" - " $on_changed$\n" - "}\n"); -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // The code below ensures that the result has an immutable list. If our - // list is immutable, we can just reuse it. If not, we make it immutable. - printer->Print(variables_, - "if ($get_mutable_bit_builder$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - " $clear_mutable_bit_builder$;\n" - "}\n" - "result.$name$_ = $name$_;\n"); -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - // Read and store the enum - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new java.util.ArrayList();\n" - " $set_mutable_bit_parser$;\n" - "}\n" - "$name$_.add(rawValue);\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "@SuppressWarnings(\"deprecation\")\n" - "$type$ value = $type$.$for_number$(rawValue);\n" - "if (value == null) {\n" - " unknownFields.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new java.util.ArrayList();\n" - " $set_mutable_bit_parser$;\n" - " }\n" - " $name$_.add(rawValue);\n" - "}\n"); - } -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - // Wrap GenerateParsingCode's contents with a while loop. - - printer->Print(variables_, - "int length = input.readRawVarint32();\n" - "int oldLimit = input.pushLimit(length);\n" - "while(input.getBytesUntilLimit() > 0) {\n"); - printer->Indent(); - - GenerateParsingCode(printer); - - printer->Outdent(); - printer->Print(variables_, - "}\n" - "input.popLimit(oldLimit);\n"); -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_mutable_bit_parser$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (get$capitalized_name$List().size() > 0) {\n" - " output.writeUInt32NoTag($tag$);\n" - " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" - "}\n" - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeEnumNoTag($name$_.get(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeEnum($number$, $name$_.get(i));\n" - "}\n"); - } -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSizeNoTag($name$_.get(i));\n" - "}\n"); - printer->Print( - "size += dataSize;\n"); - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (!get$capitalized_name$List().isEmpty()) {" - " size += $tag_size$;\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeUInt32SizeNoTag(dataSize);\n" - "}"); - } else { - printer->Print(variables_, - "size += $tag_size$ * $name$_.size();\n"); - } - - // cache the data size for packed fields. - if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && $name$_.equals(other.$name$_);\n"); -} - -void RepeatedImmutableEnumFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + $name$_.hashCode();\n" - "}\n"); -} - -string RepeatedImmutableEnumFieldGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->enum_type()); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_enum_field.h b/windows/include/google/protobuf/compiler/java/java_enum_field.h deleted file mode 100644 index 924ff2814..000000000 --- a/windows/include/google/protobuf/compiler/java/java_enum_field.h +++ /dev/null @@ -1,160 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableEnumFieldGenerator : public ImmutableFieldGenerator { - public: - explicit ImmutableEnumFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableEnumFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableEnumFieldGenerator); -}; - -class ImmutableEnumOneofFieldGenerator : public ImmutableEnumFieldGenerator { - public: - ImmutableEnumOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableEnumOneofFieldGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableEnumOneofFieldGenerator); -}; - -class RepeatedImmutableEnumFieldGenerator : public ImmutableFieldGenerator { - public: - explicit RepeatedImmutableEnumFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableEnumFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingCodeFromPacked(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableEnumFieldGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_enum_field_lite.cc b/windows/include/google/protobuf/compiler/java/java_enum_field_lite.cc deleted file mode 100644 index f1fe71b04..000000000 --- a/windows/include/google/protobuf/compiler/java/java_enum_field_lite.cc +++ /dev/null @@ -1,1022 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { - -void SetEnumVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - ClassNameResolver* name_resolver, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - - (*variables)["type"] = - name_resolver->GetImmutableClassName(descriptor->enum_type()); - (*variables)["mutable_type"] = - name_resolver->GetMutableClassName(descriptor->enum_type()); - (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["default_number"] = SimpleItoa( - descriptor->default_value_enum()->number()); - (*variables)["tag"] = - SimpleItoa(static_cast(internal::WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( - internal::WireFormat::TagSize(descriptor->number(), GetType(descriptor))); - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - (*variables)["required"] = descriptor->is_required() ? "true" : "false"; - - if (SupportFieldPresence(descriptor->file())) { - // For singular messages and builders, one bit is used for the hasField bit. - (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); - - // Note that these have a trailing ";". - (*variables)["set_has_field_bit_message"] = - GenerateSetBit(messageBitIndex) + ";"; - (*variables)["clear_has_field_bit_message"] = - GenerateClearBit(messageBitIndex) + ";"; - - (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); - } else { - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["clear_has_field_bit_message"] = ""; - - (*variables)["is_field_present_message"] = - (*variables)["name"] + "_ != " + - (*variables)["default"] + ".getNumber()"; - } - - // For repeated builders, the underlying list tracks mutability state. - (*variables)["is_mutable"] = (*variables)["name"] + "_.isModifiable()"; - - (*variables)["get_has_field_bit_from_local"] = - GenerateGetBitFromLocal(builderBitIndex); - (*variables)["set_has_field_bit_to_local"] = - GenerateSetBitToLocal(messageBitIndex); - - if (SupportUnknownEnumValue(descriptor->file())) { - (*variables)["unknown"] = (*variables)["type"] + ".UNRECOGNIZED"; - } else { - (*variables)["unknown"] = (*variables)["default"]; - } -} - -} // namespace - -// =================================================================== - -ImmutableEnumFieldLiteGenerator:: -ImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), - name_resolver_(context->GetNameResolver()) { - SetEnumVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -ImmutableEnumFieldLiteGenerator::~ImmutableEnumFieldLiteGenerator() {} - -int ImmutableEnumFieldLiteGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutableEnumFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value();\n"); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private int $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " $type$ result = $type$.forNumber($name$_);\n" - " return result == null ? $unknown$ : result;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Generate private setters for the builder to proxy into. - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$Value(int value) {\n" - " $set_has_field_bit_message$" - " $name$_ = value;\n" - "}\n"); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $set_has_field_bit_message$\n" - " $name$_ = value.getNumber();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $clear_has_field_bit_message$\n" - " $name$_ = $default_number$;\n" - "}\n"); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return instance.get$capitalized_name$Value();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$set$capitalized_name$Value$}$(int value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Value(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for enums -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - if (!IsDefaultValueJavaDefault(descriptor_)) { - printer->Print(variables_, "$name$_ = $default_number$;\n"); - } -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "$name$_ = visitor.visitInt(has$capitalized_name$(), $name$_,\n" - " other.has$capitalized_name$(), other.$name$_);\n"); - } else if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "$name$_ = visitor.visitInt($name$_ != $default_number$, $name$_," - " other.$name$_ != $default_number$, other.$name$_);\n"); - } else { - GOOGLE_LOG(FATAL) << "Can't reach here."; - } -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - // noop for scalars -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$set_has_field_bit_message$\n" - "$name$_ = rawValue;\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$type$ value = $type$.forNumber(rawValue);\n" - "if (value == null) {\n" - " super.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $set_has_field_bit_message$\n" - " $name$_ = rawValue;\n" - "}\n"); - } -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for enums -} - - -void ImmutableEnumFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.writeEnum($number$, $name$_);\n" - "}\n"); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSize($number$, $name$_);\n" - "}\n"); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && $name$_ == other.$name$_;\n"); -} - -void ImmutableEnumFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + $name$_;\n"); -} - -string ImmutableEnumFieldLiteGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->enum_type()); -} - -// =================================================================== - -ImmutableEnumOneofFieldLiteGenerator:: -ImmutableEnumOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableEnumFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); -} - -ImmutableEnumOneofFieldLiteGenerator:: -~ImmutableEnumOneofFieldLiteGenerator() {} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return (java.lang.Integer) $oneof_name$_;\n" - " }\n" - " return $default_number$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $type$ result = $type$.forNumber((java.lang.Integer) $oneof_name$_);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " return $default$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Generate private setters for the builder to proxy into. - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$Value(int value) {\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - "}\n"); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value.getNumber();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); -} - - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$() {\n" - " return instance.get$capitalized_name$Value();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$set$capitalized_name$Value$}$(int value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Value(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneofInt(\n" - " $has_oneof_case_message$, $oneof_name$_, other.$oneof_name$_);\n"); -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = rawValue;\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$type$ value = $type$.forNumber(rawValue);\n" - "if (value == null) {\n" - " super.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = rawValue;\n" - "}\n"); - } -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeEnum($number$, ((java.lang.Integer) $oneof_name$_));\n" - "}\n"); -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSize($number$, ((java.lang.Integer) $oneof_name$_));\n" - "}\n"); -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "result = result && get$capitalized_name$Value()\n" - " == other.get$capitalized_name$Value();\n"); - } else { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); - } -} - -void ImmutableEnumOneofFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$Value();\n"); - } else { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$().getNumber();\n"); - } -} - -// =================================================================== - -RepeatedImmutableEnumFieldLiteGenerator:: -RepeatedImmutableEnumFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetEnumVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -RepeatedImmutableEnumFieldLiteGenerator:: -~RepeatedImmutableEnumFieldLiteGenerator() {} - -int RepeatedImmutableEnumFieldLiteGenerator::GetNumBitsForMessage() const { - return 0; -} - -int RepeatedImmutableEnumFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List<$type$> get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List\n" - "get$capitalized_name$ValueList();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Value(int index);\n"); - } -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.Internal.IntList $name$_;\n" - "private static final com.google.protobuf.Internal.ListAdapter.Converter<\n" - " java.lang.Integer, $type$> $name$_converter_ =\n" - " new com.google.protobuf.Internal.ListAdapter.Converter<\n" - " java.lang.Integer, $type$>() {\n" - " @java.lang.Override\n" - " public $type$ convert(java.lang.Integer from) {\n" - " $type$ result = $type$.forNumber(from);\n" - " return result == null ? $unknown$ : result;\n" - " }\n" - " };\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return new com.google.protobuf.Internal.ListAdapter<\n" - " java.lang.Integer, $type$>($name$_, $name$_converter_);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_converter_.convert($name$_.getInt(index));\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List\n" - "${$get$capitalized_name$ValueList$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" - " return $name$_.getInt(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - if (descriptor_->is_packed() && - context_->HasGeneratedMethods(descriptor_->containing_type())) { - printer->Print(variables_, - "private int $name$MemoizedSerializedSize;\n"); - } - - // Generate private setters for the builder to proxy into. - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.setInt(index, value.getNumber());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addInt(value.getNumber());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for ($type$ value : values) {\n" - " $name$_.addInt(value.getNumber());\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = emptyIntList();\n" - "}\n"); - - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$Value(\n" - " int index, int value) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.setInt(index, value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$Value(int value) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addInt(value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$Value(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for (int value : values) {\n" - " $name$_.addInt(value);\n" - " }\n" - "}\n"); - } -} - - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return instance.get$capitalized_name$List();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Count();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List\n" - "${$get$capitalized_name$ValueList$}$() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$ValueList());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n" - " return instance.get$capitalized_name$Value(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n" - " int index, int value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Value(index, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$add$capitalized_name$Value$}$(int value) {\n" - " instance.add$capitalized_name$Value(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$Value(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for enums -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = emptyIntList();\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_= visitor.visitIntList($name$_, other.$name$_);\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - // Read and store the enum - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n"); - - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "$name$_.addInt(input.readEnum());\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$type$ value = $type$.forNumber(rawValue);\n" - "if (value == null) {\n" - // We store the unknown value in unknown fields. - " super.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $name$_.addInt(rawValue);\n" - "}\n"); - } -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n"); - - printer->Print(variables_, - "int length = input.readRawVarint32();\n" - "int oldLimit = input.pushLimit(length);\n" - "while(input.getBytesUntilLimit() > 0) {\n"); - printer->Indent(); - - // Read and store the enum - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print(variables_, - "$name$_.addInt(input.readEnum());\n"); - } else { - printer->Print(variables_, - "int rawValue = input.readEnum();\n" - "$type$ value = $type$.forNumber(rawValue);\n" - "if (value == null) {\n" - // We store the unknown value in unknown fields. - " super.mergeVarintField($number$, rawValue);\n" - "} else {\n" - " $name$_.addInt(rawValue);\n" - "}\n"); - } - - printer->Outdent(); - printer->Print(variables_, - "}\n" - "input.popLimit(oldLimit);\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_mutable$) {\n" - " $name$_.makeImmutable();\n" - "}\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (get$capitalized_name$List().size() > 0) {\n" - " output.writeUInt32NoTag($tag$);\n" - " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" - "}\n" - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeEnumNoTag($name$_.getInt(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeEnum($number$, $name$_.getInt(i));\n" - "}\n"); - } -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .computeEnumSizeNoTag($name$_.getInt(i));\n" - "}\n"); - printer->Print( - "size += dataSize;\n"); - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (!get$capitalized_name$List().isEmpty()) {" - " size += $tag_size$;\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeUInt32SizeNoTag(dataSize);\n" - "}"); - } else { - printer->Print(variables_, - "size += $tag_size$ * $name$_.size();\n"); - } - - // cache the data size for packed fields. - if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && $name$_.equals(other.$name$_);\n"); -} - -void RepeatedImmutableEnumFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + $name$_.hashCode();\n" - "}\n"); -} - -string RepeatedImmutableEnumFieldLiteGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->enum_type()); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_enum_field_lite.h b/windows/include/google/protobuf/compiler/java/java_enum_field_lite.h deleted file mode 100644 index fa004720f..000000000 --- a/windows/include/google/protobuf/compiler/java/java_enum_field_lite.h +++ /dev/null @@ -1,159 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_LITE_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableEnumFieldLiteGenerator : public ImmutableFieldLiteGenerator { - public: - explicit ImmutableEnumFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableEnumFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableEnumFieldLiteGenerator); -}; - -class ImmutableEnumOneofFieldLiteGenerator - : public ImmutableEnumFieldLiteGenerator { - public: - ImmutableEnumOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableEnumOneofFieldLiteGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableEnumOneofFieldLiteGenerator); -}; - -class RepeatedImmutableEnumFieldLiteGenerator - : public ImmutableFieldLiteGenerator { - public: - explicit RepeatedImmutableEnumFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableEnumFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingCodeFromPacked(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableEnumFieldLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_FIELD_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_enum_lite.cc b/windows/include/google/protobuf/compiler/java/java_enum_lite.cc deleted file mode 100644 index 806008ee1..000000000 --- a/windows/include/google/protobuf/compiler/java/java_enum_lite.cc +++ /dev/null @@ -1,226 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -EnumLiteGenerator::EnumLiteGenerator(const EnumDescriptor* descriptor, - bool immutable_api, Context* context) - : descriptor_(descriptor), - immutable_api_(immutable_api), - context_(context), - name_resolver_(context->GetNameResolver()) { - for (int i = 0; i < descriptor_->value_count(); i++) { - const EnumValueDescriptor* value = descriptor_->value(i); - const EnumValueDescriptor* canonical_value = - descriptor_->FindValueByNumber(value->number()); - - if (value == canonical_value) { - canonical_values_.push_back(value); - } else { - Alias alias; - alias.value = value; - alias.canonical_value = canonical_value; - aliases_.push_back(alias); - } - } -} - -EnumLiteGenerator::~EnumLiteGenerator() {} - -void EnumLiteGenerator::Generate(io::Printer* printer) { - WriteEnumDocComment(printer, descriptor_); - MaybePrintGeneratedAnnotation(context_, printer, descriptor_, immutable_api_); - printer->Print( - "public enum $classname$\n" - " implements com.google.protobuf.Internal.EnumLite {\n", - "classname", descriptor_->name()); - printer->Annotate("classname", descriptor_); - printer->Indent(); - - for (int i = 0; i < canonical_values_.size(); i++) { - std::map vars; - vars["name"] = canonical_values_[i]->name(); - vars["number"] = SimpleItoa(canonical_values_[i]->number()); - WriteEnumValueDocComment(printer, canonical_values_[i]); - if (canonical_values_[i]->options().deprecated()) { - printer->Print("@java.lang.Deprecated\n"); - } - printer->Print(vars, - "$name$($number$),\n"); - printer->Annotate("name", canonical_values_[i]); - } - - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print("${$UNRECOGNIZED$}$(-1),\n", "{", "", "}", ""); - printer->Annotate("{", "}", descriptor_); - } - - printer->Print( - ";\n" - "\n"); - - // ----------------------------------------------------------------- - - for (int i = 0; i < aliases_.size(); i++) { - std::map vars; - vars["classname"] = descriptor_->name(); - vars["name"] = aliases_[i].value->name(); - vars["canonical_name"] = aliases_[i].canonical_value->name(); - WriteEnumValueDocComment(printer, aliases_[i].value); - printer->Print(vars, - "public static final $classname$ $name$ = $canonical_name$;\n"); - printer->Annotate("name", aliases_[i].value); - } - - for (int i = 0; i < descriptor_->value_count(); i++) { - std::map vars; - vars["name"] = descriptor_->value(i)->name(); - vars["number"] = SimpleItoa(descriptor_->value(i)->number()); - vars["{"] = ""; - vars["}"] = ""; - WriteEnumValueDocComment(printer, descriptor_->value(i)); - printer->Print(vars, - "public static final int ${$$name$_VALUE$}$ = $number$;\n"); - printer->Annotate("{", "}", descriptor_->value(i)); - } - printer->Print("\n"); - - // ----------------------------------------------------------------- - - printer->Print( - "\n" - "@java.lang.Override\n" - "public final int getNumber() {\n"); - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print( - " if (this == UNRECOGNIZED) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Can't get the number of an unknown enum value.\");\n" - " }\n"); - } - printer->Print( - " return value;\n" - "}\n" - "\n" - "/**\n" - " * @deprecated Use {@link #forNumber(int)} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public static $classname$ valueOf(int value) {\n" - " return forNumber(value);\n" - "}\n" - "\n" - "public static $classname$ forNumber(int value) {\n" - " switch (value) {\n", - "classname", descriptor_->name()); - printer->Indent(); - printer->Indent(); - - for (int i = 0; i < canonical_values_.size(); i++) { - printer->Print( - "case $number$: return $name$;\n", - "name", canonical_values_[i]->name(), - "number", SimpleItoa(canonical_values_[i]->number())); - } - - printer->Outdent(); - printer->Outdent(); - printer->Print( - " default: return null;\n" - " }\n" - "}\n" - "\n" - "public static com.google.protobuf.Internal.EnumLiteMap<$classname$>\n" - " internalGetValueMap() {\n" - " return internalValueMap;\n" - "}\n" - "private static final com.google.protobuf.Internal.EnumLiteMap<\n" - " $classname$> internalValueMap =\n" - " new com.google.protobuf.Internal.EnumLiteMap<$classname$>() {\n" - " @java.lang.Override\n" - " public $classname$ findValueByNumber(int number) {\n" - " return $classname$.forNumber(number);\n" - " }\n" - " };\n" - "\n", - "classname", descriptor_->name()); - - printer->Print( - "private final int value;\n\n" - "private $classname$(int value) {\n", - "classname", descriptor_->name()); - printer->Print( - " this.value = value;\n" - "}\n"); - - printer->Print( - "\n" - "// @@protoc_insertion_point(enum_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - - printer->Outdent(); - printer->Print("}\n\n"); -} - -bool EnumLiteGenerator::CanUseEnumValues() { - if (canonical_values_.size() != descriptor_->value_count()) { - return false; - } - for (int i = 0; i < descriptor_->value_count(); i++) { - if (descriptor_->value(i)->name() != canonical_values_[i]->name()) { - return false; - } - } - return true; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_enum_lite.h b/windows/include/google/protobuf/compiler/java/java_enum_lite.h deleted file mode 100644 index b7be912cb..000000000 --- a/windows/include/google/protobuf/compiler/java/java_enum_lite.h +++ /dev/null @@ -1,98 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_LITE_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class EnumLiteGenerator { - public: - EnumLiteGenerator(const EnumDescriptor* descriptor, bool immutable_api, - Context* context); - ~EnumLiteGenerator(); - - void Generate(io::Printer* printer); - - private: - const EnumDescriptor* descriptor_; - - // The proto language allows multiple enum constants to have the same numeric - // value. Java, however, does not allow multiple enum constants to be - // considered equivalent. We treat the first defined constant for any - // given numeric value as "canonical" and the rest as aliases of that - // canonical value. - std::vector canonical_values_; - - struct Alias { - const EnumValueDescriptor* value; - const EnumValueDescriptor* canonical_value; - }; - std::vector aliases_; - - bool immutable_api_; - - Context* context_; - ClassNameResolver* name_resolver_; - - bool CanUseEnumValues(); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_ENUM_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_extension.cc b/windows/include/google/protobuf/compiler/java/java_extension.cc deleted file mode 100644 index 3eb1370dd..000000000 --- a/windows/include/google/protobuf/compiler/java/java_extension.cc +++ /dev/null @@ -1,173 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -ImmutableExtensionGenerator::ImmutableExtensionGenerator( - const FieldDescriptor* descriptor, Context* context) - : descriptor_(descriptor), context_(context), - name_resolver_(context->GetNameResolver()) { - if (descriptor_->extension_scope() != NULL) { - scope_ = name_resolver_->GetImmutableClassName( - descriptor_->extension_scope()); - } else { - scope_ = name_resolver_->GetImmutableClassName(descriptor_->file()); - } -} - -ImmutableExtensionGenerator::~ImmutableExtensionGenerator() {} - -// Initializes the vars referenced in the generated code templates. -void ExtensionGenerator::InitTemplateVars( - const FieldDescriptor* descriptor, const string& scope, bool immutable, - ClassNameResolver* name_resolver, std::map* vars_pointer) { - std::map &vars = *vars_pointer; - vars["scope"] = scope; - vars["name"] = UnderscoresToCamelCase(descriptor); - vars["containing_type"] = - name_resolver->GetClassName(descriptor->containing_type(), immutable); - vars["number"] = SimpleItoa(descriptor->number()); - vars["constant_name"] = FieldConstantName(descriptor); - vars["index"] = SimpleItoa(descriptor->index()); - vars["default"] = descriptor->is_repeated() ? - "" : DefaultValue(descriptor, immutable, name_resolver); - vars["type_constant"] = FieldTypeName(GetType(descriptor)); - vars["packed"] = descriptor->is_packed() ? "true" : "false"; - vars["enum_map"] = "null"; - vars["prototype"] = "null"; - - JavaType java_type = GetJavaType(descriptor); - string singular_type; - switch (java_type) { - case JAVATYPE_MESSAGE: - singular_type = name_resolver->GetClassName(descriptor->message_type(), - immutable); - vars["prototype"] = singular_type + ".getDefaultInstance()"; - break; - case JAVATYPE_ENUM: - singular_type = name_resolver->GetClassName(descriptor->enum_type(), - immutable); - vars["enum_map"] = singular_type + ".internalGetValueMap()"; - break; - case JAVATYPE_STRING: - singular_type = "java.lang.String"; - break; - case JAVATYPE_BYTES: - singular_type = immutable ? "com.google.protobuf.ByteString" : "byte[]"; - break; - default: - singular_type = BoxedPrimitiveTypeName(java_type); - break; - } - vars["type"] = descriptor->is_repeated() ? - "java.util.List<" + singular_type + ">" : singular_type; - vars["singular_type"] = singular_type; -} - -void ImmutableExtensionGenerator::Generate(io::Printer* printer) { - std::map vars; - const bool kUseImmutableNames = true; - InitTemplateVars(descriptor_, scope_, kUseImmutableNames, name_resolver_, - &vars); - printer->Print(vars, - "public static final int $constant_name$ = $number$;\n"); - - WriteFieldDocComment(printer, descriptor_); - if (descriptor_->extension_scope() == NULL) { - // Non-nested - printer->Print( - vars, - "public static final\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $containing_type$,\n" - " $type$> $name$ = com.google.protobuf.GeneratedMessage\n" - " .newFileScopedGeneratedExtension(\n" - " $singular_type$.class,\n" - " $prototype$);\n"); - } else { - // Nested - printer->Print( - vars, - "public static final\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $containing_type$,\n" - " $type$> $name$ = com.google.protobuf.GeneratedMessage\n" - " .newMessageScopedGeneratedExtension(\n" - " $scope$.getDefaultInstance(),\n" - " $index$,\n" - " $singular_type$.class,\n" - " $prototype$);\n"); - } - printer->Annotate("name", descriptor_); -} - -int ImmutableExtensionGenerator::GenerateNonNestedInitializationCode( - io::Printer* printer) { - int bytecode_estimate = 0; - if (descriptor_->extension_scope() == NULL) { - // Only applies to non-nested extensions. - printer->Print( - "$name$.internalInit(descriptor.getExtensions().get($index$));\n", - "name", UnderscoresToCamelCase(descriptor_), - "index", SimpleItoa(descriptor_->index())); - bytecode_estimate += 21; - } - return bytecode_estimate; -} - -int ImmutableExtensionGenerator::GenerateRegistrationCode( - io::Printer* printer) { - printer->Print( - "registry.add($scope$.$name$);\n", - "scope", scope_, - "name", UnderscoresToCamelCase(descriptor_)); - return 7; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_extension.h b/windows/include/google/protobuf/compiler/java/java_extension.h deleted file mode 100644 index fb8d52015..000000000 --- a/windows/include/google/protobuf/compiler/java/java_extension.h +++ /dev/null @@ -1,113 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__ - -#include -#include - -#include - -namespace google { -namespace protobuf { - class FieldDescriptor; // descriptor.h - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -// Generates code for an extension, which may be within the scope of some -// message or may be at file scope. This is much simpler than FieldGenerator -// since extensions are just simple identifiers with interesting types. -class ExtensionGenerator { - public: - explicit ExtensionGenerator() {} - virtual ~ExtensionGenerator() {} - - virtual void Generate(io::Printer* printer) = 0; - - // Returns an estimate of the number of bytes the printed code will compile to - virtual int GenerateNonNestedInitializationCode(io::Printer* printer) = 0; - - // Returns an estimate of the number of bytes the printed code will compile to - virtual int GenerateRegistrationCode(io::Printer* printer) = 0; - - protected: - static void InitTemplateVars(const FieldDescriptor* descriptor, - const string& scope, - bool immutable, - ClassNameResolver* name_resolver, - std::map* vars_pointer); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); -}; - -class ImmutableExtensionGenerator : public ExtensionGenerator { - public: - explicit ImmutableExtensionGenerator(const FieldDescriptor* descriptor, - Context* context); - virtual ~ImmutableExtensionGenerator(); - - virtual void Generate(io::Printer* printer); - virtual int GenerateNonNestedInitializationCode(io::Printer* printer); - virtual int GenerateRegistrationCode(io::Printer* printer); - - protected: - const FieldDescriptor* descriptor_; - Context* context_; - ClassNameResolver* name_resolver_; - string scope_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_extension_lite.cc b/windows/include/google/protobuf/compiler/java/java_extension_lite.cc deleted file mode 100644 index 70ce8e7d1..000000000 --- a/windows/include/google/protobuf/compiler/java/java_extension_lite.cc +++ /dev/null @@ -1,119 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -ImmutableExtensionLiteGenerator::ImmutableExtensionLiteGenerator( - const FieldDescriptor* descriptor, Context* context) - : descriptor_(descriptor), context_(context), - name_resolver_(context->GetNameResolver()) { - if (descriptor_->extension_scope() != NULL) { - scope_ = name_resolver_->GetImmutableClassName( - descriptor_->extension_scope()); - } else { - scope_ = name_resolver_->GetImmutableClassName(descriptor_->file()); - } -} - -ImmutableExtensionLiteGenerator::~ImmutableExtensionLiteGenerator() {} - -void ImmutableExtensionLiteGenerator::Generate(io::Printer* printer) { - std::map vars; - const bool kUseImmutableNames = true; - InitTemplateVars(descriptor_, scope_, kUseImmutableNames, name_resolver_, - &vars); - printer->Print(vars, - "public static final int $constant_name$ = $number$;\n"); - - WriteFieldDocComment(printer, descriptor_); - if (descriptor_->is_repeated()) { - printer->Print( - vars, - "public static final\n" - " com.google.protobuf.GeneratedMessageLite.GeneratedExtension<\n" - " $containing_type$,\n" - " $type$> $name$ = com.google.protobuf.GeneratedMessageLite\n" - " .newRepeatedGeneratedExtension(\n" - " $containing_type$.getDefaultInstance(),\n" - " $prototype$,\n" - " $enum_map$,\n" - " $number$,\n" - " com.google.protobuf.WireFormat.FieldType.$type_constant$,\n" - " $packed$,\n" - " $singular_type$.class);\n"); - } else { - printer->Print( - vars, - "public static final\n" - " com.google.protobuf.GeneratedMessageLite.GeneratedExtension<\n" - " $containing_type$,\n" - " $type$> $name$ = com.google.protobuf.GeneratedMessageLite\n" - " .newSingularGeneratedExtension(\n" - " $containing_type$.getDefaultInstance(),\n" - " $default$,\n" - " $prototype$,\n" - " $enum_map$,\n" - " $number$,\n" - " com.google.protobuf.WireFormat.FieldType.$type_constant$,\n" - " $singular_type$.class);\n"); - } - printer->Annotate("name", descriptor_); -} - -int ImmutableExtensionLiteGenerator::GenerateNonNestedInitializationCode( - io::Printer* printer) { - return 0; -} - -int ImmutableExtensionLiteGenerator::GenerateRegistrationCode( - io::Printer* printer) { - printer->Print( - "registry.add($scope$.$name$);\n", - "scope", scope_, - "name", UnderscoresToCamelCase(descriptor_)); - return 7; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_extension_lite.h b/windows/include/google/protobuf/compiler/java/java_extension_lite.h deleted file mode 100644 index 4cd49bda2..000000000 --- a/windows/include/google/protobuf/compiler/java/java_extension_lite.h +++ /dev/null @@ -1,76 +0,0 @@ -// 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_JAVA_EXTENSION_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_LITE_H__ - -#include -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -// Generates code for a lite extension, which may be within the scope of some -// message or may be at file scope. This is much simpler than FieldGenerator -// since extensions are just simple identifiers with interesting types. -class ImmutableExtensionLiteGenerator : public ExtensionGenerator { - public: - explicit ImmutableExtensionLiteGenerator(const FieldDescriptor* descriptor, - Context* context); - virtual ~ImmutableExtensionLiteGenerator(); - - virtual void Generate(io::Printer* printer); - - // Returns an estimate of the number of bytes the printed code will compile to - virtual int GenerateNonNestedInitializationCode(io::Printer* printer); - - // Returns an estimate of the number of bytes the printed code will compile to - virtual int GenerateRegistrationCode(io::Printer* printer); - - private: - const FieldDescriptor* descriptor_; - Context* context_; - ClassNameResolver* name_resolver_; - string scope_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableExtensionLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_EXTENSION_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_field.cc b/windows/include/google/protobuf/compiler/java/java_field.cc deleted file mode 100644 index 93de0229a..000000000 --- a/windows/include/google/protobuf/compiler/java/java_field.cc +++ /dev/null @@ -1,302 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { - -ImmutableFieldGenerator* MakeImmutableGenerator( - const FieldDescriptor* field, int messageBitIndex, int builderBitIndex, - Context* context) { - if (field->is_repeated()) { - switch (GetJavaType(field)) { - case JAVATYPE_MESSAGE: - if (IsMapEntry(field->message_type())) { - return new ImmutableMapFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - } else { - return new RepeatedImmutableMessageFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - } - case JAVATYPE_ENUM: - return new RepeatedImmutableEnumFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_STRING: - return new RepeatedImmutableStringFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - default: - return new RepeatedImmutablePrimitiveFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - } - } else { - if (field->containing_oneof()) { - switch (GetJavaType(field)) { - case JAVATYPE_MESSAGE: - return new ImmutableMessageOneofFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_ENUM: - return new ImmutableEnumOneofFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_STRING: - return new ImmutableStringOneofFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - default: - return new ImmutablePrimitiveOneofFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - } - } else { - switch (GetJavaType(field)) { - case JAVATYPE_MESSAGE: - return new ImmutableMessageFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_ENUM: - return new ImmutableEnumFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_STRING: - return new ImmutableStringFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - default: - return new ImmutablePrimitiveFieldGenerator( - field, messageBitIndex, builderBitIndex, context); - } - } - } -} - -ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator( - const FieldDescriptor* field, int messageBitIndex, int builderBitIndex, - Context* context) { - if (field->is_repeated()) { - switch (GetJavaType(field)) { - case JAVATYPE_MESSAGE: - if (IsMapEntry(field->message_type())) { - return new ImmutableMapFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - } else { - return new RepeatedImmutableMessageFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - } - case JAVATYPE_ENUM: - return new RepeatedImmutableEnumFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_STRING: - return new RepeatedImmutableStringFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - default: - return new RepeatedImmutablePrimitiveFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - } - } else { - if (field->containing_oneof()) { - switch (GetJavaType(field)) { - case JAVATYPE_MESSAGE: - return new ImmutableMessageOneofFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_ENUM: - return new ImmutableEnumOneofFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_STRING: - return new ImmutableStringOneofFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - default: - return new ImmutablePrimitiveOneofFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - } - } else { - switch (GetJavaType(field)) { - case JAVATYPE_MESSAGE: - return new ImmutableMessageFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_ENUM: - return new ImmutableEnumFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - case JAVATYPE_STRING: - return new ImmutableStringFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - default: - return new ImmutablePrimitiveFieldLiteGenerator( - field, messageBitIndex, builderBitIndex, context); - } - } - } -} - - -static inline void ReportUnexpectedPackedFieldsCall(io::Printer* printer) { - // Reaching here indicates a bug. Cases are: - // - This FieldGenerator should support packing, - // but this method should be overridden. - // - This FieldGenerator doesn't support packing, and this method - // should never have been called. - GOOGLE_LOG(FATAL) << "GenerateParsingCodeFromPacked() " - << "called on field generator that does not support packing."; -} - -} // namespace - -ImmutableFieldGenerator::~ImmutableFieldGenerator() {} - -void ImmutableFieldGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - ReportUnexpectedPackedFieldsCall(printer); -} - -ImmutableFieldLiteGenerator::~ImmutableFieldLiteGenerator() {} - -void ImmutableFieldLiteGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - ReportUnexpectedPackedFieldsCall(printer); -} - -// =================================================================== - -template <> -FieldGeneratorMap::FieldGeneratorMap( - const Descriptor* descriptor, Context* context) - : descriptor_(descriptor), - field_generators_(descriptor->field_count()) { - - // Construct all the FieldGenerators and assign them bit indices for their - // bit fields. - int messageBitIndex = 0; - int builderBitIndex = 0; - for (int i = 0; i < descriptor->field_count(); i++) { - ImmutableFieldGenerator* generator = MakeImmutableGenerator( - descriptor->field(i), messageBitIndex, builderBitIndex, context); - field_generators_[i].reset(generator); - messageBitIndex += generator->GetNumBitsForMessage(); - builderBitIndex += generator->GetNumBitsForBuilder(); - } -} - -template<> -FieldGeneratorMap::~FieldGeneratorMap() {} - -template <> -FieldGeneratorMap::FieldGeneratorMap( - const Descriptor* descriptor, Context* context) - : descriptor_(descriptor), - field_generators_(descriptor->field_count()) { - // Construct all the FieldGenerators and assign them bit indices for their - // bit fields. - int messageBitIndex = 0; - int builderBitIndex = 0; - for (int i = 0; i < descriptor->field_count(); i++) { - ImmutableFieldLiteGenerator* generator = MakeImmutableLiteGenerator( - descriptor->field(i), messageBitIndex, builderBitIndex, context); - field_generators_[i].reset(generator); - messageBitIndex += generator->GetNumBitsForMessage(); - builderBitIndex += generator->GetNumBitsForBuilder(); - } -} - -template<> -FieldGeneratorMap::~FieldGeneratorMap() {} - - -void SetCommonFieldVariables(const FieldDescriptor* descriptor, - const FieldGeneratorInfo* info, - std::map* variables) { - (*variables)["field_name"] = descriptor->name(); - (*variables)["name"] = info->name; - (*variables)["classname"] = descriptor->containing_type()->name(); - (*variables)["capitalized_name"] = info->capitalized_name; - (*variables)["disambiguated_reason"] = info->disambiguated_reason; - (*variables)["constant_name"] = FieldConstantName(descriptor); - (*variables)["number"] = SimpleItoa(descriptor->number()); - // These variables are placeholders to pick out the beginning and ends of - // identifiers for annotations (when doing so with existing variables would - // be ambiguous or impossible). They should never be set to anything but the - // empty string. - (*variables)["{"] = ""; - (*variables)["}"] = ""; -} - -void SetCommonOneofVariables(const FieldDescriptor* descriptor, - const OneofGeneratorInfo* info, - std::map* variables) { - (*variables)["oneof_name"] = info->name; - (*variables)["oneof_capitalized_name"] = info->capitalized_name; - (*variables)["oneof_index"] = - SimpleItoa(descriptor->containing_oneof()->index()); - (*variables)["set_oneof_case_message"] = info->name + - "Case_ = " + SimpleItoa(descriptor->number()); - (*variables)["clear_oneof_case_message"] = info->name + - "Case_ = 0"; - (*variables)["has_oneof_case_message"] = info->name + - "Case_ == " + SimpleItoa(descriptor->number()); -} - -void PrintExtraFieldInfo(const std::map& variables, - io::Printer* printer) { - const std::map::const_iterator it = - variables.find("disambiguated_reason"); - if (it != variables.end() && !it->second.empty()) { - printer->Print( - variables, - "// An alternative name is used for field \"$field_name$\" because:\n" - "// $disambiguated_reason$\n"); - } -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_field.h b/windows/include/google/protobuf/compiler/java/java_field.h deleted file mode 100644 index 7275c0998..000000000 --- a/windows/include/google/protobuf/compiler/java/java_field.h +++ /dev/null @@ -1,203 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__ - -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableFieldGenerator { - public: - ImmutableFieldGenerator() {} - virtual ~ImmutableFieldGenerator(); - - virtual int GetNumBitsForMessage() const = 0; - virtual int GetNumBitsForBuilder() const = 0; - virtual void GenerateInterfaceMembers(io::Printer* printer) const = 0; - virtual void GenerateMembers(io::Printer* printer) const = 0; - virtual void GenerateBuilderMembers(io::Printer* printer) const = 0; - virtual void GenerateInitializationCode(io::Printer* printer) const = 0; - virtual void GenerateBuilderClearCode(io::Printer* printer) const = 0; - virtual void GenerateMergingCode(io::Printer* printer) const = 0; - virtual void GenerateBuildingCode(io::Printer* printer) const = 0; - virtual void GenerateParsingCode(io::Printer* printer) const = 0; - virtual void GenerateParsingCodeFromPacked(io::Printer* printer) const; - virtual void GenerateParsingDoneCode(io::Printer* printer) const = 0; - virtual void GenerateSerializationCode(io::Printer* printer) const = 0; - virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0; - virtual void GenerateFieldBuilderInitializationCode(io::Printer* printer) - const = 0; - - virtual void GenerateEqualsCode(io::Printer* printer) const = 0; - virtual void GenerateHashCode(io::Printer* printer) const = 0; - - virtual string GetBoxedType() const = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableFieldGenerator); -}; - -class ImmutableFieldLiteGenerator { - public: - ImmutableFieldLiteGenerator() {} - virtual ~ImmutableFieldLiteGenerator(); - - virtual int GetNumBitsForMessage() const = 0; - virtual int GetNumBitsForBuilder() const = 0; - virtual void GenerateInterfaceMembers(io::Printer* printer) const = 0; - virtual void GenerateMembers(io::Printer* printer) const = 0; - virtual void GenerateBuilderMembers(io::Printer* printer) const = 0; - virtual void GenerateInitializationCode(io::Printer* printer) const = 0; - virtual void GenerateVisitCode(io::Printer* printer) const = 0; - virtual void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) - const = 0; - virtual void GenerateParsingCode(io::Printer* printer) const = 0; - virtual void GenerateParsingCodeFromPacked(io::Printer* printer) const; - virtual void GenerateParsingDoneCode(io::Printer* printer) const = 0; - virtual void GenerateSerializationCode(io::Printer* printer) const = 0; - virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0; - virtual void GenerateFieldBuilderInitializationCode(io::Printer* printer) - const = 0; - - virtual void GenerateEqualsCode(io::Printer* printer) const = 0; - virtual void GenerateHashCode(io::Printer* printer) const = 0; - - - virtual string GetBoxedType() const = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableFieldLiteGenerator); -}; - - -// Convenience class which constructs FieldGenerators for a Descriptor. -template -class FieldGeneratorMap { - public: - explicit FieldGeneratorMap(const Descriptor* descriptor, - Context* context); - ~FieldGeneratorMap(); - - const FieldGeneratorType& get(const FieldDescriptor* field) const; - - private: - const Descriptor* descriptor_; - Context* context_; - ClassNameResolver* name_resolver_; - std::vector> field_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); -}; - -template -inline const FieldGeneratorType& -FieldGeneratorMap::get(const FieldDescriptor* field) const { - GOOGLE_CHECK_EQ(field->containing_type(), descriptor_); - return *field_generators_[field->index()]; -} - -// Instantiate template for mutable and immutable maps. -template<> -FieldGeneratorMap:: -FieldGeneratorMap(const Descriptor* descriptor, - Context* context); - -template<> -FieldGeneratorMap::~FieldGeneratorMap(); - - -template <> -FieldGeneratorMap::FieldGeneratorMap( - const Descriptor* descriptor, Context* context); - -template <> -FieldGeneratorMap::~FieldGeneratorMap(); - - -// Field information used in FieldGeneartors. -struct FieldGeneratorInfo { - string name; - string capitalized_name; - string disambiguated_reason; -}; - -// Oneof information used in OneofFieldGenerators. -struct OneofGeneratorInfo { - string name; - string capitalized_name; -}; - -// Set some common variables used in variable FieldGenerators. -void SetCommonFieldVariables(const FieldDescriptor* descriptor, - const FieldGeneratorInfo* info, - std::map* variables); - -// Set some common oneof variables used in OneofFieldGenerators. -void SetCommonOneofVariables(const FieldDescriptor* descriptor, - const OneofGeneratorInfo* info, - std::map* variables); - -// Print useful comments before a field's accessors. -void PrintExtraFieldInfo(const std::map& variables, - io::Printer* printer); - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_file.cc b/windows/include/google/protobuf/compiler/java/java_file.cc deleted file mode 100644 index 5583b7795..000000000 --- a/windows/include/google/protobuf/compiler/java/java_file.cc +++ /dev/null @@ -1,677 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { - -struct FieldDescriptorCompare { - bool operator ()(const FieldDescriptor* f1, const FieldDescriptor* f2) const { - if(f1 == NULL) { - return false; - } - if(f2 == NULL) { - return true; - } - return f1->full_name() < f2->full_name(); - } -}; - -typedef std::set FieldDescriptorSet; - -// Recursively searches the given message to collect extensions. -// Returns true if all the extensions can be recognized. The extensions will be -// appended in to the extensions parameter. -// Returns false when there are unknown fields, in which case the data in the -// extensions output parameter is not reliable and should be discarded. -bool CollectExtensions(const Message& message, - FieldDescriptorSet* extensions) { - const Reflection* reflection = message.GetReflection(); - - // There are unknown fields that could be extensions, thus this call fails. - if (reflection->GetUnknownFields(message).field_count() > 0) return false; - - std::vector fields; - reflection->ListFields(message, &fields); - - for (int i = 0; i < fields.size(); i++) { - if (fields[i]->is_extension()) extensions->insert(fields[i]); - - if (GetJavaType(fields[i]) == JAVATYPE_MESSAGE) { - if (fields[i]->is_repeated()) { - int size = reflection->FieldSize(message, fields[i]); - for (int j = 0; j < size; j++) { - const Message& sub_message = - reflection->GetRepeatedMessage(message, fields[i], j); - if (!CollectExtensions(sub_message, extensions)) return false; - } - } else { - const Message& sub_message = reflection->GetMessage(message, fields[i]); - if (!CollectExtensions(sub_message, extensions)) return false; - } - } - } - - return true; -} - -// Finds all extensions in the given message and its sub-messages. If the -// message contains unknown fields (which could be extensions), then those -// extensions are defined in alternate_pool. -// The message will be converted to a DynamicMessage backed by alternate_pool -// in order to handle this case. -void CollectExtensions(const FileDescriptorProto& file_proto, - const DescriptorPool& alternate_pool, - FieldDescriptorSet* extensions, - const string& file_data) { - if (!CollectExtensions(file_proto, extensions)) { - // There are unknown fields in the file_proto, which are probably - // extensions. We need to parse the data into a dynamic message based on the - // builder-pool to find out all extensions. - const Descriptor* file_proto_desc = alternate_pool.FindMessageTypeByName( - file_proto.GetDescriptor()->full_name()); - GOOGLE_CHECK(file_proto_desc) - << "Find unknown fields in FileDescriptorProto when building " - << file_proto.name() - << ". It's likely that those fields are custom options, however, " - "descriptor.proto is not in the transitive dependencies. " - "This normally should not happen. Please report a bug."; - DynamicMessageFactory factory; - std::unique_ptr dynamic_file_proto( - factory.GetPrototype(file_proto_desc)->New()); - GOOGLE_CHECK(dynamic_file_proto.get() != NULL); - GOOGLE_CHECK(dynamic_file_proto->ParseFromString(file_data)); - - // Collect the extensions again from the dynamic message. There should be no - // more unknown fields this time, i.e. all the custom options should be - // parsed as extensions now. - extensions->clear(); - GOOGLE_CHECK(CollectExtensions(*dynamic_file_proto, extensions)) - << "Find unknown fields in FileDescriptorProto when building " - << file_proto.name() - << ". It's likely that those fields are custom options, however, " - "those options cannot be recognized in the builder pool. " - "This normally should not happen. Please report a bug."; - } -} - -// Our static initialization methods can become very, very large. -// So large that if we aren't careful we end up blowing the JVM's -// 64K bytes of bytecode/method. Fortunately, since these static -// methods are executed only once near the beginning of a program, -// there's usually plenty of stack space available and we can -// extend our methods by simply chaining them to another method -// with a tail call. This inserts the sequence call-next-method, -// end this one, begin-next-method as needed. -void MaybeRestartJavaMethod(io::Printer* printer, - int *bytecode_estimate, - int *method_num, - const char *chain_statement, - const char *method_decl) { - // The goal here is to stay under 64K bytes of jvm bytecode/method, - // since otherwise we hit a hardcoded limit in the jvm and javac will - // then fail with the error "code too large". This limit lets our - // estimates be off by a factor of two and still we're okay. - static const int bytesPerMethod = kMaxStaticSize; - - if ((*bytecode_estimate) > bytesPerMethod) { - ++(*method_num); - printer->Print(chain_statement, "method_num", SimpleItoa(*method_num)); - printer->Outdent(); - printer->Print("}\n"); - printer->Print(method_decl, "method_num", SimpleItoa(*method_num)); - printer->Indent(); - *bytecode_estimate = 0; - } -} -} // namespace - -FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options, - bool immutable_api) - : file_(file), - java_package_(FileJavaPackage(file, immutable_api)), - message_generators_(file->message_type_count()), - extension_generators_(file->extension_count()), - context_(new Context(file, options)), - name_resolver_(context_->GetNameResolver()), - options_(options), - immutable_api_(immutable_api) { - classname_ = name_resolver_->GetFileClassName(file, immutable_api); - generator_factory_.reset( - new ImmutableGeneratorFactory(context_.get())); - for (int i = 0; i < file_->message_type_count(); ++i) { - message_generators_[i].reset( - generator_factory_->NewMessageGenerator(file_->message_type(i))); - } - for (int i = 0; i < file_->extension_count(); ++i) { - extension_generators_[i].reset( - generator_factory_->NewExtensionGenerator(file_->extension(i))); - } -} - -FileGenerator::~FileGenerator() {} - -bool FileGenerator::Validate(string* error) { - // Check that no class name matches the file's class name. This is a common - // problem that leads to Java compile errors that can be hard to understand. - // It's especially bad when using the java_multiple_files, since we would - // end up overwriting the outer class with one of the inner ones. - if (name_resolver_->HasConflictingClassName(file_, classname_)) { - error->assign(file_->name()); - error->append( - ": Cannot generate Java output because the file's outer class name, \""); - error->append(classname_); - error->append( - "\", matches the name of one of the types declared inside it. " - "Please either rename the type or use the java_outer_classname " - "option to specify a different outer class name for the .proto file."); - return false; - } - // Print a warning if optimize_for = LITE_RUNTIME is used. - if (file_->options().optimize_for() == FileOptions::LITE_RUNTIME) { - GOOGLE_LOG(WARNING) - << "The optimize_for = LITE_RUNTIME option is no longer supported by " - << "protobuf Java code generator and may generate broken code. It " - << "will be ignored by protoc in the future and protoc will always " - << "generate full runtime code for Java. To use Java Lite runtime, " - << "users should use the Java Lite plugin instead. See:\n" - << " https://github.com/google/protobuf/blob/master/java/lite.md"; - } - return true; -} - -void FileGenerator::Generate(io::Printer* printer) { - // We don't import anything because we refer to all classes by their - // fully-qualified names in the generated source. - printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n", - "filename", file_->name()); - if (!java_package_.empty()) { - printer->Print( - "package $package$;\n" - "\n", - "package", java_package_); - } - PrintGeneratedAnnotation( - printer, '$', options_.annotate_code ? classname_ + ".java.pb.meta" : ""); - printer->Print( - "$deprecation$public final class $classname$ {\n" - " private $ctor$() {}\n", - "deprecation", file_->options().deprecated() ? - "@java.lang.Deprecated " : "", - "classname", classname_, - "ctor", classname_); - printer->Annotate("classname", file_->name()); - printer->Indent(); - - // ----------------------------------------------------------------- - - printer->Print( - "public static void registerAllExtensions(\n" - " com.google.protobuf.ExtensionRegistryLite registry) {\n"); - - printer->Indent(); - - for (int i = 0; i < file_->extension_count(); i++) { - extension_generators_[i]->GenerateRegistrationCode(printer); - } - - for (int i = 0; i < file_->message_type_count(); i++) { - message_generators_[i]->GenerateExtensionRegistrationCode(printer); - } - - printer->Outdent(); - printer->Print( - "}\n"); - if (HasDescriptorMethods(file_, context_->EnforceLite())) { - // Overload registerAllExtensions for the non-lite usage to - // redundantly maintain the original signature (this is - // redundant because ExtensionRegistryLite now invokes - // ExtensionRegistry in the non-lite usage). Intent is - // to remove this in the future. - printer->Print( - "\n" - "public static void registerAllExtensions(\n" - " com.google.protobuf.ExtensionRegistry registry) {\n" - " registerAllExtensions(\n" - " (com.google.protobuf.ExtensionRegistryLite) registry);\n" - "}\n"); - } - - // ----------------------------------------------------------------- - - if (!MultipleJavaFiles(file_, immutable_api_)) { - for (int i = 0; i < file_->enum_type_count(); i++) { - if (HasDescriptorMethods(file_, context_->EnforceLite())) { - EnumGenerator(file_->enum_type(i), immutable_api_, context_.get()) - .Generate(printer); - } else { - EnumLiteGenerator(file_->enum_type(i), immutable_api_, context_.get()) - .Generate(printer); - } - } - for (int i = 0; i < file_->message_type_count(); i++) { - message_generators_[i]->GenerateInterface(printer); - message_generators_[i]->Generate(printer); - } - if (HasGenericServices(file_, context_->EnforceLite())) { - for (int i = 0; i < file_->service_count(); i++) { - std::unique_ptr generator( - generator_factory_->NewServiceGenerator(file_->service(i))); - generator->Generate(printer); - } - } - } - - // Extensions must be generated in the outer class since they are values, - // not classes. - for (int i = 0; i < file_->extension_count(); i++) { - extension_generators_[i]->Generate(printer); - } - - // Static variables. We'd like them to be final if possible, but due to - // the JVM's 64k size limit on static blocks, we have to initialize some - // of them in methods; thus they cannot be final. - int static_block_bytecode_estimate = 0; - for (int i = 0; i < file_->message_type_count(); i++) { - message_generators_[i]->GenerateStaticVariables( - printer, &static_block_bytecode_estimate); - } - - printer->Print("\n"); - - if (HasDescriptorMethods(file_, context_->EnforceLite())) { - if (immutable_api_) { - GenerateDescriptorInitializationCodeForImmutable(printer); - } else { - GenerateDescriptorInitializationCodeForMutable(printer); - } - } else { - printer->Print( - "static {\n"); - printer->Indent(); - int bytecode_estimate = 0; - int method_num = 0; - - for (int i = 0; i < file_->message_type_count(); i++) { - bytecode_estimate += message_generators_[i]->GenerateStaticVariableInitializers(printer); - MaybeRestartJavaMethod( - printer, - &bytecode_estimate, &method_num, - "_clinit_autosplit_$method_num$();\n", - "private static void _clinit_autosplit_$method_num$() {\n"); - } - - printer->Outdent(); - printer->Print( - "}\n"); - } - - printer->Print( - "\n" - "// @@protoc_insertion_point(outer_class_scope)\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -void FileGenerator::GenerateDescriptorInitializationCodeForImmutable( - io::Printer* printer) { - printer->Print( - "public static com.google.protobuf.Descriptors.FileDescriptor\n" - " getDescriptor() {\n" - " return descriptor;\n" - "}\n" - "private static $final$ com.google.protobuf.Descriptors.FileDescriptor\n" - " descriptor;\n" - "static {\n", - // TODO(dweis): Mark this as final. - "final", ""); - printer->Indent(); - - SharedCodeGenerator shared_code_generator(file_, options_); - shared_code_generator.GenerateDescriptors(printer); - - int bytecode_estimate = 0; - int method_num = 0; - - for (int i = 0; i < file_->message_type_count(); i++) { - bytecode_estimate += message_generators_[i]->GenerateStaticVariableInitializers(printer); - MaybeRestartJavaMethod( - printer, - &bytecode_estimate, &method_num, - "_clinit_autosplit_dinit_$method_num$();\n", - "private static void _clinit_autosplit_dinit_$method_num$() {\n"); - } - for (int i = 0; i < file_->extension_count(); i++) { - bytecode_estimate += extension_generators_[i]->GenerateNonNestedInitializationCode(printer); - MaybeRestartJavaMethod( - printer, - &bytecode_estimate, &method_num, - "_clinit_autosplit_dinit_$method_num$();\n", - "private static void _clinit_autosplit_dinit_$method_num$() {\n"); - } - - // Proto compiler builds a DescriptorPool, which holds all the descriptors to - // generate, when processing the ".proto" files. We call this DescriptorPool - // the parsed pool (a.k.a. file_->pool()). - // - // Note that when users try to extend the (.*)DescriptorProto in their - // ".proto" files, it does not affect the pre-built FileDescriptorProto class - // in proto compiler. When we put the descriptor data in the file_proto, those - // extensions become unknown fields. - // - // Now we need to find out all the extension value to the (.*)DescriptorProto - // in the file_proto message, and prepare an ExtensionRegistry to return. - // - // To find those extensions, we need to parse the data into a dynamic message - // of the FileDescriptor based on the builder-pool, then we can use - // reflections to find all extension fields - FileDescriptorProto file_proto; - file_->CopyTo(&file_proto); - string file_data; - file_proto.SerializeToString(&file_data); - FieldDescriptorSet extensions; - CollectExtensions(file_proto, *file_->pool(), &extensions, file_data); - - if (extensions.size() > 0) { - // Must construct an ExtensionRegistry containing all existing extensions - // and use it to parse the descriptor data again to recognize extensions. - printer->Print( - "com.google.protobuf.ExtensionRegistry registry =\n" - " com.google.protobuf.ExtensionRegistry.newInstance();\n"); - FieldDescriptorSet::iterator it; - for (it = extensions.begin(); it != extensions.end(); it++) { - std::unique_ptr generator( - generator_factory_->NewExtensionGenerator(*it)); - bytecode_estimate += generator->GenerateRegistrationCode(printer); - MaybeRestartJavaMethod( - printer, - &bytecode_estimate, &method_num, - "_clinit_autosplit_dinit_$method_num$(registry);\n", - "private static void _clinit_autosplit_dinit_$method_num$(\n" - " com.google.protobuf.ExtensionRegistry registry) {\n"); - } - printer->Print( - "com.google.protobuf.Descriptors.FileDescriptor\n" - " .internalUpdateFileDescriptor(descriptor, registry);\n"); - } - - // Force descriptor initialization of all dependencies. - for (int i = 0; i < file_->dependency_count(); i++) { - if (ShouldIncludeDependency(file_->dependency(i), true)) { - string dependency = - name_resolver_->GetImmutableClassName(file_->dependency(i)); - printer->Print( - "$dependency$.getDescriptor();\n", - "dependency", dependency); - } - } - - printer->Outdent(); - printer->Print( - "}\n"); -} - -void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer* printer) { - printer->Print( - "public static com.google.protobuf.Descriptors.FileDescriptor\n" - " getDescriptor() {\n" - " return descriptor;\n" - "}\n" - "private static final com.google.protobuf.Descriptors.FileDescriptor\n" - " descriptor;\n" - "static {\n"); - printer->Indent(); - - printer->Print( - "descriptor = $immutable_package$.$descriptor_classname$.descriptor;\n", - "immutable_package", FileJavaPackage(file_, true), - "descriptor_classname", name_resolver_->GetDescriptorClassName(file_)); - - for (int i = 0; i < file_->message_type_count(); i++) { - message_generators_[i]->GenerateStaticVariableInitializers(printer); - } - for (int i = 0; i < file_->extension_count(); i++) { - extension_generators_[i]->GenerateNonNestedInitializationCode(printer); - } - - // Check if custom options exist. If any, try to load immutable classes since - // custom options are only represented with immutable messages. - FileDescriptorProto file_proto; - file_->CopyTo(&file_proto); - string file_data; - file_proto.SerializeToString(&file_data); - FieldDescriptorSet extensions; - CollectExtensions(file_proto, *file_->pool(), &extensions, file_data); - - if (extensions.size() > 0) { - // Try to load immutable messages' outer class. Its initialization code - // will take care of interpreting custom options. - printer->Print( - "try {\n" - // Note that we have to load the immutable class dynamically here as - // we want the mutable code to be independent from the immutable code - // at compile time. It is required to implement dual-compile for - // mutable and immutable API in blaze. - " java.lang.Class immutableClass = java.lang.Class.forName(\n" - " \"$immutable_classname$\");\n" - "} catch (java.lang.ClassNotFoundException e) {\n", - "immutable_classname", name_resolver_->GetImmutableClassName(file_)); - printer->Indent(); - - // The immutable class can not be found. We try our best to collect all - // custom option extensions to interpret the custom options. - printer->Print( - "com.google.protobuf.ExtensionRegistry registry =\n" - " com.google.protobuf.ExtensionRegistry.newInstance();\n" - "com.google.protobuf.MessageLite defaultExtensionInstance = null;\n"); - FieldDescriptorSet::iterator it; - for (it = extensions.begin(); it != extensions.end(); it++) { - const FieldDescriptor* field = *it; - string scope; - if (field->extension_scope() != NULL) { - scope = name_resolver_->GetMutableClassName(field->extension_scope()) + - ".getDescriptor()"; - } else { - scope = FileJavaPackage(field->file(), true) + "." + - name_resolver_->GetDescriptorClassName(field->file()) + - ".descriptor"; - } - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - printer->Print( - "defaultExtensionInstance = com.google.protobuf.Internal\n" - " .getDefaultInstance(\"$class$\");\n" - "if (defaultExtensionInstance != null) {\n" - " registry.add(\n" - " $scope$.getExtensions().get($index$),\n" - " (com.google.protobuf.Message) defaultExtensionInstance);\n" - "}\n", - "scope", scope, "index", SimpleItoa(field->index()), "class", - name_resolver_->GetImmutableClassName(field->message_type())); - } else { - printer->Print("registry.add($scope$.getExtensions().get($index$));\n", - "scope", scope, "index", SimpleItoa(field->index())); - } - } - printer->Print( - "com.google.protobuf.Descriptors.FileDescriptor\n" - " .internalUpdateFileDescriptor(descriptor, registry);\n"); - - printer->Outdent(); - printer->Print("}\n"); - } - - // Force descriptor initialization of all dependencies. - for (int i = 0; i < file_->dependency_count(); i++) { - if (ShouldIncludeDependency(file_->dependency(i), false)) { - string dependency = name_resolver_->GetMutableClassName( - file_->dependency(i)); - printer->Print( - "$dependency$.getDescriptor();\n", - "dependency", dependency); - } - } - - printer->Outdent(); - printer->Print( - "}\n"); -} - -template -static void GenerateSibling(const string& package_dir, - const string& java_package, - const DescriptorClass* descriptor, - GeneratorContext* context, - std::vector* file_list, bool annotate_code, - std::vector* annotation_list, - const string& name_suffix, - GeneratorClass* generator, - void (GeneratorClass::*pfn)(io::Printer* printer)) { - string filename = package_dir + descriptor->name() + name_suffix + ".java"; - file_list->push_back(filename); - string info_full_path = filename + ".pb.meta"; - GeneratedCodeInfo annotations; - io::AnnotationProtoCollector annotation_collector( - &annotations); - - std::unique_ptr output(context->Open(filename)); - io::Printer printer(output.get(), '$', - annotate_code ? &annotation_collector : NULL); - - printer.Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n", - "filename", descriptor->file()->name()); - if (!java_package.empty()) { - printer.Print( - "package $package$;\n" - "\n", - "package", java_package); - } - - (generator->*pfn)(&printer); - - if (annotate_code) { - std::unique_ptr info_output( - context->Open(info_full_path)); - annotations.SerializeToZeroCopyStream(info_output.get()); - annotation_list->push_back(info_full_path); - } -} - -void FileGenerator::GenerateSiblings(const string& package_dir, - GeneratorContext* context, - std::vector* file_list, - std::vector* annotation_list) { - if (MultipleJavaFiles(file_, immutable_api_)) { - for (int i = 0; i < file_->enum_type_count(); i++) { - if (HasDescriptorMethods(file_, context_->EnforceLite())) { - EnumGenerator generator(file_->enum_type(i), immutable_api_, - context_.get()); - GenerateSibling( - package_dir, java_package_, file_->enum_type(i), context, file_list, - options_.annotate_code, annotation_list, "", &generator, - &EnumGenerator::Generate); - } else { - EnumLiteGenerator generator(file_->enum_type(i), immutable_api_, - context_.get()); - GenerateSibling( - package_dir, java_package_, file_->enum_type(i), context, file_list, - options_.annotate_code, annotation_list, "", &generator, - &EnumLiteGenerator::Generate); - } - } - for (int i = 0; i < file_->message_type_count(); i++) { - if (immutable_api_) { - GenerateSibling( - package_dir, java_package_, file_->message_type(i), context, - file_list, options_.annotate_code, annotation_list, "OrBuilder", - message_generators_[i].get(), &MessageGenerator::GenerateInterface); - } - GenerateSibling( - package_dir, java_package_, file_->message_type(i), context, - file_list, options_.annotate_code, annotation_list, "", - message_generators_[i].get(), &MessageGenerator::Generate); - } - if (HasGenericServices(file_, context_->EnforceLite())) { - for (int i = 0; i < file_->service_count(); i++) { - std::unique_ptr generator( - generator_factory_->NewServiceGenerator(file_->service(i))); - GenerateSibling( - package_dir, java_package_, file_->service(i), context, file_list, - options_.annotate_code, annotation_list, "", generator.get(), - &ServiceGenerator::Generate); - } - } - } -} - -bool FileGenerator::ShouldIncludeDependency( - const FileDescriptor* descriptor, bool immutable_api) { - return true; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_file.h b/windows/include/google/protobuf/compiler/java/java_file.h deleted file mode 100644 index 78833a458..000000000 --- a/windows/include/google/protobuf/compiler/java/java_file.h +++ /dev/null @@ -1,117 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__ - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - class FileDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } - namespace compiler { - class GeneratorContext; // code_generator.h - namespace java { - class Context; // context.h - class MessageGenerator; // message.h - class GeneratorFactory; // generator_factory.h - class ExtensionGenerator; // extension.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class FileGenerator { - public: - FileGenerator(const FileDescriptor* file, const Options& options, - bool immutable_api = true); - ~FileGenerator(); - - // Checks for problems that would otherwise lead to cryptic compile errors. - // Returns true if there are no problems, or writes an error description to - // the given string and returns false otherwise. - bool Validate(string* error); - - void Generate(io::Printer* printer); - - // If we aren't putting everything into one file, this will write all the - // files other than the outer file (i.e. one for each message, enum, and - // service type). - void GenerateSiblings(const string& package_dir, - GeneratorContext* generator_context, - std::vector* file_list, - std::vector* annotation_list); - - const string& java_package() { return java_package_; } - const string& classname() { return classname_; } - - private: - void GenerateDescriptorInitializationCodeForImmutable(io::Printer* printer); - void GenerateDescriptorInitializationCodeForMutable(io::Printer* printer); - - bool ShouldIncludeDependency(const FileDescriptor* descriptor, - bool immutable_api_); - - const FileDescriptor* file_; - string java_package_; - string classname_; - - std::vector> message_generators_; - std::vector> extension_generators_; - std::unique_ptr generator_factory_; - std::unique_ptr context_; - ClassNameResolver* name_resolver_; - const Options options_; - bool immutable_api_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_generator.cc b/windows/include/google/protobuf/compiler/java/java_generator.cc deleted file mode 100644 index a5b2e7841..000000000 --- a/windows/include/google/protobuf/compiler/java/java_generator.cc +++ /dev/null @@ -1,201 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - - -JavaGenerator::JavaGenerator() {} -JavaGenerator::~JavaGenerator() {} - -bool JavaGenerator::Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - // ----------------------------------------------------------------- - // parse generator options - - - std::vector > options; - ParseGeneratorParameter(parameter, &options); - Options file_options; - - for (int i = 0; i < options.size(); i++) { - if (options[i].first == "output_list_file") { - file_options.output_list_file = options[i].second; - } else if (options[i].first == "immutable") { - file_options.generate_immutable_code = true; - } else if (options[i].first == "mutable") { - file_options.generate_mutable_code = true; - } else if (options[i].first == "shared") { - file_options.generate_shared_code = true; - } else if (options[i].first == "annotate_code") { - file_options.annotate_code = true; - } else if (options[i].first == "annotation_list_file") { - file_options.annotation_list_file = options[i].second; - } else { - *error = "Unknown generator option: " + options[i].first; - return false; - } - } - - if (file_options.enforce_lite && file_options.generate_mutable_code) { - *error = "lite runtime generator option cannot be used with mutable API."; - return false; - } - - // By default we generate immutable code and shared code for immutable API. - if (!file_options.generate_immutable_code && - !file_options.generate_mutable_code && - !file_options.generate_shared_code) { - file_options.generate_immutable_code = true; - file_options.generate_shared_code = true; - } - - // ----------------------------------------------------------------- - - - std::vector all_files; - std::vector all_annotations; - - - std::vector file_generators; - if (file_options.generate_immutable_code) { - file_generators.push_back(new FileGenerator(file, file_options, - /* immutable = */ true)); - } - if (file_options.generate_mutable_code) { - file_generators.push_back(new FileGenerator(file, file_options, - /* mutable = */ false)); - } - for (int i = 0; i < file_generators.size(); ++i) { - if (!file_generators[i]->Validate(error)) { - for (int j = 0; j < file_generators.size(); ++j) { - delete file_generators[j]; - } - return false; - } - } - - for (int i = 0; i < file_generators.size(); ++i) { - FileGenerator* file_generator = file_generators[i]; - - string package_dir = JavaPackageToDir(file_generator->java_package()); - - string java_filename = package_dir; - java_filename += file_generator->classname(); - java_filename += ".java"; - all_files.push_back(java_filename); - string info_full_path = java_filename + ".pb.meta"; - if (file_options.annotate_code) { - all_annotations.push_back(info_full_path); - } - - // Generate main java file. - std::unique_ptr output( - context->Open(java_filename)); - GeneratedCodeInfo annotations; - io::AnnotationProtoCollector annotation_collector( - &annotations); - io::Printer printer(output.get(), '$', file_options.annotate_code - ? &annotation_collector - : NULL); - - file_generator->Generate(&printer); - - // Generate sibling files. - file_generator->GenerateSiblings(package_dir, context, &all_files, - &all_annotations); - - if (file_options.annotate_code) { - std::unique_ptr info_output( - context->Open(info_full_path)); - annotations.SerializeToZeroCopyStream(info_output.get()); - } - } - - for (int i = 0; i < file_generators.size(); ++i) { - delete file_generators[i]; - } - file_generators.clear(); - - // Generate output list if requested. - if (!file_options.output_list_file.empty()) { - // Generate output list. This is just a simple text file placed in a - // deterministic location which lists the .java files being generated. - std::unique_ptr srclist_raw_output( - context->Open(file_options.output_list_file)); - io::Printer srclist_printer(srclist_raw_output.get(), '$'); - for (int i = 0; i < all_files.size(); i++) { - srclist_printer.Print("$filename$\n", "filename", all_files[i]); - } - } - - if (!file_options.annotation_list_file.empty()) { - // Generate output list. This is just a simple text file placed in a - // deterministic location which lists the .java files being generated. - std::unique_ptr annotation_list_raw_output( - context->Open(file_options.annotation_list_file)); - io::Printer annotation_list_printer(annotation_list_raw_output.get(), '$'); - for (int i = 0; i < all_annotations.size(); i++) { - annotation_list_printer.Print("$filename$\n", "filename", - all_annotations[i]); - } - } - - return true; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_generator.h b/windows/include/google/protobuf/compiler/java/java_generator.h index 47f76be98..6315e7c3f 100644 --- a/windows/include/google/protobuf/compiler/java/java_generator.h +++ b/windows/include/google/protobuf/compiler/java/java_generator.h @@ -40,6 +40,8 @@ #include #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -49,16 +51,16 @@ namespace java { // own protocol compiler binary and you want it to support Java output, you // can do so by registering an instance of this CodeGenerator with the // CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator { +class PROTOC_EXPORT JavaGenerator : public CodeGenerator { public: JavaGenerator(); ~JavaGenerator(); // implements CodeGenerator ---------------------------------------- - bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const; + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* context, std::string* error) const override; + + uint64_t GetSupportedFeatures() const override; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(JavaGenerator); @@ -67,6 +69,8 @@ class LIBPROTOC_EXPORT JavaGenerator : public CodeGenerator { } // namespace java } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_generator_factory.cc b/windows/include/google/protobuf/compiler/java/java_generator_factory.cc deleted file mode 100644 index 3218b4107..000000000 --- a/windows/include/google/protobuf/compiler/java/java_generator_factory.cc +++ /dev/null @@ -1,87 +0,0 @@ -// 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. - -// Author: liujisi@google.com (Pherl Liu) - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -GeneratorFactory::GeneratorFactory() {} -GeneratorFactory::~GeneratorFactory() {} - -// =================================================================== - -ImmutableGeneratorFactory::ImmutableGeneratorFactory( - Context* context) : context_(context) { -} -ImmutableGeneratorFactory::~ImmutableGeneratorFactory() {} - -MessageGenerator* ImmutableGeneratorFactory::NewMessageGenerator( - const Descriptor* descriptor) const { - if (HasDescriptorMethods(descriptor, context_->EnforceLite())) { - return new ImmutableMessageGenerator(descriptor, context_); - } else { - return new ImmutableMessageLiteGenerator(descriptor, context_); - } -} - -ExtensionGenerator* ImmutableGeneratorFactory::NewExtensionGenerator( - const FieldDescriptor* descriptor) const { - if (HasDescriptorMethods(descriptor->file(), context_->EnforceLite())) { - return new ImmutableExtensionGenerator(descriptor, context_); - } else { - return new ImmutableExtensionLiteGenerator(descriptor, context_); - } -} - -ServiceGenerator* ImmutableGeneratorFactory::NewServiceGenerator( - const ServiceDescriptor* descriptor) const { - return new ImmutableServiceGenerator(descriptor, context_); -} - - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_generator_factory.h b/windows/include/google/protobuf/compiler/java/java_generator_factory.h deleted file mode 100644 index 55365a9d4..000000000 --- a/windows/include/google/protobuf/compiler/java/java_generator_factory.h +++ /dev/null @@ -1,101 +0,0 @@ -// 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. - -// Author: liujisi@google.com (Pherl Liu) - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_FACTORY_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_FACTORY_H__ - -#include - -namespace google { -namespace protobuf { - class FieldDescriptor; // descriptor.h - class Descriptor; // descriptor.h - class ServiceDescriptor; // descriptor.h - namespace compiler { - namespace java { - class MessageGenerator; // message.h - class ExtensionGenerator; // extension.h - class ServiceGenerator; // service.h - class Context; // context.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class GeneratorFactory { - public: - GeneratorFactory(); - virtual ~GeneratorFactory(); - - virtual MessageGenerator* NewMessageGenerator( - const Descriptor* descriptor) const = 0; - - virtual ExtensionGenerator* NewExtensionGenerator( - const FieldDescriptor* descriptor) const = 0; - - virtual ServiceGenerator* NewServiceGenerator( - const ServiceDescriptor* descriptor) const = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GeneratorFactory); -}; - -// Factory that creates generators for immutable-default messages. -class ImmutableGeneratorFactory : public GeneratorFactory { - public: - ImmutableGeneratorFactory(Context* context); - virtual ~ImmutableGeneratorFactory(); - - virtual MessageGenerator* NewMessageGenerator( - const Descriptor* descriptor) const; - - virtual ExtensionGenerator* NewExtensionGenerator( - const FieldDescriptor* descriptor) const; - - virtual ServiceGenerator* NewServiceGenerator( - const ServiceDescriptor* descriptor) const; - - private: - Context* context_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableGeneratorFactory); -}; - - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_GENERATOR_FACTORY_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_helpers.cc b/windows/include/google/protobuf/compiler/java/java_helpers.cc deleted file mode 100644 index 957076cb4..000000000 --- a/windows/include/google/protobuf/compiler/java/java_helpers.cc +++ /dev/null @@ -1,954 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - - -#include // for hash - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -using internal::WireFormat; -using internal::WireFormatLite; - -const char kThickSeparator[] = - "// ===================================================================\n"; -const char kThinSeparator[] = - "// -------------------------------------------------------------------\n"; - -namespace { - -const char* kDefaultPackage = ""; - -// Names that should be avoided as field names. -// Using them will cause the compiler to generate accessors whose names are -// colliding with methods defined in base classes. -const char* kForbiddenWordList[] = { - // message base class: - "cached_size", "serialized_size", - // java.lang.Object: - "class", -}; - -const int kDefaultLookUpStartFieldNumber = 40; - -bool IsForbidden(const string& field_name) { - for (int i = 0; i < GOOGLE_ARRAYSIZE(kForbiddenWordList); ++i) { - if (field_name == kForbiddenWordList[i]) { - return true; - } - } - return false; -} - -string FieldName(const FieldDescriptor* field) { - string field_name; - // Groups are hacky: The name of the field is just the lower-cased name - // of the group type. In Java, though, we would like to retain the original - // capitalization of the type name. - if (GetType(field) == FieldDescriptor::TYPE_GROUP) { - field_name = field->message_type()->name(); - } else { - field_name = field->name(); - } - if (IsForbidden(field_name)) { - // Append a trailing "#" to indicate that the name should be decorated to - // avoid collision with other names. - field_name += "#"; - } - return field_name; -} - - -// Judge whether should use table or use look up. -// Copied from com.google.protobuf.SchemaUtil.shouldUseTableSwitch -bool ShouldUseTable(int lo, int hi, int number_of_fields) { - if (hi < kDefaultLookUpStartFieldNumber) { - return true; - } - int64 table_space_cost = (static_cast(hi) - lo + 1); // words - int64 table_time_cost = 3; // comparisons - int64 lookup_space_cost = 3 + 2 * static_cast(number_of_fields); - int64 lookup_time_cost = 3 + number_of_fields; - return table_space_cost + 3 * table_time_cost <= - lookup_space_cost + 3 * lookup_time_cost; -} - -} // namespace - -void PrintGeneratedAnnotation(io::Printer* printer, char delimiter, - const string& annotation_file) { - if (annotation_file.empty()) { - return; - } - string ptemplate = - "@javax.annotation.Generated(value=\"protoc\", comments=\"annotations:"; - ptemplate.push_back(delimiter); - ptemplate.append("annotation_file"); - ptemplate.push_back(delimiter); - ptemplate.append("\")\n"); - printer->Print(ptemplate.c_str(), "annotation_file", annotation_file); -} - -string UnderscoresToCamelCase(const string& input, bool cap_next_letter) { - string result; - // Note: I distrust ctype.h due to locales. - for (int i = 0; i < input.size(); i++) { - if ('a' <= input[i] && input[i] <= 'z') { - if (cap_next_letter) { - result += input[i] + ('A' - 'a'); - } else { - result += input[i]; - } - cap_next_letter = false; - } else if ('A' <= input[i] && input[i] <= 'Z') { - if (i == 0 && !cap_next_letter) { - // Force first letter to lower-case unless explicitly told to - // capitalize it. - result += input[i] + ('a' - 'A'); - } else { - // Capital letters after the first are left as-is. - result += input[i]; - } - cap_next_letter = false; - } else if ('0' <= input[i] && input[i] <= '9') { - result += input[i]; - cap_next_letter = true; - } else { - cap_next_letter = true; - } - } - // Add a trailing "_" if the name should be altered. - if (input[input.size() - 1] == '#') { - result += '_'; - } - return result; -} - -string UnderscoresToCamelCase(const FieldDescriptor* field) { - return UnderscoresToCamelCase(FieldName(field), false); -} - -string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) { - return UnderscoresToCamelCase(FieldName(field), true); -} - -string UnderscoresToCamelCase(const MethodDescriptor* method) { - return UnderscoresToCamelCase(method->name(), false); -} - -string UniqueFileScopeIdentifier(const Descriptor* descriptor) { - return "static_" + StringReplace(descriptor->full_name(), ".", "_", true); -} - -string CamelCaseFieldName(const FieldDescriptor* field) { - string fieldName = UnderscoresToCamelCase(field); - if ('0' <= fieldName[0] && fieldName[0] <= '9') { - return '_' + fieldName; - } - return fieldName; -} - -string StripProto(const string& filename) { - if (HasSuffixString(filename, ".protodevel")) { - return StripSuffixString(filename, ".protodevel"); - } else { - return StripSuffixString(filename, ".proto"); - } -} - -string FileClassName(const FileDescriptor* file, bool immutable) { - ClassNameResolver name_resolver; - return name_resolver.GetFileClassName(file, immutable); -} - -string FileJavaPackage(const FileDescriptor* file, bool immutable) { - string result; - - if (file->options().has_java_package()) { - result = file->options().java_package(); - } else { - result = kDefaultPackage; - if (!file->package().empty()) { - if (!result.empty()) result += '.'; - result += file->package(); - } - } - - return result; -} - -string JavaPackageToDir(string package_name) { - string package_dir = - StringReplace(package_name, ".", "/", true); - if (!package_dir.empty()) package_dir += "/"; - return package_dir; -} - -// TODO(xiaofeng): This function is only kept for it's publicly referenced. -// It should be removed after mutable API up-integration. -string ToJavaName(const string& full_name, - const FileDescriptor* file) { - string result; - if (file->options().java_multiple_files()) { - result = FileJavaPackage(file); - } else { - result = ClassName(file); - } - if (!result.empty()) { - result += '.'; - } - if (file->package().empty()) { - result += full_name; - } else { - // Strip the proto package from full_name since we've replaced it with - // the Java package. - result += full_name.substr(file->package().size() + 1); - } - return result; -} - -string ClassName(const Descriptor* descriptor) { - ClassNameResolver name_resolver; - return name_resolver.GetClassName(descriptor, true); -} - -string ClassName(const EnumDescriptor* descriptor) { - ClassNameResolver name_resolver; - return name_resolver.GetClassName(descriptor, true); -} - -string ClassName(const ServiceDescriptor* descriptor) { - ClassNameResolver name_resolver; - return name_resolver.GetClassName(descriptor, true); -} - -string ClassName(const FileDescriptor* descriptor) { - ClassNameResolver name_resolver; - return name_resolver.GetClassName(descriptor, true); -} - - -string ExtraMessageInterfaces(const Descriptor* descriptor) { - string interfaces = "// @@protoc_insertion_point(message_implements:" - + descriptor->full_name() + ")"; - return interfaces; -} - - -string ExtraBuilderInterfaces(const Descriptor* descriptor) { - string interfaces = "// @@protoc_insertion_point(builder_implements:" - + descriptor->full_name() + ")"; - return interfaces; -} - -string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor) { - string interfaces = "// @@protoc_insertion_point(interface_extends:" - + descriptor->full_name() + ")"; - return interfaces; -} - -string FieldConstantName(const FieldDescriptor *field) { - string name = field->name() + "_FIELD_NUMBER"; - UpperString(&name); - return name; -} - -FieldDescriptor::Type GetType(const FieldDescriptor* field) { - return field->type(); -} - -JavaType GetJavaType(const FieldDescriptor* field) { - switch (GetType(field)) { - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_SFIXED32: - return JAVATYPE_INT; - - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_SFIXED64: - return JAVATYPE_LONG; - - case FieldDescriptor::TYPE_FLOAT: - return JAVATYPE_FLOAT; - - case FieldDescriptor::TYPE_DOUBLE: - return JAVATYPE_DOUBLE; - - case FieldDescriptor::TYPE_BOOL: - return JAVATYPE_BOOLEAN; - - case FieldDescriptor::TYPE_STRING: - return JAVATYPE_STRING; - - case FieldDescriptor::TYPE_BYTES: - return JAVATYPE_BYTES; - - case FieldDescriptor::TYPE_ENUM: - return JAVATYPE_ENUM; - - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_MESSAGE: - return JAVATYPE_MESSAGE; - - // No default because we want the compiler to complain if any new - // types are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return JAVATYPE_INT; -} - -const char* PrimitiveTypeName(JavaType type) { - switch (type) { - case JAVATYPE_INT : return "int"; - case JAVATYPE_LONG : return "long"; - case JAVATYPE_FLOAT : return "float"; - case JAVATYPE_DOUBLE : return "double"; - case JAVATYPE_BOOLEAN: return "boolean"; - case JAVATYPE_STRING : return "java.lang.String"; - case JAVATYPE_BYTES : return "com.google.protobuf.ByteString"; - case JAVATYPE_ENUM : return NULL; - case JAVATYPE_MESSAGE: return NULL; - - // No default because we want the compiler to complain if any new - // JavaTypes are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -const char* BoxedPrimitiveTypeName(JavaType type) { - switch (type) { - case JAVATYPE_INT : return "java.lang.Integer"; - case JAVATYPE_LONG : return "java.lang.Long"; - case JAVATYPE_FLOAT : return "java.lang.Float"; - case JAVATYPE_DOUBLE : return "java.lang.Double"; - case JAVATYPE_BOOLEAN: return "java.lang.Boolean"; - case JAVATYPE_STRING : return "java.lang.String"; - case JAVATYPE_BYTES : return "com.google.protobuf.ByteString"; - case JAVATYPE_ENUM : return NULL; - case JAVATYPE_MESSAGE: return NULL; - - // No default because we want the compiler to complain if any new - // JavaTypes are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - - -const char* FieldTypeName(FieldDescriptor::Type field_type) { - switch (field_type) { - case FieldDescriptor::TYPE_INT32 : return "INT32"; - case FieldDescriptor::TYPE_UINT32 : return "UINT32"; - case FieldDescriptor::TYPE_SINT32 : return "SINT32"; - case FieldDescriptor::TYPE_FIXED32 : return "FIXED32"; - case FieldDescriptor::TYPE_SFIXED32: return "SFIXED32"; - case FieldDescriptor::TYPE_INT64 : return "INT64"; - case FieldDescriptor::TYPE_UINT64 : return "UINT64"; - case FieldDescriptor::TYPE_SINT64 : return "SINT64"; - case FieldDescriptor::TYPE_FIXED64 : return "FIXED64"; - case FieldDescriptor::TYPE_SFIXED64: return "SFIXED64"; - case FieldDescriptor::TYPE_FLOAT : return "FLOAT"; - case FieldDescriptor::TYPE_DOUBLE : return "DOUBLE"; - case FieldDescriptor::TYPE_BOOL : return "BOOL"; - case FieldDescriptor::TYPE_STRING : return "STRING"; - case FieldDescriptor::TYPE_BYTES : return "BYTES"; - case FieldDescriptor::TYPE_ENUM : return "ENUM"; - case FieldDescriptor::TYPE_GROUP : return "GROUP"; - case FieldDescriptor::TYPE_MESSAGE : return "MESSAGE"; - - // No default because we want the compiler to complain if any new - // types are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -bool AllAscii(const string& text) { - for (int i = 0; i < text.size(); i++) { - if ((text[i] & 0x80) != 0) { - return false; - } - } - return true; -} - -string DefaultValue(const FieldDescriptor* field, bool immutable, - ClassNameResolver* name_resolver) { - // Switch on CppType since we need to know which default_value_* method - // of FieldDescriptor to call. - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - return SimpleItoa(field->default_value_int32()); - case FieldDescriptor::CPPTYPE_UINT32: - // Need to print as a signed int since Java has no unsigned. - return SimpleItoa(static_cast(field->default_value_uint32())); - case FieldDescriptor::CPPTYPE_INT64: - return SimpleItoa(field->default_value_int64()) + "L"; - case FieldDescriptor::CPPTYPE_UINT64: - return SimpleItoa(static_cast(field->default_value_uint64())) + - "L"; - case FieldDescriptor::CPPTYPE_DOUBLE: { - double value = field->default_value_double(); - if (value == std::numeric_limits::infinity()) { - return "Double.POSITIVE_INFINITY"; - } else if (value == -std::numeric_limits::infinity()) { - return "Double.NEGATIVE_INFINITY"; - } else if (value != value) { - return "Double.NaN"; - } else { - return SimpleDtoa(value) + "D"; - } - } - case FieldDescriptor::CPPTYPE_FLOAT: { - float value = field->default_value_float(); - if (value == std::numeric_limits::infinity()) { - return "Float.POSITIVE_INFINITY"; - } else if (value == -std::numeric_limits::infinity()) { - return "Float.NEGATIVE_INFINITY"; - } else if (value != value) { - return "Float.NaN"; - } else { - return SimpleFtoa(value) + "F"; - } - } - case FieldDescriptor::CPPTYPE_BOOL: - return field->default_value_bool() ? "true" : "false"; - case FieldDescriptor::CPPTYPE_STRING: - if (GetType(field) == FieldDescriptor::TYPE_BYTES) { - if (field->has_default_value()) { - // See comments in Internal.java for gory details. - return strings::Substitute( - "com.google.protobuf.Internal.bytesDefaultValue(\"$0\")", - CEscape(field->default_value_string())); - } else { - return "com.google.protobuf.ByteString.EMPTY"; - } - } else { - if (AllAscii(field->default_value_string())) { - // All chars are ASCII. In this case CEscape() works fine. - return "\"" + CEscape(field->default_value_string()) + "\""; - } else { - // See comments in Internal.java for gory details. - return strings::Substitute( - "com.google.protobuf.Internal.stringDefaultValue(\"$0\")", - CEscape(field->default_value_string())); - } - } - - case FieldDescriptor::CPPTYPE_ENUM: - return name_resolver->GetClassName(field->enum_type(), immutable) + "." + - field->default_value_enum()->name(); - - case FieldDescriptor::CPPTYPE_MESSAGE: - return name_resolver->GetClassName(field->message_type(), immutable) + - ".getDefaultInstance()"; - - // No default because we want the compiler to complain if any new - // types are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; -} - -bool IsDefaultValueJavaDefault(const FieldDescriptor* field) { - // Switch on CppType since we need to know which default_value_* method - // of FieldDescriptor to call. - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - return field->default_value_int32() == 0; - case FieldDescriptor::CPPTYPE_UINT32: - return field->default_value_uint32() == 0; - case FieldDescriptor::CPPTYPE_INT64: - return field->default_value_int64() == 0L; - case FieldDescriptor::CPPTYPE_UINT64: - return field->default_value_uint64() == 0L; - case FieldDescriptor::CPPTYPE_DOUBLE: - return field->default_value_double() == 0.0; - case FieldDescriptor::CPPTYPE_FLOAT: - return field->default_value_float() == 0.0; - case FieldDescriptor::CPPTYPE_BOOL: - return field->default_value_bool() == false; - case FieldDescriptor::CPPTYPE_ENUM: - return field->default_value_enum()->number() == 0; - case FieldDescriptor::CPPTYPE_STRING: - case FieldDescriptor::CPPTYPE_MESSAGE: - return false; - - // No default because we want the compiler to complain if any new - // types are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return false; -} - -bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field) { - return GetJavaType(field) == JAVATYPE_BYTES && - field->default_value_string() != ""; -} - -const char* bit_masks[] = { - "0x00000001", - "0x00000002", - "0x00000004", - "0x00000008", - "0x00000010", - "0x00000020", - "0x00000040", - "0x00000080", - - "0x00000100", - "0x00000200", - "0x00000400", - "0x00000800", - "0x00001000", - "0x00002000", - "0x00004000", - "0x00008000", - - "0x00010000", - "0x00020000", - "0x00040000", - "0x00080000", - "0x00100000", - "0x00200000", - "0x00400000", - "0x00800000", - - "0x01000000", - "0x02000000", - "0x04000000", - "0x08000000", - "0x10000000", - "0x20000000", - "0x40000000", - "0x80000000", -}; - -string GetBitFieldName(int index) { - string varName = "bitField"; - varName += SimpleItoa(index); - varName += "_"; - return varName; -} - -string GetBitFieldNameForBit(int bitIndex) { - return GetBitFieldName(bitIndex / 32); -} - -namespace { - -string GenerateGetBitInternal(const string& prefix, int bitIndex) { - string varName = prefix + GetBitFieldNameForBit(bitIndex); - int bitInVarIndex = bitIndex % 32; - - string mask = bit_masks[bitInVarIndex]; - string result = "((" + varName + " & " + mask + ") == " + mask + ")"; - return result; -} - -string GenerateSetBitInternal(const string& prefix, int bitIndex) { - string varName = prefix + GetBitFieldNameForBit(bitIndex); - int bitInVarIndex = bitIndex % 32; - - string mask = bit_masks[bitInVarIndex]; - string result = varName + " |= " + mask; - return result; -} - -} // namespace - -string GenerateGetBit(int bitIndex) { - return GenerateGetBitInternal("", bitIndex); -} - -string GenerateSetBit(int bitIndex) { - return GenerateSetBitInternal("", bitIndex); -} - -string GenerateClearBit(int bitIndex) { - string varName = GetBitFieldNameForBit(bitIndex); - int bitInVarIndex = bitIndex % 32; - - string mask = bit_masks[bitInVarIndex]; - string result = varName + " = (" + varName + " & ~" + mask + ")"; - return result; -} - -string GenerateGetBitFromLocal(int bitIndex) { - return GenerateGetBitInternal("from_", bitIndex); -} - -string GenerateSetBitToLocal(int bitIndex) { - return GenerateSetBitInternal("to_", bitIndex); -} - -string GenerateGetBitMutableLocal(int bitIndex) { - return GenerateGetBitInternal("mutable_", bitIndex); -} - -string GenerateSetBitMutableLocal(int bitIndex) { - return GenerateSetBitInternal("mutable_", bitIndex); -} - -bool IsReferenceType(JavaType type) { - switch (type) { - case JAVATYPE_INT : return false; - case JAVATYPE_LONG : return false; - case JAVATYPE_FLOAT : return false; - case JAVATYPE_DOUBLE : return false; - case JAVATYPE_BOOLEAN: return false; - case JAVATYPE_STRING : return true; - case JAVATYPE_BYTES : return true; - case JAVATYPE_ENUM : return true; - case JAVATYPE_MESSAGE: return true; - - // No default because we want the compiler to complain if any new - // JavaTypes are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return false; -} - -const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable) { - switch (GetType(field)) { - case FieldDescriptor::TYPE_INT32 : return "Int32"; - case FieldDescriptor::TYPE_UINT32 : return "UInt32"; - case FieldDescriptor::TYPE_SINT32 : return "SInt32"; - case FieldDescriptor::TYPE_FIXED32 : return "Fixed32"; - case FieldDescriptor::TYPE_SFIXED32: return "SFixed32"; - case FieldDescriptor::TYPE_INT64 : return "Int64"; - case FieldDescriptor::TYPE_UINT64 : return "UInt64"; - case FieldDescriptor::TYPE_SINT64 : return "SInt64"; - case FieldDescriptor::TYPE_FIXED64 : return "Fixed64"; - case FieldDescriptor::TYPE_SFIXED64: return "SFixed64"; - case FieldDescriptor::TYPE_FLOAT : return "Float"; - case FieldDescriptor::TYPE_DOUBLE : return "Double"; - case FieldDescriptor::TYPE_BOOL : return "Bool"; - case FieldDescriptor::TYPE_STRING : return "String"; - case FieldDescriptor::TYPE_BYTES : { - return "Bytes"; - } - case FieldDescriptor::TYPE_ENUM : return "Enum"; - case FieldDescriptor::TYPE_GROUP : return "Group"; - case FieldDescriptor::TYPE_MESSAGE : return "Message"; - - // No default because we want the compiler to complain if any new - // types are added. - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -// For encodings with fixed sizes, returns that size in bytes. Otherwise -// returns -1. -int FixedSize(FieldDescriptor::Type type) { - switch (type) { - case FieldDescriptor::TYPE_INT32 : return -1; - case FieldDescriptor::TYPE_INT64 : return -1; - case FieldDescriptor::TYPE_UINT32 : return -1; - case FieldDescriptor::TYPE_UINT64 : return -1; - case FieldDescriptor::TYPE_SINT32 : return -1; - case FieldDescriptor::TYPE_SINT64 : return -1; - case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size; - case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size; - case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size; - case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size; - case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize; - case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize; - - case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize; - case FieldDescriptor::TYPE_ENUM : return -1; - - case FieldDescriptor::TYPE_STRING : return -1; - case FieldDescriptor::TYPE_BYTES : return -1; - case FieldDescriptor::TYPE_GROUP : return -1; - case FieldDescriptor::TYPE_MESSAGE : return -1; - - // No default because we want the compiler to complain if any new - // types are added. - } - GOOGLE_LOG(FATAL) << "Can't get here."; - return -1; -} - -// Sort the fields of the given Descriptor by number into a new[]'d array -// and return it. The caller should delete the returned array. -const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { - const FieldDescriptor** fields = - new const FieldDescriptor*[descriptor->field_count()]; - for (int i = 0; i < descriptor->field_count(); i++) { - fields[i] = descriptor->field(i); - } - std::sort(fields, fields + descriptor->field_count(), - FieldOrderingByNumber()); - return fields; -} - -// Returns true if the message type has any required fields. If it doesn't, -// we can optimize out calls to its isInitialized() method. -// -// already_seen is used to avoid checking the same type multiple times -// (and also to protect against recursion). -bool HasRequiredFields( - const Descriptor* type, - hash_set* already_seen) { - if (already_seen->count(type) > 0) { - // The type is already in cache. This means that either: - // a. The type has no required fields. - // b. We are in the midst of checking if the type has required fields, - // somewhere up the stack. In this case, we know that if the type - // has any required fields, they'll be found when we return to it, - // and the whole call to HasRequiredFields() will return true. - // Therefore, we don't have to check if this type has required fields - // here. - return false; - } - already_seen->insert(type); - - // If the type has extensions, an extension with message type could contain - // required fields, so we have to be conservative and assume such an - // extension exists. - if (type->extension_range_count() > 0) return true; - - for (int i = 0; i < type->field_count(); i++) { - const FieldDescriptor* field = type->field(i); - if (field->is_required()) { - return true; - } - if (GetJavaType(field) == JAVATYPE_MESSAGE) { - if (HasRequiredFields(field->message_type(), already_seen)) { - return true; - } - } - } - - return false; -} - -bool HasRequiredFields(const Descriptor* type) { - hash_set already_seen; - return HasRequiredFields(type, &already_seen); -} - -bool HasRepeatedFields(const Descriptor* descriptor) { - for (int i = 0; i < descriptor->field_count(); ++i) { - const FieldDescriptor* field = descriptor->field(i); - if (field->is_repeated()) { - return true; - } - } - return false; -} - -// Encode an unsigned 32-bit value into a sequence of UTF-16 characters. -// -// If the value is in [0x0000, 0xD7FF], we encode it with a single character -// with the same numeric value. -// -// If the value is larger than 0xD7FF, we encode its lowest 13 bits into a -// character in the range [0xE000, 0xFFFF] by combining these 13 bits with -// 0xE000 using logic-or. Then we shift the value to the right by 13 bits, and -// encode the remaining value by repeating this same process until we get to -// a value in [0x0000, 0xD7FF] where we will encode it using a character with -// the same numeric value. -// -// Note that we only use code points in [0x0000, 0xD7FF] and [0xE000, 0xFFFF]. -// There will be no surrogate pairs in the encoded character sequence. -void WriteUInt32ToUtf16CharSequence(uint32 number, - std::vector* output) { - // For values in [0x0000, 0xD7FF], only use one char to encode it. - if (number < 0xD800) { - output->push_back(static_cast(number)); - return; - } - // Encode into multiple chars. All except the last char will be in the range - // [0xE000, 0xFFFF], and the last char will be in the range [0x0000, 0xD7FF]. - // Note that we don't use any value in range [0xD800, 0xDFFF] because they - // have to come in pairs and the encoding is just more space-efficient w/o - // them. - while (number >= 0xD800) { - // [0xE000, 0xFFFF] can represent 13 bits of info. - output->push_back(static_cast(0xE000 | (number & 0x1FFF))); - number >>= 13; - } - output->push_back(static_cast(number)); -} - -int GetExperimentalJavaFieldTypeForSingular(const FieldDescriptor* field) { - // j/c/g/protobuf/FieldType.java lists field types in a slightly different - // order from FieldDescriptor::Type so we can't do a simple cast. - // - // TODO(xiaofeng): Make j/c/g/protobuf/FieldType.java follow the same order. - int result = field->type(); - if (result == FieldDescriptor::TYPE_GROUP) { - return 17; - } else if (result < FieldDescriptor::TYPE_GROUP) { - return result - 1; - } else { - return result - 2; - } -} - -int GetExperimentalJavaFieldTypeForRepeated(const FieldDescriptor* field) { - if (field->type() == FieldDescriptor::TYPE_GROUP) { - return 49; - } else { - return GetExperimentalJavaFieldTypeForSingular(field) + 18; - } -} - -int GetExperimentalJavaFieldTypeForPacked(const FieldDescriptor* field) { - int result = field->type(); - if (result < FieldDescriptor::TYPE_STRING) { - return result + 34; - } else if (result > FieldDescriptor::TYPE_BYTES) { - return result + 30; - } else { - GOOGLE_LOG(FATAL) << field->full_name() << " can't be packed."; - return 0; - } -} - -int GetExperimentalJavaFieldType(const FieldDescriptor* field) { - static const int kMapFieldType = 50; - static const int kOneofFieldTypeOffset = 51; - static const int kRequiredBit = 0x100; - static const int kUtf8CheckBit = 0x200; - static const int kCheckInitialized = 0x400; - static const int kMapWithProto2EnumValue = 0x800; - int extra_bits = field->is_required() ? kRequiredBit : 0; - if (field->type() == FieldDescriptor::TYPE_STRING && CheckUtf8(field)) { - extra_bits |= kUtf8CheckBit; - } - if (field->is_required() || (GetJavaType(field) == JAVATYPE_MESSAGE && - HasRequiredFields(field->message_type()))) { - extra_bits |= kCheckInitialized; - } - - if (field->is_map()) { - if (SupportFieldPresence(field->file())) { - const FieldDescriptor* value = - field->message_type()->FindFieldByName("value"); - if (GetJavaType(value) == JAVATYPE_ENUM) { - extra_bits |= kMapWithProto2EnumValue; - } - } - return kMapFieldType | extra_bits; - } else if (field->is_packed()) { - return GetExperimentalJavaFieldTypeForPacked(field); - } else if (field->is_repeated()) { - return GetExperimentalJavaFieldTypeForRepeated(field) | extra_bits; - } else if (field->containing_oneof() != NULL) { - return (GetExperimentalJavaFieldTypeForSingular(field) + - kOneofFieldTypeOffset) | - extra_bits; - } else { - return GetExperimentalJavaFieldTypeForSingular(field) | extra_bits; - } -} - -// Escape a UTF-16 character to be embedded in a Java string. -void EscapeUtf16ToString(uint16 code, string* output) { - if (code == '\t') { - output->append("\\t"); - } else if (code == '\b') { - output->append("\\b"); - } else if (code == '\n') { - output->append("\\n"); - } else if (code == '\r') { - output->append("\\r"); - } else if (code == '\f') { - output->append("\\f"); - } else if (code == '\'') { - output->append("\\'"); - } else if (code == '\"') { - output->append("\\\""); - } else if (code == '\\') { - output->append("\\\\"); - } else if (code >= 0x20 && code <= 0x7f) { - output->push_back(static_cast(code)); - } else { - output->append(StringPrintf("\\u%04x", code)); - } -} - -std::pair GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber( - const FieldDescriptor** fields, int count) { - GOOGLE_CHECK_GT(count, 0); - int table_driven_number_of_entries = count; - int look_up_start_field_number = 0; - for (int i = 0; i < count; i++) { - const int field_number = fields[i]->number(); - if (ShouldUseTable(fields[0]->number(), field_number, i + 1)) { - table_driven_number_of_entries = - field_number - fields[0]->number() + 1 + count - i - 1; - look_up_start_field_number = field_number + 1; - } - } - return std::make_pair( - table_driven_number_of_entries, look_up_start_field_number); -} -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_helpers.h b/windows/include/google/protobuf/compiler/java/java_helpers.h deleted file mode 100644 index dd9b65b81..000000000 --- a/windows/include/google/protobuf/compiler/java/java_helpers.h +++ /dev/null @@ -1,427 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__ - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -// Commonly-used separator comments. Thick is a line of '=', thin is a line -// of '-'. -extern const char kThickSeparator[]; -extern const char kThinSeparator[]; - -// If annotation_file is non-empty, prints a javax.annotation.Generated -// annotation to the given Printer. annotation_file will be referenced in the -// annotation's comments field. delimiter should be the Printer's delimiter -// character. annotation_file will be included verbatim into a Java literal -// string, so it should not contain quotes or invalid Java escape sequences; -// however, these are unlikely to appear in practice, as the value of -// annotation_file should be generated from the filename of the source file -// being annotated (which in turn must be a Java identifier plus ".java"). -void PrintGeneratedAnnotation(io::Printer* printer, char delimiter = '$', - const string& annotation_file = ""); - -// Converts a name to camel-case. If cap_first_letter is true, capitalize the -// first letter. -string UnderscoresToCamelCase(const string& name, bool cap_first_letter); -// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes -// "fooBarBaz" or "FooBarBaz", respectively. -string UnderscoresToCamelCase(const FieldDescriptor* field); -string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); - -// Similar, but for method names. (Typically, this merely has the effect -// of lower-casing the first letter of the name.) -string UnderscoresToCamelCase(const MethodDescriptor* method); - -// Similar to UnderscoresToCamelCase, but guarentees that the result is a -// complete Java identifier by adding a _ if needed. -string CamelCaseFieldName(const FieldDescriptor* field); - -// Get an identifier that uniquely identifies this type within the file. -// This is used to declare static variables related to this type at the -// outermost file scope. -string UniqueFileScopeIdentifier(const Descriptor* descriptor); - -// Strips ".proto" or ".protodevel" from the end of a filename. -string StripProto(const string& filename); - -// Gets the unqualified class name for the file. For each .proto file, there -// will be one Java class containing all the immutable messages and another -// Java class containing all the mutable messages. -// TODO(xiaofeng): remove the default value after updating client code. -string FileClassName(const FileDescriptor* file, bool immutable = true); - -// Returns the file's Java package name. -string FileJavaPackage(const FileDescriptor* file, bool immutable = true); - -// Returns output directory for the given package name. -string JavaPackageToDir(string package_name); - -// Converts the given fully-qualified name in the proto namespace to its -// fully-qualified name in the Java namespace, given that it is in the given -// file. -// TODO(xiaofeng): this method is deprecated and should be removed in the -// future. -string ToJavaName(const string& full_name, - const FileDescriptor* file); - -// TODO(xiaofeng): the following methods are kept for they are exposed -// publicly in //google/protobuf/compiler/java/names.h. They return -// immutable names only and should be removed after mutable API is -// integrated into google3. -string ClassName(const Descriptor* descriptor); -string ClassName(const EnumDescriptor* descriptor); -string ClassName(const ServiceDescriptor* descriptor); -string ClassName(const FileDescriptor* descriptor); - -// Comma-separate list of option-specified interfaces implemented by the -// Message, to follow the "implements" declaration of the Message definition. -string ExtraMessageInterfaces(const Descriptor* descriptor); -// Comma-separate list of option-specified interfaces implemented by the -// MutableMessage, to follow the "implements" declaration of the MutableMessage -// definition. -string ExtraMutableMessageInterfaces(const Descriptor* descriptor); -// Comma-separate list of option-specified interfaces implemented by the -// Builder, to follow the "implements" declaration of the Builder definition. -string ExtraBuilderInterfaces(const Descriptor* descriptor); -// Comma-separate list of option-specified interfaces extended by the -// MessageOrBuilder, to follow the "extends" declaration of the -// MessageOrBuilder definition. -string ExtraMessageOrBuilderInterfaces(const Descriptor* descriptor); - -// Get the unqualified Java class name for mutable messages. i.e. without -// package or outer classnames. -inline string ShortMutableJavaClassName(const Descriptor* descriptor) { - return descriptor->name(); -} - -// Whether the given descriptor is for one of the core descriptor protos. We -// cannot currently use the new runtime with core protos since there is a -// bootstrapping problem with obtaining their descriptors. -inline bool IsDescriptorProto(const Descriptor* descriptor) { - return descriptor->file()->name() == "google/protobuf/descriptor.proto"; -} - - -// Whether we should generate multiple java files for messages. -inline bool MultipleJavaFiles( - const FileDescriptor* descriptor, bool immutable) { - return descriptor->options().java_multiple_files(); -} - -// Returns true if `descriptor` will be written to its own .java file. -// `immutable` should be set to true if we're generating for the immutable API. -template -bool IsOwnFile(const Descriptor* descriptor, bool immutable) { - return descriptor->containing_type() == NULL && - MultipleJavaFiles(descriptor->file(), immutable); -} - -template <> -inline bool IsOwnFile(const ServiceDescriptor* descriptor, bool immutable) { - return MultipleJavaFiles(descriptor->file(), immutable); -} - -// If `descriptor` describes an object with its own .java file, -// returns the name (relative to that .java file) of the file that stores -// annotation data for that descriptor. `suffix` is usually empty, but may -// (e.g.) be "OrBuilder" for some generated interfaces. -template -string AnnotationFileName(const Descriptor* descriptor, const string& suffix) { - return descriptor->name() + suffix + ".java.pb.meta"; -} - -template -void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer, - Descriptor* descriptor, bool immutable, - const string& suffix = "") { - if (context->options().annotate_code && IsOwnFile(descriptor, immutable)) { - PrintGeneratedAnnotation(printer, '$', - AnnotationFileName(descriptor, suffix)); - } -} - -// Get the unqualified name that should be used for a field's field -// number constant. -string FieldConstantName(const FieldDescriptor *field); - -// Returns the type of the FieldDescriptor. -// This does nothing interesting for the open source release, but is used for -// hacks that improve compatibility with version 1 protocol buffers at Google. -FieldDescriptor::Type GetType(const FieldDescriptor* field); - -enum JavaType { - JAVATYPE_INT, - JAVATYPE_LONG, - JAVATYPE_FLOAT, - JAVATYPE_DOUBLE, - JAVATYPE_BOOLEAN, - JAVATYPE_STRING, - JAVATYPE_BYTES, - JAVATYPE_ENUM, - JAVATYPE_MESSAGE -}; - -JavaType GetJavaType(const FieldDescriptor* field); - -const char* PrimitiveTypeName(JavaType type); - -// Get the fully-qualified class name for a boxed primitive type, e.g. -// "java.lang.Integer" for JAVATYPE_INT. Returns NULL for enum and message -// types. -const char* BoxedPrimitiveTypeName(JavaType type); - -// Get the name of the java enum constant representing this type. E.g., -// "INT32" for FieldDescriptor::TYPE_INT32. The enum constant's full -// name is "com.google.protobuf.WireFormat.FieldType.INT32". -const char* FieldTypeName(const FieldDescriptor::Type field_type); - -class ClassNameResolver; -string DefaultValue(const FieldDescriptor* field, bool immutable, - ClassNameResolver* name_resolver); -inline string ImmutableDefaultValue(const FieldDescriptor* field, - ClassNameResolver* name_resolver) { - return DefaultValue(field, true, name_resolver); -} -bool IsDefaultValueJavaDefault(const FieldDescriptor* field); -bool IsByteStringWithCustomDefaultValue(const FieldDescriptor* field); - -// Does this message class have descriptor and reflection methods? -inline bool HasDescriptorMethods(const Descriptor* descriptor, - bool enforce_lite) { - return !enforce_lite && - descriptor->file()->options().optimize_for() != - FileOptions::LITE_RUNTIME; -} -inline bool HasDescriptorMethods(const EnumDescriptor* descriptor, - bool enforce_lite) { - return !enforce_lite && - descriptor->file()->options().optimize_for() != - FileOptions::LITE_RUNTIME; -} -inline bool HasDescriptorMethods(const FileDescriptor* descriptor, - bool enforce_lite) { - return !enforce_lite && - descriptor->options().optimize_for() != FileOptions::LITE_RUNTIME; -} - -// Should we generate generic services for this file? -inline bool HasGenericServices(const FileDescriptor *file, bool enforce_lite) { - return file->service_count() > 0 && - HasDescriptorMethods(file, enforce_lite) && - file->options().java_generic_services(); -} - -// Methods for shared bitfields. - -// Gets the name of the shared bitfield for the given index. -string GetBitFieldName(int index); - -// Gets the name of the shared bitfield for the given bit index. -// Effectively, GetBitFieldName(bitIndex / 32) -string GetBitFieldNameForBit(int bitIndex); - -// Generates the java code for the expression that returns the boolean value -// of the bit of the shared bitfields for the given bit index. -// Example: "((bitField1_ & 0x04) == 0x04)" -string GenerateGetBit(int bitIndex); - -// Generates the java code for the expression that sets the bit of the shared -// bitfields for the given bit index. -// Example: "bitField1_ = (bitField1_ | 0x04)" -string GenerateSetBit(int bitIndex); - -// Generates the java code for the expression that clears the bit of the shared -// bitfields for the given bit index. -// Example: "bitField1_ = (bitField1_ & ~0x04)" -string GenerateClearBit(int bitIndex); - -// Does the same as GenerateGetBit but operates on the bit field on a local -// variable. This is used by the builder to copy the value in the builder to -// the message. -// Example: "((from_bitField1_ & 0x04) == 0x04)" -string GenerateGetBitFromLocal(int bitIndex); - -// Does the same as GenerateSetBit but operates on the bit field on a local -// variable. This is used by the builder to copy the value in the builder to -// the message. -// Example: "to_bitField1_ = (to_bitField1_ | 0x04)" -string GenerateSetBitToLocal(int bitIndex); - -// Does the same as GenerateGetBit but operates on the bit field on a local -// variable. This is used by the parsing constructor to record if a repeated -// field is mutable. -// Example: "((mutable_bitField1_ & 0x04) == 0x04)" -string GenerateGetBitMutableLocal(int bitIndex); - -// Does the same as GenerateSetBit but operates on the bit field on a local -// variable. This is used by the parsing constructor to record if a repeated -// field is mutable. -// Example: "mutable_bitField1_ = (mutable_bitField1_ | 0x04)" -string GenerateSetBitMutableLocal(int bitIndex); - -// Returns whether the JavaType is a reference type. -bool IsReferenceType(JavaType type); - -// Returns the capitalized name for calling relative functions in -// CodedInputStream -const char* GetCapitalizedType(const FieldDescriptor* field, bool immutable); - -// For encodings with fixed sizes, returns that size in bytes. Otherwise -// returns -1. -int FixedSize(FieldDescriptor::Type type); - -// Comparators used to sort fields in MessageGenerator -struct FieldOrderingByNumber { - inline bool operator()(const FieldDescriptor* a, - const FieldDescriptor* b) const { - return a->number() < b->number(); - } -}; - -struct ExtensionRangeOrdering { - bool operator()(const Descriptor::ExtensionRange* a, - const Descriptor::ExtensionRange* b) const { - return a->start < b->start; - } -}; - -// Sort the fields of the given Descriptor by number into a new[]'d array -// and return it. The caller should delete the returned array. -const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor); - -// Does this message class have any packed fields? -inline bool HasPackedFields(const Descriptor* descriptor) { - for (int i = 0; i < descriptor->field_count(); i++) { - if (descriptor->field(i)->is_packed()) { - return true; - } - } - return false; -} - -// Check a message type and its sub-message types recursively to see if any of -// them has a required field. Return true if a required field is found. -bool HasRequiredFields(const Descriptor* descriptor); - -// Whether a .proto file supports field presence test for non-message types. -inline bool SupportFieldPresence(const FileDescriptor* descriptor) { - return descriptor->syntax() != FileDescriptor::SYNTAX_PROTO3; -} - -// Whether generate classes expose public PARSER instances. -inline bool ExposePublicParser(const FileDescriptor* descriptor) { - // TODO(liujisi): Mark the PARSER private in 3.1.x releases. - return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO2; -} - -// Whether unknown enum values are kept (i.e., not stored in UnknownFieldSet -// but in the message and can be queried using additional getters that return -// ints. -inline bool SupportUnknownEnumValue(const FileDescriptor* descriptor) { - return descriptor->syntax() == FileDescriptor::SYNTAX_PROTO3; -} - -// Check whether a mesasge has repeated fields. -bool HasRepeatedFields(const Descriptor* descriptor); - -inline bool IsMapEntry(const Descriptor* descriptor) { - return descriptor->options().map_entry(); -} - -inline bool IsMapField(const FieldDescriptor* descriptor) { - return descriptor->is_map(); -} - -inline bool IsAnyMessage(const Descriptor* descriptor) { - return descriptor->full_name() == "google.protobuf.Any"; -} - -inline bool IsWrappersProtoFile(const FileDescriptor* descriptor) { - return descriptor->name() == "google/protobuf/wrappers.proto"; -} - -inline bool CheckUtf8(const FieldDescriptor* descriptor) { - return descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 || - descriptor->file()->options().java_string_check_utf8(); -} - -inline string GeneratedCodeVersionSuffix() { - return "V3"; -} - -inline bool EnableExperimentalRuntime(Context* context) { - return false; -} - -void WriteUInt32ToUtf16CharSequence(uint32 number, std::vector* output); - -inline void WriteIntToUtf16CharSequence(int value, - std::vector* output) { - WriteUInt32ToUtf16CharSequence(static_cast(value), output); -} - -// Escape a UTF-16 character so it can be embedded in a Java string literal. -void EscapeUtf16ToString(uint16 code, string* output); - -// Only the lowest two bytes of the return value are used. The lowest byte -// is the integer value of a j/c/g/protobuf/FieldType enum. For the other -// byte: -// bit 0: whether the field is required. -// bit 1: whether the field requires UTF-8 validation. -// bit 2: whether the field needs isInitialized check. -// bit 3: whether the field is a map field with proto2 enum value. -// bits 4-7: unused -int GetExperimentalJavaFieldType(const FieldDescriptor* field); - -// To get the total number of entries need to be built for experimental runtime -// and the first field number that are not in the table part -std::pair GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber( - const FieldDescriptor** fields, int count); -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_HELPERS_H__ diff --git a/windows/include/google/protobuf/compiler/csharp/csharp_reflection_class.h b/windows/include/google/protobuf/compiler/java/java_kotlin_generator.h similarity index 63% rename from windows/include/google/protobuf/compiler/csharp/csharp_reflection_class.h rename to windows/include/google/protobuf/compiler/java/java_kotlin_generator.h index e0c69f31f..66e32b9e0 100644 --- a/windows/include/google/protobuf/compiler/csharp/csharp_reflection_class.h +++ b/windows/include/google/protobuf/compiler/java/java_kotlin_generator.h @@ -28,44 +28,45 @@ // (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_CSHARP_REFLECTION_CLASS_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_REFLECTION_CLASS_H__ +// Generates Kotlin code for a given .proto file. + +#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_KOTLIN_GENERATOR_H__ +#define GOOGLE_PROTOBUF_COMPILER_JAVA_KOTLIN_GENERATOR_H__ #include #include -#include +#include namespace google { namespace protobuf { namespace compiler { -namespace csharp { +namespace java { -class ReflectionClassGenerator : public SourceGeneratorBase { +// CodeGenerator implementation which generates Kotlin code. If you create your +// own protocol compiler binary and you want it to support Kotlin output, you +// can do so by registering an instance of this CodeGenerator with the +// CommandLineInterface in your main() function. +class PROTOC_EXPORT KotlinGenerator : public CodeGenerator { public: - ReflectionClassGenerator(const FileDescriptor* file, const Options* options); - ~ReflectionClassGenerator(); + KotlinGenerator(); + ~KotlinGenerator() override; - void Generate(io::Printer* printer); + // implements CodeGenerator ---------------------------------------- + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* context, std::string* error) const override; + + uint64_t GetSupportedFeatures() const override; private: - const FileDescriptor* file_; - - std::string namespace_; - std::string reflectionClassname_; - - void WriteIntroduction(io::Printer* printer); - void WriteDescriptor(io::Printer* printer); - void WriteGeneratedCodeInfo(const Descriptor* descriptor, - io::Printer* printer, - bool last); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionClassGenerator); + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(KotlinGenerator); }; -} // namespace csharp +} // namespace java } // namespace compiler } // namespace protobuf } // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_REFLECTION_CLASS_H__ +#include + +#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_KOTLIN_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_lazy_message_field.cc b/windows/include/google/protobuf/compiler/java/java_lazy_message_field.cc deleted file mode 100644 index abf8e55cf..000000000 --- a/windows/include/google/protobuf/compiler/java/java_lazy_message_field.cc +++ /dev/null @@ -1,814 +0,0 @@ -// 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. - -// Author: niwasaki@google.com (Naoki Iwasaki) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -ImmutableLazyMessageFieldGenerator:: -ImmutableLazyMessageFieldGenerator( - const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableMessageFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { -} - -ImmutableLazyMessageFieldGenerator::~ImmutableLazyMessageFieldGenerator() {} - -void ImmutableLazyMessageFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.LazyFieldLite $name$_ =\n" - " new com.google.protobuf.LazyFieldLite();\n"); - - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n" - " return $name$_;\n" - "}\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // When using nested-builders, the code initially works just like the - // non-nested builder case. It only creates a nested builder lazily on - // demand and then forever delegates to it after creation. - - printer->Print(variables_, - "private com.google.protobuf.LazyFieldLite $name$_ =\n" - " new com.google.protobuf.LazyFieldLite();\n"); - - printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" - "\n"); - - // The comments above the methods below are based on a hypothetical - // field of type "Field" called "Field". - - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "$name$_.setValue(value);\n" - "$on_changed$\n", - - NULL, // Lazy fields are supported only for lite-runtime. - - "$set_has_field_bit_builder$;\n" - "return this;\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$(\n" - " $type$.Builder builderForValue)", - - "$name$_.setValue(builderForValue.build());\n" - "$on_changed$\n", - - NULL, - - "$set_has_field_bit_builder$;\n" - "return this;\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder merge$capitalized_name$($type$ value)", - - "if ($get_has_field_bit_builder$ &&\n" - " !$name$_.containsDefaultInstance()) {\n" - " $name$_.setValue(\n" - " $type$.newBuilder(\n" - " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" - "} else {\n" - " $name$_.setValue(value);\n" - "}\n" - "$on_changed$\n", - - NULL, - - "$set_has_field_bit_builder$;\n" - "return this;\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder clear$capitalized_name$()", - - "$name$_.clear();\n" - "$on_changed$\n", - - NULL, - - "$clear_has_field_bit_builder$;\n" - "return this;\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n" - " $set_has_field_bit_builder$;\n" - " $on_changed$\n" - " return get$capitalized_name$FieldBuilder().getBuilder();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n" - " if ($name$Builder_ != null) {\n" - " return $name$Builder_.getMessageOrBuilder();\n" - " } else {\n" - " return $name$_;\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " get$capitalized_name$FieldBuilder() {\n" - " if ($name$Builder_ == null) {\n" - " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " $name$_,\n" - " getParentForChildren(),\n" - " isClean());\n" - " $name$_ = null;\n" - " }\n" - " return $name$Builder_;\n" - "}\n"); -} - - -void ImmutableLazyMessageFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.clear();\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_.clear();\n"); - printer->Print(variables_, "$clear_has_field_bit_builder$;\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " $name$_.merge(other.$name$_);\n" - " $set_has_field_bit_builder$;\n" - "}\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); - - printer->Print(variables_, - "result.$name$_.set(\n" - " $name$_);\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.setByteString(input.readBytes(), extensionRegistry);\n"); - printer->Print(variables_, - "$set_has_field_bit_message$;\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Do not de-serialize lazy fields. - printer->Print(variables_, - "if ($get_has_field_bit_message$) {\n" - " output.writeBytes($number$, $name$_.toByteString());\n" - "}\n"); -} - -void ImmutableLazyMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_has_field_bit_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, $name$_);\n" - "}\n"); -} - -// =================================================================== - -ImmutableLazyMessageOneofFieldGenerator:: -ImmutableLazyMessageOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableLazyMessageFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); - variables_["lazy_type"] = "com.google.protobuf.LazyFieldLite"; -} - -ImmutableLazyMessageOneofFieldGenerator:: -~ImmutableLazyMessageOneofFieldGenerator() {} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n" - " $type$.getDefaultInstance());\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n" - " $type$.getDefaultInstance());\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - "}\n" - "(($lazy_type$) $oneof_name$_).setValue(value);\n" - "$on_changed$\n", - - NULL, // Lazy fields are supported only for lite-runtime. - - "return this;\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$(\n" - " $type$.Builder builderForValue)", - - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - "}\n" - "(($lazy_type$) $oneof_name$_).setValue(builderForValue.build());\n" - "$on_changed$\n", - - NULL, - - "return this;\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder merge$capitalized_name$($type$ value)", - - "if ($has_oneof_case_message$ &&\n" - " !(($lazy_type$) $oneof_name$_).containsDefaultInstance()) {\n" - " (($lazy_type$) $oneof_name$_).setValue(\n" - " $type$.newBuilder(\n" - " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" - "} else {\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - " }\n" - " (($lazy_type$) $oneof_name$_).setValue(value);\n" - "}\n" - "$on_changed$\n", - - NULL, - - "return this;\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder clear$capitalized_name$()", - - "if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - "}\n", - - NULL, - - "return this;\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - "}\n" - "(($lazy_type$) $oneof_name$_).merge(\n" - " ($lazy_type$) other.$oneof_name$_);\n" - "$set_oneof_case_message$;\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n"); - printer->Indent(); - - printer->Print(variables_, - "result.$oneof_name$_ = new $lazy_type$();\n" - "(($lazy_type$) result.$oneof_name$_).set(\n" - " (($lazy_type$) $oneof_name$_));\n"); - printer->Outdent(); - printer->Print("}\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - "}\n" - "(($lazy_type$) $oneof_name$_).setByteString(\n" - " input.readBytes(), extensionRegistry);\n" - "$set_oneof_case_message$;\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Do not de-serialize lazy fields. - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeBytes(\n" - " $number$, (($lazy_type$) $oneof_name$_).toByteString());\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, ($lazy_type$) $oneof_name$_);\n" - "}\n"); -} - -// =================================================================== - -RepeatedImmutableLazyMessageFieldGenerator:: -RepeatedImmutableLazyMessageFieldGenerator( - const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : RepeatedImmutableMessageFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { -} - - -RepeatedImmutableLazyMessageFieldGenerator:: -~RepeatedImmutableLazyMessageFieldGenerator() {} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.util.List $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$>\n" - " get$capitalized_name$List() {\n" - " java.util.List<$type$> list =\n" - " new java.util.ArrayList<$type$>($name$_.size());\n" - " for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n" - " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n" - " }\n" - " return list;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List\n" - " get$capitalized_name$OrBuilderList() {\n" - " return get$capitalized_name$List();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int get$capitalized_name$Count() {\n" - " return $name$_.size();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$(int index) {\n" - " return ($type$)\n" - " $name$_.get(index).getValue($type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n" - " int index) {\n" - " return ($type$OrBuilder)\n" - " $name$_.get(index).getValue($type$.getDefaultInstance());\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // When using nested-builders, the code initially works just like the - // non-nested builder case. It only creates a nested builder lazily on - // demand and then forever delegates to it after creation. - - printer->Print(variables_, - "private java.util.List $name$_ =\n" - " java.util.Collections.emptyList();\n" - - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ =\n" - " new java.util.ArrayList(\n" - " $name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n" - "\n"); - - printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;\n" - "\n"); - - // The comments above the methods below are based on a hypothetical - // repeated field of type "Field" called "RepeatedField". - - // List getRepeatedFieldList() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public java.util.List<$type$> get$capitalized_name$List()", - - "java.util.List<$type$> list =\n" - " new java.util.ArrayList<$type$>($name$_.size());\n" - "for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n" - " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n" - "}\n" - "return java.util.Collections.unmodifiableList(list);\n", - - "return $name$Builder_.getMessageList();\n", - - NULL); - - // int getRepeatedFieldCount() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public int get$capitalized_name$Count()", - - "return $name$_.size();\n", - "return $name$Builder_.getCount();\n", - - NULL); - - // Field getRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public $type$ get$capitalized_name$(int index)", - - "return ($type$) $name$_.get(index).getValue(\n" - " $type$.getDefaultInstance());\n", - - "return $name$Builder_.getMessage(index);\n", - - NULL); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$(\n" - " int index, $type$ value)", - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "$on_changed$\n", - "$name$Builder_.setMessage(index, value);\n", - "return this;\n"); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder set$capitalized_name$(\n" - " int index, $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "$on_changed$\n", - - "$name$Builder_.setMessage(index, builderForValue.build());\n", - - "return this;\n"); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder add$capitalized_name$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(com.google.protobuf.LazyFieldLite.fromValue(value));\n" - - "$on_changed$\n", - - "$name$Builder_.addMessage(value);\n", - - "return this;\n"); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder add$capitalized_name$(\n" - " int index, $type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(index, value);\n", - - "return this;\n"); - - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder add$capitalized_name$(\n" - " $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(builderForValue.build());\n", - - "return this;\n"); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder add$capitalized_name$(\n" - " int index, $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(index, builderForValue.build());\n", - - "return this;\n"); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder addAll$capitalized_name$(\n" - " java.lang.Iterable values)", - - "ensure$capitalized_name$IsMutable();\n" - "for (com.google.protobuf.MessageLite v : values) {\n" - " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(v));\n" - "}\n" - "$on_changed$\n", - - "$name$Builder_.addAllMessages(values);\n", - - "return this;\n"); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder clear$capitalized_name$()", - - "$name$_ = java.util.Collections.emptyList();\n" - "$clear_mutable_bit_builder$;\n" - "$on_changed$\n", - - "$name$Builder_.clear();\n", - - "return this;\n"); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder remove$capitalized_name$(int index)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.remove(index);\n" - "$on_changed$\n", - - "$name$Builder_.remove(index);\n", - - "return this;\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder get$capitalized_name$Builder(\n" - " int index) {\n" - " return get$capitalized_name$FieldBuilder().getBuilder(index);\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n" - " int index) {\n" - " if ($name$Builder_ == null) {\n" - " return $name$_.get(index);" - " } else {\n" - " return $name$Builder_.getMessageOrBuilder(index);\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List \n" - " get$capitalized_name$OrBuilderList() {\n" - " if ($name$Builder_ != null) {\n" - " return $name$Builder_.getMessageOrBuilderList();\n" - " } else {\n" - " return java.util.Collections.unmodifiableList($name$_);\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder add$capitalized_name$Builder() {\n" - " return get$capitalized_name$FieldBuilder().addBuilder(\n" - " $type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder add$capitalized_name$Builder(\n" - " int index) {\n" - " return get$capitalized_name$FieldBuilder().addBuilder(\n" - " index, $type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$.Builder> \n" - " get$capitalized_name$BuilderList() {\n" - " return get$capitalized_name$FieldBuilder().getBuilderList();\n" - "}\n" - "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " get$capitalized_name$FieldBuilder() {\n" - " if ($name$Builder_ == null) {\n" - " $name$Builder_ = new com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " $name$_,\n" - " $get_mutable_bit_builder$,\n" - " getParentForChildren(),\n" - " isClean());\n" - " $name$_ = null;\n" - " }\n" - " return $name$Builder_;\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ =\n" - " new java.util.ArrayList();\n" - " $set_mutable_bit_parser$;\n" - "}\n" - "$name$_.add(new com.google.protobuf.LazyFieldLite(\n" - " extensionRegistry, input.readBytes()));\n"); -} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeBytes($number$, $name$_.get(i).toByteString());\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, $name$_.get(i));\n" - "}\n"); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_lazy_message_field.h b/windows/include/google/protobuf/compiler/java/java_lazy_message_field.h deleted file mode 100644 index b1b7f2820..000000000 --- a/windows/include/google/protobuf/compiler/java/java_lazy_message_field.h +++ /dev/null @@ -1,121 +0,0 @@ -// 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. - -// Author: niwasaki@google.com (Naoki Iwasaki) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__ - -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableLazyMessageFieldGenerator - : public ImmutableMessageFieldGenerator { - public: - explicit ImmutableLazyMessageFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableLazyMessageFieldGenerator(); - - // overroads ImmutableMessageFieldGenerator --------------------------------- - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageFieldGenerator); -}; - -class ImmutableLazyMessageOneofFieldGenerator - : public ImmutableLazyMessageFieldGenerator { - public: - ImmutableLazyMessageOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableLazyMessageOneofFieldGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageOneofFieldGenerator); -}; - -class RepeatedImmutableLazyMessageFieldGenerator - : public RepeatedImmutableMessageFieldGenerator { - public: - explicit RepeatedImmutableLazyMessageFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableLazyMessageFieldGenerator(); - - // overroads RepeatedImmutableMessageFieldGenerator ------------------------- - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableLazyMessageFieldGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_lazy_message_field_lite.cc b/windows/include/google/protobuf/compiler/java/java_lazy_message_field_lite.cc deleted file mode 100644 index 51bb11f1c..000000000 --- a/windows/include/google/protobuf/compiler/java/java_lazy_message_field_lite.cc +++ /dev/null @@ -1,725 +0,0 @@ -// 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. - -// Author: niwasaki@google.com (Naoki Iwasaki) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -ImmutableLazyMessageFieldLiteGenerator:: -ImmutableLazyMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableMessageFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { -} - -ImmutableLazyMessageFieldLiteGenerator:: -~ImmutableLazyMessageFieldLiteGenerator() {} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.LazyFieldLite $name$_;"); - - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - } else { - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $name$_ != null;\n" - "}\n"); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " if ($name$_ == null) {\n" - " return $type$.getDefaultInstance();\n" - " }\n" - " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " if ($name$_ == null) {\n" - " $name$_ = new com.google.protobuf.LazyFieldLite();\n" - " }\n" - " $name$_.setValue(value);\n" - " $set_has_field_bit_message$\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " if ($name$_ == null) {\n" - " $name$_ = new com.google.protobuf.LazyFieldLite();\n" - " }\n" - " $name$_.setValue(builderForValue.build());\n" - " $set_has_field_bit_message$\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void merge$capitalized_name$($type$ value) {\n" - " if (has$capitalized_name$() &&\n" - " !$name$_.containsDefaultInstance()) {\n" - " $name$_.setValue(\n" - " $type$.newBuilder(\n" - " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" - " } else {\n" - " if ($name$_ == null) {\n" - " $name$_ = new com.google.protobuf.LazyFieldLite();\n" - " }\n" - " $name$_.setValue(value);\n" - " $set_has_field_bit_message$\n" - " }\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = null;\n" - " $clear_has_field_bit_message$;\n" - "}\n"); -} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // The comments above the methods below are based on a hypothetical - // field of type "Field" called "Field". - - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder merge$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.merge$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder clear$capitalized_name$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); -} - - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const {} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = visitor.visitLazyMessage($name$_, other.$name$_);\n"); -} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($name$_ == null) {\n" - " $name$_ = new com.google.protobuf.LazyFieldLite();\n" - "}\n" - "$name$_.mergeFrom(input, extensionRegistry);\n"); - printer->Print(variables_, - "$set_has_field_bit_message$\n"); -} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Do not de-serialize lazy fields. - printer->Print(variables_, - "if (has$capitalized_name$()) {\n" - " output.writeBytes($number$, $name$_.toByteString());\n" - "}\n"); -} - -void ImmutableLazyMessageFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if (has$capitalized_name$()) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, $name$_);\n" - "}\n"); -} - - -// =================================================================== - -ImmutableLazyMessageOneofFieldLiteGenerator:: -ImmutableLazyMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableLazyMessageFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); - variables_["lazy_type"] = "com.google.protobuf.LazyFieldLite"; -} - -ImmutableLazyMessageOneofFieldLiteGenerator:: -~ImmutableLazyMessageOneofFieldLiteGenerator() {} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n" - " $type$.getDefaultInstance());\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - " }\n" - " (($lazy_type$) $oneof_name$_).setValue(value);\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - " }\n" - " (($lazy_type$) $oneof_name$_).setValue(builderForValue.build());\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void merge$capitalized_name$($type$ value) {\n" - " if ($has_oneof_case_message$ &&\n" - " !(($lazy_type$) $oneof_name$_).containsDefaultInstance()) {\n" - " (($lazy_type$) $oneof_name$_).setValue(\n" - " $type$.newBuilder(\n" - " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" - " } else {\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - " $set_oneof_case_message$;\n" - " }\n" - " (($lazy_type$) $oneof_name$_).setValue(value);\n" - " }\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean has$capitalized_name$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder merge$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.merge$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder clear$capitalized_name$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneofLazyMessage(\n" - " $has_oneof_case_message$,\n" - " ($lazy_type$) $oneof_name$_,\n" - " ($lazy_type$) other.$oneof_name$_);\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = new $lazy_type$();\n" - "}\n" - "(($lazy_type$) $oneof_name$_).mergeFrom(input, extensionRegistry);\n" - "$set_oneof_case_message$;\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Do not de-serialize lazy fields. - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeBytes(\n" - " $number$, (($lazy_type$) $oneof_name$_).toByteString());\n" - "}\n"); -} - -void ImmutableLazyMessageOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, ($lazy_type$) $oneof_name$_);\n" - "}\n"); -} - - -// =================================================================== - -RepeatedImmutableLazyMessageFieldLiteGenerator:: -RepeatedImmutableLazyMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : RepeatedImmutableMessageFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { -} - - -RepeatedImmutableLazyMessageFieldLiteGenerator:: -~RepeatedImmutableLazyMessageFieldLiteGenerator() {} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.Internal.ProtobufList<\n" - " com.google.protobuf.LazyFieldLite> $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$>\n" - " get$capitalized_name$List() {\n" - " java.util.List<$type$> list =\n" - " new java.util.ArrayList<$type$>($name$_.size());\n" - " for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n" - " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n" - " }\n" - " return java.util.Collections.unmodifiableList(list);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List\n" - " get$capitalized_name$OrBuilderList() {\n" - " return get$capitalized_name$List();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int get$capitalized_name$Count() {\n" - " return $name$_.size();\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$(int index) {\n" - " return ($type$)\n" - " $name$_.get(index).getValue($type$.getDefaultInstance());\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n" - " int index) {\n" - " return ($type$OrBuilder)\n" - " $name$_.get(index).getValue($type$.getDefaultInstance());\n" - "}\n"); - - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n" - "\n"); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(\n" - " index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "}\n"); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "}\n"); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "}\n"); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(\n" - " index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" - "}\n"); - - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "}\n"); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(\n" - " builderForValue.build()));\n" - "}\n"); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " for (com.google.protobuf.MessageLite v : values) {\n" - " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(v));\n" - " }\n" - "}\n"); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = emptyProtobufList();\n" - "}\n"); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void remove$capitalized_name$(int index) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.remove(index);\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // List getRepeatedFieldList() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$List());\n" - "}\n"); - - // int getRepeatedFieldCount() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int get$capitalized_name$Count() {\n" - " return instance.get$capitalized_name$Count();\n" - "}\n"); - - // Field getRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ get$capitalized_name$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder set$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, builderForValue);\n" - " return this;\n" - "}\n"); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder add$capitalized_name$($type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder add$capitalized_name$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder add$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder add$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(index, builderForValue);\n" - " return this;\n" - "}\n"); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);\n" - " return this;\n" - "}\n"); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder clear$capitalized_name$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder remove$capitalized_name$(int index) {\n" - " copyOnWrite();\n" - " instance.remove$capitalized_name$(index);\n" - " return this;\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n" - "$name$_.add(new com.google.protobuf.LazyFieldLite(\n" - " extensionRegistry, input.readBytes()));\n"); -} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeBytes($number$, $name$_.get(i).toByteString());\n" - "}\n"); -} - -void RepeatedImmutableLazyMessageFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeLazyFieldSize($number$, $name$_.get(i));\n" - "}\n"); -} - - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_lazy_message_field_lite.h b/windows/include/google/protobuf/compiler/java/java_lazy_message_field_lite.h deleted file mode 100644 index 65b84fbca..000000000 --- a/windows/include/google/protobuf/compiler/java/java_lazy_message_field_lite.h +++ /dev/null @@ -1,121 +0,0 @@ -// 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. - -// Author: niwasaki@google.com (Naoki Iwasaki) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__ - -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableLazyMessageFieldLiteGenerator - : public ImmutableMessageFieldLiteGenerator { - public: - explicit ImmutableLazyMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableLazyMessageFieldLiteGenerator(); - - // overroads ImmutableMessageFieldLiteGenerator ------------------------------ - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageFieldLiteGenerator); -}; - -class ImmutableLazyMessageOneofFieldLiteGenerator - : public ImmutableLazyMessageFieldLiteGenerator { - public: - ImmutableLazyMessageOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableLazyMessageOneofFieldLiteGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableLazyMessageOneofFieldLiteGenerator); -}; - -class RepeatedImmutableLazyMessageFieldLiteGenerator - : public RepeatedImmutableMessageFieldLiteGenerator { - public: - explicit RepeatedImmutableLazyMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableLazyMessageFieldLiteGenerator(); - - // overroads RepeatedImmutableMessageFieldLiteGenerator ---------------------- - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableLazyMessageFieldLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_LAZY_MESSAGE_FIELD_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_map_field.cc b/windows/include/google/protobuf/compiler/java/java_map_field.cc deleted file mode 100644 index b22a21993..000000000 --- a/windows/include/google/protobuf/compiler/java/java_map_field.cc +++ /dev/null @@ -1,797 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { - -const FieldDescriptor* KeyField(const FieldDescriptor* descriptor) { - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, descriptor->type()); - const Descriptor* message = descriptor->message_type(); - GOOGLE_CHECK(message->options().map_entry()); - return message->FindFieldByName("key"); -} - -const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) { - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, descriptor->type()); - const Descriptor* message = descriptor->message_type(); - GOOGLE_CHECK(message->options().map_entry()); - return message->FindFieldByName("value"); -} - -string TypeName(const FieldDescriptor* field, - ClassNameResolver* name_resolver, - bool boxed) { - if (GetJavaType(field) == JAVATYPE_MESSAGE) { - return name_resolver->GetImmutableClassName(field->message_type()); - } else if (GetJavaType(field) == JAVATYPE_ENUM) { - return name_resolver->GetImmutableClassName(field->enum_type()); - } else { - return boxed ? BoxedPrimitiveTypeName(GetJavaType(field)) - : PrimitiveTypeName(GetJavaType(field)); - } -} - -string WireType(const FieldDescriptor* field) { - return "com.google.protobuf.WireFormat.FieldType." + - string(FieldTypeName(field->type())); -} - -void SetMessageVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - Context* context, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - ClassNameResolver* name_resolver = context->GetNameResolver(); - - (*variables)["type"] = - name_resolver->GetImmutableClassName(descriptor->message_type()); - const FieldDescriptor* key = KeyField(descriptor); - const FieldDescriptor* value = ValueField(descriptor); - const JavaType keyJavaType = GetJavaType(key); - const JavaType valueJavaType = GetJavaType(value); - - (*variables)["key_type"] = TypeName(key, name_resolver, false); - string boxed_key_type = TypeName(key, name_resolver, true); - (*variables)["boxed_key_type"] = boxed_key_type; - // Used for calling the serialization function. - (*variables)["short_key_type"] = - boxed_key_type.substr(boxed_key_type.rfind('.') + 1); - (*variables)["key_wire_type"] = WireType(key); - (*variables)["key_default_value"] = DefaultValue(key, true, name_resolver); - (*variables)["key_null_check"] = IsReferenceType(keyJavaType) ? - "if (key == null) { throw new java.lang.NullPointerException(); }" : ""; - (*variables)["value_null_check"] = IsReferenceType(valueJavaType) ? - "if (value == null) { throw new java.lang.NullPointerException(); }" : ""; - if (valueJavaType == JAVATYPE_ENUM) { - // We store enums as Integers internally. - (*variables)["value_type"] = "int"; - (*variables)["boxed_value_type"] = "java.lang.Integer"; - (*variables)["value_wire_type"] = WireType(value); - (*variables)["value_default_value"] = - DefaultValue(value, true, name_resolver) + ".getNumber()"; - - (*variables)["value_enum_type"] = TypeName(value, name_resolver, false); - - if (SupportUnknownEnumValue(descriptor->file())) { - // Map unknown values to a special UNRECOGNIZED value if supported. - (*variables)["unrecognized_value"] = - (*variables)["value_enum_type"] + ".UNRECOGNIZED"; - } else { - // Map unknown values to the default value if we don't have UNRECOGNIZED. - (*variables)["unrecognized_value"] = - DefaultValue(value, true, name_resolver); - } - } else { - (*variables)["value_type"] = TypeName(value, name_resolver, false); - (*variables)["boxed_value_type"] = TypeName(value, name_resolver, true); - (*variables)["value_wire_type"] = WireType(value); - (*variables)["value_default_value"] = - DefaultValue(value, true, name_resolver); - } - (*variables)["type_parameters"] = - (*variables)["boxed_key_type"] + ", " + (*variables)["boxed_value_type"]; - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - (*variables)["on_changed"] = "onChanged();"; - - // For repeated fields, one bit is used for whether the array is immutable - // in the parsing constructor. - (*variables)["get_mutable_bit_parser"] = - GenerateGetBitMutableLocal(builderBitIndex); - (*variables)["set_mutable_bit_parser"] = - GenerateSetBitMutableLocal(builderBitIndex); - - (*variables)["default_entry"] = (*variables)["capitalized_name"] + - "DefaultEntryHolder.defaultEntry"; - (*variables)["map_field_parameter"] = (*variables)["default_entry"]; - (*variables)["descriptor"] = - name_resolver->GetImmutableClassName(descriptor->file()) + - ".internal_" + UniqueFileScopeIdentifier(descriptor->message_type()) + - "_descriptor, "; - (*variables)["ver"] = GeneratedCodeVersionSuffix(); -} - -} // namespace - -ImmutableMapFieldGenerator:: -ImmutableMapFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - context, &variables_); -} - -ImmutableMapFieldGenerator:: -~ImmutableMapFieldGenerator() {} - -int ImmutableMapFieldGenerator::GetNumBitsForMessage() const { - return 0; -} - -int ImmutableMapFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -void ImmutableMapFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$boolean ${$contains$capitalized_name$$}$(\n" - " $key_type$ key);\n"); - printer->Annotate("{", "}", descriptor_); - if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$Map$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$$value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_enum_type$ defaultValue);\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$$value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key);\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$Value$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$ValueMap$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue);\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" - " $key_type$ key);\n"); - printer->Annotate("{", "}", descriptor_); - } - } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$Map$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue);\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key);\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void ImmutableMapFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print( - variables_, - "private static final class $capitalized_name$DefaultEntryHolder {\n" - " static final com.google.protobuf.MapEntry<\n" - " $type_parameters$> defaultEntry =\n" - " com.google.protobuf.MapEntry\n" - " .<$type_parameters$>newDefaultInstance(\n" - " $descriptor$\n" - " $key_wire_type$,\n" - " $key_default_value$,\n" - " $value_wire_type$,\n" - " $value_default_value$);\n" - "}\n"); - printer->Print( - variables_, - "private com.google.protobuf.MapField<\n" - " $type_parameters$> $name$_;\n" - "private com.google.protobuf.MapField<$type_parameters$>\n" - "internalGet$capitalized_name$() {\n" - " if ($name$_ == null) {\n" - " return com.google.protobuf.MapField.emptyMapField(\n" - " $map_field_parameter$);\n" - " }\n" - " return $name$_;\n" - "}\n"); - if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "private static final\n" - "com.google.protobuf.Internal.MapAdapter.Converter<\n" - " java.lang.Integer, $value_enum_type$> $name$ValueConverter =\n" - " com.google.protobuf.Internal.MapAdapter.newEnumConverter(\n" - " $value_enum_type$.internalGetValueMap(),\n" - " $unrecognized_value$);\n"); - printer->Print( - variables_, - "private static final java.util.Map<$boxed_key_type$, " - "$value_enum_type$>\n" - "internalGetAdapted$capitalized_name$Map(\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map) {\n" - " return new com.google.protobuf.Internal.MapAdapter<\n" - " $boxed_key_type$, $value_enum_type$, java.lang.Integer>(\n" - " map, $name$ValueConverter);\n" - "}\n"); - } - GenerateMapGetters(printer); -} - -void ImmutableMapFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print( - variables_, - "private com.google.protobuf.MapField<\n" - " $type_parameters$> $name$_;\n" - "private com.google.protobuf.MapField<$type_parameters$>\n" - "internalGet$capitalized_name$() {\n" - " if ($name$_ == null) {\n" - " return com.google.protobuf.MapField.emptyMapField(\n" - " $map_field_parameter$);\n" - " }\n" - " return $name$_;\n" - "}\n" - "private com.google.protobuf.MapField<$type_parameters$>\n" - "internalGetMutable$capitalized_name$() {\n" - " $on_changed$;\n" - " if ($name$_ == null) {\n" - " $name$_ = com.google.protobuf.MapField.newMapField(\n" - " $map_field_parameter$);\n" - " }\n" - " if (!$name$_.isMutable()) {\n" - " $name$_ = $name$_.copy();\n" - " }\n" - " return $name$_;\n" - "}\n"); - GenerateMapGetters(printer); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$clear$capitalized_name$$}$() {\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .clear();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$remove$capitalized_name$$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .remove(key);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use alternate mutation accessors instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$getMutable$capitalized_name$$}$() {\n" - " return internalGetAdapted$capitalized_name$Map(\n" - " internalGetMutable$capitalized_name$().getMutableMap());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$put$capitalized_name$$}$(\n" - " $key_type$ key,\n" - " $value_enum_type$ value) {\n" - " $key_null_check$\n" - " $value_null_check$\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .put(key, $name$ValueConverter.doBackward(value));\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$public Builder ${$putAll$capitalized_name$$}$(\n" - " java.util.Map<$boxed_key_type$, $value_enum_type$> values) {\n" - " internalGetAdapted$capitalized_name$Map(\n" - " internalGetMutable$capitalized_name$().getMutableMap())\n" - " .putAll(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print( - variables_, - "/**\n" - " * Use alternate mutation accessors instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" - "${$getMutable$capitalized_name$Value$}$() {\n" - " return internalGetMutable$capitalized_name$().getMutableMap();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$public Builder ${$put$capitalized_name$Value$}$(\n" - " $key_type$ key,\n" - " $value_type$ value) {\n" - " $key_null_check$\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .put(key, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$public Builder ${$putAll$capitalized_name$Value$}$(\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> values) {\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .putAll(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - } else { - printer->Print( - variables_, - "/**\n" - " * Use alternate mutation accessors instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$type_parameters$>\n" - "${$getMutable$capitalized_name$$}$() {\n" - " return internalGetMutable$capitalized_name$().getMutableMap();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$" - "public Builder ${$put$capitalized_name$$}$(\n" - " $key_type$ key,\n" - " $value_type$ value) {\n" - " $key_null_check$\n" - " $value_null_check$\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .put(key, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$putAll$capitalized_name$$}$(\n" - " java.util.Map<$type_parameters$> values) {\n" - " internalGetMutable$capitalized_name$().getMutableMap()\n" - " .putAll(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void ImmutableMapFieldGenerator:: -GenerateMapGetters(io::Printer* printer) const { - printer->Print( - variables_, - "$deprecation$\n" - "public int ${$get$capitalized_name$Count$}$() {\n" - " return internalGet$capitalized_name$().getMap().size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public boolean ${$contains$capitalized_name$$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " return internalGet$capitalized_name$().getMap().containsKey(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$Map$}$() {\n" - " return internalGetAdapted$capitalized_name$Map(\n" - " internalGet$capitalized_name$().getMap());" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_enum_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " internalGet$capitalized_name$().getMap();\n" - " return map.containsKey(key)\n" - " ? $name$ValueConverter.doForward(map.get(key))\n" - " : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " internalGet$capitalized_name$().getMap();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return $name$ValueConverter.doForward(map.get(key));\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" - "${$get$capitalized_name$Value$}$() {\n" - " return get$capitalized_name$ValueMap();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" - "${$get$capitalized_name$ValueMap$}$() {\n" - " return internalGet$capitalized_name$().getMap();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " internalGet$capitalized_name$().getMap();\n" - " return map.containsKey(key) ? map.get(key) : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " internalGet$capitalized_name$().getMap();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$Map$}$() {\n" - " return internalGet$capitalized_name$().getMap();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " internalGet$capitalized_name$().getMap();\n" - " return map.containsKey(key) ? map.get(key) : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " internalGet$capitalized_name$().getMap();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void ImmutableMapFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // Nothing to initialize. -} - -void ImmutableMapFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - // Nothing to initialize. -} - -void ImmutableMapFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print( - variables_, - "internalGetMutable$capitalized_name$().clear();\n"); -} - -void ImmutableMapFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print( - variables_, - "internalGetMutable$capitalized_name$().mergeFrom(\n" - " other.internalGet$capitalized_name$());\n"); -} - -void ImmutableMapFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print( - variables_, - "result.$name$_ = internalGet$capitalized_name$();\n" - "result.$name$_.makeImmutable();\n"); -} - -void ImmutableMapFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print( - variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = com.google.protobuf.MapField.newMapField(\n" - " $map_field_parameter$);\n" - " $set_mutable_bit_parser$;\n" - "}\n"); - if (!SupportUnknownEnumValue(descriptor_->file()) && - GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "com.google.protobuf.ByteString bytes = input.readBytes();\n" - "com.google.protobuf.MapEntry<$type_parameters$>\n" - "$name$__ = $default_entry$.getParserForType().parseFrom(bytes);\n"); - printer->Print( - variables_, - "if ($value_enum_type$.forNumber($name$__.getValue()) == null) {\n" - " unknownFields.mergeLengthDelimitedField($number$, bytes);\n" - "} else {\n" - " $name$_.getMutableMap().put(\n" - " $name$__.getKey(), $name$__.getValue());\n" - "}\n"); - } else { - printer->Print( - variables_, - "com.google.protobuf.MapEntry<$type_parameters$>\n" - "$name$__ = input.readMessage(\n" - " $default_entry$.getParserForType(), extensionRegistry);\n" - "$name$_.getMutableMap().put(\n" - " $name$__.getKey(), $name$__.getValue());\n"); - } -} - -void ImmutableMapFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // Nothing to do here. -} - -void ImmutableMapFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print( - variables_, - "com.google.protobuf.GeneratedMessage$ver$\n" - " .serialize$short_key_type$MapTo(\n" - " output,\n" - " internalGet$capitalized_name$(),\n" - " $default_entry$,\n" - " $number$);\n"); -} - -void ImmutableMapFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print( - variables_, - "for (java.util.Map.Entry<$type_parameters$> entry\n" - " : internalGet$capitalized_name$().getMap().entrySet()) {\n" - " com.google.protobuf.MapEntry<$type_parameters$>\n" - " $name$__ = $default_entry$.newBuilderForType()\n" - " .setKey(entry.getKey())\n" - " .setValue(entry.getValue())\n" - " .build();\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeMessageSize($number$, $name$__);\n" - "}\n"); -} - -void ImmutableMapFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print( - variables_, - "result = result && internalGet$capitalized_name$().equals(\n" - " other.internalGet$capitalized_name$());\n"); -} - -void ImmutableMapFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print( - variables_, - "if (!internalGet$capitalized_name$().getMap().isEmpty()) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + internalGet$capitalized_name$().hashCode();\n" - "}\n"); -} - -string ImmutableMapFieldGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->message_type()); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_map_field.h b/windows/include/google/protobuf/compiler/java/java_map_field.h deleted file mode 100644 index 470217406..000000000 --- a/windows/include/google/protobuf/compiler/java/java_map_field.h +++ /dev/null @@ -1,80 +0,0 @@ -// 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_JAVA_MAP_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_H__ - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableMapFieldGenerator : public ImmutableFieldGenerator { - public: - explicit ImmutableMapFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableMapFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - ClassNameResolver* name_resolver_; - void GenerateMapGetters(io::Printer* printer) const; -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_map_field_lite.cc b/windows/include/google/protobuf/compiler/java/java_map_field_lite.cc deleted file mode 100644 index e2e68076c..000000000 --- a/windows/include/google/protobuf/compiler/java/java_map_field_lite.cc +++ /dev/null @@ -1,914 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { - -const FieldDescriptor* KeyField(const FieldDescriptor* descriptor) { - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, descriptor->type()); - const Descriptor* message = descriptor->message_type(); - GOOGLE_CHECK(message->options().map_entry()); - return message->FindFieldByName("key"); -} - -const FieldDescriptor* ValueField(const FieldDescriptor* descriptor) { - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, descriptor->type()); - const Descriptor* message = descriptor->message_type(); - GOOGLE_CHECK(message->options().map_entry()); - return message->FindFieldByName("value"); -} - -string TypeName(const FieldDescriptor* field, - ClassNameResolver* name_resolver, - bool boxed) { - if (GetJavaType(field) == JAVATYPE_MESSAGE) { - return name_resolver->GetImmutableClassName(field->message_type()); - } else if (GetJavaType(field) == JAVATYPE_ENUM) { - return name_resolver->GetImmutableClassName(field->enum_type()); - } else { - return boxed ? BoxedPrimitiveTypeName(GetJavaType(field)) - : PrimitiveTypeName(GetJavaType(field)); - } -} - -string WireType(const FieldDescriptor* field) { - return "com.google.protobuf.WireFormat.FieldType." + - string(FieldTypeName(field->type())); -} - -void SetMessageVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - Context* context, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - - ClassNameResolver* name_resolver = context->GetNameResolver(); - (*variables)["type"] = - name_resolver->GetImmutableClassName(descriptor->message_type()); - const FieldDescriptor* key = KeyField(descriptor); - const FieldDescriptor* value = ValueField(descriptor); - const JavaType keyJavaType = GetJavaType(key); - const JavaType valueJavaType = GetJavaType(value); - - (*variables)["key_type"] = TypeName(key, name_resolver, false); - (*variables)["boxed_key_type"] = TypeName(key, name_resolver, true); - (*variables)["key_wire_type"] = WireType(key); - (*variables)["key_default_value"] = DefaultValue(key, true, name_resolver); - (*variables)["key_null_check"] = IsReferenceType(keyJavaType) ? - "if (key == null) { throw new java.lang.NullPointerException(); }" : ""; - (*variables)["value_null_check"] = IsReferenceType(valueJavaType) ? - "if (value == null) { throw new java.lang.NullPointerException(); }" : ""; - - if (GetJavaType(value) == JAVATYPE_ENUM) { - // We store enums as Integers internally. - (*variables)["value_type"] = "int"; - (*variables)["boxed_value_type"] = "java.lang.Integer"; - (*variables)["value_wire_type"] = WireType(value); - (*variables)["value_default_value"] = - DefaultValue(value, true, name_resolver) + ".getNumber()"; - - (*variables)["value_enum_type"] = TypeName(value, name_resolver, false); - - if (SupportUnknownEnumValue(descriptor->file())) { - // Map unknown values to a special UNRECOGNIZED value if supported. - (*variables)["unrecognized_value"] = - (*variables)["value_enum_type"] + ".UNRECOGNIZED"; - } else { - // Map unknown values to the default value if we don't have UNRECOGNIZED. - (*variables)["unrecognized_value"] = - DefaultValue(value, true, name_resolver); - } - } else { - (*variables)["value_type"] = TypeName(value, name_resolver, false); - (*variables)["boxed_value_type"] = TypeName(value, name_resolver, true); - (*variables)["value_wire_type"] = WireType(value); - (*variables)["value_default_value"] = - DefaultValue(value, true, name_resolver); - } - (*variables)["type_parameters"] = - (*variables)["boxed_key_type"] + ", " + (*variables)["boxed_value_type"]; - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - - (*variables)["default_entry"] = (*variables)["capitalized_name"] + - "DefaultEntryHolder.defaultEntry"; -} - -} // namespace - -ImmutableMapFieldLiteGenerator:: -ImmutableMapFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - context, &variables_); -} - -ImmutableMapFieldLiteGenerator:: -~ImmutableMapFieldLiteGenerator() {} - -int ImmutableMapFieldLiteGenerator::GetNumBitsForMessage() const { - return 0; -} - -int ImmutableMapFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void ImmutableMapFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$int ${$get$capitalized_name$Count$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$boolean ${$contains$capitalized_name$$}$(\n" - " $key_type$ key);\n"); - printer->Annotate("{", "}", descriptor_); - if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$Map$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$$value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_enum_type$ defaultValue);\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$$value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key);\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$Value$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$ValueMap$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue);\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" - " $key_type$ key);\n"); - printer->Annotate("{", "}", descriptor_); - } - } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$java.util.Map<$type_parameters$>\n" - "${$get$capitalized_name$Map$}$();\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue);\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "$value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key);\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void ImmutableMapFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print( - variables_, - "private static final class $capitalized_name$DefaultEntryHolder {\n" - " static final com.google.protobuf.MapEntryLite<\n" - " $type_parameters$> defaultEntry =\n" - " com.google.protobuf.MapEntryLite\n" - " .<$type_parameters$>newDefaultInstance(\n" - " $key_wire_type$,\n" - " $key_default_value$,\n" - " $value_wire_type$,\n" - " $value_default_value$);\n" - "}\n"); - printer->Print( - variables_, - "private com.google.protobuf.MapFieldLite<\n" - " $type_parameters$> $name$_ =\n" - " com.google.protobuf.MapFieldLite.emptyMapField();\n" - "private com.google.protobuf.MapFieldLite<$type_parameters$>\n" - "internalGet$capitalized_name$() {\n" - " return $name$_;\n" - "}\n" - "private com.google.protobuf.MapFieldLite<$type_parameters$>\n" - "internalGetMutable$capitalized_name$() {\n" - " if (!$name$_.isMutable()) {\n" - " $name$_ = $name$_.mutableCopy();\n" - " }\n" - " return $name$_;\n" - "}\n"); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public int ${$get$capitalized_name$Count$}$() {\n" - " return internalGet$capitalized_name$().size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public boolean ${$contains$capitalized_name$$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " return internalGet$capitalized_name$().containsKey(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "private static final\n" - "com.google.protobuf.Internal.MapAdapter.Converter<\n" - " java.lang.Integer, $value_enum_type$> $name$ValueConverter =\n" - " com.google.protobuf.Internal.MapAdapter.newEnumConverter(\n" - " $value_enum_type$.internalGetValueMap(),\n" - " $unrecognized_value$);\n"); - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$Map$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " new com.google.protobuf.Internal.MapAdapter<\n" - " $boxed_key_type$, $value_enum_type$, java.lang.Integer>(\n" - " internalGet$capitalized_name$(),\n" - " $name$ValueConverter));\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_enum_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " internalGet$capitalized_name$();\n" - " return map.containsKey(key)\n" - " ? $name$ValueConverter.doForward(map.get(key))\n" - " : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " internalGet$capitalized_name$();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return $name$ValueConverter.doForward(map.get(key));\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" - " */\n" - "@java.lang.Override\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" - "${$get$capitalized_name$Value$}$() {\n" - " return get$capitalized_name$ValueMap();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" - "${$get$capitalized_name$ValueMap$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " internalGet$capitalized_name$());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " internalGet$capitalized_name$();\n" - " return map.containsKey(key) ? map.get(key) : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " internalGet$capitalized_name$();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Override\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$Map$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " internalGet$capitalized_name$());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " internalGet$capitalized_name$();\n" - " return map.containsKey(key) ? map.get(key) : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " internalGet$capitalized_name$();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - // Generate private setters for the builder to proxy into. - if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "private java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "getMutable$capitalized_name$Map() {\n" - " return new com.google.protobuf.Internal.MapAdapter<\n" - " $boxed_key_type$, $value_enum_type$, java.lang.Integer>(\n" - " internalGetMutable$capitalized_name$(),\n" - " $name$ValueConverter);\n" - "}\n"); - if (SupportUnknownEnumValue(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "private java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" - "getMutable$capitalized_name$ValueMap() {\n" - " return internalGetMutable$capitalized_name$();\n" - "}\n"); - } - } else { - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "private java.util.Map<$type_parameters$>\n" - "getMutable$capitalized_name$Map() {\n" - " return internalGetMutable$capitalized_name$();\n" - "}\n"); - } -} - - -void ImmutableMapFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Map().size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public boolean ${$contains$capitalized_name$$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " return instance.get$capitalized_name$Map().containsKey(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$Map().clear();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$\n" - "public Builder ${$remove$capitalized_name$$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$Map().remove(key);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public java.util.Map<$boxed_key_type$, $value_enum_type$>\n" - "${$get$capitalized_name$Map$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " instance.get$capitalized_name$Map());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_enum_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $value_enum_type$> map =\n" - " instance.get$capitalized_name$Map();\n" - " return map.containsKey(key)\n" - " ? map.get(key)\n" - " : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $value_enum_type$> map =\n" - " instance.get$capitalized_name$Map();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$public Builder ${$put$capitalized_name$$}$(\n" - " $key_type$ key,\n" - " $value_enum_type$ value) {\n" - " $key_null_check$\n" - " $value_null_check$\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$Map().put(key, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$public Builder ${$putAll$capitalized_name$$}$(\n" - " java.util.Map<$boxed_key_type$, $value_enum_type$> values) {\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$Map().putAll(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - if (SupportUnknownEnumValue(descriptor_->file())) { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$ValueMap()} instead.\n" - " */\n" - "@java.lang.Override\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" - "${$get$capitalized_name$Value$}$() {\n" - " return get$capitalized_name$ValueMap();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n" - "${$get$capitalized_name$ValueMap$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " instance.get$capitalized_name$ValueMap());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " instance.get$capitalized_name$ValueMap();\n" - " return map.containsKey(key) ? map.get(key) : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n" - " instance.get$capitalized_name$ValueMap();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$public Builder ${$put$capitalized_name$Value$}$(\n" - " $key_type$ key,\n" - " $value_type$ value) {\n" - " $key_null_check$\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$ValueMap().put(key, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$public Builder ${$putAll$capitalized_name$Value$}$(\n" - " java.util.Map<$boxed_key_type$, $boxed_value_type$> values) {\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$ValueMap().putAll(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - } else { - printer->Print( - variables_, - "/**\n" - " * Use {@link #get$capitalized_name$Map()} instead.\n" - " */\n" - "@java.lang.Override\n" - "@java.lang.Deprecated\n" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$$}$() {\n" - " return get$capitalized_name$Map();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$" - "public java.util.Map<$type_parameters$> " - "${$get$capitalized_name$Map$}$() {\n" - " return java.util.Collections.unmodifiableMap(\n" - " instance.get$capitalized_name$Map());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n" - " $key_type$ key,\n" - " $value_type$ defaultValue) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " instance.get$capitalized_name$Map();\n" - " return map.containsKey(key) ? map.get(key) : defaultValue;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "@java.lang.Override\n" - "$deprecation$\n" - "public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n" - " $key_type$ key) {\n" - " $key_null_check$\n" - " java.util.Map<$type_parameters$> map =\n" - " instance.get$capitalized_name$Map();\n" - " if (!map.containsKey(key)) {\n" - " throw new java.lang.IllegalArgumentException();\n" - " }\n" - " return map.get(key);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$" - "public Builder ${$put$capitalized_name$$}$(\n" - " $key_type$ key,\n" - " $value_type$ value) {\n" - " $key_null_check$\n" - " $value_null_check$\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$Map().put(key, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print( - variables_, - "$deprecation$" - "public Builder ${$putAll$capitalized_name$$}$(\n" - " java.util.Map<$type_parameters$> values) {\n" - " copyOnWrite();\n" - " instance.getMutable$capitalized_name$Map().putAll(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void ImmutableMapFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // Nothing to initialize. -} - -void ImmutableMapFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - // Nothing to initialize. -} - -void ImmutableMapFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print( - variables_, - "$name$_ = visitor.visitMap(\n" - " $name$_, other.internalGet$capitalized_name$());\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print( - variables_, - "if (!$name$_.isMutable()) {\n" - " $name$_ = $name$_.mutableCopy();\n" - "}\n"); - if (!SupportUnknownEnumValue(descriptor_->file()) && - GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) { - printer->Print( - variables_, - "com.google.protobuf.ByteString bytes = input.readBytes();\n" - "java.util.Map.Entry<$type_parameters$> $name$__ =\n" - " $default_entry$.parseEntry(bytes, extensionRegistry);\n"); - printer->Print( - variables_, - "if ($value_enum_type$.forNumber($name$__.getValue()) == null) {\n" - " super.mergeLengthDelimitedField($number$, bytes);\n" - "} else {\n" - " $name$_.put($name$__);\n" - "}\n"); - } else { - printer->Print( - variables_, - "$default_entry$.parseInto($name$_, input, extensionRegistry);"); - } -} - -void ImmutableMapFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // Nothing to do here. -} - -void ImmutableMapFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print( - variables_, - "for (java.util.Map.Entry<$type_parameters$> entry\n" - " : internalGet$capitalized_name$().entrySet()) {\n" - " $default_entry$.serializeTo(\n" - " output, $number$, entry.getKey(), entry.getValue());\n" - "}\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print( - variables_, - "for (java.util.Map.Entry<$type_parameters$> entry\n" - " : internalGet$capitalized_name$().entrySet()) {\n" - " size += $default_entry$.computeMessageSize(\n" - " $number$, entry.getKey(), entry.getValue());\n" - "}\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print( - variables_, - "result = result && internalGet$capitalized_name$().equals(\n" - " other.internalGet$capitalized_name$());\n"); -} - -void ImmutableMapFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print( - variables_, - "if (!internalGet$capitalized_name$().isEmpty()) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + internalGet$capitalized_name$().hashCode();\n" - "}\n"); -} - -string ImmutableMapFieldLiteGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->message_type()); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_map_field_lite.h b/windows/include/google/protobuf/compiler/java/java_map_field_lite.h deleted file mode 100644 index 94aa48136..000000000 --- a/windows/include/google/protobuf/compiler/java/java_map_field_lite.h +++ /dev/null @@ -1,79 +0,0 @@ -// 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_JAVA_MAP_FIELD_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_LITE_H__ - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableMapFieldLiteGenerator : public ImmutableFieldLiteGenerator { - public: - explicit ImmutableMapFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableMapFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - ClassNameResolver* name_resolver_; -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_message.cc b/windows/include/google/protobuf/compiler/java/java_message.cc deleted file mode 100644 index 209c0b2a2..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message.cc +++ /dev/null @@ -1,1507 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { -bool GenerateHasBits(const Descriptor* descriptor) { - return SupportFieldPresence(descriptor->file()) || - HasRepeatedFields(descriptor); -} - -string MapValueImmutableClassdName(const Descriptor* descriptor, - ClassNameResolver* name_resolver) { - const FieldDescriptor* value_field = descriptor->FindFieldByName("value"); - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type()); - return name_resolver->GetImmutableClassName(value_field->message_type()); -} -} // namespace - -// =================================================================== - -MessageGenerator::MessageGenerator(const Descriptor* descriptor) - : descriptor_(descriptor) {} - -MessageGenerator::~MessageGenerator() {} - -// =================================================================== -ImmutableMessageGenerator::ImmutableMessageGenerator( - const Descriptor* descriptor, Context* context) - : MessageGenerator(descriptor), context_(context), - name_resolver_(context->GetNameResolver()), - field_generators_(descriptor, context_) { - GOOGLE_CHECK(HasDescriptorMethods(descriptor->file(), context->EnforceLite())) - << "Generator factory error: A non-lite message generator is used to " - "generate lite messages."; -} - -ImmutableMessageGenerator::~ImmutableMessageGenerator() {} - -void ImmutableMessageGenerator::GenerateStaticVariables( - io::Printer* printer, int* bytecode_estimate) { - // Because descriptor.proto (com.google.protobuf.DescriptorProtos) is - // used in the construction of descriptors, we have a tricky bootstrapping - // problem. To help control static initialization order, we make sure all - // descriptors and other static data that depends on them are members of - // the outermost class in the file. This way, they will be initialized in - // a deterministic order. - - std::map vars; - vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); - vars["index"] = SimpleItoa(descriptor_->index()); - vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_); - if (descriptor_->containing_type() != NULL) { - vars["parent"] = UniqueFileScopeIdentifier( - descriptor_->containing_type()); - } - if (MultipleJavaFiles(descriptor_->file(), /* immutable = */ true)) { - // We can only make these package-private since the classes that use them - // are in separate files. - vars["private"] = ""; - } else { - vars["private"] = "private "; - } - if (*bytecode_estimate <= kMaxStaticSize) { - vars["final"] = "final "; - } else { - vars["final"] = ""; - } - - // The descriptor for this type. - printer->Print(vars, - // TODO(teboring): final needs to be added back. The way to fix it is to - // generate methods that can construct the types, and then still declare the - // types, and then init them in clinit with the new method calls. - "$private$static $final$com.google.protobuf.Descriptors.Descriptor\n" - " internal_$identifier$_descriptor;\n"); - *bytecode_estimate += 30; - - // And the FieldAccessorTable. - GenerateFieldAccessorTable(printer, bytecode_estimate); - - // Generate static members for all nested types. - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // TODO(kenton): Reuse MessageGenerator objects? - ImmutableMessageGenerator(descriptor_->nested_type(i), context_) - .GenerateStaticVariables(printer, bytecode_estimate); - } -} - -int ImmutableMessageGenerator::GenerateStaticVariableInitializers( - io::Printer* printer) { - int bytecode_estimate = 0; - std::map vars; - vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); - vars["index"] = SimpleItoa(descriptor_->index()); - vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_); - if (descriptor_->containing_type() != NULL) { - vars["parent"] = UniqueFileScopeIdentifier( - descriptor_->containing_type()); - } - - // The descriptor for this type. - if (descriptor_->containing_type() == NULL) { - printer->Print(vars, - "internal_$identifier$_descriptor =\n" - " getDescriptor().getMessageTypes().get($index$);\n"); - bytecode_estimate += 30; - } else { - printer->Print(vars, - "internal_$identifier$_descriptor =\n" - " internal_$parent$_descriptor.getNestedTypes().get($index$);\n"); - bytecode_estimate += 30; - } - - // And the FieldAccessorTable. - bytecode_estimate += GenerateFieldAccessorTableInitializer(printer); - - // Generate static member initializers for all nested types. - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // TODO(kenton): Reuse MessageGenerator objects? - bytecode_estimate += - ImmutableMessageGenerator(descriptor_->nested_type(i), context_) - .GenerateStaticVariableInitializers(printer); - } - return bytecode_estimate; -} - -void ImmutableMessageGenerator:: -GenerateFieldAccessorTable(io::Printer* printer, int* bytecode_estimate) { - std::map vars; - vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); - if (MultipleJavaFiles(descriptor_->file(), /* immutable = */ true)) { - // We can only make these package-private since the classes that use them - // are in separate files. - vars["private"] = ""; - } else { - vars["private"] = "private "; - } - if (*bytecode_estimate <= kMaxStaticSize) { - vars["final"] = "final "; - } else { - vars["final"] = ""; - } - vars["ver"] = GeneratedCodeVersionSuffix(); - printer->Print(vars, - "$private$static $final$\n" - " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" - " internal_$identifier$_fieldAccessorTable;\n"); - - // 6 bytes per field and oneof - *bytecode_estimate += 10 + 6 * descriptor_->field_count() - + 6 * descriptor_->oneof_decl_count(); -} - -int ImmutableMessageGenerator:: -GenerateFieldAccessorTableInitializer(io::Printer* printer) { - int bytecode_estimate = 10; - printer->Print( - "internal_$identifier$_fieldAccessorTable = new\n" - " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable(\n" - " internal_$identifier$_descriptor,\n" - " new java.lang.String[] { ", - "identifier", UniqueFileScopeIdentifier(descriptor_), - "ver", GeneratedCodeVersionSuffix()); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - bytecode_estimate += 6; - printer->Print( - "\"$field_name$\", ", - "field_name", info->capitalized_name); - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = descriptor_->oneof_decl(i); - const OneofGeneratorInfo* info = context_->GetOneofGeneratorInfo(oneof); - bytecode_estimate += 6; - printer->Print( - "\"$oneof_name$\", ", - "oneof_name", info->capitalized_name); - } - printer->Print("});\n"); - return bytecode_estimate; -} - -// =================================================================== - -void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) { - MaybePrintGeneratedAnnotation(context_, printer, descriptor_, - /* immutable = */ true, "OrBuilder"); - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n" - " $extra_interfaces$\n" - " com.google.protobuf.GeneratedMessage$ver$.\n" - " ExtendableMessageOrBuilder<$classname$> {\n", - "deprecation", descriptor_->options().deprecated() ? - "@java.lang.Deprecated " : "", - "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name(), - "{", "", "}", "", "ver", GeneratedCodeVersionSuffix()); - } else { - printer->Print( - "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n" - " $extra_interfaces$\n" - " com.google.protobuf.MessageOrBuilder {\n", - "deprecation", descriptor_->options().deprecated() ? - "@java.lang.Deprecated " : "", - "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name(), - "{", "", "}", ""); - } - printer->Annotate("{", "}", descriptor_); - - printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("\n"); - field_generators_.get(descriptor_->field(i)) - .GenerateInterfaceMembers(printer); - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "\n" - "public $classname$.$oneof_capitalized_name$Case " - "get$oneof_capitalized_name$Case();\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name, - "classname", - context_->GetNameResolver()->GetImmutableClassName( - descriptor_)); - } - printer->Outdent(); - - printer->Print("}\n"); -} - -// =================================================================== - -void ImmutableMessageGenerator::Generate(io::Printer* printer) { - bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true); - - std::map variables; - variables["static"] = is_own_file ? " " : " static "; - variables["classname"] = descriptor_->name(); - variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_); - variables["ver"] = GeneratedCodeVersionSuffix(); - variables["deprecation"] = descriptor_->options().deprecated() - ? "@java.lang.Deprecated " : ""; - - WriteMessageDocComment(printer, descriptor_); - MaybePrintGeneratedAnnotation(context_, printer, descriptor_, - /* immutable = */ true); - - // The builder_type stores the super type name of the nested Builder class. - string builder_type; - if (descriptor_->extension_range_count() > 0) { - printer->Print( - variables, - "$deprecation$public $static$final class $classname$ extends\n"); - printer->Annotate("classname", descriptor_); - printer->Print( - variables, - " com.google.protobuf.GeneratedMessage$ver$.ExtendableMessage<\n" - " $classname$> implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n"); - builder_type = strings::Substitute( - "com.google.protobuf.GeneratedMessage$1.ExtendableBuilder<$0, ?>", - name_resolver_->GetImmutableClassName(descriptor_), - GeneratedCodeVersionSuffix()); - } else { - printer->Print( - variables, - "$deprecation$public $static$final class $classname$ extends\n"); - printer->Annotate("classname", descriptor_); - printer->Print(variables, - " com.google.protobuf.GeneratedMessage$ver$ implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n"); - builder_type = strings::Substitute( - "com.google.protobuf.GeneratedMessage$0.Builder", - GeneratedCodeVersionSuffix()); - } - printer->Print( - "private static final long serialVersionUID = 0L;\n"); - - printer->Indent(); - // Using builder_type, instead of Builder, prevents the Builder class from - // being loaded into PermGen space when the default instance is created. - // This optimizes the PermGen space usage for clients that do not modify - // messages. - printer->Print( - "// Use $classname$.newBuilder() to construct.\n" - "private $classname$($buildertype$ builder) {\n" - " super(builder);\n" - "}\n", - "classname", descriptor_->name(), - "buildertype", builder_type); - printer->Print( - "private $classname$() {\n", - "classname", descriptor_->name()); - printer->Indent(); - GenerateInitializers(printer); - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - - - printer->Print( - "@java.lang.Override\n" - "public final com.google.protobuf.UnknownFieldSet\n" - "getUnknownFields() {\n" - " return this.unknownFields;\n" - "}\n"); - - if (context_->HasGeneratedMethods(descriptor_)) { - if (!EnableExperimentalRuntime(context_) || - IsDescriptorProto(descriptor_)) { - GenerateParsingConstructor(printer); - } - } - - GenerateDescriptorMethods(printer); - - // Nested types - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - EnumGenerator(descriptor_->enum_type(i), true, context_) - .Generate(printer); - } - - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // Don't generate Java classes for map entry messages. - if (IsMapEntry(descriptor_->nested_type(i))) continue; - ImmutableMessageGenerator messageGenerator( - descriptor_->nested_type(i), context_); - messageGenerator.GenerateInterface(printer); - messageGenerator.Generate(printer); - } - - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForMessage(); - } - int totalInts = (totalBits + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - - // oneof - std::map vars; - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - vars["oneof_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name; - vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name; - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); - // oneofCase_ and oneof_ - printer->Print(vars, - "private int $oneof_name$Case_ = 0;\n" - "private java.lang.Object $oneof_name$_;\n"); - // OneofCase enum - printer->Print(vars, - "public enum $oneof_capitalized_name$Case\n" - " implements com.google.protobuf.Internal.EnumLite {\n"); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "$deprecation$$field_name$($field_number$),\n", - "deprecation", - field->options().deprecated() ? "@java.lang.Deprecated " : "", - "field_name", ToUpper(field->name()), - "field_number", SimpleItoa(field->number())); - } - printer->Print( - "$cap_oneof_name$_NOT_SET(0);\n", - "cap_oneof_name", - ToUpper(vars["oneof_name"])); - printer->Print(vars, - "private final int value;\n" - "private $oneof_capitalized_name$Case(int value) {\n" - " this.value = value;\n" - "}\n"); - printer->Print(vars, - "/**\n" - " * @deprecated Use {@link #forNumber(int)} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public static $oneof_capitalized_name$Case valueOf(int value) {\n" - " return forNumber(value);\n" - "}\n" - "\n" - "public static $oneof_capitalized_name$Case forNumber(int value) {\n" - " switch (value) {\n"); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - " case $field_number$: return $field_name$;\n", - "field_number", - SimpleItoa(field->number()), - "field_name", - ToUpper(field->name())); - } - printer->Print( - " case 0: return $cap_oneof_name$_NOT_SET;\n" - " default: return null;\n" - " }\n" - "}\n" - "public int getNumber() {\n" - " return this.value;\n" - "}\n", - "cap_oneof_name", ToUpper(vars["oneof_name"])); - printer->Outdent(); - printer->Print("};\n\n"); - // oneofCase() - printer->Print(vars, - "public $oneof_capitalized_name$Case\n" - "get$oneof_capitalized_name$Case() {\n" - " return $oneof_capitalized_name$Case.forNumber(\n" - " $oneof_name$Case_);\n" - "}\n" - "\n"); - } - - if (IsAnyMessage(descriptor_)) { - GenerateAnyMethods(printer); - } - - // Fields - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("public static final int $constant_name$ = $number$;\n", - "constant_name", FieldConstantName(descriptor_->field(i)), - "number", SimpleItoa(descriptor_->field(i)->number())); - field_generators_.get(descriptor_->field(i)).GenerateMembers(printer); - printer->Print("\n"); - } - - if (context_->HasGeneratedMethods(descriptor_)) { - GenerateIsInitialized(printer); - GenerateMessageSerializationMethods(printer); - GenerateEqualsAndHashCode(printer); - } - - - GenerateParseFromMethods(printer); - GenerateBuilder(printer); - - printer->Print( - "\n" - "// @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - - - // Carefully initialize the default instance in such a way that it doesn't - // conflict with other initialization. - printer->Print( - "private static final $classname$ DEFAULT_INSTANCE;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - printer->Print( - "static {\n" - " DEFAULT_INSTANCE = new $classname$();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print( - "public static $classname$ getDefaultInstance() {\n" - " return DEFAULT_INSTANCE;\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - // 'of' method for Wrappers - if (IsWrappersProtoFile(descriptor_->file())) { - printer->Print( - "public static $classname$ of($field_type$ value) {\n" - " return newBuilder().setValue(value).build();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "field_type", PrimitiveTypeName(GetJavaType(descriptor_->field(0)))); - } - - GenerateParser(printer); - - printer->Print( - "@java.lang.Override\n" - "public $classname$ getDefaultInstanceForType() {\n" - " return DEFAULT_INSTANCE;\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - // Extensions must be declared after the DEFAULT_INSTANCE is initialized - // because the DEFAULT_INSTANCE is used by the extension to lazily retrieve - // the outer class's FileDescriptor. - for (int i = 0; i < descriptor_->extension_count(); i++) { - ImmutableExtensionGenerator(descriptor_->extension(i), context_) - .Generate(printer); - } - - printer->Outdent(); - printer->Print("}\n\n"); -} - - -// =================================================================== - -void ImmutableMessageGenerator:: -GenerateMessageSerializationMethods(io::Printer* printer) { - std::unique_ptr sorted_fields( - SortFieldsByNumber(descriptor_)); - - std::vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); - } - std::sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); - printer->Print( - "@java.lang.Override\n" - "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" - " throws java.io.IOException {\n"); - printer->Indent(); - - if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) { - printer->Print("writeToInternal(output);\n"); - } else { - if (HasPackedFields(descriptor_)) { - // writeTo(CodedOutputStream output) might be invoked without - // getSerializedSize() ever being called, but we need the memoized - // sizes in case this message has packed fields. Rather than emit checks - // for each packed field, just call getSerializedSize() up front. In most - // cases, getSerializedSize() will have already been called anyway by one - // of the wrapper writeTo() methods, making this call cheap. - printer->Print("getSerializedSize();\n"); - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "com.google.protobuf.GeneratedMessage$ver$\n" - " .ExtendableMessage<$classname$>.ExtensionWriter\n" - " extensionWriter = newMessageSetExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "ver", GeneratedCodeVersionSuffix()); - } else { - printer->Print( - "com.google.protobuf.GeneratedMessage$ver$\n" - " .ExtendableMessage<$classname$>.ExtensionWriter\n" - " extensionWriter = newExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "ver", GeneratedCodeVersionSuffix()); - } - } - - // Merge the fields and the extension ranges, both sorted by field number. - for (int i = 0, j = 0; - i < descriptor_->field_count() || j < sorted_extensions.size();) { - if (i == descriptor_->field_count()) { - GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); - } else if (j == sorted_extensions.size()) { - GenerateSerializeOneField(printer, sorted_fields[i++]); - } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { - GenerateSerializeOneField(printer, sorted_fields[i++]); - } else { - GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); - } - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print("unknownFields.writeAsMessageSetTo(output);\n"); - } else { - printer->Print("unknownFields.writeTo(output);\n"); - } - } - - printer->Outdent(); - printer->Print( - "}\n" - "\n" - "@java.lang.Override\n" - "public int getSerializedSize() {\n" - " int size = memoizedSize;\n" - " if (size != -1) return size;\n" - "\n"); - printer->Indent(); - if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) { - printer->Print( - "memoizedSize = getSerializedSizeInternal();\n" - "return memoizedSize;\n"); - } else { - - printer->Print("size = 0;\n"); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(sorted_fields[i]) - .GenerateSerializedSizeCode(printer); - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print("size += extensionsSerializedSizeAsMessageSet();\n"); - } else { - printer->Print("size += extensionsSerializedSize();\n"); - } - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "size += unknownFields.getSerializedSizeAsMessageSet();\n"); - } else { - printer->Print("size += unknownFields.getSerializedSize();\n"); - } - - printer->Print( - "memoizedSize = size;\n" - "return size;\n"); - } - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); -} - -void ImmutableMessageGenerator:: -GenerateParseFromMethods(io::Printer* printer) { - // Note: These are separate from GenerateMessageSerializationMethods() - // because they need to be generated even for messages that are optimized - // for code size. - printer->Print( - "public static $classname$ parseFrom(\n" - " java.nio.ByteBuffer data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " java.nio.ByteBuffer data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.ByteString data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.ByteString data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(byte[] data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " byte[] data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return PARSER.parseFrom(data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(java.io.InputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseWithIOException(PARSER, input);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " java.io.InputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseWithIOException(PARSER, input, extensionRegistry);\n" - "}\n" - "public static $classname$ parseDelimitedFrom(java.io.InputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseDelimitedWithIOException(PARSER, input);\n" - "}\n" - "public static $classname$ parseDelimitedFrom(\n" - " java.io.InputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseDelimitedWithIOException(PARSER, input, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.CodedInputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseWithIOException(PARSER, input);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage$ver$\n" - " .parseWithIOException(PARSER, input, extensionRegistry);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "ver", GeneratedCodeVersionSuffix()); -} - -void ImmutableMessageGenerator::GenerateSerializeOneField( - io::Printer* printer, const FieldDescriptor* field) { - field_generators_.get(field).GenerateSerializationCode(printer); -} - -void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* range) { - printer->Print( - "extensionWriter.writeUntil($end$, output);\n", - "end", SimpleItoa(range->end)); -} - -// =================================================================== - -void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) { - // LITE_RUNTIME implements this at the GeneratedMessageLite level. - printer->Print( - "@java.lang.Override\n" - "public Builder newBuilderForType() { return newBuilder(); }\n"); - - printer->Print( - "public static Builder newBuilder() {\n" - " return DEFAULT_INSTANCE.toBuilder();\n" - "}\n" - "public static Builder newBuilder($classname$ prototype) {\n" - " return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n" - "}\n" - "@java.lang.Override\n" - "public Builder toBuilder() {\n" - " return this == DEFAULT_INSTANCE\n" - " ? new Builder() : new Builder().mergeFrom(this);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print( - "@java.lang.Override\n" - "protected Builder newBuilderForType(\n" - " com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n" - " Builder builder = new Builder(parent);\n" - " return builder;\n" - "}\n", - "ver", GeneratedCodeVersionSuffix()); - - MessageBuilderGenerator builderGenerator(descriptor_, context_); - builderGenerator.Generate(printer); -} - -void ImmutableMessageGenerator:: -GenerateDescriptorMethods(io::Printer* printer) { - if (!descriptor_->options().no_standard_descriptor_accessor()) { - printer->Print( - "public static final com.google.protobuf.Descriptors.Descriptor\n" - " getDescriptor() {\n" - " return $fileclass$.internal_$identifier$_descriptor;\n" - "}\n" - "\n", - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_)); - } - std::vector map_fields; - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (GetJavaType(field) == JAVATYPE_MESSAGE && - IsMapEntry(field->message_type())) { - map_fields.push_back(field); - } - } - if (!map_fields.empty()) { - printer->Print( - "@SuppressWarnings({\"rawtypes\"})\n" - "@java.lang.Override\n" - "protected com.google.protobuf.MapField internalGetMapField(\n" - " int number) {\n" - " switch (number) {\n"); - printer->Indent(); - printer->Indent(); - for (int i = 0; i < map_fields.size(); ++i) { - const FieldDescriptor* field = map_fields[i]; - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - printer->Print( - "case $number$:\n" - " return internalGet$capitalized_name$();\n", - "number", SimpleItoa(field->number()), - "capitalized_name", info->capitalized_name); - } - printer->Print( - "default:\n" - " throw new RuntimeException(\n" - " \"Invalid map field number: \" + number);\n"); - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" - "}\n"); - } - printer->Print( - "@java.lang.Override\n" - "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" - " internalGetFieldAccessorTable() {\n" - " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" - " .ensureFieldAccessorsInitialized(\n" - " $classname$.class, $classname$.Builder.class);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_), - "ver", GeneratedCodeVersionSuffix()); -} - -// =================================================================== - -void ImmutableMessageGenerator::GenerateIsInitialized( - io::Printer* printer) { - // Memoizes whether the protocol buffer is fully initialized (has all - // required fields). -1 means not yet computed. 0 means false and 1 means - // true. - printer->Print( - "private byte memoizedIsInitialized = -1;\n"); - printer->Print( - "@java.lang.Override\n" - "public final boolean isInitialized() {\n"); - printer->Indent(); - - // Don't directly compare to -1 to avoid an Android x86 JIT bug. - printer->Print( - "byte isInitialized = memoizedIsInitialized;\n" - "if (isInitialized == 1) return true;\n" - "if (isInitialized == 0) return false;\n" - "\n"); - - // Check that all required fields in this message are set. - // TODO(kenton): We can optimize this when we switch to putting all the - // "has" fields into a single bitfield. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - - if (field->is_required()) { - printer->Print( - "if (!has$name$()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - "}\n", - "name", info->capitalized_name); - } - } - - // Now check that all embedded messages are initialized. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - if (GetJavaType(field) == JAVATYPE_MESSAGE && - HasRequiredFields(field->message_type())) { - switch (field->label()) { - case FieldDescriptor::LABEL_REQUIRED: - printer->Print( - "if (!get$name$().isInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); - break; - case FieldDescriptor::LABEL_OPTIONAL: - if (!SupportFieldPresence(descriptor_->file()) && - field->containing_oneof() != NULL) { - const OneofDescriptor* oneof = field->containing_oneof(); - const OneofGeneratorInfo* oneof_info = - context_->GetOneofGeneratorInfo(oneof); - printer->Print( - "if ($oneof_name$Case_ == $field_number$) {\n", - "oneof_name", oneof_info->name, - "field_number", SimpleItoa(field->number())); - } else { - printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); - } - printer->Print( - " if (!get$name$().isInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - " }\n" - "}\n", - "name", info->capitalized_name); - break; - case FieldDescriptor::LABEL_REPEATED: - if (IsMapEntry(field->message_type())) { - printer->Print( - "for ($type$ item : get$name$Map().values()) {\n" - " if (!item.isInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - " }\n" - "}\n", - "type", MapValueImmutableClassdName(field->message_type(), - name_resolver_), - "name", info->capitalized_name); - } else { - printer->Print( - "for (int i = 0; i < get$name$Count(); i++) {\n" - " if (!get$name$(i).isInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - " }\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); - } - break; - } - } - } - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if (!extensionsAreInitialized()) {\n" - " memoizedIsInitialized = 0;\n" - " return false;\n" - "}\n"); - } - - printer->Outdent(); - - printer->Print( - " memoizedIsInitialized = 1;\n"); - - printer->Print( - " return true;\n" - "}\n" - "\n"); -} - -// =================================================================== - -namespace { -bool CheckHasBitsForEqualsAndHashCode(const FieldDescriptor* field) { - if (field->is_repeated()) { - return false; - } - if (SupportFieldPresence(field->file())) { - return true; - } - return GetJavaType(field) == JAVATYPE_MESSAGE && - field->containing_oneof() == NULL; -} -} // namespace - -void ImmutableMessageGenerator:: -GenerateEqualsAndHashCode(io::Printer* printer) { - printer->Print( - "@java.lang.Override\n" - "public boolean equals(final java.lang.Object obj) {\n"); - printer->Indent(); - printer->Print( - "if (obj == this) {\n" - " return true;\n" - "}\n" - "if (!(obj instanceof $classname$)) {\n" - " return super.equals(obj);\n" - "}\n" - "$classname$ other = ($classname$) obj;\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print("boolean result = true;\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->containing_oneof() == NULL) { - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field); - if (check_has_bits) { - printer->Print( - "result = result && (has$name$() == other.has$name$());\n" - "if (has$name$()) {\n", - "name", info->capitalized_name); - printer->Indent(); - } - field_generators_.get(field).GenerateEqualsCode(printer); - if (check_has_bits) { - printer->Outdent(); - printer->Print( - "}\n"); - } - } - } - - // Compare oneofs. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "result = result && get$oneof_capitalized_name$Case().equals(\n" - " other.get$oneof_capitalized_name$Case());\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name); - printer->Print( - "if (!result) return false;\n" - "switch ($oneof_name$Case_) {\n", - "oneof_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case $field_number$:\n", - "field_number", - SimpleItoa(field->number())); - printer->Indent(); - field_generators_.get(field).GenerateEqualsCode(printer); - printer->Print("break;\n"); - printer->Outdent(); - } - printer->Print( - "case 0:\n" - "default:\n"); - printer->Outdent(); - printer->Print("}\n"); - } - - // Always consider unknown fields for equality. This will sometimes return - // false for non-canonical ordering when running in LITE_RUNTIME but it's - // the best we can do. - printer->Print( - "result = result && unknownFields.equals(other.unknownFields);\n"); - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "result = result &&\n" - " getExtensionFields().equals(other.getExtensionFields());\n"); - } - printer->Print( - "return result;\n"); - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - - printer->Print( - "@java.lang.Override\n" - "public int hashCode() {\n"); - printer->Indent(); - printer->Print( - "if (memoizedHashCode != 0) {\n"); - printer->Indent(); - printer->Print( - "return memoizedHashCode;\n"); - printer->Outdent(); - printer->Print( - "}\n" - "int hash = 41;\n"); - - // If we output a getDescriptor() method, use that as it is more efficient. - if (descriptor_->options().no_standard_descriptor_accessor()) { - printer->Print("hash = (19 * hash) + getDescriptorForType().hashCode();\n"); - } else { - printer->Print("hash = (19 * hash) + getDescriptor().hashCode();\n"); - } - - // hashCode non-oneofs. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->containing_oneof() == NULL) { - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field); - if (check_has_bits) { - printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); - printer->Indent(); - } - field_generators_.get(field).GenerateHashCode(printer); - if (check_has_bits) { - printer->Outdent(); - printer->Print("}\n"); - } - } - } - - // hashCode oneofs. - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "switch ($oneof_name$Case_) {\n", - "oneof_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case $field_number$:\n", - "field_number", - SimpleItoa(field->number())); - printer->Indent(); - field_generators_.get(field).GenerateHashCode(printer); - printer->Print("break;\n"); - printer->Outdent(); - } - printer->Print( - "case 0:\n" - "default:\n"); - printer->Outdent(); - printer->Print("}\n"); - } - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "hash = hashFields(hash, getExtensionFields());\n"); - } - - printer->Print( - "hash = (29 * hash) + unknownFields.hashCode();\n"); - printer->Print( - "memoizedHashCode = hash;\n" - "return hash;\n"); - printer->Outdent(); - printer->Print( - "}\n" - "\n"); -} - -// =================================================================== - -void ImmutableMessageGenerator:: -GenerateExtensionRegistrationCode(io::Printer* printer) { - for (int i = 0; i < descriptor_->extension_count(); i++) { - ImmutableExtensionGenerator(descriptor_->extension(i), context_) - .GenerateRegistrationCode(printer); - } - - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - ImmutableMessageGenerator(descriptor_->nested_type(i), context_) - .GenerateExtensionRegistrationCode(printer); - } -} - -// =================================================================== -void ImmutableMessageGenerator:: -GenerateParsingConstructor(io::Printer* printer) { - std::unique_ptr sorted_fields( - SortFieldsByNumber(descriptor_)); - - printer->Print( - "private $classname$(\n" - " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n", - "classname", descriptor_->name()); - printer->Indent(); - - // Initialize all fields to default. - printer->Print( - "this();\n" - "if (extensionRegistry == null) {\n" - " throw new java.lang.NullPointerException();\n" - "}\n"); - - // Use builder bits to track mutable repeated fields. - int totalBuilderBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - const ImmutableFieldGenerator& field = - field_generators_.get(descriptor_->field(i)); - totalBuilderBits += field.GetNumBitsForBuilder(); - } - int totalBuilderInts = (totalBuilderBits + 31) / 32; - for (int i = 0; i < totalBuilderInts; i++) { - printer->Print("int mutable_$bit_field_name$ = 0;\n", - "bit_field_name", GetBitFieldName(i)); - } - - printer->Print( - "com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n" - " com.google.protobuf.UnknownFieldSet.newBuilder();\n"); - - printer->Print( - "try {\n"); - printer->Indent(); - - printer->Print( - "boolean done = false;\n" - "while (!done) {\n"); - printer->Indent(); - - printer->Print( - "int tag = input.readTag();\n" - "switch (tag) {\n"); - printer->Indent(); - - printer->Print( - "case 0:\n" // zero signals EOF / limit reached - " done = true;\n" - " break;\n"); - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = sorted_fields[i]; - uint32 tag = WireFormatLite::MakeTag(field->number(), - WireFormat::WireTypeForFieldType(field->type())); - - printer->Print( - "case $tag$: {\n", - "tag", SimpleItoa(static_cast(tag))); - printer->Indent(); - - field_generators_.get(field).GenerateParsingCode(printer); - - printer->Outdent(); - printer->Print( - " break;\n" - "}\n"); - - if (field->is_packable()) { - // To make packed = true wire compatible, we generate parsing code from a - // packed version of this field regardless of field->options().packed(). - uint32 packed_tag = WireFormatLite::MakeTag(field->number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - printer->Print( - "case $tag$: {\n", - "tag", SimpleItoa(static_cast(packed_tag))); - printer->Indent(); - - field_generators_.get(field).GenerateParsingCodeFromPacked(printer); - - printer->Outdent(); - printer->Print( - " break;\n" - "}\n"); - } - } - - printer->Print( - "default: {\n" - " if (!parseUnknownField$suffix$(\n" - " input, unknownFields, extensionRegistry, tag)) {\n" - " done = true;\n" // it's an endgroup tag - " }\n" - " break;\n" - "}\n", - "suffix", - descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? "Proto3" - : ""); - - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" // switch (tag) - "}\n"); // while (!done) - - printer->Outdent(); - printer->Print( - "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" - " throw e.setUnfinishedMessage(this);\n" - "} catch (java.io.IOException e) {\n" - " throw new com.google.protobuf.InvalidProtocolBufferException(\n" - " e).setUnfinishedMessage(this);\n" - "} finally {\n"); - printer->Indent(); - - // Make repeated field list immutable. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = sorted_fields[i]; - field_generators_.get(field).GenerateParsingDoneCode(printer); - } - - // Make unknown fields immutable. - printer->Print("this.unknownFields = unknownFields.build();\n"); - - // Make extensions immutable. - printer->Print( - "makeExtensionsImmutable();\n"); - - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" // finally - "}\n"); -} - -// =================================================================== -void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) { - printer->Print( - "$visibility$ static final com.google.protobuf.Parser<$classname$>\n" - " PARSER = new com.google.protobuf.AbstractParser<$classname$>() {\n", - "visibility", - ExposePublicParser(descriptor_->file()) ? "@java.lang.Deprecated public" - : "private", - "classname", descriptor_->name()); - printer->Indent(); - printer->Print( - "@java.lang.Override\n" - "public $classname$ parsePartialFrom(\n" - " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n", - "classname", descriptor_->name()); - if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) { - printer->Indent(); - printer->Print( - "$classname$ msg = new $classname$();\n" - "msg.mergeFromInternal(input, extensionRegistry);\n" - "msg.makeImmutableInternal();\n" - "return msg;\n", - "classname", descriptor_->name()); - printer->Outdent(); - } else if (context_->HasGeneratedMethods(descriptor_)) { - printer->Print(" return new $classname$(input, extensionRegistry);\n", - "classname", descriptor_->name()); - } else { - // When parsing constructor isn't generated, use builder to parse - // messages. Note, will fallback to use reflection based mergeFieldFrom() - // in AbstractMessage.Builder. - printer->Indent(); - printer->Print( - "Builder builder = newBuilder();\n" - "try {\n" - " builder.mergeFrom(input, extensionRegistry);\n" - "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" - " throw e.setUnfinishedMessage(builder.buildPartial());\n" - "} catch (java.io.IOException e) {\n" - " throw new com.google.protobuf.InvalidProtocolBufferException(\n" - " e.getMessage()).setUnfinishedMessage(\n" - " builder.buildPartial());\n" - "}\n" - "return builder.buildPartial();\n"); - printer->Outdent(); - } - printer->Print( - "}\n"); - printer->Outdent(); - printer->Print( - "};\n" - "\n"); - - printer->Print( - "public static com.google.protobuf.Parser<$classname$> parser() {\n" - " return PARSER;\n" - "}\n" - "\n" - "@java.lang.Override\n" - "public com.google.protobuf.Parser<$classname$> getParserForType() {\n" - " return PARSER;\n" - "}\n" - "\n", - "classname", descriptor_->name()); -} - -// =================================================================== -void ImmutableMessageGenerator::GenerateInitializers(io::Printer* printer) { - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - field_generators_.get(descriptor_->field(i)) - .GenerateInitializationCode(printer); - } - } -} - - -void ImmutableMessageGenerator::GenerateAnyMethods(io::Printer* printer) { - printer->Print( - "private static String getTypeUrl(\n" - " java.lang.String typeUrlPrefix,\n" - " com.google.protobuf.Descriptors.Descriptor descriptor) {\n" - " return typeUrlPrefix.endsWith(\"/\")\n" - " ? typeUrlPrefix + descriptor.getFullName()\n" - " : typeUrlPrefix + \"/\" + descriptor.getFullName();\n" - "}\n" - "\n" - "private static String getTypeNameFromTypeUrl(\n" - " java.lang.String typeUrl) {\n" - " int pos = typeUrl.lastIndexOf('/');\n" - " return pos == -1 ? \"\" : typeUrl.substring(pos + 1);\n" - "}\n" - "\n" - "public static Any pack(\n" - " T message) {\n" - " return Any.newBuilder()\n" - " .setTypeUrl(getTypeUrl(\"type.googleapis.com\",\n" - " message.getDescriptorForType()))\n" - " .setValue(message.toByteString())\n" - " .build();\n" - "}\n" - "\n" - "/**\n" - " * Packs a message using the given type URL prefix. The type URL will\n" - " * be constructed by concatenating the message type's full name to the\n" - " * prefix with an optional \"/\" separator if the prefix doesn't end\n" - " * with \"/\" already.\n" - " */\n" - "public static Any pack(\n" - " T message, java.lang.String typeUrlPrefix) {\n" - " return Any.newBuilder()\n" - " .setTypeUrl(getTypeUrl(typeUrlPrefix,\n" - " message.getDescriptorForType()))\n" - " .setValue(message.toByteString())\n" - " .build();\n" - "}\n" - "\n" - "public boolean is(\n" - " java.lang.Class clazz) {\n" - " T defaultInstance =\n" - " com.google.protobuf.Internal.getDefaultInstance(clazz);\n" - " return getTypeNameFromTypeUrl(getTypeUrl()).equals(\n" - " defaultInstance.getDescriptorForType().getFullName());\n" - "}\n" - "\n" - "private volatile com.google.protobuf.Message cachedUnpackValue;\n" - "\n" - "@java.lang.SuppressWarnings(\"unchecked\")\n" - "public T unpack(\n" - " java.lang.Class clazz)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " if (!is(clazz)) {\n" - " throw new com.google.protobuf.InvalidProtocolBufferException(\n" - " \"Type of the Any message does not match the given class.\");\n" - " }\n" - " if (cachedUnpackValue != null) {\n" - " return (T) cachedUnpackValue;\n" - " }\n" - " T defaultInstance =\n" - " com.google.protobuf.Internal.getDefaultInstance(clazz);\n" - " T result = (T) defaultInstance.getParserForType()\n" - " .parseFrom(getValue());\n" - " cachedUnpackValue = result;\n" - " return result;\n" - "}\n"); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_message.h b/windows/include/google/protobuf/compiler/java/java_message.h deleted file mode 100644 index da1447c17..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message.h +++ /dev/null @@ -1,142 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -static const int kMaxStaticSize = 1 << 15; // aka 32k - -class MessageGenerator { - public: - explicit MessageGenerator(const Descriptor* descriptor); - virtual ~MessageGenerator(); - - // All static variables have to be declared at the top-level of the file - // so that we can control initialization order, which is important for - // DescriptorProto bootstrapping to work. - virtual void GenerateStaticVariables( - io::Printer* printer, int* bytecode_estimate) = 0; - - // Output code which initializes the static variables generated by - // GenerateStaticVariables(). Returns an estimate of bytecode size. - virtual int GenerateStaticVariableInitializers(io::Printer* printer) = 0; - - // Generate the class itself. - virtual void Generate(io::Printer* printer) = 0; - - // Generates the base interface that both the class and its builder implement - virtual void GenerateInterface(io::Printer* printer) = 0; - - // Generate code to register all contained extensions with an - // ExtensionRegistry. - virtual void GenerateExtensionRegistrationCode(io::Printer* printer) = 0; - - protected: - const Descriptor* descriptor_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); -}; - -class ImmutableMessageGenerator : public MessageGenerator { - public: - ImmutableMessageGenerator(const Descriptor* descriptor, Context* context); - virtual ~ImmutableMessageGenerator(); - - virtual void Generate(io::Printer* printer); - virtual void GenerateInterface(io::Printer* printer); - virtual void GenerateExtensionRegistrationCode(io::Printer* printer); - virtual void GenerateStaticVariables( - io::Printer* printer, int* bytecode_estimate); - - // Returns an estimate of the number of bytes the printed code will compile to - virtual int GenerateStaticVariableInitializers(io::Printer* printer); - - private: - - void GenerateFieldAccessorTable(io::Printer* printer, int* bytecode_estimate); - - // Returns an estimate of the number of bytes the printed code will compile to - int GenerateFieldAccessorTableInitializer(io::Printer* printer); - - void GenerateMessageSerializationMethods(io::Printer* printer); - void GenerateParseFromMethods(io::Printer* printer); - void GenerateSerializeOneField(io::Printer* printer, - const FieldDescriptor* field); - void GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* range); - - void GenerateBuilder(io::Printer* printer); - void GenerateIsInitialized(io::Printer* printer); - void GenerateDescriptorMethods(io::Printer* printer); - void GenerateInitializers(io::Printer* printer); - void GenerateEqualsAndHashCode(io::Printer* printer); - void GenerateParser(io::Printer* printer); - void GenerateParsingConstructor(io::Printer* printer); - void GenerateAnyMethods(io::Printer* printer); - - Context* context_; - ClassNameResolver* name_resolver_; - FieldGeneratorMap field_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_message_builder.cc b/windows/include/google/protobuf/compiler/java/java_message_builder.cc deleted file mode 100644 index 4c67e8066..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_builder.cc +++ /dev/null @@ -1,752 +0,0 @@ -// 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. - -// Author: dweis@google.com (Daniel Weis) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { -bool GenerateHasBits(const Descriptor* descriptor) { - return SupportFieldPresence(descriptor->file()) || - HasRepeatedFields(descriptor); -} - -string MapValueImmutableClassdName(const Descriptor* descriptor, - ClassNameResolver* name_resolver) { - const FieldDescriptor* value_field = descriptor->FindFieldByName("value"); - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type()); - return name_resolver->GetImmutableClassName(value_field->message_type()); -} -} // namespace - -MessageBuilderGenerator::MessageBuilderGenerator( - const Descriptor* descriptor, Context* context) - : descriptor_(descriptor), context_(context), - name_resolver_(context->GetNameResolver()), - field_generators_(descriptor, context_) { - GOOGLE_CHECK(HasDescriptorMethods(descriptor->file(), context->EnforceLite())) - << "Generator factory error: A non-lite message generator is used to " - "generate lite messages."; -} - -MessageBuilderGenerator::~MessageBuilderGenerator() {} - -void MessageBuilderGenerator:: -Generate(io::Printer* printer) { - WriteMessageDocComment(printer, descriptor_); - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "public static final class Builder extends\n" - " com.google.protobuf.GeneratedMessage$ver$.ExtendableBuilder<\n" - " $classname$, Builder> implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "extra_interfaces", ExtraBuilderInterfaces(descriptor_), - "ver", GeneratedCodeVersionSuffix()); - } else { - printer->Print( - "public static final class Builder extends\n" - " com.google.protobuf.GeneratedMessage$ver$.Builder implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "extra_interfaces", ExtraBuilderInterfaces(descriptor_), - "ver", GeneratedCodeVersionSuffix()); - } - printer->Indent(); - - GenerateDescriptorMethods(printer); - GenerateCommonBuilderMethods(printer); - - if (context_->HasGeneratedMethods(descriptor_)) { - GenerateIsInitialized(printer); - GenerateBuilderParsingMethods(printer); - } - - // oneof - std::map vars; - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - vars["oneof_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name; - vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name; - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); - // oneofCase_ and oneof_ - printer->Print(vars, - "private int $oneof_name$Case_ = 0;\n" - "private java.lang.Object $oneof_name$_;\n"); - // oneofCase() and clearOneof() - printer->Print(vars, - "public $oneof_capitalized_name$Case\n" - " get$oneof_capitalized_name$Case() {\n" - " return $oneof_capitalized_name$Case.forNumber(\n" - " $oneof_name$Case_);\n" - "}\n" - "\n" - "public Builder clear$oneof_capitalized_name$() {\n" - " $oneof_name$Case_ = 0;\n" - " $oneof_name$_ = null;\n"); - printer->Print(" onChanged();\n"); - printer->Print( - " return this;\n" - "}\n" - "\n"); - } - - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForBuilder(); - } - int totalInts = (totalBits + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("\n"); - field_generators_.get(descriptor_->field(i)) - .GenerateBuilderMembers(printer); - } - - bool is_proto3 = - descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3; - // Override methods declared in GeneratedMessage to return the concrete - // generated type so callsites won't depend on GeneratedMessage. This - // is needed to keep binary compatibility when we change generated code - // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release - // we changed all generated code to subclass GeneratedMessageV3). - printer->Print( - "@java.lang.Override\n" - "public final Builder setUnknownFields(\n" - " final com.google.protobuf.UnknownFieldSet unknownFields) {\n" - " return super.setUnknownFields$suffix$(unknownFields);\n" - "}\n" - "\n" - "@java.lang.Override\n" - "public final Builder mergeUnknownFields(\n" - " final com.google.protobuf.UnknownFieldSet unknownFields) {\n" - " return super.mergeUnknownFields(unknownFields);\n" - "}\n" - "\n", - "suffix", is_proto3 ? "Proto3" : ""); - - printer->Print( - "\n" - "// @@protoc_insertion_point(builder_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - - printer->Outdent(); - printer->Print("}\n"); -} - -// =================================================================== - -void MessageBuilderGenerator:: -GenerateDescriptorMethods(io::Printer* printer) { - if (!descriptor_->options().no_standard_descriptor_accessor()) { - printer->Print( - "public static final com.google.protobuf.Descriptors.Descriptor\n" - " getDescriptor() {\n" - " return $fileclass$.internal_$identifier$_descriptor;\n" - "}\n" - "\n", - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_)); - } - std::vector map_fields; - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (GetJavaType(field) == JAVATYPE_MESSAGE && - IsMapEntry(field->message_type())) { - map_fields.push_back(field); - } - } - if (!map_fields.empty()) { - printer->Print( - "@SuppressWarnings({\"rawtypes\"})\n" - "protected com.google.protobuf.MapField internalGetMapField(\n" - " int number) {\n" - " switch (number) {\n"); - printer->Indent(); - printer->Indent(); - for (int i = 0; i < map_fields.size(); ++i) { - const FieldDescriptor* field = map_fields[i]; - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - printer->Print( - "case $number$:\n" - " return internalGet$capitalized_name$();\n", - "number", SimpleItoa(field->number()), - "capitalized_name", info->capitalized_name); - } - printer->Print( - "default:\n" - " throw new RuntimeException(\n" - " \"Invalid map field number: \" + number);\n"); - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" - "}\n"); - printer->Print( - "@SuppressWarnings({\"rawtypes\"})\n" - "protected com.google.protobuf.MapField internalGetMutableMapField(\n" - " int number) {\n" - " switch (number) {\n"); - printer->Indent(); - printer->Indent(); - for (int i = 0; i < map_fields.size(); ++i) { - const FieldDescriptor* field = map_fields[i]; - const FieldGeneratorInfo* info = - context_->GetFieldGeneratorInfo(field); - printer->Print( - "case $number$:\n" - " return internalGetMutable$capitalized_name$();\n", - "number", SimpleItoa(field->number()), - "capitalized_name", info->capitalized_name); - } - printer->Print( - "default:\n" - " throw new RuntimeException(\n" - " \"Invalid map field number: \" + number);\n"); - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" - "}\n"); - } - printer->Print( - "@java.lang.Override\n" - "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" - " internalGetFieldAccessorTable() {\n" - " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" - " .ensureFieldAccessorsInitialized(\n" - " $classname$.class, $classname$.Builder.class);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_), - "ver", GeneratedCodeVersionSuffix()); -} - -// =================================================================== - -void MessageBuilderGenerator:: -GenerateCommonBuilderMethods(io::Printer* printer) { - printer->Print( - "// Construct using $classname$.newBuilder()\n" - "private Builder() {\n" - " maybeForceBuilderInitialization();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print( - "private Builder(\n" - " com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n" - " super(parent);\n" - " maybeForceBuilderInitialization();\n" - "}\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "ver", GeneratedCodeVersionSuffix()); - - printer->Print( - "private void maybeForceBuilderInitialization() {\n" - " if (com.google.protobuf.GeneratedMessage$ver$\n" - " .alwaysUseFieldBuilders) {\n", - "ver", GeneratedCodeVersionSuffix()); - - printer->Indent(); - printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - field_generators_.get(descriptor_->field(i)) - .GenerateFieldBuilderInitializationCode(printer); - } - } - printer->Outdent(); - printer->Outdent(); - - printer->Print( - " }\n" - "}\n"); - - printer->Print( - "@java.lang.Override\n" - "public Builder clear() {\n" - " super.clear();\n"); - - printer->Indent(); - - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - field_generators_.get(descriptor_->field(i)) - .GenerateBuilderClearCode(printer); - } - } - - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "$oneof_name$Case_ = 0;\n" - "$oneof_name$_ = null;\n", - "oneof_name", context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); - } - - printer->Outdent(); - - printer->Print( - " return this;\n" - "}\n" - "\n"); - - printer->Print( - "@java.lang.Override\n" - "public com.google.protobuf.Descriptors.Descriptor\n" - " getDescriptorForType() {\n" - " return $fileclass$.internal_$identifier$_descriptor;\n" - "}\n" - "\n", - "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_)); - - // LITE runtime implements this in GeneratedMessageLite. - printer->Print( - "@java.lang.Override\n" - "public $classname$ getDefaultInstanceForType() {\n" - " return $classname$.getDefaultInstance();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print( - "@java.lang.Override\n" - "public $classname$ build() {\n" - " $classname$ result = buildPartial();\n" - " if (!result.isInitialized()) {\n" - " throw newUninitializedMessageException(result);\n" - " }\n" - " return result;\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print( - "@java.lang.Override\n" - "public $classname$ buildPartial() {\n" - " $classname$ result = new $classname$(this);\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Indent(); - - int totalBuilderBits = 0; - int totalMessageBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - const ImmutableFieldGenerator& field = - field_generators_.get(descriptor_->field(i)); - totalBuilderBits += field.GetNumBitsForBuilder(); - totalMessageBits += field.GetNumBitsForMessage(); - } - int totalBuilderInts = (totalBuilderBits + 31) / 32; - int totalMessageInts = (totalMessageBits + 31) / 32; - - if (GenerateHasBits(descriptor_)) { - // Local vars for from and to bit fields to avoid accessing the builder and - // message over and over for these fields. Seems to provide a slight - // perforamance improvement in micro benchmark and this is also what proto1 - // code does. - for (int i = 0; i < totalBuilderInts; i++) { - printer->Print("int from_$bit_field_name$ = $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - for (int i = 0; i < totalMessageInts; i++) { - printer->Print("int to_$bit_field_name$ = 0;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - - // Output generation code for each field. - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)).GenerateBuildingCode(printer); - } - - if (GenerateHasBits(descriptor_)) { - // Copy the bit field results to the generated message - for (int i = 0; i < totalMessageInts; i++) { - printer->Print("result.$bit_field_name$ = to_$bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print("result.$oneof_name$Case_ = $oneof_name$Case_;\n", - "oneof_name", context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); - } - - printer->Outdent(); - - printer->Print( - " onBuilt();\n"); - - printer->Print( - " return result;\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - // Override methods declared in GeneratedMessage to return the concrete - // generated type so callsites won't depend on GeneratedMessage. This - // is needed to keep binary compatibility when we change generated code - // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release - // we changed all generated code to subclass GeneratedMessageV3). - printer->Print( - "@java.lang.Override\n" - "public Builder clone() {\n" - " return (Builder) super.clone();\n" - "}\n" - "@java.lang.Override\n" - "public Builder setField(\n" - " com.google.protobuf.Descriptors.FieldDescriptor field,\n" - " java.lang.Object value) {\n" - " return (Builder) super.setField(field, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder clearField(\n" - " com.google.protobuf.Descriptors.FieldDescriptor field) {\n" - " return (Builder) super.clearField(field);\n" - "}\n" - "@java.lang.Override\n" - "public Builder clearOneof(\n" - " com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n" - " return (Builder) super.clearOneof(oneof);\n" - "}\n" - "@java.lang.Override\n" - "public Builder setRepeatedField(\n" - " com.google.protobuf.Descriptors.FieldDescriptor field,\n" - " int index, java.lang.Object value) {\n" - " return (Builder) super.setRepeatedField(field, index, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder addRepeatedField(\n" - " com.google.protobuf.Descriptors.FieldDescriptor field,\n" - " java.lang.Object value) {\n" - " return (Builder) super.addRepeatedField(field, value);\n" - "}\n"); - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "@java.lang.Override\n" - "public Builder setExtension(\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $classname$, Type> extension,\n" - " Type value) {\n" - " return (Builder) super.setExtension(extension, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder setExtension(\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $classname$, java.util.List> extension,\n" - " int index, Type value) {\n" - " return (Builder) super.setExtension(extension, index, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder addExtension(\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $classname$, java.util.List> extension,\n" - " Type value) {\n" - " return (Builder) super.addExtension(extension, value);\n" - "}\n" - "@java.lang.Override\n" - "public Builder clearExtension(\n" - " com.google.protobuf.GeneratedMessage.GeneratedExtension<\n" - " $classname$, ?> extension) {\n" - " return (Builder) super.clearExtension(extension);\n" - "}\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - } - - // ----------------------------------------------------------------- - - if (context_->HasGeneratedMethods(descriptor_)) { - printer->Print( - "@java.lang.Override\n" - "public Builder mergeFrom(com.google.protobuf.Message other) {\n" - " if (other instanceof $classname$) {\n" - " return mergeFrom(($classname$)other);\n" - " } else {\n" - " super.mergeFrom(other);\n" - " return this;\n" - " }\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print( - "public Builder mergeFrom($classname$ other) {\n" - // Optimization: If other is the default instance, we know none of its - // fields are set so we can skip the merge. - " if (other == $classname$.getDefaultInstance()) return this;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - printer->Indent(); - - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - field_generators_.get( - descriptor_->field(i)).GenerateMergingCode(printer); - } - } - - // Merge oneof fields. - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - printer->Print( - "switch (other.get$oneof_capitalized_name$Case()) {\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case $field_name$: {\n", - "field_name", - ToUpper(field->name())); - printer->Indent(); - field_generators_.get(field).GenerateMergingCode(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); - } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " break;\n" - "}\n", - "cap_oneof_name", - ToUpper(context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name)); - printer->Outdent(); - printer->Print( - "}\n"); - } - - printer->Outdent(); - - // if message type has extensions - if (descriptor_->extension_range_count() > 0) { - printer->Print( - " this.mergeExtensionFields(other);\n"); - } - - printer->Print( - " this.mergeUnknownFields(other.unknownFields);\n"); - - printer->Print( - " onChanged();\n"); - - printer->Print( - " return this;\n" - "}\n" - "\n"); - } -} - -// =================================================================== - -void MessageBuilderGenerator:: -GenerateBuilderParsingMethods(io::Printer* printer) { - printer->Print( - "@java.lang.Override\n" - "public Builder mergeFrom(\n" - " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " $classname$ parsedMessage = null;\n" - " try {\n" - " parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n" - " } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" - " parsedMessage = ($classname$) e.getUnfinishedMessage();\n" - " throw e.unwrapIOException();\n" - " } finally {\n" - " if (parsedMessage != null) {\n" - " mergeFrom(parsedMessage);\n" - " }\n" - " }\n" - " return this;\n" - "}\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); -} - -// =================================================================== - -void MessageBuilderGenerator::GenerateIsInitialized( - io::Printer* printer) { - printer->Print( - "@java.lang.Override\n" - "public final boolean isInitialized() {\n"); - printer->Indent(); - - // Check that all required fields in this message are set. - // TODO(kenton): We can optimize this when we switch to putting all the - // "has" fields into a single bitfield. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - - if (field->is_required()) { - printer->Print( - "if (!has$name$()) {\n" - " return false;\n" - "}\n", - "name", info->capitalized_name); - } - } - - // Now check that all embedded messages are initialized. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - if (GetJavaType(field) == JAVATYPE_MESSAGE && - HasRequiredFields(field->message_type())) { - switch (field->label()) { - case FieldDescriptor::LABEL_REQUIRED: - printer->Print( - "if (!get$name$().isInitialized()) {\n" - " return false;\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); - break; - case FieldDescriptor::LABEL_OPTIONAL: - if (!SupportFieldPresence(descriptor_->file()) && - field->containing_oneof() != NULL) { - const OneofDescriptor* oneof = field->containing_oneof(); - const OneofGeneratorInfo* oneof_info = - context_->GetOneofGeneratorInfo(oneof); - printer->Print( - "if ($oneof_name$Case_ == $field_number$) {\n", - "oneof_name", oneof_info->name, - "field_number", SimpleItoa(field->number())); - } else { - printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); - } - printer->Print( - " if (!get$name$().isInitialized()) {\n" - " return false;\n" - " }\n" - "}\n", - "name", info->capitalized_name); - break; - case FieldDescriptor::LABEL_REPEATED: - if (IsMapEntry(field->message_type())) { - printer->Print( - "for ($type$ item : get$name$Map().values()) {\n" - " if (!item.isInitialized()) {\n" - " return false;\n" - " }\n" - "}\n", - "type", MapValueImmutableClassdName(field->message_type(), - name_resolver_), - "name", info->capitalized_name); - } else { - printer->Print( - "for (int i = 0; i < get$name$Count(); i++) {\n" - " if (!get$name$(i).isInitialized()) {\n" - " return false;\n" - " }\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); - } - break; - } - } - } - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if (!extensionsAreInitialized()) {\n" - " return false;\n" - "}\n"); - } - - printer->Outdent(); - - printer->Print( - " return true;\n" - "}\n" - "\n"); -} - -// =================================================================== - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_message_builder.h b/windows/include/google/protobuf/compiler/java/java_message_builder.h deleted file mode 100644 index 015ea0620..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_builder.h +++ /dev/null @@ -1,86 +0,0 @@ -// 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. - -// Author: dweis@google.com (Daniel Weis) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class MessageBuilderGenerator { - public: - explicit MessageBuilderGenerator(const Descriptor* descriptor, - Context* context); - virtual ~MessageBuilderGenerator(); - - virtual void Generate(io::Printer* printer); - - private: - void GenerateCommonBuilderMethods(io::Printer* printer); - void GenerateDescriptorMethods(io::Printer* printer); - void GenerateBuilderParsingMethods(io::Printer* printer); - void GenerateIsInitialized(io::Printer* printer); - - const Descriptor* descriptor_; - Context* context_; - ClassNameResolver* name_resolver_; - FieldGeneratorMap field_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageBuilderGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_message_builder_lite.cc b/windows/include/google/protobuf/compiler/java/java_message_builder_lite.cc deleted file mode 100644 index f04d394e7..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_builder_lite.cc +++ /dev/null @@ -1,170 +0,0 @@ -// 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. - -// Author: dweis@google.com (Daniel Weis) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { -bool GenerateHasBits(const Descriptor* descriptor) { - return SupportFieldPresence(descriptor->file()) || - HasRepeatedFields(descriptor); -} -} // namespace - -MessageBuilderLiteGenerator::MessageBuilderLiteGenerator( - const Descriptor* descriptor, Context* context) - : descriptor_(descriptor), context_(context), - name_resolver_(context->GetNameResolver()), - field_generators_(descriptor, context_) { - GOOGLE_CHECK(!HasDescriptorMethods(descriptor->file(), context->EnforceLite())) - << "Generator factory error: A lite message generator is used to " - "generate non-lite messages."; -} - -MessageBuilderLiteGenerator::~MessageBuilderLiteGenerator() {} - -void MessageBuilderLiteGenerator:: -Generate(io::Printer* printer) { - WriteMessageDocComment(printer, descriptor_); - printer->Print( - "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" : ""); - printer->Indent(); - - GenerateCommonBuilderMethods(printer); - - // oneof - std::map vars; - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - vars["oneof_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name; - vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name; - vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index()); - - // oneofCase() and clearOneof() - printer->Print(vars, - "@java.lang.Override\n" - "public $oneof_capitalized_name$Case\n" - " get$oneof_capitalized_name$Case() {\n" - " return instance.get$oneof_capitalized_name$Case();\n" - "}\n" - "\n" - "public Builder clear$oneof_capitalized_name$() {\n" - " copyOnWrite();\n" - " instance.clear$oneof_capitalized_name$();\n" - " return this;\n" - "}\n" - "\n"); - } - - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForBuilder(); - } - int totalInts = (totalBits + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("\n"); - field_generators_.get(descriptor_->field(i)) - .GenerateBuilderMembers(printer); - } - - printer->Print( - "\n" - "// @@protoc_insertion_point(builder_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - - printer->Outdent(); - printer->Print("}\n"); -} - -// =================================================================== - -void MessageBuilderLiteGenerator:: -GenerateCommonBuilderMethods(io::Printer* printer) { - printer->Print( - "// Construct using $classname$.newBuilder()\n" - "private Builder() {\n" - " super(DEFAULT_INSTANCE);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); -} - -// =================================================================== - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_message_builder_lite.h b/windows/include/google/protobuf/compiler/java/java_message_builder_lite.h deleted file mode 100644 index 8597b2e66..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_builder_lite.h +++ /dev/null @@ -1,83 +0,0 @@ -// 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. - -// Author: dweis@google.com (Daniel Weis) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_LITE_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class MessageBuilderLiteGenerator { - public: - explicit MessageBuilderLiteGenerator(const Descriptor* descriptor, - Context* context); - virtual ~MessageBuilderLiteGenerator(); - - virtual void Generate(io::Printer* printer); - - private: - void GenerateCommonBuilderMethods(io::Printer* printer); - - const Descriptor* descriptor_; - Context* context_; - ClassNameResolver* name_resolver_; - FieldGeneratorMap field_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageBuilderLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_BUILDER_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_message_field.cc b/windows/include/google/protobuf/compiler/java/java_message_field.cc deleted file mode 100644 index baa7f8727..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_field.cc +++ /dev/null @@ -1,1329 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { - -void SetMessageVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - ClassNameResolver* name_resolver, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - - (*variables)["type"] = - name_resolver->GetImmutableClassName(descriptor->message_type()); - (*variables)["mutable_type"] = - name_resolver->GetMutableClassName(descriptor->message_type()); - (*variables)["group_or_message"] = - (GetType(descriptor) == FieldDescriptor::TYPE_GROUP) ? - "Group" : "Message"; - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - (*variables)["on_changed"] = "onChanged();"; - (*variables)["ver"] = GeneratedCodeVersionSuffix(); - (*variables)["get_parser"] = - ExposePublicParser(descriptor->message_type()->file()) - ? "PARSER" : "parser()"; - - if (SupportFieldPresence(descriptor->file())) { - // For singular messages and builders, one bit is used for the hasField bit. - (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); - (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex); - - // Note that these have a trailing ";". - (*variables)["set_has_field_bit_message"] = - GenerateSetBit(messageBitIndex) + ";"; - (*variables)["set_has_field_bit_builder"] = - GenerateSetBit(builderBitIndex) + ";"; - (*variables)["clear_has_field_bit_builder"] = - GenerateClearBit(builderBitIndex) + ";"; - - (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); - } else { - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["set_has_field_bit_builder"] = ""; - (*variables)["clear_has_field_bit_builder"] = ""; - - (*variables)["is_field_present_message"] = - (*variables)["name"] + "_ != null"; - } - - // For repated builders, one bit is used for whether the array is immutable. - (*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex); - (*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex); - (*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex); - - // For repeated fields, one bit is used for whether the array is immutable - // in the parsing constructor. - (*variables)["get_mutable_bit_parser"] = - GenerateGetBitMutableLocal(builderBitIndex); - (*variables)["set_mutable_bit_parser"] = - GenerateSetBitMutableLocal(builderBitIndex); - - (*variables)["get_has_field_bit_from_local"] = - GenerateGetBitFromLocal(builderBitIndex); - (*variables)["set_has_field_bit_to_local"] = - GenerateSetBitToLocal(messageBitIndex); -} - -} // namespace - -// =================================================================== - -ImmutableMessageFieldGenerator:: -ImmutableMessageFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -ImmutableMessageFieldGenerator::~ImmutableMessageFieldGenerator() {} - -int ImmutableMessageFieldGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutableMessageFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -void ImmutableMessageFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - // TODO(jonp): In the future, consider having a method specific to the - // interface so that builders can choose dynamically to either return a - // message or a nested builder, so that asking for the interface doesn't - // cause a message to ever be built. - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$OrBuilder get$capitalized_name$OrBuilder();\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $type$ $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } else { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $name$_ != null;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " return get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } -} - -void ImmutableMessageFieldGenerator::PrintNestedBuilderCondition( - io::Printer* printer, - const char* regular_case, - const char* nested_builder_case) const { - printer->Print(variables_, "if ($name$Builder_ == null) {\n"); - printer->Indent(); - printer->Print(variables_, regular_case); - printer->Outdent(); - printer->Print("} else {\n"); - printer->Indent(); - printer->Print(variables_, nested_builder_case); - printer->Outdent(); - printer->Print("}\n"); -} - -void ImmutableMessageFieldGenerator::PrintNestedBuilderFunction( - io::Printer* printer, - const char* method_prototype, - const char* regular_case, - const char* nested_builder_case, - const char* trailing_code) const { - printer->Print(variables_, method_prototype); - printer->Annotate("{", "}", descriptor_); - printer->Print(" {\n"); - printer->Indent(); - PrintNestedBuilderCondition(printer, regular_case, nested_builder_case); - if (trailing_code != NULL) { - printer->Print(variables_, trailing_code); - } - printer->Outdent(); - printer->Print("}\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // When using nested-builders, the code initially works just like the - // non-nested builder case. It only creates a nested builder lazily on - // demand and then forever delegates to it after creation. - - bool support_field_presence = SupportFieldPresence(descriptor_->file()); - - printer->Print(variables_, - "private $type$ $name$_ = null;\n"); - - printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" - "\n"); - - // The comments above the methods below are based on a hypothetical - // field of type "Field" called "Field". - - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - if (support_field_presence) { - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } else { - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $name$Builder_ != null || $name$_ != null;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - // Field getField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public $type$ ${$get$capitalized_name$$}$()", - "return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n", - "return $name$Builder_.getMessage();\n", - NULL); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "$name$_ = value;\n" - "$on_changed$\n", - - "$name$Builder_.setMessage(value);\n", - - "$set_has_field_bit_builder$\n" - "return this;\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " $type$.Builder builderForValue)", - - "$name$_ = builderForValue.build();\n" - "$on_changed$\n", - - "$name$Builder_.setMessage(builderForValue.build());\n", - - "$set_has_field_bit_builder$\n" - "return this;\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)", - - support_field_presence - ? "if ($get_has_field_bit_builder$ &&\n" - " $name$_ != null &&\n" - " $name$_ != $type$.getDefaultInstance()) {\n" - " $name$_ =\n" - " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" - "} else {\n" - " $name$_ = value;\n" - "}\n" - "$on_changed$\n" - : "if ($name$_ != null) {\n" - " $name$_ =\n" - " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" - "} else {\n" - " $name$_ = value;\n" - "}\n" - "$on_changed$\n", - - "$name$Builder_.mergeFrom(value);\n", - - "$set_has_field_bit_builder$\n" - "return this;\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$clear$capitalized_name$$}$()", - - "$name$_ = null;\n" - "$on_changed$\n", - - support_field_presence - ? "$name$Builder_.clear();\n" - : "$name$_ = null;\n" - "$name$Builder_ = null;\n", - - "$clear_has_field_bit_builder$\n" - "return this;\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder " - "${$get$capitalized_name$Builder$}$() {\n" - " $set_has_field_bit_builder$\n" - " $on_changed$\n" - " return get$capitalized_name$FieldBuilder().getBuilder();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " if ($name$Builder_ != null) {\n" - " return $name$Builder_.getMessageOrBuilder();\n" - " } else {\n" - " return $name$_ == null ?\n" - " $type$.getDefaultInstance() : $name$_;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " get$capitalized_name$FieldBuilder() {\n" - " if ($name$Builder_ == null) {\n" - " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " get$capitalized_name$(),\n" - " getParentForChildren(),\n" - " isClean());\n" - " $name$_ = null;\n" - " }\n" - " return $name$Builder_;\n" - "}\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "get$capitalized_name$FieldBuilder();\n"); - } -} - - -void ImmutableMessageFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const {} - -void ImmutableMessageFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - PrintNestedBuilderCondition(printer, - "$name$_ = null;\n", - - "$name$Builder_.clear();\n"); - printer->Print(variables_, "$clear_has_field_bit_builder$\n"); - } else { - PrintNestedBuilderCondition(printer, - "$name$_ = null;\n", - - "$name$_ = null;\n" - "$name$Builder_ = null;\n"); - } -} - -void ImmutableMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " merge$capitalized_name$(other.get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); - } - - PrintNestedBuilderCondition(printer, - "result.$name$_ = $name$_;\n", - - "result.$name$_ = $name$Builder_.build();\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$type$.Builder subBuilder = null;\n" - "if ($is_field_present_message$) {\n" - " subBuilder = $name$_.toBuilder();\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$name$_ = input.readGroup($number$, $type$.$get_parser$,\n" - " extensionRegistry);\n"); - } else { - printer->Print(variables_, - "$name$_ = input.readMessage($type$.$get_parser$, extensionRegistry);\n"); - } - - printer->Print(variables_, - "if (subBuilder != null) {\n" - " subBuilder.mergeFrom($name$_);\n" - " $name$_ = subBuilder.buildPartial();\n" - "}\n" - "$set_has_field_bit_message$\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for messages. -} - -void ImmutableMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.write$group_or_message$($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); -} - -void ImmutableMessageFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); -} - -string ImmutableMessageFieldGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->message_type()); -} - -// =================================================================== - -ImmutableMessageOneofFieldGenerator:: -ImmutableMessageOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableMessageFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); -} - -ImmutableMessageOneofFieldGenerator:: -~ImmutableMessageOneofFieldGenerator() {} - -void ImmutableMessageOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableMessageOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // When using nested-builders, the code initially works just like the - // non-nested builder case. It only creates a nested builder lazily on - // demand and then forever delegates to it after creation. - printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" - "\n"); - - // The comments above the methods below are based on a hypothetical - // field of type "Field" called "Field". - - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field getField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public $type$ ${$get$capitalized_name$$}$()", - - "if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - "}\n" - "return $type$.getDefaultInstance();\n", - - "if ($has_oneof_case_message$) {\n" - " return $name$Builder_.getMessage();\n" - "}\n" - "return $type$.getDefaultInstance();\n", - - NULL); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "$oneof_name$_ = value;\n" - "$on_changed$\n", - - "$name$Builder_.setMessage(value);\n", - - "$set_oneof_case_message$;\n" - "return this;\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " $type$.Builder builderForValue)", - - "$oneof_name$_ = builderForValue.build();\n" - "$on_changed$\n", - - "$name$Builder_.setMessage(builderForValue.build());\n", - - "$set_oneof_case_message$;\n" - "return this;\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)", - - "if ($has_oneof_case_message$ &&\n" - " $oneof_name$_ != $type$.getDefaultInstance()) {\n" - " $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n" - " .mergeFrom(value).buildPartial();\n" - "} else {\n" - " $oneof_name$_ = value;\n" - "}\n" - "$on_changed$\n", - - "if ($has_oneof_case_message$) {\n" - " $name$Builder_.mergeFrom(value);\n" - "}\n" - "$name$Builder_.setMessage(value);\n", - - "$set_oneof_case_message$;\n" - "return this;\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$clear$capitalized_name$$}$()", - - "if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - "}\n", - - "if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - "}\n" - "$name$Builder_.clear();\n", - - "return this;\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder " - "${$get$capitalized_name$Builder$}$() {\n" - " return get$capitalized_name$FieldBuilder().getBuilder();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$() {\n" - " if (($has_oneof_case_message$) && ($name$Builder_ != null)) {\n" - " return $name$Builder_.getMessageOrBuilder();\n" - " } else {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - " }\n" - " return $type$.getDefaultInstance();\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " ${$get$capitalized_name$FieldBuilder$}$() {\n" - " if ($name$Builder_ == null) {\n" - " if (!($has_oneof_case_message$)) {\n" - " $oneof_name$_ = $type$.getDefaultInstance();\n" - " }\n" - " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " ($type$) $oneof_name$_,\n" - " getParentForChildren(),\n" - " isClean());\n" - " $oneof_name$_ = null;\n" - " }\n" - " $set_oneof_case_message$;\n" - " $on_changed$;\n" - " return $name$Builder_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableMessageOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n"); - printer->Indent(); - - PrintNestedBuilderCondition(printer, - "result.$oneof_name$_ = $oneof_name$_;\n", - - "result.$oneof_name$_ = $name$Builder_.build();\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -void ImmutableMessageOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "merge$capitalized_name$(other.get$capitalized_name$());\n"); -} - -void ImmutableMessageOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$type$.Builder subBuilder = null;\n" - "if ($has_oneof_case_message$) {\n" - " subBuilder = (($type$) $oneof_name$_).toBuilder();\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$oneof_name$_ = input.readGroup($number$, $type$.$get_parser$,\n" - " extensionRegistry);\n"); - } else { - printer->Print(variables_, - "$oneof_name$_ =\n" - " input.readMessage($type$.$get_parser$, extensionRegistry);\n"); - } - - printer->Print(variables_, - "if (subBuilder != null) {\n" - " subBuilder.mergeFrom(($type$) $oneof_name$_);\n" - " $oneof_name$_ = subBuilder.buildPartial();\n" - "}\n"); - printer->Print(variables_, - "$set_oneof_case_message$;\n"); -} - -void ImmutableMessageOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.write$group_or_message$($number$, ($type$) $oneof_name$_);\n" - "}\n"); -} - -void ImmutableMessageOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, ($type$) $oneof_name$_);\n" - "}\n"); -} - -// =================================================================== - -RepeatedImmutableMessageFieldGenerator:: -RepeatedImmutableMessageFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -RepeatedImmutableMessageFieldGenerator:: -~RepeatedImmutableMessageFieldGenerator() {} - -int RepeatedImmutableMessageFieldGenerator::GetNumBitsForMessage() const { - return 0; -} - -int RepeatedImmutableMessageFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - // TODO(jonp): In the future, consider having methods specific to the - // interface so that builders can choose dynamically to either return a - // message or a nested builder, so that asking for the interface doesn't - // cause a message to ever be built. - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List<$type$> \n" - " get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List \n" - " get$capitalized_name$OrBuilderList();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$OrBuilder get$capitalized_name$OrBuilder(\n" - " int index);\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.util.List<$type$> $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List \n" - " ${$get$capitalized_name$OrBuilderList$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$(\n" - " int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - -} - -void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderCondition( - io::Printer* printer, - const char* regular_case, - const char* nested_builder_case) const { - printer->Print(variables_, "if ($name$Builder_ == null) {\n"); - printer->Indent(); - printer->Print(variables_, regular_case); - printer->Outdent(); - printer->Print("} else {\n"); - printer->Indent(); - printer->Print(variables_, nested_builder_case); - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderFunction( - io::Printer* printer, - const char* method_prototype, - const char* regular_case, - const char* nested_builder_case, - const char* trailing_code) const { - printer->Print(variables_, method_prototype); - printer->Annotate("{", "}", descriptor_); - printer->Print(" {\n"); - printer->Indent(); - PrintNestedBuilderCondition(printer, regular_case, nested_builder_case); - if (trailing_code != NULL) { - printer->Print(variables_, trailing_code); - } - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // When using nested-builders, the code initially works just like the - // non-nested builder case. It only creates a nested builder lazily on - // demand and then forever delegates to it after creation. - - printer->Print(variables_, - // Used when the builder is null. - // One field is the list and the other field keeps track of whether the - // list is immutable. If it's immutable, the invariant is that it must - // either an instance of Collections.emptyList() or it's an ArrayList - // wrapped in a Collections.unmodifiableList() wrapper and nobody else has - // a refererence to the underlying ArrayList. This invariant allows us to - // share instances of lists between protocol buffers avoiding expensive - // memory allocations. Note, immutable is a strong guarantee here -- not - // just that the list cannot be modified via the reference but that the - // list can never be modified. - "private java.util.List<$type$> $name$_ =\n" - " java.util.Collections.emptyList();\n" - - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ = new java.util.ArrayList<$type$>($name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n" - "\n"); - - printer->Print(variables_, - // If this builder is non-null, it is used and the other fields are - // ignored. - "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;\n" - "\n"); - - // The comments above the methods below are based on a hypothetical - // repeated field of type "Field" called "RepeatedField". - - // List getRepeatedFieldList() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$()", - - "return java.util.Collections.unmodifiableList($name$_);\n", - "return $name$Builder_.getMessageList();\n", - - NULL); - - // int getRepeatedFieldCount() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public int ${$get$capitalized_name$Count$}$()", - - "return $name$_.size();\n", - "return $name$Builder_.getCount();\n", - - NULL); - - // Field getRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index)", - - "return $name$_.get(index);\n", - - "return $name$Builder_.getMessage(index);\n", - - NULL); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value)", - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.set(index, value);\n" - "$on_changed$\n", - "$name$Builder_.setMessage(index, value);\n", - "return this;\n"); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.set(index, builderForValue.build());\n" - "$on_changed$\n", - - "$name$Builder_.setMessage(index, builderForValue.build());\n", - - "return this;\n"); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(value);\n" - - "$on_changed$\n", - - "$name$Builder_.addMessage(value);\n", - - "return this;\n"); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " int index, $type$ value)", - - "if (value == null) {\n" - " throw new NullPointerException();\n" - "}\n" - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(index, value);\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(index, value);\n", - - "return this;\n"); - - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(builderForValue.build());\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(builderForValue.build());\n", - - "return this;\n"); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " int index, $type$.Builder builderForValue)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.add(index, builderForValue.build());\n" - "$on_changed$\n", - - "$name$Builder_.addMessage(index, builderForValue.build());\n", - - "return this;\n"); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values)", - - "ensure$capitalized_name$IsMutable();\n" - "com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" - " values, $name$_);\n" - "$on_changed$\n", - - "$name$Builder_.addAllMessages(values);\n", - - "return this;\n"); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$clear$capitalized_name$$}$()", - - "$name$_ = java.util.Collections.emptyList();\n" - "$clear_mutable_bit_builder$;\n" - "$on_changed$\n", - - "$name$Builder_.clear();\n", - - "return this;\n"); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - PrintNestedBuilderFunction(printer, - "$deprecation$public Builder ${$remove$capitalized_name$$}$(int index)", - - "ensure$capitalized_name$IsMutable();\n" - "$name$_.remove(index);\n" - "$on_changed$\n", - - "$name$Builder_.remove(index);\n", - - "return this;\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder ${$get$capitalized_name$Builder$}$(\n" - " int index) {\n" - " return get$capitalized_name$FieldBuilder().getBuilder(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$(\n" - " int index) {\n" - " if ($name$Builder_ == null) {\n" - " return $name$_.get(index);" - " } else {\n" - " return $name$Builder_.getMessageOrBuilder(index);\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List \n" - " ${$get$capitalized_name$OrBuilderList$}$() {\n" - " if ($name$Builder_ != null) {\n" - " return $name$Builder_.getMessageOrBuilderList();\n" - " } else {\n" - " return java.util.Collections.unmodifiableList($name$_);\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder " - "${$add$capitalized_name$Builder$}$() {\n" - " return get$capitalized_name$FieldBuilder().addBuilder(\n" - " $type$.getDefaultInstance());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$.Builder ${$add$capitalized_name$Builder$}$(\n" - " int index) {\n" - " return get$capitalized_name$FieldBuilder().addBuilder(\n" - " index, $type$.getDefaultInstance());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$type$.Builder> \n" - " ${$get$capitalized_name$BuilderList$}$() {\n" - " return get$capitalized_name$FieldBuilder().getBuilderList();\n" - "}\n" - "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder> \n" - " get$capitalized_name$FieldBuilder() {\n" - " if ($name$Builder_ == null) {\n" - " $name$Builder_ = new com.google.protobuf.RepeatedFieldBuilder$ver$<\n" - " $type$, $type$.Builder, $type$OrBuilder>(\n" - " $name$_,\n" - " $get_mutable_bit_builder$,\n" - " getParentForChildren(),\n" - " isClean());\n" - " $name$_ = null;\n" - " }\n" - " return $name$Builder_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - printer->Print(variables_, - "get$capitalized_name$FieldBuilder();\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = java.util.Collections.emptyList();\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - PrintNestedBuilderCondition(printer, - "$name$_ = java.util.Collections.emptyList();\n" - "$clear_mutable_bit_builder$;\n", - - "$name$Builder_.clear();\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - // The code below does two optimizations (non-nested builder case): - // 1. If the other list is empty, there's nothing to do. This ensures we - // don't allocate a new array if we already have an immutable one. - // 2. If the other list is non-empty and our current list is empty, we can - // reuse the other list which is guaranteed to be immutable. - PrintNestedBuilderCondition(printer, - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$_.isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " } else {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addAll(other.$name$_);\n" - " }\n" - " $on_changed$\n" - "}\n", - - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$Builder_.isEmpty()) {\n" - " $name$Builder_.dispose();\n" - " $name$Builder_ = null;\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " $name$Builder_ = \n" - " com.google.protobuf.GeneratedMessage$ver$.alwaysUseFieldBuilders ?\n" - " get$capitalized_name$FieldBuilder() : null;\n" - " } else {\n" - " $name$Builder_.addAllMessages(other.$name$_);\n" - " }\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // The code below (non-nested builder case) ensures that the result has an - // immutable list. If our list is immutable, we can just reuse it. If not, - // we make it immutable. - PrintNestedBuilderCondition(printer, - "if ($get_mutable_bit_builder$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - " $clear_mutable_bit_builder$;\n" - "}\n" - "result.$name$_ = $name$_;\n", - - "result.$name$_ = $name$Builder_.build();\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new java.util.ArrayList<$type$>();\n" - " $set_mutable_bit_parser$;\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$name$_.add(input.readGroup($number$, $type$.$get_parser$,\n" - " extensionRegistry));\n"); - } else { - printer->Print(variables_, - "$name$_.add(\n" - " input.readMessage($type$.$get_parser$, extensionRegistry));\n"); - } -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_mutable_bit_parser$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$group_or_message$($number$, $name$_.get(i));\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, $name$_.get(i));\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutableMessageFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); -} - -string RepeatedImmutableMessageFieldGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->message_type()); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_message_field.h b/windows/include/google/protobuf/compiler/java/java_message_field.h deleted file mode 100644 index 7ee0edb26..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_field.h +++ /dev/null @@ -1,173 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableMessageFieldGenerator : public ImmutableFieldGenerator { - public: - explicit ImmutableMessageFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableMessageFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - void PrintNestedBuilderCondition(io::Printer* printer, - const char* regular_case, const char* nested_builder_case) const; - void PrintNestedBuilderFunction(io::Printer* printer, - const char* method_prototype, const char* regular_case, - const char* nested_builder_case, - const char* trailing_code) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageFieldGenerator); -}; - -class ImmutableMessageOneofFieldGenerator - : public ImmutableMessageFieldGenerator { - public: - ImmutableMessageOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableMessageOneofFieldGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageOneofFieldGenerator); -}; - -class RepeatedImmutableMessageFieldGenerator : public ImmutableFieldGenerator { - public: - explicit RepeatedImmutableMessageFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableMessageFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - void PrintNestedBuilderCondition(io::Printer* printer, - const char* regular_case, const char* nested_builder_case) const; - void PrintNestedBuilderFunction(io::Printer* printer, - const char* method_prototype, const char* regular_case, - const char* nested_builder_case, - const char* trailing_code) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableMessageFieldGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_message_field_lite.cc b/windows/include/google/protobuf/compiler/java/java_message_field_lite.cc deleted file mode 100644 index 9cf6f3636..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_field_lite.cc +++ /dev/null @@ -1,997 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { - -void SetMessageVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - ClassNameResolver* name_resolver, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - - (*variables)["type"] = - name_resolver->GetImmutableClassName(descriptor->message_type()); - (*variables)["mutable_type"] = - name_resolver->GetMutableClassName(descriptor->message_type()); - (*variables)["group_or_message"] = - (GetType(descriptor) == FieldDescriptor::TYPE_GROUP) ? - "Group" : "Message"; - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - (*variables)["required"] = descriptor->is_required() ? "true" : "false"; - - if (SupportFieldPresence(descriptor->file())) { - // For singular messages and builders, one bit is used for the hasField bit. - (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); - - // Note that these have a trailing ";". - (*variables)["set_has_field_bit_message"] = - GenerateSetBit(messageBitIndex) + ";"; - (*variables)["clear_has_field_bit_message"] = - GenerateClearBit(messageBitIndex) + ";"; - - (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); - } else { - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["clear_has_field_bit_message"] = ""; - - (*variables)["is_field_present_message"] = - (*variables)["name"] + "_ != null"; - } - - // For repeated builders, the underlying list tracks mutability state. - (*variables)["is_mutable"] = (*variables)["name"] + "_.isModifiable()"; - - (*variables)["get_has_field_bit_from_local"] = - GenerateGetBitFromLocal(builderBitIndex); - (*variables)["set_has_field_bit_to_local"] = - GenerateSetBitToLocal(messageBitIndex); -} - -} // namespace - -// =================================================================== - -ImmutableMessageFieldLiteGenerator:: -ImmutableMessageFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -ImmutableMessageFieldLiteGenerator::~ImmutableMessageFieldLiteGenerator() {} - -int ImmutableMessageFieldLiteGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutableMessageFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - - printer->Print(variables_, - "private $type$ $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } else { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $name$_ != null;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $name$_ = value;\n" - " $set_has_field_bit_message$\n" - " }\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " $name$_ = builderForValue.build();\n" - " $set_has_field_bit_message$\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.SuppressWarnings({\"ReferenceEquality\"})\n" - "private void merge$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " if ($name$_ != null &&\n" - " $name$_ != $type$.getDefaultInstance()) {\n" - " $name$_ =\n" - " $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n" - " } else {\n" - " $name$_ = value;\n" - " }\n" - " $set_has_field_bit_message$\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {" - " $name$_ = null;\n" - " $clear_has_field_bit_message$\n" - "}\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // The comments above the methods below are based on a hypothetical - // field of type "Field" called "Field". - - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field getField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - " }\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$merge$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.merge$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "get$capitalized_name$FieldBuilder();\n"); - } -} - - -void ImmutableMessageFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const {} - -void ImmutableMessageFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = visitor.visitMessage($name$_, other.$name$_);\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - // noop for scalars -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - // TODO(dweis): Update this code to avoid the builder allocation and instead - // only allocate a submessage that isn't made immutable. Rely on the top - // message calling makeImmutable once done to actually traverse the tree and - // finalize state. This will avoid: - // - transitive builder allocations - // - the extra transitive iteration for streamed fields - // - reallocations for copying repeated fields - printer->Print(variables_, - "$type$.Builder subBuilder = null;\n" - "if ($is_field_present_message$) {\n" - " subBuilder = $name$_.toBuilder();\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$name$_ = input.readGroup($number$, $type$.parser(),\n" - " extensionRegistry);\n"); - } else { - printer->Print(variables_, - "$name$_ = input.readMessage($type$.parser(), extensionRegistry);\n"); - } - - printer->Print(variables_, - "if (subBuilder != null) {\n" - " subBuilder.mergeFrom($name$_);\n" - " $name$_ = subBuilder.buildPartial();\n" - "}\n" - "$set_has_field_bit_message$\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for messages. -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.write$group_or_message$($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); -} - -void ImmutableMessageFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n" - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); -} - -string ImmutableMessageFieldLiteGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->message_type()); -} - -// =================================================================== - -ImmutableMessageOneofFieldLiteGenerator:: -ImmutableMessageOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableMessageFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); -} - -ImmutableMessageOneofFieldLiteGenerator:: -~ImmutableMessageOneofFieldLiteGenerator() {} - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($type$) $oneof_name$_;\n" - " }\n" - " return $type$.getDefaultInstance();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " $oneof_name$_ = value;\n" - " $set_oneof_case_message$;\n" - "}\n"); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " $oneof_name$_ = builderForValue.build();\n" - " $set_oneof_case_message$;\n" - "}\n"); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void merge$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " if ($has_oneof_case_message$ &&\n" - " $oneof_name$_ != $type$.getDefaultInstance()) {\n" - " $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n" - " .mergeFrom(value).buildPartial();\n" - " } else {\n" - " $oneof_name$_ = value;\n" - " }\n" - " $set_oneof_case_message$;\n" - "}\n"); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); -} - - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // The comments above the methods below are based on a hypothetical - // field of type "Field" called "Field". - - // boolean hasField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field getField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder setField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder setField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder mergeField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder " - "${$merge$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.merge$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Field.Builder clearField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneofMessage(\n" - " $has_oneof_case_message$,\n" - " $oneof_name$_,\n" - " other.$oneof_name$_);\n"); -} - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$type$.Builder subBuilder = null;\n" - "if ($has_oneof_case_message$) {\n" - " subBuilder = (($type$) $oneof_name$_).toBuilder();\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$oneof_name$_ = input.readGroup($number$, $type$.parser(),\n" - " extensionRegistry);\n"); - } else { - printer->Print(variables_, - "$oneof_name$_ =\n" - " input.readMessage($type$.parser(), extensionRegistry);\n"); - } - - printer->Print(variables_, - "if (subBuilder != null) {\n" - " subBuilder.mergeFrom(($type$) $oneof_name$_);\n" - " $oneof_name$_ = subBuilder.buildPartial();\n" - "}\n"); - printer->Print(variables_, - "$set_oneof_case_message$;\n"); -} - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.write$group_or_message$($number$, ($type$) $oneof_name$_);\n" - "}\n"); -} - -void ImmutableMessageOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, ($type$) $oneof_name$_);\n" - "}\n"); -} - -// =================================================================== - -RepeatedImmutableMessageFieldLiteGenerator:: -RepeatedImmutableMessageFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetMessageVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -RepeatedImmutableMessageFieldLiteGenerator:: -~RepeatedImmutableMessageFieldLiteGenerator() {} - -int RepeatedImmutableMessageFieldLiteGenerator::GetNumBitsForMessage() const { - return 0; -} - -int RepeatedImmutableMessageFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - // TODO(jonp): In the future, consider having methods specific to the - // interface so that builders can choose dynamically to either return a - // message or a nested builder, so that asking for the interface doesn't - // cause a message to ever be built. - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List<$type$> \n" - " get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.Internal.ProtobufList<$type$> $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List \n" - " ${$get$capitalized_name$OrBuilderList$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$OrBuilder " - "${$get$capitalized_name$OrBuilder$}$(\n" - " int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n" - "\n"); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - "}\n"); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, builderForValue.build());\n" - "}\n"); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$($type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - "}\n"); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " int index, $type$ value) {\n" - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(index, value);\n" - "}\n"); - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(builderForValue.build());\n" - "}\n"); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " int index, $type$.Builder builderForValue) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(index, builderForValue.build());\n" - "}\n"); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.addAll(\n" - " values, $name$_);\n" - "}\n"); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = emptyProtobufList();\n" - "}\n"); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void remove$capitalized_name$(int index) {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.remove(index);\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // The comments above the methods below are based on a hypothetical - // repeated field of type "Field" called "RepeatedField". - - // List getRepeatedFieldList() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$type$> " - "${$get$capitalized_name$List$}$() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$List());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // int getRepeatedFieldCount() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Count();\n" - "}"); - printer->Annotate("{", "}", descriptor_); - - // Field getRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Builder setRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Builder setRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, builderForValue);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Builder addRepeatedField(Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Builder addRepeatedField(int index, Field value) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - // Builder addRepeatedField(Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(builderForValue);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Builder addRepeatedField(int index, Field.Builder builderForValue) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " int index, $type$.Builder builderForValue) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(index, builderForValue);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Builder addAllRepeatedField(Iterable values) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Builder clearAllRepeatedField() - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - // Builder removeRepeatedField(int index) - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$remove$capitalized_name$$}$(int index) {\n" - " copyOnWrite();\n" - " instance.remove$capitalized_name$(index);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - printer->Print(variables_, - "get$capitalized_name$FieldBuilder();\n"); -} - - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = emptyProtobufList();\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_= visitor.visitList($name$_, other.$name$_);\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n"); - - if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "$name$_.add(input.readGroup($number$, $type$.parser(),\n" - " extensionRegistry));\n"); - } else { - printer->Print(variables_, - "$name$_.add(\n" - " input.readMessage($type$.parser(), extensionRegistry));\n"); - } -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_mutable$) {\n" - " $name$_.makeImmutable();\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$group_or_message$($number$, $name$_.get(i));\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$group_or_message$Size($number$, $name$_.get(i));\n" - "}\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutableMessageFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); -} - -string RepeatedImmutableMessageFieldLiteGenerator::GetBoxedType() const { - return name_resolver_->GetImmutableClassName(descriptor_->message_type()); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_message_field_lite.h b/windows/include/google/protobuf/compiler/java/java_message_field_lite.h deleted file mode 100644 index 7c814c6d7..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_field_lite.h +++ /dev/null @@ -1,159 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_LITE_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableMessageFieldLiteGenerator : public ImmutableFieldLiteGenerator { - public: - explicit ImmutableMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableMessageFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageFieldLiteGenerator); -}; - -class ImmutableMessageOneofFieldLiteGenerator - : public ImmutableMessageFieldLiteGenerator { - public: - ImmutableMessageOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableMessageOneofFieldLiteGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageOneofFieldLiteGenerator); -}; - -class RepeatedImmutableMessageFieldLiteGenerator - : public ImmutableFieldLiteGenerator { - public: - explicit RepeatedImmutableMessageFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableMessageFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableMessageFieldLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_FIELD_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_message_lite.cc b/windows/include/google/protobuf/compiler/java/java_message_lite.cc deleted file mode 100644 index 3a512e8dd..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_lite.cc +++ /dev/null @@ -1,1171 +0,0 @@ -// 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. - -// Author: dweis@google.com (Daniel Weis) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { -bool EnableExperimentalRuntimeForLite() { -#ifdef PROTOBUF_EXPERIMENT - return PROTOBUF_EXPERIMENT; -#else // PROTOBUF_EXPERIMENT - return false; -#endif // !PROTOBUF_EXPERIMENT -} - -bool GenerateHasBits(const Descriptor* descriptor) { - return SupportFieldPresence(descriptor->file()) || - HasRepeatedFields(descriptor); -} - -string MapValueImmutableClassdName(const Descriptor* descriptor, - ClassNameResolver* name_resolver) { - const FieldDescriptor* value_field = descriptor->FindFieldByName("value"); - GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type()); - return name_resolver->GetImmutableClassName(value_field->message_type()); -} -} // namespace - -// =================================================================== -ImmutableMessageLiteGenerator::ImmutableMessageLiteGenerator( - const Descriptor* descriptor, Context* context) - : MessageGenerator(descriptor), context_(context), - name_resolver_(context->GetNameResolver()), - field_generators_(descriptor, context_) { - GOOGLE_CHECK(!HasDescriptorMethods(descriptor->file(), context->EnforceLite())) - << "Generator factory error: A lite message generator is used to " - "generate non-lite messages."; -} - -ImmutableMessageLiteGenerator::~ImmutableMessageLiteGenerator() {} - -void ImmutableMessageLiteGenerator::GenerateStaticVariables( - io::Printer* printer, int* bytecode_estimate) { - // Generate static members for all nested types. - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // TODO(kenton): Reuse MessageGenerator objects? - ImmutableMessageLiteGenerator(descriptor_->nested_type(i), context_) - .GenerateStaticVariables(printer, bytecode_estimate); - } -} - -int ImmutableMessageLiteGenerator::GenerateStaticVariableInitializers( - io::Printer* printer) { - int bytecode_estimate = 0; - // Generate static member initializers for all nested types. - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // TODO(kenton): Reuse MessageGenerator objects? - bytecode_estimate += - ImmutableMessageLiteGenerator(descriptor_->nested_type(i), context_) - .GenerateStaticVariableInitializers(printer); - } - return bytecode_estimate; -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) { - MaybePrintGeneratedAnnotation(context_, printer, descriptor_, - /* immutable = */ true, "OrBuilder"); - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "$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(), - "{", "", "}", ""); - } else { - printer->Print( - "$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(), - "{", "", "}", ""); - } - printer->Annotate("{", "}", descriptor_); - - printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("\n"); - field_generators_.get(descriptor_->field(i)) - .GenerateInterfaceMembers(printer); - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print( - "\n" - "public $classname$.$oneof_capitalized_name$Case " - "get$oneof_capitalized_name$Case();\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name, - "classname", - context_->GetNameResolver()->GetImmutableClassName(descriptor_)); - } - printer->Outdent(); - - printer->Print("}\n"); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) { - bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true); - - std::map variables; - variables["static"] = is_own_file ? " " : " static "; - variables["classname"] = descriptor_->name(); - variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_); - variables["deprecation"] = descriptor_->options().deprecated() - ? "@java.lang.Deprecated " : ""; - - WriteMessageDocComment(printer, descriptor_); - MaybePrintGeneratedAnnotation(context_, printer, descriptor_, - /* immutable = */ true); - - - // The builder_type stores the super type name of the nested Builder class. - string builder_type; - if (descriptor_->extension_range_count() > 0) { - printer->Print(variables, - "$deprecation$public $static$final class $classname$ extends\n" - " com.google.protobuf.GeneratedMessageLite.ExtendableMessage<\n" - " $classname$, $classname$.Builder> implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n"); - builder_type = strings::Substitute( - "com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<$0, ?>", - name_resolver_->GetImmutableClassName(descriptor_)); - } else { - printer->Print(variables, - "$deprecation$public $static$final class $classname$ extends\n" - " com.google.protobuf.GeneratedMessageLite<\n" - " $classname$, $classname$.Builder> implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n"); - - builder_type = "com.google.protobuf.GeneratedMessageLite.Builder"; - } - printer->Indent(); - - GenerateConstructor(printer); - - // Nested types - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - EnumLiteGenerator(descriptor_->enum_type(i), true, context_) - .Generate(printer); - } - - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - // Don't generate Java classes for map entry messages. - if (IsMapEntry(descriptor_->nested_type(i))) continue; - ImmutableMessageLiteGenerator messageGenerator( - descriptor_->nested_type(i), context_); - messageGenerator.GenerateInterface(printer); - messageGenerator.Generate(printer); - } - - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForMessage(); - } - int totalInts = (totalBits + 31) / 32; - for (int i = 0; i < totalInts; i++) { - printer->Print("private int $bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - - // oneof - std::map vars; - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = descriptor_->oneof_decl(i); - vars["oneof_name"] = context_->GetOneofGeneratorInfo(oneof)->name; - vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo( - oneof)->capitalized_name; - vars["oneof_index"] = SimpleItoa(oneof->index()); - // oneofCase_ and oneof_ - printer->Print(vars, - "private int $oneof_name$Case_ = 0;\n" - "private java.lang.Object $oneof_name$_;\n"); - // OneofCase enum - printer->Print(vars, - "public enum $oneof_capitalized_name$Case\n" - " implements com.google.protobuf.Internal.EnumLite {\n"); - 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", - ToUpper(field->name()), - "field_number", - SimpleItoa(field->number())); - } - printer->Print( - "$cap_oneof_name$_NOT_SET(0);\n", - "cap_oneof_name", - ToUpper(vars["oneof_name"])); - printer->Print(vars, - "private final int value;\n" - "private $oneof_capitalized_name$Case(int value) {\n" - " this.value = value;\n" - "}\n"); - printer->Print(vars, - "/**\n" - " * @deprecated Use {@link #forNumber(int)} instead.\n" - " */\n" - "@java.lang.Deprecated\n" - "public static $oneof_capitalized_name$Case valueOf(int value) {\n" - " return forNumber(value);\n" - "}\n" - "\n" - "public static $oneof_capitalized_name$Case forNumber(int value) {\n" - " switch (value) {\n"); - for (int j = 0; j < oneof->field_count(); j++) { - const FieldDescriptor* field = oneof->field(j); - printer->Print( - " case $field_number$: return $field_name$;\n", - "field_number", - SimpleItoa(field->number()), - "field_name", - ToUpper(field->name())); - } - printer->Print( - " case 0: return $cap_oneof_name$_NOT_SET;\n" - " default: return null;\n" - " }\n" - "}\n" - "@java.lang.Override\n" - "public int getNumber() {\n" - " return this.value;\n" - "}\n", - "cap_oneof_name", ToUpper(vars["oneof_name"])); - printer->Outdent(); - printer->Print("};\n\n"); - // oneofCase() - printer->Print(vars, - "@java.lang.Override\n" - "public $oneof_capitalized_name$Case\n" - "get$oneof_capitalized_name$Case() {\n" - " return $oneof_capitalized_name$Case.forNumber(\n" - " $oneof_name$Case_);\n" - "}\n" - "\n" - "private void clear$oneof_capitalized_name$() {\n" - " $oneof_name$Case_ = 0;\n" - " $oneof_name$_ = null;\n" - "}\n" - "\n"); - } - - // Fields - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("public static final int $constant_name$ = $number$;\n", - "constant_name", FieldConstantName(descriptor_->field(i)), - "number", SimpleItoa(descriptor_->field(i)->number())); - field_generators_.get(descriptor_->field(i)).GenerateMembers(printer); - printer->Print("\n"); - } - - if (!EnableExperimentalRuntime(context_)) { - GenerateMessageSerializationMethods(printer); - } - - GenerateParseFromMethods(printer); - GenerateBuilder(printer); - - if (HasRequiredFields(descriptor_)) { - // Memoizes whether the protocol buffer is fully initialized (has all - // required fields). 0 means false, 1 means true, and all other values - // mean not yet computed. - printer->Print( - "private byte memoizedIsInitialized = 2;\n"); - } - - printer->Print( - "@java.lang.Override\n" - "@java.lang.SuppressWarnings({\"unchecked\", \"fallthrough\"})\n" - "protected final java.lang.Object dynamicMethod(\n" - " com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,\n" - " java.lang.Object arg0, java.lang.Object arg1) {\n" - " switch (method) {\n" - " case NEW_MUTABLE_INSTANCE: {\n" - " return new $classname$();\n" - " }\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Indent(); - printer->Indent(); - - printer->Print( - "case NEW_BUILDER: {\n"); - - printer->Indent(); - GenerateDynamicMethodNewBuilder(printer); - printer->Outdent(); - - if (!EnableExperimentalRuntimeForLite()) { - printer->Print( - "}\n" - "case IS_INITIALIZED: {\n"); - printer->Indent(); - GenerateDynamicMethodIsInitialized(printer); - printer->Outdent(); - - printer->Print("}\n"); - - printer->Print( - "case MAKE_IMMUTABLE: {\n"); - - printer->Indent(); - GenerateDynamicMethodMakeImmutable(printer); - printer->Outdent(); - - printer->Print( - "}\n" - "case VISIT: {\n"); - - printer->Indent(); - GenerateDynamicMethodVisit(printer); - printer->Outdent(); - - printer->Print( - "}\n" - "case MERGE_FROM_STREAM: {\n"); - - printer->Indent(); - GenerateDynamicMethodMergeFromStream(printer); - printer->Outdent(); - } - - - printer->Print( - "}\n" - "// fall through\n" - "case GET_DEFAULT_INSTANCE: {\n" - " return DEFAULT_INSTANCE;\n" - "}\n" - "case GET_PARSER: {\n" - // Generally one would use the lazy initialization holder pattern for - // manipulating static fields but that has exceptional cost on Android as - // it will generate an extra class for every message. Instead, use the - // double-check locking pattern which works just as well. - // - // The "parser" temporary mirrors the "PARSER" field to eliminate a read - // at the final return statement. - " com.google.protobuf.Parser<$classname$> parser = PARSER;\n" - " if (parser == null) {\n" - " synchronized ($classname$.class) {\n" - " parser = PARSER;\n" - " if (parser == null) {\n" - " parser = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n" - " PARSER = parser;\n" - " }\n" - " }\n" - " }\n" - " return parser;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Outdent(); - - if (HasRequiredFields(descriptor_)) { - printer->Print( - "}\n" - "case GET_MEMOIZED_IS_INITIALIZED: {\n" - " return memoizedIsInitialized;\n" - "}\n" - "case SET_MEMOIZED_IS_INITIALIZED: {\n" - " memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1);\n" - " return null;\n" - "}\n"); - } else { - printer->Print( - "}\n" - "case GET_MEMOIZED_IS_INITIALIZED: {\n" - " return (byte) 1;\n" - "}\n" - "case SET_MEMOIZED_IS_INITIALIZED: {\n" - " return null;\n" - "}\n"); - } - - printer->Outdent(); - printer->Print( - " }\n" - " throw new UnsupportedOperationException();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print( - "\n" - "// @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - - - // Carefully initialize the default instance in such a way that it doesn't - // conflict with other initialization. - printer->Print( - "private static final $classname$ DEFAULT_INSTANCE;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - printer->Print( - "static {\n" - " // New instances are implicitly immutable so no need to make\n" - " // immutable.\n" - " DEFAULT_INSTANCE = new $classname$();\n" - "}\n" - "\n", - "classname", descriptor_->name()); - if (EnableExperimentalRuntimeForLite()) { - // Register the default instance in a map. This map will be used by - // experimental runtime to lookup default instance given a class instance - // without using Java reflection. - printer->Print( - "static {\n" - " com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(\n" - " $classname$.class, DEFAULT_INSTANCE);\n" - "}\n", - "classname", descriptor_->name()); - } - - printer->Print( - "public static $classname$ getDefaultInstance() {\n" - " return DEFAULT_INSTANCE;\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - // 'of' method for Wrappers - if (IsWrappersProtoFile(descriptor_->file())) { - printer->Print( - "public static $classname$ of($field_type$ value) {\n" - " return newBuilder().setValue(value).build();\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_), - "field_type", PrimitiveTypeName(GetJavaType(descriptor_->field(0)))); - } - - GenerateParser(printer); - - // Extensions must be declared after the DEFAULT_INSTANCE is initialized - // because the DEFAULT_INSTANCE is used by the extension to lazily retrieve - // the outer class's FileDescriptor. - for (int i = 0; i < descriptor_->extension_count(); i++) { - ImmutableExtensionLiteGenerator(descriptor_->extension(i), context_) - .Generate(printer); - } - - - printer->Outdent(); - printer->Print("}\n\n"); -} - - -// =================================================================== - -void ImmutableMessageLiteGenerator:: -GenerateMessageSerializationMethods(io::Printer* printer) { - if (EnableExperimentalRuntimeForLite()) { - return; - } - - std::unique_ptr sorted_fields( - SortFieldsByNumber(descriptor_)); - - std::vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); - } - std::sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); - - printer->Print( - "@java.lang.Override\n" - "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" - " throws java.io.IOException {\n"); - printer->Indent(); - if (HasPackedFields(descriptor_)) { - // writeTo(CodedOutputStream output) might be invoked without - // getSerializedSize() ever being called, but we need the memoized - // sizes in case this message has packed fields. Rather than emit checks - // for each packed field, just call getSerializedSize() up front. In most - // cases, getSerializedSize() will have already been called anyway by one - // of the wrapper writeTo() methods, making this call cheap. - printer->Print("getSerializedSize();\n"); - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "com.google.protobuf.GeneratedMessageLite\n" - " .ExtendableMessage<$classname$, $classname$.Builder>\n" - " .ExtensionWriter extensionWriter =\n" - " newMessageSetExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - } else { - printer->Print( - "com.google.protobuf.GeneratedMessageLite\n" - " .ExtendableMessage<$classname$, $classname$.Builder>\n" - " .ExtensionWriter extensionWriter =\n" - " newExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - } - } - - // Merge the fields and the extension ranges, both sorted by field number. - for (int i = 0, j = 0; - i < descriptor_->field_count() || j < sorted_extensions.size();) { - if (i == descriptor_->field_count()) { - GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); - } else if (j == sorted_extensions.size()) { - GenerateSerializeOneField(printer, sorted_fields[i++]); - } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { - GenerateSerializeOneField(printer, sorted_fields[i++]); - } else { - GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); - } - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print("unknownFields.writeAsMessageSetTo(output);\n"); - } else { - printer->Print("unknownFields.writeTo(output);\n"); - } - - printer->Outdent(); - printer->Print( - "}\n" - "\n" - "@java.lang.Override\n" - "public int getSerializedSize() {\n" - " int size = memoizedSerializedSize;\n" - " if (size != -1) return size;\n" - "\n"); - printer->Indent(); - printer->Print( - "size = 0;\n"); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer); - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print("size += extensionsSerializedSizeAsMessageSet();\n"); - } else { - printer->Print("size += extensionsSerializedSize();\n"); - } - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print("size += unknownFields.getSerializedSizeAsMessageSet();\n"); - } else { - printer->Print("size += unknownFields.getSerializedSize();\n"); - } - - printer->Print( - "memoizedSerializedSize = size;\n" - "return size;\n"); - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); -} - -void ImmutableMessageLiteGenerator:: -GenerateParseFromMethods(io::Printer* printer) { - // Note: These are separate from GenerateMessageSerializationMethods() - // because they need to be generated even for messages that are optimized - // for code size. - printer->Print( - "public static $classname$ parseFrom(\n" - " java.nio.ByteBuffer data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " java.nio.ByteBuffer data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.ByteString data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.ByteString data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(byte[] data)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " byte[] data,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws com.google.protobuf.InvalidProtocolBufferException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, data, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(java.io.InputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, input);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " java.io.InputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, input, extensionRegistry);\n" - "}\n" - "public static $classname$ parseDelimitedFrom(java.io.InputStream input)\n" - " throws java.io.IOException {\n" - " return parseDelimitedFrom(DEFAULT_INSTANCE, input);\n" - "}\n" - "public static $classname$ parseDelimitedFrom(\n" - " java.io.InputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.CodedInputStream input)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, input);\n" - "}\n" - "public static $classname$ parseFrom(\n" - " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" - " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessageLite.parseFrom(\n" - " DEFAULT_INSTANCE, input, extensionRegistry);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); -} - -void ImmutableMessageLiteGenerator::GenerateSerializeOneField( - io::Printer* printer, const FieldDescriptor* field) { - field_generators_.get(field).GenerateSerializationCode(printer); -} - -void ImmutableMessageLiteGenerator::GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* range) { - printer->Print( - "extensionWriter.writeUntil($end$, output);\n", - "end", SimpleItoa(range->end)); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateBuilder(io::Printer* printer) { - printer->Print( - "public static Builder newBuilder() {\n" - " return (Builder) DEFAULT_INSTANCE.createBuilder();\n" - "}\n" - "public static Builder newBuilder($classname$ prototype) {\n" - " return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n" - "}\n" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - MessageBuilderLiteGenerator builderGenerator(descriptor_, context_); - builderGenerator.Generate(printer); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized( - io::Printer* printer) { - // Returns null for false, DEFAULT_INSTANCE for true. - if (!HasRequiredFields(descriptor_)) { - printer->Print("return DEFAULT_INSTANCE;\n"); - return; - } - - // TODO(xiaofeng): Remove this when b/64445758 is fixed. We don't need to - // check memoizedIsInitialized here because the caller does that already, - // but right now proguard proto shrinker asserts on the bytecode layout of - // this code so it can't be removed until proguard is updated. - printer->Print( - "byte isInitialized = memoizedIsInitialized;\n" - "if (isInitialized == 1) return DEFAULT_INSTANCE;\n" - "if (isInitialized == 0) return null;\n" - "\n" - "boolean shouldMemoize = ((Boolean) arg0).booleanValue();\n"); - - // Check that all required fields in this message are set. - // TODO(kenton): We can optimize this when we switch to putting all the - // "has" fields into a single bitfield. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - - if (field->is_required()) { - printer->Print( - "if (!has$name$()) {\n" - " return null;\n" - "}\n", - "name", info->capitalized_name); - } - } - - // Now check that all embedded messages are initialized. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - if (GetJavaType(field) == JAVATYPE_MESSAGE && - HasRequiredFields(field->message_type())) { - switch (field->label()) { - case FieldDescriptor::LABEL_REQUIRED: - printer->Print( - "if (!get$name$().isInitialized()) {\n" - " return null;\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); - break; - case FieldDescriptor::LABEL_OPTIONAL: - if (!SupportFieldPresence(descriptor_->file()) && - field->containing_oneof() != NULL) { - const OneofDescriptor* oneof = field->containing_oneof(); - const OneofGeneratorInfo* oneof_info = - context_->GetOneofGeneratorInfo(oneof); - printer->Print( - "if ($oneof_name$Case_ == $field_number$) {\n", - "oneof_name", oneof_info->name, - "field_number", SimpleItoa(field->number())); - } else { - printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); - } - printer->Print( - " if (!get$name$().isInitialized()) {\n" - " return null;\n" - " }\n" - "}\n", - "name", info->capitalized_name); - break; - case FieldDescriptor::LABEL_REPEATED: - if (IsMapEntry(field->message_type())) { - printer->Print( - "for ($type$ item : get$name$Map().values()) {\n" - " if (!item.isInitialized()) {\n" - " return null;\n" - " }\n" - "}\n", - "type", MapValueImmutableClassdName(field->message_type(), - name_resolver_), - "name", info->capitalized_name); - } else { - printer->Print( - "for (int i = 0; i < get$name$Count(); i++) {\n" - " if (!get$name$(i).isInitialized()) {\n" - " return null;\n" - " }\n" - "}\n", - "type", name_resolver_->GetImmutableClassName( - field->message_type()), - "name", info->capitalized_name); - } - break; - } - } - } - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if (!extensionsAreInitialized()) {\n" - " return null;\n" - "}\n"); - } - - printer->Print( - "return DEFAULT_INSTANCE;\n" - "\n"); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateDynamicMethodMakeImmutable( - io::Printer* printer) { - - // Output generation code for each field. - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)) - .GenerateDynamicMethodMakeImmutableCode(printer); - } - - printer->Print( - "return null;\n"); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateDynamicMethodNewBuilder( - io::Printer* printer) { - printer->Print( - "return new Builder();\n"); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateDynamicMethodVisit( - io::Printer* printer) { - printer->Print( - "Visitor visitor = (Visitor) arg0;\n" - "$classname$ other = ($classname$) arg1;\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - field_generators_.get( - descriptor_->field(i)).GenerateVisitCode(printer); - } - } - - // Merge oneof fields. - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - printer->Print( - "switch (other.get$oneof_capitalized_name$Case()) {\n", - "oneof_capitalized_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->capitalized_name); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - printer->Print( - "case $field_name$: {\n", - "field_name", - ToUpper(field->name())); - printer->Indent(); - field_generators_.get(field).GenerateVisitCode(printer); - printer->Print( - "break;\n"); - printer->Outdent(); - printer->Print( - "}\n"); - } - printer->Print( - "case $cap_oneof_name$_NOT_SET: {\n" - " visitor.visitOneofNotSet($oneof_name$Case_ != 0);\n" - " break;\n" - "}\n", - "cap_oneof_name", - ToUpper(context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name), - "oneof_name", - context_->GetOneofGeneratorInfo( - descriptor_->oneof_decl(i))->name); - printer->Outdent(); - printer->Print( - "}\n"); - } - - printer->Print( - "if (visitor == com.google.protobuf.GeneratedMessageLite.MergeFromVisitor\n" - " .INSTANCE) {\n"); - printer->Indent(); - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - const OneofDescriptor* field = descriptor_->oneof_decl(i); - printer->Print( - "if (other.$oneof_name$Case_ != 0) {\n" - " $oneof_name$Case_ = other.$oneof_name$Case_;\n" - "}\n", - "oneof_name", context_->GetOneofGeneratorInfo(field)->name); - } - - if (GenerateHasBits(descriptor_)) { - // Integers for bit fields. - int totalBits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - totalBits += field_generators_.get(descriptor_->field(i)) - .GetNumBitsForMessage(); - } - int totalInts = (totalBits + 31) / 32; - - for (int i = 0; i < totalInts; i++) { - printer->Print( - "$bit_field_name$ |= other.$bit_field_name$;\n", - "bit_field_name", GetBitFieldName(i)); - } - } - printer->Outdent(); - printer->Print( - "}\n"); - - - printer->Print( - "return this;\n"); -} - -// =================================================================== - -void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream( - io::Printer* printer) { - printer->Print( - "com.google.protobuf.CodedInputStream input =\n" - " (com.google.protobuf.CodedInputStream) arg0;\n" - "com.google.protobuf.ExtensionRegistryLite extensionRegistry =\n" - " (com.google.protobuf.ExtensionRegistryLite) arg1;\n" - "if (extensionRegistry == null) {\n" - " throw new java.lang.NullPointerException();\n" - "}\n"); - printer->Print( - "try {\n"); - printer->Indent(); - if (EnableExperimentalRuntime(context_)) { - printer->Print( - "mergeFromInternal(input, extensionRegistry);\n" - "return DEFAULT_INSTANCE;\n"); - } else { - printer->Print( - "boolean done = false;\n" - "while (!done) {\n"); - printer->Indent(); - - printer->Print( - "int tag = input.readTag();\n" - "switch (tag) {\n"); - printer->Indent(); - - printer->Print( - "case 0:\n" // zero signals EOF / limit reached - " done = true;\n" - " break;\n"); - - std::unique_ptr sorted_fields( - SortFieldsByNumber(descriptor_)); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = sorted_fields[i]; - uint32 tag = WireFormatLite::MakeTag( - field->number(), WireFormat::WireTypeForFieldType(field->type())); - - printer->Print("case $tag$: {\n", "tag", - SimpleItoa(static_cast(tag))); - printer->Indent(); - - field_generators_.get(field).GenerateParsingCode(printer); - - printer->Outdent(); - printer->Print( - " break;\n" - "}\n"); - - if (field->is_packable()) { - // To make packed = true wire compatible, we generate parsing code from - // a packed version of this field regardless of - // field->options().packed(). - uint32 packed_tag = WireFormatLite::MakeTag( - field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - printer->Print("case $tag$: {\n", "tag", - SimpleItoa(static_cast(packed_tag))); - printer->Indent(); - - field_generators_.get(field).GenerateParsingCodeFromPacked(printer); - - printer->Outdent(); - printer->Print( - " break;\n" - "}\n"); - } - } - - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "default: {\n" - " if (!parseUnknownFieldAsMessageSet(\n" - " getDefaultInstanceForType(), input, extensionRegistry,\n" - " tag)) {\n" - " done = true;\n" // it's an endgroup tag - " }\n" - " break;\n" - "}\n"); - } else { - printer->Print( - "default: {\n" - " if (!parseUnknownField(getDefaultInstanceForType(),\n" - " input, extensionRegistry, tag)) {\n" - " done = true;\n" // it's an endgroup tag - " }\n" - " break;\n" - "}\n"); - } - } else { - printer->Print( - "default: {\n" - " if (!parseUnknownField(tag, input)) {\n" - " done = true;\n" // it's an endgroup tag - " }\n" - " break;\n" - "}\n"); - } - - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" // switch (tag) - "}\n"); // while (!done) - } - - printer->Outdent(); - printer->Print( - "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" - " throw new RuntimeException(e.setUnfinishedMessage(this));\n" - "} catch (java.io.IOException e) {\n" - " throw new RuntimeException(\n" - " new com.google.protobuf.InvalidProtocolBufferException(\n" - " e.getMessage()).setUnfinishedMessage(this));\n" - "} finally {\n"); - printer->Indent(); - - printer->Outdent(); - printer->Print( - "}\n"); // finally -} - -// =================================================================== - -void ImmutableMessageLiteGenerator:: -GenerateExtensionRegistrationCode(io::Printer* printer) { - for (int i = 0; i < descriptor_->extension_count(); i++) { - ImmutableExtensionLiteGenerator(descriptor_->extension(i), context_) - .GenerateRegistrationCode(printer); - } - - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - ImmutableMessageLiteGenerator(descriptor_->nested_type(i), context_) - .GenerateExtensionRegistrationCode(printer); - } -} - -// =================================================================== -void ImmutableMessageLiteGenerator:: -GenerateConstructor(io::Printer* printer) { - printer->Print( - "private $classname$() {\n", - "classname", descriptor_->name()); - printer->Indent(); - - // Initialize all fields to default. - GenerateInitializers(printer); - - printer->Outdent(); - printer->Print( - "}\n"); -} - -// =================================================================== -void ImmutableMessageLiteGenerator::GenerateParser(io::Printer* printer) { - printer->Print( - "private static volatile com.google.protobuf.Parser<$classname$> PARSER;\n" - "\n" - "public static com.google.protobuf.Parser<$classname$> parser() {\n" - " return DEFAULT_INSTANCE.getParserForType();\n" - "}\n", - "classname", descriptor_->name()); -} - -// =================================================================== -void ImmutableMessageLiteGenerator::GenerateInitializers(io::Printer* printer) { - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - field_generators_.get(descriptor_->field(i)) - .GenerateInitializationCode(printer); - } - } -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_message_lite.h b/windows/include/google/protobuf/compiler/java/java_message_lite.h deleted file mode 100644 index 1e319c6d6..000000000 --- a/windows/include/google/protobuf/compiler/java/java_message_lite.h +++ /dev/null @@ -1,92 +0,0 @@ -// 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. - -// Author: dweis@google.com (Daniel Weis) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableMessageLiteGenerator : public MessageGenerator { - public: - ImmutableMessageLiteGenerator(const Descriptor* descriptor, Context* context); - virtual ~ImmutableMessageLiteGenerator(); - - virtual void Generate(io::Printer* printer); - virtual void GenerateInterface(io::Printer* printer); - virtual void GenerateExtensionRegistrationCode(io::Printer* printer); - virtual void GenerateStaticVariables( - io::Printer* printer, int* bytecode_estimate); - virtual int GenerateStaticVariableInitializers(io::Printer* printer); - - private: - - void GenerateMessageSerializationMethods(io::Printer* printer); - void GenerateParseFromMethods(io::Printer* printer); - void GenerateSerializeOneField(io::Printer* printer, - const FieldDescriptor* field); - void GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* range); - - void GenerateBuilder(io::Printer* printer); - void GenerateDynamicMethodIsInitialized(io::Printer* printer); - void GenerateDynamicMethodMakeImmutable(io::Printer* printer); - void GenerateDynamicMethodVisit(io::Printer* printer); - void GenerateDynamicMethodMergeFromStream(io::Printer* printer); - void GenerateDynamicMethodNewBuilder(io::Printer* printer); - void GenerateInitializers(io::Printer* printer); - void GenerateEqualsAndHashCode(io::Printer* printer); - void GenerateParser(io::Printer* printer); - void GenerateConstructor(io::Printer* printer); - - Context* context_; - ClassNameResolver* name_resolver_; - FieldGeneratorMap field_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableMessageLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_MESSAGE_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_name_resolver.cc b/windows/include/google/protobuf/compiler/java/java_name_resolver.cc deleted file mode 100644 index 1673b4ee7..000000000 --- a/windows/include/google/protobuf/compiler/java/java_name_resolver.cc +++ /dev/null @@ -1,274 +0,0 @@ -// 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. - -#include - -#include -#include - - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -namespace { -// A suffix that will be appended to the file's outer class name if the name -// conflicts with some other types defined in the file. -const char* kOuterClassNameSuffix = "OuterClass"; - -// Strip package name from a descriptor's full name. -// For example: -// Full name : foo.Bar.Baz -// Package name: foo -// After strip : Bar.Baz -string StripPackageName(const string& full_name, - const FileDescriptor* file) { - if (file->package().empty()) { - return full_name; - } else { - // Strip package name - return full_name.substr(file->package().size() + 1); - } -} - -// Get the name of a message's Java class without package name prefix. -string ClassNameWithoutPackage(const Descriptor* descriptor, - bool immutable) { - return StripPackageName(descriptor->full_name(), - descriptor->file()); -} - -// Get the name of an enum's Java class without package name prefix. -string ClassNameWithoutPackage(const EnumDescriptor* descriptor, - bool immutable) { - // Doesn't append "Mutable" for enum type's name. - const Descriptor* message_descriptor = descriptor->containing_type(); - if (message_descriptor == NULL) { - return descriptor->name(); - } else { - return ClassNameWithoutPackage(message_descriptor, immutable) + - "." + descriptor->name(); - } -} - -// Get the name of a service's Java class without package name prefix. -string ClassNameWithoutPackage(const ServiceDescriptor* descriptor, - bool immutable) { - string full_name = StripPackageName(descriptor->full_name(), - descriptor->file()); - // We don't allow nested service definitions. - GOOGLE_CHECK(full_name.find('.') == string::npos); - return full_name; -} - -// Check whether a given message or its nested types has the given class name. -bool MessageHasConflictingClassName(const Descriptor* message, - const string& classname) { - if (message->name() == classname) return true; - for (int i = 0; i < message->nested_type_count(); ++i) { - if (MessageHasConflictingClassName(message->nested_type(i), classname)) { - return true; - } - } - for (int i = 0; i < message->enum_type_count(); ++i) { - if (message->enum_type(i)->name() == classname) { - return true; - } - } - return false; -} - -} // namespace - -ClassNameResolver::ClassNameResolver() { -} - -ClassNameResolver::~ClassNameResolver() { -} - -string ClassNameResolver::GetFileDefaultImmutableClassName( - const FileDescriptor* file) { - string basename; - string::size_type last_slash = file->name().find_last_of('/'); - if (last_slash == string::npos) { - basename = file->name(); - } else { - basename = file->name().substr(last_slash + 1); - } - return UnderscoresToCamelCase(StripProto(basename), true); -} - -string ClassNameResolver::GetFileImmutableClassName( - const FileDescriptor* file) { - string& class_name = file_immutable_outer_class_names_[file]; - if (class_name.empty()) { - if (file->options().has_java_outer_classname()) { - class_name = file->options().java_outer_classname(); - } else { - class_name = GetFileDefaultImmutableClassName(file); - if (HasConflictingClassName(file, class_name)) { - class_name += kOuterClassNameSuffix; - } - } - } - return class_name; -} - -string ClassNameResolver::GetFileClassName(const FileDescriptor* file, - bool immutable) { - if (immutable) { - return GetFileImmutableClassName(file); - } else { - return "Mutable" + GetFileImmutableClassName(file); - } -} - -// Check whether there is any type defined in the proto file that has -// the given class name. -bool ClassNameResolver::HasConflictingClassName( - const FileDescriptor* file, const string& classname) { - for (int i = 0; i < file->enum_type_count(); i++) { - if (file->enum_type(i)->name() == classname) { - return true; - } - } - for (int i = 0; i < file->service_count(); i++) { - if (file->service(i)->name() == classname) { - return true; - } - } - for (int i = 0; i < file->message_type_count(); i++) { - if (MessageHasConflictingClassName(file->message_type(i), classname)) { - return true; - } - } - return false; -} - -string ClassNameResolver::GetDescriptorClassName( - const FileDescriptor* descriptor) { - return GetFileImmutableClassName(descriptor); -} - -string ClassNameResolver::GetClassName(const FileDescriptor* descriptor, - bool immutable) { - string result = FileJavaPackage(descriptor, immutable); - if (!result.empty()) result += '.'; - result += GetFileClassName(descriptor, immutable); - return result; -} - -// Get the full name of a Java class by prepending the Java package name -// or outer class name. -string ClassNameResolver::GetClassFullName(const string& name_without_package, - const FileDescriptor* file, - bool immutable, - bool multiple_files) { - string result; - if (multiple_files) { - result = FileJavaPackage(file, immutable); - } else { - result = GetClassName(file, immutable); - } - if (!result.empty()) { - result += '.'; - } - result += name_without_package; - return result; -} - -string ClassNameResolver::GetClassName(const Descriptor* descriptor, - bool immutable) { - return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable), - descriptor->file(), immutable, - MultipleJavaFiles(descriptor->file(), immutable)); -} - -string ClassNameResolver::GetClassName(const EnumDescriptor* descriptor, - bool immutable) { - return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable), - descriptor->file(), immutable, - MultipleJavaFiles(descriptor->file(), immutable)); -} - -string ClassNameResolver::GetClassName(const ServiceDescriptor* descriptor, - bool immutable) { - return GetClassFullName(ClassNameWithoutPackage(descriptor, immutable), - descriptor->file(), immutable, - MultipleJavaFiles(descriptor->file(), immutable)); -} - -// Get the Java Class style full name of a message. -string ClassNameResolver::GetJavaClassFullName( - const string& name_without_package, - const FileDescriptor* file, - bool immutable) { - string result; - if (MultipleJavaFiles(file, immutable)) { - result = FileJavaPackage(file, immutable); - if (!result.empty()) result += '.'; - } else { - result = GetClassName(file, immutable); - if (!result.empty()) result += '$'; - } - result += StringReplace(name_without_package, ".", "$", true); - return result; -} - -string ClassNameResolver::GetExtensionIdentifierName( - const FieldDescriptor* descriptor, bool immutable) { - return GetClassName(descriptor->containing_type(), immutable) + "." + - descriptor->name(); -} - - -string ClassNameResolver::GetJavaImmutableClassName( - const Descriptor* descriptor) { - return GetJavaClassFullName( - ClassNameWithoutPackage(descriptor, true), - descriptor->file(), true); -} - -string ClassNameResolver::GetJavaImmutableClassName( - const EnumDescriptor* descriptor) { - return GetJavaClassFullName( - ClassNameWithoutPackage(descriptor, true), - descriptor->file(), true); -} - - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_name_resolver.h b/windows/include/google/protobuf/compiler/java/java_name_resolver.h deleted file mode 100644 index 28b049d1e..000000000 --- a/windows/include/google/protobuf/compiler/java/java_name_resolver.h +++ /dev/null @@ -1,125 +0,0 @@ -// 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_JAVA_NAME_RESOLVER_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_NAME_RESOLVER_H__ - -#include -#include - -#include - -namespace google { -namespace protobuf { -class Descriptor; -class EnumDescriptor; -class FieldDescriptor; -class FileDescriptor; -class ServiceDescriptor; - -namespace compiler { -namespace java { - -// Used to get the Java class related names for a given descriptor. It caches -// the results to avoid redundant calculation across multiple name queries. -// Thread-safety note: This class is *not* thread-safe. -class ClassNameResolver { - public: - ClassNameResolver(); - ~ClassNameResolver(); - - // Gets the unqualified outer class name for the file. - string GetFileClassName(const FileDescriptor* file, bool immutable); - // Gets the unqualified immutable outer class name of a file. - string GetFileImmutableClassName(const FileDescriptor* file); - // Gets the unqualified default immutable outer class name of a file - // (converted from the proto file's name). - string GetFileDefaultImmutableClassName(const FileDescriptor* file); - - // Check whether there is any type defined in the proto file that has - // the given class name. - bool HasConflictingClassName(const FileDescriptor* file, - const string& classname); - - // Gets the name of the outer class that holds descriptor information. - // Descriptors are shared between immutable messages and mutable messages. - // Since both of them are generated optionally, the descriptors need to be - // put in another common place. - string GetDescriptorClassName(const FileDescriptor* file); - - // Gets the fully-qualified class name corresponding to the given descriptor. - string GetClassName(const Descriptor* descriptor, bool immutable); - string GetClassName(const EnumDescriptor* descriptor, bool immutable); - string GetClassName(const ServiceDescriptor* descriptor, bool immutable); - string GetClassName(const FileDescriptor* descriptor, bool immutable); - - template - string GetImmutableClassName(const DescriptorType* descriptor) { - return GetClassName(descriptor, true); - } - template - string GetMutableClassName(const DescriptorType* descriptor) { - return GetClassName(descriptor, false); - } - - // Gets the fully qualified name of an extension identifier. - string GetExtensionIdentifierName(const FieldDescriptor* descriptor, - bool immutable); - - // Gets the fully qualified name for generated classes in Java convention. - // Nested classes will be separated using '$' instead of '.' - // For example: - // com.package.OuterClass$OuterMessage$InnerMessage - string GetJavaImmutableClassName(const Descriptor* descriptor); - string GetJavaImmutableClassName(const EnumDescriptor* descriptor); - private: - // Get the full name of a Java class by prepending the Java package name - // or outer class name. - string GetClassFullName(const string& name_without_package, - const FileDescriptor* file, - bool immutable, - bool multiple_files); - // Get the Java Class style full name of a message. - string GetJavaClassFullName( - const string& name_without_package, - const FileDescriptor* file, - bool immutable); - // Caches the result to provide better performance. - std::map file_immutable_outer_class_names_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ClassNameResolver); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_NAME_RESOLVER_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_names.h b/windows/include/google/protobuf/compiler/java/java_names.h index 0d6143353..313ace4fe 100644 --- a/windows/include/google/protobuf/compiler/java/java_names.h +++ b/windows/include/google/protobuf/compiler/java/java_names.h @@ -46,6 +46,7 @@ namespace protobuf { class Descriptor; class EnumDescriptor; class FileDescriptor; +class FieldDescriptor; class ServiceDescriptor; namespace compiler { @@ -56,32 +57,44 @@ namespace java { // // Returns: // The fully-qualified Java class name. -string ClassName(const Descriptor* descriptor); +std::string ClassName(const Descriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const EnumDescriptor* descriptor); +std::string ClassName(const EnumDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const FileDescriptor* descriptor); +std::string ClassName(const FileDescriptor* descriptor); // Requires: // descriptor != NULL // // Returns: // The fully-qualified Java class name. -string ClassName(const ServiceDescriptor* descriptor); +std::string ClassName(const ServiceDescriptor* descriptor); + +// Requires: +// descriptor != NULL +// +// Returns: +// Java package name. +std::string FileJavaPackage(const FileDescriptor* descriptor); + +// Requires: +// descriptor != NULL +// Returns: +// Capitalized camel case name field name. +std::string CapitalizedFieldName(const FieldDescriptor* descriptor); } // namespace java } // namespace compiler } // namespace protobuf } // namespace google - #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_NAMES_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_options.h b/windows/include/google/protobuf/compiler/java/java_options.h deleted file mode 100644 index e4e7d5e26..000000000 --- a/windows/include/google/protobuf/compiler/java/java_options.h +++ /dev/null @@ -1,73 +0,0 @@ -// 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_JAVA_OPTIONS_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_OPTIONS_H__ - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -// Generator options -struct Options { - Options() - : generate_immutable_code(false), - generate_mutable_code(false), - generate_shared_code(false), - enforce_lite(false), - annotate_code(false) { - } - - bool generate_immutable_code; - bool generate_mutable_code; - bool generate_shared_code; - // When set, the protoc will generate the current files and all the transitive - // dependencies as lite runtime. - bool enforce_lite; - // If true, we should build .meta files and emit @Generated annotations into - // generated code. - bool annotate_code; - // Name of a file where we will write a list of generated .meta file names, - // one per line. - std::string annotation_list_file; - // Name of a file where we will write a list of generated file names, one - // per line. - std::string output_list_file; -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_OPTIONS_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_plugin_unittest.cc b/windows/include/google/protobuf/compiler/java/java_plugin_unittest.cc deleted file mode 100644 index 87f687da1..000000000 --- a/windows/include/google/protobuf/compiler/java/java_plugin_unittest.cc +++ /dev/null @@ -1,125 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// -// TODO(kenton): Share code with the versions of this test in other languages? -// It seemed like parameterizing it would add more complexity than it is -// worth. - -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { -namespace { - -class TestGenerator : public CodeGenerator { - public: - TestGenerator() {} - ~TestGenerator() {} - - virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - string filename = "Test.java"; - TryInsert(filename, "outer_class_scope", context); - TryInsert(filename, "class_scope:foo.Bar", context); - TryInsert(filename, "class_scope:foo.Bar.Baz", context); - TryInsert(filename, "builder_scope:foo.Bar", context); - TryInsert(filename, "builder_scope:foo.Bar.Baz", context); - TryInsert(filename, "enum_scope:foo.Qux", context); - return true; - } - - void TryInsert(const string& filename, const string& insertion_point, - GeneratorContext* context) const { - std::unique_ptr output( - context->OpenForInsert(filename, insertion_point)); - io::Printer printer(output.get(), '$'); - printer.Print("// inserted $name$\n", "name", insertion_point); - } -}; - -// This test verifies that all the expected insertion points exist. It does -// not verify that they are correctly-placed; that would require actually -// compiling the output which is a bit more than I care to do for this test. -TEST(JavaPluginTest, PluginTest) { - GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/test.proto", - "syntax = \"proto2\";\n" - "package foo;\n" - "option java_package = \"\";\n" - "option java_outer_classname = \"Test\";\n" - "message Bar {\n" - " message Baz {}\n" - "}\n" - "enum Qux { BLAH = 1; }\n", - true)); - - google::protobuf::compiler::CommandLineInterface cli; - cli.SetInputsAreProtoPathRelative(true); - - JavaGenerator java_generator; - TestGenerator test_generator; - cli.RegisterGenerator("--java_out", &java_generator, ""); - cli.RegisterGenerator("--test_out", &test_generator, ""); - - string proto_path = "-I" + TestTempDir(); - string java_out = "--java_out=" + TestTempDir(); - string test_out = "--test_out=" + TestTempDir(); - - const char* argv[] = { - "protoc", - proto_path.c_str(), - java_out.c_str(), - test_out.c_str(), - "test.proto" - }; - - EXPECT_EQ(0, cli.Run(5, argv)); -} - -} // namespace -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_primitive_field.cc b/windows/include/google/protobuf/compiler/java/java_primitive_field.cc deleted file mode 100644 index 71ee0992b..000000000 --- a/windows/include/google/protobuf/compiler/java/java_primitive_field.cc +++ /dev/null @@ -1,900 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -void SetPrimitiveVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - ClassNameResolver* name_resolver, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - - (*variables)["type"] = PrimitiveTypeName(GetJavaType(descriptor)); - (*variables)["boxed_type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor)); - (*variables)["field_type"] = (*variables)["type"]; - (*variables)["field_list_type"] = "java.util.List<" + - (*variables)["boxed_type"] + ">"; - (*variables)["empty_list"] = "java.util.Collections.emptyList()"; - (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["default_init"] = IsDefaultValueJavaDefault(descriptor) ? - "" : ("= " + ImmutableDefaultValue(descriptor, name_resolver)); - (*variables)["capitalized_type"] = - GetCapitalizedType(descriptor, /* immutable = */ true); - (*variables)["tag"] = - SimpleItoa(static_cast(WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( - WireFormat::TagSize(descriptor->number(), GetType(descriptor))); - if (IsReferenceType(GetJavaType(descriptor))) { - (*variables)["null_check"] = - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n"; - } else { - (*variables)["null_check"] = ""; - } - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - int fixed_size = FixedSize(GetType(descriptor)); - if (fixed_size != -1) { - (*variables)["fixed_size"] = SimpleItoa(fixed_size); - } - (*variables)["on_changed"] = "onChanged();"; - - if (SupportFieldPresence(descriptor->file())) { - // For singular messages and builders, one bit is used for the hasField bit. - (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); - (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex); - - // Note that these have a trailing ";". - (*variables)["set_has_field_bit_message"] = - GenerateSetBit(messageBitIndex) + ";"; - (*variables)["set_has_field_bit_builder"] = - GenerateSetBit(builderBitIndex) + ";"; - (*variables)["clear_has_field_bit_builder"] = - GenerateClearBit(builderBitIndex) + ";"; - - (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); - } else { - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["set_has_field_bit_builder"] = ""; - (*variables)["clear_has_field_bit_builder"] = ""; - - if (descriptor->type() == FieldDescriptor::TYPE_BYTES) { - (*variables)["is_field_present_message"] = - "!" + (*variables)["name"] + "_.isEmpty()"; - } else { - (*variables)["is_field_present_message"] = - (*variables)["name"] + "_ != " + (*variables)["default"]; - } - } - - // For repated builders, one bit is used for whether the array is immutable. - (*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex); - (*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex); - (*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex); - - // For repeated fields, one bit is used for whether the array is immutable - // in the parsing constructor. - (*variables)["get_mutable_bit_parser"] = - GenerateGetBitMutableLocal(builderBitIndex); - (*variables)["set_mutable_bit_parser"] = - GenerateSetBitMutableLocal(builderBitIndex); - - (*variables)["get_has_field_bit_from_local"] = - GenerateGetBitFromLocal(builderBitIndex); - (*variables)["set_has_field_bit_to_local"] = - GenerateSetBitToLocal(messageBitIndex); -} - -} // namespace - -// =================================================================== - -ImmutablePrimitiveFieldGenerator:: -ImmutablePrimitiveFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -ImmutablePrimitiveFieldGenerator::~ImmutablePrimitiveFieldGenerator() {} - -int ImmutablePrimitiveFieldGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutablePrimitiveFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $field_type$ $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $field_type$ $name$_ $default_init$;\n"); - - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - "$null_check$" - " $set_has_field_bit_builder$\n" - " $name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $clear_has_field_bit_builder$\n"); - printer->Annotate("{", "}", descriptor_); - JavaType type = GetJavaType(descriptor_); - if (type == JAVATYPE_STRING || type == JAVATYPE_BYTES) { - // The default value is not a simple literal so we want to avoid executing - // it multiple times. Instead, get the default out of the default instance. - printer->Print(variables_, - " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); - } else { - printer->Print(variables_, - " $name$_ = $default$;\n"); - } - printer->Print(variables_, - " $on_changed$\n" - " return this;\n" - "}\n"); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for primitives -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = $default$;\n" - "$clear_has_field_bit_builder$\n"); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " set$capitalized_name$(other.get$capitalized_name$());\n" - "}\n"); - } else { - printer->Print(variables_, - "if (other.get$capitalized_name$() != $default$) {\n" - " set$capitalized_name$(other.get$capitalized_name$());\n" - "}\n"); - } -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); - } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$set_has_field_bit_message$\n" - "$name$_ = input.read$capitalized_type$();\n"); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for primitives. -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.write$capitalized_type$($number$, $name$_);\n" - "}\n"); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$Size($number$, $name$_);\n" - "}\n"); -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - switch (GetJavaType(descriptor_)) { - case JAVATYPE_INT: - case JAVATYPE_LONG: - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "result = result && (get$capitalized_name$()\n" - " == other.get$capitalized_name$());\n"); - break; - - case JAVATYPE_FLOAT: - printer->Print(variables_, - "result = result && (\n" - " java.lang.Float.floatToIntBits(get$capitalized_name$())\n" - " == java.lang.Float.floatToIntBits(\n" - " other.get$capitalized_name$()));\n"); - break; - - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "result = result && (\n" - " java.lang.Double.doubleToLongBits(get$capitalized_name$())\n" - " == java.lang.Double.doubleToLongBits(\n" - " other.get$capitalized_name$()));\n"); - break; - - case JAVATYPE_STRING: - case JAVATYPE_BYTES: - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); - break; - - case JAVATYPE_ENUM: - case JAVATYPE_MESSAGE: - default: - GOOGLE_LOG(FATAL) << "Can't get here."; - break; - } -} - -void ImmutablePrimitiveFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n"); - switch (GetJavaType(descriptor_)) { - case JAVATYPE_INT: - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$();\n"); - break; - - case JAVATYPE_LONG: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_FLOAT: - printer->Print(variables_, - "hash = (53 * hash) + java.lang.Float.floatToIntBits(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" - " java.lang.Double.doubleToLongBits(get$capitalized_name$()));\n"); - break; - - case JAVATYPE_STRING: - case JAVATYPE_BYTES: - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); - break; - - case JAVATYPE_ENUM: - case JAVATYPE_MESSAGE: - default: - GOOGLE_LOG(FATAL) << "Can't get here."; - break; - } -} - -string ImmutablePrimitiveFieldGenerator::GetBoxedType() const { - return BoxedPrimitiveTypeName(GetJavaType(descriptor_)); -} - -// =================================================================== - -ImmutablePrimitiveOneofFieldGenerator:: -ImmutablePrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutablePrimitiveFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); -} - -ImmutablePrimitiveOneofFieldGenerator:: -~ImmutablePrimitiveOneofFieldGenerator() {} - -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($boxed_type$) $oneof_name$_;\n" - " }\n" - " return $default$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - - -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($boxed_type$) $oneof_name$_;\n" - " }\n" - " return $default$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - "$null_check$" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - " }\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " result.$oneof_name$_ = $oneof_name$_;\n" - "}\n"); -} - -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - printer->Print(variables_, - "set$capitalized_name$(other.get$capitalized_name$());\n"); -} - -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$set_oneof_case_message$;\n" - "$oneof_name$_ = input.read$capitalized_type$();\n"); -} - -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.write$capitalized_type$(\n"); - // $type$ and $boxed_type$ is the same for bytes fields so we don't need to - // do redundant casts. - if (GetJavaType(descriptor_) == JAVATYPE_BYTES) { - printer->Print(variables_, - " $number$, ($type$) $oneof_name$_);\n"); - } else { - printer->Print(variables_, - " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n"); - } - printer->Print( - "}\n"); -} - -void ImmutablePrimitiveOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$Size(\n"); - // $type$ and $boxed_type$ is the same for bytes fields so we don't need to - // do redundant casts. - if (GetJavaType(descriptor_) == JAVATYPE_BYTES) { - printer->Print(variables_, - " $number$, ($type$) $oneof_name$_);\n"); - } else { - printer->Print(variables_, - " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n"); - } - printer->Print( - "}\n"); -} - -// =================================================================== - -RepeatedImmutablePrimitiveFieldGenerator:: -RepeatedImmutablePrimitiveFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -RepeatedImmutablePrimitiveFieldGenerator:: -~RepeatedImmutablePrimitiveFieldGenerator() {} - -int RepeatedImmutablePrimitiveFieldGenerator::GetNumBitsForMessage() const { - return 0; -} - -int RepeatedImmutablePrimitiveFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List<$boxed_type$> get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); -} - - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $field_list_type$ $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$boxed_type$>\n" - " ${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - if (descriptor_->is_packed()) { - printer->Print(variables_, - "private int $name$MemoizedSerializedSize = -1;\n"); - } -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // One field is the list and the bit field keeps track of whether the - // list is immutable. If it's immutable, the invariant is that it must - // either an instance of Collections.emptyList() or it's an ArrayList - // wrapped in a Collections.unmodifiableList() wrapper and nobody else has - // a refererence to the underlying ArrayList. This invariant allows us to - // share instances of lists between protocol buffers avoiding expensive - // memory allocations. Note, immutable is a strong guarantee here -- not - // just that the list cannot be modified via the reference but that the - // list can never be modified. - printer->Print(variables_, - "private $field_list_type$ $name$_ = $empty_list$;\n"); - - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ = new java.util.ArrayList<$boxed_type$>($name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n"); - - // Note: We return an unmodifiable list because otherwise the caller - // could hold on to the returned list and modify it after the message - // has been built, thus mutating the message which is supposed to be - // immutable. - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.util.List<$boxed_type$>\n" - " ${$get$capitalized_name$List$}$() {\n" - " return java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" - " values, $name$_);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $name$_ = $empty_list$;\n" - " $clear_mutable_bit_builder$;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for primitives -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $empty_list$;\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = $empty_list$;\n" - "$clear_mutable_bit_builder$;\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - // The code below does two optimizations: - // 1. If the other list is empty, there's nothing to do. This ensures we - // don't allocate a new array if we already have an immutable one. - // 2. If the other list is non-empty and our current list is empty, we can - // reuse the other list which is guaranteed to be immutable. - printer->Print(variables_, - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$_.isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " } else {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addAll(other.$name$_);\n" - " }\n" - " $on_changed$\n" - "}\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // The code below ensures that the result has an immutable list. If our - // list is immutable, we can just reuse it. If not, we make it immutable. - printer->Print(variables_, - "if ($get_mutable_bit_builder$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - " $clear_mutable_bit_builder$;\n" - "}\n" - "result.$name$_ = $name$_;\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new java.util.ArrayList<$boxed_type$>();\n" - " $set_mutable_bit_parser$;\n" - "}\n" - "$name$_.add(input.read$capitalized_type$());\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - printer->Print(variables_, - "int length = input.readRawVarint32();\n" - "int limit = input.pushLimit(length);\n" - "if (!$get_mutable_bit_parser$ && input.getBytesUntilLimit() > 0) {\n" - " $name$_ = new java.util.ArrayList<$boxed_type$>();\n" - " $set_mutable_bit_parser$;\n" - "}\n" - "while (input.getBytesUntilLimit() > 0) {\n" - " $name$_.add(input.read$capitalized_type$());\n" - "}\n" - "input.popLimit(limit);\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_mutable_bit_parser$) {\n" - " $name$_ = java.util.Collections.unmodifiableList($name$_);\n" - "}\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - if (descriptor_->is_packed()) { - // We invoke getSerializedSize in writeTo for messages that have packed - // fields in ImmutableMessageGenerator::GenerateMessageSerializationMethods. - // That makes it safe to rely on the memoized size here. - printer->Print(variables_, - "if (get$capitalized_name$List().size() > 0) {\n" - " output.writeUInt32NoTag($tag$);\n" - " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" - "}\n" - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$capitalized_type$NoTag($name$_.get(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$capitalized_type$($number$, $name$_.get(i));\n" - "}\n"); - } -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - if (FixedSize(GetType(descriptor_)) == -1) { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$SizeNoTag($name$_.get(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "dataSize = $fixed_size$ * get$capitalized_name$List().size();\n"); - } - - printer->Print( - "size += dataSize;\n"); - - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (!get$capitalized_name$List().isEmpty()) {\n" - " size += $tag_size$;\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeInt32SizeNoTag(dataSize);\n" - "}\n"); - } else { - printer->Print(variables_, - "size += $tag_size$ * get$capitalized_name$List().size();\n"); - } - - // cache the data size for packed fields. - if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutablePrimitiveFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); -} - -string RepeatedImmutablePrimitiveFieldGenerator::GetBoxedType() const { - return BoxedPrimitiveTypeName(GetJavaType(descriptor_)); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_primitive_field.h b/windows/include/google/protobuf/compiler/java/java_primitive_field.h deleted file mode 100644 index 7ac9bbfb7..000000000 --- a/windows/include/google/protobuf/compiler/java/java_primitive_field.h +++ /dev/null @@ -1,160 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutablePrimitiveFieldGenerator : public ImmutableFieldGenerator { - public: - explicit ImmutablePrimitiveFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutablePrimitiveFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutablePrimitiveFieldGenerator); -}; - -class ImmutablePrimitiveOneofFieldGenerator - : public ImmutablePrimitiveFieldGenerator { - public: - ImmutablePrimitiveOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutablePrimitiveOneofFieldGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutablePrimitiveOneofFieldGenerator); -}; - -class RepeatedImmutablePrimitiveFieldGenerator - : public ImmutableFieldGenerator { - public: - explicit RepeatedImmutablePrimitiveFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - virtual ~RepeatedImmutablePrimitiveFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingCodeFromPacked(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutablePrimitiveFieldGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_primitive_field_lite.cc b/windows/include/google/protobuf/compiler/java/java_primitive_field_lite.cc deleted file mode 100644 index d2ebc5674..000000000 --- a/windows/include/google/protobuf/compiler/java/java_primitive_field_lite.cc +++ /dev/null @@ -1,954 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -void SetPrimitiveVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - ClassNameResolver* name_resolver, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - JavaType javaType = GetJavaType(descriptor); - (*variables)["type"] = PrimitiveTypeName(javaType); - (*variables)["boxed_type"] = BoxedPrimitiveTypeName(javaType); - (*variables)["field_type"] = (*variables)["type"]; - (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["capitalized_type"] = - GetCapitalizedType(descriptor, /* immutable = */ true); - (*variables)["tag"] = - SimpleItoa(static_cast(WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( - WireFormat::TagSize(descriptor->number(), GetType(descriptor))); - (*variables)["required"] = descriptor->is_required() ? "true" : "false"; - - string capitalized_type = UnderscoresToCamelCase(PrimitiveTypeName(javaType), - true /* cap_next_letter */); - switch (javaType) { - case JAVATYPE_INT: - case JAVATYPE_LONG: - case JAVATYPE_FLOAT: - case JAVATYPE_DOUBLE: - case JAVATYPE_BOOLEAN: - (*variables)["field_list_type"] = - "com.google.protobuf.Internal." + capitalized_type + "List"; - (*variables)["empty_list"] = "empty" + capitalized_type + "List()"; - (*variables)["make_name_unmodifiable"] = - (*variables)["name"] + "_.makeImmutable()"; - (*variables)["repeated_get"] = - (*variables)["name"] + "_.get" + capitalized_type; - (*variables)["repeated_add"] = - (*variables)["name"] + "_.add" + capitalized_type; - (*variables)["repeated_set"] = - (*variables)["name"] + "_.set" + capitalized_type; - (*variables)["visit_type"] = capitalized_type; - (*variables)["visit_type_list"] = "visit" + capitalized_type + "List"; - break; - default: - (*variables)["field_list_type"] = - "com.google.protobuf.Internal.ProtobufList<" + - (*variables)["boxed_type"] + ">"; - (*variables)["empty_list"] = "emptyProtobufList()"; - (*variables)["make_name_unmodifiable"] = - (*variables)["name"] + "_.makeImmutable()"; - (*variables)["repeated_get"] = (*variables)["name"] + "_.get"; - (*variables)["repeated_add"] = (*variables)["name"] + "_.add"; - (*variables)["repeated_set"] = (*variables)["name"] + "_.set"; - (*variables)["visit_type"] = "ByteString"; - (*variables)["visit_type_list"] = "visitList"; - } - - if (javaType == JAVATYPE_BYTES) { - (*variables)["bytes_default"] = - ToUpper((*variables)["name"]) + "_DEFAULT_VALUE"; - } - - if (IsReferenceType(javaType)) { - (*variables)["null_check"] = - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n"; - } else { - (*variables)["null_check"] = ""; - } - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - int fixed_size = FixedSize(GetType(descriptor)); - if (fixed_size != -1) { - (*variables)["fixed_size"] = SimpleItoa(fixed_size); - } - - if (SupportFieldPresence(descriptor->file())) { - // For singular messages and builders, one bit is used for the hasField bit. - (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); - - // Note that these have a trailing ";". - (*variables)["set_has_field_bit_message"] = - GenerateSetBit(messageBitIndex) + ";"; - (*variables)["clear_has_field_bit_message"] = - GenerateClearBit(messageBitIndex) + ";"; - - (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); - } else { - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["clear_has_field_bit_message"] = ""; - - if (descriptor->type() == FieldDescriptor::TYPE_BYTES) { - (*variables)["is_field_present_message"] = - "!" + (*variables)["name"] + "_.isEmpty()"; - } else { - (*variables)["is_field_present_message"] = - (*variables)["name"] + "_ != " + (*variables)["default"]; - } - } - - // For repeated builders, the underlying list tracks mutability state. - (*variables)["is_mutable"] = (*variables)["name"] + "_.isModifiable()"; - - (*variables)["get_has_field_bit_from_local"] = - GenerateGetBitFromLocal(builderBitIndex); - (*variables)["set_has_field_bit_to_local"] = - GenerateSetBitToLocal(messageBitIndex); -} - -} // namespace - -// =================================================================== - -ImmutablePrimitiveFieldLiteGenerator:: -ImmutablePrimitiveFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -ImmutablePrimitiveFieldLiteGenerator::~ImmutablePrimitiveFieldLiteGenerator() {} - -int ImmutablePrimitiveFieldLiteGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutablePrimitiveFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$();\n"); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - if (IsByteStringWithCustomDefaultValue(descriptor_)) { - // allocate this once statically since we know ByteStrings are immutable - // values that can be reused. - printer->Print( - variables_, - "private static final $field_type$ $bytes_default$ = $default$;\n"); - } - printer->Print(variables_, - "private $field_type$ $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - "$null_check$" - " $set_has_field_bit_message$\n" - " $name$_ = value;\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $clear_has_field_bit_message$\n"); - JavaType type = GetJavaType(descriptor_); - if (type == JAVATYPE_STRING || type == JAVATYPE_BYTES) { - // The default value is not a simple literal so we want to avoid executing - // it multiple times. Instead, get the default out of the default instance. - printer->Print(variables_, - " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); - } else { - printer->Print(variables_, - " $name$_ = $default$;\n"); - } - printer->Print(variables_, - "}\n"); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for primitives -} - - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - if (IsByteStringWithCustomDefaultValue(descriptor_)) { - printer->Print(variables_, "$name$_ = $bytes_default$;\n"); - } else if (!IsDefaultValueJavaDefault(descriptor_)) { - printer->Print(variables_, "$name$_ = $default$;\n"); - } -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - // noop for primitives -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "$name$_ = visitor.visit$visit_type$(\n" - " has$capitalized_name$(), $name$_,\n" - " other.has$capitalized_name$(), other.$name$_);\n"); - } else { - printer->Print(variables_, - "$name$_ = visitor.visit$visit_type$($name$_ != $default$, $name$_,\n" - " other.$name$_ != $default$, other.$name$_);\n"); - } -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // noop for primitives -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - // noop for scalars -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$set_has_field_bit_message$\n" - "$name$_ = input.read$capitalized_type$();\n"); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for primitives. -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.write$capitalized_type$($number$, $name$_);\n" - "}\n"); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$Size($number$, $name$_);\n" - "}\n"); -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - switch (GetJavaType(descriptor_)) { - case JAVATYPE_INT: - case JAVATYPE_LONG: - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "result = result && (get$capitalized_name$()\n" - " == other.get$capitalized_name$());\n"); - break; - - case JAVATYPE_FLOAT: - printer->Print(variables_, - "result = result && (\n" - " java.lang.Float.floatToIntBits(get$capitalized_name$())\n" - " == java.lang.Float.floatToIntBits(\n" - " other.get$capitalized_name$()));\n"); - break; - - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "result = result && (\n" - " java.lang.Double.doubleToLongBits(get$capitalized_name$())\n" - " == java.lang.Double.doubleToLongBits(\n" - " other.get$capitalized_name$()));\n"); - break; - - case JAVATYPE_STRING: - case JAVATYPE_BYTES: - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); - break; - - case JAVATYPE_ENUM: - case JAVATYPE_MESSAGE: - default: - GOOGLE_LOG(FATAL) << "Can't get here."; - break; - } -} - -void ImmutablePrimitiveFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n"); - switch (GetJavaType(descriptor_)) { - case JAVATYPE_INT: - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$();\n"); - break; - - case JAVATYPE_LONG: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_BOOLEAN: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_FLOAT: - printer->Print(variables_, - "hash = (53 * hash) + java.lang.Float.floatToIntBits(\n" - " get$capitalized_name$());\n"); - break; - - case JAVATYPE_DOUBLE: - printer->Print(variables_, - "hash = (53 * hash) + com.google.protobuf.Internal.hashLong(\n" - " java.lang.Double.doubleToLongBits(get$capitalized_name$()));\n"); - break; - - case JAVATYPE_STRING: - case JAVATYPE_BYTES: - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); - break; - - case JAVATYPE_ENUM: - case JAVATYPE_MESSAGE: - default: - GOOGLE_LOG(FATAL) << "Can't get here."; - break; - } -} - -string ImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const { - return BoxedPrimitiveTypeName(GetJavaType(descriptor_)); -} - -// =================================================================== - -ImmutablePrimitiveOneofFieldLiteGenerator:: -ImmutablePrimitiveOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutablePrimitiveFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); -} - -ImmutablePrimitiveOneofFieldLiteGenerator:: -~ImmutablePrimitiveOneofFieldLiteGenerator() {} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " return ($boxed_type$) $oneof_name$_;\n" - " }\n" - " return $default$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$($type$ value) {\n" - "$null_check$" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); -} - - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // noop for primitives -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneof$visit_type$(\n" - " $has_oneof_case_message$, $oneof_name$_, other.$oneof_name$_);\n"); -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - printer->Print(variables_, - "$set_oneof_case_message$;\n" - "$oneof_name$_ = input.read$capitalized_type$();\n"); -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.write$capitalized_type$(\n" - " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n" - "}\n"); -} - -void ImmutablePrimitiveOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$Size(\n" - " $number$, ($type$)(($boxed_type$) $oneof_name$_));\n" - "}\n"); -} - -// =================================================================== - -RepeatedImmutablePrimitiveFieldLiteGenerator:: -RepeatedImmutablePrimitiveFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -RepeatedImmutablePrimitiveFieldLiteGenerator:: -~RepeatedImmutablePrimitiveFieldLiteGenerator() {} - -int RepeatedImmutablePrimitiveFieldLiteGenerator::GetNumBitsForMessage() const { - return 0; -} - -int RepeatedImmutablePrimitiveFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List<$boxed_type$> get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$$type$ get$capitalized_name$(int index);\n"); -} - - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private $field_list_type$ $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$boxed_type$>\n" - " ${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return $repeated_get$(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - if (descriptor_->is_packed() && - context_->HasGeneratedMethods(descriptor_->containing_type())) { - printer->Print(variables_, - "private int $name$MemoizedSerializedSize = -1;\n"); - } - - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, $type$ value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $repeated_set$(index, value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$($type$ value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $repeated_add$(value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.addAll(\n" - " values, $name$_);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = $empty_list$;\n" - "}\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List<$boxed_type$>\n" - " ${$get$capitalized_name$List$}$() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$List());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Count();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, $type$ value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for primitives -} - - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $empty_list$;\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - // noop for primitives -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_= visitor.$visit_type_list$($name$_, other.$name$_);\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // noop for primitives -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - // TODO(dweis): Scan the input buffer to count, then initialize - // appropriately. - // TODO(dweis): Scan the input buffer to count and ensure capacity. - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n" - "$repeated_add$(input.read$capitalized_type$());\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingCodeFromPacked(io::Printer* printer) const { - printer->Print(variables_, - "int length = input.readRawVarint32();\n" - "int limit = input.pushLimit(length);\n" - "if (!$is_mutable$ && input.getBytesUntilLimit() > 0) {\n"); - - int fixed_size = FixedSize(GetType(descriptor_)); - if (fixed_size == -1) { - // TODO(dweis): Scan the input buffer to count, then initialize - // appropriately. - printer->Print(variables_, - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n"); - } else { - printer->Print(variables_, - " final int currentSize = $name$_.size();\n" - " $name$_ = $name$_.mutableCopyWithCapacity(\n" - " currentSize + (length/$fixed_size$));\n"); - } - - // TODO(dweis): Scan the input buffer to count and ensure capacity. - printer->Print(variables_, - "}\n" - "while (input.getBytesUntilLimit() > 0) {\n" - " $repeated_add$(input.read$capitalized_type$());\n" - "}\n" - "input.popLimit(limit);\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_mutable$) {\n" - " $make_name_unmodifiable$;\n" - "}\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - if (descriptor_->is_packed()) { - // We invoke getSerializedSize in writeTo for messages that have packed - // fields in ImmutableMessageGenerator::GenerateMessageSerializationMethods. - // That makes it safe to rely on the memoized size here. - printer->Print(variables_, - "if (get$capitalized_name$List().size() > 0) {\n" - " output.writeUInt32NoTag($tag$);\n" - " output.writeUInt32NoTag($name$MemoizedSerializedSize);\n" - "}\n" - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$capitalized_type$NoTag($repeated_get$(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.write$capitalized_type$($number$, $repeated_get$(i));\n" - "}\n"); - } -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - if (FixedSize(GetType(descriptor_)) == -1) { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .compute$capitalized_type$SizeNoTag($repeated_get$(i));\n" - "}\n"); - } else { - printer->Print(variables_, - "dataSize = $fixed_size$ * get$capitalized_name$List().size();\n"); - } - - printer->Print( - "size += dataSize;\n"); - - if (descriptor_->is_packed()) { - printer->Print(variables_, - "if (!get$capitalized_name$List().isEmpty()) {\n" - " size += $tag_size$;\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeInt32SizeNoTag(dataSize);\n" - "}\n"); - } else { - printer->Print(variables_, - "size += $tag_size$ * get$capitalized_name$List().size();\n"); - } - - // cache the data size for packed fields. - if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutablePrimitiveFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); -} - -string RepeatedImmutablePrimitiveFieldLiteGenerator::GetBoxedType() const { - return BoxedPrimitiveTypeName(GetJavaType(descriptor_)); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_primitive_field_lite.h b/windows/include/google/protobuf/compiler/java/java_primitive_field_lite.h deleted file mode 100644 index 93416f0b6..000000000 --- a/windows/include/google/protobuf/compiler/java/java_primitive_field_lite.h +++ /dev/null @@ -1,166 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_LITE_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutablePrimitiveFieldLiteGenerator - : public ImmutableFieldLiteGenerator { - public: - explicit ImmutablePrimitiveFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutablePrimitiveFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutablePrimitiveFieldLiteGenerator); -}; - -class ImmutablePrimitiveOneofFieldLiteGenerator - : public ImmutablePrimitiveFieldLiteGenerator { - public: - ImmutablePrimitiveOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutablePrimitiveOneofFieldLiteGenerator(); - - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutablePrimitiveOneofFieldLiteGenerator); -}; - -class RepeatedImmutablePrimitiveFieldLiteGenerator - : public ImmutableFieldLiteGenerator { - public: - explicit RepeatedImmutablePrimitiveFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - virtual ~RepeatedImmutablePrimitiveFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingCodeFromPacked(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutablePrimitiveFieldLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_PRIMITIVE_FIELD_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_service.cc b/windows/include/google/protobuf/compiler/java/java_service.cc deleted file mode 100644 index 988e1942b..000000000 --- a/windows/include/google/protobuf/compiler/java/java_service.cc +++ /dev/null @@ -1,473 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor) - : descriptor_(descriptor) {} - -ServiceGenerator::~ServiceGenerator() {} - -// =================================================================== -ImmutableServiceGenerator::ImmutableServiceGenerator( - const ServiceDescriptor* descriptor, Context* context) - : ServiceGenerator(descriptor), context_(context), - name_resolver_(context->GetNameResolver()) {} - -ImmutableServiceGenerator::~ImmutableServiceGenerator() {} - -void ImmutableServiceGenerator::Generate(io::Printer* printer) { - bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true); - WriteServiceDocComment(printer, descriptor_); - MaybePrintGeneratedAnnotation(context_, printer, descriptor_, - /* immutable = */ true); - printer->Print( - "public $static$ abstract class $classname$\n" - " implements com.google.protobuf.Service {\n", - "static", is_own_file ? "" : "static", - "classname", descriptor_->name()); - printer->Indent(); - - printer->Print( - "protected $classname$() {}\n\n", - "classname", descriptor_->name()); - - GenerateInterface(printer); - - GenerateNewReflectiveServiceMethod(printer); - GenerateNewReflectiveBlockingServiceMethod(printer); - - GenerateAbstractMethods(printer); - - // Generate getDescriptor() and getDescriptorForType(). - printer->Print( - "public static final\n" - " com.google.protobuf.Descriptors.ServiceDescriptor\n" - " getDescriptor() {\n" - " return $file$.getDescriptor().getServices().get($index$);\n" - "}\n", - "file", name_resolver_->GetImmutableClassName(descriptor_->file()), - "index", SimpleItoa(descriptor_->index())); - GenerateGetDescriptorForType(printer); - - // Generate more stuff. - GenerateCallMethod(printer); - GenerateGetPrototype(REQUEST, printer); - GenerateGetPrototype(RESPONSE, printer); - GenerateStub(printer); - GenerateBlockingStub(printer); - - // Add an insertion point. - printer->Print( - "\n" - "// @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", descriptor_->full_name()); - - printer->Outdent(); - printer->Print("}\n\n"); -} - -void ImmutableServiceGenerator::GenerateGetDescriptorForType( - io::Printer* printer) { - printer->Print( - "public final com.google.protobuf.Descriptors.ServiceDescriptor\n" - " getDescriptorForType() {\n" - " return getDescriptor();\n" - "}\n"); -} - -void ImmutableServiceGenerator::GenerateInterface(io::Printer* printer) { - printer->Print("public interface Interface {\n"); - printer->Indent(); - GenerateAbstractMethods(printer); - printer->Outdent(); - printer->Print("}\n\n"); -} - -void ImmutableServiceGenerator::GenerateNewReflectiveServiceMethod( - io::Printer* printer) { - printer->Print( - "public static com.google.protobuf.Service newReflectiveService(\n" - " final Interface impl) {\n" - " return new $classname$() {\n", - "classname", descriptor_->name()); - printer->Indent(); - printer->Indent(); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - printer->Print("@java.lang.Override\n"); - GenerateMethodSignature(printer, method, IS_CONCRETE); - printer->Print( - " {\n" - " impl.$method$(controller, request, done);\n" - "}\n\n", - "method", UnderscoresToCamelCase(method)); - } - - printer->Outdent(); - printer->Print("};\n"); - printer->Outdent(); - printer->Print("}\n\n"); -} - -void ImmutableServiceGenerator::GenerateNewReflectiveBlockingServiceMethod( - io::Printer* printer) { - printer->Print( - "public static com.google.protobuf.BlockingService\n" - " newReflectiveBlockingService(final BlockingInterface impl) {\n" - " return new com.google.protobuf.BlockingService() {\n"); - printer->Indent(); - printer->Indent(); - - GenerateGetDescriptorForType(printer); - - GenerateCallBlockingMethod(printer); - GenerateGetPrototype(REQUEST, printer); - GenerateGetPrototype(RESPONSE, printer); - - printer->Outdent(); - printer->Print("};\n"); - printer->Outdent(); - printer->Print("}\n\n"); -} - -void ImmutableServiceGenerator::GenerateAbstractMethods(io::Printer* printer) { - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - WriteMethodDocComment(printer, method); - GenerateMethodSignature(printer, method, IS_ABSTRACT); - printer->Print(";\n\n"); - } -} - -string ImmutableServiceGenerator::GetOutput(const MethodDescriptor* method) { - return name_resolver_->GetImmutableClassName(method->output_type()); -} - -void ImmutableServiceGenerator::GenerateCallMethod(io::Printer* printer) { - printer->Print( - "\n" - "public final void callMethod(\n" - " com.google.protobuf.Descriptors.MethodDescriptor method,\n" - " com.google.protobuf.RpcController controller,\n" - " com.google.protobuf.Message request,\n" - " com.google.protobuf.RpcCallback<\n" - " com.google.protobuf.Message> done) {\n" - " if (method.getService() != getDescriptor()) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Service.callMethod() given method descriptor for wrong \" +\n" - " \"service type.\");\n" - " }\n" - " switch(method.getIndex()) {\n"); - printer->Indent(); - printer->Indent(); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - std::map vars; - vars["index"] = SimpleItoa(i); - vars["method"] = UnderscoresToCamelCase(method); - vars["input"] = name_resolver_->GetImmutableClassName( - method->input_type()); - vars["output"] = GetOutput(method); - printer->Print(vars, - "case $index$:\n" - " this.$method$(controller, ($input$)request,\n" - " com.google.protobuf.RpcUtil.<$output$>specializeCallback(\n" - " done));\n" - " return;\n"); - } - - printer->Print( - "default:\n" - " throw new java.lang.AssertionError(\"Can't get here.\");\n"); - - printer->Outdent(); - printer->Outdent(); - - printer->Print( - " }\n" - "}\n" - "\n"); -} - -void ImmutableServiceGenerator::GenerateCallBlockingMethod( - io::Printer* printer) { - printer->Print( - "\n" - "public final com.google.protobuf.Message callBlockingMethod(\n" - " com.google.protobuf.Descriptors.MethodDescriptor method,\n" - " com.google.protobuf.RpcController controller,\n" - " com.google.protobuf.Message request)\n" - " throws com.google.protobuf.ServiceException {\n" - " if (method.getService() != getDescriptor()) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Service.callBlockingMethod() given method descriptor for \" +\n" - " \"wrong service type.\");\n" - " }\n" - " switch(method.getIndex()) {\n"); - printer->Indent(); - printer->Indent(); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - std::map vars; - vars["index"] = SimpleItoa(i); - vars["method"] = UnderscoresToCamelCase(method); - vars["input"] = name_resolver_->GetImmutableClassName( - method->input_type()); - vars["output"] = GetOutput(method); - printer->Print(vars, - "case $index$:\n" - " return impl.$method$(controller, ($input$)request);\n"); - } - - printer->Print( - "default:\n" - " throw new java.lang.AssertionError(\"Can't get here.\");\n"); - - printer->Outdent(); - printer->Outdent(); - - printer->Print( - " }\n" - "}\n" - "\n"); -} - -void ImmutableServiceGenerator::GenerateGetPrototype(RequestOrResponse which, - io::Printer* printer) { - /* - * TODO(cpovirk): The exception message says "Service.foo" when it may be - * "BlockingService.foo." Consider fixing. - */ - printer->Print( - "public final com.google.protobuf.Message\n" - " get$request_or_response$Prototype(\n" - " com.google.protobuf.Descriptors.MethodDescriptor method) {\n" - " if (method.getService() != getDescriptor()) {\n" - " throw new java.lang.IllegalArgumentException(\n" - " \"Service.get$request_or_response$Prototype() given method \" +\n" - " \"descriptor for wrong service type.\");\n" - " }\n" - " switch(method.getIndex()) {\n", - "request_or_response", (which == REQUEST) ? "Request" : "Response"); - printer->Indent(); - printer->Indent(); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - std::map vars; - vars["index"] = SimpleItoa(i); - vars["type"] = name_resolver_->GetImmutableClassName( - (which == REQUEST) ? method->input_type() : method->output_type()); - printer->Print(vars, - "case $index$:\n" - " return $type$.getDefaultInstance();\n"); - } - - printer->Print( - "default:\n" - " throw new java.lang.AssertionError(\"Can't get here.\");\n"); - - printer->Outdent(); - printer->Outdent(); - - printer->Print( - " }\n" - "}\n" - "\n"); -} - -void ImmutableServiceGenerator::GenerateStub(io::Printer* printer) { - printer->Print( - "public static Stub newStub(\n" - " com.google.protobuf.RpcChannel channel) {\n" - " return new Stub(channel);\n" - "}\n" - "\n" - "public static final class Stub extends $classname$ implements Interface {" - "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - printer->Indent(); - - printer->Print( - "private Stub(com.google.protobuf.RpcChannel channel) {\n" - " this.channel = channel;\n" - "}\n" - "\n" - "private final com.google.protobuf.RpcChannel channel;\n" - "\n" - "public com.google.protobuf.RpcChannel getChannel() {\n" - " return channel;\n" - "}\n"); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - printer->Print("\n"); - GenerateMethodSignature(printer, method, IS_CONCRETE); - printer->Print(" {\n"); - printer->Indent(); - - std::map vars; - vars["index"] = SimpleItoa(i); - vars["output"] = GetOutput(method); - printer->Print(vars, - "channel.callMethod(\n" - " getDescriptor().getMethods().get($index$),\n" - " controller,\n" - " request,\n" - " $output$.getDefaultInstance(),\n" - " com.google.protobuf.RpcUtil.generalizeCallback(\n" - " done,\n" - " $output$.class,\n" - " $output$.getDefaultInstance()));\n"); - - printer->Outdent(); - printer->Print("}\n"); - } - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); -} - -void ImmutableServiceGenerator::GenerateBlockingStub(io::Printer* printer) { - printer->Print( - "public static BlockingInterface newBlockingStub(\n" - " com.google.protobuf.BlockingRpcChannel channel) {\n" - " return new BlockingStub(channel);\n" - "}\n" - "\n"); - - printer->Print( - "public interface BlockingInterface {"); - printer->Indent(); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - GenerateBlockingMethodSignature(printer, method); - printer->Print(";\n"); - } - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - - printer->Print( - "private static final class BlockingStub implements BlockingInterface {\n"); - printer->Indent(); - - printer->Print( - "private BlockingStub(com.google.protobuf.BlockingRpcChannel channel) {\n" - " this.channel = channel;\n" - "}\n" - "\n" - "private final com.google.protobuf.BlockingRpcChannel channel;\n"); - - for (int i = 0; i < descriptor_->method_count(); i++) { - const MethodDescriptor* method = descriptor_->method(i); - GenerateBlockingMethodSignature(printer, method); - printer->Print(" {\n"); - printer->Indent(); - - std::map vars; - vars["index"] = SimpleItoa(i); - vars["output"] = GetOutput(method); - printer->Print(vars, - "return ($output$) channel.callBlockingMethod(\n" - " getDescriptor().getMethods().get($index$),\n" - " controller,\n" - " request,\n" - " $output$.getDefaultInstance());\n"); - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void ImmutableServiceGenerator::GenerateMethodSignature(io::Printer* printer, - const MethodDescriptor* method, - IsAbstract is_abstract) { - std::map vars; - vars["name"] = UnderscoresToCamelCase(method); - vars["input"] = name_resolver_->GetImmutableClassName(method->input_type()); - vars["output"] = GetOutput(method); - vars["abstract"] = (is_abstract == IS_ABSTRACT) ? "abstract" : ""; - printer->Print(vars, - "public $abstract$ void $name$(\n" - " com.google.protobuf.RpcController controller,\n" - " $input$ request,\n" - " com.google.protobuf.RpcCallback<$output$> done)"); -} - -void ImmutableServiceGenerator::GenerateBlockingMethodSignature( - io::Printer* printer, - const MethodDescriptor* method) { - std::map vars; - vars["method"] = UnderscoresToCamelCase(method); - vars["input"] = name_resolver_->GetImmutableClassName(method->input_type()); - vars["output"] = GetOutput(method); - printer->Print(vars, - "\n" - "public $output$ $method$(\n" - " com.google.protobuf.RpcController controller,\n" - " $input$ request)\n" - " throws com.google.protobuf.ServiceException"); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_service.h b/windows/include/google/protobuf/compiler/java/java_service.h deleted file mode 100644 index 12b3f9426..000000000 --- a/windows/include/google/protobuf/compiler/java/java_service.h +++ /dev/null @@ -1,138 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_SERVICE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_SERVICE_H__ - -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ServiceGenerator { - public: - explicit ServiceGenerator(const ServiceDescriptor* descriptor); - virtual ~ServiceGenerator(); - - virtual void Generate(io::Printer* printer) = 0; - - enum RequestOrResponse { REQUEST, RESPONSE }; - enum IsAbstract { IS_ABSTRACT, IS_CONCRETE }; - - protected: - const ServiceDescriptor* descriptor_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceGenerator); -}; - -class ImmutableServiceGenerator : public ServiceGenerator { - public: - ImmutableServiceGenerator(const ServiceDescriptor* descriptor, - Context* context); - virtual ~ImmutableServiceGenerator(); - - virtual void Generate(io::Printer* printer); - - private: - - // Generate the getDescriptorForType() method. - void GenerateGetDescriptorForType(io::Printer* printer); - - // Generate a Java interface for the service. - void GenerateInterface(io::Printer* printer); - - // Generate newReflectiveService() method. - void GenerateNewReflectiveServiceMethod(io::Printer* printer); - - // Generate newReflectiveBlockingService() method. - void GenerateNewReflectiveBlockingServiceMethod(io::Printer* printer); - - // Generate abstract method declarations for all methods. - void GenerateAbstractMethods(io::Printer* printer); - - // Generate the implementation of Service.callMethod(). - void GenerateCallMethod(io::Printer* printer); - - // Generate the implementation of BlockingService.callBlockingMethod(). - void GenerateCallBlockingMethod(io::Printer* printer); - - // Generate the implementations of Service.get{Request,Response}Prototype(). - void GenerateGetPrototype(RequestOrResponse which, io::Printer* printer); - - // Generate a stub implementation of the service. - void GenerateStub(io::Printer* printer); - - // Generate a method signature, possibly abstract, without body or trailing - // semicolon. - void GenerateMethodSignature(io::Printer* printer, - const MethodDescriptor* method, - IsAbstract is_abstract); - - // Generate a blocking stub interface and implementation of the service. - void GenerateBlockingStub(io::Printer* printer); - - // Generate the method signature for one method of a blocking stub. - void GenerateBlockingMethodSignature(io::Printer* printer, - const MethodDescriptor* method); - - // Return the output type of the method. - string GetOutput(const MethodDescriptor* method); - - Context* context_; - ClassNameResolver* name_resolver_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableServiceGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -#endif // NET_PROTO2_COMPILER_JAVA_SERVICE_H__ -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_shared_code_generator.cc b/windows/include/google/protobuf/compiler/java/java_shared_code_generator.cc deleted file mode 100644 index 0cec20b97..000000000 --- a/windows/include/google/protobuf/compiler/java/java_shared_code_generator.cc +++ /dev/null @@ -1,219 +0,0 @@ -// 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. - -// Author: xiaofeng@google.com (Feng Xiao) - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -SharedCodeGenerator::SharedCodeGenerator(const FileDescriptor* file, - const Options& options) - : name_resolver_(new ClassNameResolver), file_(file), options_(options) {} - -SharedCodeGenerator::~SharedCodeGenerator() { -} - -void SharedCodeGenerator::Generate(GeneratorContext* context, - std::vector* file_list, - std::vector* annotation_file_list) { - string java_package = FileJavaPackage(file_); - string package_dir = JavaPackageToDir(java_package); - - if (HasDescriptorMethods(file_, options_.enforce_lite)) { - // Generate descriptors. - string classname = name_resolver_->GetDescriptorClassName(file_); - string filename = package_dir + classname + ".java"; - file_list->push_back(filename); - std::unique_ptr output(context->Open(filename)); - GeneratedCodeInfo annotations; - io::AnnotationProtoCollector annotation_collector( - &annotations); - std::unique_ptr printer( - new io::Printer(output.get(), '$', - options_.annotate_code ? &annotation_collector : NULL)); - string info_relative_path = classname + ".java.pb.meta"; - string info_full_path = filename + ".pb.meta"; - printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n", - "filename", file_->name()); - if (!java_package.empty()) { - printer->Print( - "package $package$;\n" - "\n", - "package", java_package); - } - PrintGeneratedAnnotation(printer.get(), '$', - options_.annotate_code ? info_relative_path : ""); - printer->Print( - "public final class $classname$ {\n" - " public static com.google.protobuf.Descriptors.FileDescriptor\n" - " descriptor;\n" - " static {\n", - "classname", classname); - printer->Annotate("classname", file_->name()); - printer->Indent(); - printer->Indent(); - GenerateDescriptors(printer.get()); - printer->Outdent(); - printer->Outdent(); - printer->Print( - " }\n" - "}\n"); - - if (options_.annotate_code) { - std::unique_ptr info_output( - context->Open(info_full_path)); - annotations.SerializeToZeroCopyStream(info_output.get()); - annotation_file_list->push_back(info_full_path); - } - - printer.reset(); - output.reset(); - } -} - -void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) { - // Embed the descriptor. We simply serialize the entire FileDescriptorProto - // and embed it as a string literal, which is parsed and built into real - // descriptors at initialization time. We unfortunately have to put it in - // a string literal, not a byte array, because apparently using a literal - // byte array causes the Java compiler to generate *instructions* to - // initialize each and every byte of the array, e.g. as if you typed: - // b[0] = 123; b[1] = 456; b[2] = 789; - // This makes huge bytecode files and can easily hit the compiler's internal - // code size limits (error "code to large"). String literals are apparently - // embedded raw, which is what we want. - FileDescriptorProto file_proto; - file_->CopyTo(&file_proto); - - string file_data; - file_proto.SerializeToString(&file_data); - - printer->Print( - "java.lang.String[] descriptorData = {\n"); - printer->Indent(); - - // Limit the number of bytes per line. - static const int kBytesPerLine = 40; - // Limit the number of lines per string part. - static const int kLinesPerPart = 400; - // Every block of bytes, start a new string literal, in order to avoid the - // 64k length limit. Note that this value needs to be <64k. - static const int kBytesPerPart = kBytesPerLine * kLinesPerPart; - for (int i = 0; i < file_data.size(); i += kBytesPerLine) { - if (i > 0) { - if (i % kBytesPerPart == 0) { - printer->Print(",\n"); - } else { - printer->Print(" +\n"); - } - } - printer->Print("\"$data$\"", - "data", CEscape(file_data.substr(i, kBytesPerLine))); - } - - printer->Outdent(); - printer->Print("\n};\n"); - - // ----------------------------------------------------------------- - // Create the InternalDescriptorAssigner. - - printer->Print( - "com.google.protobuf.Descriptors.FileDescriptor." - "InternalDescriptorAssigner assigner =\n" - " new com.google.protobuf.Descriptors.FileDescriptor." - " InternalDescriptorAssigner() {\n" - " public com.google.protobuf.ExtensionRegistry assignDescriptors(\n" - " com.google.protobuf.Descriptors.FileDescriptor root) {\n" - " descriptor = root;\n" - // Custom options will be handled when immutable messages' outer class is - // loaded. Here we just return null and let custom options be unknown - // fields. - " return null;\n" - " }\n" - " };\n"); - - // ----------------------------------------------------------------- - // Find out all dependencies. - std::vector > dependencies; - for (int i = 0; i < file_->dependency_count(); i++) { - string filename = file_->dependency(i)->name(); - string package = FileJavaPackage(file_->dependency(i)); - string classname = name_resolver_->GetDescriptorClassName( - file_->dependency(i)); - string full_name; - if (package.empty()) { - full_name = classname; - } else { - full_name = package + "." + classname; - } - dependencies.push_back(std::make_pair(filename, full_name)); - } - - // ----------------------------------------------------------------- - // Invoke internalBuildGeneratedFileFrom() to build the file. - printer->Print( - "com.google.protobuf.Descriptors.FileDescriptor\n" - " .internalBuildGeneratedFileFrom(descriptorData,\n"); - printer->Print( - " new com.google.protobuf.Descriptors.FileDescriptor[] {\n"); - - for (int i = 0; i < dependencies.size(); i++) { - const string& dependency = dependencies[i].second; - printer->Print( - " $dependency$.getDescriptor(),\n", - "dependency", dependency); - } - - printer->Print( - " }, assigner);\n"); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_shared_code_generator.h b/windows/include/google/protobuf/compiler/java/java_shared_code_generator.h deleted file mode 100644 index 58a31f5d7..000000000 --- a/windows/include/google/protobuf/compiler/java/java_shared_code_generator.h +++ /dev/null @@ -1,89 +0,0 @@ -// 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. - -// Author: xiaofeng@google.com (Feng Xiao) -// -// Generators that generate shared code between immutable API and mutable API. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__ - -#include -#include -#include - -#include -#include - -namespace google { -namespace protobuf { - class FileDescriptor; // descriptor.h - namespace compiler { - class GeneratorContext; // code_generator.h - namespace java { - class ClassNameResolver; // name_resolver.h - } - } - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -// A generator that generates code that are shared between immutable API -// and mutable API. Currently only descriptors are shared. -class SharedCodeGenerator { - public: - SharedCodeGenerator(const FileDescriptor* file, const Options& options); - ~SharedCodeGenerator(); - - void Generate(GeneratorContext* generator_context, - std::vector* file_list, - std::vector* annotation_file_list); - - void GenerateDescriptors(io::Printer* printer); - - private: - std::unique_ptr name_resolver_; - const FileDescriptor* file_; - const Options options_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SharedCodeGenerator); -}; - - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_string_field.cc b/windows/include/google/protobuf/compiler/java/java_string_field.cc deleted file mode 100644 index 2b6e93818..000000000 --- a/windows/include/google/protobuf/compiler/java/java_string_field.cc +++ /dev/null @@ -1,1039 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Author: jonp@google.com (Jon Perlow) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -void SetPrimitiveVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - ClassNameResolver* name_resolver, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - - (*variables)["empty_list"] = "com.google.protobuf.LazyStringArrayList.EMPTY"; - - (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["default_init"] = - "= " + ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["capitalized_type"] = "String"; - (*variables)["tag"] = - SimpleItoa(static_cast(WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( - WireFormat::TagSize(descriptor->number(), GetType(descriptor))); - (*variables)["null_check"] = - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n"; - (*variables)["writeString"] = - "com.google.protobuf.GeneratedMessage" + GeneratedCodeVersionSuffix() + - ".writeString"; - (*variables)["computeStringSize"] = - "com.google.protobuf.GeneratedMessage" + GeneratedCodeVersionSuffix() + - ".computeStringSize"; - - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - (*variables)["on_changed"] = "onChanged();"; - - if (SupportFieldPresence(descriptor->file())) { - // For singular messages and builders, one bit is used for the hasField bit. - (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); - (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex); - - // Note that these have a trailing ";". - (*variables)["set_has_field_bit_message"] = - GenerateSetBit(messageBitIndex) + ";"; - (*variables)["set_has_field_bit_builder"] = - GenerateSetBit(builderBitIndex) + ";"; - (*variables)["clear_has_field_bit_builder"] = - GenerateClearBit(builderBitIndex) + ";"; - - (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); - } else { - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["set_has_field_bit_builder"] = ""; - (*variables)["clear_has_field_bit_builder"] = ""; - - (*variables)["is_field_present_message"] = - "!get" + (*variables)["capitalized_name"] + "Bytes().isEmpty()"; - } - - // For repeated builders, one bit is used for whether the array is immutable. - (*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex); - (*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex); - (*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex); - - // For repeated fields, one bit is used for whether the array is immutable - // in the parsing constructor. - (*variables)["get_mutable_bit_parser"] = - GenerateGetBitMutableLocal(builderBitIndex); - (*variables)["set_mutable_bit_parser"] = - GenerateSetBitMutableLocal(builderBitIndex); - - (*variables)["get_has_field_bit_from_local"] = - GenerateGetBitFromLocal(builderBitIndex); - (*variables)["set_has_field_bit_to_local"] = - GenerateSetBitToLocal(messageBitIndex); -} - -} // namespace - -// =================================================================== - -ImmutableStringFieldGenerator:: -ImmutableStringFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -ImmutableStringFieldGenerator::~ImmutableStringFieldGenerator() {} - -int ImmutableStringFieldGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutableStringFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -// A note about how strings are handled. This code used to just store a String -// in the Message. This had two issues: -// -// 1. It wouldn't roundtrip byte arrays that were not vaid UTF-8 encoded -// strings, but rather fields that were raw bytes incorrectly marked -// as strings in the proto file. This is common because in the proto1 -// syntax, string was the way to indicate bytes and C++ engineers can -// easily make this mistake without affecting the C++ API. By converting to -// strings immediately, some java code might corrupt these byte arrays as -// it passes through a java server even if the field was never accessed by -// application code. -// -// 2. There's a performance hit to converting between bytes and strings and -// it many cases, the field is never even read by the application code. This -// avoids unnecessary conversions in the common use cases. -// -// So now, the field for String is maintained as an Object reference which can -// either store a String or a ByteString. The code uses an instanceof check -// to see which one it has and converts to the other one if needed. It remembers -// the last value requested (in a thread safe manner) as this is most likely -// the one needed next. The thread safety is such that if two threads both -// convert the field because the changes made by each thread were not visible to -// the other, they may cause a conversion to happen more times than would -// otherwise be necessary. This was deemed better than adding synchronization -// overhead. It will not cause any corruption issues or affect the behavior of -// the API. The instanceof check is also highly optimized in the JVM and we -// decided it was better to reduce the memory overhead by not having two -// separate fields but rather use dynamic type checking. -// -// For single fields, the logic for this is done inside the generated code. For -// repeated fields, the logic is done in LazyStringArrayList and -// UnmodifiableLazyStringList. -void ImmutableStringFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes();\n"); -} - -void ImmutableStringFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private volatile java.lang.Object $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.Object ref = $name$_;\n" - " if (ref instanceof java.lang.String) {\n" - " return (java.lang.String) ref;\n" - " } else {\n" - " com.google.protobuf.ByteString bs = \n" - " (com.google.protobuf.ByteString) ref;\n" - " java.lang.String s = bs.toStringUtf8();\n"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " $name$_ = s;\n"); - } else { - printer->Print(variables_, - " if (bs.isValidUtf8()) {\n" - " $name$_ = s;\n" - " }\n"); - } - printer->Print(variables_, - " return s;\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.Object ref = $name$_;\n" - " if (ref instanceof java.lang.String) {\n" - " com.google.protobuf.ByteString b = \n" - " com.google.protobuf.ByteString.copyFromUtf8(\n" - " (java.lang.String) ref);\n" - " $name$_ = b;\n" - " return b;\n" - " } else {\n" - " return (com.google.protobuf.ByteString) ref;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableStringFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.lang.Object $name$_ $default_init$;\n"); - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_builder$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.Object ref = $name$_;\n" - " if (!(ref instanceof java.lang.String)) {\n" - " com.google.protobuf.ByteString bs =\n" - " (com.google.protobuf.ByteString) ref;\n" - " java.lang.String s = bs.toStringUtf8();\n"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " $name$_ = s;\n"); - } else { - printer->Print(variables_, - " if (bs.isValidUtf8()) {\n" - " $name$_ = s;\n" - " }\n"); - } - printer->Print(variables_, - " return s;\n" - " } else {\n" - " return (java.lang.String) ref;\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.Object ref = $name$_;\n" - " if (ref instanceof String) {\n" - " com.google.protobuf.ByteString b = \n" - " com.google.protobuf.ByteString.copyFromUtf8(\n" - " (java.lang.String) ref);\n" - " $name$_ = b;\n" - " return b;\n" - " } else {\n" - " return (com.google.protobuf.ByteString) ref;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - "$null_check$" - " $set_has_field_bit_builder$\n" - " $name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $clear_has_field_bit_builder$\n"); - printer->Annotate("{", "}", descriptor_); - // The default value is not a simple literal so we want to avoid executing - // it multiple times. Instead, get the default out of the default instance. - printer->Print(variables_, - " $name$_ = getDefaultInstance().get$capitalized_name$();\n"); - printer->Print(variables_, - " $on_changed$\n" - " return this;\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); - } - printer->Print(variables_, - " $set_has_field_bit_builder$\n" - " $name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); -} - -void ImmutableStringFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for primitives -} - -void ImmutableStringFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void ImmutableStringFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = $default$;\n" - "$clear_has_field_bit_builder$\n"); -} - -void ImmutableStringFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - // Allow a slight breach of abstraction here in order to avoid forcing - // all string fields to Strings when copying fields from a Message. - printer->Print(variables_, - "if (other.has$capitalized_name$()) {\n" - " $set_has_field_bit_builder$\n" - " $name$_ = other.$name$_;\n" - " $on_changed$\n" - "}\n"); - } else { - printer->Print(variables_, - "if (!other.get$capitalized_name$().isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $on_changed$\n" - "}\n"); - } -} - -void ImmutableStringFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "if ($get_has_field_bit_from_local$) {\n" - " $set_has_field_bit_to_local$;\n" - "}\n"); - } - printer->Print(variables_, - "result.$name$_ = $name$_;\n"); -} - -void ImmutableStringFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n" - "$set_has_field_bit_message$\n" - "$name$_ = s;\n"); - } else { - printer->Print(variables_, - "com.google.protobuf.ByteString bs = input.readBytes();\n" - "$set_has_field_bit_message$\n" - "$name$_ = bs;\n"); - } -} - -void ImmutableStringFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for strings. -} - -void ImmutableStringFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " $writeString$(output, $number$, $name$_);\n" - "}\n"); -} - -void ImmutableStringFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += $computeStringSize$($number$, $name$_);\n" - "}\n"); -} - -void ImmutableStringFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); -} - -void ImmutableStringFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n"); - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); -} - -string ImmutableStringFieldGenerator::GetBoxedType() const { - return "java.lang.String"; -} - -// =================================================================== - -ImmutableStringOneofFieldGenerator:: -ImmutableStringOneofFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableStringFieldGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); -} - -ImmutableStringOneofFieldGenerator:: -~ImmutableStringOneofFieldGenerator() {} - -void ImmutableStringOneofFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.Object ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = $oneof_name$_;\n" - " }\n" - " if (ref instanceof java.lang.String) {\n" - " return (java.lang.String) ref;\n" - " } else {\n" - " com.google.protobuf.ByteString bs = \n" - " (com.google.protobuf.ByteString) ref;\n" - " java.lang.String s = bs.toStringUtf8();\n"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " if ($has_oneof_case_message$) {\n" - " $oneof_name$_ = s;\n" - " }\n"); - } else { - printer->Print(variables_, - " if (bs.isValidUtf8() && ($has_oneof_case_message$)) {\n" - " $oneof_name$_ = s;\n" - " }\n"); - } - printer->Print(variables_, - " return s;\n" - " }\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.Object ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = $oneof_name$_;\n" - " }\n" - " if (ref instanceof java.lang.String) {\n" - " com.google.protobuf.ByteString b = \n" - " com.google.protobuf.ByteString.copyFromUtf8(\n" - " (java.lang.String) ref);\n" - " if ($has_oneof_case_message$) {\n" - " $oneof_name$_ = b;\n" - " }\n" - " return b;\n" - " } else {\n" - " return (com.google.protobuf.ByteString) ref;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableStringOneofFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.Object ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = $oneof_name$_;\n" - " }\n" - " if (!(ref instanceof java.lang.String)) {\n" - " com.google.protobuf.ByteString bs =\n" - " (com.google.protobuf.ByteString) ref;\n" - " java.lang.String s = bs.toStringUtf8();\n" - " if ($has_oneof_case_message$) {\n"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " $oneof_name$_ = s;\n"); - } else { - printer->Print(variables_, - " if (bs.isValidUtf8()) {\n" - " $oneof_name$_ = s;\n" - " }\n"); - } - printer->Print(variables_, - " }\n" - " return s;\n" - " } else {\n" - " return (java.lang.String) ref;\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.Object ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = $oneof_name$_;\n" - " }\n" - " if (ref instanceof String) {\n" - " com.google.protobuf.ByteString b = \n" - " com.google.protobuf.ByteString.copyFromUtf8(\n" - " (java.lang.String) ref);\n" - " if ($has_oneof_case_message$) {\n" - " $oneof_name$_ = b;\n" - " }\n" - " return b;\n" - " } else {\n" - " return (com.google.protobuf.ByteString) ref;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - "$null_check$" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " $on_changed$\n" - " }\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); - } - printer->Print(variables_, - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); -} - -void ImmutableStringOneofFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - // Allow a slight breach of abstraction here in order to avoid forcing - // all string fields to Strings when copying fields from a Message. - printer->Print(variables_, - "$set_oneof_case_message$;\n" - "$oneof_name$_ = other.$oneof_name$_;\n" - "$on_changed$\n"); -} - -void ImmutableStringOneofFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " result.$oneof_name$_ = $oneof_name$_;\n" - "}\n"); -} - -void ImmutableStringOneofFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = s;\n"); - } else { - printer->Print(variables_, - "com.google.protobuf.ByteString bs = input.readBytes();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = bs;\n"); - } -} - -void ImmutableStringOneofFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " $writeString$(output, $number$, $oneof_name$_);\n" - "}\n"); -} - -void ImmutableStringOneofFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += $computeStringSize$($number$, $oneof_name$_);\n" - "}\n"); -} - -// =================================================================== - -RepeatedImmutableStringFieldGenerator:: -RepeatedImmutableStringFieldGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -RepeatedImmutableStringFieldGenerator:: -~RepeatedImmutableStringFieldGenerator() {} - -int RepeatedImmutableStringFieldGenerator::GetNumBitsForMessage() const { - return 0; -} - -int RepeatedImmutableStringFieldGenerator::GetNumBitsForBuilder() const { - return 1; -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - // NOTE: the same method in the implementation class actually returns - // com.google.protobuf.ProtocolStringList (a subclass of List). It's - // changed between protobuf 2.5.0 release and protobuf 2.6.1 release. - // To retain binary compatibility with both 2.5.0 and 2.6.1 generated - // code, we make this interface method return List so both methods - // with different return types exist in the compiled byte code. - "$deprecation$java.util.List\n" - " get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$(int index);\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes(int index);\n"); -} - - -void RepeatedImmutableStringFieldGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.LazyStringList $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ProtocolStringList\n" - " ${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String " - "${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$(int index) {\n" - " return $name$_.getByteString(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - // One field is the list and the bit field keeps track of whether the - // list is immutable. If it's immutable, the invariant is that it must - // either an instance of Collections.emptyList() or it's an ArrayList - // wrapped in a Collections.unmodifiableList() wrapper and nobody else has - // a refererence to the underlying ArrayList. This invariant allows us to - // share instances of lists between protocol buffers avoiding expensive - // memory allocations. Note, immutable is a strong guarantee here -- not - // just that the list cannot be modified via the reference but that the - // list can never be modified. - printer->Print(variables_, - "private com.google.protobuf.LazyStringList $name$_ = $empty_list$;\n"); - - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$get_mutable_bit_builder$) {\n" - " $name$_ = new com.google.protobuf.LazyStringArrayList($name$_);\n" - " $set_mutable_bit_builder$;\n" - " }\n" - "}\n"); - - // Note: We return an unmodifiable list because otherwise the caller - // could hold on to the returned list and modify it after the message - // has been built, thus mutating the message which is supposed to be - // immutable. - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ProtocolStringList\n" - " ${$get$capitalized_name$List$}$() {\n" - " return $name$_.getUnmodifiableView();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public java.lang.String " - "${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$(int index) {\n" - " return $name$_.getByteString(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, java.lang.String value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.Builder.addAll(\n" - " values, $name$_);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " $name$_ = $empty_list$;\n" - " $clear_mutable_bit_builder$;\n" - " $on_changed$\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); - } - printer->Print(variables_, - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - " $on_changed$\n" - " return this;\n" - "}\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for primitives -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $empty_list$;\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateBuilderClearCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_ = $empty_list$;\n" - "$clear_mutable_bit_builder$;\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateMergingCode(io::Printer* printer) const { - // The code below does two optimizations: - // 1. If the other list is empty, there's nothing to do. This ensures we - // don't allocate a new array if we already have an immutable one. - // 2. If the other list is non-empty and our current list is empty, we can - // reuse the other list which is guaranteed to be immutable. - printer->Print(variables_, - "if (!other.$name$_.isEmpty()) {\n" - " if ($name$_.isEmpty()) {\n" - " $name$_ = other.$name$_;\n" - " $clear_mutable_bit_builder$;\n" - " } else {\n" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.addAll(other.$name$_);\n" - " }\n" - " $on_changed$\n" - "}\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateBuildingCode(io::Printer* printer) const { - // The code below ensures that the result has an immutable list. If our - // list is immutable, we can just reuse it. If not, we make it immutable. - - printer->Print(variables_, - "if ($get_mutable_bit_builder$) {\n" - " $name$_ = $name$_.getUnmodifiableView();\n" - " $clear_mutable_bit_builder$;\n" - "}\n" - "result.$name$_ = $name$_;\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n"); - } else { - printer->Print(variables_, - "com.google.protobuf.ByteString bs = input.readBytes();\n"); - } - printer->Print(variables_, - "if (!$get_mutable_bit_parser$) {\n" - " $name$_ = new com.google.protobuf.LazyStringArrayList();\n" - " $set_mutable_bit_parser$;\n" - "}\n"); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "$name$_.add(s);\n"); - } else { - printer->Print(variables_, - "$name$_.add(bs);\n"); - } -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($get_mutable_bit_parser$) {\n" - " $name$_ = $name$_.getUnmodifiableView();\n" - "}\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " $writeString$(output, $number$, $name$_.getRaw(i));\n" - "}\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += computeStringSizeNoTag($name$_.getRaw(i));\n" - "}\n"); - - printer->Print( - "size += dataSize;\n"); - - printer->Print(variables_, - "size += $tag_size$ * get$capitalized_name$List().size();\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutableStringFieldGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); -} - -string RepeatedImmutableStringFieldGenerator::GetBoxedType() const { - return "String"; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_string_field.h b/windows/include/google/protobuf/compiler/java/java_string_field.h deleted file mode 100644 index 0f7c705b8..000000000 --- a/windows/include/google/protobuf/compiler/java/java_string_field.h +++ /dev/null @@ -1,159 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Author: jonp@google.com (Jon Perlow) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableStringFieldGenerator : public ImmutableFieldGenerator { - public: - explicit ImmutableStringFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableStringFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableStringFieldGenerator); -}; - -class ImmutableStringOneofFieldGenerator - : public ImmutableStringFieldGenerator { - public: - ImmutableStringOneofFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableStringOneofFieldGenerator(); - - private: - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableStringOneofFieldGenerator); -}; - -class RepeatedImmutableStringFieldGenerator : public ImmutableFieldGenerator { - public: - explicit RepeatedImmutableStringFieldGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableStringFieldGenerator(); - - // implements ImmutableFieldGenerator --------------------------------------- - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateBuilderClearCode(io::Printer* printer) const; - void GenerateMergingCode(io::Printer* printer) const; - void GenerateBuildingCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableStringFieldGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/java/java_string_field_lite.cc b/windows/include/google/protobuf/compiler/java/java_string_field_lite.cc deleted file mode 100644 index a238c67d9..000000000 --- a/windows/include/google/protobuf/compiler/java/java_string_field_lite.cc +++ /dev/null @@ -1,935 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Author: jonp@google.com (Jon Perlow) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace java { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -void SetPrimitiveVariables(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - const FieldGeneratorInfo* info, - ClassNameResolver* name_resolver, - std::map* variables) { - SetCommonFieldVariables(descriptor, info, variables); - - (*variables)["empty_list"] = - "com.google.protobuf.GeneratedMessageLite.emptyProtobufList()"; - - (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["default_init"] = - "= " + ImmutableDefaultValue(descriptor, name_resolver); - (*variables)["capitalized_type"] = "java.lang.String"; - (*variables)["tag"] = - SimpleItoa(static_cast(WireFormat::MakeTag(descriptor))); - (*variables)["tag_size"] = SimpleItoa( - WireFormat::TagSize(descriptor->number(), GetType(descriptor))); - (*variables)["null_check"] = - " if (value == null) {\n" - " throw new NullPointerException();\n" - " }\n"; - - // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported - // by the proto compiler - (*variables)["deprecation"] = descriptor->options().deprecated() - ? "@java.lang.Deprecated " : ""; - (*variables)["required"] = descriptor->is_required() ? "true" : "false"; - - if (SupportFieldPresence(descriptor->file())) { - // For singular messages and builders, one bit is used for the hasField bit. - (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex); - - // Note that these have a trailing ";". - (*variables)["set_has_field_bit_message"] = - GenerateSetBit(messageBitIndex) + ";"; - (*variables)["clear_has_field_bit_message"] = - GenerateClearBit(messageBitIndex) + ";"; - - (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex); - } else { - (*variables)["set_has_field_bit_message"] = ""; - (*variables)["clear_has_field_bit_message"] = ""; - - (*variables)["is_field_present_message"] = - "!" + (*variables)["name"] + "_.isEmpty()"; - } - - // For repeated builders, the underlying list tracks mutability state. - (*variables)["is_mutable"] = (*variables)["name"] + "_.isModifiable()"; - - (*variables)["get_has_field_bit_from_local"] = - GenerateGetBitFromLocal(builderBitIndex); - (*variables)["set_has_field_bit_to_local"] = - GenerateSetBitToLocal(messageBitIndex); -} - -} // namespace - -// =================================================================== - -ImmutableStringFieldLiteGenerator:: -ImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -ImmutableStringFieldLiteGenerator::~ImmutableStringFieldLiteGenerator() {} - -int ImmutableStringFieldLiteGenerator::GetNumBitsForMessage() const { - return 1; -} - -int ImmutableStringFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -// A note about how strings are handled. In the SPEED and CODE_SIZE runtimes, -// strings are not stored as java.lang.String in the Message because of two -// issues: -// -// 1. It wouldn't roundtrip byte arrays that were not vaid UTF-8 encoded -// strings, but rather fields that were raw bytes incorrectly marked -// as strings in the proto file. This is common because in the proto1 -// syntax, string was the way to indicate bytes and C++ engineers can -// easily make this mistake without affecting the C++ API. By converting to -// strings immediately, some java code might corrupt these byte arrays as -// it passes through a java server even if the field was never accessed by -// application code. -// -// 2. There's a performance hit to converting between bytes and strings and -// it many cases, the field is never even read by the application code. This -// avoids unnecessary conversions in the common use cases. -// -// In the LITE_RUNTIME, we store strings as java.lang.String because we assume -// that the users of this runtime are not subject to proto1 constraints and are -// running code on devices that are user facing. That is, the developers are -// properly incentivized to only fetch the data they need to read and wish to -// reduce the number of allocations incurred when running on a user's device. - -// TODO(dweis): Consider dropping all of the *Bytes() methods. They really -// shouldn't be necessary or used on devices. -void ImmutableStringFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$boolean has$capitalized_name$();\n"); - } - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes();\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private java.lang.String $name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $get_has_field_bit_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " return $name$_;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " return com.google.protobuf.ByteString.copyFromUtf8($name$_);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " java.lang.String value) {\n" - "$null_check$" - " $set_has_field_bit_message$\n" - " $name$_ = value;\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $clear_has_field_bit_message$\n" - // The default value is not a simple literal so we want to avoid executing - // it multiple times. Instead, get the default out of the default instance. - " $name$_ = getDefaultInstance().get$capitalized_name$();\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$Bytes(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); - } - printer->Print(variables_, - " $set_has_field_bit_message$\n" - " $name$_ = value.toStringUtf8();\n" - "}\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " return instance.get$capitalized_name$Bytes();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Bytes(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for strings -} - - -void ImmutableStringFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $default$;\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - "$name$_ = visitor.visitString(\n" - " has$capitalized_name$(), $name$_,\n" - " other.has$capitalized_name$(), other.$name$_);\n"); - } else { - printer->Print(variables_, - "$name$_ = visitor.visitString(!$name$_.isEmpty(), $name$_,\n" - " !other.$name$_.isEmpty(), other.$name$_);\n"); - } -} - -void ImmutableStringFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - // noop for scalars -} - -void ImmutableStringFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n" - "$set_has_field_bit_message$\n" - "$name$_ = s;\n"); - } else { - // Lite runtime should attempt to reduce allocations by attempting to - // construct the string directly from the input stream buffer. This avoids - // spurious intermediary ByteString allocations, cutting overall allocations - // in half. - printer->Print(variables_, - "java.lang.String s = input.readString();\n" - "$set_has_field_bit_message$\n" - "$name$_ = s;\n"); - } -} - -void ImmutableStringFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - // noop for strings -} - -void ImmutableStringFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by serializing the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " output.writeString($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by computing on the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "if ($is_field_present_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeStringSize($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$()\n" - " .equals(other.get$capitalized_name$());\n"); -} - -void ImmutableStringFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "hash = (37 * hash) + $constant_name$;\n"); - printer->Print(variables_, - "hash = (53 * hash) + get$capitalized_name$().hashCode();\n"); -} - -string ImmutableStringFieldLiteGenerator::GetBoxedType() const { - return "java.lang.String"; -} - -// =================================================================== - -ImmutableStringOneofFieldLiteGenerator:: -ImmutableStringOneofFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : ImmutableStringFieldLiteGenerator( - descriptor, messageBitIndex, builderBitIndex, context) { - const OneofGeneratorInfo* info = - context->GetOneofGeneratorInfo(descriptor->containing_oneof()); - SetCommonOneofVariables(descriptor, info, &variables_); -} - -ImmutableStringOneofFieldLiteGenerator:: -~ImmutableStringOneofFieldLiteGenerator() {} - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - PrintExtraFieldInfo(variables_, printer); - - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return $has_oneof_case_message$;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " java.lang.String ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = (java.lang.String) $oneof_name$_;\n" - " }\n" - " return ref;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " java.lang.String ref $default_init$;\n" - " if ($has_oneof_case_message$) {\n" - " ref = (java.lang.String) $oneof_name$_;\n" - " }\n" - " return com.google.protobuf.ByteString.copyFromUtf8(ref);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - "$null_check$" - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void ${$clear$capitalized_name$$}$() {\n" - " if ($has_oneof_case_message$) {\n" - " $clear_oneof_case_message$;\n" - " $oneof_name$_ = null;\n" - " }\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); - printer->Annotate("{", "}", descriptor_); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); - } - printer->Print(variables_, - " $set_oneof_case_message$;\n" - " $oneof_name$_ = value.toStringUtf8();\n" - "}\n"); -} - - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - if (SupportFieldPresence(descriptor_->file())) { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public boolean ${$has$capitalized_name$$}$() {\n" - " return instance.has$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - } - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n" - " return instance.get$capitalized_name$();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$() {\n" - " return instance.get$capitalized_name$Bytes();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$Bytes(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$oneof_name$_ = visitor.visitOneofString(\n" - " $has_oneof_case_message$, $oneof_name$_, other.$oneof_name$_);\n"); -} - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = s;\n"); - } else { - // Lite runtime should attempt to reduce allocations by attempting to - // construct the string directly from the input stream buffer. This avoids - // spurious intermediary ByteString allocations, cutting overall allocations - // in half. - printer->Print(variables_, - "java.lang.String s = input.readString();\n" - "$set_oneof_case_message$;\n" - "$oneof_name$_ = s;\n"); - } -} - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by serializing the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " output.writeString($number$, get$capitalized_name$());\n" - "}\n"); -} - -void ImmutableStringOneofFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by computing on the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "if ($has_oneof_case_message$) {\n" - " size += com.google.protobuf.CodedOutputStream\n" - " .computeStringSize($number$, get$capitalized_name$());\n" - "}\n"); -} - -// =================================================================== - -RepeatedImmutableStringFieldLiteGenerator:: -RepeatedImmutableStringFieldLiteGenerator(const FieldDescriptor* descriptor, - int messageBitIndex, - int builderBitIndex, - Context* context) - : descriptor_(descriptor), messageBitIndex_(messageBitIndex), - builderBitIndex_(builderBitIndex), context_(context), - name_resolver_(context->GetNameResolver()) { - SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex, - context->GetFieldGeneratorInfo(descriptor), - name_resolver_, &variables_); -} - -RepeatedImmutableStringFieldLiteGenerator:: -~RepeatedImmutableStringFieldLiteGenerator() {} - -int RepeatedImmutableStringFieldLiteGenerator::GetNumBitsForMessage() const { - return 0; -} - -int RepeatedImmutableStringFieldLiteGenerator::GetNumBitsForBuilder() const { - return 0; -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateInterfaceMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.util.List\n" - " get$capitalized_name$List();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$int get$capitalized_name$Count();\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$java.lang.String get$capitalized_name$(int index);\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$com.google.protobuf.ByteString\n" - " get$capitalized_name$Bytes(int index);\n"); -} - - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateMembers(io::Printer* printer) const { - printer->Print(variables_, - "private com.google.protobuf.Internal.ProtobufList " - "$name$_;\n"); - PrintExtraFieldInfo(variables_, printer); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List " - "${$get$capitalized_name$List$}$() {\n" - " return $name$_;\n" // note: unmodifiable list - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return $name$_.size();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String " - "${$get$capitalized_name$$}$(int index) {\n" - " return $name$_.get(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$(int index) {\n" - " return com.google.protobuf.ByteString.copyFromUtf8(\n" - " $name$_.get(index));\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - printer->Print(variables_, - "private void ensure$capitalized_name$IsMutable() {\n" - " if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - " }\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void set$capitalized_name$(\n" - " int index, java.lang.String value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.set(index, value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$(\n" - " java.lang.String value) {\n" - "$null_check$" - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void addAll$capitalized_name$(\n" - " java.lang.Iterable values) {\n" - " ensure$capitalized_name$IsMutable();\n" - " com.google.protobuf.AbstractMessageLite.addAll(\n" - " values, $name$_);\n" - "}\n"); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void clear$capitalized_name$() {\n" - " $name$_ = $empty_list$;\n" - "}\n"); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "private void add$capitalized_name$Bytes(\n" - " com.google.protobuf.ByteString value) {\n" - "$null_check$"); - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - " checkByteStringIsUtf8(value);\n"); - } - printer->Print(variables_, - " ensure$capitalized_name$IsMutable();\n" - " $name$_.add(value.toStringUtf8());\n" - "}\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateBuilderMembers(io::Printer* printer) const { - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.util.List\n" - " ${$get$capitalized_name$List$}$() {\n" - " return java.util.Collections.unmodifiableList(\n" - " instance.get$capitalized_name$List());\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public int ${$get$capitalized_name$Count$}$() {\n" - " return instance.get$capitalized_name$Count();\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public java.lang.String " - "${$get$capitalized_name$$}$(int index) {\n" - " return instance.get$capitalized_name$(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "@java.lang.Override\n" - "$deprecation$public com.google.protobuf.ByteString\n" - " ${$get$capitalized_name$Bytes$}$(int index) {\n" - " return instance.get$capitalized_name$Bytes(index);\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$set$capitalized_name$$}$(\n" - " int index, java.lang.String value) {\n" - " copyOnWrite();\n" - " instance.set$capitalized_name$(index, value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$$}$(\n" - " java.lang.String value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n" - " java.lang.Iterable values) {\n" - " copyOnWrite();\n" - " instance.addAll$capitalized_name$(values);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n" - " copyOnWrite();\n" - " instance.clear$capitalized_name$();\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); - - WriteFieldDocComment(printer, descriptor_); - printer->Print(variables_, - "$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n" - " com.google.protobuf.ByteString value) {\n" - " copyOnWrite();\n" - " instance.add$capitalized_name$Bytes(value);\n" - " return this;\n" - "}\n"); - printer->Annotate("{", "}", descriptor_); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateFieldBuilderInitializationCode(io::Printer* printer) const { - // noop for strings -} - - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateInitializationCode(io::Printer* printer) const { - printer->Print(variables_, "$name$_ = $empty_list$;\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateVisitCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_= visitor.visitList($name$_, other.$name$_);\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const { - printer->Print(variables_, - "$name$_.makeImmutable();\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateParsingCode(io::Printer* printer) const { - if (CheckUtf8(descriptor_)) { - printer->Print(variables_, - "java.lang.String s = input.readStringRequireUtf8();\n"); - } else { - // Lite runtime should attempt to reduce allocations by attempting to - // construct the string directly from the input stream buffer. This avoids - // spurious intermediary ByteString allocations, cutting overall allocations - // in half. - printer->Print(variables_, - "java.lang.String s = input.readString();\n"); - } - printer->Print(variables_, - "if (!$is_mutable$) {\n" - " $name$_ =\n" - " com.google.protobuf.GeneratedMessageLite.mutableCopy($name$_);\n" - "}\n"); - printer->Print(variables_, - "$name$_.add(s);\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateParsingDoneCode(io::Printer* printer) const { - printer->Print(variables_, - "if ($is_mutable$) {\n" - " $name$_.makeImmutable();\n" - "}\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateSerializationCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by serializing the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " output.writeString($number$, $name$_.get(i));\n" - "}\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateSerializedSizeCode(io::Printer* printer) const { - // Lite runtime should reduce allocations by computing on the string directly. - // This avoids spurious intermediary ByteString allocations, cutting overall - // allocations in half. - printer->Print(variables_, - "{\n" - " int dataSize = 0;\n"); - printer->Indent(); - - printer->Print(variables_, - "for (int i = 0; i < $name$_.size(); i++) {\n" - " dataSize += com.google.protobuf.CodedOutputStream\n" - " .computeStringSizeNoTag($name$_.get(i));\n" - "}\n"); - - printer->Print( - "size += dataSize;\n"); - - - printer->Print(variables_, - "size += $tag_size$ * get$capitalized_name$List().size();\n"); - - printer->Outdent(); - printer->Print("}\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateEqualsCode(io::Printer* printer) const { - printer->Print(variables_, - "result = result && get$capitalized_name$List()\n" - " .equals(other.get$capitalized_name$List());\n"); -} - -void RepeatedImmutableStringFieldLiteGenerator:: -GenerateHashCode(io::Printer* printer) const { - printer->Print(variables_, - "if (get$capitalized_name$Count() > 0) {\n" - " hash = (37 * hash) + $constant_name$;\n" - " hash = (53 * hash) + get$capitalized_name$List().hashCode();\n" - "}\n"); -} - -string RepeatedImmutableStringFieldLiteGenerator::GetBoxedType() const { - return "java.lang.String"; -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/java/java_string_field_lite.h b/windows/include/google/protobuf/compiler/java/java_string_field_lite.h deleted file mode 100644 index b7fb64095..000000000 --- a/windows/include/google/protobuf/compiler/java/java_string_field_lite.h +++ /dev/null @@ -1,160 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Author: jonp@google.com (Jon Perlow) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_LITE_H__ -#define GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_LITE_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - namespace compiler { - namespace java { - class Context; // context.h - class ClassNameResolver; // name_resolver.h - } - } -} - -namespace protobuf { -namespace compiler { -namespace java { - -class ImmutableStringFieldLiteGenerator : public ImmutableFieldLiteGenerator { - public: - explicit ImmutableStringFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableStringFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - - string GetBoxedType() const; - - protected: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableStringFieldLiteGenerator); -}; - -class ImmutableStringOneofFieldLiteGenerator - : public ImmutableStringFieldLiteGenerator { - public: - ImmutableStringOneofFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~ImmutableStringOneofFieldLiteGenerator(); - - private: - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ImmutableStringOneofFieldLiteGenerator); -}; - -class RepeatedImmutableStringFieldLiteGenerator - : public ImmutableFieldLiteGenerator { - public: - explicit RepeatedImmutableStringFieldLiteGenerator( - const FieldDescriptor* descriptor, int messageBitIndex, - int builderBitIndex, Context* context); - ~RepeatedImmutableStringFieldLiteGenerator(); - - // implements ImmutableFieldLiteGenerator ------------------------------------ - int GetNumBitsForMessage() const; - int GetNumBitsForBuilder() const; - void GenerateInterfaceMembers(io::Printer* printer) const; - void GenerateMembers(io::Printer* printer) const; - void GenerateBuilderMembers(io::Printer* printer) const; - void GenerateInitializationCode(io::Printer* printer) const; - void GenerateVisitCode(io::Printer* printer) const; - void GenerateDynamicMethodMakeImmutableCode(io::Printer* printer) const; - void GenerateParsingCode(io::Printer* printer) const; - void GenerateParsingDoneCode(io::Printer* printer) const; - void GenerateSerializationCode(io::Printer* printer) const; - void GenerateSerializedSizeCode(io::Printer* printer) const; - void GenerateFieldBuilderInitializationCode(io::Printer* printer) const; - void GenerateEqualsCode(io::Printer* printer) const; - void GenerateHashCode(io::Printer* printer) const; - - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - std::map variables_; - const int messageBitIndex_; - const int builderBitIndex_; - Context* context_; - ClassNameResolver* name_resolver_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedImmutableStringFieldLiteGenerator); -}; - -} // namespace java -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_JAVA_STRING_FIELD_LITE_H__ diff --git a/windows/include/google/protobuf/compiler/js/js_generator.cc b/windows/include/google/protobuf/compiler/js/js_generator.cc deleted file mode 100644 index b5771f260..000000000 --- a/windows/include/google/protobuf/compiler/js/js_generator.cc +++ /dev/null @@ -1,3674 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { -namespace js { - -// Sorted list of JavaScript keywords. These cannot be used as names. If they -// appear, we prefix them with "pb_". -const char* kKeyword[] = { - "abstract", - "boolean", - "break", - "byte", - "case", - "catch", - "char", - "class", - "const", - "continue", - "debugger", - "default", - "delete", - "do", - "double", - "else", - "enum", - "export", - "extends", - "false", - "final", - "finally", - "float", - "for", - "function", - "goto", - "if", - "implements", - "import", - "in", - "instanceof", - "int", - "interface", - "long", - "native", - "new", - "null", - "package", - "private", - "protected", - "public", - "return", - "short", - "static", - "super", - "switch", - "synchronized", - "this", - "throw", - "throws", - "transient", - "try", - "typeof", - "var", - "void", - "volatile", - "while", - "with", -}; - -static const int kNumKeyword = sizeof(kKeyword) / sizeof(char*); - -namespace { - -// The mode of operation for bytes fields. Historically JSPB always carried -// bytes as JS {string}, containing base64 content by convention. With binary -// and proto3 serialization the new convention is to represent it as binary -// data in Uint8Array. See b/26173701 for background on the migration. -enum BytesMode { - BYTES_DEFAULT, // Default type for getBytesField to return. - BYTES_B64, // Explicitly coerce to base64 string where needed. - BYTES_U8, // Explicitly coerce to Uint8Array where needed. -}; - -bool IsReserved(const string& ident) { - for (int i = 0; i < kNumKeyword; i++) { - if (ident == kKeyword[i]) { - return true; - } - } - return false; -} - -bool StrEndsWith(StringPiece sp, StringPiece x) { - return sp.size() >= x.size() && sp.substr(sp.size() - x.size()) == x; -} - -// Returns a copy of |filename| with any trailing ".protodevel" or ".proto -// suffix stripped. -// TODO(haberman): Unify with copy in compiler/cpp/internal/helpers.cc. -string StripProto(const string& filename) { - const char* suffix = - StrEndsWith(filename, ".protodevel") ? ".protodevel" : ".proto"; - return StripSuffixString(filename, suffix); -} - -// Given a filename like foo/bar/baz.proto, returns the corresponding JavaScript -// file foo/bar/baz.js. -string GetJSFilename(const GeneratorOptions& options, const string& filename) { - return StripProto(filename) + options.GetFileNameExtension(); -} - -// Given a filename like foo/bar/baz.proto, returns the root directory -// path ../../ -string GetRootPath(const string& from_filename, const string& to_filename) { - if (to_filename.find("google/protobuf") == 0) { - // Well-known types (.proto files in the google/protobuf directory) are - // assumed to come from the 'google-protobuf' npm package. We may want to - // generalize this exception later by letting others put generated code in - // their own npm packages. - return "google-protobuf/"; - } - - size_t slashes = std::count(from_filename.begin(), from_filename.end(), '/'); - if (slashes == 0) { - return "./"; - } - string result = ""; - for (size_t i = 0; i < slashes; i++) { - result += "../"; - } - return result; -} - -// Returns the alias we assign to the module of the given .proto filename -// when importing. -string ModuleAlias(const string& filename) { - // This scheme could technically cause problems if a file includes any 2 of: - // foo/bar_baz.proto - // foo_bar_baz.proto - // foo_bar/baz.proto - // - // We'll worry about this problem if/when we actually see it. This name isn't - // exposed to users so we can change it later if we need to. - string basename = StripProto(filename); - ReplaceCharacters(&basename, "-", '$'); - ReplaceCharacters(&basename, "/", '_'); - ReplaceCharacters(&basename, ".", '_'); - return basename + "_pb"; -} - -// Returns the fully normalized JavaScript path for the given -// file descriptor's package. -string GetFilePath(const GeneratorOptions& options, - const FileDescriptor* file) { - if (!options.namespace_prefix.empty()) { - return options.namespace_prefix; - } else if (!file->package().empty()) { - return "proto." + file->package(); - } else { - return "proto"; - } -} - -// Returns the name of the message with a leading dot and taking into account -// nesting, for example ".OuterMessage.InnerMessage", or returns empty if -// descriptor is null. This function does not handle namespacing, only message -// nesting. -string GetNestedMessageName(const Descriptor* descriptor) { - if (descriptor == NULL) { - return ""; - } - string result = - StripPrefixString(descriptor->full_name(), descriptor->file()->package()); - // Add a leading dot if one is not already present. - if (!result.empty() && result[0] != '.') { - result = "." + result; - } - return result; -} - -// Returns the path prefix for a message or enumeration that -// lives under the given file and containing type. -string GetPrefix(const GeneratorOptions& options, - const FileDescriptor* file_descriptor, - const Descriptor* containing_type) { - string prefix = GetFilePath(options, file_descriptor) + - GetNestedMessageName(containing_type); - if (!prefix.empty()) { - prefix += "."; - } - return prefix; -} - -// Returns the fully normalized JavaScript path prefix for the given -// message descriptor. -string GetMessagePathPrefix(const GeneratorOptions& options, - const Descriptor* descriptor) { - return GetPrefix( - options, descriptor->file(), - descriptor->containing_type()); -} - -// Returns the fully normalized JavaScript path for the given -// message descriptor. -string GetMessagePath(const GeneratorOptions& options, - const Descriptor* descriptor) { - return GetMessagePathPrefix(options, descriptor) + descriptor->name(); -} - -// Returns the fully normalized JavaScript path prefix for the given -// enumeration descriptor. -string GetEnumPathPrefix(const GeneratorOptions& options, - const EnumDescriptor* enum_descriptor) { - return GetPrefix(options, enum_descriptor->file(), - enum_descriptor->containing_type()); -} - -// Returns the fully normalized JavaScript path for the given -// enumeration descriptor. -string GetEnumPath(const GeneratorOptions& options, - const EnumDescriptor* enum_descriptor) { - return GetEnumPathPrefix(options, enum_descriptor) + enum_descriptor->name(); -} - -string MaybeCrossFileRef(const GeneratorOptions& options, - const FileDescriptor* from_file, - const Descriptor* to_message) { - if (options.import_style == GeneratorOptions::kImportCommonJs && - from_file != to_message->file()) { - // Cross-file ref in CommonJS needs to use the module alias instead of - // the global name. - return ModuleAlias(to_message->file()->name()) + - GetNestedMessageName(to_message->containing_type()) + "." + - to_message->name(); - } else { - // Within a single file we use a full name. - return GetMessagePath(options, to_message); - } -} - -string SubmessageTypeRef(const GeneratorOptions& options, - const FieldDescriptor* field) { - GOOGLE_CHECK(field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE); - return MaybeCrossFileRef(options, field->file(), field->message_type()); -} - -// - Object field name: LOWER_UNDERSCORE -> LOWER_CAMEL, except for group fields -// (UPPER_CAMEL -> LOWER_CAMEL), with "List" (or "Map") appended if appropriate, -// and with reserved words triggering a "pb_" prefix. -// - Getters/setters: LOWER_UNDERSCORE -> UPPER_CAMEL, except for group fields -// (use the name directly), then append "List" if appropriate, then append "$" -// if resulting name is equal to a reserved word. -// - Enums: just uppercase. - -// Locale-independent version of ToLower that deals only with ASCII A-Z. -char ToLowerASCII(char c) { - if (c >= 'A' && c <= 'Z') { - return (c - 'A') + 'a'; - } else { - return c; - } -} - -std::vector ParseLowerUnderscore(const string& input) { - std::vector words; - string running = ""; - for (int i = 0; i < input.size(); i++) { - if (input[i] == '_') { - if (!running.empty()) { - words.push_back(running); - running.clear(); - } - } else { - running += ToLowerASCII(input[i]); - } - } - if (!running.empty()) { - words.push_back(running); - } - return words; -} - -std::vector ParseUpperCamel(const string& input) { - std::vector words; - string running = ""; - for (int i = 0; i < input.size(); i++) { - if (input[i] >= 'A' && input[i] <= 'Z' && !running.empty()) { - words.push_back(running); - running.clear(); - } - running += ToLowerASCII(input[i]); - } - if (!running.empty()) { - words.push_back(running); - } - return words; -} - -string ToLowerCamel(const std::vector& words) { - string result; - for (int i = 0; i < words.size(); i++) { - string word = words[i]; - if (i == 0 && (word[0] >= 'A' && word[0] <= 'Z')) { - word[0] = (word[0] - 'A') + 'a'; - } else if (i != 0 && (word[0] >= 'a' && word[0] <= 'z')) { - word[0] = (word[0] - 'a') + 'A'; - } - result += word; - } - return result; -} - -string ToUpperCamel(const std::vector& words) { - string result; - for (int i = 0; i < words.size(); i++) { - string word = words[i]; - if (word[0] >= 'a' && word[0] <= 'z') { - word[0] = (word[0] - 'a') + 'A'; - } - result += word; - } - return result; -} - -// Based on code from descriptor.cc (Thanks Kenton!) -// Uppercases the entire string, turning ValueName into -// VALUENAME. -string ToEnumCase(const string& input) { - string result; - result.reserve(input.size()); - - for (int i = 0; i < input.size(); i++) { - if ('a' <= input[i] && input[i] <= 'z') { - result.push_back(input[i] - 'a' + 'A'); - } else { - result.push_back(input[i]); - } - } - - return result; -} - -string ToFileName(const string& input) { - string result; - result.reserve(input.size()); - - for (int i = 0; i < input.size(); i++) { - if ('A' <= input[i] && input[i] <= 'Z') { - result.push_back(input[i] - 'A' + 'a'); - } else { - result.push_back(input[i]); - } - } - - return result; -} - -// When we're generating one output file per type name, this is the filename -// that top-level extensions should go in. -string GetExtensionFileName(const GeneratorOptions& options, - const FileDescriptor* file) { - return options.output_dir + "/" + ToFileName(GetFilePath(options, file)) + - options.GetFileNameExtension(); -} - -// When we're generating one output file per type name, this is the filename -// that a top-level message should go in. -string GetMessageFileName(const GeneratorOptions& options, - const Descriptor* desc) { - return options.output_dir + "/" + ToFileName(desc->name()) + - options.GetFileNameExtension(); -} - -// When we're generating one output file per type name, this is the filename -// that a top-level message should go in. -string GetEnumFileName(const GeneratorOptions& options, - const EnumDescriptor* desc) { - return options.output_dir + "/" + ToFileName(desc->name()) + - options.GetFileNameExtension(); -} - -// Returns the message/response ID, if set. -string GetMessageId(const Descriptor* desc) { - return string(); -} - -bool IgnoreExtensionField(const FieldDescriptor* field) { - // Exclude descriptor extensions from output "to avoid clutter" (from original - // codegen). - return field->is_extension() && - field->containing_type()->file()->name() == - "google/protobuf/descriptor.proto"; -} - - -// Used inside Google only -- do not remove. -bool IsResponse(const Descriptor* desc) { return false; } - -bool IgnoreField(const FieldDescriptor* field) { - return IgnoreExtensionField(field); -} - - -// Used inside Google only -- do not remove. -bool ShouldTreatMapsAsRepeatedFields(const FileDescriptor& descriptor) { - return false; -} - -// Do we ignore this message type? -bool IgnoreMessage(const GeneratorOptions& options, const Descriptor* d) { - return d->options().map_entry() && - !ShouldTreatMapsAsRepeatedFields(*d->file()); -} - -bool IsMap(const GeneratorOptions& options, const FieldDescriptor* field) { - return field->is_map() && !ShouldTreatMapsAsRepeatedFields(*field->file()); -} - -// Does JSPB ignore this entire oneof? True only if all fields are ignored. -bool IgnoreOneof(const OneofDescriptor* oneof) { - for (int i = 0; i < oneof->field_count(); i++) { - if (!IgnoreField(oneof->field(i))) { - return false; - } - } - return true; -} - -string JSIdent(const GeneratorOptions& options, const FieldDescriptor* field, - bool is_upper_camel, bool is_map, bool drop_list) { - string result; - if (field->type() == FieldDescriptor::TYPE_GROUP) { - result = is_upper_camel ? - ToUpperCamel(ParseUpperCamel(field->message_type()->name())) : - ToLowerCamel(ParseUpperCamel(field->message_type()->name())); - } else { - result = is_upper_camel ? - ToUpperCamel(ParseLowerUnderscore(field->name())) : - ToLowerCamel(ParseLowerUnderscore(field->name())); - } - if (is_map || IsMap(options, field)) { - // JSPB-style or proto3-style map. - result += "Map"; - } else if (!drop_list && field->is_repeated()) { - // Repeated field. - result += "List"; - } - return result; -} - -string JSObjectFieldName(const GeneratorOptions& options, - const FieldDescriptor* field) { - string name = JSIdent(options, field, - /* is_upper_camel = */ false, - /* is_map = */ false, - /* drop_list = */ false); - if (IsReserved(name)) { - name = "pb_" + name; - } - return name; -} - -string JSByteGetterSuffix(BytesMode bytes_mode) { - switch (bytes_mode) { - case BYTES_DEFAULT: - return ""; - case BYTES_B64: - return "B64"; - case BYTES_U8: - return "U8"; - default: - assert(false); - } - return ""; -} - -// Returns the field name as a capitalized portion of a getter/setter method -// name, e.g. MyField for .getMyField(). -string JSGetterName(const GeneratorOptions& options, - const FieldDescriptor* field, - BytesMode bytes_mode = BYTES_DEFAULT, - bool drop_list = false) { - string name = JSIdent(options, field, - /* is_upper_camel = */ true, - /* is_map = */ false, drop_list); - if (field->type() == FieldDescriptor::TYPE_BYTES) { - string suffix = JSByteGetterSuffix(bytes_mode); - if (!suffix.empty()) { - name += "_as" + suffix; - } - } - if (name == "Extension" || name == "JsPbMessageId") { - // Avoid conflicts with base-class names. - name += "$"; - } - return name; -} - - - -string JSOneofName(const OneofDescriptor* oneof) { - return ToUpperCamel(ParseLowerUnderscore(oneof->name())); -} - -// Returns the index corresponding to this field in the JSPB array (underlying -// data storage array). -string JSFieldIndex(const FieldDescriptor* field) { - // Determine whether this field is a member of a group. Group fields are a bit - // wonky: their "containing type" is a message type created just for the - // group, and that type's parent type has a field with the group-message type - // as its message type and TYPE_GROUP as its field type. For such fields, the - // index we use is relative to the field number of the group submessage field. - // For all other fields, we just use the field number. - const Descriptor* containing_type = field->containing_type(); - const Descriptor* parent_type = containing_type->containing_type(); - if (parent_type != NULL) { - for (int i = 0; i < parent_type->field_count(); i++) { - if (parent_type->field(i)->type() == FieldDescriptor::TYPE_GROUP && - parent_type->field(i)->message_type() == containing_type) { - return SimpleItoa(field->number() - parent_type->field(i)->number()); - } - } - } - return SimpleItoa(field->number()); -} - -string JSOneofIndex(const OneofDescriptor* oneof) { - int index = -1; - for (int i = 0; i < oneof->containing_type()->oneof_decl_count(); i++) { - const OneofDescriptor* o = oneof->containing_type()->oneof_decl(i); - // If at least one field in this oneof is not JSPB-ignored, count the oneof. - for (int j = 0; j < o->field_count(); j++) { - const FieldDescriptor* f = o->field(j); - if (!IgnoreField(f)) { - index++; - break; // inner loop - } - } - if (o == oneof) { - break; - } - } - return SimpleItoa(index); -} - -// Decodes a codepoint in \x0000 -- \xFFFF. -uint16 DecodeUTF8Codepoint(uint8* bytes, size_t* length) { - if (*length == 0) { - return 0; - } - size_t expected = 0; - if ((*bytes & 0x80) == 0) { - expected = 1; - } else if ((*bytes & 0xe0) == 0xc0) { - expected = 2; - } else if ((*bytes & 0xf0) == 0xe0) { - expected = 3; - } else { - // Too long -- don't accept. - *length = 0; - return 0; - } - - if (*length < expected) { - // Not enough bytes -- don't accept. - *length = 0; - return 0; - } - - *length = expected; - switch (expected) { - case 1: return bytes[0]; - case 2: return ((bytes[0] & 0x1F) << 6) | - ((bytes[1] & 0x3F) << 0); - case 3: return ((bytes[0] & 0x0F) << 12) | - ((bytes[1] & 0x3F) << 6) | - ((bytes[2] & 0x3F) << 0); - default: return 0; - } -} - -// Escapes the contents of a string to be included within double-quotes ("") in -// JavaScript. The input data should be a UTF-8 encoded C++ string of chars. -// Returns false if |out| was truncated because |in| contained invalid UTF-8 or -// codepoints outside the BMP. -// TODO(lukestebbing): Support codepoints outside the BMP. -bool EscapeJSString(const string& in, string* out) { - size_t decoded = 0; - for (size_t i = 0; i < in.size(); i += decoded) { - uint16 codepoint = 0; - // Decode the next UTF-8 codepoint. - size_t have_bytes = in.size() - i; - uint8 bytes[3] = { - static_cast(in[i]), - static_cast(((i + 1) < in.size()) ? in[i + 1] : 0), - static_cast(((i + 2) < in.size()) ? in[i + 2] : 0), - }; - codepoint = DecodeUTF8Codepoint(bytes, &have_bytes); - if (have_bytes == 0) { - return false; - } - decoded = have_bytes; - - switch (codepoint) { - case '\'': *out += "\\x27"; break; - case '"': *out += "\\x22"; break; - case '<': *out += "\\x3c"; break; - case '=': *out += "\\x3d"; break; - case '>': *out += "\\x3e"; break; - case '&': *out += "\\x26"; break; - case '\b': *out += "\\b"; break; - case '\t': *out += "\\t"; break; - case '\n': *out += "\\n"; break; - case '\f': *out += "\\f"; break; - case '\r': *out += "\\r"; break; - case '\\': *out += "\\\\"; break; - default: - // TODO(lukestebbing): Once we're supporting codepoints outside the BMP, - // use a single Unicode codepoint escape if the output language is - // ECMAScript 2015 or above. Otherwise, use a surrogate pair. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals - if (codepoint >= 0x20 && codepoint <= 0x7e) { - *out += static_cast(codepoint); - } else if (codepoint >= 0x100) { - *out += StringPrintf("\\u%04x", codepoint); - } else { - *out += StringPrintf("\\x%02x", codepoint); - } - break; - } - } - return true; -} - -string EscapeBase64(const string& in) { - static const char* kAlphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - string result; - - for (size_t i = 0; i < in.size(); i += 3) { - int value = (in[i] << 16) | - (((i + 1) < in.size()) ? (in[i + 1] << 8) : 0) | - (((i + 2) < in.size()) ? (in[i + 2] << 0) : 0); - result += kAlphabet[(value >> 18) & 0x3f]; - result += kAlphabet[(value >> 12) & 0x3f]; - if ((i + 1) < in.size()) { - result += kAlphabet[(value >> 6) & 0x3f]; - } else { - result += '='; - } - if ((i + 2) < in.size()) { - result += kAlphabet[(value >> 0) & 0x3f]; - } else { - result += '='; - } - } - - return result; -} - -// Post-process the result of SimpleFtoa/SimpleDtoa to *exactly* match the -// original codegen's formatting (which is just .toString() on java.lang.Double -// or java.lang.Float). -string PostProcessFloat(string result) { - // If inf, -inf or nan, replace with +Infinity, -Infinity or NaN. - if (result == "inf") { - return "Infinity"; - } else if (result == "-inf") { - return "-Infinity"; - } else if (result == "nan") { - return "NaN"; - } - - // If scientific notation (e.g., "1e10"), (i) capitalize the "e", (ii) - // ensure that the mantissa (portion prior to the "e") has at least one - // fractional digit (after the decimal point), and (iii) strip any unnecessary - // leading zeroes and/or '+' signs from the exponent. - string::size_type exp_pos = result.find('e'); - if (exp_pos != string::npos) { - string mantissa = result.substr(0, exp_pos); - string exponent = result.substr(exp_pos + 1); - - // Add ".0" to mantissa if no fractional part exists. - if (mantissa.find('.') == string::npos) { - mantissa += ".0"; - } - - // Strip the sign off the exponent and store as |exp_neg|. - bool exp_neg = false; - if (!exponent.empty() && exponent[0] == '+') { - exponent = exponent.substr(1); - } else if (!exponent.empty() && exponent[0] == '-') { - exp_neg = true; - exponent = exponent.substr(1); - } - - // Strip any leading zeroes off the exponent. - while (exponent.size() > 1 && exponent[0] == '0') { - exponent = exponent.substr(1); - } - - return mantissa + "E" + string(exp_neg ? "-" : "") + exponent; - } - - // Otherwise, this is an ordinary decimal number. Append ".0" if result has no - // decimal/fractional part in order to match output of original codegen. - if (result.find('.') == string::npos) { - result += ".0"; - } - - return result; -} - -string FloatToString(float value) { - string result = SimpleFtoa(value); - return PostProcessFloat(result); -} - -string DoubleToString(double value) { - string result = SimpleDtoa(value); - return PostProcessFloat(result); -} - -// Return true if this is an integral field that should be represented as string -// in JS. -bool IsIntegralFieldWithStringJSType(const FieldDescriptor* field) { - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT64: - case FieldDescriptor::CPPTYPE_UINT64: - // The default value of JSType is JS_NORMAL, which behaves the same as - // JS_NUMBER. - return field->options().jstype() == google::protobuf::FieldOptions::JS_STRING; - default: - return false; - } -} - -string MaybeNumberString(const FieldDescriptor* field, const string& orig) { - return IsIntegralFieldWithStringJSType(field) ? ("\"" + orig + "\"") : orig; -} - -string JSFieldDefault(const FieldDescriptor* field) { - if (field->is_repeated()) { - return "[]"; - } - - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - return MaybeNumberString( - field, SimpleItoa(field->default_value_int32())); - case FieldDescriptor::CPPTYPE_UINT32: - // The original codegen is in Java, and Java protobufs store unsigned - // integer values as signed integer values. In order to exactly match the - // output, we need to reinterpret as base-2 signed. Ugh. - return MaybeNumberString( - field, SimpleItoa(static_cast(field->default_value_uint32()))); - case FieldDescriptor::CPPTYPE_INT64: - return MaybeNumberString( - field, SimpleItoa(field->default_value_int64())); - case FieldDescriptor::CPPTYPE_UINT64: - // See above note for uint32 -- reinterpreting as signed. - return MaybeNumberString( - field, SimpleItoa(static_cast(field->default_value_uint64()))); - case FieldDescriptor::CPPTYPE_ENUM: - return SimpleItoa(field->default_value_enum()->number()); - case FieldDescriptor::CPPTYPE_BOOL: - return field->default_value_bool() ? "true" : "false"; - case FieldDescriptor::CPPTYPE_FLOAT: - return FloatToString(field->default_value_float()); - case FieldDescriptor::CPPTYPE_DOUBLE: - return DoubleToString(field->default_value_double()); - case FieldDescriptor::CPPTYPE_STRING: - if (field->type() == FieldDescriptor::TYPE_STRING) { - string out; - bool is_valid = EscapeJSString(field->default_value_string(), &out); - if (!is_valid) { - // TODO(lukestebbing): Decide whether this should be a hard error. - GOOGLE_LOG(WARNING) << "The default value for field " << field->full_name() - << " was truncated since it contained invalid UTF-8 or" - " codepoints outside the basic multilingual plane."; - } - return "\"" + out + "\""; - } else { // Bytes - return "\"" + EscapeBase64(field->default_value_string()) + "\""; - } - case FieldDescriptor::CPPTYPE_MESSAGE: - return "null"; - } - GOOGLE_LOG(FATAL) << "Shouldn't reach here."; - return ""; -} - -string ProtoTypeName(const GeneratorOptions& options, - const FieldDescriptor* field) { - switch (field->type()) { - case FieldDescriptor::TYPE_BOOL: - return "bool"; - case FieldDescriptor::TYPE_INT32: - return "int32"; - case FieldDescriptor::TYPE_UINT32: - return "uint32"; - case FieldDescriptor::TYPE_SINT32: - return "sint32"; - case FieldDescriptor::TYPE_FIXED32: - return "fixed32"; - case FieldDescriptor::TYPE_SFIXED32: - return "sfixed32"; - case FieldDescriptor::TYPE_INT64: - return "int64"; - case FieldDescriptor::TYPE_UINT64: - return "uint64"; - case FieldDescriptor::TYPE_SINT64: - return "sint64"; - case FieldDescriptor::TYPE_FIXED64: - return "fixed64"; - case FieldDescriptor::TYPE_SFIXED64: - return "sfixed64"; - case FieldDescriptor::TYPE_FLOAT: - return "float"; - case FieldDescriptor::TYPE_DOUBLE: - return "double"; - case FieldDescriptor::TYPE_STRING: - return "string"; - case FieldDescriptor::TYPE_BYTES: - return "bytes"; - case FieldDescriptor::TYPE_GROUP: - return GetMessagePath(options, field->message_type()); - case FieldDescriptor::TYPE_ENUM: - return GetEnumPath(options, field->enum_type()); - case FieldDescriptor::TYPE_MESSAGE: - return GetMessagePath(options, field->message_type()); - default: - return ""; - } -} - -string JSIntegerTypeName(const FieldDescriptor* field) { - return IsIntegralFieldWithStringJSType(field) ? "string" : "number"; -} - -string JSStringTypeName(const GeneratorOptions& options, - const FieldDescriptor* field, - BytesMode bytes_mode) { - if (field->type() == FieldDescriptor::TYPE_BYTES) { - switch (bytes_mode) { - case BYTES_DEFAULT: - return "(string|Uint8Array)"; - case BYTES_B64: - return "string"; - case BYTES_U8: - return "Uint8Array"; - default: - assert(false); - } - } - return "string"; -} - -string JSTypeName(const GeneratorOptions& options, - const FieldDescriptor* field, - BytesMode bytes_mode) { - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_BOOL: - return "boolean"; - case FieldDescriptor::CPPTYPE_INT32: - return JSIntegerTypeName(field); - case FieldDescriptor::CPPTYPE_INT64: - return JSIntegerTypeName(field); - case FieldDescriptor::CPPTYPE_UINT32: - return JSIntegerTypeName(field); - case FieldDescriptor::CPPTYPE_UINT64: - return JSIntegerTypeName(field); - case FieldDescriptor::CPPTYPE_FLOAT: - return "number"; - case FieldDescriptor::CPPTYPE_DOUBLE: - return "number"; - case FieldDescriptor::CPPTYPE_STRING: - return JSStringTypeName(options, field, bytes_mode); - case FieldDescriptor::CPPTYPE_ENUM: - return GetEnumPath(options, field->enum_type()); - case FieldDescriptor::CPPTYPE_MESSAGE: - return GetMessagePath(options, field->message_type()); - default: - return ""; - } -} - -// Used inside Google only -- do not remove. -bool UseBrokenPresenceSemantics(const GeneratorOptions& options, - const FieldDescriptor* field) { - return false; -} - -// Returns true for fields that return "null" from accessors when they are -// unset. This should normally only be true for non-repeated submessages, but -// we have legacy users who relied on old behavior where accessors behaved this -// way. -bool ReturnsNullWhenUnset(const GeneratorOptions& options, - const FieldDescriptor* field) { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - field->is_optional()) { - return true; - } - - // TODO(haberman): remove this case and unconditionally return false. - return UseBrokenPresenceSemantics(options, field) && !field->is_repeated() && - !field->has_default_value(); -} - -// In a sane world, this would be the same as ReturnsNullWhenUnset(). But in -// the status quo, some fields declare that they never return null/undefined -// even though they actually do: -// * required fields -// * optional enum fields -// * proto3 primitive fields. -bool DeclaredReturnTypeIsNullable(const GeneratorOptions& options, - const FieldDescriptor* field) { - if (field->is_required() || field->type() == FieldDescriptor::TYPE_ENUM) { - return false; - } - - if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 && - field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - return false; - } - - return ReturnsNullWhenUnset(options, field); -} - -bool SetterAcceptsUndefined(const GeneratorOptions& options, - const FieldDescriptor* field) { - if (ReturnsNullWhenUnset(options, field)) { - return true; - } - - // Broken presence semantics always accepts undefined for setters. - return UseBrokenPresenceSemantics(options, field); -} - -bool SetterAcceptsNull(const GeneratorOptions& options, - const FieldDescriptor* field) { - if (ReturnsNullWhenUnset(options, field)) { - return true; - } - - // With broken presence semantics, fields with defaults accept "null" for - // setters, but other fields do not. This is a strange quirk of the old - // codegen. - return UseBrokenPresenceSemantics(options, field) && - field->has_default_value(); -} - -// Returns types which are known to by non-nullable by default. -// The style guide requires that we omit "!" in this case. -bool IsPrimitive(const string& type) { - return type == "undefined" || type == "string" || type == "number" || - type == "boolean"; -} - -string JSFieldTypeAnnotation(const GeneratorOptions& options, - const FieldDescriptor* field, - bool is_setter_argument, - bool force_present, - bool singular_if_not_packed, - BytesMode bytes_mode = BYTES_DEFAULT) { - GOOGLE_CHECK(!(is_setter_argument && force_present)); - string jstype = JSTypeName(options, field, bytes_mode); - - if (field->is_repeated() && - (field->is_packed() || !singular_if_not_packed)) { - if (field->type() == FieldDescriptor::TYPE_BYTES && - bytes_mode == BYTES_DEFAULT) { - jstype = "(Array|Array)"; - } else { - if (!IsPrimitive(jstype)) { - jstype = "!" + jstype; - } - jstype = "Array<" + jstype + ">"; - } - } - - bool is_null_or_undefined = false; - - if (is_setter_argument) { - if (SetterAcceptsNull(options, field)) { - jstype = "?" + jstype; - is_null_or_undefined = true; - } - - if (SetterAcceptsUndefined(options, field)) { - jstype += "|undefined"; - is_null_or_undefined = true; - } - } else if (force_present) { - // Don't add null or undefined. - } else { - if (DeclaredReturnTypeIsNullable(options, field)) { - jstype = "?" + jstype; - is_null_or_undefined = true; - } - } - - if (!is_null_or_undefined && !IsPrimitive(jstype)) { - jstype = "!" + jstype; - } - - return jstype; -} - -string JSBinaryReaderMethodType(const FieldDescriptor* field) { - string name = field->type_name(); - if (name[0] >= 'a' && name[0] <= 'z') { - name[0] = (name[0] - 'a') + 'A'; - } - return IsIntegralFieldWithStringJSType(field) ? (name + "String") : name; -} - -string JSBinaryReadWriteMethodName(const FieldDescriptor* field, - bool is_writer) { - string name = JSBinaryReaderMethodType(field); - if (field->is_packed()) { - name = "Packed" + name; - } else if (is_writer && field->is_repeated()) { - name = "Repeated" + name; - } - return name; -} - -string JSBinaryReaderMethodName(const GeneratorOptions& options, - const FieldDescriptor* field) { - return "jspb.BinaryReader.prototype.read" + - JSBinaryReadWriteMethodName(field, /* is_writer = */ false); -} - -string JSBinaryWriterMethodName(const GeneratorOptions& options, - const FieldDescriptor* field) { - return "jspb.BinaryWriter.prototype.write" + - JSBinaryReadWriteMethodName(field, /* is_writer = */ true); -} - -string JSReturnClause(const FieldDescriptor* desc) { - return ""; -} - -string JSTypeTag(const FieldDescriptor* desc) { - switch (desc->type()) { - case FieldDescriptor::TYPE_DOUBLE: - case FieldDescriptor::TYPE_FLOAT: - return "Float"; - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_SFIXED32: - case FieldDescriptor::TYPE_SFIXED64: - if (IsIntegralFieldWithStringJSType(desc)) { - return "StringInt"; - } else { - return "Int"; - } - case FieldDescriptor::TYPE_BOOL: - return "Boolean"; - case FieldDescriptor::TYPE_STRING: - return "String"; - case FieldDescriptor::TYPE_BYTES: - return "Bytes"; - case FieldDescriptor::TYPE_ENUM: - return "Enum"; - default: - assert(false); - } - return ""; -} - -string JSReturnDoc(const GeneratorOptions& options, - const FieldDescriptor* desc) { - return ""; -} - -bool HasRepeatedFields(const GeneratorOptions& options, - const Descriptor* desc) { - for (int i = 0; i < desc->field_count(); i++) { - if (desc->field(i)->is_repeated() && !IsMap(options, desc->field(i))) { - return true; - } - } - return false; -} - -static const char* kRepeatedFieldArrayName = ".repeatedFields_"; - -string RepeatedFieldsArrayName(const GeneratorOptions& options, - const Descriptor* desc) { - return HasRepeatedFields(options, desc) - ? (GetMessagePath(options, desc) + kRepeatedFieldArrayName) - : "null"; -} - -bool HasOneofFields(const Descriptor* desc) { - for (int i = 0; i < desc->field_count(); i++) { - if (desc->field(i)->containing_oneof()) { - return true; - } - } - return false; -} - -static const char* kOneofGroupArrayName = ".oneofGroups_"; - -string OneofFieldsArrayName(const GeneratorOptions& options, - const Descriptor* desc) { - return HasOneofFields(desc) - ? (GetMessagePath(options, desc) + kOneofGroupArrayName) - : "null"; -} - -string RepeatedFieldNumberList(const GeneratorOptions& options, - const Descriptor* desc) { - std::vector numbers; - for (int i = 0; i < desc->field_count(); i++) { - if (desc->field(i)->is_repeated() && !IsMap(options, desc->field(i))) { - numbers.push_back(JSFieldIndex(desc->field(i))); - } - } - return "[" + Join(numbers, ",") + "]"; -} - -string OneofGroupList(const Descriptor* desc) { - // List of arrays (one per oneof), each of which is a list of field indices - std::vector oneof_entries; - for (int i = 0; i < desc->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = desc->oneof_decl(i); - if (IgnoreOneof(oneof)) { - continue; - } - - std::vector oneof_fields; - for (int j = 0; j < oneof->field_count(); j++) { - if (IgnoreField(oneof->field(j))) { - continue; - } - oneof_fields.push_back(JSFieldIndex(oneof->field(j))); - } - oneof_entries.push_back("[" + Join(oneof_fields, ",") + "]"); - } - return "[" + Join(oneof_entries, ",") + "]"; -} - -string JSOneofArray(const GeneratorOptions& options, - const FieldDescriptor* field) { - return OneofFieldsArrayName(options, field->containing_type()) + "[" + - JSOneofIndex(field->containing_oneof()) + "]"; -} - -string RelativeTypeName(const FieldDescriptor* field) { - assert(field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM || - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE); - // For a field with an enum or message type, compute a name relative to the - // path name of the message type containing this field. - string package = field->file()->package(); - string containing_type = field->containing_type()->full_name() + "."; - string type = (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) ? - field->enum_type()->full_name() : field->message_type()->full_name(); - - // |prefix| is advanced as we find separators '.' past the common package - // prefix that yield common prefixes in the containing type's name and this - // type's name. - int prefix = 0; - for (int i = 0; i < type.size() && i < containing_type.size(); i++) { - if (type[i] != containing_type[i]) { - break; - } - if (type[i] == '.' && i >= package.size()) { - prefix = i + 1; - } - } - - return type.substr(prefix); -} - -string JSExtensionsObjectName(const GeneratorOptions& options, - const FileDescriptor* from_file, - const Descriptor* desc) { - if (desc->full_name() == "google.protobuf.bridge.MessageSet") { - // TODO(haberman): fix this for the kImportCommonJs case. - return "jspb.Message.messageSetExtensions"; - } else { - return MaybeCrossFileRef(options, from_file, desc) + ".extensions"; - } -} - -static const int kMapKeyField = 1; -static const int kMapValueField = 2; - -const FieldDescriptor* MapFieldKey(const FieldDescriptor* field) { - assert(field->is_map()); - return field->message_type()->FindFieldByNumber(kMapKeyField); -} - -const FieldDescriptor* MapFieldValue(const FieldDescriptor* field) { - assert(field->is_map()); - return field->message_type()->FindFieldByNumber(kMapValueField); -} - -string FieldDefinition(const GeneratorOptions& options, - const FieldDescriptor* field) { - if (IsMap(options, field)) { - const FieldDescriptor* key_field = MapFieldKey(field); - const FieldDescriptor* value_field = MapFieldValue(field); - string key_type = ProtoTypeName(options, key_field); - string value_type; - if (value_field->type() == FieldDescriptor::TYPE_ENUM || - value_field->type() == FieldDescriptor::TYPE_MESSAGE) { - value_type = RelativeTypeName(value_field); - } else { - value_type = ProtoTypeName(options, value_field); - } - return StringPrintf("map<%s, %s> %s = %d;", - key_type.c_str(), - value_type.c_str(), - field->name().c_str(), - field->number()); - } else { - string qualifier = field->is_repeated() ? "repeated" : - (field->is_optional() ? "optional" : "required"); - string type, name; - if (field->type() == FieldDescriptor::TYPE_ENUM || - field->type() == FieldDescriptor::TYPE_MESSAGE) { - type = RelativeTypeName(field); - name = field->name(); - } else if (field->type() == FieldDescriptor::TYPE_GROUP) { - type = "group"; - name = field->message_type()->name(); - } else { - type = ProtoTypeName(options, field); - name = field->name(); - } - return StringPrintf("%s %s %s = %d;", - qualifier.c_str(), - type.c_str(), - name.c_str(), - field->number()); - } -} - -string FieldComments(const FieldDescriptor* field, BytesMode bytes_mode) { - string comments; - if (field->cpp_type() == FieldDescriptor::CPPTYPE_BOOL) { - comments += - " * Note that Boolean fields may be set to 0/1 when serialized from " - "a Java server.\n" - " * You should avoid comparisons like {@code val === true/false} in " - "those cases.\n"; - } - if (field->type() == FieldDescriptor::TYPE_BYTES && bytes_mode == BYTES_U8) { - comments += - " * Note that Uint8Array is not supported on all browsers.\n" - " * @see http://caniuse.com/Uint8Array\n"; - } - return comments; -} - -bool ShouldGenerateExtension(const FieldDescriptor* field) { - return - field->is_extension() && - !IgnoreField(field); -} - -bool HasExtensions(const Descriptor* desc) { - for (int i = 0; i < desc->extension_count(); i++) { - if (ShouldGenerateExtension(desc->extension(i))) { - return true; - } - } - for (int i = 0; i < desc->nested_type_count(); i++) { - if (HasExtensions(desc->nested_type(i))) { - return true; - } - } - return false; -} - -bool HasExtensions(const FileDescriptor* file) { - for (int i = 0; i < file->extension_count(); i++) { - if (ShouldGenerateExtension(file->extension(i))) { - return true; - } - } - for (int i = 0; i < file->message_type_count(); i++) { - if (HasExtensions(file->message_type(i))) { - return true; - } - } - return false; -} - -bool HasMap(const GeneratorOptions& options, const Descriptor* desc) { - for (int i = 0; i < desc->field_count(); i++) { - if (IsMap(options, desc->field(i))) { - return true; - } - } - for (int i = 0; i < desc->nested_type_count(); i++) { - if (HasMap(options, desc->nested_type(i))) { - return true; - } - } - return false; -} - -bool FileHasMap(const GeneratorOptions& options, const FileDescriptor* desc) { - for (int i = 0; i < desc->message_type_count(); i++) { - if (HasMap(options, desc->message_type(i))) { - return true; - } - } - return false; -} - -bool IsExtendable(const Descriptor* desc) { - return desc->extension_range_count() > 0; -} - -// Returns the max index in the underlying data storage array beyond which the -// extension object is used. -string GetPivot(const Descriptor* desc) { - static const int kDefaultPivot = 500; - - // Find the max field number - int max_field_number = 0; - for (int i = 0; i < desc->field_count(); i++) { - if (!IgnoreField(desc->field(i)) && - desc->field(i)->number() > max_field_number) { - max_field_number = desc->field(i)->number(); - } - } - - int pivot = -1; - if (IsExtendable(desc) || (max_field_number >= kDefaultPivot)) { - pivot = ((max_field_number + 1) < kDefaultPivot) ? - (max_field_number + 1) : kDefaultPivot; - } - - return SimpleItoa(pivot); -} - -// Whether this field represents presence. For fields with presence, we -// generate extra methods (clearFoo() and hasFoo()) for this field. -bool HasFieldPresence(const GeneratorOptions& options, - const FieldDescriptor* field) { - if (field->is_repeated() || field->is_map()) { - // We say repeated fields and maps don't have presence, but we still do - // generate clearFoo() methods for them through a special case elsewhere. - return false; - } - - if (UseBrokenPresenceSemantics(options, field)) { - // Proto3 files with broken presence semantics have field presence. - return true; - } - - return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE || - field->containing_oneof() != NULL || - field->file()->syntax() == FileDescriptor::SYNTAX_PROTO2; -} - -// We use this to implement the semantics that same file can be generated -// multiple times, but the last one wins. We never actually write the files, -// but we keep a set of which descriptors were the final one for a given -// filename. -class FileDeduplicator { - public: - explicit FileDeduplicator(const GeneratorOptions& options) - : error_on_conflict_(options.error_on_name_conflict) {} - - bool AddFile(const string& filename, const void* desc, string* error) { - if (descs_by_filename_.find(filename) != descs_by_filename_.end()) { - if (error_on_conflict_) { - *error = "Name conflict: file name " + filename + - " would be generated by two descriptors"; - return false; - } - allowed_descs_.erase(descs_by_filename_[filename]); - } - - descs_by_filename_[filename] = desc; - allowed_descs_.insert(desc); - return true; - } - - void GetAllowedSet(std::set* allowed_set) { - *allowed_set = allowed_descs_; - } - - private: - bool error_on_conflict_; - std::map descs_by_filename_; - std::set allowed_descs_; -}; - -void DepthFirstSearch(const FileDescriptor* file, - std::vector* list, - std::set* seen) { - if (!seen->insert(file).second) { - return; - } - - // Add all dependencies. - for (int i = 0; i < file->dependency_count(); i++) { - DepthFirstSearch(file->dependency(i), list, seen); - } - - // Add this file. - list->push_back(file); -} - -// A functor for the predicate to remove_if() below. Returns true if a given -// FileDescriptor is not in the given set. -class NotInSet { - public: - explicit NotInSet(const std::set& file_set) - : file_set_(file_set) {} - - bool operator()(const FileDescriptor* file) { - return file_set_.count(file) == 0; - } - - private: - const std::set& file_set_; -}; - -// This function generates an ordering of the input FileDescriptors that matches -// the logic of the old code generator. The order is significant because two -// different input files can generate the same output file, and the last one -// needs to win. -void GenerateJspbFileOrder(const std::vector& input, - std::vector* ordered) { - // First generate an ordering of all reachable files (including dependencies) - // with depth-first search. This mimics the behavior of --include_imports, - // which is what the old codegen used. - ordered->clear(); - std::set seen; - std::set input_set; - for (int i = 0; i < input.size(); i++) { - DepthFirstSearch(input[i], ordered, &seen); - input_set.insert(input[i]); - } - - // Now remove the entries that are not actually in our input list. - ordered->erase( - std::remove_if(ordered->begin(), ordered->end(), NotInSet(input_set)), - ordered->end()); -} - -// If we're generating code in file-per-type mode, avoid overwriting files -// by choosing the last descriptor that writes each filename and permitting -// only those to generate code. - -bool GenerateJspbAllowedSet(const GeneratorOptions& options, - const std::vector& files, - std::set* allowed_set, - string* error) { - std::vector files_ordered; - GenerateJspbFileOrder(files, &files_ordered); - - // Choose the last descriptor for each filename. - FileDeduplicator dedup(options); - for (int i = 0; i < files_ordered.size(); i++) { - for (int j = 0; j < files_ordered[i]->message_type_count(); j++) { - const Descriptor* desc = files_ordered[i]->message_type(j); - if (!dedup.AddFile(GetMessageFileName(options, desc), desc, error)) { - return false; - } - } - for (int j = 0; j < files_ordered[i]->enum_type_count(); j++) { - const EnumDescriptor* desc = files_ordered[i]->enum_type(j); - if (!dedup.AddFile(GetEnumFileName(options, desc), desc, error)) { - return false; - } - } - - // Pull out all free-floating extensions and generate files for those too. - bool has_extension = false; - - for (int j = 0; j < files_ordered[i]->extension_count(); j++) { - if (ShouldGenerateExtension(files_ordered[i]->extension(j))) { - has_extension = true; - } - } - - if (has_extension) { - if (!dedup.AddFile(GetExtensionFileName(options, files_ordered[i]), - files_ordered[i], error)) { - return false; - } - } - } - - dedup.GetAllowedSet(allowed_set); - - return true; -} - -// Embeds base64 encoded GeneratedCodeInfo proto in a comment at the end of -// file. -void EmbedCodeAnnotations(const GeneratedCodeInfo& annotations, - io::Printer* printer) { - // Serialize annotations proto into base64 string. - string meta_content; - annotations.SerializeToString(&meta_content); - string meta_64; - Base64Escape(meta_content, &meta_64); - - // Print base64 encoded annotations at the end of output file in - // a comment. - printer->Print("\n// Below is base64 encoded GeneratedCodeInfo proto"); - printer->Print("\n// $encoded_proto$\n", "encoded_proto", meta_64); -} - -} // anonymous namespace - -void Generator::GenerateHeader(const GeneratorOptions& options, - io::Printer* printer) const { - printer->Print("/**\n" - " * @fileoverview\n" - " * @enhanceable\n" - " * @suppress {messageConventions} JS Compiler reports an " - "error if a variable or\n" - " * field starts with 'MSG_' and isn't a translatable " - "message.\n" - " * @public\n" - " */\n" - "// GENERATED CODE -- DO NOT EDIT!\n" - "\n"); -} - -void Generator::FindProvidesForFile(const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* file, - std::set* provided) const { - for (int i = 0; i < file->message_type_count(); i++) { - FindProvidesForMessage(options, printer, file->message_type(i), provided); - } - for (int i = 0; i < file->enum_type_count(); i++) { - FindProvidesForEnum(options, printer, file->enum_type(i), provided); - } -} - -void Generator::FindProvides(const GeneratorOptions& options, - io::Printer* printer, - const std::vector& files, - std::set* provided) const { - for (int i = 0; i < files.size(); i++) { - FindProvidesForFile(options, printer, files[i], provided); - } - - printer->Print("\n"); -} - -void Generator::FindProvidesForMessage( - const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc, - std::set* provided) const { - if (IgnoreMessage(options, desc)) { - return; - } - - string name = GetMessagePath(options, desc); - provided->insert(name); - - for (int i = 0; i < desc->enum_type_count(); i++) { - FindProvidesForEnum(options, printer, desc->enum_type(i), - provided); - } - for (int i = 0; i < desc->nested_type_count(); i++) { - FindProvidesForMessage(options, printer, desc->nested_type(i), - provided); - } -} - -void Generator::FindProvidesForEnum(const GeneratorOptions& options, - io::Printer* printer, - const EnumDescriptor* enumdesc, - std::set* provided) const { - string name = GetEnumPath(options, enumdesc); - provided->insert(name); -} - -void Generator::FindProvidesForFields( - const GeneratorOptions& options, - io::Printer* printer, - const std::vector& fields, - std::set* provided) const { - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - - if (IgnoreField(field)) { - continue; - } - - string name = GetFilePath(options, field->file()) + "." + - JSObjectFieldName(options, field); - provided->insert(name); - } -} - -void Generator::GenerateProvides(const GeneratorOptions& options, - io::Printer* printer, - std::set* provided) const { - for (std::set::iterator it = provided->begin(); - it != provided->end(); ++it) { - if (options.import_style == GeneratorOptions::kImportClosure) { - printer->Print("goog.provide('$name$');\n", "name", *it); - } else { - // We aren't using Closure's import system, but we use goog.exportSymbol() - // to construct the expected tree of objects, eg. - // - // goog.exportSymbol('foo.bar.Baz', null, this); - // - // // Later generated code expects foo.bar = {} to exist: - // foo.bar.Baz = function() { /* ... */ } - printer->Print("goog.exportSymbol('$name$', null, global);\n", "name", - *it); - } - } -} - -void Generator::GenerateRequiresForMessage(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc, - std::set* provided) const { - std::set required; - std::set forwards; - bool have_message = false; - FindRequiresForMessage(options, desc, - &required, &forwards, &have_message); - - GenerateRequiresImpl(options, printer, &required, &forwards, provided, - /* require_jspb = */ have_message, - /* require_extension = */ HasExtensions(desc), - /* require_map = */ HasMap(options, desc)); -} - -void Generator::GenerateRequiresForLibrary( - const GeneratorOptions& options, io::Printer* printer, - const std::vector& files, - std::set* provided) const { - GOOGLE_CHECK_EQ(options.import_style, GeneratorOptions::kImportClosure); - // For Closure imports we need to import every message type individually. - std::set required; - std::set forwards; - bool have_extensions = false; - bool have_map = false; - bool have_message = false; - - for (int i = 0; i < files.size(); i++) { - for (int j = 0; j < files[i]->message_type_count(); j++) { - const Descriptor* desc = files[i]->message_type(j); - if (!IgnoreMessage(options, desc)) { - FindRequiresForMessage(options, desc, &required, &forwards, - &have_message); - } - } - - if (!have_extensions && HasExtensions(files[i])) { - have_extensions = true; - } - - if (!have_map && FileHasMap(options, files[i])) { - have_map = true; - } - - for (int j = 0; j < files[i]->extension_count(); j++) { - const FieldDescriptor* extension = files[i]->extension(j); - if (IgnoreField(extension)) { - continue; - } - if (extension->containing_type()->full_name() != - "google.protobuf.bridge.MessageSet") { - required.insert(GetMessagePath(options, extension->containing_type())); - } - FindRequiresForField(options, extension, &required, &forwards); - have_extensions = true; - } - } - - GenerateRequiresImpl(options, printer, &required, &forwards, provided, - /* require_jspb = */ have_message, - /* require_extension = */ have_extensions, - /* require_map = */ have_map); -} - -void Generator::GenerateRequiresForExtensions( - const GeneratorOptions& options, io::Printer* printer, - const std::vector& fields, - std::set* provided) const { - std::set required; - std::set forwards; - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - if (IgnoreField(field)) { - continue; - } - FindRequiresForExtension(options, field, &required, &forwards); - } - - GenerateRequiresImpl(options, printer, &required, &forwards, provided, - /* require_jspb = */ false, - /* require_extension = */ fields.size() > 0, - /* require_map = */ false); -} - -void Generator::GenerateRequiresImpl(const GeneratorOptions& options, - io::Printer* printer, - std::set* required, - std::set* forwards, - std::set* provided, - bool require_jspb, bool require_extension, - bool require_map) const { - if (require_jspb) { - required->insert("jspb.Message"); - required->insert("jspb.BinaryReader"); - required->insert("jspb.BinaryWriter"); - } - if (require_extension) { - required->insert("jspb.ExtensionFieldBinaryInfo"); - required->insert("jspb.ExtensionFieldInfo"); - } - if (require_map) { - required->insert("jspb.Map"); - } - - std::set::iterator it; - for (it = required->begin(); it != required->end(); ++it) { - if (provided->find(*it) != provided->end()) { - continue; - } - printer->Print("goog.require('$name$');\n", - "name", *it); - } - - printer->Print("\n"); - - for (it = forwards->begin(); it != forwards->end(); ++it) { - if (provided->find(*it) != provided->end()) { - continue; - } - printer->Print("goog.forwardDeclare('$name$');\n", - "name", *it); - } -} - -bool NamespaceOnly(const Descriptor* desc) { - return false; -} - -void Generator::FindRequiresForMessage( - const GeneratorOptions& options, - const Descriptor* desc, - std::set* required, - std::set* forwards, - bool* have_message) const { - - - if (!NamespaceOnly(desc)) { - *have_message = true; - for (int i = 0; i < desc->field_count(); i++) { - const FieldDescriptor* field = desc->field(i); - if (IgnoreField(field)) { - continue; - } - FindRequiresForField(options, field, required, forwards); - } - } - - for (int i = 0; i < desc->extension_count(); i++) { - const FieldDescriptor* field = desc->extension(i); - if (IgnoreField(field)) { - continue; - } - FindRequiresForExtension(options, field, required, forwards); - } - - for (int i = 0; i < desc->nested_type_count(); i++) { - FindRequiresForMessage(options, desc->nested_type(i), required, forwards, - have_message); - } -} - -void Generator::FindRequiresForField(const GeneratorOptions& options, - const FieldDescriptor* field, - std::set* required, - std::set* forwards) const { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM && - // N.B.: file-level extensions with enum type do *not* create - // dependencies, as per original codegen. - !(field->is_extension() && field->extension_scope() == NULL)) { - if (options.add_require_for_enums) { - required->insert(GetEnumPath(options, field->enum_type())); - } else { - forwards->insert(GetEnumPath(options, field->enum_type())); - } - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (!IgnoreMessage(options, field->message_type())) { - required->insert(GetMessagePath(options, field->message_type())); - } - } -} - -void Generator::FindRequiresForExtension(const GeneratorOptions& options, - const FieldDescriptor* field, - std::set* required, - std::set* forwards) const { - if (field->containing_type()->full_name() != "google.protobuf.bridge.MessageSet") { - required->insert(GetMessagePath(options, field->containing_type())); - } - FindRequiresForField(options, field, required, forwards); -} - -void Generator::GenerateTestOnly(const GeneratorOptions& options, - io::Printer* printer) const { - if (options.testonly) { - printer->Print("goog.setTestOnly();\n\n"); - } - printer->Print("\n"); -} - -void Generator::GenerateClassesAndEnums(const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* file) const { - for (int i = 0; i < file->message_type_count(); i++) { - GenerateClass(options, printer, file->message_type(i)); - } - for (int i = 0; i < file->enum_type_count(); i++) { - GenerateEnum(options, printer, file->enum_type(i)); - } -} - -void Generator::GenerateClass(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - if (IgnoreMessage(options, desc)) { - return; - } - - if (!NamespaceOnly(desc)) { - printer->Print("\n"); - GenerateClassConstructor(options, printer, desc); - GenerateClassFieldInfo(options, printer, desc); - - - GenerateClassToObject(options, printer, desc); - // These must come *before* the extension-field info generation in - // GenerateClassRegistration so that references to the binary - // serialization/deserialization functions may be placed in the extension - // objects. - GenerateClassDeserializeBinary(options, printer, desc); - GenerateClassSerializeBinary(options, printer, desc); - } - - // Recurse on nested types. These must come *before* the extension-field - // info generation in GenerateClassRegistration so that extensions that - // reference nested types proceed the definitions of the nested types. - for (int i = 0; i < desc->enum_type_count(); i++) { - GenerateEnum(options, printer, desc->enum_type(i)); - } - for (int i = 0; i < desc->nested_type_count(); i++) { - GenerateClass(options, printer, desc->nested_type(i)); - } - - if (!NamespaceOnly(desc)) { - GenerateClassRegistration(options, printer, desc); - GenerateClassFields(options, printer, desc); - if (IsExtendable(desc) && desc->full_name() != "google.protobuf.bridge.MessageSet") { - GenerateClassExtensionFieldInfo(options, printer, desc); - } - - if (options.import_style != GeneratorOptions::kImportClosure) { - for (int i = 0; i < desc->extension_count(); i++) { - GenerateExtension(options, printer, desc->extension(i)); - } - } - } -} - -void Generator::GenerateClassConstructor(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - printer->Print( - "/**\n" - " * Generated by JsPbCodeGenerator.\n" - " * @param {Array=} opt_data Optional initial data array, typically " - "from a\n" - " * server response, or constructed directly in Javascript. The array " - "is used\n" - " * in place and becomes part of the constructed object. It is not " - "cloned.\n" - " * If no data is provided, the constructed object will be empty, but " - "still\n" - " * valid.\n" - " * @extends {jspb.Message}\n" - " * @constructor\n" - " */\n" - "$classprefix$$classname$ = function(opt_data) {\n", - "classprefix", GetMessagePathPrefix(options, desc), - "classname", desc->name()); - printer->Annotate("classname", desc); - string message_id = GetMessageId(desc); - printer->Print( - " jspb.Message.initialize(this, opt_data, $messageId$, $pivot$, " - "$rptfields$, $oneoffields$);\n", - "messageId", !message_id.empty() ? - ("'" + message_id + "'") : - (IsResponse(desc) ? "''" : "0"), - "pivot", GetPivot(desc), - "rptfields", RepeatedFieldsArrayName(options, desc), - "oneoffields", OneofFieldsArrayName(options, desc)); - printer->Print( - "};\n" - "goog.inherits($classname$, jspb.Message);\n" - "if (goog.DEBUG && !COMPILED) {\n" - " $classname$.displayName = '$classname$';\n" - "}\n", - "classname", GetMessagePath(options, desc)); -} - -void Generator::GenerateClassFieldInfo(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - if (HasRepeatedFields(options, desc)) { - printer->Print( - "/**\n" - " * List of repeated fields within this message type.\n" - " * @private {!Array}\n" - " * @const\n" - " */\n" - "$classname$$rptfieldarray$ = $rptfields$;\n" - "\n", - "classname", GetMessagePath(options, desc), - "rptfieldarray", kRepeatedFieldArrayName, - "rptfields", RepeatedFieldNumberList(options, desc)); - } - - if (HasOneofFields(desc)) { - printer->Print( - "/**\n" - " * Oneof group definitions for this message. Each group defines the " - "field\n" - " * numbers belonging to that group. When of these fields' value is " - "set, all\n" - " * other fields in the group are cleared. During deserialization, if " - "multiple\n" - " * fields are encountered for a group, only the last value seen will " - "be kept.\n" - " * @private {!Array>}\n" - " * @const\n" - " */\n" - "$classname$$oneofgrouparray$ = $oneofgroups$;\n" - "\n", - "classname", GetMessagePath(options, desc), - "oneofgrouparray", kOneofGroupArrayName, - "oneofgroups", OneofGroupList(desc)); - - for (int i = 0; i < desc->oneof_decl_count(); i++) { - if (IgnoreOneof(desc->oneof_decl(i))) { - continue; - } - GenerateOneofCaseDefinition(options, printer, desc->oneof_decl(i)); - } - } -} - -void Generator::GenerateClassXid(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - printer->Print( - "\n" - "\n" - "$class$.prototype.messageXid = xid('$class$');\n", - "class", GetMessagePath(options, desc)); -} - -void Generator::GenerateOneofCaseDefinition( - const GeneratorOptions& options, - io::Printer* printer, - const OneofDescriptor* oneof) const { - printer->Print( - "/**\n" - " * @enum {number}\n" - " */\n" - "$classname$.$oneof$Case = {\n" - " $upcase$_NOT_SET: 0", - "classname", GetMessagePath(options, oneof->containing_type()), - "oneof", JSOneofName(oneof), - "upcase", ToEnumCase(oneof->name())); - - for (int i = 0; i < oneof->field_count(); i++) { - if (IgnoreField(oneof->field(i))) { - continue; - } - - printer->Print( - ",\n" - " $upcase$: $number$", - "upcase", ToEnumCase(oneof->field(i)->name()), - "number", JSFieldIndex(oneof->field(i))); - printer->Annotate("upcase", oneof->field(i)); - } - - printer->Print( - "\n" - "};\n" - "\n" - "/**\n" - " * @return {$class$.$oneof$Case}\n" - " */\n" - "$class$.prototype.get$oneof$Case = function() {\n" - " return /** @type {$class$.$oneof$Case} */(jspb.Message." - "computeOneofCase(this, $class$.oneofGroups_[$oneofindex$]));\n" - "};\n" - "\n", - "class", GetMessagePath(options, oneof->containing_type()), - "oneof", JSOneofName(oneof), - "oneofindex", JSOneofIndex(oneof)); -} - -void Generator::GenerateClassToObject(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - printer->Print( - "\n" - "\n" - "if (jspb.Message.GENERATE_TO_OBJECT) {\n" - "/**\n" - " * Creates an object representation of this proto suitable for use in " - "Soy templates.\n" - " * Field names that are reserved in JavaScript and will be renamed to " - "pb_name.\n" - " * To access a reserved field use, foo.pb_, eg, foo.pb_default.\n" - " * For the list of reserved names please see:\n" - " * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS.\n" - " * @param {boolean=} opt_includeInstance Whether to include the JSPB " - "instance\n" - " * for transitional soy proto support: http://goto/soy-param-" - "migration\n" - " * @return {!Object}\n" - " */\n" - "$classname$.prototype.toObject = function(opt_includeInstance) {\n" - " return $classname$.toObject(opt_includeInstance, this);\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Static version of the {@see toObject} method.\n" - " * @param {boolean|undefined} includeInstance Whether to include the " - "JSPB\n" - " * instance for transitional soy proto support:\n" - " * http://goto/soy-param-migration\n" - " * @param {!$classname$} msg The msg instance to transform.\n" - " * @return {!Object}\n" - " * @suppress {unusedLocalVariables} f is only used for nested messages\n" - " */\n" - "$classname$.toObject = function(includeInstance, msg) {\n" - " var f, obj = {", - "classname", GetMessagePath(options, desc)); - - bool first = true; - for (int i = 0; i < desc->field_count(); i++) { - const FieldDescriptor* field = desc->field(i); - if (IgnoreField(field)) { - continue; - } - - if (!first) { - printer->Print(",\n "); - } else { - printer->Print("\n "); - first = false; - } - - GenerateClassFieldToObject(options, printer, field); - } - - if (!first) { - printer->Print("\n };\n\n"); - } else { - printer->Print("\n\n };\n\n"); - } - - if (IsExtendable(desc)) { - printer->Print( - " jspb.Message.toObjectExtension(/** @type {!jspb.Message} */ (msg), " - "obj,\n" - " $extObject$, $class$.prototype.getExtension,\n" - " includeInstance);\n", - "extObject", JSExtensionsObjectName(options, desc->file(), desc), - "class", GetMessagePath(options, desc)); - } - - printer->Print( - " if (includeInstance) {\n" - " obj.$$jspbMessageInstance = msg;\n" - " }\n" - " return obj;\n" - "};\n" - "}\n" - "\n" - "\n", - "classname", GetMessagePath(options, desc)); -} - -void Generator::GenerateFieldValueExpression(io::Printer* printer, - const char *obj_reference, - const FieldDescriptor* field, - bool use_default) const { - bool is_float_or_double = - field->cpp_type() == FieldDescriptor::CPPTYPE_FLOAT || - field->cpp_type() == FieldDescriptor::CPPTYPE_DOUBLE; - if (use_default) { - if (is_float_or_double) { - // Coerce "Nan" and "Infinity" to actual float values. - // - // This will change null to 0, but that doesn't matter since we're getting - // with a default. - printer->Print("+"); - } - - printer->Print( - "jspb.Message.getFieldWithDefault($obj$, $index$, $default$)", - "obj", obj_reference, - "index", JSFieldIndex(field), - "default", JSFieldDefault(field)); - } else { - if (is_float_or_double) { - if (field->is_required()) { - // Use "+" to convert all fields to numeric (including null). - printer->Print( - "+jspb.Message.getField($obj$, $index$)", - "index", JSFieldIndex(field), - "obj", obj_reference); - } else { - // Converts "NaN" and "Infinity" while preserving null. - printer->Print( - "jspb.Message.get$cardinality$FloatingPointField($obj$, $index$)", - "cardinality", field->is_repeated() ? "Repeated" : "Optional", - "index", JSFieldIndex(field), - "obj", obj_reference); - } - } else { - printer->Print("jspb.Message.get$cardinality$Field($obj$, $index$)", - "cardinality", field->is_repeated() ? "Repeated" : "", - "index", JSFieldIndex(field), - "obj", obj_reference); - } - } -} - -void Generator::GenerateClassFieldToObject(const GeneratorOptions& options, - io::Printer* printer, - const FieldDescriptor* field) const { - printer->Print("$fieldname$: ", - "fieldname", JSObjectFieldName(options, field)); - - if (IsMap(options, field)) { - const FieldDescriptor* value_field = MapFieldValue(field); - // If the map values are of a message type, we must provide their static - // toObject() method; otherwise we pass undefined for that argument. - string value_to_object; - if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - value_to_object = - GetMessagePath(options, value_field->message_type()) + ".toObject"; - } else { - value_to_object = "undefined"; - } - printer->Print( - "(f = msg.get$name$()) ? f.toObject(includeInstance, $valuetoobject$) " - ": []", - "name", JSGetterName(options, field), "valuetoobject", value_to_object); - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - // Message field. - if (field->is_repeated()) { - { - printer->Print("jspb.Message.toObjectList(msg.get$getter$(),\n" - " $type$.toObject, includeInstance)", - "getter", JSGetterName(options, field), - "type", SubmessageTypeRef(options, field)); - } - } else { - printer->Print("(f = msg.get$getter$()) && " - "$type$.toObject(includeInstance, f)", - "getter", JSGetterName(options, field), - "type", SubmessageTypeRef(options, field)); - } - } else if (field->type() == FieldDescriptor::TYPE_BYTES) { - // For bytes fields we want to always return the B64 data. - printer->Print("msg.get$getter$()", - "getter", JSGetterName(options, field, BYTES_B64)); - } else { - bool use_default = field->has_default_value(); - - if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 && - // Repeated fields get initialized to their default in the constructor - // (why?), so we emit a plain getField() call for them. - !field->is_repeated() && !UseBrokenPresenceSemantics(options, field)) { - // Proto3 puts all defaults (including implicit defaults) in toObject(). - // But for proto2 we leave the existing semantics unchanged: unset fields - // without default are unset. - use_default = true; - } - - // We don't implement this by calling the accessors, because the semantics - // of the accessors are changing independently of the toObject() semantics. - // We are migrating the accessors to return defaults instead of null, but - // it may take longer to migrate toObject (or we might not want to do it at - // all). So we want to generate independent code. - GenerateFieldValueExpression(printer, "msg", field, use_default); - } -} - -void Generator::GenerateClassFromObject(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - printer->Print( - "if (jspb.Message.GENERATE_FROM_OBJECT) {\n" - "/**\n" - " * Loads data from an object into a new instance of this proto.\n" - " * @param {!Object} obj The object representation of this proto to\n" - " * load the data from.\n" - " * @return {!$classname$}\n" - " */\n" - "$classname$.fromObject = function(obj) {\n" - " var f, msg = new $classname$();\n", - "classname", GetMessagePath(options, desc)); - - for (int i = 0; i < desc->field_count(); i++) { - const FieldDescriptor* field = desc->field(i); - GenerateClassFieldFromObject(options, printer, field); - } - - printer->Print( - " return msg;\n" - "};\n" - "}\n"); -} - -void Generator::GenerateClassFieldFromObject( - const GeneratorOptions& options, - io::Printer* printer, - const FieldDescriptor* field) const { - if (IsMap(options, field)) { - const FieldDescriptor* value_field = MapFieldValue(field); - if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) { - // Since the map values are of message type, we have to do some extra work - // to recursively call fromObject() on them before setting the map field. - printer->Print( - " goog.isDef(obj.$name$) && jspb.Message.setWrapperField(\n" - " msg, $index$, jspb.Map.fromObject(obj.$name$, $fieldclass$, " - "$fieldclass$.fromObject));\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field), - "fieldclass", GetMessagePath(options, value_field->message_type())); - } else { - // `msg` is a newly-constructed message object that has not yet built any - // map containers wrapping underlying arrays, so we can simply directly - // set the array here without fear of a stale wrapper. - printer->Print( - " goog.isDef(obj.$name$) && " - "jspb.Message.setField(msg, $index$, obj.$name$);\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field)); - } - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - // Message field (singular or repeated) - if (field->is_repeated()) { - { - printer->Print( - " goog.isDef(obj.$name$) && " - "jspb.Message.setRepeatedWrapperField(\n" - " msg, $index$, goog.array.map(obj.$name$, function(i) {\n" - " return $fieldclass$.fromObject(i);\n" - " }));\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field), - "fieldclass", SubmessageTypeRef(options, field)); - } - } else { - printer->Print( - " goog.isDef(obj.$name$) && jspb.Message.setWrapperField(\n" - " msg, $index$, $fieldclass$.fromObject(obj.$name$));\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field), - "fieldclass", SubmessageTypeRef(options, field)); - } - } else { - // Simple (primitive) field. - printer->Print( - " goog.isDef(obj.$name$) && jspb.Message.setField(msg, $index$, " - "obj.$name$);\n", - "name", JSObjectFieldName(options, field), - "index", JSFieldIndex(field)); - } -} - -void Generator::GenerateClassRegistration(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - // Register any extensions defined inside this message type. - for (int i = 0; i < desc->extension_count(); i++) { - const FieldDescriptor* extension = desc->extension(i); - if (ShouldGenerateExtension(extension)) { - GenerateExtension(options, printer, extension); - } - } - -} - -void Generator::GenerateClassFields(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - for (int i = 0; i < desc->field_count(); i++) { - if (!IgnoreField(desc->field(i))) { - GenerateClassField(options, printer, desc->field(i)); - } - } -} - -void GenerateBytesWrapper(const GeneratorOptions& options, - io::Printer* printer, - const FieldDescriptor* field, - BytesMode bytes_mode) { - string type = JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false, bytes_mode); - printer->Print( - "/**\n" - " * $fielddef$\n" - "$comment$" - " * This is a type-conversion wrapper around `get$defname$()`\n" - " * @return {$type$}\n" - " */\n" - "$class$.prototype.get$name$ = function() {\n" - " return /** @type {$type$} */ (jspb.Message.bytes$list$As$suffix$(\n" - " this.get$defname$()));\n" - "};\n" - "\n" - "\n", - "fielddef", FieldDefinition(options, field), - "comment", FieldComments(field, bytes_mode), - "type", type, - "class", GetMessagePath(options, field->containing_type()), - "name", JSGetterName(options, field, bytes_mode), - "list", field->is_repeated() ? "List" : "", - "suffix", JSByteGetterSuffix(bytes_mode), - "defname", JSGetterName(options, field, BYTES_DEFAULT)); -} - -void Generator::GenerateClassField(const GeneratorOptions& options, - io::Printer* printer, - const FieldDescriptor* field) const { - if (IsMap(options, field)) { - const FieldDescriptor* key_field = MapFieldKey(field); - const FieldDescriptor* value_field = MapFieldValue(field); - // Map field: special handling to instantiate the map object on demand. - string key_type = - JSFieldTypeAnnotation( - options, key_field, - /* is_setter_argument = */ false, - /* force_present = */ true, - /* singular_if_not_packed = */ false); - string value_type = - JSFieldTypeAnnotation( - options, value_field, - /* is_setter_argument = */ false, - /* force_present = */ true, - /* singular_if_not_packed = */ false); - - printer->Print( - "/**\n" - " * $fielddef$\n" - " * @param {boolean=} opt_noLazyCreate Do not create the map if\n" - " * empty, instead returning `undefined`\n" - " * @return {!jspb.Map<$keytype$,$valuetype$>}\n" - " */\n", - "fielddef", FieldDefinition(options, field), - "keytype", key_type, - "valuetype", value_type); - printer->Print( - "$class$.prototype.$gettername$ = function(opt_noLazyCreate) {\n" - " return /** @type {!jspb.Map<$keytype$,$valuetype$>} */ (\n", - "class", GetMessagePath(options, field->containing_type()), - "gettername", "get" + JSGetterName(options, field), - "keytype", key_type, - "valuetype", value_type); - printer->Annotate("gettername", field); - printer->Print( - " jspb.Message.getMapField(this, $index$, opt_noLazyCreate", - "index", JSFieldIndex(field)); - - if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) { - printer->Print( - ",\n" - " $messageType$", - "messageType", GetMessagePath(options, value_field->message_type())); - } else { - printer->Print(",\n" - " null"); - } - - printer->Print( - "));\n"); - - printer->Print( - "};\n" - "\n" - "\n"); - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - // Message field: special handling in order to wrap the underlying data - // array with a message object. - - printer->Print( - "/**\n" - " * $fielddef$\n" - "$comment$" - " * @return {$type$}\n" - " */\n", - "fielddef", FieldDefinition(options, field), - "comment", FieldComments(field, BYTES_DEFAULT), - "type", JSFieldTypeAnnotation(options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false)); - printer->Print( - "$class$.prototype.$gettername$ = function() {\n" - " return /** @type{$type$} */ (\n" - " jspb.Message.get$rpt$WrapperField(this, $wrapperclass$, " - "$index$$required$));\n" - "};\n" - "\n" - "\n", - "class", GetMessagePath(options, field->containing_type()), - "gettername", "get" + JSGetterName(options, field), - "type", JSFieldTypeAnnotation(options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false), - "rpt", (field->is_repeated() ? "Repeated" : ""), - "index", JSFieldIndex(field), - "wrapperclass", SubmessageTypeRef(options, field), - "required", (field->label() == FieldDescriptor::LABEL_REQUIRED ? - ", 1" : "")); - printer->Annotate("gettername", field); - printer->Print( - "/** @param {$optionaltype$} value$returndoc$ */\n" - "$class$.prototype.$settername$ = function(value) {\n" - " jspb.Message.set$oneoftag$$repeatedtag$WrapperField(", - "optionaltype", - JSFieldTypeAnnotation(options, field, - /* is_setter_argument = */ true, - /* force_present = */ false, - /* singular_if_not_packed = */ false), - "returndoc", JSReturnDoc(options, field), - "class", GetMessagePath(options, field->containing_type()), - "settername", "set" + JSGetterName(options, field), - "oneoftag", (field->containing_oneof() ? "Oneof" : ""), - "repeatedtag", (field->is_repeated() ? "Repeated" : "")); - printer->Annotate("settername", field); - - printer->Print( - "this, $index$$oneofgroup$, value);$returnvalue$\n" - "};\n" - "\n" - "\n", - "index", JSFieldIndex(field), - "oneofgroup", (field->containing_oneof() ? - (", " + JSOneofArray(options, field)) : ""), - "returnvalue", JSReturnClause(field)); - - if (field->is_repeated()) { - GenerateRepeatedMessageHelperMethods(options, printer, field); - } - - } else { - bool untyped = - false; - - // Simple (primitive) field, either singular or repeated. - - // TODO(b/26173701): Always use BYTES_DEFAULT for the getter return type; - // at this point we "lie" to non-binary users and tell the return - // type is always base64 string, pending a LSC to migrate to typed getters. - BytesMode bytes_mode = - field->type() == FieldDescriptor::TYPE_BYTES && !options.binary ? - BYTES_B64 : BYTES_DEFAULT; - string typed_annotation = JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false, - /* bytes_mode = */ bytes_mode); - if (untyped) { - printer->Print( - "/**\n" - " * @return {?} Raw field, untyped.\n" - " */\n"); - } else { - printer->Print( - "/**\n" - " * $fielddef$\n" - "$comment$" - " * @return {$type$}\n" - " */\n", - "fielddef", FieldDefinition(options, field), - "comment", FieldComments(field, bytes_mode), - "type", typed_annotation); - } - - printer->Print( - "$class$.prototype.$gettername$ = function() {\n", - "class", GetMessagePath(options, field->containing_type()), - "gettername", "get" + JSGetterName(options, field)); - printer->Annotate("gettername", field); - - if (untyped) { - printer->Print( - " return "); - } else { - printer->Print( - " return /** @type {$type$} */ (", - "type", typed_annotation); - } - - bool use_default = !ReturnsNullWhenUnset(options, field); - - // Raw fields with no default set should just return undefined. - if (untyped && !field->has_default_value()) { - use_default = false; - } - - // Repeated fields get initialized to their default in the constructor - // (why?), so we emit a plain getField() call for them. - if (field->is_repeated()) { - use_default = false; - } - - GenerateFieldValueExpression(printer, "this", field, use_default); - - if (untyped) { - printer->Print( - ";\n" - "};\n" - "\n" - "\n"); - } else { - printer->Print( - ");\n" - "};\n" - "\n" - "\n"); - } - - if (field->type() == FieldDescriptor::TYPE_BYTES && !untyped) { - GenerateBytesWrapper(options, printer, field, BYTES_B64); - GenerateBytesWrapper(options, printer, field, BYTES_U8); - } - - if (untyped) { - printer->Print( - "/**\n" - " * @param {*} value$returndoc$\n" - " */\n", - "returndoc", JSReturnDoc(options, field)); - } else { - printer->Print( - "/** @param {$optionaltype$} value$returndoc$ */\n", "optionaltype", - JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ true, - /* force_present = */ false, - /* singular_if_not_packed = */ false), - "returndoc", JSReturnDoc(options, field)); - } - - if (field->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 && - !field->is_repeated() && !field->is_map() && - !HasFieldPresence(options, field)) { - // Proto3 non-repeated and non-map fields without presence use the - // setProto3*Field function. - printer->Print( - "$class$.prototype.$settername$ = function(value) {\n" - " jspb.Message.setProto3$typetag$Field(this, $index$, " - "value);$returnvalue$\n" - "};\n" - "\n" - "\n", - "class", GetMessagePath(options, field->containing_type()), - "settername", "set" + JSGetterName(options, field), "typetag", - JSTypeTag(field), "index", JSFieldIndex(field), "returnvalue", - JSReturnClause(field)); - printer->Annotate("settername", field); - } else { - // Otherwise, use the regular setField function. - printer->Print( - "$class$.prototype.$settername$ = function(value) {\n" - " jspb.Message.set$oneoftag$Field(this, $index$", - "class", GetMessagePath(options, field->containing_type()), - "settername", "set" + JSGetterName(options, field), "oneoftag", - (field->containing_oneof() ? "Oneof" : ""), "index", - JSFieldIndex(field)); - printer->Annotate("settername", field); - printer->Print( - "$oneofgroup$, $type$value$rptvalueinit$$typeclose$);$returnvalue$\n" - "};\n" - "\n" - "\n", - "type", - untyped ? "/** @type{string|number|boolean|Array|undefined} */(" : "", - "typeclose", untyped ? ")" : "", "oneofgroup", - (field->containing_oneof() ? (", " + JSOneofArray(options, field)) - : ""), - "returnvalue", JSReturnClause(field), "rptvalueinit", - (field->is_repeated() ? " || []" : "")); - } - - if (untyped) { - printer->Print( - "/**\n" - " * Clears the value.$returndoc$\n" - " */\n", - "returndoc", JSReturnDoc(options, field)); - } - - - if (field->is_repeated()) { - GenerateRepeatedPrimitiveHelperMethods(options, printer, field, untyped); - } - } - - // Generate clearFoo() method for map fields, repeated fields, and other - // fields with presence. - if (IsMap(options, field)) { - printer->Print( - "$class$.prototype.$clearername$ = function() {\n" - " this.$gettername$().clear();$returnvalue$\n" - "};\n" - "\n" - "\n", - "class", GetMessagePath(options, field->containing_type()), - "clearername", "clear" + JSGetterName(options, field), - "gettername", "get" + JSGetterName(options, field), - "returnvalue", JSReturnClause(field)); - printer->Annotate("clearername", field); - } else if (field->is_repeated() || - (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !field->is_required())) { - // Fields where we can delegate to the regular setter. - printer->Print( - "$class$.prototype.$clearername$ = function() {\n" - " this.$settername$($clearedvalue$);$returnvalue$\n" - "};\n" - "\n" - "\n", - "class", GetMessagePath(options, field->containing_type()), - "clearername", "clear" + JSGetterName(options, field), - "settername", "set" + JSGetterName(options, field), - "clearedvalue", (field->is_repeated() ? "[]" : "undefined"), - "returnvalue", JSReturnClause(field)); - printer->Annotate("clearername", field); - } else if (HasFieldPresence(options, field)) { - // Fields where we can't delegate to the regular setter because it doesn't - // accept "undefined" as an argument. - printer->Print( - "$class$.prototype.$clearername$ = function() {\n" - " jspb.Message.set$maybeoneof$Field(this, " - "$index$$maybeoneofgroup$, ", - "class", GetMessagePath(options, field->containing_type()), - "clearername", "clear" + JSGetterName(options, field), - "maybeoneof", (field->containing_oneof() ? "Oneof" : ""), - "maybeoneofgroup", (field->containing_oneof() ? - (", " + JSOneofArray(options, field)) : ""), - "index", JSFieldIndex(field)); - printer->Annotate("clearername", field); - printer->Print( - "$clearedvalue$);$returnvalue$\n" - "};\n" - "\n" - "\n", - "clearedvalue", (field->is_repeated() ? "[]" : "undefined"), - "returnvalue", JSReturnClause(field)); - } - - if (HasFieldPresence(options, field)) { - printer->Print( - "/**\n" - " * Returns whether this field is set.\n" - " * @return {!boolean}\n" - " */\n" - "$class$.prototype.$hasername$ = function() {\n" - " return jspb.Message.getField(this, $index$) != null;\n" - "};\n" - "\n" - "\n", - "class", GetMessagePath(options, field->containing_type()), - "hasername", "has" + JSGetterName(options, field), - "index", JSFieldIndex(field)); - printer->Annotate("hasername", field); - } -} - -void Generator::GenerateRepeatedPrimitiveHelperMethods( - const GeneratorOptions& options, io::Printer* printer, - const FieldDescriptor* field, bool untyped) const { - // clang-format off - printer->Print( - "/**\n" - " * @param {!$optionaltype$} value\n" - " * @param {number=} opt_index$returndoc$\n" - " */\n" - "$class$.prototype.$addername$ = function(value, opt_index) {\n" - " jspb.Message.addToRepeatedField(this, $index$", - "class", GetMessagePath(options, field->containing_type()), "addername", - "add" + JSGetterName(options, field, BYTES_DEFAULT, - /* drop_list = */ true), - "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), - "index", JSFieldIndex(field), - "returndoc", JSReturnDoc(options, field)); - printer->Annotate("addername", field); - printer->Print( - "$oneofgroup$, $type$value$rptvalueinit$$typeclose$, " - "opt_index);$returnvalue$\n" - "};\n" - "\n" - "\n", - "type", untyped ? "/** @type{string|number|boolean|!Uint8Array} */(" : "", - "typeclose", untyped ? ")" : "", "oneofgroup", - (field->containing_oneof() ? (", " + JSOneofArray(options, field)) : ""), - "rptvalueinit", "", - "returnvalue", JSReturnClause(field)); - // clang-format on -} - -void Generator::GenerateRepeatedMessageHelperMethods( - const GeneratorOptions& options, io::Printer* printer, - const FieldDescriptor* field) const { - printer->Print( - "/**\n" - " * @param {!$optionaltype$=} opt_value\n" - " * @param {number=} opt_index\n" - " * @return {!$optionaltype$}\n" - " */\n" - "$class$.prototype.add$name$ = function(opt_value, opt_index) {\n" - " return jspb.Message.addTo$repeatedtag$WrapperField(", - "optionaltype", JSTypeName(options, field, BYTES_DEFAULT), - "class", GetMessagePath(options, field->containing_type()), - "name", JSGetterName(options, field, BYTES_DEFAULT, - /* drop_list = */ true), - "repeatedtag", (field->is_repeated() ? "Repeated" : "")); - - printer->Print( - "this, $index$$oneofgroup$, opt_value, $ctor$, opt_index);\n" - "};\n" - "\n" - "\n", - "index", JSFieldIndex(field), "oneofgroup", - (field->containing_oneof() ? (", " + JSOneofArray(options, field)) : ""), - "ctor", GetMessagePath(options, field->message_type())); -} - -void Generator::GenerateClassExtensionFieldInfo(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - if (IsExtendable(desc)) { - printer->Print( - "\n" - "/**\n" - " * The extensions registered with this message class. This is a " - "map of\n" - " * extension field number to fieldInfo object.\n" - " *\n" - " * For example:\n" - " * { 123: {fieldIndex: 123, fieldName: {my_field_name: 0}, " - "ctor: proto.example.MyMessage} }\n" - " *\n" - " * fieldName contains the JsCompiler renamed field name property " - "so that it\n" - " * works in OPTIMIZED mode.\n" - " *\n" - " * @type {!Object}\n" - " */\n" - "$class$.extensions = {};\n" - "\n", - "class", GetMessagePath(options, desc)); - - printer->Print( - "\n" - "/**\n" - " * The extensions registered with this message class. This is a " - "map of\n" - " * extension field number to fieldInfo object.\n" - " *\n" - " * For example:\n" - " * { 123: {fieldIndex: 123, fieldName: {my_field_name: 0}, " - "ctor: proto.example.MyMessage} }\n" - " *\n" - " * fieldName contains the JsCompiler renamed field name property " - "so that it\n" - " * works in OPTIMIZED mode.\n" - " *\n" - " * @type {!Object}\n" - " */\n" - "$class$.extensionsBinary = {};\n" - "\n", - "class", GetMessagePath(options, desc)); - } -} - - -void Generator::GenerateClassDeserializeBinary(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - // TODO(cfallin): Handle lazy decoding when requested by field option and/or - // by default for 'bytes' fields and packed repeated fields. - - printer->Print( - "/**\n" - " * Deserializes binary data (in protobuf wire format).\n" - " * @param {jspb.ByteSource} bytes The bytes to deserialize.\n" - " * @return {!$class$}\n" - " */\n" - "$class$.deserializeBinary = function(bytes) {\n" - " var reader = new jspb.BinaryReader(bytes);\n" - " var msg = new $class$;\n" - " return $class$.deserializeBinaryFromReader(msg, reader);\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Deserializes binary data (in protobuf wire format) from the\n" - " * given reader into the given message object.\n" - " * @param {!$class$} msg The message object to deserialize into.\n" - " * @param {!jspb.BinaryReader} reader The BinaryReader to use.\n" - " * @return {!$class$}\n" - " */\n" - "$class$.deserializeBinaryFromReader = function(msg, reader) {\n" - " while (reader.nextField()) {\n" - " if (reader.isEndGroup()) {\n" - " break;\n" - " }\n" - " var field = reader.getFieldNumber();\n" - " switch (field) {\n", - "class", GetMessagePath(options, desc)); - - for (int i = 0; i < desc->field_count(); i++) { - if (!IgnoreField(desc->field(i))) { - GenerateClassDeserializeBinaryField(options, printer, desc->field(i)); - } - } - - printer->Print( - " default:\n"); - if (IsExtendable(desc)) { - printer->Print( - " jspb.Message.readBinaryExtension(msg, reader, $extobj$Binary,\n" - " $class$.prototype.getExtension,\n" - " $class$.prototype.setExtension);\n" - " break;\n", - "extobj", JSExtensionsObjectName(options, desc->file(), desc), - "class", GetMessagePath(options, desc)); - } else { - printer->Print( - " reader.skipField();\n" - " break;\n"); - } - - printer->Print( - " }\n" - " }\n" - " return msg;\n" - "};\n" - "\n" - "\n"); -} - -void Generator::GenerateClassDeserializeBinaryField( - const GeneratorOptions& options, - io::Printer* printer, - const FieldDescriptor* field) const { - - printer->Print(" case $num$:\n", - "num", SimpleItoa(field->number())); - - if (IsMap(options, field)) { - const FieldDescriptor* key_field = MapFieldKey(field); - const FieldDescriptor* value_field = MapFieldValue(field); - printer->Print( - " var value = msg.get$name$();\n" - " reader.readMessage(value, function(message, reader) {\n", - "name", JSGetterName(options, field)); - - printer->Print(" jspb.Map.deserializeBinary(message, reader, " - "$keyReaderFn$, $valueReaderFn$", - "keyReaderFn", JSBinaryReaderMethodName(options, key_field), - "valueReaderFn", JSBinaryReaderMethodName(options, value_field)); - - if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) { - printer->Print(", $messageType$.deserializeBinaryFromReader", - "messageType", GetMessagePath(options, value_field->message_type())); - } else { - printer->Print(", null"); - } - printer->Print(", $defaultKey$", - "defaultKey", JSFieldDefault(key_field) - ); - printer->Print(");\n"); - printer->Print(" });\n"); - } else { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - printer->Print( - " var value = new $fieldclass$;\n" - " reader.read$msgOrGroup$($grpfield$value," - "$fieldclass$.deserializeBinaryFromReader);\n", - "fieldclass", SubmessageTypeRef(options, field), - "msgOrGroup", (field->type() == FieldDescriptor::TYPE_GROUP) ? - "Group" : "Message", - "grpfield", (field->type() == FieldDescriptor::TYPE_GROUP) ? - (SimpleItoa(field->number()) + ", ") : ""); - } else { - printer->Print( - " var value = /** @type {$fieldtype$} */ " - "(reader.read$reader$());\n", - "fieldtype", JSFieldTypeAnnotation(options, field, false, true, - /* singular_if_not_packed */ true, - BYTES_U8), - "reader", - JSBinaryReadWriteMethodName(field, /* is_writer = */ false)); - } - - if (field->is_repeated() && !field->is_packed()) { - printer->Print( - " msg.add$name$(value);\n", "name", - JSGetterName(options, field, BYTES_DEFAULT, /* drop_list = */ true)); - } else { - // Singular fields, and packed repeated fields, receive a |value| either - // as the field's value or as the array of all the field's values; set - // this as the field's value directly. - printer->Print( - " msg.set$name$(value);\n", - "name", JSGetterName(options, field)); - } - } - - printer->Print(" break;\n"); -} - -void Generator::GenerateClassSerializeBinary(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const { - printer->Print( - "/**\n" - " * Serializes the message to binary data (in protobuf wire format).\n" - " * @return {!Uint8Array}\n" - " */\n" - "$class$.prototype.serializeBinary = function() {\n" - " var writer = new jspb.BinaryWriter();\n" - " $class$.serializeBinaryToWriter(this, writer);\n" - " return writer.getResultBuffer();\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Serializes the given message to binary data (in protobuf wire\n" - " * format), writing to the given BinaryWriter.\n" - " * @param {!$class$} message\n" - " * @param {!jspb.BinaryWriter} writer\n" - " * @suppress {unusedLocalVariables} f is only used for nested messages\n" - " */\n" - "$class$.serializeBinaryToWriter = function(message, " - "writer) {\n" - " var f = undefined;\n", - "class", GetMessagePath(options, desc)); - - for (int i = 0; i < desc->field_count(); i++) { - if (!IgnoreField(desc->field(i))) { - GenerateClassSerializeBinaryField(options, printer, desc->field(i)); - } - } - - if (IsExtendable(desc)) { - printer->Print( - " jspb.Message.serializeBinaryExtensions(message, writer,\n" - " $extobj$Binary, $class$.prototype.getExtension);\n", - "extobj", JSExtensionsObjectName(options, desc->file(), desc), - "class", GetMessagePath(options, desc)); - } - - printer->Print( - "};\n" - "\n" - "\n"); -} - -void Generator::GenerateClassSerializeBinaryField( - const GeneratorOptions& options, - io::Printer* printer, - const FieldDescriptor* field) const { - if (HasFieldPresence(options, field) && - field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - string typed_annotation = JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ false, - /* force_present = */ false, - /* singular_if_not_packed = */ false, - /* bytes_mode = */ BYTES_DEFAULT); - printer->Print( - " f = /** @type {$type$} */ " - "(jspb.Message.getField(message, $index$));\n", - "index", JSFieldIndex(field), - "type", typed_annotation); - } else { - printer->Print( - " f = message.get$name$($nolazy$);\n", - "name", JSGetterName(options, field, BYTES_U8), - // No lazy creation for maps containers -- fastpath the empty case. - "nolazy", IsMap(options, field) ? "true" : ""); - } - - // Print an `if (condition)` statement that evaluates to true if the field - // goes on the wire. - if (IsMap(options, field)) { - printer->Print( - " if (f && f.getLength() > 0) {\n"); - } else if (field->is_repeated()) { - printer->Print( - " if (f.length > 0) {\n"); - } else { - if (HasFieldPresence(options, field)) { - printer->Print( - " if (f != null) {\n"); - } else { - // No field presence: serialize onto the wire only if value is - // non-default. Defaults are documented here: - // https://goto.google.com/lhdfm - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - case FieldDescriptor::CPPTYPE_INT64: - case FieldDescriptor::CPPTYPE_UINT32: - case FieldDescriptor::CPPTYPE_UINT64: { - if (IsIntegralFieldWithStringJSType(field)) { - // We can use `parseInt` here even though it will not be precise for - // 64-bit quantities because we are only testing for zero/nonzero, - // and JS numbers (64-bit floating point values, i.e., doubles) are - // integer-precise in the range that includes zero. - printer->Print(" if (parseInt(f, 10) !== 0) {\n"); - } else { - printer->Print(" if (f !== 0) {\n"); - } - break; - } - - case FieldDescriptor::CPPTYPE_ENUM: - case FieldDescriptor::CPPTYPE_FLOAT: - case FieldDescriptor::CPPTYPE_DOUBLE: - printer->Print( - " if (f !== 0.0) {\n"); - break; - case FieldDescriptor::CPPTYPE_BOOL: - printer->Print( - " if (f) {\n"); - break; - case FieldDescriptor::CPPTYPE_STRING: - printer->Print( - " if (f.length > 0) {\n"); - break; - default: - assert(false); - break; - } - } - } - - // Write the field on the wire. - if (IsMap(options, field)) { - const FieldDescriptor* key_field = MapFieldKey(field); - const FieldDescriptor* value_field = MapFieldValue(field); - printer->Print( - " f.serializeBinary($index$, writer, " - "$keyWriterFn$, $valueWriterFn$", - "index", SimpleItoa(field->number()), - "keyWriterFn", JSBinaryWriterMethodName(options, key_field), - "valueWriterFn", JSBinaryWriterMethodName(options, value_field)); - - if (value_field->type() == FieldDescriptor::TYPE_MESSAGE) { - printer->Print(", $messageType$.serializeBinaryToWriter", - "messageType", GetMessagePath(options, value_field->message_type())); - } - - printer->Print(");\n"); - } else { - printer->Print( - " writer.write$method$(\n" - " $index$,\n" - " f", - "method", JSBinaryReadWriteMethodName(field, /* is_writer = */ true), - "index", SimpleItoa(field->number())); - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !IsMap(options, field)) { - printer->Print( - ",\n" - " $submsg$.serializeBinaryToWriter\n", - "submsg", SubmessageTypeRef(options, field)); - } else { - printer->Print("\n"); - } - - printer->Print( - " );\n"); - } - - // Close the `if`. - printer->Print( - " }\n"); -} - -void Generator::GenerateEnum(const GeneratorOptions& options, - io::Printer* printer, - const EnumDescriptor* enumdesc) const { - printer->Print( - "/**\n" - " * @enum {number}\n" - " */\n" - "$enumprefix$$name$ = {\n", - "enumprefix", GetEnumPathPrefix(options, enumdesc), - "name", enumdesc->name()); - printer->Annotate("name", enumdesc); - - for (int i = 0; i < enumdesc->value_count(); i++) { - const EnumValueDescriptor* value = enumdesc->value(i); - printer->Print( - " $name$: $value$$comma$\n", - "name", ToEnumCase(value->name()), - "value", SimpleItoa(value->number()), - "comma", (i == enumdesc->value_count() - 1) ? "" : ","); - printer->Annotate("name", value); - } - - printer->Print( - "};\n" - "\n"); -} - -void Generator::GenerateExtension(const GeneratorOptions& options, - io::Printer* printer, - const FieldDescriptor* field) const { - string extension_scope = - (field->extension_scope() - ? GetMessagePath(options, field->extension_scope()) - : GetFilePath(options, field->file())); - - const string extension_object_name = JSObjectFieldName(options, field); - printer->Print( - "\n" - "/**\n" - " * A tuple of {field number, class constructor} for the extension\n" - " * field named `$nameInComment$`.\n" - " * @type {!jspb.ExtensionFieldInfo<$extensionType$>}\n" - " */\n" - "$class$.$name$ = new jspb.ExtensionFieldInfo(\n", - "nameInComment", extension_object_name, - "name", extension_object_name, - "class", extension_scope, - "extensionType", JSFieldTypeAnnotation( - options, field, - /* is_setter_argument = */ false, - /* force_present = */ true, - /* singular_if_not_packed = */ false)); - printer->Annotate("name", field); - printer->Print( - " $index$,\n" - " {$name$: 0},\n" - " $ctor$,\n" - " /** @type {?function((boolean|undefined),!jspb.Message=): " - "!Object} */ (\n" - " $toObject$),\n" - " $repeated$);\n", - "index", SimpleItoa(field->number()), - "name", extension_object_name, - "ctor", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? - SubmessageTypeRef(options, field) : string("null")), - "toObject", (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? - (SubmessageTypeRef(options, field) + ".toObject") : - string("null")), - "repeated", (field->is_repeated() ? "1" : "0")); - - printer->Print( - "\n" - "$extendName$Binary[$index$] = new jspb.ExtensionFieldBinaryInfo(\n" - " $class$.$name$,\n" - " $binaryReaderFn$,\n" - " $binaryWriterFn$,\n" - " $binaryMessageSerializeFn$,\n" - " $binaryMessageDeserializeFn$,\n", - "extendName", - JSExtensionsObjectName(options, field->file(), field->containing_type()), - "index", SimpleItoa(field->number()), "class", extension_scope, "name", - extension_object_name, "binaryReaderFn", - JSBinaryReaderMethodName(options, field), "binaryWriterFn", - JSBinaryWriterMethodName(options, field), "binaryMessageSerializeFn", - (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) - ? (SubmessageTypeRef(options, field) + ".serializeBinaryToWriter") - : "undefined", - "binaryMessageDeserializeFn", - (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) - ? (SubmessageTypeRef(options, field) + ".deserializeBinaryFromReader") - : "undefined"); - - printer->Print(" $isPacked$);\n", "isPacked", - (field->is_packed() ? "true" : "false")); - - printer->Print( - "// This registers the extension field with the extended class, so that\n" - "// toObject() will function correctly.\n" - "$extendName$[$index$] = $class$.$name$;\n" - "\n", - "extendName", JSExtensionsObjectName(options, field->file(), - field->containing_type()), - "index", SimpleItoa(field->number()), - "class", extension_scope, - "name", extension_object_name); -} - -bool GeneratorOptions::ParseFromOptions( - const std::vector< std::pair< string, string > >& options, - string* error) { - for (int i = 0; i < options.size(); i++) { - if (options[i].first == "add_require_for_enums") { - if (options[i].second != "") { - *error = "Unexpected option value for add_require_for_enums"; - return false; - } - add_require_for_enums = true; - } else if (options[i].first == "binary") { - if (options[i].second != "") { - *error = "Unexpected option value for binary"; - return false; - } - binary = true; - } else if (options[i].first == "testonly") { - if (options[i].second != "") { - *error = "Unexpected option value for testonly"; - return false; - } - testonly = true; - } else if (options[i].first == "error_on_name_conflict") { - if (options[i].second != "") { - *error = "Unexpected option value for error_on_name_conflict"; - return false; - } - error_on_name_conflict = true; - } else if (options[i].first == "output_dir") { - output_dir = options[i].second; - } else if (options[i].first == "namespace_prefix") { - namespace_prefix = options[i].second; - } else if (options[i].first == "library") { - library = options[i].second; - } else if (options[i].first == "import_style") { - if (options[i].second == "closure") { - import_style = kImportClosure; - } else if (options[i].second == "commonjs") { - import_style = kImportCommonJs; - } else if (options[i].second == "browser") { - import_style = kImportBrowser; - } else if (options[i].second == "es6") { - import_style = kImportEs6; - } else { - *error = "Unknown import style " + options[i].second + ", expected " + - "one of: closure, commonjs, browser, es6."; - } - } else if (options[i].first == "extension") { - extension = options[i].second; - } else if (options[i].first == "one_output_file_per_input_file") { - if (!options[i].second.empty()) { - *error = "Unexpected option value for one_output_file_per_input_file"; - return false; - } - one_output_file_per_input_file = true; - } else if (options[i].first == "annotate_code") { - if (!options[i].second.empty()) { - *error = "Unexpected option value for annotate_code"; - return false; - } - annotate_code = true; - } else { - // Assume any other option is an output directory, as long as it is a bare - // `key` rather than a `key=value` option. - if (options[i].second != "") { - *error = "Unknown option: " + options[i].first; - return false; - } - output_dir = options[i].first; - } - } - - if (import_style != kImportClosure && - (add_require_for_enums || testonly || !library.empty() || - error_on_name_conflict || extension != ".js" || - one_output_file_per_input_file)) { - *error = - "The add_require_for_enums, testonly, library, error_on_name_conflict, " - "extension, and one_output_file_per_input_file options should only be " - "used for import_style=closure"; - return false; - } - - return true; -} - -GeneratorOptions::OutputMode GeneratorOptions::output_mode() const { - // We use one output file per input file if we are not using Closure or if - // this is explicitly requested. - if (import_style != kImportClosure || one_output_file_per_input_file) { - return kOneOutputFilePerInputFile; - } - - // If a library name is provided, we put everything in that one file. - if (!library.empty()) { - return kEverythingInOneFile; - } - - // Otherwise, we create one output file per type. - return kOneOutputFilePerType; -} - -void Generator::GenerateFilesInDepOrder( - const GeneratorOptions& options, - io::Printer* printer, - const std::vector& files) const { - // Build a std::set over all files so that the DFS can detect when it recurses - // into a dep not specified in the user's command line. - std::set all_files(files.begin(), files.end()); - // Track the in-progress set of files that have been generated already. - std::set generated; - for (int i = 0; i < files.size(); i++) { - GenerateFileAndDeps(options, printer, files[i], &all_files, &generated); - } -} - -void Generator::GenerateFileAndDeps( - const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* root, - std::set* all_files, - std::set* generated) const { - // Skip if already generated. - if (generated->find(root) != generated->end()) { - return; - } - generated->insert(root); - - // Generate all dependencies before this file's content. - for (int i = 0; i < root->dependency_count(); i++) { - const FileDescriptor* dep = root->dependency(i); - GenerateFileAndDeps(options, printer, dep, all_files, generated); - } - - // Generate this file's content. Only generate if the file is part of the - // original set requested to be generated; i.e., don't take all transitive - // deps down to the roots. - if (all_files->find(root) != all_files->end()) { - GenerateClassesAndEnums(options, printer, root); - } -} - -void Generator::GenerateFile(const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* file) const { - GenerateHeader(options, printer); - - // Generate "require" statements. - if (options.import_style == GeneratorOptions::kImportCommonJs) { - printer->Print("var jspb = require('google-protobuf');\n"); - printer->Print("var goog = jspb;\n"); - printer->Print("var global = Function('return this')();\n\n"); - - for (int i = 0; i < file->dependency_count(); i++) { - const string& name = file->dependency(i)->name(); - printer->Print( - "var $alias$ = require('$file$');\n", - "alias", ModuleAlias(name), - "file", - GetRootPath(file->name(), name) + GetJSFilename(options, name)); - } - } - - std::set provided; - std::set extensions; - for (int i = 0; i < file->extension_count(); i++) { - // We honor the jspb::ignore option here only when working with - // Closure-style imports. Use of this option is discouraged and so we want - // to avoid adding new support for it. - if (options.import_style == GeneratorOptions::kImportClosure && - IgnoreField(file->extension(i))) { - continue; - } - provided.insert(GetFilePath(options, file) + "." + - JSObjectFieldName(options, file->extension(i))); - extensions.insert(file->extension(i)); - } - - FindProvidesForFile(options, printer, file, &provided); - GenerateProvides(options, printer, &provided); - std::vector files; - files.push_back(file); - if (options.import_style == GeneratorOptions::kImportClosure) { - GenerateRequiresForLibrary(options, printer, files, &provided); - } - - GenerateClassesAndEnums(options, printer, file); - - // Generate code for top-level extensions. Extensions nested inside messages - // are emitted inside GenerateClassesAndEnums(). - for (std::set::const_iterator it = extensions.begin(); - it != extensions.end(); ++it) { - GenerateExtension(options, printer, *it); - } - - if (options.import_style == GeneratorOptions::kImportCommonJs) { - printer->Print("goog.object.extend(exports, $package$);\n", - "package", GetFilePath(options, file)); - } - - // Emit well-known type methods. - for (FileToc* toc = well_known_types_js; toc->name != NULL; toc++) { - string name = string("google/protobuf/") + toc->name; - if (name == StripProto(file->name()) + ".js") { - printer->Print(toc->data); - } - } -} - -bool Generator::GenerateAll(const std::vector& files, - const string& parameter, - GeneratorContext* context, - string* error) const { - std::vector< std::pair< string, string > > option_pairs; - ParseGeneratorParameter(parameter, &option_pairs); - GeneratorOptions options; - if (!options.ParseFromOptions(option_pairs, error)) { - return false; - } - - - if (options.output_mode() == GeneratorOptions::kEverythingInOneFile) { - // All output should go in a single file. - string filename = options.output_dir + "/" + options.library + - options.GetFileNameExtension(); - std::unique_ptr output(context->Open(filename)); - GOOGLE_CHECK(output.get()); - io::Printer printer(output.get(), '$'); - - // Pull out all extensions -- we need these to generate all - // provides/requires. - std::vector extensions; - for (int i = 0; i < files.size(); i++) { - for (int j = 0; j < files[i]->extension_count(); j++) { - const FieldDescriptor* extension = files[i]->extension(j); - extensions.push_back(extension); - } - } - - GenerateHeader(options, &printer); - - std::set provided; - FindProvides(options, &printer, files, &provided); - FindProvidesForFields(options, &printer, extensions, &provided); - GenerateProvides(options, &printer, &provided); - GenerateTestOnly(options, &printer); - GenerateRequiresForLibrary(options, &printer, files, &provided); - - GenerateFilesInDepOrder(options, &printer, files); - - for (int i = 0; i < extensions.size(); i++) { - if (ShouldGenerateExtension(extensions[i])) { - GenerateExtension(options, &printer, extensions[i]); - } - } - - if (printer.failed()) { - return false; - } - } else if (options.output_mode() == GeneratorOptions::kOneOutputFilePerType) { - std::set allowed_set; - if (!GenerateJspbAllowedSet(options, files, &allowed_set, error)) { - return false; - } - - for (int i = 0; i < files.size(); i++) { - const FileDescriptor* file = files[i]; - for (int j = 0; j < file->message_type_count(); j++) { - const Descriptor* desc = file->message_type(j); - if (allowed_set.count(desc) == 0) { - continue; - } - - string filename = GetMessageFileName(options, desc); - std::unique_ptr output( - context->Open(filename)); - GOOGLE_CHECK(output.get()); - io::Printer printer(output.get(), '$'); - - GenerateHeader(options, &printer); - - std::set provided; - FindProvidesForMessage(options, &printer, desc, &provided); - GenerateProvides(options, &printer, &provided); - GenerateTestOnly(options, &printer); - GenerateRequiresForMessage(options, &printer, desc, &provided); - - GenerateClass(options, &printer, desc); - - if (printer.failed()) { - return false; - } - } - for (int j = 0; j < file->enum_type_count(); j++) { - const EnumDescriptor* enumdesc = file->enum_type(j); - if (allowed_set.count(enumdesc) == 0) { - continue; - } - - string filename = GetEnumFileName(options, enumdesc); - std::unique_ptr output( - context->Open(filename)); - GOOGLE_CHECK(output.get()); - io::Printer printer(output.get(), '$'); - - GenerateHeader(options, &printer); - - std::set provided; - FindProvidesForEnum(options, &printer, enumdesc, &provided); - GenerateProvides(options, &printer, &provided); - GenerateTestOnly(options, &printer); - - GenerateEnum(options, &printer, enumdesc); - - if (printer.failed()) { - return false; - } - } - // File-level extensions (message-level extensions are generated under - // the enclosing message). - if (allowed_set.count(file) == 1) { - string filename = GetExtensionFileName(options, file); - - std::unique_ptr output( - context->Open(filename)); - GOOGLE_CHECK(output.get()); - io::Printer printer(output.get(), '$'); - - GenerateHeader(options, &printer); - - std::set provided; - std::vector fields; - - for (int j = 0; j < files[i]->extension_count(); j++) { - if (ShouldGenerateExtension(files[i]->extension(j))) { - fields.push_back(files[i]->extension(j)); - } - } - - FindProvidesForFields(options, &printer, fields, &provided); - GenerateProvides(options, &printer, &provided); - GenerateTestOnly(options, &printer); - GenerateRequiresForExtensions(options, &printer, fields, &provided); - - for (int j = 0; j < files[i]->extension_count(); j++) { - if (ShouldGenerateExtension(files[i]->extension(j))) { - GenerateExtension(options, &printer, files[i]->extension(j)); - } - } - } - } - } else /* options.output_mode() == kOneOutputFilePerInputFile */ { - // Generate one output file per input (.proto) file. - - for (int i = 0; i < files.size(); i++) { - const google::protobuf::FileDescriptor* file = files[i]; - - string filename = - options.output_dir + "/" + GetJSFilename(options, file->name()); - std::unique_ptr output(context->Open(filename)); - GOOGLE_CHECK(output.get()); - GeneratedCodeInfo annotations; - io::AnnotationProtoCollector annotation_collector( - &annotations); - io::Printer printer(output.get(), '$', - options.annotate_code ? &annotation_collector : NULL); - - - GenerateFile(options, &printer, file); - - if (printer.failed()) { - return false; - } - - if (options.annotate_code) { - EmbedCodeAnnotations(annotations, &printer); - } - } - } - return true; -} - -} // namespace js -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/js/js_generator.h b/windows/include/google/protobuf/compiler/js/js_generator.h index 3cc60e228..cd9631afb 100644 --- a/windows/include/google/protobuf/compiler/js/js_generator.h +++ b/windows/include/google/protobuf/compiler/js/js_generator.h @@ -33,13 +33,16 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__ #define GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__ -#include #include +#include #include #include +#include #include +#include + namespace google { namespace protobuf { @@ -49,24 +52,27 @@ class FieldDescriptor; class OneofDescriptor; class FileDescriptor; -namespace io { class Printer; } +namespace io { +class Printer; +} namespace compiler { namespace js { struct GeneratorOptions { // Output path. - string output_dir; + std::string output_dir; // Namespace prefix. - string namespace_prefix; + std::string namespace_prefix; // Enable binary-format support? bool binary; // What style of imports should be used. enum ImportStyle { - kImportClosure, // goog.require() - kImportCommonJs, // require() - kImportBrowser, // no import statements - kImportEs6, // import { member } from '' + kImportClosure, // goog.require() + kImportCommonJs, // require() + kImportCommonJsStrict, // require() with no global export + kImportBrowser, // no import statements + kImportEs6, // import { member } from '' } import_style; GeneratorOptions() @@ -77,17 +83,16 @@ struct GeneratorOptions { add_require_for_enums(false), testonly(false), library(""), - error_on_name_conflict(false), extension(".js"), one_output_file_per_input_file(false), annotate_code(false) {} bool ParseFromOptions( - const std::vector< std::pair< string, string > >& options, - string* error); + const std::vector >& options, + std::string* error); // Returns the file name extension to use for generated code. - string GetFileNameExtension() const { + std::string GetFileNameExtension() const { return import_style == kImportClosure ? extension : "_pb.js"; } @@ -95,7 +100,7 @@ struct GeneratorOptions { // Create an output file for each input .proto file. kOneOutputFilePerInputFile, // Create an output file for each type. - kOneOutputFilePerType, + kOneOutputFilePerSCC, // Put everything in a single file named by the library option. kEverythingInOneFile, }; @@ -112,15 +117,16 @@ struct GeneratorOptions { bool testonly; // Create a library with name _lib.js rather than a separate .js file // per type? - string library; - // Error if there are two types that would generate the same output file? - bool error_on_name_conflict; + std::string library; // The extension to use for output file names. - string extension; + std::string extension; // Create a separate output file for each input file? bool one_output_file_per_input_file; - // If true, we should build .meta files that contain annotations for - // generated code. See GeneratedCodeInfo in descriptor.proto. + // If true, we should append annotations as comments on the last line for + // generated .js file. Annotations used by tools like https://kythe.io + // to provide cross-references between .js and .proto files. Annotations + // are encoded as base64 proto of GeneratedCodeInfo message (see + // descriptor.proto). bool annotate_code; }; @@ -128,56 +134,52 @@ struct GeneratorOptions { // header. If you create your own protocol compiler binary and you want it to // support JavaScript output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator : public CodeGenerator { +class PROTOC_EXPORT Generator : public CodeGenerator { public: Generator() {} virtual ~Generator() {} - virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* context, std::string* error) const override { *error = "Unimplemented Generate() method. Call GenerateAll() instead."; return false; } - virtual bool HasGenerateAll() const { return true; } + bool HasGenerateAll() const override { return true; } - virtual bool GenerateAll(const std::vector& files, - const string& parameter, - GeneratorContext* context, - string* error) const; + bool GenerateAll(const std::vector& files, + const std::string& parameter, GeneratorContext* context, + std::string* error) const override; + + uint64 GetSupportedFeatures() const override { + return FEATURE_PROTO3_OPTIONAL; + } private: void GenerateHeader(const GeneratorOptions& options, - io::Printer* printer) const; + const FileDescriptor* file, io::Printer* printer) const; // Generate goog.provides() calls. - void FindProvides(const GeneratorOptions& options, - io::Printer* printer, + void FindProvides(const GeneratorOptions& options, io::Printer* printer, const std::vector& file, - std::set* provided) const; + std::set* provided) const; void FindProvidesForFile(const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* file, - std::set* provided) const; + io::Printer* printer, const FileDescriptor* file, + std::set* provided) const; void FindProvidesForMessage(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc, - std::set* provided) const; + io::Printer* printer, const Descriptor* desc, + std::set* provided) const; void FindProvidesForEnum(const GeneratorOptions& options, - io::Printer* printer, - const EnumDescriptor* enumdesc, - std::set* provided) const; + io::Printer* printer, const EnumDescriptor* enumdesc, + std::set* provided) const; // For extension fields at file scope. void FindProvidesForFields(const GeneratorOptions& options, io::Printer* printer, const std::vector& fields, - std::set* provided) const; + std::set* provided) const; // Print the goog.provides() found by the methods above. - void GenerateProvides(const GeneratorOptions& options, - io::Printer* printer, - std::set* provided) const; + void GenerateProvides(const GeneratorOptions& options, io::Printer* printer, + std::set* provided) const; // Generate goog.setTestOnly() if indicated. void GenerateTestOnly(const GeneratorOptions& options, @@ -187,37 +189,40 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void GenerateRequiresForLibrary( const GeneratorOptions& options, io::Printer* printer, const std::vector& files, - std::set* provided) const; - void GenerateRequiresForMessage(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc, - std::set* provided) const; + std::set* provided) const; + void GenerateRequiresForSCC(const GeneratorOptions& options, + io::Printer* printer, const SCC* scc, + std::set* provided) const; // For extension fields at file scope. void GenerateRequiresForExtensions( const GeneratorOptions& options, io::Printer* printer, const std::vector& fields, - std::set* provided) const; + std::set* provided) const; void GenerateRequiresImpl(const GeneratorOptions& options, - io::Printer* printer, std::set* required, - std::set* forwards, - std::set* provided, bool require_jspb, + io::Printer* printer, + std::set* required, + std::set* forwards, + std::set* provided, bool require_jspb, bool require_extension, bool require_map) const; void FindRequiresForMessage(const GeneratorOptions& options, const Descriptor* desc, - std::set* required, - std::set* forwards, + std::set* required, + std::set* forwards, bool* have_message) const; void FindRequiresForField(const GeneratorOptions& options, const FieldDescriptor* field, - std::set* required, - std::set* forwards) const; + std::set* required, + std::set* forwards) const; void FindRequiresForExtension(const GeneratorOptions& options, const FieldDescriptor* field, - std::set* required, - std::set* forwards) const; - - void GenerateFile(const GeneratorOptions& options, - io::Printer* printer, + std::set* required, + std::set* forwards) const; + // Generate all things in a proto file into one file. + // If use_short_name is true, the generated file's name will only be short + // name that without directory, otherwise filename equals file->name() + bool GenerateFile(const FileDescriptor* file, const GeneratorOptions& options, + GeneratorContext* context, bool use_short_name) const; + void GenerateFile(const GeneratorOptions& options, io::Printer* printer, const FileDescriptor* file) const; // Generate definitions for all message classes and enums in all files, @@ -227,8 +232,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const std::vector& file) const; // Helper for above. void GenerateFileAndDeps(const GeneratorOptions& options, - io::Printer* printer, - const FileDescriptor* root, + io::Printer* printer, const FileDescriptor* root, std::set* all_files, std::set* generated) const; @@ -243,8 +247,7 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { bool use_default) const; // Generate definition for one class. - void GenerateClass(const GeneratorOptions& options, - io::Printer* printer, + void GenerateClass(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; void GenerateClassConstructor(const GeneratorOptions& options, io::Printer* printer, @@ -252,12 +255,17 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void GenerateClassFieldInfo(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; - void GenerateClassXid(const GeneratorOptions& options, - io::Printer* printer, + void GenerateClassConstructorAndDeclareExtensionFieldInfo( + const GeneratorOptions& options, io::Printer* printer, + const Descriptor* desc) const; + void GenerateClassXid(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; void GenerateOneofCaseDefinition(const GeneratorOptions& options, io::Printer* printer, const OneofDescriptor* oneof) const; + void GenerateObjectTypedef(const GeneratorOptions& options, + io::Printer* printer, + const Descriptor* desc) const; void GenerateClassToObject(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; @@ -270,17 +278,12 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { void GenerateClassFieldFromObject(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const; - void GenerateClassClone(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const; void GenerateClassRegistration(const GeneratorOptions& options, io::Printer* printer, const Descriptor* desc) const; void GenerateClassFields(const GeneratorOptions& options, - io::Printer* printer, - const Descriptor* desc) const; - void GenerateClassField(const GeneratorOptions& options, - io::Printer* printer, + io::Printer* printer, const Descriptor* desc) const; + void GenerateClassField(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* desc) const; void GenerateClassExtensionFieldInfo(const GeneratorOptions& options, io::Printer* printer, @@ -302,13 +305,11 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const FieldDescriptor* field) const; // Generate definition for one enum. - void GenerateEnum(const GeneratorOptions& options, - io::Printer* printer, + void GenerateEnum(const GeneratorOptions& options, io::Printer* printer, const EnumDescriptor* enumdesc) const; // Generate an extension definition. - void GenerateExtension(const GeneratorOptions& options, - io::Printer* printer, + void GenerateExtension(const GeneratorOptions& options, io::Printer* printer, const FieldDescriptor* field) const; // Generate addFoo() method for repeated primitive fields. @@ -328,6 +329,8 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { } // namespace js } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_JS_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/js/well_known_types_embed.cc b/windows/include/google/protobuf/compiler/js/well_known_types_embed.cc deleted file mode 100644 index e5ee5510d..000000000 --- a/windows/include/google/protobuf/compiler/js/well_known_types_embed.cc +++ /dev/null @@ -1,225 +0,0 @@ -#include - -struct FileToc well_known_types_js[] = { - {"any.js", - "/* This code will be inserted into generated code for\n" - " * google/protobuf/any.proto. */\n" - "\n" - "/**\n" - " * Returns the type name contained in this instance, if any.\n" - " * @return {string|undefined}\n" - " */\n" - "proto.google.protobuf.Any.prototype.getTypeName = function() {\n" - " return this.getTypeUrl().split('/').pop();\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Packs the given message instance into this Any.\n" - " * @param {!Uint8Array} serialized The serialized data to pack.\n" - " * @param {string} name The type name of this message object.\n" - " * @param {string=} opt_typeUrlPrefix the type URL prefix.\n" - " */\n" - "proto.google.protobuf.Any.prototype.pack = function(serialized, name,\n" - " opt_typeUrlPrefix) " - "{\n" - " if (!opt_typeUrlPrefix) {\n" - " opt_typeUrlPrefix = 'type.googleapis.com/';\n" - " }\n" - "\n" - " if (opt_typeUrlPrefix.substr(-1) != '/') {\n" - " this.setTypeUrl(opt_typeUrlPrefix + '/' + name);\n" - " } else {\n" - " this.setTypeUrl(opt_typeUrlPrefix + name);\n" - " }\n" - "\n" - " this.setValue(serialized);\n" - "};\n" - "\n" - "\n" - "/**\n" - " * @template T\n" - " * Unpacks this Any into the given message object.\n" - " * @param {function(Uint8Array):T} deserialize Function that will " - "deserialize\n" - " * the binary data properly.\n" - " * @param {string} name The expected type name of this message object.\n" - " * @return {?T} If the name matched the expected name, returns the " - "deserialized\n" - " * object, otherwise returns null.\n" - " */\n" - "proto.google.protobuf.Any.prototype.unpack = function(deserialize, name) " - "{\n" - " if (this.getTypeName() == name) {\n" - " return deserialize(this.getValue_asU8());\n" - " } else {\n" - " return null;\n" - " }\n" - "};\n"}, - {"timestamp.js", - "/* This code will be inserted into generated code for\n" - " * google/protobuf/timestamp.proto. */\n" - "\n" - "/**\n" - " * Returns a JavaScript 'Date' object corresponding to this Timestamp.\n" - " * @return {!Date}\n" - " */\n" - "proto.google.protobuf.Timestamp.prototype.toDate = function() {\n" - " var seconds = this.getSeconds();\n" - " var nanos = this.getNanos();\n" - "\n" - " return new Date((seconds * 1000) + (nanos / 1000000));\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Sets the value of this Timestamp object to be the given Date.\n" - " * @param {!Date} value The value to set.\n" - " */\n" - "proto.google.protobuf.Timestamp.prototype.fromDate = function(value) {\n" - " this.setSeconds(Math.floor(value.getTime() / 1000));\n" - " this.setNanos(value.getMilliseconds() * 1000000);\n" - "};\n"}, - {"struct.js", - "/* This code will be inserted into generated code for\n" - " * google/protobuf/struct.proto. */\n" - "\n" - "/**\n" - " * Typedef representing plain JavaScript values that can go into a\n" - " * Struct.\n" - " * @typedef {null|number|string|boolean|Array|Object}\n" - " */\n" - "proto.google.protobuf.JavaScriptValue;\n" - "\n" - "\n" - "/**\n" - " * Converts this Value object to a plain JavaScript value.\n" - " * @return {?proto.google.protobuf.JavaScriptValue} a plain JavaScript\n" - " * value representing this Struct.\n" - " */\n" - "proto.google.protobuf.Value.prototype.toJavaScript = function() {\n" - " var kindCase = proto.google.protobuf.Value.KindCase;\n" - " switch (this.getKindCase()) {\n" - " case kindCase.NULL_VALUE:\n" - " return null;\n" - " case kindCase.NUMBER_VALUE:\n" - " return this.getNumberValue();\n" - " case kindCase.STRING_VALUE:\n" - " return this.getStringValue();\n" - " case kindCase.BOOL_VALUE:\n" - " return this.getBoolValue();\n" - " case kindCase.STRUCT_VALUE:\n" - " return this.getStructValue().toJavaScript();\n" - " case kindCase.LIST_VALUE:\n" - " return this.getListValue().toJavaScript();\n" - " default:\n" - " throw new Error('Unexpected struct type');\n" - " }\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Converts this JavaScript value to a new Value proto.\n" - " * @param {!proto.google.protobuf.JavaScriptValue} value The value to\n" - " * convert.\n" - " * @return {!proto.google.protobuf.Value} The newly constructed value.\n" - " */\n" - "proto.google.protobuf.Value.fromJavaScript = function(value) {\n" - " var ret = new proto.google.protobuf.Value();\n" - " switch (goog.typeOf(value)) {\n" - " case 'string':\n" - " ret.setStringValue(/** @type {string} */ (value));\n" - " break;\n" - " case 'number':\n" - " ret.setNumberValue(/** @type {number} */ (value));\n" - " break;\n" - " case 'boolean':\n" - " ret.setBoolValue(/** @type {boolean} */ (value));\n" - " break;\n" - " case 'null':\n" - " ret.setNullValue(proto.google.protobuf.NullValue.NULL_VALUE);\n" - " break;\n" - " case 'array':\n" - " ret.setListValue(proto.google.protobuf.ListValue.fromJavaScript(\n" - " /** @type{!Array} */ (value)));\n" - " break;\n" - " case 'object':\n" - " ret.setStructValue(proto.google.protobuf.Struct.fromJavaScript(\n" - " /** @type{!Object} */ (value)));\n" - " break;\n" - " default:\n" - " throw new Error('Unexpected struct type.');\n" - " }\n" - "\n" - " return ret;\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Converts this ListValue object to a plain JavaScript array.\n" - " * @return {!Array} a plain JavaScript array representing this List.\n" - " */\n" - "proto.google.protobuf.ListValue.prototype.toJavaScript = function() {\n" - " var ret = [];\n" - " var values = this.getValuesList();\n" - "\n" - " for (var i = 0; i < values.length; i++) {\n" - " ret[i] = values[i].toJavaScript();\n" - " }\n" - "\n" - " return ret;\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Constructs a ListValue protobuf from this plain JavaScript array.\n" - " * @param {!Array} array a plain JavaScript array\n" - " * @return {proto.google.protobuf.ListValue} a new ListValue object\n" - " */\n" - "proto.google.protobuf.ListValue.fromJavaScript = function(array) {\n" - " var ret = new proto.google.protobuf.ListValue();\n" - "\n" - " for (var i = 0; i < array.length; i++) {\n" - " " - "ret.addValues(proto.google.protobuf.Value.fromJavaScript(array[i]));\n" - " }\n" - "\n" - " return ret;\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Converts this Struct object to a plain JavaScript object.\n" - " * @return {!Object} a " - "plain\n" - " * JavaScript object representing this Struct.\n" - " */\n" - "proto.google.protobuf.Struct.prototype.toJavaScript = function() {\n" - " var ret = {};\n" - "\n" - " this.getFieldsMap().forEach(function(value, key) {\n" - " ret[key] = value.toJavaScript();\n" - " });\n" - "\n" - " return ret;\n" - "};\n" - "\n" - "\n" - "/**\n" - " * Constructs a Struct protobuf from this plain JavaScript object.\n" - " * @param {!Object} obj a plain JavaScript object\n" - " * @return {proto.google.protobuf.Struct} a new Struct object\n" - " */\n" - "proto.google.protobuf.Struct.fromJavaScript = function(obj) {\n" - " var ret = new proto.google.protobuf.Struct();\n" - " var map = ret.getFieldsMap();\n" - "\n" - " for (var property in obj) {\n" - " var val = obj[property];\n" - " map.set(property, proto.google.protobuf.Value.fromJavaScript(val));\n" - " }\n" - "\n" - " return ret;\n" - "};\n"}, - {NULL, NULL} // Terminate the list. -}; diff --git a/windows/include/google/protobuf/compiler/main.cc b/windows/include/google/protobuf/compiler/main.cc deleted file mode 100644 index 1db35441a..000000000 --- a/windows/include/google/protobuf/compiler/main.cc +++ /dev/null @@ -1,100 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) - -#include -#include - -#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP -#include -#include -#endif // ! OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP - -#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP -#include -#include -#include -#include -#include -#endif // ! OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP - -int main(int argc, char* argv[]) { - - google::protobuf::compiler::CommandLineInterface cli; - cli.AllowPlugins("protoc-"); - - // Proto2 C++ - google::protobuf::compiler::cpp::CppGenerator cpp_generator; - cli.RegisterGenerator("--cpp_out", "--cpp_opt", &cpp_generator, - "Generate C++ header and source."); - -#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP - // Proto2 Java - google::protobuf::compiler::java::JavaGenerator java_generator; - cli.RegisterGenerator("--java_out", "--java_opt", &java_generator, - "Generate Java source file."); -#endif // !OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP - - -#ifndef OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP - // Proto2 Python - google::protobuf::compiler::python::Generator py_generator; - cli.RegisterGenerator("--python_out", &py_generator, - "Generate Python source file."); - - // PHP - google::protobuf::compiler::php::Generator php_generator; - cli.RegisterGenerator("--php_out", &php_generator, - "Generate PHP source file."); - - // Ruby - google::protobuf::compiler::ruby::Generator rb_generator; - cli.RegisterGenerator("--ruby_out", &rb_generator, - "Generate Ruby source file."); - - // CSharp - google::protobuf::compiler::csharp::Generator csharp_generator; - cli.RegisterGenerator("--csharp_out", "--csharp_opt", &csharp_generator, - "Generate C# source file."); - - // Objective C - google::protobuf::compiler::objectivec::ObjectiveCGenerator objc_generator; - cli.RegisterGenerator("--objc_out", "--objc_opt", &objc_generator, - "Generate Objective C header and source."); - - // JavaScript - google::protobuf::compiler::js::Generator js_generator; - cli.RegisterGenerator("--js_out", &js_generator, - "Generate JavaScript source."); -#endif // !OPENSOURCE_PROTOBUF_CPP_BOOTSTRAP - - return cli.Run(argc, argv); -} diff --git a/windows/include/google/protobuf/compiler/mock_code_generator.cc b/windows/include/google/protobuf/compiler/mock_code_generator.cc deleted file mode 100644 index e150f97d4..000000000 --- a/windows/include/google/protobuf/compiler/mock_code_generator.cc +++ /dev/null @@ -1,335 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) - -#include - -#include -#include -#include -#include - - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef major -#undef major -#endif -#ifdef minor -#undef minor -#endif - -namespace google { -namespace protobuf { -namespace compiler { - -// Returns the list of the names of files in all_files in the form of a -// comma-separated string. -string CommaSeparatedList(const std::vector& all_files) { - std::vector names; - for (size_t i = 0; i < all_files.size(); i++) { - names.push_back(all_files[i]->name()); - } - return Join(names, ","); -} - -static const char* kFirstInsertionPointName = "first_mock_insertion_point"; -static const char* kSecondInsertionPointName = "second_mock_insertion_point"; -static const char* kFirstInsertionPoint = - "# @@protoc_insertion_point(first_mock_insertion_point) is here\n"; -static const char* kSecondInsertionPoint = - " # @@protoc_insertion_point(second_mock_insertion_point) is here\n"; - -MockCodeGenerator::MockCodeGenerator(const string& name) - : name_(name) {} - -MockCodeGenerator::~MockCodeGenerator() {} - -void MockCodeGenerator::ExpectGenerated( - const string& name, - const string& parameter, - const string& insertions, - const string& file, - const string& first_message_name, - const string& first_parsed_file_name, - const string& output_directory) { - string content; - GOOGLE_CHECK_OK( - File::GetContents(output_directory + "/" + GetOutputFileName(name, file), - &content, true)); - - std::vector lines = Split(content, "\n", true); - - while (!lines.empty() && lines.back().empty()) { - lines.pop_back(); - } - for (size_t i = 0; i < lines.size(); i++) { - lines[i] += "\n"; - } - - std::vector insertion_list; - if (!insertions.empty()) { - SplitStringUsing(insertions, ",", &insertion_list); - } - - EXPECT_EQ(lines.size(), 3 + insertion_list.size() * 2); - EXPECT_EQ(GetOutputFileContent(name, parameter, file, - first_parsed_file_name, first_message_name), - lines[0]); - - EXPECT_EQ(kFirstInsertionPoint, lines[1 + insertion_list.size()]); - EXPECT_EQ(kSecondInsertionPoint, lines[2 + insertion_list.size() * 2]); - - for (size_t i = 0; i < insertion_list.size(); i++) { - EXPECT_EQ(GetOutputFileContent(insertion_list[i], "first_insert", - file, file, first_message_name), - lines[1 + i]); - // Second insertion point is indented, so the inserted text should - // automatically be indented too. - EXPECT_EQ(" " + GetOutputFileContent(insertion_list[i], "second_insert", - file, file, first_message_name), - lines[2 + insertion_list.size() + i]); - } -} - -namespace { -void CheckSingleAnnotation(const string& expected_file, - const string& expected_text, - const string& file_content, - const GeneratedCodeInfo::Annotation& annotation) { - EXPECT_EQ(expected_file, annotation.source_file()); - ASSERT_GE(file_content.size(), annotation.begin()); - ASSERT_GE(file_content.size(), annotation.end()); - ASSERT_LE(annotation.begin(), annotation.end()); - EXPECT_EQ(expected_text.size(), annotation.end() - annotation.begin()); - EXPECT_EQ(expected_text, - file_content.substr(annotation.begin(), expected_text.size())); -} -} // anonymous namespace - -void MockCodeGenerator::CheckGeneratedAnnotations( - const string& name, const string& file, const string& output_directory) { - string file_content; - GOOGLE_CHECK_OK( - File::GetContents(output_directory + "/" + GetOutputFileName(name, file), - &file_content, true)); - string meta_content; - GOOGLE_CHECK_OK(File::GetContents( - output_directory + "/" + GetOutputFileName(name, file) + ".meta", - &meta_content, true)); - GeneratedCodeInfo annotations; - GOOGLE_CHECK(TextFormat::ParseFromString(meta_content, &annotations)); - ASSERT_EQ(3, annotations.annotation_size()); - CheckSingleAnnotation("first_annotation", "first", file_content, - annotations.annotation(0)); - CheckSingleAnnotation("second_annotation", "second", file_content, - annotations.annotation(1)); - CheckSingleAnnotation("third_annotation", "third", file_content, - annotations.annotation(2)); -} - -bool MockCodeGenerator::Generate( - const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - bool annotate = false; - for (int i = 0; i < file->message_type_count(); i++) { - if (HasPrefixString(file->message_type(i)->name(), "MockCodeGenerator_")) { - string command = StripPrefixString(file->message_type(i)->name(), - "MockCodeGenerator_"); - if (command == "Error") { - *error = "Saw message type MockCodeGenerator_Error."; - return false; - } else if (command == "Exit") { - std::cerr << "Saw message type MockCodeGenerator_Exit." << std::endl; - exit(123); - } else if (command == "Abort") { - std::cerr << "Saw message type MockCodeGenerator_Abort." << std::endl; - abort(); - } else if (command == "HasSourceCodeInfo") { - FileDescriptorProto file_descriptor_proto; - file->CopySourceCodeInfoTo(&file_descriptor_proto); - bool has_source_code_info = - file_descriptor_proto.has_source_code_info() && - file_descriptor_proto.source_code_info().location_size() > 0; - std::cerr << "Saw message type MockCodeGenerator_HasSourceCodeInfo: " - << has_source_code_info << "." << std::endl; - abort(); - } else if (command == "HasJsonName") { - FieldDescriptorProto field_descriptor_proto; - file->message_type(i)->field(0)->CopyTo(&field_descriptor_proto); - std::cerr << "Saw json_name: " - << field_descriptor_proto.has_json_name() << std::endl; - abort(); - } else if (command == "Annotate") { - annotate = true; - } else if (command == "ShowVersionNumber") { - Version compiler_version; - context->GetCompilerVersion(&compiler_version); - std::cerr << "Saw compiler_version: " - << compiler_version.major() * 1000000 + - compiler_version.minor() * 1000 + - compiler_version.patch() - << " " << compiler_version.suffix() << std::endl; - abort(); - } else { - GOOGLE_LOG(FATAL) << "Unknown MockCodeGenerator command: " << command; - } - } - } - - if (HasPrefixString(parameter, "insert=")) { - std::vector insert_into; - SplitStringUsing(StripPrefixString(parameter, "insert="), - ",", &insert_into); - - for (size_t i = 0; i < insert_into.size(); i++) { - { - std::unique_ptr output(context->OpenForInsert( - GetOutputFileName(insert_into[i], file), kFirstInsertionPointName)); - io::Printer printer(output.get(), '$'); - printer.PrintRaw(GetOutputFileContent(name_, "first_insert", - file, context)); - if (printer.failed()) { - *error = "MockCodeGenerator detected write error."; - return false; - } - } - - { - std::unique_ptr output( - context->OpenForInsert(GetOutputFileName(insert_into[i], file), - kSecondInsertionPointName)); - io::Printer printer(output.get(), '$'); - printer.PrintRaw(GetOutputFileContent(name_, "second_insert", - file, context)); - if (printer.failed()) { - *error = "MockCodeGenerator detected write error."; - return false; - } - } - } - } else { - std::unique_ptr output( - context->Open(GetOutputFileName(name_, file))); - - GeneratedCodeInfo annotations; - io::AnnotationProtoCollector annotation_collector( - &annotations); - io::Printer printer(output.get(), '$', - annotate ? &annotation_collector : NULL); - printer.PrintRaw(GetOutputFileContent(name_, parameter, file, context)); - string annotate_suffix = "_annotation"; - if (annotate) { - printer.Print("$p$", "p", "first"); - printer.Annotate("p", "first" + annotate_suffix); - } - printer.PrintRaw(kFirstInsertionPoint); - if (annotate) { - printer.Print("$p$", "p", "second"); - printer.Annotate("p", "second" + annotate_suffix); - } - printer.PrintRaw(kSecondInsertionPoint); - if (annotate) { - printer.Print("$p$", "p", "third"); - printer.Annotate("p", "third" + annotate_suffix); - } - - if (printer.failed()) { - *error = "MockCodeGenerator detected write error."; - return false; - } - if (annotate) { - std::unique_ptr meta_output( - context->Open(GetOutputFileName(name_, file) + ".meta")); - if (!TextFormat::Print(annotations, meta_output.get())) { - *error = "MockCodeGenerator couldn't write .meta"; - return false; - } - } - } - - return true; -} - -string MockCodeGenerator::GetOutputFileName(const string& generator_name, - const FileDescriptor* file) { - return GetOutputFileName(generator_name, file->name()); -} - -string MockCodeGenerator::GetOutputFileName(const string& generator_name, - const string& file) { - return file + ".MockCodeGenerator." + generator_name; -} - -string MockCodeGenerator::GetOutputFileContent( - const string& generator_name, - const string& parameter, - const FileDescriptor* file, - GeneratorContext *context) { - std::vector all_files; - context->ListParsedFiles(&all_files); - return GetOutputFileContent( - generator_name, parameter, file->name(), - CommaSeparatedList(all_files), - file->message_type_count() > 0 ? - file->message_type(0)->name() : "(none)"); -} - -string MockCodeGenerator::GetOutputFileContent( - const string& generator_name, - const string& parameter, - const string& file, - const string& parsed_file_list, - const string& first_message_name) { - return strings::Substitute("$0: $1, $2, $3, $4\n", - generator_name, parameter, file, - first_message_name, parsed_file_list); -} - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/mock_code_generator.h b/windows/include/google/protobuf/compiler/mock_code_generator.h deleted file mode 100644 index cdd9138c9..000000000 --- a/windows/include/google/protobuf/compiler/mock_code_generator.h +++ /dev/null @@ -1,130 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) - -#ifndef GOOGLE_PROTOBUF_COMPILER_MOCK_CODE_GENERATOR_H__ -#define GOOGLE_PROTOBUF_COMPILER_MOCK_CODE_GENERATOR_H__ - -#include - -#include - -namespace google { -namespace protobuf { -class FileDescriptor; -} // namespace protobuf - -namespace protobuf { -namespace compiler { - -// A mock CodeGenerator, used by command_line_interface_unittest. This is in -// its own file so that it can be used both directly and as a plugin. -// -// Generate() produces some output which can be checked by ExpectCalled(). The -// generator can run in a different process (e.g. a plugin). -// -// If the parameter is "insert=NAMES", the MockCodeGenerator will insert lines -// into the files generated by other MockCodeGenerators instead of creating -// its own file. NAMES is a comma-separated list of the names of those other -// MockCodeGenerators. -// -// MockCodeGenerator will also modify its behavior slightly if the input file -// contains a message type with one of the following names: -// MockCodeGenerator_Error: Causes Generate() to return false and set the -// error message to "Saw message type MockCodeGenerator_Error." -// MockCodeGenerator_Exit: Generate() prints "Saw message type -// MockCodeGenerator_Exit." to stderr and then calls exit(123). -// MockCodeGenerator_Abort: Generate() prints "Saw message type -// MockCodeGenerator_Abort." to stderr and then calls abort(). -// MockCodeGenerator_HasSourceCodeInfo: Causes Generate() to abort after -// printing "Saw message type MockCodeGenerator_HasSourceCodeInfo: FOO." to -// stderr, where FOO is "1" if the supplied FileDescriptorProto has source -// code info, and "0" otherwise. -// MockCodeGenerator_Annotate: Generate() will add annotations to its output -// that can later be verified with CheckGeneratedAnnotations. -class MockCodeGenerator : public CodeGenerator { - public: - MockCodeGenerator(const string& name); - virtual ~MockCodeGenerator(); - - // Expect (via gTest) that a MockCodeGenerator with the given name was called - // with the given parameters by inspecting the output location. - // - // |insertions| is a comma-separated list of names of MockCodeGenerators which - // should have inserted lines into this file. - // |parsed_file_list| is a comma-separated list of names of the files - // that are being compiled together in this run. - static void ExpectGenerated(const string& name, - const string& parameter, - const string& insertions, - const string& file, - const string& first_message_name, - const string& parsed_file_list, - const string& output_directory); - - // Checks that the correct text ranges were annotated by the - // MockCodeGenerator_Annotate directive. - static void CheckGeneratedAnnotations(const string& name, - const string& file, - const string& output_directory); - - // Get the name of the file which would be written by the given generator. - static string GetOutputFileName(const string& generator_name, - const FileDescriptor* file); - static string GetOutputFileName(const string& generator_name, - const string& file); - - // implements CodeGenerator ---------------------------------------- - - virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const; - - private: - string name_; - - static string GetOutputFileContent(const string& generator_name, - const string& parameter, - const FileDescriptor* file, - GeneratorContext *context); - static string GetOutputFileContent(const string& generator_name, - const string& parameter, - const string& file, - const string& parsed_file_list, - const string& first_message_name); -}; - -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_MOCK_CODE_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_enum.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_enum.cc deleted file mode 100644 index 978e985cf..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_enum.cc +++ /dev/null @@ -1,224 +0,0 @@ -// 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. - -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor) - : descriptor_(descriptor), - name_(EnumName(descriptor_)) { - for (int i = 0; i < descriptor_->value_count(); i++) { - const EnumValueDescriptor* value = descriptor_->value(i); - const EnumValueDescriptor* canonical_value = - descriptor_->FindValueByNumber(value->number()); - - if (value == canonical_value) { - base_values_.push_back(value); - } - all_values_.push_back(value); - } -} - -EnumGenerator::~EnumGenerator() {} - -void EnumGenerator::GenerateHeader(io::Printer* printer) { - string enum_comments; - SourceLocation location; - if (descriptor_->GetSourceLocation(&location)) { - enum_comments = BuildCommentsString(location, true); - } else { - enum_comments = ""; - } - - printer->Print( - "#pragma mark - Enum $name$\n" - "\n", - "name", name_); - - printer->Print("$comments$typedef$deprecated_attribute$ GPB_ENUM($name$) {\n", - "comments", enum_comments, - "deprecated_attribute", GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()), - "name", name_); - printer->Indent(); - - if (HasPreservingUnknownEnumSemantics(descriptor_->file())) { - // Include the unknown value. - printer->Print( - "/**\n" - " * Value used if any message's field encounters a value that is not defined\n" - " * by this enum. The message will also have C functions to get/set the rawValue\n" - " * of the field.\n" - " **/\n" - "$name$_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,\n", - "name", name_); - } - for (int i = 0; i < all_values_.size(); i++) { - SourceLocation location; - if (all_values_[i]->GetSourceLocation(&location)) { - string comments = BuildCommentsString(location, true).c_str(); - if (comments.length() > 0) { - if (i > 0) { - printer->Print("\n"); - } - printer->Print(comments.c_str()); - } - } - - printer->Print( - "$name$$deprecated_attribute$ = $value$,\n", - "name", EnumValueName(all_values_[i]), - "deprecated_attribute", GetOptionalDeprecatedAttribute(all_values_[i]), - "value", SimpleItoa(all_values_[i]->number())); - } - printer->Outdent(); - printer->Print( - "};\n" - "\n" - "GPBEnumDescriptor *$name$_EnumDescriptor(void);\n" - "\n" - "/**\n" - " * Checks to see if the given value is defined by the enum or was not known at\n" - " * the time this source was generated.\n" - " **/\n" - "BOOL $name$_IsValidValue(int32_t value);\n" - "\n", - "name", name_); -} - -void EnumGenerator::GenerateSource(io::Printer* printer) { - printer->Print( - "#pragma mark - Enum $name$\n" - "\n", - "name", name_); - - // Note: For the TextFormat decode info, we can't use the enum value as - // the key because protocol buffer enums have 'allow_alias', which lets - // a value be used more than once. Instead, the index into the list of - // enum value descriptions is used. Note: start with -1 so the first one - // will be zero. - TextFormatDecodeData text_format_decode_data; - int enum_value_description_key = -1; - string text_blob; - - for (int i = 0; i < all_values_.size(); i++) { - ++enum_value_description_key; - string short_name(EnumValueShortName(all_values_[i])); - text_blob += short_name + '\0'; - if (UnCamelCaseEnumShortName(short_name) != all_values_[i]->name()) { - text_format_decode_data.AddString(enum_value_description_key, short_name, - all_values_[i]->name()); - } - } - - printer->Print( - "GPBEnumDescriptor *$name$_EnumDescriptor(void) {\n" - " static _Atomic(GPBEnumDescriptor*) descriptor = nil;\n" - " if (!descriptor) {\n", - "name", name_); - - static const int kBytesPerLine = 40; // allow for escaping - printer->Print( - " static const char *valueNames ="); - for (int i = 0; i < text_blob.size(); i += kBytesPerLine) { - printer->Print( - "\n \"$data$\"", - "data", EscapeTrigraphs(CEscape(text_blob.substr(i, kBytesPerLine)))); - } - printer->Print( - ";\n" - " static const int32_t values[] = {\n"); - for (int i = 0; i < all_values_.size(); i++) { - printer->Print(" $name$,\n", "name", EnumValueName(all_values_[i])); - } - printer->Print(" };\n"); - - if (text_format_decode_data.num_entries() == 0) { - printer->Print( - " GPBEnumDescriptor *worker =\n" - " [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol($name$)\n" - " valueNames:valueNames\n" - " values:values\n" - " count:(uint32_t)(sizeof(values) / sizeof(int32_t))\n" - " enumVerifier:$name$_IsValidValue];\n", - "name", name_); - } else { - printer->Print( - " static const char *extraTextFormatInfo = \"$extraTextFormatInfo$\";\n" - " GPBEnumDescriptor *worker =\n" - " [GPBEnumDescriptor allocDescriptorForName:GPBNSStringifySymbol($name$)\n" - " valueNames:valueNames\n" - " values:values\n" - " count:(uint32_t)(sizeof(values) / sizeof(int32_t))\n" - " enumVerifier:$name$_IsValidValue\n" - " extraTextFormatInfo:extraTextFormatInfo];\n", - "name", name_, - "extraTextFormatInfo", CEscape(text_format_decode_data.Data())); - } - printer->Print( - " GPBEnumDescriptor *expected = nil;\n" - " if (!atomic_compare_exchange_strong(&descriptor, &expected, worker)) {\n" - " [worker release];\n" - " }\n" - " }\n" - " return descriptor;\n" - "}\n\n"); - - printer->Print( - "BOOL $name$_IsValidValue(int32_t value__) {\n" - " switch (value__) {\n", - "name", name_); - - for (int i = 0; i < base_values_.size(); i++) { - printer->Print( - " case $name$:\n", - "name", EnumValueName(base_values_[i])); - } - - printer->Print( - " return YES;\n" - " default:\n" - " return NO;\n" - " }\n" - "}\n\n"); -} -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_enum.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_enum.h deleted file mode 100644 index f52e9e687..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_enum.h +++ /dev/null @@ -1,73 +0,0 @@ -// 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_ENUM_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ENUM_H__ - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { -class Printer; // printer.h -} -} - -namespace protobuf { -namespace compiler { -namespace objectivec { - -class EnumGenerator { - public: - explicit EnumGenerator(const EnumDescriptor* descriptor); - ~EnumGenerator(); - - void GenerateHeader(io::Printer* printer); - void GenerateSource(io::Printer* printer); - - const string& name() const { return name_; } - - private: - const EnumDescriptor* descriptor_; - std::vector base_values_; - std::vector all_values_; - const string name_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); -}; - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ENUM_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_enum_field.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_enum_field.cc deleted file mode 100644 index 8899a13aa..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_enum_field.cc +++ /dev/null @@ -1,151 +0,0 @@ -// 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. - -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -namespace { - -void SetEnumVariables(const FieldDescriptor* descriptor, - std::map* variables) { - string type = EnumName(descriptor->enum_type()); - (*variables)["storage_type"] = type; - // For non repeated fields, if it was defined in a different file, the - // property decls need to use "enum NAME" rather than just "NAME" to support - // the forward declaration of the enums. - if (!descriptor->is_repeated() && - (descriptor->file() != descriptor->enum_type()->file())) { - (*variables)["property_type"] = "enum " + type; - } - (*variables)["enum_verifier"] = type + "_IsValidValue"; - (*variables)["enum_desc_func"] = type + "_EnumDescriptor"; - - (*variables)["dataTypeSpecific_name"] = "enumDescFunc"; - (*variables)["dataTypeSpecific_value"] = (*variables)["enum_desc_func"]; - - const Descriptor* msg_descriptor = descriptor->containing_type(); - (*variables)["owning_message_class"] = ClassName(msg_descriptor); -} -} // namespace - -EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : SingleFieldGenerator(descriptor, options) { - SetEnumVariables(descriptor, &variables_); -} - -EnumFieldGenerator::~EnumFieldGenerator() {} - -void EnumFieldGenerator::GenerateCFunctionDeclarations( - io::Printer* printer) const { - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) { - return; - } - - printer->Print( - variables_, - "/**\n" - " * Fetches the raw value of a @c $owning_message_class$'s @c $name$ property, even\n" - " * if the value was not defined by the enum at the time the code was generated.\n" - " **/\n" - "int32_t $owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message);\n" - "/**\n" - " * Sets the raw value of an @c $owning_message_class$'s @c $name$ property, allowing\n" - " * it to be set to a value that was not defined by the enum at the time the code\n" - " * was generated.\n" - " **/\n" - "void Set$owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message, int32_t value);\n" - "\n"); -} - -void EnumFieldGenerator::GenerateCFunctionImplementations( - io::Printer* printer) const { - if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) return; - - printer->Print( - variables_, - "int32_t $owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message) {\n" - " GPBDescriptor *descriptor = [$owning_message_class$ descriptor];\n" - " GPBFieldDescriptor *field = [descriptor fieldWithNumber:$field_number_name$];\n" - " return GPBGetMessageInt32Field(message, field);\n" - "}\n" - "\n" - "void Set$owning_message_class$_$capitalized_name$_RawValue($owning_message_class$ *message, int32_t value) {\n" - " GPBDescriptor *descriptor = [$owning_message_class$ descriptor];\n" - " GPBFieldDescriptor *field = [descriptor fieldWithNumber:$field_number_name$];\n" - " GPBSetInt32IvarWithFieldInternal(message, field, value, descriptor.file.syntax);\n" - "}\n" - "\n"); -} - -void EnumFieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls) const { - SingleFieldGenerator::DetermineForwardDeclarations(fwd_decls); - // If it is an enum defined in a different file, then we'll need a forward - // declaration for it. When it is in our file, all the enums are output - // before the message, so it will be declared before it is needed. - if (descriptor_->file() != descriptor_->enum_type()->file()) { - // Enum name is already in "storage_type". - const string& name = variable("storage_type"); - fwd_decls->insert("GPB_ENUM_FWD_DECLARE(" + name + ")"); - } -} - -RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : RepeatedFieldGenerator(descriptor, options) { - SetEnumVariables(descriptor, &variables_); - variables_["array_storage_type"] = "GPBEnumArray"; -} - -RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {} - -void RepeatedEnumFieldGenerator::FinishInitialization(void) { - RepeatedFieldGenerator::FinishInitialization(); - variables_["array_comment"] = - "// |" + variables_["name"] + "| contains |" + variables_["storage_type"] + "|\n"; -} - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_enum_field.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_enum_field.h deleted file mode 100644 index ae56c069a..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_enum_field.h +++ /dev/null @@ -1,80 +0,0 @@ -// 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_ENUM_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ENUM_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -class EnumFieldGenerator : public SingleFieldGenerator { - friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options); - - public: - virtual void GenerateCFunctionDeclarations(io::Printer* printer) const; - virtual void GenerateCFunctionImplementations(io::Printer* printer) const; - virtual void DetermineForwardDeclarations(std::set* fwd_decls) const; - - protected: - EnumFieldGenerator(const FieldDescriptor* descriptor, const Options& options); - virtual ~EnumFieldGenerator(); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); -}; - -class RepeatedEnumFieldGenerator : public RepeatedFieldGenerator { - friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options); - - public: - virtual void FinishInitialization(); - - protected: - RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - virtual ~RepeatedEnumFieldGenerator(); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); -}; - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ENUM_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_extension.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_extension.cc deleted file mode 100644 index b788d0a32..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_extension.cc +++ /dev/null @@ -1,139 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -ExtensionGenerator::ExtensionGenerator(const string& root_class_name, - const FieldDescriptor* descriptor) - : method_name_(ExtensionMethodName(descriptor)), - root_class_and_method_name_(root_class_name + "_" + method_name_), - descriptor_(descriptor) { - if (descriptor->is_map()) { - // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some - // error cases, so it seems to be ok to use as a back door for errors. - std::cerr << "error: Extension is a map<>!" - << " That used to be blocked by the compiler." << std::endl; - std::cerr.flush(); - abort(); - } -} - -ExtensionGenerator::~ExtensionGenerator() {} - -void ExtensionGenerator::GenerateMembersHeader(io::Printer* printer) { - std::map vars; - vars["method_name"] = method_name_; - SourceLocation location; - if (descriptor_->GetSourceLocation(&location)) { - vars["comments"] = BuildCommentsString(location, true); - } else { - vars["comments"] = ""; - } - // Unlike normal message fields, check if the file for the extension was - // deprecated. - vars["deprecated_attribute"] = GetOptionalDeprecatedAttribute(descriptor_, descriptor_->file()); - printer->Print(vars, - "$comments$" - "+ (GPBExtensionDescriptor *)$method_name$$deprecated_attribute$;\n"); -} - -void ExtensionGenerator::GenerateStaticVariablesInitialization( - io::Printer* printer) { - std::map vars; - vars["root_class_and_method_name"] = root_class_and_method_name_; - vars["extended_type"] = ClassName(descriptor_->containing_type()); - vars["number"] = SimpleItoa(descriptor_->number()); - - std::vector options; - if (descriptor_->is_repeated()) options.push_back("GPBExtensionRepeated"); - if (descriptor_->is_packed()) options.push_back("GPBExtensionPacked"); - if (descriptor_->containing_type()->options().message_set_wire_format()) - options.push_back("GPBExtensionSetWireFormat"); - - vars["options"] = BuildFlagsString(FLAGTYPE_EXTENSION, options); - - ObjectiveCType objc_type = GetObjectiveCType(descriptor_); - string singular_type; - if (objc_type == OBJECTIVECTYPE_MESSAGE) { - vars["type"] = string("GPBStringifySymbol(") + - ClassName(descriptor_->message_type()) + ")"; - } else { - vars["type"] = "NULL"; - } - - vars["default_name"] = GPBGenericValueFieldName(descriptor_); - if (descriptor_->is_repeated()) { - vars["default"] = "nil"; - } else { - vars["default"] = DefaultValue(descriptor_); - } - string type = GetCapitalizedType(descriptor_); - vars["extension_type"] = string("GPBDataType") + type; - - if (objc_type == OBJECTIVECTYPE_ENUM) { - vars["enum_desc_func_name"] = - EnumName(descriptor_->enum_type()) + "_EnumDescriptor"; - } else { - vars["enum_desc_func_name"] = "NULL"; - } - - printer->Print(vars, - "{\n" - " .defaultValue.$default_name$ = $default$,\n" - " .singletonName = GPBStringifySymbol($root_class_and_method_name$),\n" - " .extendedClass = GPBStringifySymbol($extended_type$),\n" - " .messageOrGroupClassName = $type$,\n" - " .enumDescriptorFunc = $enum_desc_func_name$,\n" - " .fieldNumber = $number$,\n" - " .dataType = $extension_type$,\n" - " .options = $options$,\n" - "},\n"); -} - -void ExtensionGenerator::GenerateRegistrationSource(io::Printer* printer) { - printer->Print( - "[registry addExtension:$root_class_and_method_name$];\n", - "root_class_and_method_name", root_class_and_method_name_); -} -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_extension.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_extension.h deleted file mode 100644 index e361e639b..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_extension.h +++ /dev/null @@ -1,69 +0,0 @@ -// 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_EXTENSION_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_EXTENSION_H__ - -#include - -namespace google { -namespace protobuf { -class FieldDescriptor; // descriptor.h -namespace io { -class Printer; // printer.h -} -} - -namespace protobuf { -namespace compiler { -namespace objectivec { - -class ExtensionGenerator { - public: - ExtensionGenerator(const string& root_class_name, - const FieldDescriptor* descriptor); - ~ExtensionGenerator(); - - void GenerateMembersHeader(io::Printer* printer); - void GenerateStaticVariablesInitialization(io::Printer* printer); - void GenerateRegistrationSource(io::Printer* printer); - - private: - string method_name_; - string root_class_and_method_name_; - const FieldDescriptor* descriptor_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); -}; -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MESSAGE_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_field.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_field.cc deleted file mode 100644 index f74599ba8..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_field.cc +++ /dev/null @@ -1,475 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -namespace { - -void SetCommonFieldVariables(const FieldDescriptor* descriptor, - std::map* variables) { - string camel_case_name = FieldName(descriptor); - string raw_field_name; - if (descriptor->type() == FieldDescriptor::TYPE_GROUP) { - raw_field_name = descriptor->message_type()->name(); - } else { - raw_field_name = descriptor->name(); - } - // The logic here has to match -[GGPBFieldDescriptor textFormatName]. - const string un_camel_case_name( - UnCamelCaseFieldName(camel_case_name, descriptor)); - const bool needs_custom_name = (raw_field_name != un_camel_case_name); - - SourceLocation location; - if (descriptor->GetSourceLocation(&location)) { - (*variables)["comments"] = BuildCommentsString(location, true); - } else { - (*variables)["comments"] = "\n"; - } - const string& classname = ClassName(descriptor->containing_type()); - (*variables)["classname"] = classname; - (*variables)["name"] = camel_case_name; - const string& capitalized_name = FieldNameCapitalized(descriptor); - (*variables)["capitalized_name"] = capitalized_name; - (*variables)["raw_field_name"] = raw_field_name; - (*variables)["field_number_name"] = - classname + "_FieldNumber_" + capitalized_name; - (*variables)["field_number"] = SimpleItoa(descriptor->number()); - (*variables)["field_type"] = GetCapitalizedType(descriptor); - (*variables)["deprecated_attribute"] = GetOptionalDeprecatedAttribute(descriptor); - std::vector field_flags; - if (descriptor->is_repeated()) field_flags.push_back("GPBFieldRepeated"); - if (descriptor->is_required()) field_flags.push_back("GPBFieldRequired"); - if (descriptor->is_optional()) field_flags.push_back("GPBFieldOptional"); - if (descriptor->is_packed()) field_flags.push_back("GPBFieldPacked"); - - // ObjC custom flags. - if (descriptor->has_default_value()) - field_flags.push_back("GPBFieldHasDefaultValue"); - if (needs_custom_name) field_flags.push_back("GPBFieldTextFormatNameCustom"); - if (descriptor->type() == FieldDescriptor::TYPE_ENUM) { - field_flags.push_back("GPBFieldHasEnumDescriptor"); - } - - (*variables)["fieldflags"] = BuildFlagsString(FLAGTYPE_FIELD, field_flags); - - (*variables)["default"] = DefaultValue(descriptor); - (*variables)["default_name"] = GPBGenericValueFieldName(descriptor); - - (*variables)["dataTypeSpecific_name"] = "className"; - (*variables)["dataTypeSpecific_value"] = "NULL"; - - (*variables)["storage_offset_value"] = - "(uint32_t)offsetof(" + classname + "__storage_, " + camel_case_name + ")"; - (*variables)["storage_offset_comment"] = ""; - - // Clear some common things so they can be set just when needed. - (*variables)["storage_attribute"] = ""; -} - -} // namespace - -FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options) { - FieldGenerator* result = NULL; - if (field->is_repeated()) { - switch (GetObjectiveCType(field)) { - case OBJECTIVECTYPE_MESSAGE: { - if (field->is_map()) { - result = new MapFieldGenerator(field, options); - } else { - result = new RepeatedMessageFieldGenerator(field, options); - } - break; - } - case OBJECTIVECTYPE_ENUM: - result = new RepeatedEnumFieldGenerator(field, options); - break; - default: - result = new RepeatedPrimitiveFieldGenerator(field, options); - break; - } - } else { - switch (GetObjectiveCType(field)) { - case OBJECTIVECTYPE_MESSAGE: { - result = new MessageFieldGenerator(field, options); - break; - } - case OBJECTIVECTYPE_ENUM: - result = new EnumFieldGenerator(field, options); - break; - default: - if (IsReferenceType(field)) { - result = new PrimitiveObjFieldGenerator(field, options); - } else { - result = new PrimitiveFieldGenerator(field, options); - } - break; - } - } - result->FinishInitialization(); - return result; -} - -FieldGenerator::FieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : descriptor_(descriptor) { - SetCommonFieldVariables(descriptor, &variables_); -} - -FieldGenerator::~FieldGenerator() {} - -void FieldGenerator::GenerateFieldNumberConstant(io::Printer* printer) const { - printer->Print( - variables_, - "$field_number_name$ = $field_number$,\n"); -} - -void FieldGenerator::GenerateCFunctionDeclarations( - io::Printer* printer) const { - // Nothing -} - -void FieldGenerator::GenerateCFunctionImplementations( - io::Printer* printer) const { - // Nothing -} - -void FieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls) const { - // Nothing -} - -void FieldGenerator::GenerateFieldDescription( - io::Printer* printer, bool include_default) const { - // Printed in the same order as the structure decl. - if (include_default) { - printer->Print( - variables_, - "{\n" - " .defaultValue.$default_name$ = $default$,\n" - " .core.name = \"$name$\",\n" - " .core.dataTypeSpecific.$dataTypeSpecific_name$ = $dataTypeSpecific_value$,\n" - " .core.number = $field_number_name$,\n" - " .core.hasIndex = $has_index$,\n" - " .core.offset = $storage_offset_value$,$storage_offset_comment$\n" - " .core.flags = $fieldflags$,\n" - " .core.dataType = GPBDataType$field_type$,\n" - "},\n"); - } else { - printer->Print( - variables_, - "{\n" - " .name = \"$name$\",\n" - " .dataTypeSpecific.$dataTypeSpecific_name$ = $dataTypeSpecific_value$,\n" - " .number = $field_number_name$,\n" - " .hasIndex = $has_index$,\n" - " .offset = $storage_offset_value$,$storage_offset_comment$\n" - " .flags = $fieldflags$,\n" - " .dataType = GPBDataType$field_type$,\n" - "},\n"); - } -} - -void FieldGenerator::SetRuntimeHasBit(int has_index) { - variables_["has_index"] = SimpleItoa(has_index); -} - -void FieldGenerator::SetNoHasBit(void) { - variables_["has_index"] = "GPBNoHasBit"; -} - -int FieldGenerator::ExtraRuntimeHasBitsNeeded(void) const { - return 0; -} - -void FieldGenerator::SetExtraRuntimeHasBitsBase(int index_base) { - // NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some - // error cases, so it seems to be ok to use as a back door for errors. - std::cerr << "Error: should have overridden SetExtraRuntimeHasBitsBase()." << std::endl; - std::cerr.flush(); - abort(); -} - -void FieldGenerator::SetOneofIndexBase(int index_base) { - if (descriptor_->containing_oneof() != NULL) { - int index = descriptor_->containing_oneof()->index() + index_base; - // Flip the sign to mark it as a oneof. - variables_["has_index"] = SimpleItoa(-index); - } -} - -void FieldGenerator::FinishInitialization(void) { - // If "property_type" wasn't set, make it "storage_type". - if ((variables_.find("property_type") == variables_.end()) && - (variables_.find("storage_type") != variables_.end())) { - variables_["property_type"] = variable("storage_type"); - } -} - -SingleFieldGenerator::SingleFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : FieldGenerator(descriptor, options) { - // Nothing -} - -SingleFieldGenerator::~SingleFieldGenerator() {} - -void SingleFieldGenerator::GenerateFieldStorageDeclaration( - io::Printer* printer) const { - printer->Print(variables_, "$storage_type$ $name$;\n"); -} - -void SingleFieldGenerator::GeneratePropertyDeclaration( - io::Printer* printer) const { - printer->Print(variables_, "$comments$"); - printer->Print( - variables_, - "@property(nonatomic, readwrite) $property_type$ $name$$deprecated_attribute$;\n" - "\n"); - if (WantsHasProperty()) { - printer->Print( - variables_, - "@property(nonatomic, readwrite) BOOL has$capitalized_name$$deprecated_attribute$;\n"); - } -} - -void SingleFieldGenerator::GeneratePropertyImplementation( - io::Printer* printer) const { - if (WantsHasProperty()) { - printer->Print(variables_, "@dynamic has$capitalized_name$, $name$;\n"); - } else { - printer->Print(variables_, "@dynamic $name$;\n"); - } -} - -bool SingleFieldGenerator::WantsHasProperty(void) const { - if (descriptor_->containing_oneof() != NULL) { - // If in a oneof, it uses the oneofcase instead of a has bit. - return false; - } - if (HasFieldPresence(descriptor_->file())) { - // In proto1/proto2, every field has a has_$name$() method. - return true; - } - return false; -} - -bool SingleFieldGenerator::RuntimeUsesHasBit(void) const { - if (descriptor_->containing_oneof() != NULL) { - // The oneof tracks what is set instead. - return false; - } - return true; -} - -ObjCObjFieldGenerator::ObjCObjFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : SingleFieldGenerator(descriptor, options) { - variables_["property_storage_attribute"] = "strong"; - if (IsRetainedName(variables_["name"])) { - variables_["storage_attribute"] = " NS_RETURNS_NOT_RETAINED"; - } -} - -ObjCObjFieldGenerator::~ObjCObjFieldGenerator() {} - -void ObjCObjFieldGenerator::GenerateFieldStorageDeclaration( - io::Printer* printer) const { - printer->Print(variables_, "$storage_type$ *$name$;\n"); -} - -void ObjCObjFieldGenerator::GeneratePropertyDeclaration( - io::Printer* printer) const { - - // Differs from SingleFieldGenerator::GeneratePropertyDeclaration() in that - // it uses pointers and deals with Objective C's rules around storage name - // conventions (init*, new*, etc.) - - printer->Print(variables_, "$comments$"); - printer->Print( - variables_, - "@property(nonatomic, readwrite, $property_storage_attribute$, null_resettable) $property_type$ *$name$$storage_attribute$$deprecated_attribute$;\n"); - if (WantsHasProperty()) { - printer->Print( - variables_, - "/** Test to see if @c $name$ has been set. */\n" - "@property(nonatomic, readwrite) BOOL has$capitalized_name$$deprecated_attribute$;\n"); - } - if (IsInitName(variables_.find("name")->second)) { - // If property name starts with init we need to annotate it to get past ARC. - // http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227 - printer->Print(variables_, - "- ($property_type$ *)$name$ GPB_METHOD_FAMILY_NONE$deprecated_attribute$;\n"); - } - printer->Print("\n"); -} - -RepeatedFieldGenerator::RepeatedFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : ObjCObjFieldGenerator(descriptor, options) { - // Default to no comment and let the cases needing it fill it in. - variables_["array_comment"] = ""; -} - -RepeatedFieldGenerator::~RepeatedFieldGenerator() {} - -void RepeatedFieldGenerator::FinishInitialization(void) { - FieldGenerator::FinishInitialization(); - if (variables_.find("array_property_type") == variables_.end()) { - variables_["array_property_type"] = variable("array_storage_type"); - } -} - -void RepeatedFieldGenerator::GenerateFieldStorageDeclaration( - io::Printer* printer) const { - printer->Print(variables_, "$array_storage_type$ *$name$;\n"); -} - -void RepeatedFieldGenerator::GeneratePropertyImplementation( - io::Printer* printer) const { - printer->Print(variables_, "@dynamic $name$, $name$_Count;\n"); -} - -void RepeatedFieldGenerator::GeneratePropertyDeclaration( - io::Printer* printer) const { - - // Repeated fields don't need the has* properties, but they do expose a - // *Count (to check without autocreation). So for the field property we need - // the same logic as ObjCObjFieldGenerator::GeneratePropertyDeclaration() for - // dealing with needing Objective C's rules around storage name conventions - // (init*, new*, etc.) - - printer->Print( - variables_, - "$comments$" - "$array_comment$" - "@property(nonatomic, readwrite, strong, null_resettable) $array_property_type$ *$name$$storage_attribute$$deprecated_attribute$;\n" - "/** The number of items in @c $name$ without causing the array to be created. */\n" - "@property(nonatomic, readonly) NSUInteger $name$_Count$deprecated_attribute$;\n"); - if (IsInitName(variables_.find("name")->second)) { - // If property name starts with init we need to annotate it to get past ARC. - // http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227 - printer->Print(variables_, - "- ($array_property_type$ *)$name$ GPB_METHOD_FAMILY_NONE$deprecated_attribute$;\n"); - } - printer->Print("\n"); -} - -bool RepeatedFieldGenerator::WantsHasProperty(void) const { - // Consumer check the array size/existance rather than a has bit. - return false; -} - -bool RepeatedFieldGenerator::RuntimeUsesHasBit(void) const { - return false; // The array having anything is what is used. -} - -FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor, - const Options& options) - : descriptor_(descriptor), - field_generators_(descriptor->field_count()), - extension_generators_(descriptor->extension_count()) { - // Construct all the FieldGenerators. - for (int i = 0; i < descriptor->field_count(); i++) { - field_generators_[i].reset( - FieldGenerator::Make(descriptor->field(i), options)); - } - for (int i = 0; i < descriptor->extension_count(); i++) { - extension_generators_[i].reset( - FieldGenerator::Make(descriptor->extension(i), options)); - } -} - -FieldGeneratorMap::~FieldGeneratorMap() {} - -const FieldGenerator& FieldGeneratorMap::get( - const FieldDescriptor* field) const { - GOOGLE_CHECK_EQ(field->containing_type(), descriptor_); - return *field_generators_[field->index()]; -} - -const FieldGenerator& FieldGeneratorMap::get_extension(int index) const { - return *extension_generators_[index]; -} - -int FieldGeneratorMap::CalculateHasBits(void) { - int total_bits = 0; - for (int i = 0; i < descriptor_->field_count(); i++) { - if (field_generators_[i]->RuntimeUsesHasBit()) { - field_generators_[i]->SetRuntimeHasBit(total_bits); - ++total_bits; - } else { - field_generators_[i]->SetNoHasBit(); - } - int extra_bits = field_generators_[i]->ExtraRuntimeHasBitsNeeded(); - if (extra_bits) { - field_generators_[i]->SetExtraRuntimeHasBitsBase(total_bits); - total_bits += extra_bits; - } - } - return total_bits; -} - -void FieldGeneratorMap::SetOneofIndexBase(int index_base) { - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_[i]->SetOneofIndexBase(index_base); - } -} - -bool FieldGeneratorMap::DoesAnyFieldHaveNonZeroDefault(void) const { - for (int i = 0; i < descriptor_->field_count(); i++) { - if (HasNonZeroDefaultValue(descriptor_->field(i))) { - return true; - } - } - - return false; -} - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_field.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_field.h deleted file mode 100644 index 216034d06..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_field.h +++ /dev/null @@ -1,194 +0,0 @@ -// 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_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_FIELD_H__ - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -namespace io { -class Printer; // printer.h -} // namespace io - -namespace compiler { -namespace objectivec { - -class FieldGenerator { - public: - static FieldGenerator* Make(const FieldDescriptor* field, - const Options& options); - - virtual ~FieldGenerator(); - - // Exposed for subclasses to fill in. - virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const = 0; - virtual void GeneratePropertyDeclaration(io::Printer* printer) const = 0; - virtual void GeneratePropertyImplementation(io::Printer* printer) const = 0; - - // Called by GenerateFieldDescription, exposed for classes that need custom - // generation. - - // Exposed for subclasses to extend, base does nothing. - virtual void GenerateCFunctionDeclarations(io::Printer* printer) const; - virtual void GenerateCFunctionImplementations(io::Printer* printer) const; - - // Exposed for subclasses, should always call it on the parent class also. - virtual void DetermineForwardDeclarations(std::set* fwd_decls) const; - - // Used during generation, not intended to be extended by subclasses. - void GenerateFieldDescription( - io::Printer* printer, bool include_default) const; - void GenerateFieldNumberConstant(io::Printer* printer) const; - - // Exposed to get and set the has bits information. - virtual bool RuntimeUsesHasBit(void) const = 0; - void SetRuntimeHasBit(int has_index); - void SetNoHasBit(void); - virtual int ExtraRuntimeHasBitsNeeded(void) const; - virtual void SetExtraRuntimeHasBitsBase(int index_base); - void SetOneofIndexBase(int index_base); - - string variable(const char* key) const { - return variables_.find(key)->second; - } - - bool needs_textformat_name_support() const { - const string& field_flags = variable("fieldflags"); - return field_flags.find("GPBFieldTextFormatNameCustom") != string::npos; - } - string generated_objc_name() const { return variable("name"); } - string raw_field_name() const { return variable("raw_field_name"); } - - protected: - FieldGenerator(const FieldDescriptor* descriptor, const Options& options); - - virtual void FinishInitialization(void); - virtual bool WantsHasProperty(void) const = 0; - - const FieldDescriptor* descriptor_; - std::map variables_; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); -}; - -class SingleFieldGenerator : public FieldGenerator { - public: - virtual ~SingleFieldGenerator(); - - virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const; - virtual void GeneratePropertyDeclaration(io::Printer* printer) const; - - virtual void GeneratePropertyImplementation(io::Printer* printer) const; - - virtual bool RuntimeUsesHasBit(void) const; - - protected: - SingleFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - virtual bool WantsHasProperty(void) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SingleFieldGenerator); -}; - -// Subclass with common support for when the field ends up as an ObjC Object. -class ObjCObjFieldGenerator : public SingleFieldGenerator { - public: - virtual ~ObjCObjFieldGenerator(); - - virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const; - virtual void GeneratePropertyDeclaration(io::Printer* printer) const; - - protected: - ObjCObjFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ObjCObjFieldGenerator); -}; - -class RepeatedFieldGenerator : public ObjCObjFieldGenerator { - public: - virtual ~RepeatedFieldGenerator(); - - virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const; - virtual void GeneratePropertyDeclaration(io::Printer* printer) const; - - virtual void GeneratePropertyImplementation(io::Printer* printer) const; - - virtual bool RuntimeUsesHasBit(void) const; - - protected: - RepeatedFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - virtual void FinishInitialization(void); - virtual bool WantsHasProperty(void) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedFieldGenerator); -}; - -// Convenience class which constructs FieldGenerators for a Descriptor. -class FieldGeneratorMap { - public: - FieldGeneratorMap(const Descriptor* descriptor, const Options& options); - ~FieldGeneratorMap(); - - const FieldGenerator& get(const FieldDescriptor* field) const; - const FieldGenerator& get_extension(int index) const; - - // Assigns the has bits and returns the number of bits needed. - int CalculateHasBits(void); - - void SetOneofIndexBase(int index_base); - - // Check if any field of this message has a non zero default. - bool DoesAnyFieldHaveNonZeroDefault(void) const; - - private: - const Descriptor* descriptor_; - std::vector> field_generators_; - std::vector> extension_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); -}; -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_file.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_file.cc deleted file mode 100644 index f0d9b4d5f..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_file.cc +++ /dev/null @@ -1,631 +0,0 @@ -// 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. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#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. - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -namespace { - -// This is also found in GPBBootstrap.h, and needs to be kept in sync. -const int32 GOOGLE_PROTOBUF_OBJC_VERSION = 30002; - -const char* kHeaderExtension = ".pbobjc.h"; - -// Checks if a message contains any enums definitions (on the message or -// a nested message under it). -bool MessageContainsEnums(const Descriptor* message) { - if (message->enum_type_count() > 0) { - return true; - } - for (int i = 0; i < message->nested_type_count(); i++) { - if (MessageContainsEnums(message->nested_type(i))) { - return true; - } - } - return false; -} - -// Checks if a message contains any extension definitions (on the message or -// a nested message under it). -bool MessageContainsExtensions(const Descriptor* message) { - if (message->extension_count() > 0) { - return true; - } - for (int i = 0; i < message->nested_type_count(); i++) { - if (MessageContainsExtensions(message->nested_type(i))) { - return true; - } - } - return false; -} - -// Checks if the file contains any enum definitions (at the root or -// nested under a message). -bool FileContainsEnums(const FileDescriptor* file) { - if (file->enum_type_count() > 0) { - return true; - } - for (int i = 0; i < file->message_type_count(); i++) { - if (MessageContainsEnums(file->message_type(i))) { - return true; - } - } - return false; -} - -// Checks if the file contains any extensions definitions (at the root or -// nested under a message). -bool FileContainsExtensions(const FileDescriptor* file) { - if (file->extension_count() > 0) { - return true; - } - for (int i = 0; i < file->message_type_count(); i++) { - if (MessageContainsExtensions(file->message_type(i))) { - return true; - } - } - return false; -} - -// Helper for CollectMinimalFileDepsContainingExtensionsWorker that marks all -// deps as visited and prunes them from the needed files list. -void PruneFileAndDepsMarkingAsVisited( - const FileDescriptor* file, - std::vector* files, - std::set* files_visited) { - std::vector::iterator iter = - std::find(files->begin(), files->end(), file); - if (iter != files->end()) { - files->erase(iter); - } - files_visited->insert(file); - for (int i = 0; i < file->dependency_count(); i++) { - PruneFileAndDepsMarkingAsVisited(file->dependency(i), files, files_visited); - } -} - -// Helper for CollectMinimalFileDepsContainingExtensions. -void CollectMinimalFileDepsContainingExtensionsWorker( - const FileDescriptor* file, - std::vector* files, - std::set* files_visited) { - if (files_visited->find(file) != files_visited->end()) { - return; - } - files_visited->insert(file); - - if (FileContainsExtensions(file)) { - files->push_back(file); - for (int i = 0; i < file->dependency_count(); i++) { - const FileDescriptor* dep = file->dependency(i); - PruneFileAndDepsMarkingAsVisited(dep, files, files_visited); - } - } else { - for (int i = 0; i < file->dependency_count(); i++) { - const FileDescriptor* dep = file->dependency(i); - CollectMinimalFileDepsContainingExtensionsWorker(dep, files, - files_visited); - } - } -} - -// Collect the deps of the given file that contain extensions. This can be used to -// create the chain of roots that need to be wired together. -// -// NOTE: If any changes are made to this and the supporting functions, you will -// need to manually validate what the generated code is for the test files: -// objectivec/Tests/unittest_extension_chain_*.proto -// There are comments about what the expected code should be line and limited -// testing objectivec/Tests/GPBUnittestProtos2.m around compilation (#imports -// specifically). -void CollectMinimalFileDepsContainingExtensions( - const FileDescriptor* file, - std::vector* files) { - std::set files_visited; - for (int i = 0; i < file->dependency_count(); i++) { - const FileDescriptor* dep = file->dependency(i); - CollectMinimalFileDepsContainingExtensionsWorker(dep, files, - &files_visited); - } -} - -bool IsDirectDependency(const FileDescriptor* dep, const FileDescriptor* file) { - for (int i = 0; i < file->dependency_count(); i++) { - if (dep == file->dependency(i)) { - return true; - } - } - return false; -} - -} // namespace - -FileGenerator::FileGenerator(const FileDescriptor *file, const Options& options) - : file_(file), - root_class_name_(FileClassName(file)), - is_bundled_proto_(IsProtobufLibraryBundledProtoFile(file)), - options_(options) { - for (int i = 0; i < file_->enum_type_count(); i++) { - EnumGenerator *generator = new EnumGenerator(file_->enum_type(i)); - enum_generators_.push_back(generator); - } - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator *generator = - new MessageGenerator(root_class_name_, file_->message_type(i), options_); - message_generators_.push_back(generator); - } - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator *generator = - new ExtensionGenerator(root_class_name_, file_->extension(i)); - extension_generators_.push_back(generator); - } -} - -FileGenerator::~FileGenerator() { - STLDeleteContainerPointers(enum_generators_.begin(), enum_generators_.end()); - STLDeleteContainerPointers(message_generators_.begin(), - message_generators_.end()); - STLDeleteContainerPointers(extension_generators_.begin(), - extension_generators_.end()); -} - -void FileGenerator::GenerateHeader(io::Printer *printer) { - std::set headers; - // Generated files bundled with the library get minimal imports, everything - // else gets the wrapper so everything is usable. - if (is_bundled_proto_) { - headers.insert("GPBRootObject.h"); - headers.insert("GPBMessage.h"); - headers.insert("GPBDescriptor.h"); - } else { - headers.insert("GPBProtocolBuffers.h"); - } - PrintFileRuntimePreamble(printer, headers); - - // Add some verification that the generated code matches the source the - // code is being compiled with. - // NOTE: This captures the raw numeric values at the time the generator was - // compiled, since that will be the versions for the ObjC runtime at that - // time. The constants in the generated code will then get their values at - // at compile time (so checking against the headers being used to compile). - printer->Print( - "#if GOOGLE_PROTOBUF_OBJC_VERSION < $google_protobuf_objc_version$\n" - "#error This file was generated by a newer version of protoc which is incompatible with your Protocol Buffer library sources.\n" - "#endif\n" - "#if $google_protobuf_objc_version$ < GOOGLE_PROTOBUF_OBJC_MIN_SUPPORTED_VERSION\n" - "#error This file was generated by an older version of protoc which is incompatible with your Protocol Buffer library sources.\n" - "#endif\n" - "\n", - "google_protobuf_objc_version", SimpleItoa(GOOGLE_PROTOBUF_OBJC_VERSION)); - - // #import any headers for "public imports" in the proto file. - { - ImportWriter import_writer( - options_.generate_for_named_framework, - options_.named_framework_to_proto_path_mappings_path, - is_bundled_proto_); - const string header_extension(kHeaderExtension); - for (int i = 0; i < file_->public_dependency_count(); i++) { - import_writer.AddFile(file_->public_dependency(i), header_extension); - } - import_writer.Print(printer); - } - - // Note: - // deprecated-declarations suppression is only needed if some place in this - // proto file is something deprecated or if it references something from - // another file that is deprecated. - printer->Print( - "// @@protoc_insertion_point(imports)\n" - "\n" - "#pragma clang diagnostic push\n" - "#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n" - "\n" - "CF_EXTERN_C_BEGIN\n" - "\n"); - - std::set fwd_decls; - for (std::vector::iterator iter = message_generators_.begin(); - iter != message_generators_.end(); ++iter) { - (*iter)->DetermineForwardDeclarations(&fwd_decls); - } - for (std::set::const_iterator i(fwd_decls.begin()); - i != fwd_decls.end(); ++i) { - printer->Print("$value$;\n", "value", *i); - } - if (fwd_decls.begin() != fwd_decls.end()) { - printer->Print("\n"); - } - - printer->Print( - "NS_ASSUME_NONNULL_BEGIN\n" - "\n"); - - // need to write out all enums first - for (std::vector::iterator iter = enum_generators_.begin(); - iter != enum_generators_.end(); ++iter) { - (*iter)->GenerateHeader(printer); - } - - for (std::vector::iterator iter = message_generators_.begin(); - iter != message_generators_.end(); ++iter) { - (*iter)->GenerateEnumHeader(printer); - } - - // For extensions to chain together, the Root gets created even if there - // are no extensions. - printer->Print( - "#pragma mark - $root_class_name$\n" - "\n" - "/**\n" - " * Exposes the extension registry for this file.\n" - " *\n" - " * The base class provides:\n" - " * @code\n" - " * + (GPBExtensionRegistry *)extensionRegistry;\n" - " * @endcode\n" - " * which is a @c GPBExtensionRegistry that includes all the extensions defined by\n" - " * this file and all files that it depends on.\n" - " **/\n" - "@interface $root_class_name$ : GPBRootObject\n" - "@end\n" - "\n", - "root_class_name", root_class_name_); - - if (extension_generators_.size() > 0) { - // The dynamic methods block is only needed if there are extensions. - printer->Print( - "@interface $root_class_name$ (DynamicMethods)\n", - "root_class_name", root_class_name_); - - for (std::vector::iterator iter = - extension_generators_.begin(); - iter != extension_generators_.end(); ++iter) { - (*iter)->GenerateMembersHeader(printer); - } - - printer->Print("@end\n\n"); - } // extension_generators_.size() > 0 - - for (std::vector::iterator iter = message_generators_.begin(); - iter != message_generators_.end(); ++iter) { - (*iter)->GenerateMessageHeader(printer); - } - - printer->Print( - "NS_ASSUME_NONNULL_END\n" - "\n" - "CF_EXTERN_C_END\n" - "\n" - "#pragma clang diagnostic pop\n" - "\n" - "// @@protoc_insertion_point(global_scope)\n"); -} - -void FileGenerator::GenerateSource(io::Printer *printer) { - // #import the runtime support. - std::set headers; - headers.insert("GPBProtocolBuffers_RuntimeSupport.h"); - PrintFileRuntimePreamble(printer, headers); - - // Enums use atomic in the generated code, so add the system import as needed. - if (FileContainsEnums(file_)) { - printer->Print( - "#import \n" - "\n"); - } - - std::vector deps_with_extensions; - CollectMinimalFileDepsContainingExtensions(file_, &deps_with_extensions); - - { - ImportWriter import_writer( - options_.generate_for_named_framework, - options_.named_framework_to_proto_path_mappings_path, - is_bundled_proto_); - const string header_extension(kHeaderExtension); - - // #import the header for this proto file. - import_writer.AddFile(file_, header_extension); - - // #import the headers for anything that a plain dependency of this proto - // file (that means they were just an include, not a "public" include). - std::set public_import_names; - for (int i = 0; i < file_->public_dependency_count(); i++) { - public_import_names.insert(file_->public_dependency(i)->name()); - } - for (int i = 0; i < file_->dependency_count(); i++) { - const FileDescriptor *dep = file_->dependency(i); - bool public_import = (public_import_names.count(dep->name()) != 0); - if (!public_import) { - import_writer.AddFile(dep, header_extension); - } - } - - // If any indirect dependency provided extensions, it needs to be directly - // imported so it can get merged into the root's extensions registry. - // See the Note by CollectMinimalFileDepsContainingExtensions before - // changing this. - for (std::vector::iterator iter = - deps_with_extensions.begin(); - iter != deps_with_extensions.end(); ++iter) { - if (!IsDirectDependency(*iter, file_)) { - import_writer.AddFile(*iter, header_extension); - } - } - - import_writer.Print(printer); - } - - bool includes_oneof = false; - for (std::vector::iterator iter = message_generators_.begin(); - iter != message_generators_.end(); ++iter) { - if ((*iter)->IncludesOneOfDefinition()) { - includes_oneof = true; - break; - } - } - - // Note: - // deprecated-declarations suppression is only needed if some place in this - // proto file is something deprecated or if it references something from - // another file that is deprecated. - printer->Print( - "// @@protoc_insertion_point(imports)\n" - "\n" - "#pragma clang diagnostic push\n" - "#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"\n"); - if (includes_oneof) { - // The generated code for oneof's uses direct ivar access, suppress the - // warning incase developer turn that on in the context they compile the - // generated code. - printer->Print( - "#pragma clang diagnostic ignored \"-Wdirect-ivar-access\"\n"); - } - - printer->Print( - "\n" - "#pragma mark - $root_class_name$\n" - "\n" - "@implementation $root_class_name$\n\n", - "root_class_name", root_class_name_); - - const bool file_contains_extensions = FileContainsExtensions(file_); - - // If there were any extensions or this file has any dependencies, output - // a registry to override to create the file specific registry. - if (file_contains_extensions || !deps_with_extensions.empty()) { - printer->Print( - "+ (GPBExtensionRegistry*)extensionRegistry {\n" - " // This is called by +initialize so there is no need to worry\n" - " // about thread safety and initialization of registry.\n" - " static GPBExtensionRegistry* registry = nil;\n" - " if (!registry) {\n" - " GPB_DEBUG_CHECK_RUNTIME_VERSIONS();\n" - " registry = [[GPBExtensionRegistry alloc] init];\n"); - - printer->Indent(); - printer->Indent(); - - if (file_contains_extensions) { - printer->Print( - "static GPBExtensionDescription descriptions[] = {\n"); - printer->Indent(); - for (std::vector::iterator iter = - extension_generators_.begin(); - iter != extension_generators_.end(); ++iter) { - (*iter)->GenerateStaticVariablesInitialization(printer); - } - for (std::vector::iterator iter = - message_generators_.begin(); - iter != message_generators_.end(); ++iter) { - (*iter)->GenerateStaticVariablesInitialization(printer); - } - printer->Outdent(); - printer->Print( - "};\n" - "for (size_t i = 0; i < sizeof(descriptions) / sizeof(descriptions[0]); ++i) {\n" - " GPBExtensionDescriptor *extension =\n" - " [[GPBExtensionDescriptor alloc] initWithExtensionDescription:&descriptions[i]];\n" - " [registry addExtension:extension];\n" - " [self globallyRegisterExtension:extension];\n" - " [extension release];\n" - "}\n"); - } - - if (deps_with_extensions.empty()) { - printer->Print( - "// None of the imports (direct or indirect) defined extensions, so no need to add\n" - "// them to this registry.\n"); - } else { - printer->Print( - "// Merge in the imports (direct or indirect) that defined extensions.\n"); - for (std::vector::iterator iter = - deps_with_extensions.begin(); - iter != deps_with_extensions.end(); ++iter) { - const string root_class_name(FileClassName((*iter))); - printer->Print( - "[registry addExtensions:[$dependency$ extensionRegistry]];\n", - "dependency", root_class_name); - } - } - - printer->Outdent(); - printer->Outdent(); - - printer->Print( - " }\n" - " return registry;\n" - "}\n"); - } else { - if (file_->dependency_count() > 0) { - printer->Print( - "// No extensions in the file and none of the imports (direct or indirect)\n" - "// defined extensions, so no need to generate +extensionRegistry.\n"); - } else { - printer->Print( - "// No extensions in the file and no imports, so no need to generate\n" - "// +extensionRegistry.\n"); - } - } - - printer->Print("\n@end\n\n"); - - // File descriptor only needed if there are messages to use it. - if (message_generators_.size() > 0) { - std::map vars; - vars["root_class_name"] = root_class_name_; - vars["package"] = file_->package(); - vars["objc_prefix"] = FileClassPrefix(file_); - switch (file_->syntax()) { - case FileDescriptor::SYNTAX_UNKNOWN: - vars["syntax"] = "GPBFileSyntaxUnknown"; - break; - case FileDescriptor::SYNTAX_PROTO2: - vars["syntax"] = "GPBFileSyntaxProto2"; - break; - case FileDescriptor::SYNTAX_PROTO3: - vars["syntax"] = "GPBFileSyntaxProto3"; - break; - } - printer->Print(vars, - "#pragma mark - $root_class_name$_FileDescriptor\n" - "\n" - "static GPBFileDescriptor *$root_class_name$_FileDescriptor(void) {\n" - " // This is called by +initialize so there is no need to worry\n" - " // about thread safety of the singleton.\n" - " static GPBFileDescriptor *descriptor = NULL;\n" - " if (!descriptor) {\n" - " GPB_DEBUG_CHECK_RUNTIME_VERSIONS();\n"); - if (vars["objc_prefix"].size() > 0) { - printer->Print( - vars, - " descriptor = [[GPBFileDescriptor alloc] initWithPackage:@\"$package$\"\n" - " objcPrefix:@\"$objc_prefix$\"\n" - " syntax:$syntax$];\n"); - } else { - printer->Print( - vars, - " descriptor = [[GPBFileDescriptor alloc] initWithPackage:@\"$package$\"\n" - " syntax:$syntax$];\n"); - } - printer->Print( - " }\n" - " return descriptor;\n" - "}\n" - "\n"); - } - - for (std::vector::iterator iter = enum_generators_.begin(); - iter != enum_generators_.end(); ++iter) { - (*iter)->GenerateSource(printer); - } - for (std::vector::iterator iter = message_generators_.begin(); - iter != message_generators_.end(); ++iter) { - (*iter)->GenerateSource(printer); - } - - printer->Print( - "\n" - "#pragma clang diagnostic pop\n" - "\n" - "// @@protoc_insertion_point(global_scope)\n"); -} - -// Helper to print the import of the runtime support at the top of generated -// files. This currently only supports the runtime coming from a framework -// as defined by the official CocoaPod. -void FileGenerator::PrintFileRuntimePreamble( - io::Printer* printer, const std::set& headers_to_import) const { - printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "// source: $filename$\n" - "\n", - "filename", file_->name()); - - const string framework_name(ProtobufLibraryFrameworkName); - const string cpp_symbol(ProtobufFrameworkImportSymbol(framework_name)); - - printer->Print( - "// This CPP symbol can be defined to use imports that match up to the framework\n" - "// imports needed when using CocoaPods.\n" - "#if !defined($cpp_symbol$)\n" - " #define $cpp_symbol$ 0\n" - "#endif\n" - "\n" - "#if $cpp_symbol$\n", - "cpp_symbol", cpp_symbol); - - - for (std::set::const_iterator iter = headers_to_import.begin(); - iter != headers_to_import.end(); ++iter) { - printer->Print( - " #import <$framework_name$/$header$>\n", - "header", *iter, - "framework_name", framework_name); - } - - printer->Print( - "#else\n"); - - for (std::set::const_iterator iter = headers_to_import.begin(); - iter != headers_to_import.end(); ++iter) { - printer->Print( - " #import \"$header$\"\n", - "header", *iter); - } - - printer->Print( - "#endif\n" - "\n"); -} - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_file.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_file.h deleted file mode 100644 index 1754fc0ad..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_file.h +++ /dev/null @@ -1,88 +0,0 @@ -// 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_FILE_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_FILE_H__ - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -class FileDescriptor; // descriptor.h -namespace io { -class Printer; // printer.h -} -} - -namespace protobuf { -namespace compiler { -namespace objectivec { - -class EnumGenerator; -class ExtensionGenerator; -class MessageGenerator; - -class FileGenerator { - public: - FileGenerator(const FileDescriptor* file, const Options& options); - ~FileGenerator(); - - void GenerateSource(io::Printer* printer); - void GenerateHeader(io::Printer* printer); - - const string& RootClassName() const { return root_class_name_; } - - private: - const FileDescriptor* file_; - string root_class_name_; - bool is_bundled_proto_; - - std::vector enum_generators_; - std::vector message_generators_; - std::vector extension_generators_; - - const Options options_; - - void PrintFileRuntimePreamble( - io::Printer* printer, const std::set& headers_to_import) const; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); -}; - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_FILE_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_generator.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_generator.cc deleted file mode 100644 index e0597cc7f..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_generator.cc +++ /dev/null @@ -1,166 +0,0 @@ -// 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. - -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -ObjectiveCGenerator::ObjectiveCGenerator() {} - -ObjectiveCGenerator::~ObjectiveCGenerator() {} - -bool ObjectiveCGenerator::HasGenerateAll() const { - return true; -} - -bool ObjectiveCGenerator::Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - *error = "Unimplemented Generate() method. Call GenerateAll() instead."; - return false; -} - -bool ObjectiveCGenerator::GenerateAll(const std::vector& files, - const string& parameter, - GeneratorContext* context, - string* error) const { - // ----------------------------------------------------------------- - // Parse generator options. These options are passed to the compiler using the - // --objc_opt flag. The options are passed as a comma separated list of - // options along with their values. If the option appears multiple times, only - // the last value will be considered. - // - // e.g. protoc ... --objc_opt=expected_prefixes=file.txt,generate_for_named_framework=MyFramework - - Options generation_options; - - std::vector > options; - ParseGeneratorParameter(parameter, &options); - for (int i = 0; i < options.size(); i++) { - if (options[i].first == "expected_prefixes_path") { - // Path to find a file containing the expected prefixes - // (objc_class_prefix "PREFIX") for proto packages (package NAME). The - // generator will then issue warnings/errors if in the proto files being - // generated the option is not listed/wrong/etc in the file. - // - // The format of the file is: - // - An entry is a line of "package=prefix". - // - Comments start with "#". - // - A comment can go on a line after a expected package/prefix pair. - // (i.e. - "package=prefix # comment") - // - // There is no validation that the prefixes are good prefixes, it is - // assumed that they are when you create the file. - generation_options.expected_prefixes_path = options[i].second; - } else if (options[i].first == "generate_for_named_framework") { - // The name of the framework that protos are being generated for. This - // will cause the #import statements to be framework based using this - // name (i.e. - "#import ). - // - // NOTE: If this option is used with - // named_framework_to_proto_path_mappings_path, then this is effectively - // the "default" framework name used for everything that wasn't mapped by - // the mapping file. - generation_options.generate_for_named_framework = options[i].second; - } else if (options[i].first == "named_framework_to_proto_path_mappings_path") { - // Path to find a file containing the list of framework names and proto - // files. The generator uses this to decide if a proto file - // referenced should use a framework style import vs. a user level import - // (#import vs #import "dir/file.pbobjc.h"). - // - // The format of the file is: - // - An entry is a line of "frameworkName: file.proto, dir/file2.proto". - // - Comments start with "#". - // - A comment can go on a line after a expected package/prefix pair. - // (i.e. - "frameworkName: file.proto # comment") - // - // Any number of files can be listed for a framework, just separate them - // with commas. - // - // There can be multiple lines listing the same frameworkName incase it - // has a lot of proto files included in it; having multiple lines makes - // things easier to read. If a proto file is not configured in the - // mappings file, it will use the default framework name if one was passed - // with generate_for_named_framework, or the relative path to it's include - // path otherwise. - generation_options.named_framework_to_proto_path_mappings_path = options[i].second; - } else { - *error = "error: Unknown generator option: " + options[i].first; - return false; - } - } - - // ----------------------------------------------------------------- - - // Validate the objc prefix/package pairings. - if (!ValidateObjCClassPrefixes(files, generation_options, error)) { - // *error will have been filled in. - return false; - } - - for (int i = 0; i < files.size(); i++) { - const FileDescriptor* file = files[i]; - FileGenerator file_generator(file, generation_options); - string filepath = FilePath(file); - - // Generate header. - { - std::unique_ptr output( - context->Open(filepath + ".pbobjc.h")); - io::Printer printer(output.get(), '$'); - file_generator.GenerateHeader(&printer); - } - - // Generate m file. - { - std::unique_ptr output( - context->Open(filepath + ".pbobjc.m")); - io::Printer printer(output.get(), '$'); - file_generator.GenerateSource(&printer); - } - } - - return true; -} - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_generator.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_generator.h index 3e43f732d..1dbc666af 100644 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_generator.h +++ b/windows/include/google/protobuf/compiler/objectivec/objectivec_generator.h @@ -35,6 +35,9 @@ #include #include +#include + +#include namespace google { namespace protobuf { @@ -45,28 +48,32 @@ namespace objectivec { // header. If you create your own protocol compiler binary and you want it to // support ObjectiveC output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { +class PROTOC_EXPORT ObjectiveCGenerator : public CodeGenerator { public: ObjectiveCGenerator(); ~ObjectiveCGenerator(); - // implements CodeGenerator ---------------------------------------- - bool HasGenerateAll() const; - bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const; - bool GenerateAll(const std::vector& files, - const string& parameter, - GeneratorContext* context, - string* error) const; + ObjectiveCGenerator(const ObjectiveCGenerator&) = delete; + ObjectiveCGenerator& operator=(const ObjectiveCGenerator&) = delete; - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ObjectiveCGenerator); + // implements CodeGenerator ---------------------------------------- + bool HasGenerateAll() const override; + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* context, std::string* error) const override; + bool GenerateAll(const std::vector& files, + const std::string& parameter, GeneratorContext* context, + std::string* error) const override; + + uint64_t GetSupportedFeatures() const override { + return FEATURE_PROTO3_OPTIONAL; + } }; } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers.cc deleted file mode 100644 index df71c8bb1..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers.cc +++ /dev/null @@ -1,1688 +0,0 @@ -// 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 _MSC_VER -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#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. - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -// is transitively included in this file. Import the functions explicitly -// in this port namespace to avoid ambiguous definition. -namespace posix { -#ifdef _WIN32 -using ::google::protobuf::internal::win32::open; -#else -using ::open; -#endif -} // namespace port - -Options::Options() { - // Default is the value of the env for the package prefixes. - const char* file_path = getenv("GPB_OBJC_EXPECTED_PACKAGE_PREFIXES"); - if (file_path) { - expected_prefixes_path = file_path; - } -} - -namespace { - -hash_set MakeWordsMap(const char* const words[], size_t num_words) { - hash_set result; - for (int i = 0; i < num_words; i++) { - result.insert(words[i]); - } - return result; -} - -const char* const kUpperSegmentsList[] = {"url", "http", "https"}; - -hash_set kUpperSegments = - MakeWordsMap(kUpperSegmentsList, GOOGLE_ARRAYSIZE(kUpperSegmentsList)); - -bool ascii_isnewline(char c) { - return c == '\n' || c == '\r'; -} - -// Internal helper for name handing. -// Do not expose this outside of helpers, stick to having functions for specific -// cases (ClassName(), FieldName()), so there is always consistent suffix rules. -string UnderscoresToCamelCase(const string& input, bool first_capitalized) { - std::vector values; - string current; - - bool last_char_was_number = false; - bool last_char_was_lower = false; - bool last_char_was_upper = false; - for (int i = 0; i < input.size(); i++) { - char c = input[i]; - if (ascii_isdigit(c)) { - if (!last_char_was_number) { - values.push_back(current); - current = ""; - } - current += c; - last_char_was_number = last_char_was_lower = last_char_was_upper = false; - last_char_was_number = true; - } else if (ascii_islower(c)) { - // lowercase letter can follow a lowercase or uppercase letter - if (!last_char_was_lower && !last_char_was_upper) { - values.push_back(current); - current = ""; - } - current += c; // already lower - last_char_was_number = last_char_was_lower = last_char_was_upper = false; - last_char_was_lower = true; - } else if (ascii_isupper(c)) { - if (!last_char_was_upper) { - values.push_back(current); - current = ""; - } - current += ascii_tolower(c); - last_char_was_number = last_char_was_lower = last_char_was_upper = false; - last_char_was_upper = true; - } else { - last_char_was_number = last_char_was_lower = last_char_was_upper = false; - } - } - values.push_back(current); - - string result; - bool first_segment_forces_upper = false; - for (std::vector::iterator i = values.begin(); i != values.end(); ++i) { - string value = *i; - bool all_upper = (kUpperSegments.count(value) > 0); - if (all_upper && (result.length() == 0)) { - first_segment_forces_upper = true; - } - for (int j = 0; j < value.length(); j++) { - if (j == 0 || all_upper) { - value[j] = ascii_toupper(value[j]); - } else { - // Nothing, already in lower. - } - } - result += value; - } - if ((result.length() != 0) && - !first_capitalized && - !first_segment_forces_upper) { - result[0] = ascii_tolower(result[0]); - } - return result; -} - -const char* const kReservedWordList[] = { - // Objective C "keywords" that aren't in C - // From - // http://stackoverflow.com/questions/1873630/reserved-keywords-in-objective-c - "id", "_cmd", "super", "in", "out", "inout", "bycopy", "byref", "oneway", - "self", - - // C/C++ keywords (Incl C++ 0x11) - // From http://en.cppreference.com/w/cpp/keywords - "and", "and_eq", "alignas", "alignof", "asm", "auto", "bitand", "bitor", - "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", - "compl", "const", "constexpr", "const_cast", "continue", "decltype", - "default", "delete", "double", "dynamic_cast", "else", "enum", "explicit", - "export", "extern ", "false", "float", "for", "friend", "goto", "if", - "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not", - "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", - "public", "register", "reinterpret_cast", "return", "short", "signed", - "sizeof", "static", "static_assert", "static_cast", "struct", "switch", - "template", "this", "thread_local", "throw", "true", "try", "typedef", - "typeid", "typename", "union", "unsigned", "using", "virtual", "void", - "volatile", "wchar_t", "while", "xor", "xor_eq", - - // C99 keywords - // From - // http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fkeyw.htm - "restrict", - - // Objective-C Runtime typedefs - // From - "Category", "Ivar", "Method", "Protocol", - - // NSObject Methods - // new is covered by C++ keywords. - "description", "debugDescription", "finalize", "hash", "dealloc", "init", - "class", "superclass", "retain", "release", "autorelease", "retainCount", - "zone", "isProxy", "copy", "mutableCopy", "classForCoder", - - // GPBMessage Methods - // Only need to add instance methods that may conflict with - // method declared in protos. The main cases are methods - // that take no arguments, or setFoo:/hasFoo: type methods. - "clear", "data", "delimitedData", "descriptor", "extensionRegistry", - "extensionsCurrentlySet", "initialized", "isInitialized", "serializedSize", - "sortedExtensionsInUse", "unknownFields", - - // MacTypes.h names - "Fixed", "Fract", "Size", "LogicalAddress", "PhysicalAddress", "ByteCount", - "ByteOffset", "Duration", "AbsoluteTime", "OptionBits", "ItemCount", - "PBVersion", "ScriptCode", "LangCode", "RegionCode", "OSType", - "ProcessSerialNumber", "Point", "Rect", "FixedPoint", "FixedRect", "Style", - "StyleParameter", "StyleField", "TimeScale", "TimeBase", "TimeRecord", -}; - -hash_set kReservedWords = - MakeWordsMap(kReservedWordList, GOOGLE_ARRAYSIZE(kReservedWordList)); - -string SanitizeNameForObjC(const string& input, - const string& extension, - string* out_suffix_added) { - if (kReservedWords.count(input) > 0) { - if (out_suffix_added) *out_suffix_added = extension; - return input + extension; - } - if (out_suffix_added) out_suffix_added->clear(); - return input; -} - -string NameFromFieldDescriptor(const FieldDescriptor* field) { - if (field->type() == FieldDescriptor::TYPE_GROUP) { - return field->message_type()->name(); - } else { - return field->name(); - } -} - -void PathSplit(const string& path, string* directory, string* basename) { - string::size_type last_slash = path.rfind('/'); - if (last_slash == string::npos) { - if (directory) { - *directory = ""; - } - if (basename) { - *basename = path; - } - } else { - if (directory) { - *directory = path.substr(0, last_slash); - } - if (basename) { - *basename = path.substr(last_slash + 1); - } - } -} - -bool IsSpecialName(const string& name, const string* special_names, - size_t count) { - for (size_t i = 0; i < count; ++i) { - 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 - // the next character must be not lower case (newton vs newTon vs - // new_ton). - return !ascii_islower(name[length]); - } else { - return true; - } - } - } - return false; -} - -string GetZeroEnumNameForFlagType(const FlagType flag_type) { - switch(flag_type) { - case FLAGTYPE_DESCRIPTOR_INITIALIZATION: - return "GPBDescriptorInitializationFlag_None"; - case FLAGTYPE_EXTENSION: - return "GPBExtensionNone"; - case FLAGTYPE_FIELD: - return "GPBFieldNone"; - default: - GOOGLE_LOG(FATAL) << "Can't get here."; - return "0"; - } -} - -string GetEnumNameForFlagType(const FlagType flag_type) { - switch(flag_type) { - case FLAGTYPE_DESCRIPTOR_INITIALIZATION: - return "GPBDescriptorInitializationFlags"; - case FLAGTYPE_EXTENSION: - return "GPBExtensionOptions"; - case FLAGTYPE_FIELD: - return "GPBFieldFlags"; - default: - GOOGLE_LOG(FATAL) << "Can't get here."; - return string(); - } -} - -} // namespace - -// Escape C++ trigraphs by escaping question marks to \? -string EscapeTrigraphs(const string& to_escape) { - return StringReplace(to_escape, "?", "\\?", true); -} - -string StripProto(const string& filename) { - if (HasSuffixString(filename, ".protodevel")) { - return StripSuffixString(filename, ".protodevel"); - } else { - return StripSuffixString(filename, ".proto"); - } -} - -void StringPieceTrimWhitespace(StringPiece* input) { - while (!input->empty() && ascii_isspace(*input->data())) { - input->remove_prefix(1); - } - while (!input->empty() && ascii_isspace((*input)[input->length() - 1])) { - input->remove_suffix(1); - } -} - - -bool IsRetainedName(const string& name) { - // List of prefixes from - // http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html - static const string retained_names[] = {"new", "alloc", "copy", - "mutableCopy"}; - return IsSpecialName(name, retained_names, - sizeof(retained_names) / sizeof(retained_names[0])); -} - -bool IsInitName(const string& name) { - static const string init_names[] = {"init"}; - return IsSpecialName(name, init_names, - sizeof(init_names) / sizeof(init_names[0])); -} - -string BaseFileName(const FileDescriptor* file) { - string basename; - PathSplit(file->name(), NULL, &basename); - return basename; -} - -string FileClassPrefix(const FileDescriptor* file) { - // Default is empty string, no need to check has_objc_class_prefix. - string result = file->options().objc_class_prefix(); - return result; -} - -string FilePath(const FileDescriptor* file) { - string output; - string basename; - string directory; - PathSplit(file->name(), &directory, &basename); - if (directory.length() > 0) { - output = directory + "/"; - } - basename = StripProto(basename); - - // CamelCase to be more ObjC friendly. - basename = UnderscoresToCamelCase(basename, true); - - output += basename; - return output; -} - -string FilePathBasename(const FileDescriptor* file) { - string output; - string basename; - string directory; - PathSplit(file->name(), &directory, &basename); - basename = StripProto(basename); - - // CamelCase to be more ObjC friendly. - output = UnderscoresToCamelCase(basename, true); - - return output; -} - -string FileClassName(const FileDescriptor* file) { - string name = FileClassPrefix(file); - name += UnderscoresToCamelCase(StripProto(BaseFileName(file)), true); - name += "Root"; - // There aren't really any reserved words that end in "Root", but playing - // it safe and checking. - return SanitizeNameForObjC(name, "_RootClass", NULL); -} - -string ClassNameWorker(const Descriptor* descriptor) { - string name; - if (descriptor->containing_type() != NULL) { - name = ClassNameWorker(descriptor->containing_type()); - name += "_"; - } - return name + descriptor->name(); -} - -string ClassNameWorker(const EnumDescriptor* descriptor) { - string name; - if (descriptor->containing_type() != NULL) { - name = ClassNameWorker(descriptor->containing_type()); - name += "_"; - } - return name + descriptor->name(); -} - -string ClassName(const Descriptor* descriptor) { - return ClassName(descriptor, NULL); -} - -string ClassName(const Descriptor* descriptor, string* out_suffix_added) { - // 1. Message names are used as is (style calls for CamelCase, trust it). - // 2. Check for reserved word at the very end and then suffix things. - string prefix = FileClassPrefix(descriptor->file()); - string name = ClassNameWorker(descriptor); - return SanitizeNameForObjC(prefix + name, "_Class", out_suffix_added); -} - -string EnumName(const EnumDescriptor* descriptor) { - // 1. Enum names are used as is (style calls for CamelCase, trust it). - // 2. Check for reserved word at the every end and then suffix things. - // message Fixed { - // message Size {...} - // enum Mumble {...} - // ... - // } - // yields Fixed_Class, Fixed_Size. - string name = FileClassPrefix(descriptor->file()); - name += ClassNameWorker(descriptor); - return SanitizeNameForObjC(name, "_Enum", NULL); -} - -string EnumValueName(const EnumValueDescriptor* descriptor) { - // Because of the Switch enum compatibility, the name on the enum has to have - // the suffix handing, so it slightly diverges from how nested classes work. - // enum Fixed { - // FOO = 1 - // } - // yields Fixed_Enum and Fixed_Enum_Foo (not Fixed_Foo). - const string& class_name = EnumName(descriptor->type()); - const string& value_str = UnderscoresToCamelCase(descriptor->name(), true); - const string& name = class_name + "_" + value_str; - // There aren't really any reserved words with an underscore and a leading - // capital letter, but playing it safe and checking. - return SanitizeNameForObjC(name, "_Value", NULL); -} - -string EnumValueShortName(const EnumValueDescriptor* descriptor) { - // Enum value names (EnumValueName above) are the enum name turned into - // a class name and then the value name is CamelCased and concatenated; the - // whole thing then gets sanitized for reserved words. - // The "short name" is intended to be the final leaf, the value name; but - // you can't simply send that off to sanitize as that could result in it - // getting modified when the full name didn't. For example enum - // "StorageModes" has a value "retain". So the full name is - // "StorageModes_Retain", but if we sanitize "retain" it would become - // "RetainValue". - // So the right way to get the short name is to take the full enum name - // and then strip off the enum name (leaving the value name and anything - // done by sanitize). - const string& class_name = EnumName(descriptor->type()); - const string& long_name_prefix = class_name + "_"; - const string& long_name = EnumValueName(descriptor); - return StripPrefixString(long_name, long_name_prefix); -} - -string UnCamelCaseEnumShortName(const string& name) { - string result; - for (int i = 0; i < name.size(); i++) { - char c = name[i]; - if (i > 0 && ascii_isupper(c)) { - result += '_'; - } - result += ascii_toupper(c); - } - return result; -} - -string ExtensionMethodName(const FieldDescriptor* descriptor) { - const string& name = NameFromFieldDescriptor(descriptor); - const string& result = UnderscoresToCamelCase(name, false); - return SanitizeNameForObjC(result, "_Extension", NULL); -} - -string FieldName(const FieldDescriptor* field) { - const string& name = NameFromFieldDescriptor(field); - string result = UnderscoresToCamelCase(name, false); - if (field->is_repeated() && !field->is_map()) { - // Add "Array" before do check for reserved worlds. - result += "Array"; - } else { - // If it wasn't repeated, but ends in "Array", force on the _p suffix. - if (HasSuffixString(result, "Array")) { - result += "_p"; - } - } - return SanitizeNameForObjC(result, "_p", NULL); -} - -string FieldNameCapitalized(const FieldDescriptor* field) { - // Want the same suffix handling, so upcase the first letter of the other - // name. - string result = FieldName(field); - if (result.length() > 0) { - result[0] = ascii_toupper(result[0]); - } - return result; -} - -string OneofEnumName(const OneofDescriptor* descriptor) { - const Descriptor* fieldDescriptor = descriptor->containing_type(); - string name = ClassName(fieldDescriptor); - name += "_" + UnderscoresToCamelCase(descriptor->name(), true) + "_OneOfCase"; - // No sanitize needed because the OS never has names that end in _OneOfCase. - return name; -} - -string OneofName(const OneofDescriptor* descriptor) { - string name = UnderscoresToCamelCase(descriptor->name(), false); - // No sanitize needed because it gets OneOfCase added and that shouldn't - // ever conflict. - return name; -} - -string OneofNameCapitalized(const OneofDescriptor* descriptor) { - // Use the common handling and then up-case the first letter. - string result = OneofName(descriptor); - if (result.length() > 0) { - result[0] = ascii_toupper(result[0]); - } - return result; -} - -string UnCamelCaseFieldName(const string& name, const FieldDescriptor* field) { - string worker(name); - if (HasSuffixString(worker, "_p")) { - worker = StripSuffixString(worker, "_p"); - } - if (field->is_repeated() && HasSuffixString(worker, "Array")) { - worker = StripSuffixString(worker, "Array"); - } - if (field->type() == FieldDescriptor::TYPE_GROUP) { - if (worker.length() > 0) { - if (ascii_islower(worker[0])) { - worker[0] = ascii_toupper(worker[0]); - } - } - return worker; - } else { - string result; - for (int i = 0; i < worker.size(); i++) { - char c = worker[i]; - if (ascii_isupper(c)) { - if (i > 0) { - result += '_'; - } - result += ascii_tolower(c); - } else { - result += c; - } - } - return result; - } -} - -string GetCapitalizedType(const FieldDescriptor* field) { - switch (field->type()) { - case FieldDescriptor::TYPE_INT32: - return "Int32"; - case FieldDescriptor::TYPE_UINT32: - return "UInt32"; - case FieldDescriptor::TYPE_SINT32: - return "SInt32"; - case FieldDescriptor::TYPE_FIXED32: - return "Fixed32"; - case FieldDescriptor::TYPE_SFIXED32: - return "SFixed32"; - case FieldDescriptor::TYPE_INT64: - return "Int64"; - case FieldDescriptor::TYPE_UINT64: - return "UInt64"; - case FieldDescriptor::TYPE_SINT64: - return "SInt64"; - case FieldDescriptor::TYPE_FIXED64: - return "Fixed64"; - case FieldDescriptor::TYPE_SFIXED64: - return "SFixed64"; - case FieldDescriptor::TYPE_FLOAT: - return "Float"; - case FieldDescriptor::TYPE_DOUBLE: - return "Double"; - case FieldDescriptor::TYPE_BOOL: - return "Bool"; - case FieldDescriptor::TYPE_STRING: - return "String"; - case FieldDescriptor::TYPE_BYTES: - return "Bytes"; - case FieldDescriptor::TYPE_ENUM: - return "Enum"; - case FieldDescriptor::TYPE_GROUP: - return "Group"; - case FieldDescriptor::TYPE_MESSAGE: - return "Message"; - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -ObjectiveCType GetObjectiveCType(FieldDescriptor::Type field_type) { - switch (field_type) { - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_SFIXED32: - return OBJECTIVECTYPE_INT32; - - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_FIXED32: - return OBJECTIVECTYPE_UINT32; - - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_SFIXED64: - return OBJECTIVECTYPE_INT64; - - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_FIXED64: - return OBJECTIVECTYPE_UINT64; - - case FieldDescriptor::TYPE_FLOAT: - return OBJECTIVECTYPE_FLOAT; - - case FieldDescriptor::TYPE_DOUBLE: - return OBJECTIVECTYPE_DOUBLE; - - case FieldDescriptor::TYPE_BOOL: - return OBJECTIVECTYPE_BOOLEAN; - - case FieldDescriptor::TYPE_STRING: - return OBJECTIVECTYPE_STRING; - - case FieldDescriptor::TYPE_BYTES: - return OBJECTIVECTYPE_DATA; - - case FieldDescriptor::TYPE_ENUM: - return OBJECTIVECTYPE_ENUM; - - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_MESSAGE: - return OBJECTIVECTYPE_MESSAGE; - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return OBJECTIVECTYPE_INT32; -} - -bool IsPrimitiveType(const FieldDescriptor* field) { - ObjectiveCType type = GetObjectiveCType(field); - switch (type) { - case OBJECTIVECTYPE_INT32: - case OBJECTIVECTYPE_UINT32: - case OBJECTIVECTYPE_INT64: - case OBJECTIVECTYPE_UINT64: - case OBJECTIVECTYPE_FLOAT: - case OBJECTIVECTYPE_DOUBLE: - case OBJECTIVECTYPE_BOOLEAN: - case OBJECTIVECTYPE_ENUM: - return true; - break; - default: - return false; - } -} - -bool IsReferenceType(const FieldDescriptor* field) { - return !IsPrimitiveType(field); -} - -static string HandleExtremeFloatingPoint(string val, bool add_float_suffix) { - if (val == "nan") { - return "NAN"; - } else if (val == "inf") { - return "INFINITY"; - } else if (val == "-inf") { - return "-INFINITY"; - } else { - // float strings with ., e or E need to have f appended - if (add_float_suffix && - (val.find(".") != string::npos || val.find("e") != string::npos || - val.find("E") != string::npos)) { - val += "f"; - } - return val; - } -} - -string GPBGenericValueFieldName(const FieldDescriptor* field) { - // Returns the field within the GPBGenericValue union to use for the given - // field. - if (field->is_repeated()) { - return "valueMessage"; - } - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - return "valueInt32"; - case FieldDescriptor::CPPTYPE_UINT32: - return "valueUInt32"; - case FieldDescriptor::CPPTYPE_INT64: - return "valueInt64"; - case FieldDescriptor::CPPTYPE_UINT64: - return "valueUInt64"; - case FieldDescriptor::CPPTYPE_FLOAT: - return "valueFloat"; - case FieldDescriptor::CPPTYPE_DOUBLE: - return "valueDouble"; - case FieldDescriptor::CPPTYPE_BOOL: - return "valueBool"; - case FieldDescriptor::CPPTYPE_STRING: - if (field->type() == FieldDescriptor::TYPE_BYTES) { - return "valueData"; - } else { - return "valueString"; - } - case FieldDescriptor::CPPTYPE_ENUM: - return "valueEnum"; - case FieldDescriptor::CPPTYPE_MESSAGE: - return "valueMessage"; - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - - -string DefaultValue(const FieldDescriptor* field) { - // Repeated fields don't have defaults. - if (field->is_repeated()) { - return "nil"; - } - - // Switch on cpp_type since we need to know which default_value_* method - // of FieldDescriptor to call. - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - // gcc and llvm reject the decimal form of kint32min and kint64min. - if (field->default_value_int32() == INT_MIN) { - return "-0x80000000"; - } - return SimpleItoa(field->default_value_int32()); - case FieldDescriptor::CPPTYPE_UINT32: - return SimpleItoa(field->default_value_uint32()) + "U"; - case FieldDescriptor::CPPTYPE_INT64: - // gcc and llvm reject the decimal form of kint32min and kint64min. - if (field->default_value_int64() == LLONG_MIN) { - return "-0x8000000000000000LL"; - } - return SimpleItoa(field->default_value_int64()) + "LL"; - case FieldDescriptor::CPPTYPE_UINT64: - return SimpleItoa(field->default_value_uint64()) + "ULL"; - case FieldDescriptor::CPPTYPE_DOUBLE: - return HandleExtremeFloatingPoint( - SimpleDtoa(field->default_value_double()), false); - case FieldDescriptor::CPPTYPE_FLOAT: - return HandleExtremeFloatingPoint( - SimpleFtoa(field->default_value_float()), true); - case FieldDescriptor::CPPTYPE_BOOL: - return field->default_value_bool() ? "YES" : "NO"; - case FieldDescriptor::CPPTYPE_STRING: { - const bool has_default_value = field->has_default_value(); - const string& default_string = field->default_value_string(); - if (!has_default_value || default_string.length() == 0) { - // If the field is defined as being the empty string, - // then we will just assign to nil, as the empty string is the - // default for both strings and data. - return "nil"; - } - if (field->type() == FieldDescriptor::TYPE_BYTES) { - // We want constant fields in our data structures so we can - // declare them as static. To achieve this we cheat and stuff - // a escaped c string (prefixed with a length) into the data - // field, and cast it to an (NSData*) so it will compile. - // The runtime library knows how to handle it. - - // Must convert to a standard byte order for packing length into - // a cstring. - uint32 length = ghtonl(default_string.length()); - string bytes((const char*)&length, sizeof(length)); - bytes.append(default_string); - return "(NSData*)\"" + EscapeTrigraphs(CEscape(bytes)) + "\""; - } else { - return "@\"" + EscapeTrigraphs(CEscape(default_string)) + "\""; - } - } - case FieldDescriptor::CPPTYPE_ENUM: - return EnumValueName(field->default_value_enum()); - case FieldDescriptor::CPPTYPE_MESSAGE: - return "nil"; - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -bool HasNonZeroDefaultValue(const FieldDescriptor* field) { - // Repeated fields don't have defaults. - if (field->is_repeated()) { - return false; - } - - // As much as checking field->has_default_value() seems useful, it isn't - // because of enums. proto2 syntax allows the first item in an enum (the - // default) to be non zero. So checking field->has_default_value() would - // result in missing this non zero default. See MessageWithOneBasedEnum in - // objectivec/Tests/unittest_objc.proto for a test Message to confirm this. - - // Some proto file set the default to the zero value, so make sure the value - // isn't the zero case. - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - return field->default_value_int32() != 0; - case FieldDescriptor::CPPTYPE_UINT32: - return field->default_value_uint32() != 0U; - case FieldDescriptor::CPPTYPE_INT64: - return field->default_value_int64() != 0LL; - case FieldDescriptor::CPPTYPE_UINT64: - return field->default_value_uint64() != 0ULL; - case FieldDescriptor::CPPTYPE_DOUBLE: - return field->default_value_double() != 0.0; - case FieldDescriptor::CPPTYPE_FLOAT: - return field->default_value_float() != 0.0f; - case FieldDescriptor::CPPTYPE_BOOL: - return field->default_value_bool(); - case FieldDescriptor::CPPTYPE_STRING: { - const string& default_string = field->default_value_string(); - return default_string.length() != 0; - } - case FieldDescriptor::CPPTYPE_ENUM: - return field->default_value_enum()->number() != 0; - case FieldDescriptor::CPPTYPE_MESSAGE: - return false; - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return false; -} - -string BuildFlagsString(const FlagType flag_type, - const std::vector& strings) { - if (strings.size() == 0) { - return GetZeroEnumNameForFlagType(flag_type); - } else if (strings.size() == 1) { - return strings[0]; - } - string string("(" + GetEnumNameForFlagType(flag_type) + ")("); - for (size_t i = 0; i != strings.size(); ++i) { - if (i > 0) { - string.append(" | "); - } - string.append(strings[i]); - } - string.append(")"); - return string; -} - -string BuildCommentsString(const SourceLocation& location, - bool prefer_single_line) { - const string& comments = location.leading_comments.empty() - ? location.trailing_comments - : location.leading_comments; - std::vector lines; - SplitStringAllowEmpty(comments, "\n", &lines); - while (!lines.empty() && lines.back().empty()) { - lines.pop_back(); - } - // If there are no comments, just return an empty string. - if (lines.size() == 0) { - return ""; - } - - string prefix; - string suffix; - string final_comments; - string epilogue; - - bool add_leading_space = false; - - if (prefer_single_line && lines.size() == 1) { - prefix = "/** "; - suffix = " */\n"; - } else { - prefix = "* "; - suffix = "\n"; - final_comments += "/**\n"; - epilogue = " **/\n"; - add_leading_space = true; - } - - for (int i = 0; i < lines.size(); i++) { - string line = StripPrefixString(lines[i], " "); - // HeaderDoc and appledoc use '\' and '@' for markers; escape them. - line = StringReplace(line, "\\", "\\\\", true); - line = StringReplace(line, "@", "\\@", true); - // Decouple / from * to not have inline comments inside comments. - line = StringReplace(line, "/*", "/\\*", true); - line = StringReplace(line, "*/", "*\\/", true); - line = prefix + line; - StripWhitespace(&line); - // If not a one line, need to add the first space before *, as - // StripWhitespace would have removed it. - line = (add_leading_space ? " " : "") + line; - final_comments += line + suffix; - } - final_comments += epilogue; - return final_comments; -} - -// Making these a generator option for folks that don't use CocoaPods, but do -// want to put the library in a framework is an interesting question. The -// problem is it means changing sources shipped with the library to actually -// use a different value; so it isn't as simple as a option. -const char* const ProtobufLibraryFrameworkName = "Protobuf"; - -string ProtobufFrameworkImportSymbol(const string& framework_name) { - // GPB_USE_[framework_name]_FRAMEWORK_IMPORTS - string result = string("GPB_USE_"); - result += ToUpper(framework_name); - result += "_FRAMEWORK_IMPORTS"; - return result; -} - -bool IsProtobufLibraryBundledProtoFile(const FileDescriptor* file) { - // We don't check the name prefix or proto package because some files - // (descriptor.proto), aren't shipped generated by the library, so this - // seems to be the safest way to only catch the ones shipped. - const string name = file->name(); - if (name == "google/protobuf/any.proto" || - name == "google/protobuf/api.proto" || - name == "google/protobuf/duration.proto" || - name == "google/protobuf/empty.proto" || - name == "google/protobuf/field_mask.proto" || - name == "google/protobuf/source_context.proto" || - name == "google/protobuf/struct.proto" || - name == "google/protobuf/timestamp.proto" || - name == "google/protobuf/type.proto" || - name == "google/protobuf/wrappers.proto") { - return true; - } - return false; -} - -bool ReadLine(StringPiece* input, StringPiece* line) { - for (int len = 0; len < input->size(); ++len) { - if (ascii_isnewline((*input)[len])) { - *line = StringPiece(input->data(), len); - ++len; // advance over the newline - *input = StringPiece(input->data() + len, input->size() - len); - return true; - } - } - return false; // Ran out of input with no newline. -} - -void RemoveComment(StringPiece* input) { - int offset = input->find('#'); - if (offset != StringPiece::npos) { - input->remove_suffix(input->length() - offset); - } -} - -namespace { - -class ExpectedPrefixesCollector : public LineConsumer { - public: - ExpectedPrefixesCollector(std::map* inout_package_to_prefix_map) - : prefix_map_(inout_package_to_prefix_map) {} - - virtual bool ConsumeLine(const StringPiece& line, string* out_error); - - private: - std::map* prefix_map_; -}; - -bool ExpectedPrefixesCollector::ConsumeLine( - const StringPiece& line, string* out_error) { - int offset = line.find('='); - if (offset == StringPiece::npos) { - *out_error = - string("Expected prefixes file line without equal sign: '") + - line.ToString() + "'."; - return false; - } - StringPiece package(line, 0, offset); - StringPiece prefix(line, offset + 1, line.length() - offset - 1); - StringPieceTrimWhitespace(&package); - StringPieceTrimWhitespace(&prefix); - // Don't really worry about error checking the package/prefix for - // being valid. Assume the file is validated when it is created/edited. - (*prefix_map_)[package.ToString()] = prefix.ToString(); - return true; -} - -bool LoadExpectedPackagePrefixes(const Options &generation_options, - std::map* prefix_map, - string* out_error) { - if (generation_options.expected_prefixes_path.empty()) { - return true; - } - - ExpectedPrefixesCollector collector(prefix_map); - return ParseSimpleFile( - generation_options.expected_prefixes_path, &collector, out_error); -} - -bool ValidateObjCClassPrefix( - const FileDescriptor* file, - const string& expected_prefixes_path, - const std::map& expected_package_prefixes, - string* out_error) { - const string prefix = file->options().objc_class_prefix(); - const string package = file->package(); - - // 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 warnings. - - // Check: Error - See if there was an expected prefix for the package and - // report if it doesn't match (wrong or missing). - std::map::const_iterator package_match = - expected_package_prefixes.find(package); - if (package_match != expected_package_prefixes.end()) { - // There was an entry, and... - if (package_match->second == prefix) { - // ...it matches. All good, out of here! - return true; - } else { - // ...it didn't match! - *out_error = "error: Expected 'option objc_class_prefix = \"" + - package_match->second + "\";' for package '" + package + - "' in '" + file->name() + "'"; - if (prefix.length()) { - *out_error += "; but found '" + prefix + "' instead"; - } - *out_error += "."; - return false; - } - } - - // If there was no prefix option, we're done at this point. - if (prefix.empty()) { - // No prefix, nothing left to check. - return true; - } - - // Check: Warning - Make sure the prefix is is a reasonable value according - // to Apple's rules (the checks above implicitly whitelist anything that - // doesn't meet these rules). - if (!ascii_isupper(prefix[0])) { - std::cerr << std::endl - << "protoc:0: warning: Invalid 'option objc_class_prefix = \"" - << prefix << "\";' in '" << file->name() << "';" - << " it should start with a capital letter." << std::endl; - std::cerr.flush(); - } - if (prefix.length() < 3) { - // Apple reserves 2 character prefixes for themselves. They do use some - // 3 character prefixes, but they haven't updated the rules/docs. - std::cerr << std::endl - << "protoc:0: warning: Invalid 'option objc_class_prefix = \"" - << prefix << "\";' in '" << file->name() << "';" - << " Apple recommends they should be at least 3 characters long." - << std::endl; - std::cerr.flush(); - } - - // Look for any other package that uses the same prefix. - string other_package_for_prefix; - for (std::map::const_iterator i = expected_package_prefixes.begin(); - i != expected_package_prefixes.end(); ++i) { - if (i->second == prefix) { - other_package_for_prefix = i->first; - break; - } - } - - // Check: Warning - If the file does not have a package, check whether - // the prefix declared is being used by another package or not. - if (package.empty()) { - // The file does not have a package and ... - if (other_package_for_prefix.empty()) { - // ... no other package has declared that prefix. - std::cerr << std::endl - << "protoc:0: warning: File '" << file->name() << "' has no " - << "package. Consider adding a new package to the proto and adding '" - << "new.package = " << prefix << "' to the expected prefixes file (" - << expected_prefixes_path << ")." << std::endl; - std::cerr.flush(); - } else { - // ... another package has declared the same prefix. - std::cerr << std::endl - << "protoc:0: warning: File '" << file->name() << "' has no package " - << "and package '" << other_package_for_prefix << "' already uses '" - << prefix << "' as its prefix. Consider either adding a new package " - << "to the proto, or reusing one of the packages already using this " - << "prefix in the expected prefixes file (" - << expected_prefixes_path << ")." << std::endl; - std::cerr.flush(); - } - return true; - } - - // Check: Error - Make sure the prefix wasn't expected for a different - // package (overlap is allowed, but it has to be listed as an expected - // overlap). - if (!other_package_for_prefix.empty()) { - *out_error = - "error: Found 'option objc_class_prefix = \"" + prefix + - "\";' in '" + file->name() + - "'; that prefix is already used for 'package " + - other_package_for_prefix + ";'. It can only be reused by listing " + - "it in the expected file (" + - expected_prefixes_path + ")."; - return false; // Only report first usage of the prefix. - } - - // Check: Warning - If the given package/prefix pair wasn't expected, issue a - // warning issue a warning suggesting it gets added to the file. - if (!expected_package_prefixes.empty()) { - std::cerr << std::endl - << "protoc:0: warning: Found unexpected 'option objc_class_prefix = \"" - << prefix << "\";' in '" << file->name() << "';" - << " consider adding it to the expected prefixes file (" - << expected_prefixes_path << ")." << std::endl; - std::cerr.flush(); - } - - return true; -} - -} // namespace - -bool ValidateObjCClassPrefixes(const std::vector& files, - const Options& generation_options, - string* out_error) { - // Load the expected package prefixes, if available, to validate against. - std::map expected_package_prefixes; - if (!LoadExpectedPackagePrefixes(generation_options, - &expected_package_prefixes, - out_error)) { - return false; - } - - for (int i = 0; i < files.size(); i++) { - bool is_valid = - ValidateObjCClassPrefix(files[i], - generation_options.expected_prefixes_path, - expected_package_prefixes, - out_error); - if (!is_valid) { - return false; - } - } - return true; -} - -TextFormatDecodeData::TextFormatDecodeData() { } - -TextFormatDecodeData::~TextFormatDecodeData() { } - -void TextFormatDecodeData::AddString(int32 key, - const string& input_for_decode, - const string& desired_output) { - for (std::vector::const_iterator i = entries_.begin(); - i != entries_.end(); ++i) { - if (i->first == key) { - std::cerr << "error: duplicate key (" << key - << ") making TextFormat data, input: \"" << input_for_decode - << "\", desired: \"" << desired_output << "\"." << std::endl; - std::cerr.flush(); - abort(); - } - } - - const string& data = TextFormatDecodeData::DecodeDataForString( - input_for_decode, desired_output); - entries_.push_back(DataEntry(key, data)); -} - -string TextFormatDecodeData::Data() const { - std::ostringstream data_stringstream; - - if (num_entries() > 0) { - io::OstreamOutputStream data_outputstream(&data_stringstream); - io::CodedOutputStream output_stream(&data_outputstream); - - output_stream.WriteVarint32(num_entries()); - for (std::vector::const_iterator i = entries_.begin(); - i != entries_.end(); ++i) { - output_stream.WriteVarint32(i->first); - output_stream.WriteString(i->second); - } - } - - data_stringstream.flush(); - return data_stringstream.str(); -} - -namespace { - -// Helper to build up the decode data for a string. -class DecodeDataBuilder { - public: - DecodeDataBuilder() { Reset(); } - - bool AddCharacter(const char desired, const char input); - void AddUnderscore() { - Push(); - need_underscore_ = true; - } - string Finish() { - Push(); - return decode_data_; - } - - private: - static const uint8 kAddUnderscore = 0x80; - - static const uint8 kOpAsIs = 0x00; - static const uint8 kOpFirstUpper = 0x40; - static const uint8 kOpFirstLower = 0x20; - static const uint8 kOpAllUpper = 0x60; - - static const int kMaxSegmentLen = 0x1f; - - void AddChar(const char desired) { - ++segment_len_; - is_all_upper_ &= ascii_isupper(desired); - } - - void Push() { - uint8 op = (op_ | segment_len_); - if (need_underscore_) op |= kAddUnderscore; - if (op != 0) { - decode_data_ += (char)op; - } - Reset(); - } - - bool AddFirst(const char desired, const char input) { - if (desired == input) { - op_ = kOpAsIs; - } else if (desired == ascii_toupper(input)) { - op_ = kOpFirstUpper; - } else if (desired == ascii_tolower(input)) { - op_ = kOpFirstLower; - } else { - // Can't be transformed to match. - return false; - } - AddChar(desired); - return true; - } - - void Reset() { - need_underscore_ = false; - op_ = 0; - segment_len_ = 0; - is_all_upper_ = true; - } - - bool need_underscore_; - bool is_all_upper_; - uint8 op_; - int segment_len_; - - string decode_data_; -}; - -bool DecodeDataBuilder::AddCharacter(const char desired, const char input) { - // If we've hit the max size, push to start a new segment. - if (segment_len_ == kMaxSegmentLen) { - Push(); - } - if (segment_len_ == 0) { - return AddFirst(desired, input); - } - - // Desired and input match... - if (desired == input) { - // If we aren't transforming it, or we're upper casing it and it is - // supposed to be uppercase; just add it to the segment. - if ((op_ != kOpAllUpper) || ascii_isupper(desired)) { - AddChar(desired); - return true; - } - - // Add the current segment, and start the next one. - Push(); - return AddFirst(desired, input); - } - - // If we need to uppercase, and everything so far has been uppercase, - // promote op to AllUpper. - if ((desired == ascii_toupper(input)) && is_all_upper_) { - op_ = kOpAllUpper; - AddChar(desired); - return true; - } - - // Give up, push and start a new segment. - Push(); - return AddFirst(desired, input); -} - -// If decode data can't be generated, a directive for the raw string -// is used instead. -string DirectDecodeString(const string& str) { - string result; - result += (char)'\0'; // Marker for full string. - result += str; - result += (char)'\0'; // End of string. - return result; -} - -} // namespace - -// static -string TextFormatDecodeData::DecodeDataForString(const string& input_for_decode, - const string& desired_output) { - if ((input_for_decode.size() == 0) || (desired_output.size() == 0)) { - std::cerr << "error: got empty string for making TextFormat data, input: \"" - << input_for_decode << "\", desired: \"" << desired_output << "\"." - << std::endl; - std::cerr.flush(); - abort(); - } - if ((input_for_decode.find('\0') != string::npos) || - (desired_output.find('\0') != string::npos)) { - std::cerr << "error: got a null char in a string for making TextFormat data," - << " input: \"" << CEscape(input_for_decode) << "\", desired: \"" - << CEscape(desired_output) << "\"." << std::endl; - std::cerr.flush(); - abort(); - } - - DecodeDataBuilder builder; - - // Walk the output building it from the input. - int x = 0; - for (int y = 0; y < desired_output.size(); y++) { - const char d = desired_output[y]; - if (d == '_') { - builder.AddUnderscore(); - continue; - } - - if (x >= input_for_decode.size()) { - // Out of input, no way to encode it, just return a full decode. - return DirectDecodeString(desired_output); - } - if (builder.AddCharacter(d, input_for_decode[x])) { - ++x; // Consumed one input - } else { - // Couldn't transform for the next character, just return a full decode. - return DirectDecodeString(desired_output); - } - } - - if (x != input_for_decode.size()) { - // Extra input (suffix from name sanitizing?), just return a full decode. - return DirectDecodeString(desired_output); - } - - // Add the end marker. - return builder.Finish() + (char)'\0'; -} - -namespace { - -class Parser { - public: - Parser(LineConsumer* line_consumer) - : line_consumer_(line_consumer), line_(0) {} - - // Parses a check of input, returning success/failure. - bool ParseChunk(StringPiece chunk); - - // Should be called to finish parsing (after all input has been provided via - // ParseChunk()). Returns success/failure. - bool Finish(); - - int last_line() const { return line_; } - string error_str() const { return error_str_; } - - private: - bool ParseLoop(); - - LineConsumer* line_consumer_; - int line_; - string error_str_; - StringPiece p_; - string leftover_; -}; - -bool Parser::ParseChunk(StringPiece chunk) { - if (!leftover_.empty()) { - chunk.AppendToString(&leftover_); - p_ = StringPiece(leftover_); - } else { - p_ = chunk; - } - bool result = ParseLoop(); - if (p_.empty()) { - leftover_.clear(); - } else { - leftover_ = p_.ToString(); - } - return result; -} - -bool Parser::Finish() { - if (leftover_.empty()) { - return true; - } - // Force a newline onto the end to finish parsing. - leftover_ += "\n"; - p_ = StringPiece(leftover_); - if (!ParseLoop()) { - return false; - } - return p_.empty(); // Everything used? -} - -bool Parser::ParseLoop() { - StringPiece line; - while (ReadLine(&p_, &line)) { - ++line_; - RemoveComment(&line); - StringPieceTrimWhitespace(&line); - if (line.size() == 0) { - continue; // Blank line. - } - if (!line_consumer_->ConsumeLine(line, &error_str_)) { - return false; - } - } - return true; -} - -} // namespace - -LineConsumer::LineConsumer() {} - -LineConsumer::~LineConsumer() {} - -bool ParseSimpleFile( - const string& path, LineConsumer* line_consumer, string* out_error) { - int fd; - do { - fd = posix::open(path.c_str(), O_RDONLY); - } while (fd < 0 && errno == EINTR); - if (fd < 0) { - *out_error = - string("error: Unable to open \"") + path + "\", " + strerror(errno); - return false; - } - io::FileInputStream file_stream(fd); - file_stream.SetCloseOnDelete(true); - - Parser parser(line_consumer); - const void* buf; - int buf_len; - while (file_stream.Next(&buf, &buf_len)) { - if (buf_len == 0) { - continue; - } - - if (!parser.ParseChunk(StringPiece(static_cast(buf), buf_len))) { - *out_error = - string("error: ") + path + - " Line " + SimpleItoa(parser.last_line()) + ", " + parser.error_str(); - return false; - } - } - return parser.Finish(); -} - -ImportWriter::ImportWriter( - const string& generate_for_named_framework, - const string& named_framework_to_proto_path_mappings_path, - bool include_wkt_imports) - : generate_for_named_framework_(generate_for_named_framework), - named_framework_to_proto_path_mappings_path_( - named_framework_to_proto_path_mappings_path), - include_wkt_imports_(include_wkt_imports), - need_to_parse_mapping_file_(true) { -} - -ImportWriter::~ImportWriter() {} - -void ImportWriter::AddFile(const FileDescriptor* file, - const string& header_extension) { - const string file_path(FilePath(file)); - - if (IsProtobufLibraryBundledProtoFile(file)) { - // The imports of the WKTs are only needed within the library itself, - // in other cases, they get skipped because the generated code already - // import GPBProtocolBuffers.h and hence proves them. - if (include_wkt_imports_) { - protobuf_framework_imports_.push_back( - FilePathBasename(file) + header_extension); - protobuf_non_framework_imports_.push_back(file_path + header_extension); - } - return; - } - - // Lazy parse any mappings. - if (need_to_parse_mapping_file_) { - ParseFrameworkMappings(); - } - - std::map::iterator proto_lookup = - proto_file_to_framework_name_.find(file->name()); - if (proto_lookup != proto_file_to_framework_name_.end()) { - other_framework_imports_.push_back( - proto_lookup->second + "/" + - FilePathBasename(file) + header_extension); - return; - } - - if (!generate_for_named_framework_.empty()) { - other_framework_imports_.push_back( - generate_for_named_framework_ + "/" + - FilePathBasename(file) + header_extension); - return; - } - - other_imports_.push_back(file_path + header_extension); -} - -void ImportWriter::Print(io::Printer* printer) const { - assert(protobuf_non_framework_imports_.size() == - protobuf_framework_imports_.size()); - - bool add_blank_line = false; - - if (protobuf_framework_imports_.size() > 0) { - const string framework_name(ProtobufLibraryFrameworkName); - const string cpp_symbol(ProtobufFrameworkImportSymbol(framework_name)); - - printer->Print( - "#if $cpp_symbol$\n", - "cpp_symbol", cpp_symbol); - for (std::vector::const_iterator iter = protobuf_framework_imports_.begin(); - iter != protobuf_framework_imports_.end(); ++iter) { - printer->Print( - " #import <$framework_name$/$header$>\n", - "framework_name", framework_name, - "header", *iter); - } - printer->Print( - "#else\n"); - for (std::vector::const_iterator iter = protobuf_non_framework_imports_.begin(); - iter != protobuf_non_framework_imports_.end(); ++iter) { - printer->Print( - " #import \"$header$\"\n", - "header", *iter); - } - printer->Print( - "#endif\n"); - - add_blank_line = true; - } - - if (other_framework_imports_.size() > 0) { - if (add_blank_line) { - printer->Print("\n"); - } - - for (std::vector::const_iterator iter = other_framework_imports_.begin(); - iter != other_framework_imports_.end(); ++iter) { - printer->Print( - "#import <$header$>\n", - "header", *iter); - } - - add_blank_line = true; - } - - if (other_imports_.size() > 0) { - if (add_blank_line) { - printer->Print("\n"); - } - - for (std::vector::const_iterator iter = other_imports_.begin(); - iter != other_imports_.end(); ++iter) { - printer->Print( - "#import \"$header$\"\n", - "header", *iter); - } - } -} - -void ImportWriter::ParseFrameworkMappings() { - need_to_parse_mapping_file_ = false; - if (named_framework_to_proto_path_mappings_path_.empty()) { - return; // Nothing to do. - } - - ProtoFrameworkCollector collector(&proto_file_to_framework_name_); - string parse_error; - if (!ParseSimpleFile(named_framework_to_proto_path_mappings_path_, - &collector, &parse_error)) { - std::cerr << "error parsing " << named_framework_to_proto_path_mappings_path_ - << " : " << parse_error << std::endl; - std::cerr.flush(); - } -} - -bool ImportWriter::ProtoFrameworkCollector::ConsumeLine( - const StringPiece& line, string* out_error) { - int offset = line.find(':'); - if (offset == StringPiece::npos) { - *out_error = - string("Framework/proto file mapping line without colon sign: '") + - line.ToString() + "'."; - return false; - } - StringPiece framework_name(line, 0, offset); - StringPiece proto_file_list(line, offset + 1, line.length() - offset - 1); - StringPieceTrimWhitespace(&framework_name); - - int start = 0; - while (start < proto_file_list.length()) { - offset = proto_file_list.find(',', start); - if (offset == StringPiece::npos) { - offset = proto_file_list.length(); - } - - StringPiece proto_file(proto_file_list, start, offset - start); - StringPieceTrimWhitespace(&proto_file); - if (proto_file.size() != 0) { - std::map::iterator existing_entry = - map_->find(proto_file.ToString()); - if (existing_entry != map_->end()) { - std::cerr << "warning: duplicate proto file reference, replacing framework entry for '" - << proto_file.ToString() << "' with '" << framework_name.ToString() - << "' (was '" << existing_entry->second << "')." << std::endl; - std::cerr.flush(); - } - - if (proto_file.find(' ') != StringPiece::npos) { - std::cerr << "note: framework mapping file had a proto file with a space in, hopefully that isn't a missing comma: '" - << proto_file.ToString() << "'" << std::endl; - std::cerr.flush(); - } - - (*map_)[proto_file.ToString()] = framework_name.ToString(); - } - - start = offset + 1; - } - - return true; -} - - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers.h index 8999aa595..13a105240 100644 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers.h +++ b/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers.h @@ -38,85 +38,107 @@ #include #include +#include + +#include namespace google { namespace protobuf { namespace compiler { namespace objectivec { +// Get/Set if the proto package should be used to make the default prefix for +// symbols. This will then impact most of the type naming apis below. It is done +// as a global to not break any other generator reusing the methods since they +// are exported. +bool PROTOC_EXPORT UseProtoPackageAsDefaultPrefix(); +void PROTOC_EXPORT SetUseProtoPackageAsDefaultPrefix(bool on_or_off); +// Get/Set the path to a file to load as exceptions when +// `UseProtoPackageAsDefaultPrefixUseProtoPackageAsDefaultPrefix()` is `true`. +// And empty string means there should be no exceptions loaded. +std::string PROTOC_EXPORT GetProtoPackagePrefixExceptionList(); +void PROTOC_EXPORT SetProtoPackagePrefixExceptionList( + const std::string& file_path); + // Generator options (see objectivec_generator.cc for a description of each): struct Options { Options(); - string expected_prefixes_path; - string generate_for_named_framework; - string named_framework_to_proto_path_mappings_path; + std::string expected_prefixes_path; + std::vector expected_prefixes_suppressions; + std::string generate_for_named_framework; + std::string named_framework_to_proto_path_mappings_path; + std::string runtime_import_prefix; + bool prefixes_must_be_registered; + bool require_prefixes; }; // Escape C++ trigraphs by escaping question marks to "\?". -string LIBPROTOC_EXPORT EscapeTrigraphs(const string& to_escape); - -// Strips ".proto" or ".protodevel" from the end of a filename. -string LIBPROTOC_EXPORT StripProto(const string& filename); +std::string PROTOC_EXPORT EscapeTrigraphs(const std::string& to_escape); // Remove white space from either end of a StringPiece. -void LIBPROTOC_EXPORT StringPieceTrimWhitespace(StringPiece* input); +void PROTOC_EXPORT TrimWhitespace(StringPiece* input); // Returns true if the name requires a ns_returns_not_retained attribute applied // to it. -bool LIBPROTOC_EXPORT IsRetainedName(const string& name); +bool PROTOC_EXPORT IsRetainedName(const std::string& name); // Returns true if the name starts with "init" and will need to have special // handling under ARC. -bool LIBPROTOC_EXPORT IsInitName(const string& name); +bool PROTOC_EXPORT IsInitName(const std::string& name); -// Gets the objc_class_prefix. -string LIBPROTOC_EXPORT FileClassPrefix(const FileDescriptor* file); +// Gets the objc_class_prefix or the prefix made from the proto package. +std::string PROTOC_EXPORT FileClassPrefix(const FileDescriptor* file); // Gets the path of the file we're going to generate (sans the .pb.h // extension). The path will be dependent on the objectivec package // declared in the proto package. -string LIBPROTOC_EXPORT FilePath(const FileDescriptor* file); +std::string PROTOC_EXPORT FilePath(const FileDescriptor* file); // Just like FilePath(), but without the directory part. -string LIBPROTOC_EXPORT FilePathBasename(const FileDescriptor* file); +std::string PROTOC_EXPORT FilePathBasename(const FileDescriptor* file); // Gets the name of the root class we'll generate in the file. This class // is not meant for external consumption, but instead contains helpers that // the rest of the classes need -string LIBPROTOC_EXPORT FileClassName(const FileDescriptor* file); +std::string PROTOC_EXPORT FileClassName(const FileDescriptor* file); // These return the fully-qualified class name corresponding to the given // descriptor. -string LIBPROTOC_EXPORT ClassName(const Descriptor* descriptor); -string LIBPROTOC_EXPORT ClassName(const Descriptor* descriptor, string* out_suffix_added); -string LIBPROTOC_EXPORT EnumName(const EnumDescriptor* descriptor); +std::string PROTOC_EXPORT ClassName(const Descriptor* descriptor); +std::string PROTOC_EXPORT ClassName(const Descriptor* descriptor, + std::string* out_suffix_added); +std::string PROTOC_EXPORT EnumName(const EnumDescriptor* descriptor); // Returns the fully-qualified name of the enum value corresponding to the // the descriptor. -string LIBPROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor); +std::string PROTOC_EXPORT EnumValueName(const EnumValueDescriptor* descriptor); // Returns the name of the enum value corresponding to the descriptor. -string LIBPROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor); +std::string PROTOC_EXPORT EnumValueShortName(const EnumValueDescriptor* descriptor); // Reverse what an enum does. -string LIBPROTOC_EXPORT UnCamelCaseEnumShortName(const string& name); +std::string PROTOC_EXPORT UnCamelCaseEnumShortName(const std::string& name); // Returns the name to use for the extension (used as the method off the file's // Root class). -string LIBPROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor); +std::string PROTOC_EXPORT ExtensionMethodName(const FieldDescriptor* descriptor); // Returns the transformed field name. -string LIBPROTOC_EXPORT FieldName(const FieldDescriptor* field); -string LIBPROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field); +std::string PROTOC_EXPORT FieldName(const FieldDescriptor* field); +std::string PROTOC_EXPORT FieldNameCapitalized(const FieldDescriptor* field); // Returns the transformed oneof name. -string LIBPROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor); -string LIBPROTOC_EXPORT OneofName(const OneofDescriptor* descriptor); -string LIBPROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor); +std::string PROTOC_EXPORT OneofEnumName(const OneofDescriptor* descriptor); +std::string PROTOC_EXPORT OneofName(const OneofDescriptor* descriptor); +std::string PROTOC_EXPORT OneofNameCapitalized(const OneofDescriptor* descriptor); -inline bool HasFieldPresence(const FileDescriptor* file) { - return file->syntax() != FileDescriptor::SYNTAX_PROTO3; -} +// Returns a symbol that can be used in C code to refer to an Objective C +// class without initializing the class. +std::string PROTOC_EXPORT ObjCClass(const std::string& class_name); + +// Declares an Objective C class without initializing the class so that it can +// be refrerred to by ObjCClass. +std::string PROTOC_EXPORT ObjCClassDeclaration(const std::string& class_name); inline bool HasPreservingUnknownEnumSemantics(const FileDescriptor* file) { return file->syntax() == FileDescriptor::SYNTAX_PROTO3; @@ -127,7 +149,8 @@ inline bool IsMapEntryMessage(const Descriptor* descriptor) { } // Reverse of the above. -string LIBPROTOC_EXPORT UnCamelCaseFieldName(const string& name, const FieldDescriptor* field); +std::string PROTOC_EXPORT UnCamelCaseFieldName(const std::string& name, + const FieldDescriptor* field); enum ObjectiveCType { OBJECTIVECTYPE_INT32, @@ -149,20 +172,31 @@ enum FlagType { FLAGTYPE_FIELD }; -template -string GetOptionalDeprecatedAttribute( - const TDescriptor* descriptor, - const FileDescriptor* file = NULL, - bool preSpace = true, bool postNewline = false) { +template +std::string GetOptionalDeprecatedAttribute(const TDescriptor* descriptor, + const FileDescriptor* file = NULL, + bool preSpace = true, + bool postNewline = false) { bool isDeprecated = descriptor->options().deprecated(); // The file is only passed when checking Messages & Enums, so those types // get tagged. At the moment, it doesn't seem to make sense to tag every // field or enum value with when the file is deprecated. + bool isFileLevelDeprecation = false; if (!isDeprecated && file) { - isDeprecated = file->options().deprecated(); + isFileLevelDeprecation = file->options().deprecated(); + isDeprecated = isFileLevelDeprecation; } if (isDeprecated) { - string result = "DEPRECATED_ATTRIBUTE"; + std::string message; + const FileDescriptor* sourceFile = descriptor->file(); + if (isFileLevelDeprecation) { + message = sourceFile->name() + " is deprecated."; + } else { + message = descriptor->full_name() + " is deprecated (see " + + sourceFile->name() + ")."; + } + + std::string result = std::string("GPB_DEPRECATED_MSG(\"") + message + "\")"; if (preSpace) { result.insert(0, " "); } @@ -175,119 +209,139 @@ string GetOptionalDeprecatedAttribute( } } -string LIBPROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field); +std::string PROTOC_EXPORT GetCapitalizedType(const FieldDescriptor* field); -ObjectiveCType LIBPROTOC_EXPORT GetObjectiveCType(FieldDescriptor::Type field_type); +ObjectiveCType PROTOC_EXPORT +GetObjectiveCType(FieldDescriptor::Type field_type); inline ObjectiveCType GetObjectiveCType(const FieldDescriptor* field) { return GetObjectiveCType(field->type()); } -bool LIBPROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field); -bool LIBPROTOC_EXPORT IsReferenceType(const FieldDescriptor* field); +bool PROTOC_EXPORT IsPrimitiveType(const FieldDescriptor* field); +bool PROTOC_EXPORT IsReferenceType(const FieldDescriptor* field); -string LIBPROTOC_EXPORT GPBGenericValueFieldName(const FieldDescriptor* field); -string LIBPROTOC_EXPORT DefaultValue(const FieldDescriptor* field); -bool LIBPROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field); +std::string PROTOC_EXPORT +GPBGenericValueFieldName(const FieldDescriptor* field); +std::string PROTOC_EXPORT DefaultValue(const FieldDescriptor* field); +bool PROTOC_EXPORT HasNonZeroDefaultValue(const FieldDescriptor* field); -string LIBPROTOC_EXPORT BuildFlagsString(const FlagType type, const std::vector& strings); +std::string PROTOC_EXPORT +BuildFlagsString(const FlagType type, const std::vector& strings); // Builds HeaderDoc/appledoc style comments out of the comments in the .proto // file. -string LIBPROTOC_EXPORT BuildCommentsString(const SourceLocation& location, - bool prefer_single_line); +std::string PROTOC_EXPORT BuildCommentsString(const SourceLocation& location, + bool prefer_single_line); // The name the commonly used by the library when built as a framework. // This lines up to the name used in the CocoaPod. -extern LIBPROTOC_EXPORT const char* const ProtobufLibraryFrameworkName; +extern PROTOC_EXPORT const char* const ProtobufLibraryFrameworkName; // Returns the CPP symbol name to use as the gate for framework style imports // for the given framework name to use. -string LIBPROTOC_EXPORT ProtobufFrameworkImportSymbol(const string& framework_name); +std::string PROTOC_EXPORT +ProtobufFrameworkImportSymbol(const std::string& framework_name); // Checks if the file is one of the proto's bundled with the library. -bool LIBPROTOC_EXPORT IsProtobufLibraryBundledProtoFile(const FileDescriptor* file); +bool PROTOC_EXPORT +IsProtobufLibraryBundledProtoFile(const FileDescriptor* file); // Checks the prefix for the given files and outputs any warnings as needed. If // there are flat out errors, then out_error is filled in with the first error // and the result is false. -bool LIBPROTOC_EXPORT ValidateObjCClassPrefixes(const std::vector& files, - const Options& generation_options, - string* out_error); +bool PROTOC_EXPORT ValidateObjCClassPrefixes( + const std::vector& files, + const Options& generation_options, std::string* out_error); // Generate decode data needed for ObjC's GPBDecodeTextFormatName() to transform // the input into the expected output. -class LIBPROTOC_EXPORT TextFormatDecodeData { +class PROTOC_EXPORT TextFormatDecodeData { public: TextFormatDecodeData(); ~TextFormatDecodeData(); - void AddString(int32 key, const string& input_for_decode, - const string& desired_output); - size_t num_entries() const { return entries_.size(); } - string Data() const; + TextFormatDecodeData(const TextFormatDecodeData&) = delete; + TextFormatDecodeData& operator=(const TextFormatDecodeData&) = delete; - static string DecodeDataForString(const string& input_for_decode, - const string& desired_output); + void AddString(int32_t key, const std::string& input_for_decode, + const std::string& desired_output); + size_t num_entries() const { return entries_.size(); } + std::string Data() const; + + static std::string DecodeDataForString(const std::string& input_for_decode, + const std::string& desired_output); private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextFormatDecodeData); - - typedef std::pair DataEntry; + typedef std::pair DataEntry; std::vector entries_; }; // Helper for parsing simple files. -class LIBPROTOC_EXPORT LineConsumer { +class PROTOC_EXPORT LineConsumer { public: LineConsumer(); virtual ~LineConsumer(); - virtual bool ConsumeLine(const StringPiece& line, string* out_error) = 0; + virtual bool ConsumeLine(const StringPiece& line, std::string* out_error) = 0; }; -bool LIBPROTOC_EXPORT ParseSimpleFile( - const string& path, LineConsumer* line_consumer, string* out_error); +bool PROTOC_EXPORT ParseSimpleFile(const std::string& path, + LineConsumer* line_consumer, + std::string* out_error); +bool PROTOC_EXPORT ParseSimpleStream(io::ZeroCopyInputStream& input_stream, + const std::string& stream_name, + LineConsumer* line_consumer, + std::string* out_error); // Helper class for parsing framework import mappings and generating // import statements. -class LIBPROTOC_EXPORT ImportWriter { +class PROTOC_EXPORT ImportWriter { public: - ImportWriter(const string& generate_for_named_framework, - const string& named_framework_to_proto_path_mappings_path, + ImportWriter(const std::string& generate_for_named_framework, + const std::string& named_framework_to_proto_path_mappings_path, + const std::string& runtime_import_prefix, bool include_wkt_imports); ~ImportWriter(); - void AddFile(const FileDescriptor* file, const string& header_extension); - void Print(io::Printer *printer) const; + void AddFile(const FileDescriptor* file, const std::string& header_extension); + void Print(io::Printer* printer) const; + + static void PrintRuntimeImports(io::Printer* printer, + const std::vector& header_to_import, + const std::string& runtime_import_prefix, + bool default_cpp_symbol = false); private: class ProtoFrameworkCollector : public LineConsumer { public: - ProtoFrameworkCollector(std::map* inout_proto_file_to_framework_name) + ProtoFrameworkCollector(std::map* inout_proto_file_to_framework_name) : map_(inout_proto_file_to_framework_name) {} - virtual bool ConsumeLine(const StringPiece& line, string* out_error); + virtual bool ConsumeLine(const StringPiece& line, std::string* out_error) override; private: - std::map* map_; + std::map* map_; }; void ParseFrameworkMappings(); - const string generate_for_named_framework_; - const string named_framework_to_proto_path_mappings_path_; + const std::string generate_for_named_framework_; + const std::string named_framework_to_proto_path_mappings_path_; + const std::string runtime_import_prefix_; const bool include_wkt_imports_; - std::map proto_file_to_framework_name_; + std::map proto_file_to_framework_name_; bool need_to_parse_mapping_file_; - std::vector protobuf_framework_imports_; - std::vector protobuf_non_framework_imports_; - std::vector other_framework_imports_; - std::vector other_imports_; + std::vector protobuf_imports_; + std::vector other_framework_imports_; + std::vector other_imports_; }; } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_HELPERS_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc deleted file mode 100644 index dc1cef556..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc +++ /dev/null @@ -1,257 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2014 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. - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { -namespace { - -TEST(ObjCHelper, TextFormatDecodeData_DecodeDataForString_RawStrings) { - string input_for_decode("abcdefghIJ"); - string desired_output_for_decode; - string expected; - string result; - - // Different data, can't transform. - - desired_output_for_decode = "zbcdefghIJ"; - expected = string("\0zbcdefghIJ\0", 12); - result = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output_for_decode); - EXPECT_EQ(expected, result); - - desired_output_for_decode = "abcdezghIJ"; - expected = string("\0abcdezghIJ\0", 12); - result = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output_for_decode); - EXPECT_EQ(expected, result); - - // Shortened data, can't transform. - - desired_output_for_decode = "abcdefghI"; - expected = string("\0abcdefghI\0", 11); - result = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output_for_decode); - EXPECT_EQ(expected, result); - - // Extra data, can't transform. - - desired_output_for_decode = "abcdefghIJz"; - expected = string("\0abcdefghIJz\0", 13); - result = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output_for_decode); - EXPECT_EQ(expected, result); -} - -TEST(ObjCHelper, TextFormatDecodeData_DecodeDataForString_ByteCodes) { - string input_for_decode("abcdefghIJ"); - string desired_output_for_decode; - string expected; - string result; - - desired_output_for_decode = "abcdefghIJ"; - expected = string("\x0A\x0", 2); - result = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output_for_decode); - EXPECT_EQ(expected, result); - - desired_output_for_decode = "_AbcdefghIJ"; - expected = string("\xCA\x0", 2); - result = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output_for_decode); - EXPECT_EQ(expected, result); - - desired_output_for_decode = "ABCD__EfghI_j"; - expected = string("\x64\x80\xC5\xA1\x0", 5); - result = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output_for_decode); - EXPECT_EQ(expected, result); - - // Long name so multiple decode ops are needed. - - input_for_decode = - "longFieldNameIsLooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong1000"; - desired_output_for_decode = - "long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1000"; - expected = string("\x04\xA5\xA4\xA2\xBF\x1F\x0E\x84\x0", 9); - result = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output_for_decode); - EXPECT_EQ(expected, result); -} - -// Death tests do not work on Windows as of yet. -#ifdef PROTOBUF_HAS_DEATH_TEST -TEST(ObjCHelperDeathTest, TextFormatDecodeData_DecodeDataForString_Failures) { - // Empty inputs. - - EXPECT_EXIT(TextFormatDecodeData::DecodeDataForString("", ""), - ::testing::KilledBySignal(SIGABRT), - "error: got empty string for making TextFormat data, input:"); - EXPECT_EXIT(TextFormatDecodeData::DecodeDataForString("a", ""), - ::testing::KilledBySignal(SIGABRT), - "error: got empty string for making TextFormat data, input:"); - EXPECT_EXIT(TextFormatDecodeData::DecodeDataForString("", "a"), - ::testing::KilledBySignal(SIGABRT), - "error: got empty string for making TextFormat data, input:"); - - // Null char in the string. - - string str_with_null_char("ab\0c", 4); - EXPECT_EXIT( - TextFormatDecodeData::DecodeDataForString(str_with_null_char, "def"), - ::testing::KilledBySignal(SIGABRT), - "error: got a null char in a string for making TextFormat data, input:"); - EXPECT_EXIT( - TextFormatDecodeData::DecodeDataForString("def", str_with_null_char), - ::testing::KilledBySignal(SIGABRT), - "error: got a null char in a string for making TextFormat data, input:"); -} -#endif // PROTOBUF_HAS_DEATH_TEST - -TEST(ObjCHelper, TextFormatDecodeData_RawStrings) { - TextFormatDecodeData decode_data; - - // Different data, can't transform. - decode_data.AddString(1, "abcdefghIJ", "zbcdefghIJ"); - decode_data.AddString(3, "abcdefghIJ", "abcdezghIJ"); - // Shortened data, can't transform. - decode_data.AddString(2, "abcdefghIJ", "abcdefghI"); - // Extra data, can't transform. - decode_data.AddString(4, "abcdefghIJ", "abcdefghIJz"); - - EXPECT_EQ(4, decode_data.num_entries()); - - uint8 expected_data[] = { - 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, - }; - string expected((const char*)expected_data, sizeof(expected_data)); - - EXPECT_EQ(expected, decode_data.Data()); -} - -TEST(ObjCHelper, TextFormatDecodeData_ByteCodes) { - TextFormatDecodeData decode_data; - - decode_data.AddString(1, "abcdefghIJ", "abcdefghIJ"); - decode_data.AddString(3, "abcdefghIJ", "_AbcdefghIJ"); - decode_data.AddString(2, "abcdefghIJ", "Abcd_EfghIJ"); - decode_data.AddString(4, "abcdefghIJ", "ABCD__EfghI_j"); - decode_data.AddString(1000, - "longFieldNameIsLooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong1000", - "long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1000"); - - EXPECT_EQ(5, decode_data.num_entries()); - - uint8 expected_data[] = { - 0x5, - // All as is (00 op) - 0x1, 0x0A, 0x0, - // Underscore, upper + 9 (10 op) - 0x3, 0xCA, 0x0, - // Upper + 3 (10 op), underscore, upper + 5 (10 op) - 0x2, 0x44, 0xC6, 0x0, - // All Upper for 4 (11 op), underscore, underscore, upper + 5 (10 op), - // underscore, lower + 0 (01 op) - 0x4, 0x64, 0x80, 0xC5, 0xA1, 0x0, - // 2 byte key: as is + 3 (00 op), underscore, lower + 4 (01 op), - // underscore, lower + 3 (01 op), underscore, lower + 1 (01 op), - // 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, - }; - string expected((const char*)expected_data, sizeof(expected_data)); - - EXPECT_EQ(expected, decode_data.Data()); -} - - -// Death tests do not work on Windows as of yet. -#ifdef PROTOBUF_HAS_DEATH_TEST -TEST(ObjCHelperDeathTest, TextFormatDecodeData_Failures) { - TextFormatDecodeData decode_data; - - // Empty inputs. - - EXPECT_EXIT(decode_data.AddString(1, "", ""), - ::testing::KilledBySignal(SIGABRT), - "error: got empty string for making TextFormat data, input:"); - EXPECT_EXIT(decode_data.AddString(1, "a", ""), - ::testing::KilledBySignal(SIGABRT), - "error: got empty string for making TextFormat data, input:"); - EXPECT_EXIT(decode_data.AddString(1, "", "a"), - ::testing::KilledBySignal(SIGABRT), - "error: got empty string for making TextFormat data, input:"); - - // Null char in the string. - - string str_with_null_char("ab\0c", 4); - EXPECT_EXIT( - decode_data.AddString(1, str_with_null_char, "def"), - ::testing::KilledBySignal(SIGABRT), - "error: got a null char in a string for making TextFormat data, input:"); - EXPECT_EXIT( - decode_data.AddString(1, "def", str_with_null_char), - ::testing::KilledBySignal(SIGABRT), - "error: got a null char in a string for making TextFormat data, input:"); - - // Duplicate keys - - decode_data.AddString(1, "abcdefghIJ", "abcdefghIJ"); - decode_data.AddString(3, "abcdefghIJ", "_AbcdefghIJ"); - decode_data.AddString(2, "abcdefghIJ", "Abcd_EfghIJ"); - EXPECT_EXIT(decode_data.AddString(2, "xyz", "x_yz"), - ::testing::KilledBySignal(SIGABRT), - "error: duplicate key \\(2\\) making TextFormat data, input:"); -} -#endif // PROTOBUF_HAS_DEATH_TEST - -// 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 -// use src/google/protobuf/compiler/importer* (like other tests) to support a -// virtual file system to feed in protos, once we have the Descriptor tree, the -// tests could use the helper methods for generating names and validate the -// right things are happening. - -} // namespace -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_map_field.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_map_field.cc deleted file mode 100644 index bcaf57090..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_map_field.cc +++ /dev/null @@ -1,180 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2015 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. - -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -// MapFieldGenerator uses RepeatedFieldGenerator as the parent because it -// provides a bunch of things (no has* methods, comments for contained type, -// etc.). - -namespace { - -const char* MapEntryTypeName(const FieldDescriptor* descriptor, bool isKey) { - ObjectiveCType type = GetObjectiveCType(descriptor); - switch (type) { - case OBJECTIVECTYPE_INT32: - return "Int32"; - case OBJECTIVECTYPE_UINT32: - return "UInt32"; - case OBJECTIVECTYPE_INT64: - return "Int64"; - case OBJECTIVECTYPE_UINT64: - return "UInt64"; - case OBJECTIVECTYPE_FLOAT: - return "Float"; - case OBJECTIVECTYPE_DOUBLE: - return "Double"; - case OBJECTIVECTYPE_BOOLEAN: - return "Bool"; - case OBJECTIVECTYPE_STRING: - return (isKey ? "String" : "Object"); - case OBJECTIVECTYPE_DATA: - return "Object"; - case OBJECTIVECTYPE_ENUM: - return "Enum"; - case OBJECTIVECTYPE_MESSAGE: - return "Object"; - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -} // namespace - -MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : RepeatedFieldGenerator(descriptor, options) { - const FieldDescriptor* key_descriptor = - descriptor->message_type()->FindFieldByName("key"); - const FieldDescriptor* value_descriptor = - descriptor->message_type()->FindFieldByName("value"); - value_field_generator_.reset(FieldGenerator::Make(value_descriptor, options)); - - // Pull over some variables_ from the value. - variables_["field_type"] = value_field_generator_->variable("field_type"); - variables_["default"] = value_field_generator_->variable("default"); - variables_["default_name"] = value_field_generator_->variable("default_name"); - - // Build custom field flags. - std::vector field_flags; - field_flags.push_back("GPBFieldMapKey" + GetCapitalizedType(key_descriptor)); - // Pull over the current text format custom name values that was calculated. - if (variables_["fieldflags"].find("GPBFieldTextFormatNameCustom") != - string::npos) { - field_flags.push_back("GPBFieldTextFormatNameCustom"); - } - // Pull over some info from the value's flags. - const string& value_field_flags = - value_field_generator_->variable("fieldflags"); - if (value_field_flags.find("GPBFieldHasDefaultValue") != string::npos) { - field_flags.push_back("GPBFieldHasDefaultValue"); - } - if (value_field_flags.find("GPBFieldHasEnumDescriptor") != string::npos) { - field_flags.push_back("GPBFieldHasEnumDescriptor"); - } - variables_["fieldflags"] = BuildFlagsString(FLAGTYPE_FIELD, field_flags); - - ObjectiveCType value_objc_type = GetObjectiveCType(value_descriptor); - const bool value_is_object_type = - ((value_objc_type == OBJECTIVECTYPE_STRING) || - (value_objc_type == OBJECTIVECTYPE_DATA) || - (value_objc_type == OBJECTIVECTYPE_MESSAGE)); - if ((GetObjectiveCType(key_descriptor) == OBJECTIVECTYPE_STRING) && - value_is_object_type) { - variables_["array_storage_type"] = "NSMutableDictionary"; - variables_["array_property_type"] = - "NSMutableDictionaryvariable("storage_type") + "*>"; - } else { - string class_name("GPB"); - class_name += MapEntryTypeName(key_descriptor, true); - class_name += MapEntryTypeName(value_descriptor, false); - class_name += "Dictionary"; - variables_["array_storage_type"] = class_name; - if (value_is_object_type) { - variables_["array_property_type"] = - class_name + "<" + - value_field_generator_->variable("storage_type") + "*>"; - } - } - - variables_["dataTypeSpecific_name"] = - value_field_generator_->variable("dataTypeSpecific_name"); - variables_["dataTypeSpecific_value"] = - value_field_generator_->variable("dataTypeSpecific_value"); -} - -MapFieldGenerator::~MapFieldGenerator() {} - -void MapFieldGenerator::FinishInitialization(void) { - RepeatedFieldGenerator::FinishInitialization(); - // Use the array_comment support in RepeatedFieldGenerator to output what the - // values in the map are. - const FieldDescriptor* value_descriptor = - descriptor_->message_type()->FindFieldByName("value"); - if (GetObjectiveCType(value_descriptor) == OBJECTIVECTYPE_ENUM) { - variables_["array_comment"] = - "// |" + variables_["name"] + "| values are |" + value_field_generator_->variable("storage_type") + "|\n"; - } -} - -void MapFieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls) const { - RepeatedFieldGenerator::DetermineForwardDeclarations(fwd_decls); - const FieldDescriptor* value_descriptor = - descriptor_->message_type()->FindFieldByName("value"); - if (GetObjectiveCType(value_descriptor) == OBJECTIVECTYPE_MESSAGE) { - const string& value_storage_type = - value_field_generator_->variable("storage_type"); - fwd_decls->insert("@class " + value_storage_type); - } -} - - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_map_field.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_map_field.h deleted file mode 100644 index dc7beacf2..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_map_field.h +++ /dev/null @@ -1,67 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2015 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_MAP_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MAP_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -class MapFieldGenerator : public RepeatedFieldGenerator { - friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options); - - public: - virtual void FinishInitialization(void); - - protected: - MapFieldGenerator(const FieldDescriptor* descriptor, const Options& options); - virtual ~MapFieldGenerator(); - - virtual void DetermineForwardDeclarations(std::set* fwd_decls) const; - - private: - std::unique_ptr value_field_generator_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator); -}; - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MAP_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_message.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_message.cc deleted file mode 100644 index 838888549..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_message.cc +++ /dev/null @@ -1,647 +0,0 @@ -// 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. - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { -struct FieldOrderingByNumber { - inline bool operator()(const FieldDescriptor* a, - const FieldDescriptor* b) const { - return a->number() < b->number(); - } -}; - -int OrderGroupForFieldDescriptor(const FieldDescriptor* descriptor) { - // The first item in the object structure is our uint32[] for has bits. - // We then want to order things to make the instances as small as - // possible. So we follow the has bits with: - // 1. Anything always 4 bytes - float, *32, enums - // 2. Anything that is always a pointer (they will be 8 bytes on 64 bit - // builds and 4 bytes on 32bit builds. - // 3. Anything always 8 bytes - double, *64 - // - // NOTE: Bools aren't listed, they were stored in the has bits. - // - // Why? Using 64bit builds as an example, this means worse case, we have - // enough bools that we overflow 1 byte from 4 byte alignment, so 3 bytes - // are wasted before the 4 byte values. Then if we have an odd number of - // those 4 byte values, the 8 byte values will be pushed down by 32bits to - // keep them aligned. But the structure will end 8 byte aligned, so no - // waste on the end. If you did the reverse order, you could waste 4 bytes - // before the first 8 byte value (after the has array), then a single - // bool on the end would need 7 bytes of padding to make the overall - // structure 8 byte aligned; so 11 bytes, wasted total. - - // Anything repeated is a GPB*Array/NSArray, so pointer. - if (descriptor->is_repeated()) { - return 3; - } - - switch (descriptor->type()) { - // All always 8 bytes. - case FieldDescriptor::TYPE_DOUBLE: - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_SFIXED64: - case FieldDescriptor::TYPE_FIXED64: - return 4; - - // Pointers (string and bytes are NSString and NSData); 8 or 4 bytes - // depending on the build architecture. - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_BYTES: - return 3; - - // All always 4 bytes (enums are int32s). - case FieldDescriptor::TYPE_FLOAT: - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_SFIXED32: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_ENUM: - return 2; - - // 0 bytes. Stored in the has bits. - case FieldDescriptor::TYPE_BOOL: - return 99; // End of the list (doesn't really matter). - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return 0; -} - -struct FieldOrderingByStorageSize { - inline bool operator()(const FieldDescriptor* a, - const FieldDescriptor* b) const { - // Order by grouping. - const int order_group_a = OrderGroupForFieldDescriptor(a); - const int order_group_b = OrderGroupForFieldDescriptor(b); - if (order_group_a != order_group_b) { - return order_group_a < order_group_b; - } - // Within the group, order by field number (provides stable ordering). - return a->number() < b->number(); - } -}; - -struct ExtensionRangeOrdering { - bool operator()(const Descriptor::ExtensionRange* a, - const Descriptor::ExtensionRange* b) const { - return a->start < b->start; - } -}; - -// Sort the fields of the given Descriptor by number into a new[]'d array -// and return it. -const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { - const FieldDescriptor** fields = - new const FieldDescriptor* [descriptor->field_count()]; - for (int i = 0; i < descriptor->field_count(); i++) { - fields[i] = descriptor->field(i); - } - std::sort(fields, fields + descriptor->field_count(), FieldOrderingByNumber()); - return fields; -} - -// Sort the fields of the given Descriptor by storage size into a new[]'d -// array and return it. -const FieldDescriptor** SortFieldsByStorageSize(const Descriptor* descriptor) { - const FieldDescriptor** fields = - new const FieldDescriptor* [descriptor->field_count()]; - for (int i = 0; i < descriptor->field_count(); i++) { - fields[i] = descriptor->field(i); - } - std::sort(fields, fields + descriptor->field_count(), - FieldOrderingByStorageSize()); - return fields; -} -} // namespace - -MessageGenerator::MessageGenerator(const string& root_classname, - const Descriptor* descriptor, - const Options& options) - : root_classname_(root_classname), - descriptor_(descriptor), - field_generators_(descriptor, options), - class_name_(ClassName(descriptor_)), - deprecated_attribute_( - GetOptionalDeprecatedAttribute(descriptor, descriptor->file(), false, true)) { - - for (int i = 0; i < descriptor_->extension_count(); i++) { - extension_generators_.push_back( - new ExtensionGenerator(class_name_, descriptor_->extension(i))); - } - - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - OneofGenerator* generator = new OneofGenerator(descriptor_->oneof_decl(i)); - oneof_generators_.push_back(generator); - } - - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - EnumGenerator* generator = new EnumGenerator(descriptor_->enum_type(i)); - enum_generators_.push_back(generator); - } - - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - MessageGenerator* generator = - new MessageGenerator(root_classname_, - descriptor_->nested_type(i), - options); - nested_message_generators_.push_back(generator); - } -} - -MessageGenerator::~MessageGenerator() { - STLDeleteContainerPointers(extension_generators_.begin(), - extension_generators_.end()); - STLDeleteContainerPointers(enum_generators_.begin(), enum_generators_.end()); - STLDeleteContainerPointers(nested_message_generators_.begin(), - nested_message_generators_.end()); - STLDeleteContainerPointers(oneof_generators_.begin(), - oneof_generators_.end()); -} - -void MessageGenerator::GenerateStaticVariablesInitialization( - io::Printer* printer) { - for (std::vector::iterator iter = - extension_generators_.begin(); - iter != extension_generators_.end(); ++iter) { - (*iter)->GenerateStaticVariablesInitialization(printer); - } - - for (std::vector::iterator iter = - nested_message_generators_.begin(); - iter != nested_message_generators_.end(); ++iter) { - (*iter)->GenerateStaticVariablesInitialization(printer); - } -} - -void MessageGenerator::DetermineForwardDeclarations(std::set* fwd_decls) { - if (!IsMapEntryMessage(descriptor_)) { - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* fieldDescriptor = descriptor_->field(i); - field_generators_.get(fieldDescriptor) - .DetermineForwardDeclarations(fwd_decls); - } - } - - for (std::vector::iterator iter = - nested_message_generators_.begin(); - iter != nested_message_generators_.end(); ++iter) { - (*iter)->DetermineForwardDeclarations(fwd_decls); - } -} - -bool MessageGenerator::IncludesOneOfDefinition() const { - if (!oneof_generators_.empty()) { - return true; - } - - for (std::vector::const_iterator iter = - nested_message_generators_.begin(); - iter != nested_message_generators_.end(); ++iter) { - if ((*iter)->IncludesOneOfDefinition()) { - return true; - } - } - - return false; -} - -void MessageGenerator::GenerateEnumHeader(io::Printer* printer) { - for (std::vector::iterator iter = enum_generators_.begin(); - iter != enum_generators_.end(); ++iter) { - (*iter)->GenerateHeader(printer); - } - - for (std::vector::iterator iter = - nested_message_generators_.begin(); - iter != nested_message_generators_.end(); ++iter) { - (*iter)->GenerateEnumHeader(printer); - } -} - -void MessageGenerator::GenerateExtensionRegistrationSource( - io::Printer* printer) { - for (std::vector::iterator iter = - extension_generators_.begin(); - iter != extension_generators_.end(); ++iter) { - (*iter)->GenerateRegistrationSource(printer); - } - - for (std::vector::iterator iter = - nested_message_generators_.begin(); - iter != nested_message_generators_.end(); ++iter) { - (*iter)->GenerateExtensionRegistrationSource(printer); - } -} - -void MessageGenerator::GenerateMessageHeader(io::Printer* printer) { - // This a a map entry message, just recurse and do nothing directly. - if (IsMapEntryMessage(descriptor_)) { - for (std::vector::iterator iter = - nested_message_generators_.begin(); - iter != nested_message_generators_.end(); ++iter) { - (*iter)->GenerateMessageHeader(printer); - } - return; - } - - printer->Print( - "#pragma mark - $classname$\n" - "\n", - "classname", class_name_); - - if (descriptor_->field_count()) { - std::unique_ptr sorted_fields( - SortFieldsByNumber(descriptor_)); - - printer->Print("typedef GPB_ENUM($classname$_FieldNumber) {\n", - "classname", class_name_); - printer->Indent(); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(sorted_fields[i]) - .GenerateFieldNumberConstant(printer); - } - - printer->Outdent(); - printer->Print("};\n\n"); - } - - for (std::vector::iterator iter = oneof_generators_.begin(); - iter != oneof_generators_.end(); ++iter) { - (*iter)->GenerateCaseEnum(printer); - } - - string message_comments; - SourceLocation location; - if (descriptor_->GetSourceLocation(&location)) { - message_comments = BuildCommentsString(location, false); - } else { - message_comments = ""; - } - - printer->Print( - "$comments$$deprecated_attribute$@interface $classname$ : GPBMessage\n\n", - "classname", class_name_, - "deprecated_attribute", deprecated_attribute_, - "comments", message_comments); - - std::vector seen_oneofs(descriptor_->oneof_decl_count(), 0); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->containing_oneof() != NULL) { - const int oneof_index = field->containing_oneof()->index(); - if (!seen_oneofs[oneof_index]) { - seen_oneofs[oneof_index] = 1; - oneof_generators_[oneof_index]->GeneratePublicCasePropertyDeclaration( - printer); - } - } - field_generators_.get(field).GeneratePropertyDeclaration(printer); - } - - printer->Print("@end\n\n"); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)) - .GenerateCFunctionDeclarations(printer); - } - - if (!oneof_generators_.empty()) { - for (std::vector::iterator iter = oneof_generators_.begin(); - iter != oneof_generators_.end(); ++iter) { - (*iter)->GenerateClearFunctionDeclaration(printer); - } - printer->Print("\n"); - } - - if (descriptor_->extension_count() > 0) { - printer->Print("@interface $classname$ (DynamicMethods)\n\n", - "classname", class_name_); - for (std::vector::iterator iter = - extension_generators_.begin(); - iter != extension_generators_.end(); ++iter) { - (*iter)->GenerateMembersHeader(printer); - } - printer->Print("@end\n\n"); - } - - for (std::vector::iterator iter = - nested_message_generators_.begin(); - iter != nested_message_generators_.end(); ++iter) { - (*iter)->GenerateMessageHeader(printer); - } -} - -void MessageGenerator::GenerateSource(io::Printer* printer) { - if (!IsMapEntryMessage(descriptor_)) { - printer->Print( - "#pragma mark - $classname$\n" - "\n", - "classname", class_name_); - - if (!deprecated_attribute_.empty()) { - // No warnings when compiling the impl of this deprecated class. - printer->Print( - "#pragma clang diagnostic push\n" - "#pragma clang diagnostic ignored \"-Wdeprecated-implementations\"\n" - "\n"); - } - - printer->Print("@implementation $classname$\n\n", - "classname", class_name_); - - for (std::vector::iterator iter = oneof_generators_.begin(); - iter != oneof_generators_.end(); ++iter) { - (*iter)->GeneratePropertyImplementation(printer); - } - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)) - .GeneratePropertyImplementation(printer); - } - - std::unique_ptr sorted_fields( - SortFieldsByNumber(descriptor_)); - std::unique_ptr size_order_fields( - SortFieldsByStorageSize(descriptor_)); - - std::vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); - } - - std::sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); - - // Assign has bits: - // 1. FieldGeneratorMap::CalculateHasBits() loops through the fields seeing - // who needs has bits and assigning them. - // 2. FieldGenerator::SetOneofIndexBase() overrides has_bit with a negative - // index that groups all the elements in the oneof. - size_t num_has_bits = field_generators_.CalculateHasBits(); - size_t sizeof_has_storage = (num_has_bits + 31) / 32; - if (sizeof_has_storage == 0) { - // In the case where no field needs has bits, don't let the _has_storage_ - // end up as zero length (zero length arrays are sort of a grey area - // since it has to be at the start of the struct). This also ensures a - // field with only oneofs keeps the required negative indices they need. - sizeof_has_storage = 1; - } - // Tell all the fields the oneof base. - for (std::vector::iterator iter = oneof_generators_.begin(); - iter != oneof_generators_.end(); ++iter) { - (*iter)->SetOneofIndexBase(sizeof_has_storage); - } - field_generators_.SetOneofIndexBase(sizeof_has_storage); - // sizeof_has_storage needs enough bits for the single fields that aren't in - // any oneof, and then one int32 for each oneof (to store the field number). - sizeof_has_storage += descriptor_->oneof_decl_count(); - - printer->Print( - "\n" - "typedef struct $classname$__storage_ {\n" - " uint32_t _has_storage_[$sizeof_has_storage$];\n", - "classname", class_name_, - "sizeof_has_storage", SimpleItoa(sizeof_has_storage)); - printer->Indent(); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(size_order_fields[i]) - .GenerateFieldStorageDeclaration(printer); - } - printer->Outdent(); - - printer->Print("} $classname$__storage_;\n\n", "classname", class_name_); - - - printer->Print( - "// This method is threadsafe because it is initially called\n" - "// in +initialize for each subclass.\n" - "+ (GPBDescriptor *)descriptor {\n" - " static GPBDescriptor *descriptor = nil;\n" - " if (!descriptor) {\n"); - - TextFormatDecodeData text_format_decode_data; - bool has_fields = descriptor_->field_count() > 0; - bool need_defaults = field_generators_.DoesAnyFieldHaveNonZeroDefault(); - string field_description_type; - if (need_defaults) { - field_description_type = "GPBMessageFieldDescriptionWithDefault"; - } else { - field_description_type = "GPBMessageFieldDescription"; - } - if (has_fields) { - printer->Print( - " static $field_description_type$ fields[] = {\n", - "field_description_type", field_description_type); - printer->Indent(); - printer->Indent(); - printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); ++i) { - const FieldGenerator& field_generator = - field_generators_.get(sorted_fields[i]); - field_generator.GenerateFieldDescription(printer, need_defaults); - if (field_generator.needs_textformat_name_support()) { - text_format_decode_data.AddString(sorted_fields[i]->number(), - field_generator.generated_objc_name(), - field_generator.raw_field_name()); - } - } - printer->Outdent(); - printer->Outdent(); - printer->Outdent(); - printer->Print( - " };\n"); - } - - std::map vars; - vars["classname"] = class_name_; - vars["rootclassname"] = root_classname_; - vars["fields"] = has_fields ? "fields" : "NULL"; - if (has_fields) { - vars["fields_count"] = - "(uint32_t)(sizeof(fields) / sizeof(" + field_description_type + "))"; - } else { - vars["fields_count"] = "0"; - } - - std::vector init_flags; - if (need_defaults) { - init_flags.push_back("GPBDescriptorInitializationFlag_FieldsWithDefault"); - } - if (descriptor_->options().message_set_wire_format()) { - init_flags.push_back("GPBDescriptorInitializationFlag_WireFormat"); - } - vars["init_flags"] = BuildFlagsString(FLAGTYPE_DESCRIPTOR_INITIALIZATION, - init_flags); - - printer->Print( - vars, - " GPBDescriptor *localDescriptor =\n" - " [GPBDescriptor allocDescriptorForClass:[$classname$ class]\n" - " rootClass:[$rootclassname$ class]\n" - " file:$rootclassname$_FileDescriptor()\n" - " fields:$fields$\n" - " fieldCount:$fields_count$\n" - " storageSize:sizeof($classname$__storage_)\n" - " flags:$init_flags$];\n"); - if (oneof_generators_.size() != 0) { - printer->Print( - " static const char *oneofs[] = {\n"); - for (std::vector::iterator iter = oneof_generators_.begin(); - iter != oneof_generators_.end(); ++iter) { - printer->Print( - " \"$name$\",\n", - "name", (*iter)->DescriptorName()); - } - printer->Print( - " };\n" - " [localDescriptor setupOneofs:oneofs\n" - " count:(uint32_t)(sizeof(oneofs) / sizeof(char*))\n" - " firstHasIndex:$first_has_index$];\n", - "first_has_index", oneof_generators_[0]->HasIndexAsString()); - } - if (text_format_decode_data.num_entries() != 0) { - const string text_format_data_str(text_format_decode_data.Data()); - printer->Print( - "#if !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS\n" - " static const char *extraTextFormatInfo ="); - static const int kBytesPerLine = 40; // allow for escaping - for (int i = 0; i < text_format_data_str.size(); i += kBytesPerLine) { - printer->Print( - "\n \"$data$\"", - "data", EscapeTrigraphs( - CEscape(text_format_data_str.substr(i, kBytesPerLine)))); - } - printer->Print( - ";\n" - " [localDescriptor setupExtraTextInfo:extraTextFormatInfo];\n" - "#endif // !GPBOBJC_SKIP_MESSAGE_TEXTFORMAT_EXTRAS\n"); - } - if (sorted_extensions.size() != 0) { - printer->Print( - " static const GPBExtensionRange ranges[] = {\n"); - for (int i = 0; i < sorted_extensions.size(); i++) { - printer->Print(" { .start = $start$, .end = $end$ },\n", - "start", SimpleItoa(sorted_extensions[i]->start), - "end", SimpleItoa(sorted_extensions[i]->end)); - } - printer->Print( - " };\n" - " [localDescriptor setupExtensionRanges:ranges\n" - " count:(uint32_t)(sizeof(ranges) / sizeof(GPBExtensionRange))];\n"); - } - if (descriptor_->containing_type() != NULL) { - string parent_class_name = ClassName(descriptor_->containing_type()); - printer->Print( - " [localDescriptor setupContainingMessageClassName:GPBStringifySymbol($parent_name$)];\n", - "parent_name", parent_class_name); - } - string suffix_added; - ClassName(descriptor_, &suffix_added); - if (suffix_added.size() > 0) { - printer->Print( - " [localDescriptor setupMessageClassNameSuffix:@\"$suffix$\"];\n", - "suffix", suffix_added); - } - printer->Print( - " NSAssert(descriptor == nil, @\"Startup recursed!\");\n" - " descriptor = localDescriptor;\n" - " }\n" - " return descriptor;\n" - "}\n\n" - "@end\n\n"); - - if (!deprecated_attribute_.empty()) { - printer->Print( - "#pragma clang diagnostic pop\n" - "\n"); - } - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)) - .GenerateCFunctionImplementations(printer); - } - - for (std::vector::iterator iter = oneof_generators_.begin(); - iter != oneof_generators_.end(); ++iter) { - (*iter)->GenerateClearFunctionImplementation(printer); - } - } - - for (std::vector::iterator iter = enum_generators_.begin(); - iter != enum_generators_.end(); ++iter) { - (*iter)->GenerateSource(printer); - } - - for (std::vector::iterator iter = - nested_message_generators_.begin(); - iter != nested_message_generators_.end(); ++iter) { - (*iter)->GenerateSource(printer); - } -} - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_message.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_message.h deleted file mode 100644 index 2de03f12f..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_message.h +++ /dev/null @@ -1,100 +0,0 @@ -// 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_MESSAGE_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MESSAGE_H__ - -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -namespace io { -class Printer; // printer.h -} // namespace io - -namespace compiler { -namespace objectivec { - -class ExtensionGenerator; -class EnumGenerator; - -class MessageGenerator { - public: - MessageGenerator(const string& root_classname, - const Descriptor* descriptor, - const Options& options); - ~MessageGenerator(); - - void GenerateStaticVariablesInitialization(io::Printer* printer); - void GenerateEnumHeader(io::Printer* printer); - void GenerateMessageHeader(io::Printer* printer); - void GenerateSource(io::Printer* printer); - void GenerateExtensionRegistrationSource(io::Printer* printer); - void DetermineForwardDeclarations(std::set* fwd_decls); - - // Checks if the message or a nested message includes a oneof definition. - bool IncludesOneOfDefinition() const; - - private: - void GenerateParseFromMethodsHeader(io::Printer* printer); - - void GenerateSerializeOneFieldSource(io::Printer* printer, - const FieldDescriptor* field); - void GenerateSerializeOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range); - - void GenerateMessageDescriptionSource(io::Printer* printer); - void GenerateDescriptionOneFieldSource(io::Printer* printer, - const FieldDescriptor* field); - - const string root_classname_; - const Descriptor* descriptor_; - FieldGeneratorMap field_generators_; - const string class_name_; - const string deprecated_attribute_; - std::vector extension_generators_; - std::vector enum_generators_; - std::vector nested_message_generators_; - std::vector oneof_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); -}; -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MESSAGE_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_message_field.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_message_field.cc deleted file mode 100644 index 699d25b31..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_message_field.cc +++ /dev/null @@ -1,108 +0,0 @@ -// 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. - -#include -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -namespace { - -void SetMessageVariables(const FieldDescriptor* descriptor, - std::map* variables) { - const string& message_type = ClassName(descriptor->message_type()); - (*variables)["type"] = message_type; - (*variables)["containing_class"] = ClassName(descriptor->containing_type()); - (*variables)["storage_type"] = message_type; - (*variables)["group_or_message"] = - (descriptor->type() == FieldDescriptor::TYPE_GROUP) ? "Group" : "Message"; - - (*variables)["dataTypeSpecific_value"] = "GPBStringifySymbol(" + message_type + ")"; -} - -} // namespace - -MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options) - : ObjCObjFieldGenerator(descriptor, options) { - SetMessageVariables(descriptor, &variables_); -} - -MessageFieldGenerator::~MessageFieldGenerator() {} - -void MessageFieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls) const { - ObjCObjFieldGenerator::DetermineForwardDeclarations(fwd_decls); - // Class name is already in "storage_type". - fwd_decls->insert("@class " + variable("storage_type")); -} - -bool MessageFieldGenerator::WantsHasProperty(void) const { - if (descriptor_->containing_oneof() != NULL) { - // If in a oneof, it uses the oneofcase instead of a has bit. - return false; - } - // In both proto2 & proto3, message fields have a has* property to tell - // when it is a non default value. - return true; -} - -RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : RepeatedFieldGenerator(descriptor, options) { - SetMessageVariables(descriptor, &variables_); - variables_["array_storage_type"] = "NSMutableArray"; - variables_["array_property_type"] = - "NSMutableArray<" + variables_["storage_type"] + "*>"; -} - -RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() {} - -void RepeatedMessageFieldGenerator::DetermineForwardDeclarations( - std::set* fwd_decls) const { - RepeatedFieldGenerator::DetermineForwardDeclarations(fwd_decls); - // Class name is already in "storage_type". - fwd_decls->insert("@class " + variable("storage_type")); -} - - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_message_field.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_message_field.h deleted file mode 100644 index 50f4b6d4a..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_message_field.h +++ /dev/null @@ -1,81 +0,0 @@ -// 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_MESSAGE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MESSAGE_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -class MessageFieldGenerator : public ObjCObjFieldGenerator { - friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options); - - protected: - MessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - virtual ~MessageFieldGenerator(); - virtual bool WantsHasProperty(void) const; - - public: - virtual void DetermineForwardDeclarations(std::set* fwd_decls) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); -}; - -class RepeatedMessageFieldGenerator : public RepeatedFieldGenerator { - friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options); - - protected: - RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - virtual ~RepeatedMessageFieldGenerator(); - - public: - virtual void DetermineForwardDeclarations(std::set* fwd_decls) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); -}; - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_MESSAGE_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_oneof.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_oneof.cc deleted file mode 100644 index 5531ae249..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_oneof.cc +++ /dev/null @@ -1,140 +0,0 @@ -// 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. - -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -OneofGenerator::OneofGenerator(const OneofDescriptor* descriptor) - : descriptor_(descriptor) { - variables_["enum_name"] = OneofEnumName(descriptor_); - variables_["name"] = OneofName(descriptor_); - variables_["capitalized_name"] = OneofNameCapitalized(descriptor_); - variables_["raw_index"] = SimpleItoa(descriptor_->index()); - const Descriptor* msg_descriptor = descriptor_->containing_type(); - variables_["owning_message_class"] = ClassName(msg_descriptor); - - string comments; - SourceLocation location; - if (descriptor_->GetSourceLocation(&location)) { - comments = BuildCommentsString(location, true); - } else { - comments = ""; - } - variables_["comments"] = comments; -} - -OneofGenerator::~OneofGenerator() {} - -void OneofGenerator::SetOneofIndexBase(int index_base) { - int index = descriptor_->index() + index_base; - // Flip the sign to mark it as a oneof. - variables_["index"] = SimpleItoa(-index); -} - -void OneofGenerator::GenerateCaseEnum(io::Printer* printer) { - printer->Print( - variables_, - "typedef GPB_ENUM($enum_name$) {\n"); - printer->Indent(); - printer->Print( - variables_, - "$enum_name$_GPBUnsetOneOfCase = 0,\n"); - string enum_name = variables_["enum_name"]; - for (int j = 0; j < descriptor_->field_count(); j++) { - const FieldDescriptor* field = descriptor_->field(j); - string field_name = FieldNameCapitalized(field); - printer->Print( - "$enum_name$_$field_name$ = $field_number$,\n", - "enum_name", enum_name, - "field_name", field_name, - "field_number", SimpleItoa(field->number())); - } - printer->Outdent(); - printer->Print( - "};\n" - "\n"); -} - -void OneofGenerator::GeneratePublicCasePropertyDeclaration( - io::Printer* printer) { - printer->Print( - variables_, - "$comments$" - "@property(nonatomic, readonly) $enum_name$ $name$OneOfCase;\n" - "\n"); -} - -void OneofGenerator::GenerateClearFunctionDeclaration(io::Printer* printer) { - printer->Print( - variables_, - "/**\n" - " * Clears whatever value was set for the oneof '$name$'.\n" - " **/\n" - "void $owning_message_class$_Clear$capitalized_name$OneOfCase($owning_message_class$ *message);\n"); -} - -void OneofGenerator::GeneratePropertyImplementation(io::Printer* printer) { - printer->Print( - variables_, - "@dynamic $name$OneOfCase;\n"); -} - -void OneofGenerator::GenerateClearFunctionImplementation(io::Printer* printer) { - printer->Print( - variables_, - "void $owning_message_class$_Clear$capitalized_name$OneOfCase($owning_message_class$ *message) {\n" - " GPBDescriptor *descriptor = [message descriptor];\n" - " GPBOneofDescriptor *oneof = [descriptor.oneofs objectAtIndex:$raw_index$];\n" - " GPBMaybeClearOneof(message, oneof, $index$, 0);\n" - "}\n"); -} - -string OneofGenerator::DescriptorName(void) const { - return variables_.find("name")->second; -} - -string OneofGenerator::HasIndexAsString(void) const { - return variables_.find("index")->second; -} - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_oneof.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_oneof.h deleted file mode 100644 index ff353a6c6..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_oneof.h +++ /dev/null @@ -1,79 +0,0 @@ -// 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_ONEOF_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ONEOF_H__ - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { -class Printer; // printer.h -} -} - -namespace protobuf { -namespace compiler { -namespace objectivec { - -class OneofGenerator { - public: - explicit OneofGenerator(const OneofDescriptor* descriptor); - ~OneofGenerator(); - - void SetOneofIndexBase(int index_base); - - void GenerateCaseEnum(io::Printer* printer); - - void GeneratePublicCasePropertyDeclaration(io::Printer* printer); - void GenerateClearFunctionDeclaration(io::Printer* printer); - - void GeneratePropertyImplementation(io::Printer* printer); - void GenerateClearFunctionImplementation(io::Printer* printer); - - string DescriptorName(void) const; - string HasIndexAsString(void) const; - - private: - const OneofDescriptor* descriptor_; - std::map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OneofGenerator); -}; - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_ONEOF_H__ diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc b/windows/include/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc deleted file mode 100644 index aa8ac3243..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc +++ /dev/null @@ -1,192 +0,0 @@ -// 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. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -using internal::WireFormat; -using internal::WireFormatLite; - -namespace { - -const char* PrimitiveTypeName(const FieldDescriptor* descriptor) { - ObjectiveCType type = GetObjectiveCType(descriptor); - switch (type) { - case OBJECTIVECTYPE_INT32: - return "int32_t"; - case OBJECTIVECTYPE_UINT32: - return "uint32_t"; - case OBJECTIVECTYPE_INT64: - return "int64_t"; - case OBJECTIVECTYPE_UINT64: - return "uint64_t"; - case OBJECTIVECTYPE_FLOAT: - return "float"; - case OBJECTIVECTYPE_DOUBLE: - return "double"; - case OBJECTIVECTYPE_BOOLEAN: - return "BOOL"; - case OBJECTIVECTYPE_STRING: - return "NSString"; - case OBJECTIVECTYPE_DATA: - return "NSData"; - case OBJECTIVECTYPE_ENUM: - return "int32_t"; - case OBJECTIVECTYPE_MESSAGE: - return NULL; // Messages go through objectivec_message_field.cc|h. - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -const char* PrimitiveArrayTypeName(const FieldDescriptor* descriptor) { - ObjectiveCType type = GetObjectiveCType(descriptor); - switch (type) { - case OBJECTIVECTYPE_INT32: - return "Int32"; - case OBJECTIVECTYPE_UINT32: - return "UInt32"; - case OBJECTIVECTYPE_INT64: - return "Int64"; - case OBJECTIVECTYPE_UINT64: - return "UInt64"; - case OBJECTIVECTYPE_FLOAT: - return "Float"; - case OBJECTIVECTYPE_DOUBLE: - return "Double"; - case OBJECTIVECTYPE_BOOLEAN: - return "Bool"; - case OBJECTIVECTYPE_STRING: - return ""; // Want NSArray - case OBJECTIVECTYPE_DATA: - return ""; // Want NSArray - case OBJECTIVECTYPE_ENUM: - return "Enum"; - case OBJECTIVECTYPE_MESSAGE: - // Want NSArray (but goes through objectivec_message_field.cc|h). - return ""; - } - - // Some compilers report reaching end of function even though all cases of - // the enum are handed in the switch. - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; -} - -void SetPrimitiveVariables(const FieldDescriptor* descriptor, - std::map* variables) { - std::string primitive_name = PrimitiveTypeName(descriptor); - (*variables)["type"] = primitive_name; - (*variables)["storage_type"] = primitive_name; -} - -} // namespace - -PrimitiveFieldGenerator::PrimitiveFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : SingleFieldGenerator(descriptor, options) { - SetPrimitiveVariables(descriptor, &variables_); -} - -PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {} - -void PrimitiveFieldGenerator::GenerateFieldStorageDeclaration( - io::Printer* printer) const { - if (GetObjectiveCType(descriptor_) == OBJECTIVECTYPE_BOOLEAN) { - // Nothing, BOOLs are stored in the has bits. - } else { - SingleFieldGenerator::GenerateFieldStorageDeclaration(printer); - } -} - -int PrimitiveFieldGenerator::ExtraRuntimeHasBitsNeeded(void) const { - if (GetObjectiveCType(descriptor_) == OBJECTIVECTYPE_BOOLEAN) { - // Reserve a bit for the storage of the boolean. - return 1; - } - return 0; -} - -void PrimitiveFieldGenerator::SetExtraRuntimeHasBitsBase(int has_base) { - if (GetObjectiveCType(descriptor_) == OBJECTIVECTYPE_BOOLEAN) { - // Set into the offset the has bit to use for the actual value. - variables_["storage_offset_value"] = SimpleItoa(has_base); - variables_["storage_offset_comment"] = - " // Stored in _has_storage_ to save space."; - } -} - -PrimitiveObjFieldGenerator::PrimitiveObjFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : ObjCObjFieldGenerator(descriptor, options) { - SetPrimitiveVariables(descriptor, &variables_); - variables_["property_storage_attribute"] = "copy"; -} - -PrimitiveObjFieldGenerator::~PrimitiveObjFieldGenerator() {} - -RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( - const FieldDescriptor* descriptor, const Options& options) - : RepeatedFieldGenerator(descriptor, options) { - SetPrimitiveVariables(descriptor, &variables_); - - string base_name = PrimitiveArrayTypeName(descriptor); - if (base_name.length()) { - variables_["array_storage_type"] = "GPB" + base_name + "Array"; - } else { - variables_["array_storage_type"] = "NSMutableArray"; - variables_["array_property_type"] = - "NSMutableArray<" + variables_["storage_type"] + "*>"; - } -} - -RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {} - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/objectivec/objectivec_primitive_field.h b/windows/include/google/protobuf/compiler/objectivec/objectivec_primitive_field.h deleted file mode 100644 index 69bb1fddc..000000000 --- a/windows/include/google/protobuf/compiler/objectivec/objectivec_primitive_field.h +++ /dev/null @@ -1,92 +0,0 @@ -// 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_PRIMITIVE_FIELD_H__ -#define GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_PRIMITIVE_FIELD_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace objectivec { - -class PrimitiveFieldGenerator : public SingleFieldGenerator { - friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options); - - protected: - PrimitiveFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - virtual ~PrimitiveFieldGenerator(); - - virtual void GenerateFieldStorageDeclaration(io::Printer* printer) const; - - virtual int ExtraRuntimeHasBitsNeeded(void) const; - virtual void SetExtraRuntimeHasBitsBase(int index_base); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); -}; - -class PrimitiveObjFieldGenerator : public ObjCObjFieldGenerator { - friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options); - - protected: - PrimitiveObjFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - virtual ~PrimitiveObjFieldGenerator(); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveObjFieldGenerator); -}; - -class RepeatedPrimitiveFieldGenerator : public RepeatedFieldGenerator { - friend FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, - const Options& options); - - protected: - RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor, - const Options& options); - virtual ~RepeatedPrimitiveFieldGenerator(); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); -}; - -} // namespace objectivec -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_OBJECTIVEC_PRIMITIVE_FIELD_H__ diff --git a/windows/include/google/protobuf/compiler/package_info.h b/windows/include/google/protobuf/compiler/package_info.h deleted file mode 100644 index fb6b473e1..000000000 --- a/windows/include/google/protobuf/compiler/package_info.h +++ /dev/null @@ -1,64 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file exists solely to document the google::protobuf::compiler namespace. -// It is not compiled into anything, but it may be read by an automated -// documentation generator. - -namespace google { - -namespace protobuf { - -// Implementation of the Protocol Buffer compiler. -// -// This package contains code for parsing .proto files and generating code -// based on them. There are two reasons you might be interested in this -// package: -// - You want to parse .proto files at runtime. In this case, you should -// look at importer.h. Since this functionality is widely useful, it is -// included in the libprotobuf base library; you do not have to link against -// libprotoc. -// - You want to write a custom protocol compiler which generates different -// kinds of code, e.g. code in a different language which is not supported -// by the official compiler. For this purpose, command_line_interface.h -// provides you with a complete compiler front-end, so all you need to do -// is write a custom implementation of CodeGenerator and a trivial main() -// function. You can even make your compiler support the official languages -// in addition to your own. Since this functionality is only useful to those -// writing custom compilers, it is in a separate library called "libprotoc" -// which you will have to link against. -namespace compiler {} - -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/parser.cc b/windows/include/google/protobuf/compiler/parser.cc deleted file mode 100644 index 5c7047a63..000000000 --- a/windows/include/google/protobuf/compiler/parser.cc +++ /dev/null @@ -1,2281 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Recursive descent FTW. - -#include -#include -#include - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { - -using internal::WireFormat; - -namespace { - -typedef hash_map TypeNameMap; - -TypeNameMap MakeTypeNameTable() { - TypeNameMap result; - - result["double" ] = FieldDescriptorProto::TYPE_DOUBLE; - result["float" ] = FieldDescriptorProto::TYPE_FLOAT; - result["uint64" ] = FieldDescriptorProto::TYPE_UINT64; - result["fixed64" ] = FieldDescriptorProto::TYPE_FIXED64; - result["fixed32" ] = FieldDescriptorProto::TYPE_FIXED32; - result["bool" ] = FieldDescriptorProto::TYPE_BOOL; - result["string" ] = FieldDescriptorProto::TYPE_STRING; - result["group" ] = FieldDescriptorProto::TYPE_GROUP; - - result["bytes" ] = FieldDescriptorProto::TYPE_BYTES; - result["uint32" ] = FieldDescriptorProto::TYPE_UINT32; - result["sfixed32"] = FieldDescriptorProto::TYPE_SFIXED32; - result["sfixed64"] = FieldDescriptorProto::TYPE_SFIXED64; - result["int32" ] = FieldDescriptorProto::TYPE_INT32; - result["int64" ] = FieldDescriptorProto::TYPE_INT64; - result["sint32" ] = FieldDescriptorProto::TYPE_SINT32; - result["sint64" ] = FieldDescriptorProto::TYPE_SINT64; - - return result; -} - -const TypeNameMap kTypeNames = MakeTypeNameTable(); - -// Camel-case the field name and append "Entry" for generated map entry name. -// e.g. map foo_map => FooMapEntry -string MapEntryName(const string& field_name) { - string result; - static const char kSuffix[] = "Entry"; - result.reserve(field_name.size() + sizeof(kSuffix)); - bool cap_next = true; - for (int i = 0; i < field_name.size(); ++i) { - if (field_name[i] == '_') { - cap_next = true; - } else if (cap_next) { - // Note: Do not use ctype.h due to locales. - if ('a' <= field_name[i] && field_name[i] <= 'z') { - result.push_back(field_name[i] - 'a' + 'A'); - } else { - result.push_back(field_name[i]); - } - cap_next = false; - } else { - result.push_back(field_name[i]); - } - } - result.append(kSuffix); - return result; -} - -} // anonymous namespace - -// Makes code slightly more readable. The meaning of "DO(foo)" is -// "Execute foo and fail if it fails.", where failure is indicated by -// returning false. -#define DO(STATEMENT) if (STATEMENT) {} else return false - -// =================================================================== - -Parser::Parser() - : input_(NULL), - error_collector_(NULL), - source_location_table_(NULL), - had_errors_(false), - require_syntax_identifier_(false), - stop_after_syntax_identifier_(false) { -} - -Parser::~Parser() { -} - -// =================================================================== - -inline bool Parser::LookingAt(const char* text) { - return input_->current().text == text; -} - -inline bool Parser::LookingAtType(io::Tokenizer::TokenType token_type) { - return input_->current().type == token_type; -} - -inline bool Parser::AtEnd() { - return LookingAtType(io::Tokenizer::TYPE_END); -} - -bool Parser::TryConsume(const char* text) { - if (LookingAt(text)) { - input_->Next(); - return true; - } else { - return false; - } -} - -bool Parser::Consume(const char* text, const char* error) { - if (TryConsume(text)) { - return true; - } else { - AddError(error); - return false; - } -} - -bool Parser::Consume(const char* text) { - if (TryConsume(text)) { - return true; - } else { - AddError("Expected \"" + string(text) + "\"."); - return false; - } -} - -bool Parser::ConsumeIdentifier(string* output, const char* error) { - if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { - *output = input_->current().text; - input_->Next(); - return true; - } else { - AddError(error); - return false; - } -} - -bool Parser::ConsumeInteger(int* output, const char* error) { - if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { - uint64 value = 0; - if (!io::Tokenizer::ParseInteger(input_->current().text, - kint32max, &value)) { - AddError("Integer out of range."); - // We still return true because we did, in fact, parse an integer. - } - *output = value; - input_->Next(); - return true; - } else { - AddError(error); - return false; - } -} - -bool Parser::ConsumeSignedInteger(int* output, const char* error) { - bool is_negative = false; - uint64 max_value = kint32max; - if (TryConsume("-")) { - is_negative = true; - max_value += 1; - } - uint64 value = 0; - DO(ConsumeInteger64(max_value, &value, error)); - if (is_negative) value *= -1; - *output = value; - return true; -} - -bool Parser::ConsumeInteger64(uint64 max_value, uint64* output, - const char* error) { - if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { - if (!io::Tokenizer::ParseInteger(input_->current().text, max_value, - output)) { - AddError("Integer out of range."); - // We still return true because we did, in fact, parse an integer. - *output = 0; - } - input_->Next(); - return true; - } else { - AddError(error); - return false; - } -} - -bool Parser::ConsumeNumber(double* output, const char* error) { - if (LookingAtType(io::Tokenizer::TYPE_FLOAT)) { - *output = io::Tokenizer::ParseFloat(input_->current().text); - input_->Next(); - return true; - } else if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { - // Also accept integers. - uint64 value = 0; - if (!io::Tokenizer::ParseInteger(input_->current().text, - kuint64max, &value)) { - AddError("Integer out of range."); - // We still return true because we did, in fact, parse a number. - } - *output = value; - input_->Next(); - return true; - } else if (LookingAt("inf")) { - *output = std::numeric_limits::infinity(); - input_->Next(); - return true; - } else if (LookingAt("nan")) { - *output = std::numeric_limits::quiet_NaN(); - input_->Next(); - return true; - } else { - AddError(error); - return false; - } -} - -bool Parser::ConsumeString(string* output, const char* error) { - if (LookingAtType(io::Tokenizer::TYPE_STRING)) { - io::Tokenizer::ParseString(input_->current().text, output); - input_->Next(); - // Allow C++ like concatenation of adjacent string tokens. - while (LookingAtType(io::Tokenizer::TYPE_STRING)) { - io::Tokenizer::ParseStringAppend(input_->current().text, output); - input_->Next(); - } - return true; - } else { - AddError(error); - return false; - } -} - -bool Parser::TryConsumeEndOfDeclaration( - const char* text, const LocationRecorder* location) { - if (LookingAt(text)) { - string leading, trailing; - std::vector detached; - input_->NextWithComments(&trailing, &detached, &leading); - - // Save the leading comments for next time, and recall the leading comments - // from last time. - leading.swap(upcoming_doc_comments_); - - if (location != NULL) { - upcoming_detached_comments_.swap(detached); - location->AttachComments(&leading, &trailing, &detached); - } else if (strcmp(text, "}") == 0) { - // If the current location is null and we are finishing the current scope, - // drop pending upcoming detached comments. - upcoming_detached_comments_.swap(detached); - } else { - // Otherwise, append the new detached comments to the existing upcoming - // detached comments. - upcoming_detached_comments_.insert(upcoming_detached_comments_.end(), - detached.begin(), detached.end()); - } - - return true; - } else { - return false; - } -} - -bool Parser::ConsumeEndOfDeclaration( - const char* text, const LocationRecorder* location) { - if (TryConsumeEndOfDeclaration(text, location)) { - return true; - } else { - AddError("Expected \"" + string(text) + "\"."); - return false; - } -} - -// ------------------------------------------------------------------- - -void Parser::AddError(int line, int column, const string& error) { - if (error_collector_ != NULL) { - error_collector_->AddError(line, column, error); - } - had_errors_ = true; -} - -void Parser::AddError(const string& error) { - AddError(input_->current().line, input_->current().column, error); -} - -// ------------------------------------------------------------------- - -Parser::LocationRecorder::LocationRecorder(Parser* parser) - : parser_(parser), - source_code_info_(parser->source_code_info_), - location_(parser_->source_code_info_->add_location()) { - location_->add_span(parser_->input_->current().line); - location_->add_span(parser_->input_->current().column); -} - -Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent) { - Init(parent, parent.source_code_info_); -} - -Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent, - int path1, - SourceCodeInfo* source_code_info) { - Init(parent, source_code_info); - AddPath(path1); -} - -Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent, - int path1) { - Init(parent, parent.source_code_info_); - AddPath(path1); -} - -Parser::LocationRecorder::LocationRecorder(const LocationRecorder& parent, - int path1, int path2) { - Init(parent, parent.source_code_info_); - AddPath(path1); - AddPath(path2); -} - -void Parser::LocationRecorder::Init(const LocationRecorder& parent, - SourceCodeInfo* source_code_info) { - parser_ = parent.parser_; - source_code_info_ = source_code_info; - - location_ = source_code_info_->add_location(); - location_->mutable_path()->CopyFrom(parent.location_->path()); - - location_->add_span(parser_->input_->current().line); - location_->add_span(parser_->input_->current().column); -} - -Parser::LocationRecorder::~LocationRecorder() { - if (location_->span_size() <= 2) { - EndAt(parser_->input_->previous()); - } -} - -void Parser::LocationRecorder::AddPath(int path_component) { - location_->add_path(path_component); -} - -void Parser::LocationRecorder::StartAt(const io::Tokenizer::Token& token) { - location_->set_span(0, token.line); - location_->set_span(1, token.column); -} - -void Parser::LocationRecorder::StartAt(const LocationRecorder& other) { - location_->set_span(0, other.location_->span(0)); - location_->set_span(1, other.location_->span(1)); -} - -void Parser::LocationRecorder::EndAt(const io::Tokenizer::Token& token) { - if (token.line != location_->span(0)) { - location_->add_span(token.line); - } - location_->add_span(token.end_column); -} - -void Parser::LocationRecorder::RecordLegacyLocation(const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location) { - if (parser_->source_location_table_ != NULL) { - parser_->source_location_table_->Add( - descriptor, location, location_->span(0), location_->span(1)); - } -} - -int Parser::LocationRecorder::CurrentPathSize() const { - return location_->path_size(); -} - -void Parser::LocationRecorder::AttachComments( - string* leading, string* trailing, - std::vector* detached_comments) const { - GOOGLE_CHECK(!location_->has_leading_comments()); - GOOGLE_CHECK(!location_->has_trailing_comments()); - - if (!leading->empty()) { - location_->mutable_leading_comments()->swap(*leading); - } - if (!trailing->empty()) { - location_->mutable_trailing_comments()->swap(*trailing); - } - for (int i = 0; i < detached_comments->size(); ++i) { - location_->add_leading_detached_comments()->swap( - (*detached_comments)[i]); - } - detached_comments->clear(); -} - -// ------------------------------------------------------------------- - -void Parser::SkipStatement() { - while (true) { - if (AtEnd()) { - return; - } else if (LookingAtType(io::Tokenizer::TYPE_SYMBOL)) { - if (TryConsumeEndOfDeclaration(";", NULL)) { - return; - } else if (TryConsume("{")) { - SkipRestOfBlock(); - return; - } else if (LookingAt("}")) { - return; - } - } - input_->Next(); - } -} - -void Parser::SkipRestOfBlock() { - while (true) { - if (AtEnd()) { - return; - } else if (LookingAtType(io::Tokenizer::TYPE_SYMBOL)) { - if (TryConsumeEndOfDeclaration("}", NULL)) { - return; - } else if (TryConsume("{")) { - SkipRestOfBlock(); - } - } - input_->Next(); - } -} - -// =================================================================== - -bool Parser::ValidateEnum(const EnumDescriptorProto* proto) { - bool has_allow_alias = false; - bool allow_alias = false; - - for (int i = 0; i < proto->options().uninterpreted_option_size(); i++) { - const UninterpretedOption option = proto->options().uninterpreted_option(i); - if (option.name_size() > 1) { - continue; - } - if (!option.name(0).is_extension() && - option.name(0).name_part() == "allow_alias") { - has_allow_alias = true; - if (option.identifier_value() == "true") { - allow_alias = true; - } - break; - } - } - - if (has_allow_alias && !allow_alias) { - string error = - "\"" + proto->name() + - "\" declares 'option allow_alias = false;' which has no effect. " - "Please remove the declaration."; - // This needlessly clutters declarations with nops. - AddError(error); - return false; - } - - std::set used_values; - bool has_duplicates = false; - for (int i = 0; i < proto->value_size(); ++i) { - const EnumValueDescriptorProto enum_value = proto->value(i); - if (used_values.find(enum_value.number()) != used_values.end()) { - has_duplicates = true; - break; - } else { - used_values.insert(enum_value.number()); - } - } - if (allow_alias && !has_duplicates) { - string error = - "\"" + proto->name() + - "\" declares support for enum aliases but no enum values share field " - "numbers. Please remove the unnecessary 'option allow_alias = true;' " - "declaration."; - // Generate an error if an enum declares support for duplicate enum values - // and does not use it protect future authors. - AddError(error); - return false; - } - - return true; -} - -bool Parser::Parse(io::Tokenizer* input, FileDescriptorProto* file) { - input_ = input; - had_errors_ = false; - syntax_identifier_.clear(); - - // Note that |file| could be NULL at this point if - // stop_after_syntax_identifier_ is true. So, we conservatively allocate - // SourceCodeInfo on the stack, then swap it into the FileDescriptorProto - // later on. - SourceCodeInfo source_code_info; - source_code_info_ = &source_code_info; - - if (LookingAtType(io::Tokenizer::TYPE_START)) { - // Advance to first token. - input_->NextWithComments(NULL, &upcoming_detached_comments_, - &upcoming_doc_comments_); - } - - { - LocationRecorder root_location(this); - - if (require_syntax_identifier_ || LookingAt("syntax")) { - if (!ParseSyntaxIdentifier(root_location)) { - // Don't attempt to parse the file if we didn't recognize the syntax - // identifier. - return false; - } - // Store the syntax into the file. - if (file != NULL) file->set_syntax(syntax_identifier_); - } else if (!stop_after_syntax_identifier_) { - GOOGLE_LOG(WARNING) << "No syntax specified for the proto file: " - << file->name() << ". Please use 'syntax = \"proto2\";' " - << "or 'syntax = \"proto3\";' to specify a syntax " - << "version. (Defaulted to proto2 syntax.)"; - syntax_identifier_ = "proto2"; - } - - if (stop_after_syntax_identifier_) return !had_errors_; - - // Repeatedly parse statements until we reach the end of the file. - while (!AtEnd()) { - if (!ParseTopLevelStatement(file, root_location)) { - // This statement failed to parse. Skip it, but keep looping to parse - // other statements. - SkipStatement(); - - if (LookingAt("}")) { - AddError("Unmatched \"}\"."); - input_->NextWithComments(NULL, &upcoming_detached_comments_, - &upcoming_doc_comments_); - } - } - } - } - - input_ = NULL; - source_code_info_ = NULL; - assert(file != NULL); - source_code_info.Swap(file->mutable_source_code_info()); - return !had_errors_; -} - -bool Parser::ParseSyntaxIdentifier(const LocationRecorder& parent) { - LocationRecorder syntax_location(parent, - FileDescriptorProto::kSyntaxFieldNumber); - DO(Consume( - "syntax", - "File must begin with a syntax statement, e.g. 'syntax = \"proto2\";'.")); - DO(Consume("=")); - io::Tokenizer::Token syntax_token = input_->current(); - string syntax; - DO(ConsumeString(&syntax, "Expected syntax identifier.")); - DO(ConsumeEndOfDeclaration(";", &syntax_location)); - - syntax_identifier_ = syntax; - - if (syntax != "proto2" && syntax != "proto3" && - !stop_after_syntax_identifier_) { - AddError(syntax_token.line, syntax_token.column, - "Unrecognized syntax identifier \"" + syntax + "\". This parser " - "only recognizes \"proto2\" and \"proto3\"."); - return false; - } - - return true; -} - -bool Parser::ParseTopLevelStatement(FileDescriptorProto* file, - const LocationRecorder& root_location) { - if (TryConsumeEndOfDeclaration(";", NULL)) { - // empty statement; ignore - return true; - } else if (LookingAt("message")) { - LocationRecorder location(root_location, - FileDescriptorProto::kMessageTypeFieldNumber, file->message_type_size()); - return ParseMessageDefinition(file->add_message_type(), location, file); - } else if (LookingAt("enum")) { - LocationRecorder location(root_location, - FileDescriptorProto::kEnumTypeFieldNumber, file->enum_type_size()); - return ParseEnumDefinition(file->add_enum_type(), location, file); - } else if (LookingAt("service")) { - LocationRecorder location(root_location, - FileDescriptorProto::kServiceFieldNumber, file->service_size()); - return ParseServiceDefinition(file->add_service(), location, file); - } else if (LookingAt("extend")) { - LocationRecorder location(root_location, - FileDescriptorProto::kExtensionFieldNumber); - return ParseExtend(file->mutable_extension(), - file->mutable_message_type(), - root_location, - FileDescriptorProto::kMessageTypeFieldNumber, - location, file); - } else if (LookingAt("import")) { - return ParseImport(file->mutable_dependency(), - file->mutable_public_dependency(), - file->mutable_weak_dependency(), - root_location, file); - } else if (LookingAt("package")) { - return ParsePackage(file, root_location, file); - } else if (LookingAt("option")) { - LocationRecorder location(root_location, - FileDescriptorProto::kOptionsFieldNumber); - return ParseOption(file->mutable_options(), location, file, - OPTION_STATEMENT); - } else { - AddError("Expected top-level statement (e.g. \"message\")."); - return false; - } -} - -// ------------------------------------------------------------------- -// Messages - -bool Parser::ParseMessageDefinition( - DescriptorProto* message, - const LocationRecorder& message_location, - const FileDescriptorProto* containing_file) { - DO(Consume("message")); - { - LocationRecorder location(message_location, - DescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - message, DescriptorPool::ErrorCollector::NAME); - DO(ConsumeIdentifier(message->mutable_name(), "Expected message name.")); - } - DO(ParseMessageBlock(message, message_location, containing_file)); - return true; -} - -namespace { - -const int kMaxRangeSentinel = -1; - -bool IsMessageSetWireFormatMessage(const DescriptorProto& message) { - const MessageOptions& options = message.options(); - for (int i = 0; i < options.uninterpreted_option_size(); ++i) { - const UninterpretedOption& uninterpreted = options.uninterpreted_option(i); - if (uninterpreted.name_size() == 1 && - uninterpreted.name(0).name_part() == "message_set_wire_format" && - uninterpreted.identifier_value() == "true") { - return true; - } - } - return false; -} - -// Modifies any extension ranges that specified 'max' as the end of the -// extension range, and sets them to the type-specific maximum. The actual max -// tag number can only be determined after all options have been parsed. -void AdjustExtensionRangesWithMaxEndNumber(DescriptorProto* message) { - const bool is_message_set = IsMessageSetWireFormatMessage(*message); - const int max_extension_number = is_message_set ? - kint32max : - FieldDescriptor::kMaxNumber + 1; - for (int i = 0; i < message->extension_range_size(); ++i) { - if (message->extension_range(i).end() == kMaxRangeSentinel) { - message->mutable_extension_range(i)->set_end(max_extension_number); - } - } -} - -// Modifies any reserved ranges that specified 'max' as the end of the -// reserved range, and sets them to the type-specific maximum. The actual max -// tag number can only be determined after all options have been parsed. -void AdjustReservedRangesWithMaxEndNumber(DescriptorProto* message) { - const bool is_message_set = IsMessageSetWireFormatMessage(*message); - const int max_field_number = is_message_set ? - kint32max : - FieldDescriptor::kMaxNumber + 1; - for (int i = 0; i < message->reserved_range_size(); ++i) { - if (message->reserved_range(i).end() == kMaxRangeSentinel) { - message->mutable_reserved_range(i)->set_end(max_field_number); - } - } -} - -} // namespace - -bool Parser::ParseMessageBlock(DescriptorProto* message, - const LocationRecorder& message_location, - const FileDescriptorProto* containing_file) { - DO(ConsumeEndOfDeclaration("{", &message_location)); - - while (!TryConsumeEndOfDeclaration("}", NULL)) { - if (AtEnd()) { - AddError("Reached end of input in message definition (missing '}')."); - return false; - } - - if (!ParseMessageStatement(message, message_location, containing_file)) { - // This statement failed to parse. Skip it, but keep looping to parse - // other statements. - SkipStatement(); - } - } - - if (message->extension_range_size() > 0) { - AdjustExtensionRangesWithMaxEndNumber(message); - } - if (message->reserved_range_size() > 0) { - AdjustReservedRangesWithMaxEndNumber(message); - } - return true; -} - -bool Parser::ParseMessageStatement(DescriptorProto* message, - const LocationRecorder& message_location, - const FileDescriptorProto* containing_file) { - if (TryConsumeEndOfDeclaration(";", NULL)) { - // empty statement; ignore - return true; - } else if (LookingAt("message")) { - LocationRecorder location(message_location, - DescriptorProto::kNestedTypeFieldNumber, - message->nested_type_size()); - return ParseMessageDefinition(message->add_nested_type(), location, - containing_file); - } else if (LookingAt("enum")) { - LocationRecorder location(message_location, - DescriptorProto::kEnumTypeFieldNumber, - message->enum_type_size()); - return ParseEnumDefinition(message->add_enum_type(), location, - containing_file); - } else if (LookingAt("extensions")) { - LocationRecorder location(message_location, - DescriptorProto::kExtensionRangeFieldNumber); - return ParseExtensions(message, location, containing_file); - } else if (LookingAt("reserved")) { - return ParseReserved(message, message_location); - } else if (LookingAt("extend")) { - LocationRecorder location(message_location, - DescriptorProto::kExtensionFieldNumber); - return ParseExtend(message->mutable_extension(), - message->mutable_nested_type(), - message_location, - DescriptorProto::kNestedTypeFieldNumber, - location, containing_file); - } else if (LookingAt("option")) { - LocationRecorder location(message_location, - DescriptorProto::kOptionsFieldNumber); - return ParseOption(message->mutable_options(), location, - containing_file, OPTION_STATEMENT); - } else if (LookingAt("oneof")) { - int oneof_index = message->oneof_decl_size(); - LocationRecorder oneof_location(message_location, - DescriptorProto::kOneofDeclFieldNumber, - oneof_index); - - return ParseOneof(message->add_oneof_decl(), message, - oneof_index, oneof_location, message_location, - containing_file); - } else { - LocationRecorder location(message_location, - DescriptorProto::kFieldFieldNumber, - message->field_size()); - return ParseMessageField(message->add_field(), - message->mutable_nested_type(), - message_location, - DescriptorProto::kNestedTypeFieldNumber, - location, - containing_file); - } -} - -bool Parser::ParseMessageField(FieldDescriptorProto* field, - RepeatedPtrField* messages, - const LocationRecorder& parent_location, - int location_field_number_for_nested_type, - const LocationRecorder& field_location, - const FileDescriptorProto* containing_file) { - { - LocationRecorder location(field_location, - FieldDescriptorProto::kLabelFieldNumber); - FieldDescriptorProto::Label label; - if (ParseLabel(&label, containing_file)) { - field->set_label(label); - if (label == FieldDescriptorProto::LABEL_OPTIONAL && - syntax_identifier_ == "proto3") { - AddError( - "Explicit 'optional' labels are disallowed in the Proto3 syntax. " - "To define 'optional' fields in Proto3, simply remove the " - "'optional' label, as fields are 'optional' by default."); - } - } - } - - return ParseMessageFieldNoLabel(field, messages, parent_location, - location_field_number_for_nested_type, - field_location, - containing_file); -} - -bool Parser::ParseMessageFieldNoLabel( - FieldDescriptorProto* field, - RepeatedPtrField* messages, - const LocationRecorder& parent_location, - int location_field_number_for_nested_type, - const LocationRecorder& field_location, - const FileDescriptorProto* containing_file) { - MapField map_field; - // Parse type. - { - LocationRecorder location(field_location); // add path later - location.RecordLegacyLocation(field, DescriptorPool::ErrorCollector::TYPE); - - bool type_parsed = false; - FieldDescriptorProto::Type type = FieldDescriptorProto::TYPE_INT32; - string type_name; - - // Special case map field. We only treat the field as a map field if the - // field type name starts with the word "map" with a following "<". - if (TryConsume("map")) { - if (LookingAt("<")) { - map_field.is_map_field = true; - } else { - // False positive - type_parsed = true; - type_name = "map"; - } - } - if (map_field.is_map_field) { - if (field->has_oneof_index()) { - AddError("Map fields are not allowed in oneofs."); - return false; - } - if (field->has_label()) { - AddError( - "Field labels (required/optional/repeated) are not allowed on " - "map fields."); - return false; - } - if (field->has_extendee()) { - AddError("Map fields are not allowed to be extensions."); - return false; - } - field->set_label(FieldDescriptorProto::LABEL_REPEATED); - DO(Consume("<")); - DO(ParseType(&map_field.key_type, &map_field.key_type_name)); - DO(Consume(",")); - DO(ParseType(&map_field.value_type, &map_field.value_type_name)); - DO(Consume(">")); - // Defer setting of the type name of the map field until the - // field name is parsed. Add the source location though. - location.AddPath(FieldDescriptorProto::kTypeNameFieldNumber); - } else { - // Handle the case where no explicit label is given for a non-map field. - if (!field->has_label() && DefaultToOptionalFields()) { - field->set_label(FieldDescriptorProto::LABEL_OPTIONAL); - } - if (!field->has_label()) { - AddError("Expected \"required\", \"optional\", or \"repeated\"."); - // We can actually reasonably recover here by just assuming the user - // forgot the label altogether. - field->set_label(FieldDescriptorProto::LABEL_OPTIONAL); - } - - // Handle the case where the actual type is a message or enum named "map", - // which we already consumed in the code above. - if (!type_parsed) { - DO(ParseType(&type, &type_name)); - } - if (type_name.empty()) { - location.AddPath(FieldDescriptorProto::kTypeFieldNumber); - field->set_type(type); - } else { - location.AddPath(FieldDescriptorProto::kTypeNameFieldNumber); - field->set_type_name(type_name); - } - } - } - - // Parse name and '='. - io::Tokenizer::Token name_token = input_->current(); - { - LocationRecorder location(field_location, - FieldDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation(field, DescriptorPool::ErrorCollector::NAME); - DO(ConsumeIdentifier(field->mutable_name(), "Expected field name.")); - } - DO(Consume("=", "Missing field number.")); - - // Parse field number. - { - LocationRecorder location(field_location, - FieldDescriptorProto::kNumberFieldNumber); - location.RecordLegacyLocation( - field, DescriptorPool::ErrorCollector::NUMBER); - int number; - DO(ConsumeInteger(&number, "Expected field number.")); - field->set_number(number); - } - - // Parse options. - DO(ParseFieldOptions(field, field_location, containing_file)); - - // Deal with groups. - if (field->has_type() && field->type() == FieldDescriptorProto::TYPE_GROUP) { - // Awkward: Since a group declares both a message type and a field, we - // have to create overlapping locations. - LocationRecorder group_location(parent_location); - group_location.StartAt(field_location); - group_location.AddPath(location_field_number_for_nested_type); - group_location.AddPath(messages->size()); - - DescriptorProto* group = messages->Add(); - group->set_name(field->name()); - - // Record name location to match the field name's location. - { - LocationRecorder location(group_location, - DescriptorProto::kNameFieldNumber); - location.StartAt(name_token); - location.EndAt(name_token); - location.RecordLegacyLocation( - group, DescriptorPool::ErrorCollector::NAME); - } - - // The field's type_name also comes from the name. Confusing! - { - LocationRecorder location(field_location, - FieldDescriptorProto::kTypeNameFieldNumber); - location.StartAt(name_token); - location.EndAt(name_token); - } - - // As a hack for backwards-compatibility, we force the group name to start - // with a capital letter and lower-case the field name. New code should - // not use groups; it should use nested messages. - if (group->name()[0] < 'A' || 'Z' < group->name()[0]) { - AddError(name_token.line, name_token.column, - "Group names must start with a capital letter."); - } - LowerString(field->mutable_name()); - - field->set_type_name(group->name()); - if (LookingAt("{")) { - DO(ParseMessageBlock(group, group_location, containing_file)); - } else { - AddError("Missing group body."); - return false; - } - } else { - DO(ConsumeEndOfDeclaration(";", &field_location)); - } - - // Create a map entry type if this is a map field. - if (map_field.is_map_field) { - GenerateMapEntry(map_field, field, messages); - } - - return true; -} - -void Parser::GenerateMapEntry(const MapField& map_field, - FieldDescriptorProto* field, - RepeatedPtrField* messages) { - DescriptorProto* entry = messages->Add(); - string entry_name = MapEntryName(field->name()); - field->set_type_name(entry_name); - entry->set_name(entry_name); - entry->mutable_options()->set_map_entry(true); - FieldDescriptorProto* key_field = entry->add_field(); - key_field->set_name("key"); - key_field->set_label(FieldDescriptorProto::LABEL_OPTIONAL); - key_field->set_number(1); - if (map_field.key_type_name.empty()) { - key_field->set_type(map_field.key_type); - } else { - key_field->set_type_name(map_field.key_type_name); - } - FieldDescriptorProto* value_field = entry->add_field(); - value_field->set_name("value"); - value_field->set_label(FieldDescriptorProto::LABEL_OPTIONAL); - value_field->set_number(2); - if (map_field.value_type_name.empty()) { - value_field->set_type(map_field.value_type); - } else { - value_field->set_type_name(map_field.value_type_name); - } - // Propagate the "enforce_utf8" option to key and value fields if they - // are strings. This helps simplify the implementation of code generators - // and also reflection-based parsing code. - // - // The following definition: - // message Foo { - // map value = 1 [enforce_utf8 = false]; - // } - // will be interpreted as: - // message Foo { - // message ValueEntry { - // option map_entry = true; - // string key = 1 [enforce_utf8 = false]; - // string value = 2 [enforce_utf8 = false]; - // } - // repeated ValueEntry value = 1 [enforce_utf8 = false]; - // } - // - // TODO(xiaofeng): Remove this when the "enforce_utf8" option is removed - // from protocol compiler. - for (int i = 0; i < field->options().uninterpreted_option_size(); ++i) { - const UninterpretedOption& option = - field->options().uninterpreted_option(i); - if (option.name_size() == 1 && - option.name(0).name_part() == "enforce_utf8" && - !option.name(0).is_extension()) { - if (key_field->type() == FieldDescriptorProto::TYPE_STRING) { - key_field->mutable_options()->add_uninterpreted_option() - ->CopyFrom(option); - } - if (value_field->type() == FieldDescriptorProto::TYPE_STRING) { - value_field->mutable_options()->add_uninterpreted_option() - ->CopyFrom(option); - } - } - } -} - -bool Parser::ParseFieldOptions(FieldDescriptorProto* field, - const LocationRecorder& field_location, - const FileDescriptorProto* containing_file) { - if (!LookingAt("[")) return true; - - LocationRecorder location(field_location, - FieldDescriptorProto::kOptionsFieldNumber); - - DO(Consume("[")); - - // Parse field options. - do { - if (LookingAt("default")) { - // We intentionally pass field_location rather than location here, since - // the default value is not actually an option. - DO(ParseDefaultAssignment(field, field_location, containing_file)); - } else if (LookingAt("json_name")) { - // Like default value, this "json_name" is not an actual option. - DO(ParseJsonName(field, field_location, containing_file)); - } else { - DO(ParseOption(field->mutable_options(), location, - containing_file, OPTION_ASSIGNMENT)); - } - } while (TryConsume(",")); - - DO(Consume("]")); - return true; -} - -bool Parser::ParseDefaultAssignment( - FieldDescriptorProto* field, - const LocationRecorder& field_location, - const FileDescriptorProto* containing_file) { - if (field->has_default_value()) { - AddError("Already set option \"default\"."); - field->clear_default_value(); - } - - DO(Consume("default")); - DO(Consume("=")); - - LocationRecorder location(field_location, - FieldDescriptorProto::kDefaultValueFieldNumber); - location.RecordLegacyLocation( - field, DescriptorPool::ErrorCollector::DEFAULT_VALUE); - string* default_value = field->mutable_default_value(); - - if (!field->has_type()) { - // The field has a type name, but we don't know if it is a message or an - // enum yet. (If it were a primitive type, |field| would have a type set - // already.) In this case, simply take the current string as the default - // value; we will catch the error later if it is not a valid enum value. - // (N.B. that we do not check whether the current token is an identifier: - // doing so throws strange errors when the user mistypes a primitive - // typename and we assume it's an enum. E.g.: "optional int foo = 1 [default - // = 42]". In such a case the fundamental error is really that "int" is not - // a type, not that "42" is not an identifier. See b/12533582.) - *default_value = input_->current().text; - input_->Next(); - return true; - } - - switch (field->type()) { - case FieldDescriptorProto::TYPE_INT32: - case FieldDescriptorProto::TYPE_INT64: - case FieldDescriptorProto::TYPE_SINT32: - case FieldDescriptorProto::TYPE_SINT64: - case FieldDescriptorProto::TYPE_SFIXED32: - case FieldDescriptorProto::TYPE_SFIXED64: { - uint64 max_value = kint64max; - if (field->type() == FieldDescriptorProto::TYPE_INT32 || - field->type() == FieldDescriptorProto::TYPE_SINT32 || - field->type() == FieldDescriptorProto::TYPE_SFIXED32) { - max_value = kint32max; - } - - // These types can be negative. - if (TryConsume("-")) { - default_value->append("-"); - // Two's complement always has one more negative value than positive. - ++max_value; - } - // Parse the integer to verify that it is not out-of-range. - uint64 value; - DO(ConsumeInteger64(max_value, &value, - "Expected integer for field default value.")); - // And stringify it again. - default_value->append(SimpleItoa(value)); - break; - } - - case FieldDescriptorProto::TYPE_UINT32: - case FieldDescriptorProto::TYPE_UINT64: - case FieldDescriptorProto::TYPE_FIXED32: - case FieldDescriptorProto::TYPE_FIXED64: { - uint64 max_value = kuint64max; - if (field->type() == FieldDescriptorProto::TYPE_UINT32 || - field->type() == FieldDescriptorProto::TYPE_FIXED32) { - max_value = kuint32max; - } - - // Numeric, not negative. - if (TryConsume("-")) { - AddError("Unsigned field can't have negative default value."); - } - // Parse the integer to verify that it is not out-of-range. - uint64 value; - DO(ConsumeInteger64(max_value, &value, - "Expected integer for field default value.")); - // And stringify it again. - default_value->append(SimpleItoa(value)); - break; - } - - case FieldDescriptorProto::TYPE_FLOAT: - case FieldDescriptorProto::TYPE_DOUBLE: - // These types can be negative. - if (TryConsume("-")) { - default_value->append("-"); - } - // Parse the integer because we have to convert hex integers to decimal - // floats. - double value; - DO(ConsumeNumber(&value, "Expected number.")); - // And stringify it again. - default_value->append(SimpleDtoa(value)); - break; - - case FieldDescriptorProto::TYPE_BOOL: - if (TryConsume("true")) { - default_value->assign("true"); - } else if (TryConsume("false")) { - default_value->assign("false"); - } else { - AddError("Expected \"true\" or \"false\"."); - return false; - } - break; - - case FieldDescriptorProto::TYPE_STRING: - // Note: When file opton java_string_check_utf8 is true, if a - // non-string representation (eg byte[]) is later supported, it must - // be checked for UTF-8-ness. - DO(ConsumeString(default_value, "Expected string for field default " - "value.")); - break; - - case FieldDescriptorProto::TYPE_BYTES: - DO(ConsumeString(default_value, "Expected string.")); - *default_value = CEscape(*default_value); - break; - - case FieldDescriptorProto::TYPE_ENUM: - DO(ConsumeIdentifier(default_value, "Expected enum identifier for field " - "default value.")); - break; - - case FieldDescriptorProto::TYPE_MESSAGE: - case FieldDescriptorProto::TYPE_GROUP: - AddError("Messages can't have default values."); - return false; - } - - return true; -} - -bool Parser::ParseJsonName( - FieldDescriptorProto* field, - const LocationRecorder& field_location, - const FileDescriptorProto* containing_file) { - if (field->has_json_name()) { - AddError("Already set option \"json_name\"."); - field->clear_json_name(); - } - - DO(Consume("json_name")); - DO(Consume("=")); - - LocationRecorder location(field_location, - FieldDescriptorProto::kJsonNameFieldNumber); - location.RecordLegacyLocation( - field, DescriptorPool::ErrorCollector::OPTION_VALUE); - DO(ConsumeString(field->mutable_json_name(), - "Expected string for JSON name.")); - return true; -} - - -bool Parser::ParseOptionNamePart(UninterpretedOption* uninterpreted_option, - const LocationRecorder& part_location, - const FileDescriptorProto* containing_file) { - UninterpretedOption::NamePart* name = uninterpreted_option->add_name(); - string identifier; // We parse identifiers into this string. - if (LookingAt("(")) { // This is an extension. - DO(Consume("(")); - - { - LocationRecorder location( - part_location, UninterpretedOption::NamePart::kNamePartFieldNumber); - // An extension name consists of dot-separated identifiers, and may begin - // with a dot. - if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { - DO(ConsumeIdentifier(&identifier, "Expected identifier.")); - name->mutable_name_part()->append(identifier); - } - while (LookingAt(".")) { - DO(Consume(".")); - name->mutable_name_part()->append("."); - DO(ConsumeIdentifier(&identifier, "Expected identifier.")); - name->mutable_name_part()->append(identifier); - } - } - - DO(Consume(")")); - name->set_is_extension(true); - } else { // This is a regular field. - LocationRecorder location( - part_location, UninterpretedOption::NamePart::kNamePartFieldNumber); - DO(ConsumeIdentifier(&identifier, "Expected identifier.")); - name->mutable_name_part()->append(identifier); - name->set_is_extension(false); - } - return true; -} - -bool Parser::ParseUninterpretedBlock(string* value) { - // Note that enclosing braces are not added to *value. - // We do NOT use ConsumeEndOfStatement for this brace because it's delimiting - // an expression, not a block of statements. - DO(Consume("{")); - int brace_depth = 1; - while (!AtEnd()) { - if (LookingAt("{")) { - brace_depth++; - } else if (LookingAt("}")) { - brace_depth--; - if (brace_depth == 0) { - input_->Next(); - return true; - } - } - // TODO(sanjay): Interpret line/column numbers to preserve formatting - if (!value->empty()) value->push_back(' '); - value->append(input_->current().text); - input_->Next(); - } - AddError("Unexpected end of stream while parsing aggregate value."); - return false; -} - -// We don't interpret the option here. Instead we store it in an -// UninterpretedOption, to be interpreted later. -bool Parser::ParseOption(Message* options, - const LocationRecorder& options_location, - const FileDescriptorProto* containing_file, - OptionStyle style) { - // Create an entry in the uninterpreted_option field. - const FieldDescriptor* uninterpreted_option_field = options->GetDescriptor()-> - FindFieldByName("uninterpreted_option"); - GOOGLE_CHECK(uninterpreted_option_field != NULL) - << "No field named \"uninterpreted_option\" in the Options proto."; - - const Reflection* reflection = options->GetReflection(); - - LocationRecorder location( - options_location, uninterpreted_option_field->number(), - reflection->FieldSize(*options, uninterpreted_option_field)); - - if (style == OPTION_STATEMENT) { - DO(Consume("option")); - } - - UninterpretedOption* uninterpreted_option = down_cast( - options->GetReflection()->AddMessage(options, - uninterpreted_option_field)); - - // Parse dot-separated name. - { - LocationRecorder name_location(location, - UninterpretedOption::kNameFieldNumber); - name_location.RecordLegacyLocation( - uninterpreted_option, DescriptorPool::ErrorCollector::OPTION_NAME); - - { - LocationRecorder part_location(name_location, - uninterpreted_option->name_size()); - DO(ParseOptionNamePart(uninterpreted_option, part_location, - containing_file)); - } - - while (LookingAt(".")) { - DO(Consume(".")); - LocationRecorder part_location(name_location, - uninterpreted_option->name_size()); - DO(ParseOptionNamePart(uninterpreted_option, part_location, - containing_file)); - } - } - - DO(Consume("=")); - - { - LocationRecorder value_location(location); - value_location.RecordLegacyLocation( - uninterpreted_option, DescriptorPool::ErrorCollector::OPTION_VALUE); - - // All values are a single token, except for negative numbers, which consist - // of a single '-' symbol, followed by a positive number. - bool is_negative = TryConsume("-"); - - switch (input_->current().type) { - case io::Tokenizer::TYPE_START: - GOOGLE_LOG(FATAL) << "Trying to read value before any tokens have been read."; - return false; - - case io::Tokenizer::TYPE_END: - AddError("Unexpected end of stream while parsing option value."); - return false; - - case io::Tokenizer::TYPE_IDENTIFIER: { - value_location.AddPath( - UninterpretedOption::kIdentifierValueFieldNumber); - if (is_negative) { - AddError("Invalid '-' symbol before identifier."); - return false; - } - string value; - DO(ConsumeIdentifier(&value, "Expected identifier.")); - uninterpreted_option->set_identifier_value(value); - break; - } - - case io::Tokenizer::TYPE_INTEGER: { - uint64 value; - uint64 max_value = - is_negative ? static_cast(kint64max) + 1 : kuint64max; - DO(ConsumeInteger64(max_value, &value, "Expected integer.")); - if (is_negative) { - value_location.AddPath( - UninterpretedOption::kNegativeIntValueFieldNumber); - uninterpreted_option->set_negative_int_value( - static_cast(-value)); - } else { - value_location.AddPath( - UninterpretedOption::kPositiveIntValueFieldNumber); - uninterpreted_option->set_positive_int_value(value); - } - break; - } - - case io::Tokenizer::TYPE_FLOAT: { - value_location.AddPath(UninterpretedOption::kDoubleValueFieldNumber); - double value; - DO(ConsumeNumber(&value, "Expected number.")); - uninterpreted_option->set_double_value(is_negative ? -value : value); - break; - } - - case io::Tokenizer::TYPE_STRING: { - value_location.AddPath(UninterpretedOption::kStringValueFieldNumber); - if (is_negative) { - AddError("Invalid '-' symbol before string."); - return false; - } - string value; - DO(ConsumeString(&value, "Expected string.")); - uninterpreted_option->set_string_value(value); - break; - } - - case io::Tokenizer::TYPE_SYMBOL: - if (LookingAt("{")) { - value_location.AddPath( - UninterpretedOption::kAggregateValueFieldNumber); - DO(ParseUninterpretedBlock( - uninterpreted_option->mutable_aggregate_value())); - } else { - AddError("Expected option value."); - return false; - } - break; - } - } - - if (style == OPTION_STATEMENT) { - DO(ConsumeEndOfDeclaration(";", &location)); - } - - return true; -} - -bool Parser::ParseExtensions(DescriptorProto* message, - const LocationRecorder& extensions_location, - const FileDescriptorProto* containing_file) { - // Parse the declaration. - DO(Consume("extensions")); - - int old_range_size = message->extension_range_size(); - - do { - // Note that kExtensionRangeFieldNumber was already pushed by the parent. - LocationRecorder location(extensions_location, - message->extension_range_size()); - - DescriptorProto::ExtensionRange* range = message->add_extension_range(); - location.RecordLegacyLocation( - range, DescriptorPool::ErrorCollector::NUMBER); - - int start, end; - io::Tokenizer::Token start_token; - - { - LocationRecorder start_location( - location, DescriptorProto::ExtensionRange::kStartFieldNumber); - start_token = input_->current(); - DO(ConsumeInteger(&start, "Expected field number range.")); - } - - if (TryConsume("to")) { - LocationRecorder end_location( - location, DescriptorProto::ExtensionRange::kEndFieldNumber); - if (TryConsume("max")) { - // Set to the sentinel value - 1 since we increment the value below. - // The actual value of the end of the range should be set with - // AdjustExtensionRangesWithMaxEndNumber. - end = kMaxRangeSentinel - 1; - } else { - DO(ConsumeInteger(&end, "Expected integer.")); - } - } else { - LocationRecorder end_location( - location, DescriptorProto::ExtensionRange::kEndFieldNumber); - end_location.StartAt(start_token); - end_location.EndAt(start_token); - end = start; - } - - // Users like to specify inclusive ranges, but in code we like the end - // number to be exclusive. - ++end; - - range->set_start(start); - range->set_end(end); - } while (TryConsume(",")); - - - if (LookingAt("[")) { - int range_number_index = extensions_location.CurrentPathSize(); - SourceCodeInfo info; - - // Parse extension range options in the first range. - ExtensionRangeOptions* options = - message->mutable_extension_range(old_range_size)->mutable_options(); - - { - LocationRecorder index_location( - extensions_location, 0 /* we fill this in w/ actual index below */, - &info); - LocationRecorder location( - index_location, - DescriptorProto::ExtensionRange::kOptionsFieldNumber); - DO(Consume("[")); - - do { - DO(ParseOption(options, location, containing_file, OPTION_ASSIGNMENT)); - } while (TryConsume(",")); - - DO(Consume("]")); - } - - // Then copy the extension range options to all of the other ranges we've - // parsed. - for (int i = old_range_size + 1; i < message->extension_range_size(); i++) { - message->mutable_extension_range(i)->mutable_options() - ->CopyFrom(*options); - } - // and copy source locations to the other ranges, too - for (int i = old_range_size; i < message->extension_range_size(); i++) { - for (int j = 0; j < info.location_size(); j++) { - if (info.location(j).path_size() == range_number_index + 1) { - // this location's path is up to the extension range index, but doesn't - // include options; so it's redundant with location above - continue; - } - SourceCodeInfo_Location* dest = source_code_info_->add_location(); - dest->CopyFrom(info.location(j)); - dest->set_path(range_number_index, i); - } - } - } - - DO(ConsumeEndOfDeclaration(";", &extensions_location)); - return true; -} - -// This is similar to extension range parsing, except that it accepts field -// name literals. -bool Parser::ParseReserved(DescriptorProto* message, - const LocationRecorder& message_location) { - // Parse the declaration. - DO(Consume("reserved")); - if (LookingAtType(io::Tokenizer::TYPE_STRING)) { - LocationRecorder location(message_location, - DescriptorProto::kReservedNameFieldNumber); - return ParseReservedNames(message, location); - } else { - LocationRecorder location(message_location, - DescriptorProto::kReservedRangeFieldNumber); - return ParseReservedNumbers(message, location); - } -} - -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.")); - } while (TryConsume(",")); - DO(ConsumeEndOfDeclaration(";", &parent_location)); - return true; -} - -bool Parser::ParseReservedNumbers(DescriptorProto* message, - const LocationRecorder& parent_location) { - bool first = true; - do { - LocationRecorder location(parent_location, message->reserved_range_size()); - - DescriptorProto::ReservedRange* range = message->add_reserved_range(); - int start, end; - io::Tokenizer::Token start_token; - { - LocationRecorder start_location( - location, DescriptorProto::ReservedRange::kStartFieldNumber); - start_token = input_->current(); - DO(ConsumeInteger(&start, (first ? - "Expected field name or number range." : - "Expected field number range."))); - } - - if (TryConsume("to")) { - LocationRecorder end_location( - location, DescriptorProto::ReservedRange::kEndFieldNumber); - if (TryConsume("max")) { - // Set to the sentinel value - 1 since we increment the value below. - // The actual value of the end of the range should be set with - // AdjustExtensionRangesWithMaxEndNumber. - end = kMaxRangeSentinel - 1; - } else { - DO(ConsumeInteger(&end, "Expected integer.")); - } - } else { - LocationRecorder end_location( - location, DescriptorProto::ReservedRange::kEndFieldNumber); - end_location.StartAt(start_token); - end_location.EndAt(start_token); - end = start; - } - - // Users like to specify inclusive ranges, but in code we like the end - // number to be exclusive. - ++end; - - range->set_start(start); - range->set_end(end); - first = false; - } while (TryConsume(",")); - - DO(ConsumeEndOfDeclaration(";", &parent_location)); - return true; -} - -bool Parser::ParseReserved(EnumDescriptorProto* message, - const LocationRecorder& message_location) { - // Parse the declaration. - DO(Consume("reserved")); - if (LookingAtType(io::Tokenizer::TYPE_STRING)) { - LocationRecorder location(message_location, - DescriptorProto::kReservedNameFieldNumber); - return ParseReservedNames(message, location); - } else { - LocationRecorder location(message_location, - DescriptorProto::kReservedRangeFieldNumber); - return ParseReservedNumbers(message, location); - } -} - -bool Parser::ParseReservedNames(EnumDescriptorProto* message, - const LocationRecorder& parent_location) { - do { - LocationRecorder location(parent_location, message->reserved_name_size()); - DO(ConsumeString(message->add_reserved_name(), "Expected enum value.")); - } while (TryConsume(",")); - DO(ConsumeEndOfDeclaration(";", &parent_location)); - return true; -} - -bool Parser::ParseReservedNumbers(EnumDescriptorProto* message, - const LocationRecorder& parent_location) { - bool first = true; - do { - LocationRecorder location(parent_location, message->reserved_range_size()); - - EnumDescriptorProto::EnumReservedRange* range = - message->add_reserved_range(); - int start, end; - io::Tokenizer::Token start_token; - { - LocationRecorder start_location( - location, EnumDescriptorProto::EnumReservedRange::kStartFieldNumber); - start_token = input_->current(); - DO(ConsumeSignedInteger(&start, (first ? - "Expected enum value or number range." : - "Expected enum number range."))); - } - - if (TryConsume("to")) { - LocationRecorder end_location( - location, EnumDescriptorProto::EnumReservedRange::kEndFieldNumber); - if (TryConsume("max")) { - // This is in the enum descriptor path, which doesn't have the message - // set duality to fix up, so it doesn't integrate with the sentinel. - end = INT_MAX; - } else { - DO(ConsumeSignedInteger(&end, "Expected integer.")); - } - } else { - LocationRecorder end_location( - location, EnumDescriptorProto::EnumReservedRange::kEndFieldNumber); - end_location.StartAt(start_token); - end_location.EndAt(start_token); - end = start; - } - - range->set_start(start); - range->set_end(end); - first = false; - } while (TryConsume(",")); - - DO(ConsumeEndOfDeclaration(";", &parent_location)); - return true; -} - -bool Parser::ParseExtend(RepeatedPtrField* extensions, - RepeatedPtrField* messages, - const LocationRecorder& parent_location, - int location_field_number_for_nested_type, - const LocationRecorder& extend_location, - const FileDescriptorProto* containing_file) { - DO(Consume("extend")); - - // Parse the extendee type. - io::Tokenizer::Token extendee_start = input_->current(); - string extendee; - DO(ParseUserDefinedType(&extendee)); - io::Tokenizer::Token extendee_end = input_->previous(); - - // Parse the block. - DO(ConsumeEndOfDeclaration("{", &extend_location)); - - bool is_first = true; - - do { - if (AtEnd()) { - AddError("Reached end of input in extend definition (missing '}')."); - return false; - } - - // Note that kExtensionFieldNumber was already pushed by the parent. - LocationRecorder location(extend_location, extensions->size()); - - FieldDescriptorProto* field = extensions->Add(); - - { - LocationRecorder extendee_location( - location, FieldDescriptorProto::kExtendeeFieldNumber); - extendee_location.StartAt(extendee_start); - extendee_location.EndAt(extendee_end); - - if (is_first) { - extendee_location.RecordLegacyLocation( - field, DescriptorPool::ErrorCollector::EXTENDEE); - is_first = false; - } - } - - field->set_extendee(extendee); - - if (!ParseMessageField(field, messages, parent_location, - location_field_number_for_nested_type, - location, - containing_file)) { - // This statement failed to parse. Skip it, but keep looping to parse - // other statements. - SkipStatement(); - } - } while (!TryConsumeEndOfDeclaration("}", NULL)); - - return true; -} - -bool Parser::ParseOneof(OneofDescriptorProto* oneof_decl, - DescriptorProto* containing_type, - int oneof_index, - const LocationRecorder& oneof_location, - const LocationRecorder& containing_type_location, - const FileDescriptorProto* containing_file) { - DO(Consume("oneof")); - - { - LocationRecorder name_location(oneof_location, - OneofDescriptorProto::kNameFieldNumber); - DO(ConsumeIdentifier(oneof_decl->mutable_name(), "Expected oneof name.")); - } - - DO(ConsumeEndOfDeclaration("{", &oneof_location)); - - do { - if (AtEnd()) { - AddError("Reached end of input in oneof definition (missing '}')."); - return false; - } - - if (LookingAt("option")) { - LocationRecorder option_location( - oneof_location, OneofDescriptorProto::kOptionsFieldNumber); - if (!ParseOption(oneof_decl->mutable_options(), option_location, - containing_file, OPTION_STATEMENT)) { - return false; - } - continue; - } - - // Print a nice error if the user accidentally tries to place a label - // on an individual member of a oneof. - if (LookingAt("required") || - LookingAt("optional") || - LookingAt("repeated")) { - AddError("Fields in oneofs must not have labels (required / optional " - "/ repeated)."); - // We can continue parsing here because we understand what the user - // meant. The error report will still make parsing fail overall. - input_->Next(); - } - - LocationRecorder field_location(containing_type_location, - DescriptorProto::kFieldFieldNumber, - containing_type->field_size()); - - FieldDescriptorProto* field = containing_type->add_field(); - field->set_label(FieldDescriptorProto::LABEL_OPTIONAL); - field->set_oneof_index(oneof_index); - - if (!ParseMessageFieldNoLabel(field, - containing_type->mutable_nested_type(), - containing_type_location, - DescriptorProto::kNestedTypeFieldNumber, - field_location, - containing_file)) { - // This statement failed to parse. Skip it, but keep looping to parse - // other statements. - SkipStatement(); - } - } while (!TryConsumeEndOfDeclaration("}", NULL)); - - return true; -} - -// ------------------------------------------------------------------- -// Enums - -bool Parser::ParseEnumDefinition(EnumDescriptorProto* enum_type, - const LocationRecorder& enum_location, - const FileDescriptorProto* containing_file) { - DO(Consume("enum")); - - { - LocationRecorder location(enum_location, - EnumDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - enum_type, DescriptorPool::ErrorCollector::NAME); - DO(ConsumeIdentifier(enum_type->mutable_name(), "Expected enum name.")); - } - - DO(ParseEnumBlock(enum_type, enum_location, containing_file)); - - DO(ValidateEnum(enum_type)); - - return true; -} - -bool Parser::ParseEnumBlock(EnumDescriptorProto* enum_type, - const LocationRecorder& enum_location, - const FileDescriptorProto* containing_file) { - DO(ConsumeEndOfDeclaration("{", &enum_location)); - - while (!TryConsumeEndOfDeclaration("}", NULL)) { - if (AtEnd()) { - AddError("Reached end of input in enum definition (missing '}')."); - return false; - } - - if (!ParseEnumStatement(enum_type, enum_location, containing_file)) { - // This statement failed to parse. Skip it, but keep looping to parse - // other statements. - SkipStatement(); - } - } - - return true; -} - -bool Parser::ParseEnumStatement(EnumDescriptorProto* enum_type, - const LocationRecorder& enum_location, - const FileDescriptorProto* containing_file) { - if (TryConsumeEndOfDeclaration(";", NULL)) { - // empty statement; ignore - return true; - } else if (LookingAt("option")) { - LocationRecorder location(enum_location, - EnumDescriptorProto::kOptionsFieldNumber); - return ParseOption(enum_type->mutable_options(), location, - containing_file, OPTION_STATEMENT); - } else if (LookingAt("reserved")) { - return ParseReserved(enum_type, enum_location); - } else { - LocationRecorder location(enum_location, - EnumDescriptorProto::kValueFieldNumber, enum_type->value_size()); - return ParseEnumConstant(enum_type->add_value(), location, containing_file); - } -} - -bool Parser::ParseEnumConstant(EnumValueDescriptorProto* enum_value, - const LocationRecorder& enum_value_location, - const FileDescriptorProto* containing_file) { - // Parse name. - { - LocationRecorder location(enum_value_location, - EnumValueDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - enum_value, DescriptorPool::ErrorCollector::NAME); - DO(ConsumeIdentifier(enum_value->mutable_name(), - "Expected enum constant name.")); - } - - DO(Consume("=", "Missing numeric value for enum constant.")); - - // Parse value. - { - LocationRecorder location( - enum_value_location, EnumValueDescriptorProto::kNumberFieldNumber); - location.RecordLegacyLocation( - enum_value, DescriptorPool::ErrorCollector::NUMBER); - - int number; - DO(ConsumeSignedInteger(&number, "Expected integer.")); - enum_value->set_number(number); - } - - DO(ParseEnumConstantOptions(enum_value, enum_value_location, - containing_file)); - - DO(ConsumeEndOfDeclaration(";", &enum_value_location)); - - return true; -} - -bool Parser::ParseEnumConstantOptions( - EnumValueDescriptorProto* value, - const LocationRecorder& enum_value_location, - const FileDescriptorProto* containing_file) { - if (!LookingAt("[")) return true; - - LocationRecorder location( - enum_value_location, EnumValueDescriptorProto::kOptionsFieldNumber); - - DO(Consume("[")); - - do { - DO(ParseOption(value->mutable_options(), location, - containing_file, OPTION_ASSIGNMENT)); - } while (TryConsume(",")); - - DO(Consume("]")); - return true; -} - -// ------------------------------------------------------------------- -// Services - -bool Parser::ParseServiceDefinition( - ServiceDescriptorProto* service, - const LocationRecorder& service_location, - const FileDescriptorProto* containing_file) { - DO(Consume("service")); - - { - LocationRecorder location(service_location, - ServiceDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - service, DescriptorPool::ErrorCollector::NAME); - DO(ConsumeIdentifier(service->mutable_name(), "Expected service name.")); - } - - DO(ParseServiceBlock(service, service_location, containing_file)); - return true; -} - -bool Parser::ParseServiceBlock(ServiceDescriptorProto* service, - const LocationRecorder& service_location, - const FileDescriptorProto* containing_file) { - DO(ConsumeEndOfDeclaration("{", &service_location)); - - while (!TryConsumeEndOfDeclaration("}", NULL)) { - if (AtEnd()) { - AddError("Reached end of input in service definition (missing '}')."); - return false; - } - - if (!ParseServiceStatement(service, service_location, containing_file)) { - // This statement failed to parse. Skip it, but keep looping to parse - // other statements. - SkipStatement(); - } - } - - return true; -} - -bool Parser::ParseServiceStatement(ServiceDescriptorProto* service, - const LocationRecorder& service_location, - const FileDescriptorProto* containing_file) { - if (TryConsumeEndOfDeclaration(";", NULL)) { - // empty statement; ignore - return true; - } else if (LookingAt("option")) { - LocationRecorder location( - service_location, ServiceDescriptorProto::kOptionsFieldNumber); - return ParseOption(service->mutable_options(), location, - containing_file, OPTION_STATEMENT); - } else { - LocationRecorder location(service_location, - ServiceDescriptorProto::kMethodFieldNumber, service->method_size()); - return ParseServiceMethod(service->add_method(), location, containing_file); - } -} - -bool Parser::ParseServiceMethod(MethodDescriptorProto* method, - const LocationRecorder& method_location, - const FileDescriptorProto* containing_file) { - DO(Consume("rpc")); - - { - LocationRecorder location(method_location, - MethodDescriptorProto::kNameFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::NAME); - DO(ConsumeIdentifier(method->mutable_name(), "Expected method name.")); - } - - // Parse input type. - DO(Consume("(")); - { - if (LookingAt("stream")) { - LocationRecorder location( - method_location, MethodDescriptorProto::kClientStreamingFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::OTHER); - method->set_client_streaming(true); - DO(Consume("stream")); - - } - LocationRecorder location(method_location, - MethodDescriptorProto::kInputTypeFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::INPUT_TYPE); - DO(ParseUserDefinedType(method->mutable_input_type())); - } - DO(Consume(")")); - - // Parse output type. - DO(Consume("returns")); - DO(Consume("(")); - { - if (LookingAt("stream")) { - LocationRecorder location( - method_location, MethodDescriptorProto::kServerStreamingFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::OTHER); - DO(Consume("stream")); - method->set_server_streaming(true); - - } - LocationRecorder location(method_location, - MethodDescriptorProto::kOutputTypeFieldNumber); - location.RecordLegacyLocation( - method, DescriptorPool::ErrorCollector::OUTPUT_TYPE); - DO(ParseUserDefinedType(method->mutable_output_type())); - } - DO(Consume(")")); - - if (LookingAt("{")) { - // Options! - DO(ParseMethodOptions(method_location, containing_file, - MethodDescriptorProto::kOptionsFieldNumber, - method->mutable_options())); - } else { - DO(ConsumeEndOfDeclaration(";", &method_location)); - } - - return true; -} - - -bool Parser::ParseMethodOptions(const LocationRecorder& parent_location, - const FileDescriptorProto* containing_file, - const int optionsFieldNumber, - Message* mutable_options) { - // Options! - ConsumeEndOfDeclaration("{", &parent_location); - while (!TryConsumeEndOfDeclaration("}", NULL)) { - if (AtEnd()) { - AddError("Reached end of input in method options (missing '}')."); - return false; - } - - if (TryConsumeEndOfDeclaration(";", NULL)) { - // empty statement; ignore - } else { - LocationRecorder location(parent_location, - optionsFieldNumber); - if (!ParseOption(mutable_options, location, - containing_file, OPTION_STATEMENT)) { - // This statement failed to parse. Skip it, but keep looping to - // parse other statements. - SkipStatement(); - } - } - } - - return true; -} - -// ------------------------------------------------------------------- - -bool Parser::ParseLabel(FieldDescriptorProto::Label* label, - const FileDescriptorProto* containing_file) { - if (TryConsume("optional")) { - *label = FieldDescriptorProto::LABEL_OPTIONAL; - return true; - } else if (TryConsume("repeated")) { - *label = FieldDescriptorProto::LABEL_REPEATED; - return true; - } else if (TryConsume("required")) { - *label = FieldDescriptorProto::LABEL_REQUIRED; - return true; - } - return false; -} - -bool Parser::ParseType(FieldDescriptorProto::Type* type, - string* type_name) { - TypeNameMap::const_iterator iter = kTypeNames.find(input_->current().text); - if (iter != kTypeNames.end()) { - *type = iter->second; - input_->Next(); - } else { - DO(ParseUserDefinedType(type_name)); - } - return true; -} - -bool Parser::ParseUserDefinedType(string* type_name) { - type_name->clear(); - - TypeNameMap::const_iterator iter = kTypeNames.find(input_->current().text); - if (iter != kTypeNames.end()) { - // Note: The only place enum types are allowed is for field types, but - // if we are parsing a field type then we would not get here because - // primitives are allowed there as well. So this error message doesn't - // need to account for enums. - AddError("Expected message type."); - - // Pretend to accept this type so that we can go on parsing. - *type_name = input_->current().text; - input_->Next(); - return true; - } - - // A leading "." means the name is fully-qualified. - if (TryConsume(".")) type_name->append("."); - - // Consume the first part of the name. - string identifier; - DO(ConsumeIdentifier(&identifier, "Expected type name.")); - type_name->append(identifier); - - // Consume more parts. - while (TryConsume(".")) { - type_name->append("."); - DO(ConsumeIdentifier(&identifier, "Expected identifier.")); - type_name->append(identifier); - } - - return true; -} - -// =================================================================== - -bool Parser::ParsePackage(FileDescriptorProto* file, - const LocationRecorder& root_location, - const FileDescriptorProto* containing_file) { - if (file->has_package()) { - AddError("Multiple package definitions."); - // Don't append the new package to the old one. Just replace it. Not - // that it really matters since this is an error anyway. - file->clear_package(); - } - - DO(Consume("package")); - - { - LocationRecorder location(root_location, - FileDescriptorProto::kPackageFieldNumber); - location.RecordLegacyLocation(file, DescriptorPool::ErrorCollector::NAME); - - while (true) { - string identifier; - DO(ConsumeIdentifier(&identifier, "Expected identifier.")); - file->mutable_package()->append(identifier); - if (!TryConsume(".")) break; - file->mutable_package()->append("."); - } - - location.EndAt(input_->previous()); - - DO(ConsumeEndOfDeclaration(";", &location)); - } - - return true; -} - -bool Parser::ParseImport(RepeatedPtrField* dependency, - RepeatedField* public_dependency, - RepeatedField* weak_dependency, - const LocationRecorder& root_location, - const FileDescriptorProto* containing_file) { - DO(Consume("import")); - if (LookingAt("public")) { - LocationRecorder location( - root_location, FileDescriptorProto::kPublicDependencyFieldNumber, - public_dependency->size()); - DO(Consume("public")); - *public_dependency->Add() = dependency->size(); - } else if (LookingAt("weak")) { - LocationRecorder location( - root_location, FileDescriptorProto::kWeakDependencyFieldNumber, - weak_dependency->size()); - DO(Consume("weak")); - *weak_dependency->Add() = dependency->size(); - } - { - LocationRecorder location(root_location, - FileDescriptorProto::kDependencyFieldNumber, - dependency->size()); - DO(ConsumeString(dependency->Add(), - "Expected a string naming the file to import.")); - - location.EndAt(input_->previous()); - - DO(ConsumeEndOfDeclaration(";", &location)); - } - return true; -} - -// =================================================================== - -SourceLocationTable::SourceLocationTable() {} -SourceLocationTable::~SourceLocationTable() {} - -bool SourceLocationTable::Find( - const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - int* line, int* column) const { - const std::pair* result = - FindOrNull(location_map_, std::make_pair(descriptor, location)); - if (result == NULL) { - *line = -1; - *column = 0; - return false; - } else { - *line = result->first; - *column = result->second; - return true; - } -} - -void SourceLocationTable::Add( - const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - int line, int column) { - location_map_[std::make_pair(descriptor, location)] = - std::make_pair(line, column); -} - -void SourceLocationTable::Clear() { - location_map_.clear(); -} - -} // namespace compiler -} // namespace protobuf - -} // namespace google diff --git a/windows/include/google/protobuf/compiler/parser.h b/windows/include/google/protobuf/compiler/parser.h index 5d98e5e18..b5a5df899 100644 --- a/windows/include/google/protobuf/compiler/parser.h +++ b/windows/include/google/protobuf/compiler/parser.h @@ -37,18 +37,24 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_PARSER_H__ #define GOOGLE_PROTOBUF_COMPILER_PARSER_H__ +#include #include #include #include + #include #include #include #include -namespace google { -namespace protobuf { class Message; } +// Must be included last. +#include +namespace google { namespace protobuf { + +class Message; + namespace compiler { // Defined in this file. @@ -62,7 +68,7 @@ class SourceLocationTable; // to a FileDescriptorProto. It does not resolve import directives or perform // many other kinds of validation needed to construct a complete // FileDescriptor. -class LIBPROTOBUF_EXPORT Parser { +class PROTOBUF_EXPORT Parser { public: Parser(); ~Parser(); @@ -92,7 +98,7 @@ class LIBPROTOBUF_EXPORT Parser { // Returns the identifier used in the "syntax = " declaration, if one was // seen during the last call to Parse(), or the empty string otherwise. - const string& GetSyntaxIdentifier() { return syntax_identifier_; } + const std::string& GetSyntaxIdentifier() { return syntax_identifier_; } // If set true, input files will be required to begin with a syntax // identifier. Otherwise, files may omit this. If a syntax identifier @@ -162,19 +168,20 @@ class LIBPROTOBUF_EXPORT Parser { // where "text" is the expected token text. bool Consume(const char* text); // Consume a token of type IDENTIFIER and store its text in "output". - bool ConsumeIdentifier(string* output, const char* error); + bool ConsumeIdentifier(std::string* output, const char* error); // Consume an integer and store its value in "output". bool ConsumeInteger(int* output, const char* error); // Consume a signed integer and store its value in "output". bool ConsumeSignedInteger(int* output, const char* error); // Consume a 64-bit integer and store its value in "output". If the value // is greater than max_value, an error will be reported. - bool ConsumeInteger64(uint64 max_value, uint64* output, const char* error); + bool ConsumeInteger64(uint64_t max_value, uint64_t* output, + const char* error); // 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); // Consume a string literal and store its (unescaped) value in "output". - bool ConsumeString(string* output, const char* error); + bool ConsumeString(std::string* output, const char* error); // Consume a token representing the end of the statement. Comments between // this token and the next will be harvested for documentation. The given @@ -185,30 +192,34 @@ class LIBPROTOBUF_EXPORT Parser { // have been passed around by const reference, for no particularly good // reason. We should probably go through and change them all to mutable // pointer to make this more intuitive. - bool TryConsumeEndOfDeclaration( - const char* text, const LocationRecorder* location); - bool TryConsumeEndOfDeclarationFinishScope( - const char* text, const LocationRecorder* location); + bool TryConsumeEndOfDeclaration(const char* text, + const LocationRecorder* location); + bool TryConsumeEndOfDeclarationFinishScope(const char* text, + const LocationRecorder* location); - bool ConsumeEndOfDeclaration( - const char* text, const LocationRecorder* location); + bool ConsumeEndOfDeclaration(const char* text, + const LocationRecorder* location); // ----------------------------------------------------------------- // Error logging helpers // Invokes error_collector_->AddError(), if error_collector_ is not NULL. - void AddError(int line, int column, const string& error); + void AddError(int line, int column, const std::string& error); // Invokes error_collector_->AddError() with the line and column number // of the current token. - void AddError(const string& error); + void AddError(const std::string& error); + + // Invokes error_collector_->AddWarning() with the line and column number + // of the current token. + void AddWarning(const std::string& warning); // Records a location in the SourceCodeInfo.location table (see // descriptor.proto). We use RAII to ensure that the start and end locations // are recorded -- the constructor records the start location and the // destructor records the end location. Since the parser is // recursive-descent, this works out beautifully. - class LIBPROTOBUF_EXPORT LocationRecorder { + class PROTOBUF_EXPORT LocationRecorder { public: // Construct the file's "root" location. LocationRecorder(Parser* parser); @@ -226,7 +237,7 @@ class LIBPROTOBUF_EXPORT Parser { // Creates a recorder that generates locations into given source code info. LocationRecorder(const LocationRecorder& parent, int path1, - SourceCodeInfo* source_code_info); + SourceCodeInfo* source_code_info); ~LocationRecorder(); @@ -251,8 +262,11 @@ class LIBPROTOBUF_EXPORT Parser { // was passed to RecordSourceLocationsTo(), if any. SourceLocationTable // is an older way of keeping track of source locations which is still // used in some places. - void RecordLegacyLocation(const Message* descriptor, + void RecordLegacyLocation( + const Message* descriptor, DescriptorPool::ErrorCollector::ErrorLocation location); + void RecordLegacyImportLocation(const Message* descriptor, + const std::string& name); // Returns the number of path components in the recorder's current location. int CurrentPathSize() const; @@ -263,8 +277,8 @@ class LIBPROTOBUF_EXPORT Parser { // // TODO(kenton): See comment on TryConsumeEndOfDeclaration(), above, for // why this is const. - void AttachComments(string* leading, string* trailing, - std::vector* detached_comments) const; + void AttachComments(std::string* leading, std::string* trailing, + std::vector* detached_comments) const; private: // Indexes of parent and current location in the parent @@ -312,9 +326,9 @@ class LIBPROTOBUF_EXPORT Parser { bool ParsePackage(FileDescriptorProto* file, const LocationRecorder& root_location, const FileDescriptorProto* containing_file); - bool ParseImport(RepeatedPtrField* dependency, - RepeatedField* public_dependency, - RepeatedField* weak_dependency, + bool ParseImport(RepeatedPtrField* dependency, + RepeatedField* public_dependency, + RepeatedField* weak_dependency, const LocationRecorder& root_location, const FileDescriptorProto* containing_file); @@ -399,8 +413,7 @@ class LIBPROTOBUF_EXPORT Parser { // oneof_decl->label() since it will have had to parse the label before it // knew it was parsing a oneof. bool ParseOneof(OneofDescriptorProto* oneof_decl, - DescriptorProto* containing_type, - int oneof_index, + DescriptorProto* containing_type, int oneof_index, const LocationRecorder& oneof_location, const LocationRecorder& containing_type_location, const FileDescriptorProto* containing_file); @@ -431,15 +444,15 @@ class LIBPROTOBUF_EXPORT Parser { // Parse "required", "optional", or "repeated" and fill in "label" // with the value. Returns true if such a label is consumed. bool ParseLabel(FieldDescriptorProto::Label* label, + const LocationRecorder& field_location, const FileDescriptorProto* containing_file); // Parse a type name and fill in "type" (if it is a primitive) or // "type_name" (if it is not) with the type parsed. - bool ParseType(FieldDescriptorProto::Type* type, - string* type_name); + bool ParseType(FieldDescriptorProto::Type* type, std::string* type_name); // Parse a user-defined type and fill in "type_name" with the name. // If a primitive type is named, it is treated as an error. - bool ParseUserDefinedType(string* type_name); + bool ParseUserDefinedType(std::string* type_name); // Parses field options, i.e. the stuff in square brackets at the end // of a field definition. Also parses default value. @@ -465,8 +478,7 @@ class LIBPROTOBUF_EXPORT Parser { // Parse a single option name/value pair, e.g. "ctype = CORD". The name // identifies a field of the given Message, and the value of that field // is set to the parsed value. - bool ParseOption(Message* options, - const LocationRecorder& options_location, + bool ParseOption(Message* options, const LocationRecorder& options_location, const FileDescriptorProto* containing_file, OptionStyle style); @@ -488,7 +500,7 @@ class LIBPROTOBUF_EXPORT Parser { // REQUIRES: LookingAt("{") // When finished successfully, we are looking at the first token past // the ending brace. - bool ParseUninterpretedBlock(string* value); + bool ParseUninterpretedBlock(std::string* value); struct MapField { // Whether the field is a map field. @@ -497,8 +509,8 @@ class LIBPROTOBUF_EXPORT Parser { FieldDescriptorProto::Type key_type; FieldDescriptorProto::Type value_type; // Or the type names string if the types are customized types. - string key_type_name; - string value_type_name; + std::string key_type_name; + std::string value_type_name; MapField() : is_map_field(false) {} }; @@ -511,7 +523,6 @@ class LIBPROTOBUF_EXPORT Parser { return syntax_identifier_ == "proto3"; } - bool ValidateEnum(const EnumDescriptorProto* proto); // ================================================================= @@ -523,18 +534,18 @@ class LIBPROTOBUF_EXPORT Parser { bool had_errors_; bool require_syntax_identifier_; bool stop_after_syntax_identifier_; - string syntax_identifier_; + std::string syntax_identifier_; // Leading doc comments for the next declaration. These are not complete // yet; use ConsumeEndOfDeclaration() to get the complete comments. - string upcoming_doc_comments_; + std::string upcoming_doc_comments_; // Detached comments are not connected to any syntax entities. Elements in // this vector are paragraphs of comments separated by empty lines. The // detached comments will be put into the leading_detached_comments field for // the next element (See SourceCodeInfo.Location in descriptor.proto), when // ConsumeEndOfDeclaration() is called. - std::vector upcoming_detached_comments_; + std::vector upcoming_detached_comments_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Parser); }; @@ -547,7 +558,7 @@ class LIBPROTOBUF_EXPORT Parser { // far more complete information about source locations. However, as of this // writing you still need to use SourceLocationTable when integrating with // DescriptorPool. -class LIBPROTOBUF_EXPORT SourceLocationTable { +class PROTOBUF_EXPORT SourceLocationTable { public: SourceLocationTable(); ~SourceLocationTable(); @@ -558,26 +569,35 @@ class LIBPROTOBUF_EXPORT SourceLocationTable { // location" in the ErrorCollector interface). Returns true if found, false // otherwise. bool Find(const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - int* line, int* column) const; + DescriptorPool::ErrorCollector::ErrorLocation location, int* line, + int* column) const; + bool FindImport(const Message* descriptor, const std::string& name, int* line, + int* column) const; // Adds a location to the table. void Add(const Message* descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - int line, int column); + DescriptorPool::ErrorCollector::ErrorLocation location, int line, + int column); + void AddImport(const Message* descriptor, const std::string& name, int line, + int column); // Clears the contents of the table. void Clear(); private: typedef std::map< - std::pair, - std::pair > LocationMap; + std::pair, + std::pair > + LocationMap; LocationMap location_map_; + std::map, std::pair > + import_location_map_; }; } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PARSER_H__ diff --git a/windows/include/google/protobuf/compiler/parser_unittest.cc b/windows/include/google/protobuf/compiler/parser_unittest.cc deleted file mode 100644 index 0725a6822..000000000 --- a/windows/include/google/protobuf/compiler/parser_unittest.cc +++ /dev/null @@ -1,3375 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { - -namespace { - -class MockErrorCollector : public io::ErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - - // implements ErrorCollector --------------------------------------- - void AddError(int line, int column, const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", - line, column, message); - } -}; - -class MockValidationErrorCollector : public DescriptorPool::ErrorCollector { - public: - MockValidationErrorCollector(const SourceLocationTable& source_locations, - io::ErrorCollector* wrapped_collector) - : source_locations_(source_locations), - wrapped_collector_(wrapped_collector) {} - ~MockValidationErrorCollector() {} - - // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, - const string& element_name, - const Message* descriptor, - ErrorLocation location, - const string& message) { - int line, column; - source_locations_.Find(descriptor, location, &line, &column); - wrapped_collector_->AddError(line, column, message); - } - - private: - const SourceLocationTable& source_locations_; - io::ErrorCollector* wrapped_collector_; -}; - -class ParserTest : public testing::Test { - protected: - ParserTest() - : require_syntax_identifier_(false) {} - - // Set up the parser to parse the given text. - void SetupParser(const char* text) { - raw_input_.reset(new io::ArrayInputStream(text, strlen(text))); - input_.reset(new io::Tokenizer(raw_input_.get(), &error_collector_)); - parser_.reset(new Parser()); - parser_->RecordErrorsTo(&error_collector_); - parser_->SetRequireSyntaxIdentifier(require_syntax_identifier_); - } - - // Parse the input and expect that the resulting FileDescriptorProto matches - // the given output. The output is a FileDescriptorProto in protocol buffer - // text format. - void ExpectParsesTo(const char* input, const char* output) { - SetupParser(input); - FileDescriptorProto actual, expected; - - parser_->Parse(input_.get(), &actual); - EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - ASSERT_EQ("", error_collector_.text_); - - // We don't cover SourceCodeInfo in these tests. - actual.clear_source_code_info(); - - // Parse the ASCII representation in order to canonicalize it. We could - // just compare directly to actual.DebugString(), but that would require - // that the caller precisely match the formatting that DebugString() - // produces. - ASSERT_TRUE(TextFormat::ParseFromString(output, &expected)); - - // Compare by comparing debug strings. - // TODO(kenton): Use differencer, once it is available. - EXPECT_EQ(expected.DebugString(), actual.DebugString()); - } - - // Parse the text and expect that the given errors are reported. - void ExpectHasErrors(const char* text, const char* expected_errors) { - ExpectHasEarlyExitErrors(text, expected_errors); - EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - } - - // Same as above but does not expect that the parser parses the complete - // input. - void ExpectHasEarlyExitErrors(const char* text, const char* expected_errors) { - SetupParser(text); - FileDescriptorProto file; - parser_->Parse(input_.get(), &file); - EXPECT_EQ(expected_errors, error_collector_.text_); - } - - // Parse the text as a file and validate it (with a DescriptorPool), and - // expect that the validation step reports the given errors. - void ExpectHasValidationErrors(const char* text, - const char* expected_errors) { - SetupParser(text); - SourceLocationTable source_locations; - parser_->RecordSourceLocationsTo(&source_locations); - - FileDescriptorProto file; - file.set_name("foo.proto"); - parser_->Parse(input_.get(), &file); - EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - ASSERT_EQ("", error_collector_.text_); - - MockValidationErrorCollector validation_error_collector( - source_locations, &error_collector_); - EXPECT_TRUE(pool_.BuildFileCollectingErrors( - file, &validation_error_collector) == NULL); - EXPECT_EQ(expected_errors, error_collector_.text_); - } - - MockErrorCollector error_collector_; - DescriptorPool pool_; - - std::unique_ptr raw_input_; - std::unique_ptr input_; - std::unique_ptr parser_; - bool require_syntax_identifier_; -}; - -// =================================================================== - -TEST_F(ParserTest, StopAfterSyntaxIdentifier) { - SetupParser( - "// blah\n" - "syntax = \"foobar\";\n" - "this line will not be parsed\n"); - parser_->SetStopAfterSyntaxIdentifier(true); - EXPECT_TRUE(parser_->Parse(input_.get(), NULL)); - EXPECT_EQ("", error_collector_.text_); - EXPECT_EQ("foobar", parser_->GetSyntaxIdentifier()); -} - -TEST_F(ParserTest, StopAfterOmittedSyntaxIdentifier) { - SetupParser( - "// blah\n" - "this line will not be parsed\n"); - parser_->SetStopAfterSyntaxIdentifier(true); - EXPECT_TRUE(parser_->Parse(input_.get(), NULL)); - EXPECT_EQ("", error_collector_.text_); - EXPECT_EQ("", parser_->GetSyntaxIdentifier()); -} - -TEST_F(ParserTest, StopAfterSyntaxIdentifierWithErrors) { - SetupParser( - "// blah\n" - "syntax = error;\n"); - parser_->SetStopAfterSyntaxIdentifier(true); - EXPECT_FALSE(parser_->Parse(input_.get(), NULL)); - EXPECT_EQ("1:9: Expected syntax identifier.\n", error_collector_.text_); -} - -TEST_F(ParserTest, WarnIfSyntaxIdentifierOmmitted) { - SetupParser("message A {}"); - FileDescriptorProto file; - CaptureTestStderr(); - EXPECT_TRUE(parser_->Parse(input_.get(), &file)); - EXPECT_TRUE( - GetCapturedTestStderr().find("No syntax specified") != string::npos); -} - -// =================================================================== - -typedef ParserTest ParseMessageTest; - -TEST_F(ParseMessageTest, IgnoreBOM) { - char input[] = " message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n"; - // Set UTF-8 BOM. - input[0] = (char)0xEF; - input[1] = (char)0xBB; - input[2] = (char)0xBF; - ExpectParsesTo(input, - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); -} - -TEST_F(ParseMessageTest, BOMError) { - char input[] = " message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n"; - input[0] = (char)0xEF; - ExpectHasErrors(input, - "0:1: Proto file starts with 0xEF but not UTF-8 BOM. " - "Only UTF-8 is accepted for proto file.\n" - "0:0: Expected top-level statement (e.g. \"message\").\n"); -} - -TEST_F(ParseMessageTest, SimpleMessage) { - ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); -} - -TEST_F(ParseMessageTest, ImplicitSyntaxIdentifier) { - require_syntax_identifier_ = false; - ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); - EXPECT_EQ("proto2", parser_->GetSyntaxIdentifier()); -} - -TEST_F(ParseMessageTest, ExplicitSyntaxIdentifier) { - ExpectParsesTo( - "syntax = \"proto2\";\n" - "message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n", - - "syntax: 'proto2' " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); - EXPECT_EQ("proto2", parser_->GetSyntaxIdentifier()); -} - -TEST_F(ParseMessageTest, ExplicitRequiredSyntaxIdentifier) { - require_syntax_identifier_ = true; - ExpectParsesTo( - "syntax = \"proto2\";\n" - "message TestMessage {\n" - " required int32 foo = 1;\n" - "}\n", - - "syntax: 'proto2' " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - "}"); - EXPECT_EQ("proto2", parser_->GetSyntaxIdentifier()); -} - -TEST_F(ParseMessageTest, SimpleFields) { - ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 15;\n" - " optional int32 bar = 34;\n" - " repeated int32 baz = 3;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:15 }" - " field { name:\"bar\" label:LABEL_OPTIONAL type:TYPE_INT32 number:34 }" - " field { name:\"baz\" label:LABEL_REPEATED type:TYPE_INT32 number:3 }" - "}"); -} - -TEST_F(ParseMessageTest, PrimitiveFieldTypes) { - ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1;\n" - " required int64 foo = 1;\n" - " required uint32 foo = 1;\n" - " required uint64 foo = 1;\n" - " required sint32 foo = 1;\n" - " required sint64 foo = 1;\n" - " required fixed32 foo = 1;\n" - " required fixed64 foo = 1;\n" - " required sfixed32 foo = 1;\n" - " required sfixed64 foo = 1;\n" - " required float foo = 1;\n" - " required double foo = 1;\n" - " required string foo = 1;\n" - " required bytes foo = 1;\n" - " required bool foo = 1;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_UINT32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_UINT64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SINT32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SINT64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FIXED32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FIXED64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SFIXED32 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_SFIXED64 number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_FLOAT number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_DOUBLE number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_STRING number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_BYTES number:1 }" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_BOOL number:1 }" - "}"); -} - -TEST_F(ParseMessageTest, FieldDefaults) { - ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1 [default= 1 ];\n" - " required int32 foo = 1 [default= -2 ];\n" - " required int64 foo = 1 [default= 3 ];\n" - " required int64 foo = 1 [default= -4 ];\n" - " required uint32 foo = 1 [default= 5 ];\n" - " required uint64 foo = 1 [default= 6 ];\n" - " required float foo = 1 [default= 7.5];\n" - " required float foo = 1 [default= -8.5];\n" - " required float foo = 1 [default= 9 ];\n" - " required double foo = 1 [default= 10.5];\n" - " required double foo = 1 [default=-11.5];\n" - " required double foo = 1 [default= 12 ];\n" - " required double foo = 1 [default= inf ];\n" - " required double foo = 1 [default=-inf ];\n" - " required double foo = 1 [default= nan ];\n" - " required string foo = 1 [default='13\\001'];\n" - " required string foo = 1 [default='a' \"b\" \n \"c\"];\n" - " required bytes foo = 1 [default='14\\002'];\n" - " required bytes foo = 1 [default='a' \"b\" \n 'c'];\n" - " required bool foo = 1 [default=true ];\n" - " required Foo foo = 1 [default=FOO ];\n" - - " required int32 foo = 1 [default= 0x7FFFFFFF];\n" - " required int32 foo = 1 [default=-0x80000000];\n" - " required uint32 foo = 1 [default= 0xFFFFFFFF];\n" - " required int64 foo = 1 [default= 0x7FFFFFFFFFFFFFFF];\n" - " required int64 foo = 1 [default=-0x8000000000000000];\n" - " required uint64 foo = 1 [default= 0xFFFFFFFFFFFFFFFF];\n" - " required double foo = 1 [default= 0xabcd];\n" - "}\n", - -#define ETC "name:\"foo\" label:LABEL_REQUIRED number:1" - "message_type {" - " name: \"TestMessage\"" - " field { type:TYPE_INT32 default_value:\"1\" " ETC " }" - " field { type:TYPE_INT32 default_value:\"-2\" " ETC " }" - " field { type:TYPE_INT64 default_value:\"3\" " ETC " }" - " field { type:TYPE_INT64 default_value:\"-4\" " ETC " }" - " field { type:TYPE_UINT32 default_value:\"5\" " ETC " }" - " field { type:TYPE_UINT64 default_value:\"6\" " ETC " }" - " field { type:TYPE_FLOAT default_value:\"7.5\" " ETC " }" - " field { type:TYPE_FLOAT default_value:\"-8.5\" " ETC " }" - " field { type:TYPE_FLOAT default_value:\"9\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"10.5\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"-11.5\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"12\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"inf\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"-inf\" " ETC " }" - " field { type:TYPE_DOUBLE default_value:\"nan\" " ETC " }" - " field { type:TYPE_STRING default_value:\"13\\001\" " ETC " }" - " field { type:TYPE_STRING default_value:\"abc\" " ETC " }" - " field { type:TYPE_BYTES default_value:\"14\\\\002\" " ETC " }" - " field { type:TYPE_BYTES default_value:\"abc\" " ETC " }" - " field { type:TYPE_BOOL default_value:\"true\" " ETC " }" - " field { type_name:\"Foo\" default_value:\"FOO\" " ETC " }" - - " field {" - " type:TYPE_INT32 default_value:\"2147483647\" " ETC - " }" - " field {" - " type:TYPE_INT32 default_value:\"-2147483648\" " ETC - " }" - " field {" - " type:TYPE_UINT32 default_value:\"4294967295\" " ETC - " }" - " field {" - " type:TYPE_INT64 default_value:\"9223372036854775807\" " ETC - " }" - " field {" - " type:TYPE_INT64 default_value:\"-9223372036854775808\" " ETC - " }" - " field {" - " type:TYPE_UINT64 default_value:\"18446744073709551615\" " ETC - " }" - " field {" - " type:TYPE_DOUBLE default_value:\"43981\" " ETC - " }" - "}"); -#undef ETC -} - -TEST_F(ParseMessageTest, FieldJsonName) { - ExpectParsesTo( - "message TestMessage {\n" - " optional string foo = 1 [json_name = \"@type\"];\n" - "}\n", - "message_type {" - " name: \"TestMessage\"" - " field {\n" - " name: \"foo\" label: LABEL_OPTIONAL type: TYPE_STRING number: 1" - " json_name: \"@type\"\n" - " }\n" - "}\n"); -} - -TEST_F(ParseMessageTest, FieldOptions) { - ExpectParsesTo( - "message TestMessage {\n" - " optional string foo = 1\n" - " [ctype=CORD, (foo)=7, foo.(.bar.baz).qux.quux.(corge)=-33, \n" - " (quux)=\"x\040y\", (baz.qux)=hey];\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " field { name: \"foo\" label: LABEL_OPTIONAL type: TYPE_STRING number: 1" - " options { uninterpreted_option: { name { name_part: \"ctype\" " - " is_extension: false } " - " identifier_value: \"CORD\" }" - " uninterpreted_option: { name { name_part: \"foo\" " - " is_extension: true } " - " positive_int_value: 7 }" - " uninterpreted_option: { name { name_part: \"foo\" " - " is_extension: false } " - " name { name_part: \".bar.baz\"" - " is_extension: true } " - " name { name_part: \"qux\" " - " is_extension: false } " - " name { name_part: \"quux\" " - " is_extension: false } " - " name { name_part: \"corge\" " - " is_extension: true } " - " negative_int_value: -33 }" - " uninterpreted_option: { name { name_part: \"quux\" " - " is_extension: true } " - " string_value: \"x y\" }" - " uninterpreted_option: { name { name_part: \"baz.qux\" " - " is_extension: true } " - " identifier_value: \"hey\" }" - " }" - " }" - "}"); -} - -TEST_F(ParseMessageTest, Oneof) { - ExpectParsesTo( - "message TestMessage {\n" - " oneof foo {\n" - " int32 a = 1;\n" - " string b = 2;\n" - " TestMessage c = 3;\n" - " group D = 4 { optional int32 i = 5; }\n" - " }\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " field { name:\"a\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 " - " oneof_index:0 }" - " field { name:\"b\" label:LABEL_OPTIONAL type:TYPE_STRING number:2 " - " oneof_index:0 }" - " field { name:\"c\" label:LABEL_OPTIONAL type_name:\"TestMessage\" " - " number:3 oneof_index:0 }" - " field { name:\"d\" label:LABEL_OPTIONAL type:TYPE_GROUP " - " type_name:\"D\" number:4 oneof_index:0 }" - " oneof_decl {" - " name: \"foo\"" - " }" - " nested_type {" - " name: \"D\"" - " field { name:\"i\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 }" - " }" - "}"); -} - -TEST_F(ParseMessageTest, MultipleOneofs) { - ExpectParsesTo( - "message TestMessage {\n" - " oneof foo {\n" - " int32 a = 1;\n" - " string b = 2;\n" - " }\n" - " oneof bar {\n" - " int32 c = 3;\n" - " string d = 4;\n" - " }\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " field { name:\"a\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 " - " oneof_index:0 }" - " field { name:\"b\" label:LABEL_OPTIONAL type:TYPE_STRING number:2 " - " oneof_index:0 }" - " field { name:\"c\" label:LABEL_OPTIONAL type:TYPE_INT32 number:3 " - " oneof_index:1 }" - " field { name:\"d\" label:LABEL_OPTIONAL type:TYPE_STRING number:4 " - " oneof_index:1 }" - " oneof_decl {" - " name: \"foo\"" - " }" - " oneof_decl {" - " name: \"bar\"" - " }" - "}"); -} - -TEST_F(ParseMessageTest, Maps) { - ExpectParsesTo( - "message TestMessage {\n" - " map primitive_type_map = 1;\n" - " map composite_type_map = 2;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " nested_type {" - " name: \"PrimitiveTypeMapEntry\"" - " field { " - " name: \"key\" number: 1 label:LABEL_OPTIONAL" - " type:TYPE_INT32" - " }" - " field { " - " name: \"value\" number: 2 label:LABEL_OPTIONAL" - " type:TYPE_STRING" - " }" - " options { map_entry: true }" - " }" - " nested_type {" - " name: \"CompositeTypeMapEntry\"" - " field { " - " name: \"key\" number: 1 label:LABEL_OPTIONAL" - " type_name: \"KeyType\"" - " }" - " field { " - " name: \"value\" number: 2 label:LABEL_OPTIONAL" - " type_name: \"ValueType\"" - " }" - " options { map_entry: true }" - " }" - " field {" - " name: \"primitive_type_map\"" - " label: LABEL_REPEATED" - " type_name: \"PrimitiveTypeMapEntry\"" - " number: 1" - " }" - " field {" - " name: \"composite_type_map\"" - " label: LABEL_REPEATED" - " type_name: \"CompositeTypeMapEntry\"" - " number: 2" - " }" - "}"); -} - -TEST_F(ParseMessageTest, Group) { - ExpectParsesTo( - "message TestMessage {\n" - " optional group TestGroup = 1 {};\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " nested_type { name: \"TestGroup\" }" - " field { name:\"testgroup\" label:LABEL_OPTIONAL number:1" - " type:TYPE_GROUP type_name: \"TestGroup\" }" - "}"); -} - -TEST_F(ParseMessageTest, NestedMessage) { - ExpectParsesTo( - "message TestMessage {\n" - " message Nested {}\n" - " optional Nested test_nested = 1;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " nested_type { name: \"Nested\" }" - " field { name:\"test_nested\" label:LABEL_OPTIONAL number:1" - " type_name: \"Nested\" }" - "}"); -} - -TEST_F(ParseMessageTest, NestedEnum) { - ExpectParsesTo( - "message TestMessage {\n" - " enum NestedEnum {}\n" - " optional NestedEnum test_enum = 1;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " enum_type { name: \"NestedEnum\" }" - " field { name:\"test_enum\" label:LABEL_OPTIONAL number:1" - " type_name: \"NestedEnum\" }" - "}"); -} - -TEST_F(ParseMessageTest, ReservedRange) { - ExpectParsesTo( - "message TestMessage {\n" - " required int32 foo = 1;\n" - " reserved 2, 15, 9 to 11, 3, 20 to max;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_REQUIRED type:TYPE_INT32 number:1 }" - " reserved_range { start:2 end:3 }" - " reserved_range { start:15 end:16 }" - " reserved_range { start:9 end:12 }" - " reserved_range { start:3 end:4 }" - " reserved_range { start:20 end:536870912 }" - "}"); -} - -TEST_F(ParseMessageTest, ReservedRangeOnMessageSet) { - ExpectParsesTo( - "message TestMessage {\n" - " option message_set_wire_format = true;\n" - " reserved 20 to max;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"message_set_wire_format\"" - " is_extension: false" - " }" - " identifier_value: \"true\"" - " }" - " }" - " reserved_range { start:20 end:2147483647 }" - "}"); -} - -TEST_F(ParseMessageTest, ReservedNames) { - ExpectParsesTo( - "message TestMessage {\n" - " reserved \"foo\", \"bar\";\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " reserved_name: \"foo\"" - " reserved_name: \"bar\"" - "}"); -} - -TEST_F(ParseMessageTest, ExtensionRange) { - ExpectParsesTo( - "message TestMessage {\n" - " extensions 10 to 19;\n" - " extensions 30 to max;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " extension_range { start:10 end:20 }" - " extension_range { start:30 end:536870912 }" - "}"); -} - -TEST_F(ParseMessageTest, ExtensionRangeWithOptions) { - ExpectParsesTo( - "message TestMessage {\n" - " extensions 10 to 19 [(i) = 5];\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " extension_range {" - " start:10" - " end:20" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - "}"); -} - -TEST_F(ParseMessageTest, CompoundExtensionRange) { - ExpectParsesTo( - "message TestMessage {\n" - " extensions 2, 15, 9 to 11, 100 to max, 3;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " extension_range { start:2 end:3 }" - " extension_range { start:15 end:16 }" - " extension_range { start:9 end:12 }" - " extension_range { start:100 end:536870912 }" - " extension_range { start:3 end:4 }" - "}"); -} - -TEST_F(ParseMessageTest, CompoundExtensionRangeWithOptions) { - ExpectParsesTo( - "message TestMessage {\n" - " extensions 2, 15, 9 to 11, 100 to max, 3 [(i) = 5];\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " extension_range {" - " start:2" - " end:3" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - " extension_range {" - " start:15" - " end:16" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - " extension_range {" - " start:9" - " end:12" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - " extension_range {" - " start:100" - " end:536870912" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - " extension_range {" - " start:3" - " end:4" - " options {" - " uninterpreted_option {" - " name {" - " name_part: \"i\"" - " is_extension: true" - " }" - " positive_int_value: 5" - " }" - " }" - " }" - "}"); -} - -TEST_F(ParseMessageTest, LargerMaxForMessageSetWireFormatMessages) { - // Messages using the message_set_wire_format option can accept larger - // extension numbers, as the numbers are not encoded as int32 field values - // rather than tags. - ExpectParsesTo( - "message TestMessage {\n" - " extensions 4 to max;\n" - " option message_set_wire_format = true;\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " extension_range { start:4 end: 0x7fffffff }" - " options {\n" - " uninterpreted_option { \n" - " name {\n" - " name_part: \"message_set_wire_format\"\n" - " is_extension: false\n" - " }\n" - " identifier_value: \"true\"\n" - " }\n" - " }\n" - "}"); -} - -TEST_F(ParseMessageTest, Extensions) { - ExpectParsesTo( - "extend Extendee1 { optional int32 foo = 12; }\n" - "extend Extendee2 { repeated TestMessage bar = 22; }\n", - - "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:12" - " extendee: \"Extendee1\" } " - "extension { name:\"bar\" label:LABEL_REPEATED number:22" - " type_name:\"TestMessage\" extendee: \"Extendee2\" }"); -} - -TEST_F(ParseMessageTest, ExtensionsInMessageScope) { - ExpectParsesTo( - "message TestMessage {\n" - " extend Extendee1 { optional int32 foo = 12; }\n" - " extend Extendee2 { repeated TestMessage bar = 22; }\n" - "}\n", - - "message_type {" - " name: \"TestMessage\"" - " extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:12" - " extendee: \"Extendee1\" }" - " extension { name:\"bar\" label:LABEL_REPEATED number:22" - " type_name:\"TestMessage\" extendee: \"Extendee2\" }" - "}"); -} - -TEST_F(ParseMessageTest, MultipleExtensionsOneExtendee) { - ExpectParsesTo( - "extend Extendee1 {\n" - " optional int32 foo = 12;\n" - " repeated TestMessage bar = 22;\n" - "}\n", - - "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:12" - " extendee: \"Extendee1\" } " - "extension { name:\"bar\" label:LABEL_REPEATED number:22" - " type_name:\"TestMessage\" extendee: \"Extendee1\" }"); -} - -TEST_F(ParseMessageTest, OptionalLabelProto3) { - ExpectParsesTo( - "syntax = \"proto3\";\n" - "message TestMessage {\n" - " int32 foo = 1;\n" - "}\n", - - "syntax: \"proto3\" " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 } }"); -} - -// =================================================================== - -typedef ParserTest ParseEnumTest; - -TEST_F(ParseEnumTest, SimpleEnum) { - ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 0;\n" - "}\n", - - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"FOO\" number:0 }" - "}"); -} - -TEST_F(ParseEnumTest, Values) { - ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 13;\n" - " BAR = -10;\n" - " BAZ = 500;\n" - " HEX_MAX = 0x7FFFFFFF;\n" - " HEX_MIN = -0x80000000;\n" - " INT_MAX = 2147483647;\n" - " INT_MIN = -2147483648;\n" - "}\n", - - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"FOO\" number:13 }" - " value { name:\"BAR\" number:-10 }" - " value { name:\"BAZ\" number:500 }" - " value { name:\"HEX_MAX\" number:2147483647 }" - " value { name:\"HEX_MIN\" number:-2147483648 }" - " value { name:\"INT_MAX\" number:2147483647 }" - " value { name:\"INT_MIN\" number:-2147483648 }" - "}"); -} - -TEST_F(ParseEnumTest, ValueOptions) { - ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 13;\n" - " BAR = -10 [ (something.text) = 'abc' ];\n" - " BAZ = 500 [ (something.text) = 'def', other = 1 ];\n" - "}\n", - - "enum_type {" - " name: \"TestEnum\"" - " value { name: \"FOO\" number: 13 }" - " value { name: \"BAR\" number: -10 " - " options { " - " uninterpreted_option { " - " name { name_part: \"something.text\" is_extension: true } " - " string_value: \"abc\" " - " } " - " } " - " } " - " value { name: \"BAZ\" number: 500 " - " options { " - " uninterpreted_option { " - " name { name_part: \"something.text\" is_extension: true } " - " string_value: \"def\" " - " } " - " uninterpreted_option { " - " name { name_part: \"other\" is_extension: false } " - " positive_int_value: 1 " - " } " - " } " - " } " - "}"); -} - -TEST_F(ParseEnumTest, ReservedRange) { - ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 0;\n" - " reserved -2147483648, -6 to -4, -1 to 1, 2, 15, 9 to 11, 3, 20 to max;\n" - "}\n", - - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"FOO\" number:0 }" - " reserved_range { start:-2147483648 end:-2147483648 }" - " reserved_range { start:-6 end:-4 }" - " reserved_range { start:-1 end:1 }" - " reserved_range { start:2 end:2 }" - " reserved_range { start:15 end:15 }" - " reserved_range { start:9 end:11 }" - " reserved_range { start:3 end:3 }" - " reserved_range { start:20 end:2147483647 }" - "}"); -} - -TEST_F(ParseEnumTest, ReservedNames) { - ExpectParsesTo( - "enum TestEnum {\n" - " FOO = 0;\n" - " reserved \"foo\", \"bar\";\n" - "}\n", - - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"FOO\" number:0 }" - " reserved_name: \"foo\"" - " reserved_name: \"bar\"" - "}"); -} - -// =================================================================== - -typedef ParserTest ParseServiceTest; - -TEST_F(ParseServiceTest, SimpleService) { - ExpectParsesTo( - "service TestService {\n" - " rpc Foo(In) returns (Out);\n" - "}\n", - - "service {" - " name: \"TestService\"" - " method { name:\"Foo\" input_type:\"In\" output_type:\"Out\" }" - "}"); -} - -TEST_F(ParseServiceTest, MethodsAndStreams) { - ExpectParsesTo( - "service TestService {\n" - " rpc Foo(In1) returns (Out1);\n" - " rpc Bar(In2) returns (Out2);\n" - " rpc Baz(In3) returns (Out3);\n" - "}\n", - - "service {" - " name: \"TestService\"" - " method { name:\"Foo\" input_type:\"In1\" output_type:\"Out1\" }" - " method { name:\"Bar\" input_type:\"In2\" output_type:\"Out2\" }" - " method { name:\"Baz\" input_type:\"In3\" output_type:\"Out3\" }" - "}"); -} - - - -// =================================================================== -// imports and packages - -typedef ParserTest ParseMiscTest; - -TEST_F(ParseMiscTest, ParseImport) { - ExpectParsesTo( - "import \"foo/bar/baz.proto\";\n", - "dependency: \"foo/bar/baz.proto\""); -} - -TEST_F(ParseMiscTest, ParseMultipleImports) { - ExpectParsesTo( - "import \"foo.proto\";\n" - "import \"bar.proto\";\n" - "import \"baz.proto\";\n", - "dependency: \"foo.proto\"" - "dependency: \"bar.proto\"" - "dependency: \"baz.proto\""); -} - -TEST_F(ParseMiscTest, ParsePublicImports) { - ExpectParsesTo( - "import \"foo.proto\";\n" - "import public \"bar.proto\";\n" - "import \"baz.proto\";\n" - "import public \"qux.proto\";\n", - "dependency: \"foo.proto\"" - "dependency: \"bar.proto\"" - "dependency: \"baz.proto\"" - "dependency: \"qux.proto\"" - "public_dependency: 1 " - "public_dependency: 3 "); -} - -TEST_F(ParseMiscTest, ParsePackage) { - ExpectParsesTo( - "package foo.bar.baz;\n", - "package: \"foo.bar.baz\""); -} - -TEST_F(ParseMiscTest, ParsePackageWithSpaces) { - ExpectParsesTo( - "package foo . bar. \n" - " baz;\n", - "package: \"foo.bar.baz\""); -} - -// =================================================================== -// options - -TEST_F(ParseMiscTest, ParseFileOptions) { - ExpectParsesTo( - "option java_package = \"com.google.foo\";\n" - "option optimize_for = CODE_SIZE;", - - "options {" - "uninterpreted_option { name { name_part: \"java_package\" " - " is_extension: false }" - " string_value: \"com.google.foo\"} " - "uninterpreted_option { name { name_part: \"optimize_for\" " - " is_extension: false }" - " identifier_value: \"CODE_SIZE\" } " - "}"); -} - -// =================================================================== -// Error tests -// -// There are a very large number of possible errors that the parser could -// report, so it's infeasible to test every single one of them. Instead, -// we test each unique call to AddError() in parser.h. This does not mean -// we are testing every possible error that Parser can generate because -// each variant of the Consume() helper only counts as one unique call to -// AddError(). - -typedef ParserTest ParseErrorTest; - -TEST_F(ParseErrorTest, MissingSyntaxIdentifier) { - require_syntax_identifier_ = true; - ExpectHasEarlyExitErrors("message TestMessage {}", - "0:0: File must begin with a syntax statement, e.g. " - "'syntax = \"proto2\";'.\n"); - EXPECT_EQ("", parser_->GetSyntaxIdentifier()); -} - -TEST_F(ParseErrorTest, UnknownSyntaxIdentifier) { - ExpectHasEarlyExitErrors( - "syntax = \"no_such_syntax\";", - "0:9: Unrecognized syntax identifier \"no_such_syntax\". This parser " - "only recognizes \"proto2\" and \"proto3\".\n"); - EXPECT_EQ("no_such_syntax", parser_->GetSyntaxIdentifier()); -} - -TEST_F(ParseErrorTest, SimpleSyntaxError) { - ExpectHasErrors( - "message TestMessage @#$ { blah }", - "0:20: Expected \"{\".\n"); - EXPECT_EQ("proto2", parser_->GetSyntaxIdentifier()); -} - -TEST_F(ParseErrorTest, ExpectedTopLevel) { - ExpectHasErrors( - "blah;", - "0:0: Expected top-level statement (e.g. \"message\").\n"); -} - -TEST_F(ParseErrorTest, UnmatchedCloseBrace) { - // This used to cause an infinite loop. Doh. - ExpectHasErrors( - "}", - "0:0: Expected top-level statement (e.g. \"message\").\n" - "0:0: Unmatched \"}\".\n"); -} - -// ------------------------------------------------------------------- -// Message errors - -TEST_F(ParseErrorTest, MessageMissingName) { - ExpectHasErrors( - "message {}", - "0:8: Expected message name.\n"); -} - -TEST_F(ParseErrorTest, MessageMissingBody) { - ExpectHasErrors( - "message TestMessage;", - "0:19: Expected \"{\".\n"); -} - -TEST_F(ParseErrorTest, EofInMessage) { - ExpectHasErrors( - "message TestMessage {", - "0:21: Reached end of input in message definition (missing '}').\n"); -} - -TEST_F(ParseErrorTest, MissingFieldNumber) { - ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo;\n" - "}\n", - "1:20: Missing field number.\n"); -} - -TEST_F(ParseErrorTest, ExpectedFieldNumber) { - ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo = ;\n" - "}\n", - "1:23: Expected field number.\n"); -} - -TEST_F(ParseErrorTest, FieldNumberOutOfRange) { - ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo = 0x100000000;\n" - "}\n", - "1:23: Integer out of range.\n"); -} - -TEST_F(ParseErrorTest, MissingLabel) { - ExpectHasErrors( - "message TestMessage {\n" - " int32 foo = 1;\n" - "}\n", - "1:2: Expected \"required\", \"optional\", or \"repeated\".\n"); -} - -TEST_F(ParseErrorTest, ExpectedOptionName) { - ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [];\n" - "}\n", - "1:27: Expected identifier.\n"); -} - -TEST_F(ParseErrorTest, NonExtensionOptionNameBeginningWithDot) { - ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [.foo=1];\n" - "}\n", - "1:27: Expected identifier.\n"); -} - -TEST_F(ParseErrorTest, DefaultValueTypeMismatch) { - ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [default=true];\n" - "}\n", - "1:35: Expected integer for field default value.\n"); -} - -TEST_F(ParseErrorTest, DefaultValueNotBoolean) { - ExpectHasErrors( - "message TestMessage {\n" - " optional bool foo = 1 [default=blah];\n" - "}\n", - "1:33: Expected \"true\" or \"false\".\n"); -} - -TEST_F(ParseErrorTest, DefaultValueNotString) { - ExpectHasErrors( - "message TestMessage {\n" - " optional string foo = 1 [default=1];\n" - "}\n", - "1:35: Expected string for field default value.\n"); -} - -TEST_F(ParseErrorTest, DefaultValueUnsignedNegative) { - ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [default=-1];\n" - "}\n", - "1:36: Unsigned field can't have negative default value.\n"); -} - -TEST_F(ParseErrorTest, DefaultValueTooLarge) { - ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo = 1 [default= 0x80000000];\n" - " optional int32 foo = 1 [default=-0x80000001];\n" - " optional uint32 foo = 1 [default= 0x100000000];\n" - " optional int64 foo = 1 [default= 0x80000000000000000];\n" - " optional int64 foo = 1 [default=-0x80000000000000001];\n" - " optional uint64 foo = 1 [default= 0x100000000000000000];\n" - "}\n", - "1:36: Integer out of range.\n" - "2:36: Integer out of range.\n" - "3:36: Integer out of range.\n" - "4:36: Integer out of range.\n" - "5:36: Integer out of range.\n" - "6:36: Integer out of range.\n"); -} - -TEST_F(ParseErrorTest, JsonNameNotString) { - ExpectHasErrors( - "message TestMessage {\n" - " optional string foo = 1 [json_name=1];\n" - "}\n", - "1:37: Expected string for JSON name.\n"); -} - -TEST_F(ParseErrorTest, DuplicateJsonName) { - ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [json_name=\"a\",json_name=\"b\"];\n" - "}\n", - "1:41: Already set option \"json_name\".\n"); -} - -TEST_F(ParseErrorTest, EnumValueOutOfRange) { - ExpectHasErrors( - "enum TestEnum {\n" - " HEX_TOO_BIG = 0x80000000;\n" - " HEX_TOO_SMALL = -0x80000001;\n" - " INT_TOO_BIG = 2147483648;\n" - " INT_TOO_SMALL = -2147483649;\n" - "}\n", - "1:19: Integer out of range.\n" - "2:19: Integer out of range.\n" - "3:19: Integer out of range.\n" - "4:19: Integer out of range.\n"); -} - -TEST_F(ParseErrorTest, EnumAllowAliasFalse) { - ExpectHasErrors( - "enum Foo {\n" - " option allow_alias = false;\n" - " BAR = 1;\n" - " BAZ = 2;\n" - "}\n", - "5:0: \"Foo\" declares 'option allow_alias = false;' which has no effect. " - "Please remove the declaration.\n"); -} - -TEST_F(ParseErrorTest, UnnecessaryEnumAllowAlias) { - ExpectHasErrors( - "enum Foo {\n" - " option allow_alias = true;\n" - " BAR = 1;\n" - " BAZ = 2;\n" - "}\n", - "5:0: \"Foo\" declares support for enum aliases but no enum values share " - "field numbers. Please remove the unnecessary 'option allow_alias = true;' " - "declaration.\n"); -} - -TEST_F(ParseErrorTest, DefaultValueMissing) { - ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [default=];\n" - "}\n", - "1:35: Expected integer for field default value.\n"); -} - -TEST_F(ParseErrorTest, DefaultValueForGroup) { - ExpectHasErrors( - "message TestMessage {\n" - " optional group Foo = 1 [default=blah] {}\n" - "}\n", - "1:34: Messages can't have default values.\n"); -} - -TEST_F(ParseErrorTest, DuplicateDefaultValue) { - ExpectHasErrors( - "message TestMessage {\n" - " optional uint32 foo = 1 [default=1,default=2];\n" - "}\n", - "1:37: Already set option \"default\".\n"); -} - -TEST_F(ParseErrorTest, MissingOneofName) { - ExpectHasErrors( - "message TestMessage {\n" - " oneof {\n" - " int32 bar = 1;\n" - " }\n" - "}\n", - "1:8: Expected oneof name.\n"); -} - -TEST_F(ParseErrorTest, LabelInOneof) { - ExpectHasErrors( - "message TestMessage {\n" - " oneof foo {\n" - " optional int32 bar = 1;\n" - " }\n" - "}\n", - "2:4: Fields in oneofs must not have labels (required / optional " - "/ repeated).\n"); -} - -TEST_F(ParseErrorTest, MapInOneof) { - ExpectHasErrors( - "message TestMessage {\n" - " oneof foo {\n" - " map foo_map = 1;\n" - " map message_field = 2;\n" // a normal message field is OK - " }\n" - "}\n", - "2:7: Map fields are not allowed in oneofs.\n"); -} - -TEST_F(ParseErrorTest, LabelForMap) { - ExpectHasErrors( - "message TestMessage {\n" - " optional map int_map = 1;\n" - " required map int_map2 = 2;\n" - " repeated map int_map3 = 3;\n" - " optional map map_message = 4;\n" // a normal message field is OK - "}\n", - "1:14: Field labels (required/optional/repeated) are not allowed on map " - "fields.\n" - "2:14: Field labels (required/optional/repeated) are not allowed on map " - "fields.\n" - "3:14: Field labels (required/optional/repeated) are not allowed on map " - "fields.\n"); -} - -TEST_F(ParseErrorTest, MalformedMaps) { - ExpectHasErrors( - "message TestMessage {\n" - " map map_message = 1;\n" // a normal message field lacking label - " map str_map = 2;\n" - " map str_map2 = 3;\n" - " map<,string> str_map3 = 4;\n" - " map<> empty_map = 5;\n" - " map int_map = 1;\n" - "}", - "1:6: Expected \"required\", \"optional\", or \"repeated\".\n" - "2:12: Expected \",\".\n" - "3:13: Expected type name.\n" - "4:6: Expected type name.\n" - "5:6: Expected type name.\n" - "6:20: Expected \">\".\n" - "8:5: Map fields are not allowed to be extensions.\n"); -} - -TEST_F(ParseErrorTest, GroupNotCapitalized) { - ExpectHasErrors( - "message TestMessage {\n" - " optional group foo = 1 {}\n" - "}\n", - "1:17: Group names must start with a capital letter.\n"); -} - -TEST_F(ParseErrorTest, GroupMissingBody) { - ExpectHasErrors( - "message TestMessage {\n" - " optional group Foo = 1;\n" - "}\n", - "1:24: Missing group body.\n"); -} - -TEST_F(ParseErrorTest, ExtendingPrimitive) { - ExpectHasErrors( - "extend int32 { optional string foo = 4; }\n", - "0:7: Expected message type.\n"); -} - -TEST_F(ParseErrorTest, ErrorInExtension) { - ExpectHasErrors( - "message Foo { extensions 100 to 199; }\n" - "extend Foo { optional string foo; }\n", - "1:32: Missing field number.\n"); -} - -TEST_F(ParseErrorTest, MultipleParseErrors) { - // When a statement has a parse error, the parser should be able to continue - // parsing at the next statement. - ExpectHasErrors( - "message TestMessage {\n" - " optional int32 foo;\n" - " !invalid statement ending in a block { blah blah { blah } blah }\n" - " optional int32 bar = 3 {}\n" - "}\n", - "1:20: Missing field number.\n" - "2:2: Expected \"required\", \"optional\", or \"repeated\".\n" - "2:2: Expected type name.\n" - "3:25: Expected \";\".\n"); -} - -TEST_F(ParseErrorTest, EofInAggregateValue) { - ExpectHasErrors( - "option (fileopt) = { i:100\n", - "1:0: Unexpected end of stream while parsing aggregate value.\n"); -} - -TEST_F(ParseErrorTest, ExplicitOptionalLabelProto3) { - ExpectHasErrors( - "syntax = 'proto3';\n" - "message TestMessage {\n" - " optional int32 foo = 1;\n" - "}\n", - "2:11: Explicit 'optional' labels are disallowed in the Proto3 syntax. " - "To define 'optional' fields in Proto3, simply remove the 'optional' " - "label, as fields are 'optional' by default.\n"); -} - - -// ------------------------------------------------------------------- -// Enum errors - -TEST_F(ParseErrorTest, EofInEnum) { - ExpectHasErrors( - "enum TestEnum {", - "0:15: Reached end of input in enum definition (missing '}').\n"); -} - -TEST_F(ParseErrorTest, EnumValueMissingNumber) { - ExpectHasErrors( - "enum TestEnum {\n" - " FOO;\n" - "}\n", - "1:5: Missing numeric value for enum constant.\n"); -} - -TEST_F(ParseErrorTest, EnumReservedStandaloneMaxNotAllowed) { - ExpectHasErrors( - "enum TestEnum {\n" - " FOO = 1;\n" - " reserved max;\n" - "}\n", - "2:11: Expected enum value or number range.\n"); -} - -TEST_F(ParseErrorTest, EnumReservedMixNameAndNumber) { - ExpectHasErrors( - "enum TestEnum {\n" - " FOO = 1;\n" - " reserved 10, \"foo\";\n" - "}\n", - "2:15: Expected enum number range.\n"); -} - -TEST_F(ParseErrorTest, EnumReservedPositiveNumberOutOfRange) { - ExpectHasErrors( - "enum TestEnum {\n" - "FOO = 1;\n" - " reserved 2147483648;\n" - "}\n", - "2:11: Integer out of range.\n"); -} - -TEST_F(ParseErrorTest, EnumReservedNegativeNumberOutOfRange) { - ExpectHasErrors( - "enum TestEnum {\n" - "FOO = 1;\n" - " reserved -2147483649;\n" - "}\n", - "2:12: Integer out of range.\n"); -} - -TEST_F(ParseErrorTest, EnumReservedMissingQuotes) { - ExpectHasErrors( - "enum TestEnum {\n" - " FOO = 1;\n" - " reserved foo;\n" - "}\n", - "2:11: Expected enum value or number range.\n"); -} - -// ------------------------------------------------------------------- -// Reserved field number errors - -TEST_F(ParseErrorTest, ReservedStandaloneMaxNotAllowed) { - ExpectHasErrors( - "message Foo {\n" - " reserved max;\n" - "}\n", - "1:11: Expected field name or number range.\n"); -} - -TEST_F(ParseErrorTest, ReservedMixNameAndNumber) { - ExpectHasErrors( - "message Foo {\n" - " reserved 10, \"foo\";\n" - "}\n", - "1:15: Expected field number range.\n"); -} - -TEST_F(ParseErrorTest, ReservedMissingQuotes) { - ExpectHasErrors( - "message Foo {\n" - " reserved foo;\n" - "}\n", - "1:11: Expected field name or number range.\n"); -} - -TEST_F(ParseErrorTest, ReservedNegativeNumber) { - ExpectHasErrors( - "message Foo {\n" - " reserved -10;\n" - "}\n", - "1:11: Expected field name or number range.\n"); -} - -TEST_F(ParseErrorTest, ReservedNumberOutOfRange) { - ExpectHasErrors( - "message Foo {\n" - " reserved 2147483648;\n" - "}\n", - "1:11: Integer out of range.\n"); -} - - -// ------------------------------------------------------------------- -// Service errors - -TEST_F(ParseErrorTest, EofInService) { - ExpectHasErrors( - "service TestService {", - "0:21: Reached end of input in service definition (missing '}').\n"); -} - -TEST_F(ParseErrorTest, ServiceMethodPrimitiveParams) { - ExpectHasErrors( - "service TestService {\n" - " rpc Foo(int32) returns (string);\n" - "}\n", - "1:10: Expected message type.\n" - "1:26: Expected message type.\n"); -} - - -TEST_F(ParseErrorTest, EofInMethodOptions) { - ExpectHasErrors( - "service TestService {\n" - " rpc Foo(Bar) returns(Bar) {", - "1:29: Reached end of input in method options (missing '}').\n" - "1:29: Reached end of input in service definition (missing '}').\n"); -} - - -TEST_F(ParseErrorTest, PrimitiveMethodInput) { - ExpectHasErrors( - "service TestService {\n" - " rpc Foo(int32) returns(Bar);\n" - "}\n", - "1:10: Expected message type.\n"); -} - - -TEST_F(ParseErrorTest, MethodOptionTypeError) { - // This used to cause an infinite loop. - ExpectHasErrors( - "message Baz {}\n" - "service Foo {\n" - " rpc Bar(Baz) returns(Baz) { option invalid syntax; }\n" - "}\n", - "2:45: Expected \"=\".\n"); -} - - -// ------------------------------------------------------------------- -// Import and package errors - -TEST_F(ParseErrorTest, ImportNotQuoted) { - ExpectHasErrors( - "import foo;\n", - "0:7: Expected a string naming the file to import.\n"); -} - -TEST_F(ParseErrorTest, MultiplePackagesInFile) { - ExpectHasErrors( - "package foo;\n" - "package bar;\n", - "1:0: Multiple package definitions.\n"); -} - -// =================================================================== -// Test that errors detected by DescriptorPool correctly report line and -// column numbers. We have one test for every call to RecordLocation() in -// parser.cc. - -typedef ParserTest ParserValidationErrorTest; - -TEST_F(ParserValidationErrorTest, PackageNameError) { - // Create another file which defines symbol "foo". - FileDescriptorProto other_file; - other_file.set_name("bar.proto"); - other_file.add_message_type()->set_name("foo"); - EXPECT_TRUE(pool_.BuildFile(other_file) != NULL); - - // Now try to define it as a package. - ExpectHasValidationErrors( - "package foo.bar;", - "0:8: \"foo\" is already defined (as something other than a package) " - "in file \"bar.proto\".\n"); -} - -TEST_F(ParserValidationErrorTest, MessageNameError) { - ExpectHasValidationErrors( - "message Foo {}\n" - "message Foo {}\n", - "1:8: \"Foo\" is already defined.\n"); -} - -TEST_F(ParserValidationErrorTest, FieldNameError) { - ExpectHasValidationErrors( - "message Foo {\n" - " optional int32 bar = 1;\n" - " optional int32 bar = 2;\n" - "}\n", - "2:17: \"bar\" is already defined in \"Foo\".\n"); -} - -TEST_F(ParserValidationErrorTest, FieldTypeError) { - ExpectHasValidationErrors( - "message Foo {\n" - " optional Baz bar = 1;\n" - "}\n", - "1:11: \"Baz\" is not defined.\n"); -} - -TEST_F(ParserValidationErrorTest, FieldNumberError) { - ExpectHasValidationErrors( - "message Foo {\n" - " optional int32 bar = 0;\n" - "}\n", - "1:23: Field numbers must be positive integers.\n"); -} - -TEST_F(ParserValidationErrorTest, FieldExtendeeError) { - ExpectHasValidationErrors( - "extend Baz { optional int32 bar = 1; }\n", - "0:7: \"Baz\" is not defined.\n"); -} - -TEST_F(ParserValidationErrorTest, FieldDefaultValueError) { - ExpectHasValidationErrors( - "enum Baz { QUX = 1; }\n" - "message Foo {\n" - " optional Baz bar = 1 [default=NO_SUCH_VALUE];\n" - "}\n", - "2:32: Enum type \"Baz\" has no value named \"NO_SUCH_VALUE\".\n"); -} - -TEST_F(ParserValidationErrorTest, FileOptionNameError) { - ExpectHasValidationErrors( - "option foo = 5;", - "0:7: Option \"foo\" unknown.\n"); -} - -TEST_F(ParserValidationErrorTest, FileOptionValueError) { - ExpectHasValidationErrors( - "option java_outer_classname = 5;", - "0:30: Value must be quoted string for string option " - "\"google.protobuf.FileOptions.java_outer_classname\".\n"); -} - -TEST_F(ParserValidationErrorTest, FieldOptionNameError) { - ExpectHasValidationErrors( - "message Foo {\n" - " optional bool bar = 1 [foo=1];\n" - "}\n", - "1:25: Option \"foo\" unknown.\n"); -} - -TEST_F(ParserValidationErrorTest, FieldOptionValueError) { - ExpectHasValidationErrors( - "message Foo {\n" - " optional int32 bar = 1 [ctype=1];\n" - "}\n", - "1:32: Value must be identifier for enum-valued option " - "\"google.protobuf.FieldOptions.ctype\".\n"); -} - -TEST_F(ParserValidationErrorTest, ExtensionRangeNumberError) { - ExpectHasValidationErrors( - "message Foo {\n" - " extensions 0;\n" - "}\n", - "1:13: Extension numbers must be positive integers.\n"); -} - -TEST_F(ParserValidationErrorTest, EnumNameError) { - ExpectHasValidationErrors( - "enum Foo {A = 1;}\n" - "enum Foo {B = 1;}\n", - "1:5: \"Foo\" is already defined.\n"); -} - -TEST_F(ParserValidationErrorTest, EnumValueNameError) { - ExpectHasValidationErrors( - "enum Foo {\n" - " BAR = 1;\n" - " BAR = 1;\n" - "}\n", - "2:2: \"BAR\" is already defined.\n"); -} - -TEST_F(ParserValidationErrorTest, ServiceNameError) { - ExpectHasValidationErrors( - "service Foo {}\n" - "service Foo {}\n", - "1:8: \"Foo\" is already defined.\n"); -} - -TEST_F(ParserValidationErrorTest, MethodNameError) { - ExpectHasValidationErrors( - "message Baz {}\n" - "service Foo {\n" - " rpc Bar(Baz) returns(Baz);\n" - " rpc Bar(Baz) returns(Baz);\n" - "}\n", - "3:6: \"Bar\" is already defined in \"Foo\".\n"); -} - - -TEST_F(ParserValidationErrorTest, MethodInputTypeError) { - ExpectHasValidationErrors( - "message Baz {}\n" - "service Foo {\n" - " rpc Bar(Qux) returns(Baz);\n" - "}\n", - "2:10: \"Qux\" is not defined.\n"); -} - - -TEST_F(ParserValidationErrorTest, MethodOutputTypeError) { - ExpectHasValidationErrors( - "message Baz {}\n" - "service Foo {\n" - " rpc Bar(Baz) returns(Qux);\n" - "}\n", - "2:23: \"Qux\" is not defined.\n"); -} - - -TEST_F(ParserValidationErrorTest, ResovledUndefinedError) { - // Create another file which defines symbol ".base.bar". - FileDescriptorProto other_file; - other_file.set_name("base.proto"); - other_file.set_package("base"); - other_file.add_message_type()->set_name("bar"); - EXPECT_TRUE(pool_.BuildFile(other_file) != NULL); - - // Define "foo.base" and try "base.bar". - // "base.bar" is resolved to "foo.base.bar" which is not defined. - ExpectHasValidationErrors( - "package foo.base;\n" - "import \"base.proto\";\n" - "message qux {\n" - " optional base.bar baz = 1;\n" - " optional .base.bar quz = 2;\n" - "}\n", - "3:11: \"base.bar\" is resolved to \"foo.base.bar\"," - " which is not defined. The innermost scope is searched first " - "in name resolution. Consider using a leading '.'(i.e., \".base.bar\")" - " to start from the outermost scope.\n"); -} - -TEST_F(ParserValidationErrorTest, ResovledUndefinedOptionError) { - // Build descriptor message in test pool - FileDescriptorProto descriptor_proto; - DescriptorProto::descriptor()->file()->CopyTo(&descriptor_proto); - ASSERT_TRUE(pool_.BuildFile(descriptor_proto) != NULL); - - // base2.proto: - // package baz - // import google/protobuf/descriptor.proto - // message Bar { optional int32 foo = 1; } - // extend FileOptions { optional Bar bar = 7672757; } - FileDescriptorProto other_file; - other_file.set_name("base2.proto"); - other_file.set_package("baz"); - other_file.add_dependency(); - other_file.set_dependency(0, descriptor_proto.name()); - - DescriptorProto* message(other_file.add_message_type()); - message->set_name("Bar"); - FieldDescriptorProto* field(message->add_field()); - field->set_name("foo"); - field->set_number(1); - field->set_label(FieldDescriptorProto_Label_LABEL_OPTIONAL); - field->set_type(FieldDescriptorProto_Type_TYPE_INT32); - - FieldDescriptorProto* extension(other_file.add_extension()); - extension->set_name("bar"); - extension->set_number(7672757); - extension->set_label(FieldDescriptorProto_Label_LABEL_OPTIONAL); - extension->set_type(FieldDescriptorProto_Type_TYPE_MESSAGE); - extension->set_type_name("Bar"); - extension->set_extendee("google.protobuf.FileOptions"); - - EXPECT_TRUE(pool_.BuildFile(other_file) != NULL); - - // qux.proto: - // package qux.baz - // option (baz.bar).foo = 1; - // - // Although "baz.bar" is already defined, the lookup code will try - // "qux.baz.bar", since it's the match from the innermost scope, - // which will cause a symbol not defined error. - ExpectHasValidationErrors( - "package qux.baz;\n" - "import \"base2.proto\";\n" - "option (baz.bar).foo = 1;\n", - "2:7: Option \"(baz.bar)\" is resolved to \"(qux.baz.bar)\"," - " which is not defined. The innermost scope is searched first " - "in name resolution. Consider using a leading '.'(i.e., \"(.baz.bar)\")" - " to start from the outermost scope.\n"); -} - -// =================================================================== -// Test that the output from FileDescriptor::DebugString() (and all other -// descriptor types) is parseable, and results in the same Descriptor -// definitions again afoter parsing (note, however, that the order of messages -// cannot be guaranteed to be the same) - -typedef ParserTest ParseDescriptorDebugTest; - -class CompareDescriptorNames { - public: - bool operator()(const DescriptorProto* left, - const DescriptorProto* right) const { - return left->name() < right->name(); - } -}; - -// Sorts nested DescriptorProtos of a DescriptoProto, by name. -void SortMessages(DescriptorProto *descriptor_proto) { - int size = descriptor_proto->nested_type_size(); - // recursively sort; we can't guarantee the order of nested messages either - for (int i = 0; i < size; ++i) { - SortMessages(descriptor_proto->mutable_nested_type(i)); - } - DescriptorProto **data = - descriptor_proto->mutable_nested_type()->mutable_data(); - std::sort(data, data + size, CompareDescriptorNames()); -} - -// Sorts DescriptorProtos belonging to a FileDescriptorProto, by name. -void SortMessages(FileDescriptorProto *file_descriptor_proto) { - int size = file_descriptor_proto->message_type_size(); - // recursively sort; we can't guarantee the order of nested messages either - for (int i = 0; i < size; ++i) { - SortMessages(file_descriptor_proto->mutable_message_type(i)); - } - DescriptorProto **data = - file_descriptor_proto->mutable_message_type()->mutable_data(); - std::sort(data, data + size, CompareDescriptorNames()); -} - -// Strips the message and enum field type names for comparison purpose only. -void StripFieldTypeName(DescriptorProto* proto) { - for (int i = 0; i < proto->field_size(); ++i) { - string type_name = proto->field(i).type_name(); - string::size_type pos = type_name.find_last_of("."); - if (pos != string::npos) { - proto->mutable_field(i)->mutable_type_name()->assign( - type_name.begin() + pos + 1, type_name.end()); - } - } - for (int i = 0; i < proto->nested_type_size(); ++i) { - StripFieldTypeName(proto->mutable_nested_type(i)); - } -} - -void StripFieldTypeName(FileDescriptorProto* file_proto) { - for (int i = 0; i < file_proto->message_type_size(); ++i) { - StripFieldTypeName(file_proto->mutable_message_type(i)); - } -} - -TEST_F(ParseDescriptorDebugTest, TestAllDescriptorTypes) { - const FileDescriptor* original_file = - protobuf_unittest::TestAllTypes::descriptor()->file(); - FileDescriptorProto expected; - original_file->CopyTo(&expected); - - // Get the DebugString of the unittest.proto FileDecriptor, which includes - // all other descriptor types - string debug_string = original_file->DebugString(); - - // Parse the debug string - SetupParser(debug_string.c_str()); - FileDescriptorProto parsed; - parser_->Parse(input_.get(), &parsed); - EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - ASSERT_EQ("", error_collector_.text_) - << "Failed to parse:\n" << debug_string; - - // We now have a FileDescriptorProto, but to compare with the expected we - // need to link to a FileDecriptor, then output back to a proto. We'll - // also need to give it the same name as the original. - parsed.set_name("google/protobuf/unittest.proto"); - // We need the imported dependency before we can build our parsed proto - const FileDescriptor* public_import = - protobuf_unittest_import::PublicImportMessage::descriptor()->file(); - FileDescriptorProto public_import_proto; - public_import->CopyTo(&public_import_proto); - ASSERT_TRUE(pool_.BuildFile(public_import_proto) != NULL); - const FileDescriptor* import = - protobuf_unittest_import::ImportMessage::descriptor()->file(); - FileDescriptorProto import_proto; - import->CopyTo(&import_proto); - ASSERT_TRUE(pool_.BuildFile(import_proto) != NULL); - const FileDescriptor* actual = pool_.BuildFile(parsed); - parsed.Clear(); - ASSERT_TRUE(actual != NULL) - << "Failed to validate:\n" << debug_string; - actual->CopyTo(&parsed); - ASSERT_TRUE(actual != NULL); - - // The messages might be in different orders, making them hard to compare. - // So, sort the messages in the descriptor protos (including nested messages, - // recursively). - SortMessages(&expected); - SortMessages(&parsed); - - // I really wanted to use StringDiff here for the debug output on fail, - // but the strings are too long for it, and if I increase its max size, - // we get a memory allocation failure :( - EXPECT_EQ(expected.DebugString(), parsed.DebugString()); -} - -TEST_F(ParseDescriptorDebugTest, TestCustomOptions) { - const FileDescriptor* original_file = - protobuf_unittest::AggregateMessage::descriptor()->file(); - FileDescriptorProto expected; - original_file->CopyTo(&expected); - - string debug_string = original_file->DebugString(); - - // Parse the debug string - SetupParser(debug_string.c_str()); - FileDescriptorProto parsed; - parser_->Parse(input_.get(), &parsed); - EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - ASSERT_EQ("", error_collector_.text_); - - // We now have a FileDescriptorProto, but to compare with the expected we - // need to link to a FileDecriptor, then output back to a proto. We'll - // also need to give it the same name as the original. - parsed.set_name(original_file->name()); - - // unittest_custom_options.proto depends on descriptor.proto. - const FileDescriptor* import = FileDescriptorProto::descriptor()->file(); - FileDescriptorProto import_proto; - import->CopyTo(&import_proto); - ASSERT_TRUE(pool_.BuildFile(import_proto) != NULL); - const FileDescriptor* actual = pool_.BuildFile(parsed); - ASSERT_TRUE(actual != NULL); - parsed.Clear(); - actual->CopyTo(&parsed); - - // The messages might be in different orders, making them hard to compare. - // So, sort the messages in the descriptor protos (including nested messages, - // recursively). - SortMessages(&expected); - SortMessages(&parsed); - - EXPECT_EQ(expected.DebugString(), parsed.DebugString()); -} - -// Ensure that DebugStringWithOptions(), with |include_comments| set to true, -// includes comments from the original parser input in all of the appropriate -// places. -TEST_F(ParseDescriptorDebugTest, TestCommentsInDebugString) { - SetupParser( - "// Detached comment before syntax.\n" - "\n" - "// Syntax comment.\n" - "syntax = \"proto2\";\n" - "\n" - "// Detached comment before package.\n" - "\n" - "// Package comment.\n" - "package comment_test;\n" - "\n" - "// Detached comment before TestMessage1.\n" - "\n" - "// Message comment.\n" - "//\n" - "// More detail in message comment.\n" - "message TestMessage1 {\n" - "\n" - " // Detached comment before foo.\n" - "\n" - " // Field comment.\n" - " optional int32 foo = 1;\n" - "\n" - " // Detached comment before NestedMessage.\n" - "\n" - " // Nested-message comment.\n" - " message NestedMessage {\n" - " optional int32 bar = 1;\n" - " }\n" - "}\n" - "\n" - "// Detached comment before MyEnumType.\n" - "\n" - "// Enum comment.\n" - "enum MyEnumType {\n" - "\n" - " // Detached comment before ASDF.\n" - "\n" - " // Enum-value comment.\n" - " ASDF = 1;\n" - "}\n" - "\n" - "// Detached comment before MyService.\n" - "\n" - "// Service comment.\n" - "service MyService {\n" - "\n" - " // Detached comment before MyRPCCall.\n" - "\n" - " // RPC comment.\n" - " rpc MyRPCCall(TestMessage1) returns (TestMessage1) { }\n" - "}\n"); - - FileDescriptorProto parsed_desc; - parsed_desc.set_name("foo.proto"); - SourceLocationTable source_locations; - parser_->RecordSourceLocationsTo(&source_locations); - parser_->Parse(input_.get(), &parsed_desc); - EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - ASSERT_EQ("", error_collector_.text_); - - // We need to import the FileDescriptorProto to get a FileDescriptor. - MockValidationErrorCollector collector(source_locations, &error_collector_); - const FileDescriptor* descriptor = - pool_.BuildFileCollectingErrors(parsed_desc, &collector); - ASSERT_TRUE(descriptor != NULL); - - // Ensure that each of the comments appears somewhere in the DebugString(). - // We don't test the exact comment placement or formatting, because we do not - // want to be too fragile here. - const char* expected_comments[] = { - "Detached comment before syntax.", - "Syntax comment.", - "Detached comment before package.", - "Package comment.", - "Detached comment before TestMessage1.", - "Message comment.", - "More detail in message comment.", - "Detached comment before foo.", - "Field comment", - "Detached comment before NestedMessage.", - "Nested-message comment", - "Detached comment before MyEnumType.", - "Enum comment", - "Detached comment before ASDF.", - "Enum-value comment", - "Detached comment before MyService.", - "Service comment", - "Detached comment before MyRPCCall.", - "RPC comment", - }; - - DebugStringOptions debug_string_options; - debug_string_options.include_comments = true; - - { - const string debug_string = - descriptor->DebugStringWithOptions(debug_string_options); - - for (int i = 0; i < GOOGLE_ARRAYSIZE(expected_comments); ++i) { - string::size_type found_pos = debug_string.find(expected_comments[i]); - EXPECT_TRUE(found_pos != string::npos) - << "\"" << expected_comments[i] << "\" not found."; - } - - // Result of DebugStringWithOptions should be parseable. - SetupParser(debug_string.c_str()); - FileDescriptorProto parsed; - parser_->Parse(input_.get(), &parsed); - EXPECT_EQ(io::Tokenizer::TYPE_END, input_->current().type); - ASSERT_EQ("", error_collector_.text_) - << "Failed to parse:\n" << debug_string; - } - -} - -TEST_F(ParseDescriptorDebugTest, TestMaps) { - SetupParser( - "syntax = \"proto3\"; " - "message Foo { " - " message Bar { } " - " map enum_message_map = 1; " - " map primitive_map = 2; " - "} "); - FileDescriptorProto original; - EXPECT_TRUE(parser_->Parse(input_.get(), &original)); - original.set_name("foo.proto"); - const FileDescriptor* file = pool_.BuildFile(original); - ASSERT_TRUE(file != NULL); - - // Make sure the debug string uses map syntax and does not have the auto - // generated entry. - string debug_string = file->DebugString(); - EXPECT_TRUE(debug_string.find("map<") != string::npos); - EXPECT_TRUE(debug_string.find("option map_entry") == string::npos); - EXPECT_TRUE(debug_string.find("MapEntry") == string::npos); - - // Make sure the descriptor debug string is parsable. - FileDescriptorProto parsed; - SetupParser(debug_string.c_str()); - parsed.set_name("foo.proto"); - ASSERT_TRUE(parser_->Parse(input_.get(), &parsed)); - - original.clear_source_code_info(); - parsed.clear_source_code_info(); - StripFieldTypeName(&original); - StripFieldTypeName(&parsed); - EXPECT_EQ(original.DebugString(), parsed.DebugString()); -} - -// =================================================================== -// SourceCodeInfo tests. - -// Follows a path -- as defined by SourceCodeInfo.Location.path -- from a -// message to a particular sub-field. -// * If the target is itself a message, sets *output_message to point at it, -// *output_field to NULL, and *output_index to -1. -// * Otherwise, if the target is an element of a repeated field, sets -// *output_message to the containing message, *output_field to the descriptor -// of the field, and *output_index to the index of the element. -// * Otherwise, the target is a field (possibly a repeated field, but not any -// one element). Sets *output_message to the containing message, -// *output_field to the descriptor of the field, and *output_index to -1. -// Returns true if the path was valid, false otherwise. A gTest failure is -// recorded before returning false. -bool FollowPath(const Message& root, - const int* path_begin, const int* path_end, - const Message** output_message, - const FieldDescriptor** output_field, - int* output_index) { - if (path_begin == path_end) { - // Path refers to this whole message. - *output_message = &root; - *output_field = NULL; - *output_index = -1; - return true; - } - - const Descriptor* descriptor = root.GetDescriptor(); - const Reflection* reflection = root.GetReflection(); - - const FieldDescriptor* field = descriptor->FindFieldByNumber(*path_begin); - - if (field == NULL) { - ADD_FAILURE() << descriptor->name() << " has no field number: " - << *path_begin; - return false; - } - - ++path_begin; - - if (field->is_repeated()) { - if (path_begin == path_end) { - // Path refers to the whole repeated field. - *output_message = &root; - *output_field = field; - *output_index = -1; - return true; - } - - int index = *path_begin++; - int size = reflection->FieldSize(root, field); - - if (index >= size) { - ADD_FAILURE() << descriptor->name() << "." << field->name() - << " has size " << size << ", but path contained index: " - << index; - return false; - } - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - // Descend into child message. - const Message& child = reflection->GetRepeatedMessage(root, field, index); - return FollowPath(child, path_begin, path_end, - output_message, output_field, output_index); - } else if (path_begin == path_end) { - // Path refers to this element. - *output_message = &root; - *output_field = field; - *output_index = index; - return true; - } else { - ADD_FAILURE() << descriptor->name() << "." << field->name() - << " is not a message; cannot descend into it."; - return false; - } - } else { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - const Message& child = reflection->GetMessage(root, field); - return FollowPath(child, path_begin, path_end, - output_message, output_field, output_index); - } else if (path_begin == path_end) { - // Path refers to this field. - *output_message = &root; - *output_field = field; - *output_index = -1; - return true; - } else { - ADD_FAILURE() << descriptor->name() << "." << field->name() - << " is not a message; cannot descend into it."; - return false; - } - } -} - -// Check if two spans are equal. -bool CompareSpans(const RepeatedField& span1, - const RepeatedField& span2) { - if (span1.size() != span2.size()) return false; - for (int i = 0; i < span1.size(); i++) { - if (span1.Get(i) != span2.Get(i)) return false; - } - return true; -} - -// Test fixture for source info tests, which check that source locations are -// recorded correctly in FileDescriptorProto.source_code_info.location. -class SourceInfoTest : public ParserTest { - protected: - // The parsed file (initialized by Parse()). - FileDescriptorProto file_; - - // Parse the given text as a .proto file and populate the spans_ map with - // all the source location spans in its SourceCodeInfo table. - bool Parse(const char* text) { - ExtractMarkers(text); - SetupParser(text_without_markers_.c_str()); - if (!parser_->Parse(input_.get(), &file_)) { - return false; - } - - const SourceCodeInfo& source_info = file_.source_code_info(); - for (int i = 0; i < source_info.location_size(); i++) { - const SourceCodeInfo::Location& location = source_info.location(i); - const Message* descriptor_proto = NULL; - const FieldDescriptor* field = NULL; - int index = 0; - if (!FollowPath(file_, location.path().begin(), location.path().end(), - &descriptor_proto, &field, &index)) { - return false; - } - - spans_.insert( - std::make_pair(SpanKey(*descriptor_proto, field, index), &location)); - } - - return true; - } - - virtual void TearDown() { - EXPECT_TRUE(spans_.empty()) - << "Forgot to call HasSpan() for:\n" - << spans_.begin()->second->DebugString(); - } - - // ----------------------------------------------------------------- - // HasSpan() checks that the span of source code delimited by the given - // tags (comments) correspond via the SourceCodeInfo table to the given - // part of the FileDescriptorProto. (If unclear, look at the actual tests; - // it should quickly become obvious.) - - bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto) { - return HasSpanWithComment( - start_marker, end_marker, descriptor_proto, NULL, -1, NULL, NULL, NULL); - } - - bool HasSpanWithComment(char start_marker, char end_marker, - const Message& descriptor_proto, - const char* expected_leading_comments, - const char* expected_trailing_comments, - const char* expected_leading_detached_comments) { - return HasSpanWithComment( - start_marker, end_marker, descriptor_proto, NULL, -1, - expected_leading_comments, expected_trailing_comments, - expected_leading_detached_comments); - } - - bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, const string& field_name) { - return HasSpan(start_marker, end_marker, descriptor_proto, field_name, -1); - } - - bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, const string& field_name, - int index) { - return HasSpan(start_marker, end_marker, descriptor_proto, - field_name, index, NULL, NULL, NULL); - } - - bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, - const string& field_name, int index, - const char* expected_leading_comments, - const char* expected_trailing_comments, - const char* expected_leading_detached_comments) { - const FieldDescriptor* field = - descriptor_proto.GetDescriptor()->FindFieldByName(field_name); - if (field == NULL) { - ADD_FAILURE() << descriptor_proto.GetDescriptor()->name() - << " has no such field: " << field_name; - return false; - } - - return HasSpanWithComment( - start_marker, end_marker, descriptor_proto, field, index, - expected_leading_comments, expected_trailing_comments, - expected_leading_detached_comments); - } - - bool HasSpan(const Message& descriptor_proto) { - return HasSpanWithComment( - '\0', '\0', descriptor_proto, NULL, -1, NULL, NULL, NULL); - } - - bool HasSpan(const Message& descriptor_proto, const string& field_name) { - return HasSpan('\0', '\0', descriptor_proto, field_name, -1); - } - - bool HasSpan(const Message& descriptor_proto, const string& field_name, - int index) { - return HasSpan('\0', '\0', descriptor_proto, field_name, index); - } - - bool HasSpanWithComment( - char start_marker, char end_marker, const Message& descriptor_proto, - const FieldDescriptor* field, int index, - const char* expected_leading_comments, - const char* expected_trailing_comments, - const char* expected_leading_detached_comments) { - std::pair range = - spans_.equal_range(SpanKey(descriptor_proto, field, index)); - - if (start_marker == '\0') { - if (range.first == range.second) { - return false; - } else { - spans_.erase(range.first); - return true; - } - } else { - std::pair start_pos = FindOrDie(markers_, start_marker); - std::pair end_pos = FindOrDie(markers_, end_marker); - - RepeatedField expected_span; - expected_span.Add(start_pos.first); - expected_span.Add(start_pos.second); - if (end_pos.first != start_pos.first) { - expected_span.Add(end_pos.first); - } - expected_span.Add(end_pos.second); - - for (SpanMap::iterator iter = range.first; iter != range.second; ++iter) { - if (CompareSpans(expected_span, iter->second->span())) { - if (expected_leading_comments == NULL) { - EXPECT_FALSE(iter->second->has_leading_comments()); - } else { - EXPECT_TRUE(iter->second->has_leading_comments()); - EXPECT_EQ(expected_leading_comments, - iter->second->leading_comments()); - } - if (expected_trailing_comments == NULL) { - EXPECT_FALSE(iter->second->has_trailing_comments()); - } else { - EXPECT_TRUE(iter->second->has_trailing_comments()); - EXPECT_EQ(expected_trailing_comments, - iter->second->trailing_comments()); - } - if (expected_leading_detached_comments == NULL) { - EXPECT_EQ(0, iter->second->leading_detached_comments_size()); - } else { - EXPECT_EQ( - expected_leading_detached_comments, - Join(iter->second->leading_detached_comments(), "\n")); - } - - spans_.erase(iter); - return true; - } - } - - return false; - } - } - - private: - struct SpanKey { - const Message* descriptor_proto; - const FieldDescriptor* field; - int index; - - inline SpanKey() {} - inline SpanKey(const Message& descriptor_proto_param, - const FieldDescriptor* field_param, - int index_param) - : descriptor_proto(&descriptor_proto_param), field(field_param), - index(index_param) {} - - inline bool operator<(const SpanKey& other) const { - if (descriptor_proto < other.descriptor_proto) return true; - if (descriptor_proto > other.descriptor_proto) return false; - if (field < other.field) return true; - if (field > other.field) return false; - return index < other.index; - } - }; - - typedef std::multimap SpanMap; - SpanMap spans_; - std::map > markers_; - string text_without_markers_; - - void ExtractMarkers(const char* text) { - markers_.clear(); - text_without_markers_.clear(); - int line = 0; - int column = 0; - while (*text != '\0') { - if (*text == '$') { - ++text; - GOOGLE_CHECK_NE('\0', *text); - if (*text == '$') { - text_without_markers_ += '$'; - ++column; - } else { - markers_[*text] = std::make_pair(line, column); - ++text; - GOOGLE_CHECK_EQ('$', *text); - } - } else if (*text == '\n') { - ++line; - column = 0; - text_without_markers_ += *text; - } else { - text_without_markers_ += *text; - ++column; - } - ++text; - } - } -}; - -TEST_F(SourceInfoTest, BasicFileDecls) { - EXPECT_TRUE(Parse( - "$a$syntax = \"proto2\";$i$\n" - "package $b$foo.bar$c$;\n" - "import $d$\"baz.proto\"$e$;\n" - "import $f$\"qux.proto\"$g$;$h$\n" - "\n" - "// comment ignored\n")); - - EXPECT_TRUE(HasSpan('a', 'h', file_)); - EXPECT_TRUE(HasSpan('b', 'c', file_, "package")); - EXPECT_TRUE(HasSpan('d', 'e', file_, "dependency", 0)); - EXPECT_TRUE(HasSpan('f', 'g', file_, "dependency", 1)); - EXPECT_TRUE(HasSpan('a', 'i', file_, "syntax")); -} - -TEST_F(SourceInfoTest, Messages) { - EXPECT_TRUE(Parse( - "$a$message $b$Foo$c$ {}$d$\n" - "$e$message $f$Bar$g$ {}$h$\n")); - - EXPECT_TRUE(HasSpan('a', 'd', file_.message_type(0))); - EXPECT_TRUE(HasSpan('b', 'c', file_.message_type(0), "name")); - EXPECT_TRUE(HasSpan('e', 'h', file_.message_type(1))); - EXPECT_TRUE(HasSpan('f', 'g', file_.message_type(1), "name")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); -} - -TEST_F(SourceInfoTest, Fields) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$optional$b$ $c$int32$d$ $e$bar$f$ = $g$1$h$;$i$\n" - " $j$repeated$k$ $l$X.Y$m$ $n$baz$o$ = $p$2$q$;$r$\n" - "}\n")); - - const FieldDescriptorProto& field1 = file_.message_type(0).field(0); - const FieldDescriptorProto& field2 = file_.message_type(0).field(1); - - EXPECT_TRUE(HasSpan('a', 'i', field1)); - EXPECT_TRUE(HasSpan('a', 'b', field1, "label")); - EXPECT_TRUE(HasSpan('c', 'd', field1, "type")); - EXPECT_TRUE(HasSpan('e', 'f', field1, "name")); - EXPECT_TRUE(HasSpan('g', 'h', field1, "number")); - - EXPECT_TRUE(HasSpan('j', 'r', field2)); - EXPECT_TRUE(HasSpan('j', 'k', field2, "label")); - EXPECT_TRUE(HasSpan('l', 'm', field2, "type_name")); - EXPECT_TRUE(HasSpan('n', 'o', field2, "name")); - EXPECT_TRUE(HasSpan('p', 'q', field2, "number")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); -} - -TEST_F(SourceInfoTest, Extensions) { - EXPECT_TRUE(Parse( - "$a$extend $b$Foo$c$ {\n" - " $d$optional$e$ int32 bar = 1;$f$\n" - " $g$repeated$h$ X.Y baz = 2;$i$\n" - "}$j$\n" - "$k$extend $l$Bar$m$ {\n" - " $n$optional int32 qux = 1;$o$\n" - "}$p$\n")); - - const FieldDescriptorProto& field1 = file_.extension(0); - const FieldDescriptorProto& field2 = file_.extension(1); - const FieldDescriptorProto& field3 = file_.extension(2); - - EXPECT_TRUE(HasSpan('a', 'j', file_, "extension")); - EXPECT_TRUE(HasSpan('k', 'p', file_, "extension")); - - EXPECT_TRUE(HasSpan('d', 'f', field1)); - EXPECT_TRUE(HasSpan('d', 'e', field1, "label")); - EXPECT_TRUE(HasSpan('b', 'c', field1, "extendee")); - - EXPECT_TRUE(HasSpan('g', 'i', field2)); - EXPECT_TRUE(HasSpan('g', 'h', field2, "label")); - EXPECT_TRUE(HasSpan('b', 'c', field2, "extendee")); - - EXPECT_TRUE(HasSpan('n', 'o', field3)); - EXPECT_TRUE(HasSpan('l', 'm', field3, "extendee")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(field1, "type")); - EXPECT_TRUE(HasSpan(field1, "name")); - EXPECT_TRUE(HasSpan(field1, "number")); - EXPECT_TRUE(HasSpan(field2, "type_name")); - EXPECT_TRUE(HasSpan(field2, "name")); - EXPECT_TRUE(HasSpan(field2, "number")); - EXPECT_TRUE(HasSpan(field3, "label")); - EXPECT_TRUE(HasSpan(field3, "type")); - EXPECT_TRUE(HasSpan(field3, "name")); - EXPECT_TRUE(HasSpan(field3, "number")); -} - -TEST_F(SourceInfoTest, NestedExtensions) { - EXPECT_TRUE(Parse( - "message Message {\n" - " $a$extend $b$Foo$c$ {\n" - " $d$optional$e$ int32 bar = 1;$f$\n" - " $g$repeated$h$ X.Y baz = 2;$i$\n" - " }$j$\n" - " $k$extend $l$Bar$m$ {\n" - " $n$optional int32 qux = 1;$o$\n" - " }$p$\n" - "}\n")); - - const FieldDescriptorProto& field1 = file_.message_type(0).extension(0); - const FieldDescriptorProto& field2 = file_.message_type(0).extension(1); - const FieldDescriptorProto& field3 = file_.message_type(0).extension(2); - - EXPECT_TRUE(HasSpan('a', 'j', file_.message_type(0), "extension")); - EXPECT_TRUE(HasSpan('k', 'p', file_.message_type(0), "extension")); - - EXPECT_TRUE(HasSpan('d', 'f', field1)); - EXPECT_TRUE(HasSpan('d', 'e', field1, "label")); - EXPECT_TRUE(HasSpan('b', 'c', field1, "extendee")); - - EXPECT_TRUE(HasSpan('g', 'i', field2)); - EXPECT_TRUE(HasSpan('g', 'h', field2, "label")); - EXPECT_TRUE(HasSpan('b', 'c', field2, "extendee")); - - EXPECT_TRUE(HasSpan('n', 'o', field3)); - EXPECT_TRUE(HasSpan('l', 'm', field3, "extendee")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); - EXPECT_TRUE(HasSpan(field1, "type")); - EXPECT_TRUE(HasSpan(field1, "name")); - EXPECT_TRUE(HasSpan(field1, "number")); - EXPECT_TRUE(HasSpan(field2, "type_name")); - EXPECT_TRUE(HasSpan(field2, "name")); - EXPECT_TRUE(HasSpan(field2, "number")); - EXPECT_TRUE(HasSpan(field3, "label")); - EXPECT_TRUE(HasSpan(field3, "type")); - EXPECT_TRUE(HasSpan(field3, "name")); - EXPECT_TRUE(HasSpan(field3, "number")); -} - -TEST_F(SourceInfoTest, ExtensionRanges) { - EXPECT_TRUE(Parse( - "message Message {\n" - " $a$extensions $b$1$c$ to $d$4$e$, $f$6$g$;$h$\n" - " $i$extensions $j$8$k$ to $l$max$m$;$n$\n" - "}\n")); - - const DescriptorProto::ExtensionRange& range1 = - file_.message_type(0).extension_range(0); - const DescriptorProto::ExtensionRange& range2 = - file_.message_type(0).extension_range(1); - const DescriptorProto::ExtensionRange& range3 = - file_.message_type(0).extension_range(2); - - EXPECT_TRUE(HasSpan('a', 'h', file_.message_type(0), "extension_range")); - EXPECT_TRUE(HasSpan('i', 'n', file_.message_type(0), "extension_range")); - - EXPECT_TRUE(HasSpan('b', 'e', range1)); - EXPECT_TRUE(HasSpan('b', 'c', range1, "start")); - EXPECT_TRUE(HasSpan('d', 'e', range1, "end")); - - EXPECT_TRUE(HasSpan('f', 'g', range2)); - EXPECT_TRUE(HasSpan('f', 'g', range2, "start")); - EXPECT_TRUE(HasSpan('f', 'g', range2, "end")); - - EXPECT_TRUE(HasSpan('j', 'm', range3)); - EXPECT_TRUE(HasSpan('j', 'k', range3, "start")); - EXPECT_TRUE(HasSpan('l', 'm', range3, "end")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); -} - -TEST_F(SourceInfoTest, Oneofs) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$oneof $c$foo$d$ {\n" - " $e$int32$f$ $g$a$h$ = $i$1$j$;$k$\n" - " }$r$\n" - "}\n")); - - const OneofDescriptorProto& oneof_decl = file_.message_type(0).oneof_decl(0); - const FieldDescriptorProto& field = file_.message_type(0).field(0); - - EXPECT_TRUE(HasSpan('a', 'r', oneof_decl)); - EXPECT_TRUE(HasSpan('c', 'd', oneof_decl, "name")); - - EXPECT_TRUE(HasSpan('e', 'k', field)); - EXPECT_TRUE(HasSpan('e', 'f', field, "type")); - EXPECT_TRUE(HasSpan('g', 'h', field, "name")); - EXPECT_TRUE(HasSpan('i', 'j', field, "number")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); -} - -TEST_F(SourceInfoTest, NestedMessages) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$message $b$Bar$c$ {\n" - " $d$message $e$Baz$f$ {}$g$\n" - " }$h$\n" - " $i$message $j$Qux$k$ {}$l$\n" - "}\n")); - - const DescriptorProto& bar = file_.message_type(0).nested_type(0); - const DescriptorProto& baz = bar.nested_type(0); - const DescriptorProto& qux = file_.message_type(0).nested_type(1); - - EXPECT_TRUE(HasSpan('a', 'h', bar)); - EXPECT_TRUE(HasSpan('b', 'c', bar, "name")); - EXPECT_TRUE(HasSpan('d', 'g', baz)); - EXPECT_TRUE(HasSpan('e', 'f', baz, "name")); - EXPECT_TRUE(HasSpan('i', 'l', qux)); - EXPECT_TRUE(HasSpan('j', 'k', qux, "name")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); -} - -TEST_F(SourceInfoTest, Groups) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " message Bar {}\n" - " $a$optional$b$ $c$group$d$ $e$Baz$f$ = $g$1$h$ {\n" - " $i$message Qux {}$j$\n" - " }$k$\n" - "}\n")); - - const DescriptorProto& bar = file_.message_type(0).nested_type(0); - const DescriptorProto& baz = file_.message_type(0).nested_type(1); - const DescriptorProto& qux = baz.nested_type(0); - const FieldDescriptorProto& field = file_.message_type(0).field(0); - - EXPECT_TRUE(HasSpan('a', 'k', field)); - EXPECT_TRUE(HasSpan('a', 'b', field, "label")); - EXPECT_TRUE(HasSpan('c', 'd', field, "type")); - EXPECT_TRUE(HasSpan('e', 'f', field, "name")); - EXPECT_TRUE(HasSpan('e', 'f', field, "type_name")); - EXPECT_TRUE(HasSpan('g', 'h', field, "number")); - - EXPECT_TRUE(HasSpan('a', 'k', baz)); - EXPECT_TRUE(HasSpan('e', 'f', baz, "name")); - EXPECT_TRUE(HasSpan('i', 'j', qux)); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); - EXPECT_TRUE(HasSpan(bar)); - EXPECT_TRUE(HasSpan(bar, "name")); - EXPECT_TRUE(HasSpan(qux, "name")); -} - -TEST_F(SourceInfoTest, Enums) { - EXPECT_TRUE(Parse( - "$a$enum $b$Foo$c$ {}$d$\n" - "$e$enum $f$Bar$g$ {}$h$\n")); - - EXPECT_TRUE(HasSpan('a', 'd', file_.enum_type(0))); - EXPECT_TRUE(HasSpan('b', 'c', file_.enum_type(0), "name")); - EXPECT_TRUE(HasSpan('e', 'h', file_.enum_type(1))); - EXPECT_TRUE(HasSpan('f', 'g', file_.enum_type(1), "name")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); -} - -TEST_F(SourceInfoTest, EnumValues) { - EXPECT_TRUE(Parse( - "enum Foo {\n" - " $a$BAR$b$ = $c$1$d$;$e$\n" - " $f$BAZ$g$ = $h$2$i$;$j$\n" - "}")); - - const EnumValueDescriptorProto& bar = file_.enum_type(0).value(0); - const EnumValueDescriptorProto& baz = file_.enum_type(0).value(1); - - EXPECT_TRUE(HasSpan('a', 'e', bar)); - EXPECT_TRUE(HasSpan('a', 'b', bar, "name")); - EXPECT_TRUE(HasSpan('c', 'd', bar, "number")); - EXPECT_TRUE(HasSpan('f', 'j', baz)); - EXPECT_TRUE(HasSpan('f', 'g', baz, "name")); - EXPECT_TRUE(HasSpan('h', 'i', baz, "number")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.enum_type(0))); - EXPECT_TRUE(HasSpan(file_.enum_type(0), "name")); -} - -TEST_F(SourceInfoTest, NestedEnums) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$enum $b$Bar$c$ {}$d$\n" - " $e$enum $f$Baz$g$ {}$h$\n" - "}\n")); - - const EnumDescriptorProto& bar = file_.message_type(0).enum_type(0); - const EnumDescriptorProto& baz = file_.message_type(0).enum_type(1); - - EXPECT_TRUE(HasSpan('a', 'd', bar)); - EXPECT_TRUE(HasSpan('b', 'c', bar, "name")); - EXPECT_TRUE(HasSpan('e', 'h', baz)); - EXPECT_TRUE(HasSpan('f', 'g', baz, "name")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); -} - -TEST_F(SourceInfoTest, Services) { - EXPECT_TRUE(Parse( - "$a$service $b$Foo$c$ {}$d$\n" - "$e$service $f$Bar$g$ {}$h$\n")); - - EXPECT_TRUE(HasSpan('a', 'd', file_.service(0))); - EXPECT_TRUE(HasSpan('b', 'c', file_.service(0), "name")); - EXPECT_TRUE(HasSpan('e', 'h', file_.service(1))); - EXPECT_TRUE(HasSpan('f', 'g', file_.service(1), "name")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); -} - -TEST_F(SourceInfoTest, MethodsAndStreams) { - EXPECT_TRUE(Parse( - "service Foo {\n" - " $a$rpc $b$Bar$c$($d$X$e$) returns($f$Y$g$);$h$" - " $i$rpc $j$Baz$k$($l$Z$m$) returns($n$W$o$);$p$" - "}")); - - const MethodDescriptorProto& bar = file_.service(0).method(0); - const MethodDescriptorProto& baz = file_.service(0).method(1); - - EXPECT_TRUE(HasSpan('a', 'h', bar)); - EXPECT_TRUE(HasSpan('b', 'c', bar, "name")); - EXPECT_TRUE(HasSpan('d', 'e', bar, "input_type")); - EXPECT_TRUE(HasSpan('f', 'g', bar, "output_type")); - - EXPECT_TRUE(HasSpan('i', 'p', baz)); - EXPECT_TRUE(HasSpan('j', 'k', baz, "name")); - EXPECT_TRUE(HasSpan('l', 'm', baz, "input_type")); - EXPECT_TRUE(HasSpan('n', 'o', baz, "output_type")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.service(0))); - EXPECT_TRUE(HasSpan(file_.service(0), "name")); -} - - -TEST_F(SourceInfoTest, Options) { - EXPECT_TRUE(Parse( - "$a$option $b$foo$c$.$d$($e$bar.baz$f$)$g$ = " - "$h$123$i$;$j$\n" - "$k$option qux = $l$-123$m$;$n$\n" - "$o$option corge = $p$abc$q$;$r$\n" - "$s$option grault = $t$'blah'$u$;$v$\n" - "$w$option garply = $x${ yadda yadda }$y$;$z$\n" - "$0$option waldo = $1$123.0$2$;$3$\n" - )); - - const UninterpretedOption& option1 = file_.options().uninterpreted_option(0); - const UninterpretedOption& option2 = file_.options().uninterpreted_option(1); - const UninterpretedOption& option3 = file_.options().uninterpreted_option(2); - const UninterpretedOption& option4 = file_.options().uninterpreted_option(3); - const UninterpretedOption& option5 = file_.options().uninterpreted_option(4); - const UninterpretedOption& option6 = file_.options().uninterpreted_option(5); - - EXPECT_TRUE(HasSpan('a', 'j', file_.options())); - EXPECT_TRUE(HasSpan('a', 'j', option1)); - EXPECT_TRUE(HasSpan('b', 'g', option1, "name")); - EXPECT_TRUE(HasSpan('b', 'c', option1.name(0))); - EXPECT_TRUE(HasSpan('b', 'c', option1.name(0), "name_part")); - EXPECT_TRUE(HasSpan('d', 'g', option1.name(1))); - EXPECT_TRUE(HasSpan('e', 'f', option1.name(1), "name_part")); - EXPECT_TRUE(HasSpan('h', 'i', option1, "positive_int_value")); - - EXPECT_TRUE(HasSpan('k', 'n', file_.options())); - EXPECT_TRUE(HasSpan('l', 'm', option2, "negative_int_value")); - - EXPECT_TRUE(HasSpan('o', 'r', file_.options())); - EXPECT_TRUE(HasSpan('p', 'q', option3, "identifier_value")); - - EXPECT_TRUE(HasSpan('s', 'v', file_.options())); - EXPECT_TRUE(HasSpan('t', 'u', option4, "string_value")); - - EXPECT_TRUE(HasSpan('w', 'z', file_.options())); - EXPECT_TRUE(HasSpan('x', 'y', option5, "aggregate_value")); - - EXPECT_TRUE(HasSpan('0', '3', file_.options())); - EXPECT_TRUE(HasSpan('1', '2', option6, "double_value")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(option2)); - EXPECT_TRUE(HasSpan(option3)); - EXPECT_TRUE(HasSpan(option4)); - EXPECT_TRUE(HasSpan(option5)); - EXPECT_TRUE(HasSpan(option6)); - EXPECT_TRUE(HasSpan(option2, "name")); - EXPECT_TRUE(HasSpan(option3, "name")); - EXPECT_TRUE(HasSpan(option4, "name")); - EXPECT_TRUE(HasSpan(option5, "name")); - EXPECT_TRUE(HasSpan(option6, "name")); - EXPECT_TRUE(HasSpan(option2.name(0))); - EXPECT_TRUE(HasSpan(option3.name(0))); - EXPECT_TRUE(HasSpan(option4.name(0))); - EXPECT_TRUE(HasSpan(option5.name(0))); - EXPECT_TRUE(HasSpan(option6.name(0))); - EXPECT_TRUE(HasSpan(option2.name(0), "name_part")); - EXPECT_TRUE(HasSpan(option3.name(0), "name_part")); - EXPECT_TRUE(HasSpan(option4.name(0), "name_part")); - EXPECT_TRUE(HasSpan(option5.name(0), "name_part")); - EXPECT_TRUE(HasSpan(option6.name(0), "name_part")); -} - -TEST_F(SourceInfoTest, ScopedOptions) { - EXPECT_TRUE(Parse( - "message Foo {\n" - " $a$option mopt = 1;$b$\n" - "}\n" - "enum Bar {\n" - " $c$option eopt = 1;$d$\n" - "}\n" - "service Baz {\n" - " $e$option sopt = 1;$f$\n" - " rpc M(X) returns(Y) {\n" - " $g$option mopt = 1;$h$\n" - " }\n" - " rpc MS4($1$stream$2$ X) returns($3$stream$4$ Y) {\n" - " $k$option mopt = 1;$l$\n" - " }\n" - "}\n")); - - EXPECT_TRUE(HasSpan('a', 'b', file_.message_type(0).options())); - EXPECT_TRUE(HasSpan('c', 'd', file_.enum_type(0).options())); - EXPECT_TRUE(HasSpan('e', 'f', file_.service(0).options())); - EXPECT_TRUE(HasSpan('g', 'h', file_.service(0).method(0).options())); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.message_type(0).options() - .uninterpreted_option(0), "positive_int_value")); - EXPECT_TRUE(HasSpan(file_.enum_type(0))); - EXPECT_TRUE(HasSpan(file_.enum_type(0), "name")); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.enum_type(0).options() - .uninterpreted_option(0), "positive_int_value")); - EXPECT_TRUE(HasSpan(file_.service(0))); - EXPECT_TRUE(HasSpan(file_.service(0), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0))); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.service(0).options() - .uninterpreted_option(0), "positive_int_value")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0), "input_type")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0), "output_type")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.service(0).method(0).options() - .uninterpreted_option(0), "positive_int_value")); - - EXPECT_TRUE(HasSpan('k', 'l', file_.service(0).method(1).options())); - EXPECT_TRUE(HasSpan(file_.service(0).method(1))); - EXPECT_TRUE(HasSpan(file_.service(0).method(1), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).method(1), "input_type")); - EXPECT_TRUE(HasSpan(file_.service(0).method(1), "output_type")); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan(file_.service(0).method(1).options() - .uninterpreted_option(0), "positive_int_value")); - EXPECT_TRUE(HasSpan('1', '2', file_.service(0).method(1), - "client_streaming")); - EXPECT_TRUE(HasSpan('3', '4', file_.service(0).method(1), - "server_streaming")); -} - -TEST_F(SourceInfoTest, FieldOptions) { - // The actual "name = value" pairs are parsed by the same code as for - // top-level options so we won't re-test that -- just make sure that the - // syntax used for field options is understood. - EXPECT_TRUE(Parse( - "message Foo {" - " optional int32 bar = 1 " - "$a$[default=$b$123$c$,$d$opt1=123$e$," - "$f$opt2='hi'$g$]$h$;" - "}\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('b', 'c', field, "default_value")); - EXPECT_TRUE(HasSpan('d', 'e', option1)); - EXPECT_TRUE(HasSpan('f', 'g', option2)); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.message_type(0))); - EXPECT_TRUE(HasSpan(file_.message_type(0), "name")); - EXPECT_TRUE(HasSpan(field)); - EXPECT_TRUE(HasSpan(field, "label")); - EXPECT_TRUE(HasSpan(field, "type")); - EXPECT_TRUE(HasSpan(field, "name")); - EXPECT_TRUE(HasSpan(field, "number")); - EXPECT_TRUE(HasSpan(option1, "name")); - EXPECT_TRUE(HasSpan(option2, "name")); - EXPECT_TRUE(HasSpan(option1.name(0))); - EXPECT_TRUE(HasSpan(option2.name(0))); - EXPECT_TRUE(HasSpan(option1.name(0), "name_part")); - EXPECT_TRUE(HasSpan(option2.name(0), "name_part")); - EXPECT_TRUE(HasSpan(option1, "positive_int_value")); - EXPECT_TRUE(HasSpan(option2, "string_value")); -} - -TEST_F(SourceInfoTest, EnumValueOptions) { - // The actual "name = value" pairs are parsed by the same code as for - // top-level options so we won't re-test that -- just make sure that the - // syntax used for enum options is understood. - EXPECT_TRUE(Parse( - "enum Foo {" - " BAR = 1 $a$[$b$opt1=123$c$,$d$opt2='hi'$e$]$f$;" - "}\n" - )); - - const EnumValueDescriptorProto& value = file_.enum_type(0).value(0); - const UninterpretedOption& option1 = value.options().uninterpreted_option(0); - const UninterpretedOption& option2 = value.options().uninterpreted_option(1); - - EXPECT_TRUE(HasSpan('a', 'f', value.options())); - EXPECT_TRUE(HasSpan('b', 'c', option1)); - EXPECT_TRUE(HasSpan('d', 'e', option2)); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(file_.enum_type(0))); - EXPECT_TRUE(HasSpan(file_.enum_type(0), "name")); - EXPECT_TRUE(HasSpan(value)); - EXPECT_TRUE(HasSpan(value, "name")); - EXPECT_TRUE(HasSpan(value, "number")); - EXPECT_TRUE(HasSpan(option1, "name")); - EXPECT_TRUE(HasSpan(option2, "name")); - EXPECT_TRUE(HasSpan(option1.name(0))); - EXPECT_TRUE(HasSpan(option2.name(0))); - EXPECT_TRUE(HasSpan(option1.name(0), "name_part")); - EXPECT_TRUE(HasSpan(option2.name(0), "name_part")); - EXPECT_TRUE(HasSpan(option1, "positive_int_value")); - EXPECT_TRUE(HasSpan(option2, "string_value")); -} - -TEST_F(SourceInfoTest, DocComments) { - EXPECT_TRUE(Parse( - "// Foo leading\n" - "// line 2\n" - "$a$message Foo {\n" - " // Foo trailing\n" - " // line 2\n" - "\n" - " // detached\n" - "\n" - " // bar leading\n" - " $b$optional int32 bar = 1;$c$\n" - " // bar trailing\n" - "}$d$\n" - "// ignored\n" - )); - - const DescriptorProto& foo = file_.message_type(0); - const FieldDescriptorProto& bar = foo.field(0); - - EXPECT_TRUE(HasSpanWithComment('a', 'd', foo, - " Foo leading\n line 2\n", - " Foo trailing\n line 2\n", - NULL)); - EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, - " bar leading\n", - " bar trailing\n", - " detached\n")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(foo, "name")); - EXPECT_TRUE(HasSpan(bar, "label")); - EXPECT_TRUE(HasSpan(bar, "type")); - EXPECT_TRUE(HasSpan(bar, "name")); - EXPECT_TRUE(HasSpan(bar, "number")); -} - -TEST_F(SourceInfoTest, DocComments2) { - EXPECT_TRUE(Parse( - "// detached before message.\n" - "\n" - "// Foo leading\n" - "// line 2\n" - "$a$message Foo {\n" - " /* Foo trailing\n" - " * line 2 */\n" - " // detached\n" - " /* bar leading\n" - " */" - " $b$optional int32 bar = 1;$c$ // bar trailing\n" - " // ignored detached\n" - "}$d$\n" - "// ignored\n" - "\n" - "// detached before option\n" - "\n" - "// option leading\n" - "$e$option baz = 123;$f$\n" - "// option trailing\n" - )); - - const DescriptorProto& foo = file_.message_type(0); - const FieldDescriptorProto& bar = foo.field(0); - const UninterpretedOption& baz = file_.options().uninterpreted_option(0); - - EXPECT_TRUE(HasSpanWithComment('a', 'd', foo, - " Foo leading\n line 2\n", - " Foo trailing\n line 2 ", - " detached before message.\n")); - EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, - " bar leading\n", - " bar trailing\n", - " detached\n")); - EXPECT_TRUE(HasSpanWithComment('e', 'f', baz, - " option leading\n", - " option trailing\n", - " detached before option\n")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(foo, "name")); - EXPECT_TRUE(HasSpan(bar, "label")); - EXPECT_TRUE(HasSpan(bar, "type")); - EXPECT_TRUE(HasSpan(bar, "name")); - EXPECT_TRUE(HasSpan(bar, "number")); - EXPECT_TRUE(HasSpan(file_.options())); - EXPECT_TRUE(HasSpan(baz, "name")); - EXPECT_TRUE(HasSpan(baz.name(0))); - EXPECT_TRUE(HasSpan(baz.name(0), "name_part")); - EXPECT_TRUE(HasSpan(baz, "positive_int_value")); -} - -TEST_F(SourceInfoTest, DocComments3) { - EXPECT_TRUE(Parse( - "$a$message Foo {\n" - " // bar leading\n" - " $b$optional int32 bar = 1 [(baz.qux) = {}];$c$\n" - " // bar trailing\n" - "}$d$\n" - "// ignored\n" - )); - - const DescriptorProto& foo = file_.message_type(0); - const FieldDescriptorProto& bar = foo.field(0); - - EXPECT_TRUE(HasSpanWithComment('b', 'c', bar, - " bar leading\n", - " bar trailing\n", - NULL)); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(foo)); - EXPECT_TRUE(HasSpan(foo, "name")); - EXPECT_TRUE(HasSpan(bar, "label")); - EXPECT_TRUE(HasSpan(bar, "type")); - EXPECT_TRUE(HasSpan(bar, "name")); - EXPECT_TRUE(HasSpan(bar, "number")); - EXPECT_TRUE(HasSpan(bar.options())); - EXPECT_TRUE(HasSpan(bar.options().uninterpreted_option(0))); - EXPECT_TRUE(HasSpan(bar.options().uninterpreted_option(0), "name")); - EXPECT_TRUE(HasSpan(bar.options().uninterpreted_option(0).name(0))); - EXPECT_TRUE(HasSpan( - bar.options().uninterpreted_option(0).name(0), "name_part")); - EXPECT_TRUE(HasSpan( - bar.options().uninterpreted_option(0), "aggregate_value")); -} - -TEST_F(SourceInfoTest, DocCommentsTopLevel) { - EXPECT_TRUE(Parse( - "// detached before syntax paragraph 1\n" - "\n" - "// detached before syntax paragraph 2\n" - "\n" - "// syntax leading\n" - "$a$syntax = \"proto2\";$b$\n" - "// syntax trailing\n" - "\n" - "// syntax-package detached comments\n" - "\n" - ";\n" - "\n" - "// detached after empty before package\n" - "\n" - "// package leading\n" - "package $c$foo$d$;\n" - "// package trailing\n" - "\n" - "// ignored detach\n" - "\n")); - - EXPECT_TRUE(HasSpan('a', 'b', file_, "syntax", -1, - " syntax leading\n", - " syntax trailing\n", - " detached before syntax paragraph 1\n" - "\n" - " detached before syntax paragraph 2\n")); - EXPECT_TRUE(HasSpan('c', 'd', file_, "package", -1, - " package leading\n", - " package trailing\n", - " syntax-package detached comments\n" - "\n" - " detached after empty before package\n")); - - // ignore these. - EXPECT_TRUE(HasSpan(file_)); -} - -TEST_F(SourceInfoTest, DocCommentsOneof) { - EXPECT_TRUE(Parse( - "// Foo leading\n" - "$a$message Foo {\n" - " /* Foo trailing\n" - " */\n" - " // detached before oneof\n" - " /* bar leading\n" - " * line 2 */\n" - " $b$oneof bar {\n" - " /* bar trailing\n" - " * line 2 */\n" - " // detached before bar_int\n" - " /* bar_int leading\n" - " */\n" - " $c$int32 bar_int = 1;$d$ // bar_int trailing\n" - " // detach comment ignored\n" - " }$e$\n" - "}$f$\n")); - - const DescriptorProto& foo = file_.message_type(0); - const OneofDescriptorProto& bar = foo.oneof_decl(0); - const FieldDescriptorProto& bar_int = foo.field(0); - - EXPECT_TRUE(HasSpanWithComment('a', 'f', foo, - " Foo leading\n", - " Foo trailing\n", - NULL)); - EXPECT_TRUE(HasSpanWithComment('b', 'e', bar, - " bar leading\n line 2 ", - " bar trailing\n line 2 ", - " detached before oneof\n")); - EXPECT_TRUE(HasSpanWithComment('c', 'd', bar_int, - " bar_int leading\n", - " bar_int trailing\n", - " detached before bar_int\n")); - - // Ignore these. - EXPECT_TRUE(HasSpan(file_)); - EXPECT_TRUE(HasSpan(foo, "name")); - EXPECT_TRUE(HasSpan(bar, "name")); - EXPECT_TRUE(HasSpan(bar_int, "type")); - EXPECT_TRUE(HasSpan(bar_int, "name")); - EXPECT_TRUE(HasSpan(bar_int, "number")); -} - -// =================================================================== - -} // anonymous namespace - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/php/php_generator.cc b/windows/include/google/protobuf/compiler/php/php_generator.cc deleted file mode 100644 index a58e1754d..000000000 --- a/windows/include/google/protobuf/compiler/php/php_generator.cc +++ /dev/null @@ -1,1563 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include - -const std::string kDescriptorFile = "google/protobuf/descriptor.proto"; -const std::string kEmptyFile = "google/protobuf/empty.proto"; -const std::string kEmptyMetadataFile = "GPBMetadata/Google/Protobuf/GPBEmpty.php"; -const std::string kDescriptorMetadataFile = - "GPBMetadata/Google/Protobuf/Internal/Descriptor.php"; -const std::string kDescriptorDirName = "Google/Protobuf/Internal"; -const std::string kDescriptorPackageName = "Google\\Protobuf\\Internal"; -const char* const kReservedNames[] = { - "abstract", "and", "array", "as", "break", - "callable", "case", "catch", "class", "clone", - "const", "continue", "declare", "default", "die", - "do", "echo", "else", "elseif", "empty", - "enddeclare", "endfor", "endforeach", "endif", "endswitch", - "endwhile", "eval", "exit", "extends", "final", - "for", "foreach", "function", "global", "goto", - "if", "implements", "include", "include_once", "instanceof", - "insteadof", "interface", "isset", "list", "namespace", - "new", "or", "print", "private", "protected", - "public", "require", "require_once", "return", "static", - "switch", "throw", "trait", "try", "unset", - "use", "var", "while", "xor", "int", - "float", "bool", "string", "true", "false", - "null", "void", "iterable"}; -const char* const kValidConstantNames[] = { - "int", "float", "bool", "string", "true", - "false", "null", "void", "iterable", -}; -const int kReservedNamesSize = 73; -const int kValidConstantNamesSize = 9; -const int kFieldSetter = 1; -const int kFieldGetter = 2; -const int kFieldProperty = 3; - -namespace google { -namespace protobuf { -namespace compiler { -namespace php { - -// Forward decls. -std::string PhpName(const std::string& full_name, bool is_descriptor); -std::string DefaultForField(FieldDescriptor* field); -std::string IntToString(int32 value); -std::string FilenameToClassname(const string& filename); -std::string GeneratedMetadataFileName(const FileDescriptor* file, - bool is_descriptor); -std::string LabelForField(FieldDescriptor* field); -std::string TypeName(FieldDescriptor* field); -std::string UnderscoresToCamelCase(const string& name, bool cap_first_letter); -std::string EscapeDollor(const string& to_escape); -std::string BinaryToHex(const string& binary); -void Indent(io::Printer* printer); -void Outdent(io::Printer* printer); -void GenerateMessageDocComment(io::Printer* printer, const Descriptor* message, - int is_descriptor); -void GenerateMessageConstructorDocComment(io::Printer* printer, - const Descriptor* message, - int is_descriptor); -void GenerateFieldDocComment(io::Printer* printer, const FieldDescriptor* field, - int is_descriptor, int function_type); -void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_, - int is_descriptor); -void GenerateEnumValueDocComment(io::Printer* printer, - const EnumValueDescriptor* value); -void GenerateServiceDocComment(io::Printer* printer, - const ServiceDescriptor* service); -void GenerateServiceMethodDocComment(io::Printer* printer, - const MethodDescriptor* method); - - -std::string ReservedNamePrefix(const string& classname, - const FileDescriptor* file) { - bool is_reserved = false; - - string lower = classname; - transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - - for (int i = 0; i < kReservedNamesSize; i++) { - if (lower == kReservedNames[i]) { - is_reserved = true; - break; - } - } - - if (is_reserved) { - if (file->package() == "google.protobuf") { - return "GPB"; - } else { - return "PB"; - } - } - - return ""; -} - -template -std::string DescriptorFullName(const DescriptorType* desc, bool is_descriptor) { - if (is_descriptor) { - return StringReplace(desc->full_name(), - "google.protobuf", - "google.protobuf.internal", false); - } else { - return desc->full_name(); - } -} - -template -std::string ClassNamePrefix(const string& classname, - const DescriptorType* desc) { - const string& prefix = (desc->file()->options()).php_class_prefix(); - if (prefix != "") { - return prefix; - } - - return ReservedNamePrefix(classname, desc->file()); -} - -template -std::string GeneratedClassNameImpl(const DescriptorType* desc) { - std::string classname = ClassNamePrefix(desc->name(), desc) + desc->name(); - const Descriptor* containing = desc->containing_type(); - while (containing != NULL) { - classname = ClassNamePrefix(containing->name(), desc) + containing->name() - + '\\' + classname; - containing = containing->containing_type(); - } - return classname; -} - -std::string GeneratedClassNameImpl(const ServiceDescriptor* desc) { - std::string classname = desc->name(); - return ClassNamePrefix(classname, desc) + classname; -} - -std::string GeneratedClassName(const Descriptor* desc) { - return GeneratedClassNameImpl(desc); -} - -std::string GeneratedClassName(const EnumDescriptor* desc) { - return GeneratedClassNameImpl(desc); -} - -std::string GeneratedClassName(const ServiceDescriptor* desc) { - return GeneratedClassNameImpl(desc); -} - -template -std::string LegacyGeneratedClassName(const DescriptorType* desc) { - std::string classname = desc->name(); - const Descriptor* containing = desc->containing_type(); - while (containing != NULL) { - classname = containing->name() + '_' + classname; - containing = containing->containing_type(); - } - return ClassNamePrefix(classname, desc) + classname; -} - -std::string ClassNamePrefix(const string& classname) { - string lower = classname; - transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - - for (int i = 0; i < kReservedNamesSize; i++) { - if (lower == kReservedNames[i]) { - return "PB"; - } - } - - return ""; -} - -std::string ConstantNamePrefix(const string& classname) { - bool is_reserved = false; - - string lower = classname; - transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - - for (int i = 0; i < kReservedNamesSize; i++) { - if (lower == kReservedNames[i]) { - is_reserved = true; - break; - } - } - - for (int i = 0; i < kValidConstantNamesSize; i++) { - if (lower == kValidConstantNames[i]) { - is_reserved = false; - break; - } - } - - if (is_reserved) { - return "PB"; - } - - return ""; -} - -template -std::string RootPhpNamespace(const DescriptorType* desc, bool is_descriptor) { - if (desc->file()->options().has_php_namespace()) { - const string& php_namespace = desc->file()->options().php_namespace(); - if (php_namespace != "") { - return php_namespace; - } - return ""; - } - - if (desc->file()->package() != "") { - return PhpName(desc->file()->package(), is_descriptor); - } - return ""; -} - -template -std::string FullClassName(const DescriptorType* desc, bool is_descriptor) { - string classname = GeneratedClassNameImpl(desc); - string php_namespace = RootPhpNamespace(desc, is_descriptor); - if (php_namespace != "") { - return php_namespace + "\\" + classname; - } - return classname; -} - -template -std::string LegacyFullClassName(const DescriptorType* desc, bool is_descriptor) { - string classname = LegacyGeneratedClassName(desc); - string php_namespace = RootPhpNamespace(desc, is_descriptor); - if (php_namespace != "") { - return php_namespace + "\\" + classname; - } - return classname; -} - -std::string PhpName(const std::string& full_name, bool is_descriptor) { - if (is_descriptor) { - return kDescriptorPackageName; - } - - std::string segment; - std::string result; - bool cap_next_letter = true; - for (int i = 0; i < full_name.size(); i++) { - if ('a' <= full_name[i] && full_name[i] <= 'z' && cap_next_letter) { - segment += full_name[i] + ('A' - 'a'); - cap_next_letter = false; - } else if (full_name[i] == '.') { - result += ClassNamePrefix(segment) + segment + '\\'; - segment = ""; - cap_next_letter = true; - } else { - segment += full_name[i]; - cap_next_letter = false; - } - } - result += ClassNamePrefix(segment) + segment; - return result; -} - -std::string DefaultForField(const FieldDescriptor* field) { - switch (field->type()) { - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_SFIXED32: - case FieldDescriptor::TYPE_SFIXED64: - case FieldDescriptor::TYPE_ENUM: return "0"; - case FieldDescriptor::TYPE_DOUBLE: - case FieldDescriptor::TYPE_FLOAT: return "0.0"; - case FieldDescriptor::TYPE_BOOL: return "false"; - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_BYTES: return "''"; - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_GROUP: return "null"; - default: assert(false); return ""; - } -} - -std::string GeneratedMetadataFileName(const FileDescriptor* file, - bool is_descriptor) { - const string& proto_file = file->name(); - int start_index = 0; - int first_index = proto_file.find_first_of("/", start_index); - std::string result = ""; - std::string segment = ""; - - if (proto_file == kEmptyFile) { - return kEmptyMetadataFile; - } - if (is_descriptor) { - return kDescriptorMetadataFile; - } - - // Append directory name. - std::string file_no_suffix; - int lastindex = proto_file.find_last_of("."); - if (proto_file == kEmptyFile) { - return kEmptyMetadataFile; - } else { - file_no_suffix = proto_file.substr(0, lastindex); - } - - if (file->options().has_php_metadata_namespace()) { - const string& php_metadata_namespace = - file->options().php_metadata_namespace(); - if (php_metadata_namespace != "" && php_metadata_namespace != "\\") { - result += php_metadata_namespace; - std::replace(result.begin(), result.end(), '\\', '/'); - if (result.at(result.size() - 1) != '/') { - result += "/"; - } - } - } else { - result += "GPBMetadata/"; - while (first_index != string::npos) { - segment = UnderscoresToCamelCase( - file_no_suffix.substr(start_index, first_index - start_index), true); - result += ReservedNamePrefix(segment, file) + segment + "/"; - start_index = first_index + 1; - first_index = file_no_suffix.find_first_of("/", start_index); - } - } - - // Append file name. - int file_name_start = file_no_suffix.find_last_of("/"); - if (file_name_start == string::npos) { - file_name_start = 0; - } else { - file_name_start += 1; - } - segment = UnderscoresToCamelCase( - file_no_suffix.substr(file_name_start, first_index - file_name_start), true); - - return result + ReservedNamePrefix(segment, file) + segment + ".php"; -} - -template -std::string GeneratedClassFileName(const DescriptorType* desc, - bool is_descriptor) { - std::string result = FullClassName(desc, is_descriptor); - for (int i = 0; i < result.size(); i++) { - if (result[i] == '\\') { - result[i] = '/'; - } - } - return result + ".php"; -} - -template -std::string LegacyGeneratedClassFileName(const DescriptorType* desc, - bool is_descriptor) { - std::string result = LegacyFullClassName(desc, is_descriptor); - - for (int i = 0; i < result.size(); i++) { - if (result[i] == '\\') { - result[i] = '/'; - } - } - return result + ".php"; -} - -std::string GeneratedServiceFileName(const ServiceDescriptor* service, - bool is_descriptor) { - std::string result = FullClassName(service, is_descriptor) + "Interface"; - for (int i = 0; i < result.size(); i++) { - if (result[i] == '\\') { - result[i] = '/'; - } - } - return result + ".php"; -} - -std::string IntToString(int32 value) { - std::ostringstream os; - os << value; - return os.str(); -} - -std::string LabelForField(const FieldDescriptor* field) { - switch (field->label()) { - case FieldDescriptor::LABEL_OPTIONAL: return "optional"; - case FieldDescriptor::LABEL_REQUIRED: return "required"; - case FieldDescriptor::LABEL_REPEATED: return "repeated"; - default: assert(false); return ""; - } -} - -std::string TypeName(const FieldDescriptor* field) { - switch (field->type()) { - case FieldDescriptor::TYPE_INT32: return "int32"; - case FieldDescriptor::TYPE_INT64: return "int64"; - case FieldDescriptor::TYPE_UINT32: return "uint32"; - case FieldDescriptor::TYPE_UINT64: return "uint64"; - case FieldDescriptor::TYPE_SINT32: return "sint32"; - case FieldDescriptor::TYPE_SINT64: return "sint64"; - case FieldDescriptor::TYPE_FIXED32: return "fixed32"; - case FieldDescriptor::TYPE_FIXED64: return "fixed64"; - case FieldDescriptor::TYPE_SFIXED32: return "sfixed32"; - case FieldDescriptor::TYPE_SFIXED64: return "sfixed64"; - case FieldDescriptor::TYPE_DOUBLE: return "double"; - case FieldDescriptor::TYPE_FLOAT: return "float"; - case FieldDescriptor::TYPE_BOOL: return "bool"; - case FieldDescriptor::TYPE_ENUM: return "enum"; - case FieldDescriptor::TYPE_STRING: return "string"; - case FieldDescriptor::TYPE_BYTES: return "bytes"; - case FieldDescriptor::TYPE_MESSAGE: return "message"; - case FieldDescriptor::TYPE_GROUP: return "group"; - default: assert(false); return ""; - } -} - -std::string PhpSetterTypeName(const FieldDescriptor* field, bool is_descriptor) { - if (field->is_map()) { - return "array|\\Google\\Protobuf\\Internal\\MapField"; - } - string type; - switch (field->type()) { - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_SFIXED32: - case FieldDescriptor::TYPE_ENUM: - type = "int"; - break; - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_SFIXED64: - type = "int|string"; - break; - case FieldDescriptor::TYPE_DOUBLE: - case FieldDescriptor::TYPE_FLOAT: - type = "float"; - break; - case FieldDescriptor::TYPE_BOOL: - type = "bool"; - break; - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_BYTES: - type = "string"; - break; - case FieldDescriptor::TYPE_MESSAGE: - type = "\\" + FullClassName(field->message_type(), is_descriptor); - break; - case FieldDescriptor::TYPE_GROUP: - return "null"; - default: assert(false); return ""; - } - if (field->is_repeated()) { - // accommodate for edge case with multiple types. - size_t start_pos = type.find("|"); - if (start_pos != std::string::npos) { - type.replace(start_pos, 1, "[]|"); - } - type += "[]|\\Google\\Protobuf\\Internal\\RepeatedField"; - } - return type; -} - -std::string PhpGetterTypeName(const FieldDescriptor* field, bool is_descriptor) { - if (field->is_map()) { - return "\\Google\\Protobuf\\Internal\\MapField"; - } - if (field->is_repeated()) { - return "\\Google\\Protobuf\\Internal\\RepeatedField"; - } - switch (field->type()) { - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_SFIXED32: - case FieldDescriptor::TYPE_ENUM: return "int"; - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_SFIXED64: return "int|string"; - case FieldDescriptor::TYPE_DOUBLE: - case FieldDescriptor::TYPE_FLOAT: return "float"; - case FieldDescriptor::TYPE_BOOL: return "bool"; - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_BYTES: return "string"; - case FieldDescriptor::TYPE_MESSAGE: - return "\\" + FullClassName(field->message_type(), is_descriptor); - case FieldDescriptor::TYPE_GROUP: return "null"; - default: assert(false); return ""; - } -} - -std::string EnumOrMessageSuffix( - const FieldDescriptor* field, bool is_descriptor) { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - return ", '" + DescriptorFullName(field->message_type(), is_descriptor) + "'"; - } - if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - return ", '" + DescriptorFullName(field->enum_type(), is_descriptor) + "'"; - } - return ""; -} - -// Converts a name to camel-case. If cap_first_letter is true, capitalize the -// first letter. -std::string UnderscoresToCamelCase(const string& input, bool cap_first_letter) { - std::string result; - for (int i = 0; i < input.size(); i++) { - if ('a' <= input[i] && input[i] <= 'z') { - if (cap_first_letter) { - result += input[i] + ('A' - 'a'); - } else { - result += input[i]; - } - cap_first_letter = false; - } else if ('A' <= input[i] && input[i] <= 'Z') { - if (i == 0 && !cap_first_letter) { - // Force first letter to lower-case unless explicitly told to - // capitalize it. - result += input[i] + ('a' - 'A'); - } else { - // Capital letters after the first are left as-is. - result += input[i]; - } - cap_first_letter = false; - } else if ('0' <= input[i] && input[i] <= '9') { - result += input[i]; - cap_first_letter = true; - } else { - cap_first_letter = true; - } - } - // Add a trailing "_" if the name should be altered. - if (input[input.size() - 1] == '#') { - result += '_'; - } - return result; -} - -std::string EscapeDollor(const string& to_escape) { - return StringReplace(to_escape, "$", "\\$", true); -} - -std::string BinaryToHex(const string& src) { - string dest; - size_t i; - unsigned char symbol[16] = { - '0', '1', '2', '3', - '4', '5', '6', '7', - '8', '9', 'a', 'b', - 'c', 'd', 'e', 'f', - }; - - dest.resize(src.size() * 2); - char* append_ptr = &dest[0]; - - for (i = 0; i < src.size(); i++) { - *append_ptr++ = symbol[(src[i] & 0xf0) >> 4]; - *append_ptr++ = symbol[src[i] & 0x0f]; - } - - return dest; -} - -void Indent(io::Printer* printer) { - printer->Indent(); - printer->Indent(); -} -void Outdent(io::Printer* printer) { - printer->Outdent(); - printer->Outdent(); -} - -void GenerateField(const FieldDescriptor* field, io::Printer* printer, - bool is_descriptor) { - if (field->is_repeated()) { - GenerateFieldDocComment(printer, field, is_descriptor, kFieldProperty); - printer->Print( - "private $^name^;\n", - "name", field->name()); - } else if (field->containing_oneof()) { - // Oneof fields are handled by GenerateOneofField. - return; - } else { - GenerateFieldDocComment(printer, field, is_descriptor, kFieldProperty); - printer->Print( - "private $^name^ = ^default^;\n", - "name", field->name(), - "default", DefaultForField(field)); - } - - if (is_descriptor) { - printer->Print( - "private $has_^name^ = false;\n", - "name", field->name()); - } -} - -void GenerateOneofField(const OneofDescriptor* oneof, io::Printer* printer) { - // Oneof property needs to be protected in order to be accessed by parent - // class in implementation. - printer->Print( - "protected $^name^;\n", - "name", oneof->name()); -} - -void GenerateFieldAccessor(const FieldDescriptor* field, bool is_descriptor, - io::Printer* printer) { - const OneofDescriptor* oneof = field->containing_oneof(); - - // Generate getter. - if (oneof != NULL) { - GenerateFieldDocComment(printer, field, is_descriptor, kFieldGetter); - printer->Print( - "public function get^camel_name^()\n" - "{\n" - " return $this->readOneof(^number^);\n" - "}\n\n", - "camel_name", UnderscoresToCamelCase(field->name(), true), - "number", IntToString(field->number())); - } else { - GenerateFieldDocComment(printer, field, is_descriptor, kFieldGetter); - printer->Print( - "public function get^camel_name^()\n" - "{\n" - " return $this->^name^;\n" - "}\n\n", - "camel_name", UnderscoresToCamelCase(field->name(), true), "name", - field->name()); - } - - // Generate setter. - GenerateFieldDocComment(printer, field, is_descriptor, kFieldSetter); - printer->Print( - "public function set^camel_name^($var)\n" - "{\n", - "camel_name", UnderscoresToCamelCase(field->name(), true)); - - Indent(printer); - - // Type check. - if (field->is_map()) { - const Descriptor* map_entry = field->message_type(); - const FieldDescriptor* key = map_entry->FindFieldByName("key"); - const FieldDescriptor* value = map_entry->FindFieldByName("value"); - printer->Print( - "$arr = GPBUtil::checkMapField($var, " - "\\Google\\Protobuf\\Internal\\GPBType::^key_type^, " - "\\Google\\Protobuf\\Internal\\GPBType::^value_type^", - "key_type", ToUpper(key->type_name()), - "value_type", ToUpper(value->type_name())); - if (value->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - printer->Print( - ", \\^class_name^);\n", - "class_name", - FullClassName(value->message_type(), is_descriptor) + "::class"); - } else if (value->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - printer->Print( - ", \\^class_name^);\n", - "class_name", - FullClassName(value->enum_type(), is_descriptor) + "::class"); - } else { - printer->Print(");\n"); - } - } else if (field->is_repeated()) { - printer->Print( - "$arr = GPBUtil::checkRepeatedField($var, " - "\\Google\\Protobuf\\Internal\\GPBType::^type^", - "type", ToUpper(field->type_name())); - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - printer->Print( - ", \\^class_name^);\n", - "class_name", - FullClassName(field->message_type(), is_descriptor) + "::class"); - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - printer->Print( - ", \\^class_name^);\n", - "class_name", - FullClassName(field->enum_type(), is_descriptor) + "::class"); - } else { - printer->Print(");\n"); - } - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - printer->Print( - "GPBUtil::checkMessage($var, \\^class_name^::class);\n", - "class_name", LegacyFullClassName(field->message_type(), is_descriptor)); - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - printer->Print( - "GPBUtil::checkEnum($var, \\^class_name^::class);\n", - "class_name", LegacyFullClassName(field->enum_type(), is_descriptor)); - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { - printer->Print( - "GPBUtil::checkString($var, ^utf8^);\n", - "utf8", - field->type() == FieldDescriptor::TYPE_STRING ? "True": "False"); - } else { - printer->Print( - "GPBUtil::check^type^($var);\n", - "type", UnderscoresToCamelCase(field->cpp_type_name(), true)); - } - - if (oneof != NULL) { - printer->Print( - "$this->writeOneof(^number^, $var);\n", - "number", IntToString(field->number())); - } else if (field->is_repeated()) { - printer->Print( - "$this->^name^ = $arr;\n", - "name", field->name()); - } else { - printer->Print( - "$this->^name^ = $var;\n", - "name", field->name()); - } - - // Set has bit for proto2 only. - if (is_descriptor) { - printer->Print( - "$this->has_^field_name^ = true;\n", - "field_name", field->name()); - } - - printer->Print("\nreturn $this;\n"); - - Outdent(printer); - - printer->Print( - "}\n\n"); - - // Generate has method for proto2 only. - if (is_descriptor) { - printer->Print( - "public function has^camel_name^()\n" - "{\n" - " return $this->has_^field_name^;\n" - "}\n\n", - "camel_name", UnderscoresToCamelCase(field->name(), true), - "field_name", field->name()); - } -} - -void GenerateEnumToPool(const EnumDescriptor* en, io::Printer* printer) { - printer->Print( - "$pool->addEnum('^name^', " - "\\Google\\Protobuf\\Internal\\^class_name^::class)\n", - "name", DescriptorFullName(en, true), - "class_name", en->name()); - Indent(printer); - - for (int i = 0; i < en->value_count(); i++) { - const EnumValueDescriptor* value = en->value(i); - printer->Print( - "->value(\"^name^\", ^number^)\n", - "name", ConstantNamePrefix(value->name()) + value->name(), - "number", IntToString(value->number())); - } - printer->Print("->finalizeToPool();\n\n"); - Outdent(printer); -} - -void GenerateServiceMethod(const MethodDescriptor* method, - io::Printer* printer) { - printer->Print( - "public function ^camel_name^(\\^request_name^ $request);\n\n", - "camel_name", UnderscoresToCamelCase(method->name(), false), - "request_name", FullClassName( - method->input_type(), false) - ); -} - -void GenerateMessageToPool(const string& name_prefix, const Descriptor* message, - io::Printer* printer) { - // Don't generate MapEntry messages -- we use the PHP extension's native - // support for map fields instead. - if (message->options().map_entry()) { - return; - } - string class_name = (name_prefix.empty() ? "" : name_prefix + "\\") + - ReservedNamePrefix(message->name(), message->file()) + message->name(); - - printer->Print( - "$pool->addMessage('^message^', " - "\\Google\\Protobuf\\Internal\\^class_name^::class)\n", - "message", DescriptorFullName(message, true), - "class_name", class_name); - - Indent(printer); - - for (int i = 0; i < message->field_count(); i++) { - const FieldDescriptor* field = message->field(i); - if (field->is_map()) { - const FieldDescriptor* key = - field->message_type()->FindFieldByName("key"); - const FieldDescriptor* val = - field->message_type()->FindFieldByName("value"); - printer->Print( - "->map('^field^', \\Google\\Protobuf\\Internal\\GPBType::^key^, " - "\\Google\\Protobuf\\Internal\\GPBType::^value^, ^number^^other^)\n", - "field", field->name(), - "key", ToUpper(key->type_name()), - "value", ToUpper(val->type_name()), - "number", SimpleItoa(field->number()), - "other", EnumOrMessageSuffix(val, true)); - } else if (!field->containing_oneof()) { - printer->Print( - "->^label^('^field^', " - "\\Google\\Protobuf\\Internal\\GPBType::^type^, ^number^^other^)\n", - "field", field->name(), - "label", LabelForField(field), - "type", ToUpper(field->type_name()), - "number", SimpleItoa(field->number()), - "other", EnumOrMessageSuffix(field, true)); - } - } - - // oneofs. - for (int i = 0; i < message->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = message->oneof_decl(i); - printer->Print("->oneof(^name^)\n", - "name", oneof->name()); - Indent(printer); - for (int index = 0; index < oneof->field_count(); index++) { - const FieldDescriptor* field = oneof->field(index); - printer->Print( - "->value('^field^', " - "\\Google\\Protobuf\\Internal\\GPBType::^type^, ^number^^other^)\n", - "field", field->name(), - "type", ToUpper(field->type_name()), - "number", SimpleItoa(field->number()), - "other", EnumOrMessageSuffix(field, true)); - } - printer->Print("->finish()\n"); - Outdent(printer); - } - - printer->Print( - "->finalizeToPool();\n"); - - Outdent(printer); - - printer->Print( - "\n"); - - for (int i = 0; i < message->nested_type_count(); i++) { - GenerateMessageToPool(class_name, message->nested_type(i), printer); - } - for (int i = 0; i < message->enum_type_count(); i++) { - GenerateEnumToPool(message->enum_type(i), printer); - } -} - -void GenerateAddFileToPool(const FileDescriptor* file, bool is_descriptor, - io::Printer* printer) { - printer->Print( - "public static $is_initialized = false;\n\n" - "public static function initOnce() {\n"); - Indent(printer); - - printer->Print( - "$pool = \\Google\\Protobuf\\Internal\\" - "DescriptorPool::getGeneratedPool();\n\n" - "if (static::$is_initialized == true) {\n" - " return;\n" - "}\n"); - - if (is_descriptor) { - for (int i = 0; i < file->message_type_count(); i++) { - GenerateMessageToPool("", file->message_type(i), printer); - } - for (int i = 0; i < file->enum_type_count(); i++) { - GenerateEnumToPool(file->enum_type(i), printer); - } - - printer->Print( - "$pool->finish();\n"); - } else { - for (int i = 0; i < file->dependency_count(); i++) { - const std::string& name = file->dependency(i)->name(); - // Currently, descriptor.proto is not ready for external usage. Skip to - // import it for now, so that its dependencies can still work as long as - // they don't use protos defined in descriptor.proto. - if (name == kDescriptorFile) { - continue; - } - std::string dependency_filename = - GeneratedMetadataFileName(file->dependency(i), is_descriptor); - printer->Print( - "\\^name^::initOnce();\n", - "name", FilenameToClassname(dependency_filename)); - } - - // Add messages and enums to descriptor pool. - FileDescriptorSet files; - FileDescriptorProto* file_proto = files.add_file(); - file->CopyTo(file_proto); - - // Filter out descriptor.proto as it cannot be depended on for now. - RepeatedPtrField* dependency = file_proto->mutable_dependency(); - for (RepeatedPtrField::iterator it = dependency->begin(); - it != dependency->end(); ++it) { - if (*it != kDescriptorFile) { - dependency->erase(it); - break; - } - } - - // Filter out all extensions, since we do not support extension yet. - file_proto->clear_extension(); - RepeatedPtrField* message_type = - file_proto->mutable_message_type(); - for (RepeatedPtrField::iterator it = message_type->begin(); - it != message_type->end(); ++it) { - it->clear_extension(); - } - - string files_data; - files.SerializeToString(&files_data); - - printer->Print("$pool->internalAddGeneratedFile(hex2bin(\n"); - Indent(printer); - - // Only write 30 bytes per line. - static const int kBytesPerLine = 30; - for (int i = 0; i < files_data.size(); i += kBytesPerLine) { - printer->Print( - "\"^data^\"^dot^\n", - "data", BinaryToHex(files_data.substr(i, kBytesPerLine)), - "dot", i + kBytesPerLine < files_data.size() ? " ." : ""); - } - - Outdent(printer); - printer->Print( - "));\n\n"); - } - printer->Print( - "static::$is_initialized = true;\n"); - Outdent(printer); - printer->Print("}\n"); -} - -void GenerateUseDeclaration(bool is_descriptor, io::Printer* printer) { - if (!is_descriptor) { - printer->Print( - "use Google\\Protobuf\\Internal\\GPBType;\n" - "use Google\\Protobuf\\Internal\\RepeatedField;\n" - "use Google\\Protobuf\\Internal\\GPBUtil;\n\n"); - } else { - printer->Print( - "use Google\\Protobuf\\Internal\\GPBType;\n" - "use Google\\Protobuf\\Internal\\GPBWire;\n" - "use Google\\Protobuf\\Internal\\RepeatedField;\n" - "use Google\\Protobuf\\Internal\\InputStream;\n" - "use Google\\Protobuf\\Internal\\GPBUtil;\n\n"); - } -} - -void GenerateHead(const FileDescriptor* file, io::Printer* printer) { - printer->Print( - "name()); -} - -std::string FilenameToClassname(const string& filename) { - int lastindex = filename.find_last_of("."); - std::string result = filename.substr(0, lastindex); - for (int i = 0; i < result.size(); i++) { - if (result[i] == '/') { - result[i] = '\\'; - } - } - return result; -} - -void GenerateMetadataFile(const FileDescriptor* file, - bool is_descriptor, - GeneratorContext* generator_context) { - std::string filename = GeneratedMetadataFileName(file, is_descriptor); - std::unique_ptr output( - generator_context->Open(filename)); - io::Printer printer(output.get(), '^'); - - GenerateHead(file, &printer); - - std::string fullname = FilenameToClassname(filename); - int lastindex = fullname.find_last_of("\\"); - - if (lastindex != string::npos) { - printer.Print( - "namespace ^name^;\n\n", - "name", fullname.substr(0, lastindex)); - - printer.Print( - "class ^name^\n" - "{\n", - "name", fullname.substr(lastindex + 1)); - } else { - printer.Print( - "class ^name^\n" - "{\n", - "name", fullname); - } - Indent(&printer); - - GenerateAddFileToPool(file, is_descriptor, &printer); - - Outdent(&printer); - printer.Print("}\n\n"); -} - -template -void LegacyGenerateClassFile(const FileDescriptor* file, const DescriptorType* desc, - bool is_descriptor, - GeneratorContext* generator_context) { - - std::string filename = LegacyGeneratedClassFileName(desc, is_descriptor); - std::unique_ptr output( - generator_context->Open(filename)); - io::Printer printer(output.get(), '^'); - - GenerateHead(file, &printer); - - std::string php_namespace = RootPhpNamespace(desc, is_descriptor); - if (php_namespace != "") { - printer.Print( - "namespace ^name^;\n\n", - "name", php_namespace); - } - std::string newname = FullClassName(desc, is_descriptor); - printer.Print("if (false) {\n"); - Indent(&printer); - printer.Print("/**\n"); - printer.Print(" * This class is deprecated. Use ^new^ instead.\n", - "new", newname); - printer.Print(" * @deprecated\n"); - printer.Print(" */\n"); - printer.Print("class ^old^ {}\n", - "old", LegacyGeneratedClassName(desc)); - Outdent(&printer); - printer.Print("}\n"); - printer.Print("class_exists(^new^::class);\n", - "new", GeneratedClassNameImpl(desc)); - printer.Print("@trigger_error('^old^ is deprecated and will be removed in " - "the next major release. Use ^fullname^ instead', E_USER_DEPRECATED);\n\n", - "old", LegacyFullClassName(desc, is_descriptor), - "fullname", newname); -} - -void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en, - bool is_descriptor, GeneratorContext* generator_context) { - std::string filename = GeneratedClassFileName(en, is_descriptor); - std::unique_ptr output( - generator_context->Open(filename)); - io::Printer printer(output.get(), '^'); - - GenerateHead(file, &printer); - - std::string fullname = FilenameToClassname(filename); - int lastindex = fullname.find_last_of("\\"); - - if (lastindex != string::npos) { - printer.Print( - "namespace ^name^;\n\n", - "name", fullname.substr(0, lastindex)); - } - - if (lastindex != string::npos) { - fullname = fullname.substr(lastindex + 1); - } - - GenerateEnumDocComment(&printer, en, is_descriptor); - - printer.Print( - "class ^name^\n" - "{\n", - "name", fullname); - Indent(&printer); - - for (int i = 0; i < en->value_count(); i++) { - const EnumValueDescriptor* value = en->value(i); - GenerateEnumValueDocComment(&printer, value); - printer.Print("const ^name^ = ^number^;\n", - "name", ConstantNamePrefix(value->name()) + value->name(), - "number", IntToString(value->number())); - } - - Outdent(&printer); - printer.Print("}\n\n"); - - // write legacy file for backwards compatiblity with nested messages and enums - if (en->containing_type() != NULL) { - printer.Print( - "// Adding a class alias for backwards compatibility with the previous class name.\n"); - printer.Print( - "class_alias(^new^::class, \\^old^::class);\n\n", - "new", fullname, - "old", LegacyFullClassName(en, is_descriptor)); - LegacyGenerateClassFile(file, en, is_descriptor, generator_context); - } -} - -void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message, - bool is_descriptor, - GeneratorContext* generator_context) { - // Don't generate MapEntry messages -- we use the PHP extension's native - // support for map fields instead. - if (message->options().map_entry()) { - return; - } - - std::string filename = GeneratedClassFileName(message, is_descriptor); - std::unique_ptr output( - generator_context->Open(filename)); - io::Printer printer(output.get(), '^'); - - GenerateHead(file, &printer); - - std::string fullname = FilenameToClassname(filename); - int lastindex = fullname.find_last_of("\\"); - - if (lastindex != string::npos) { - printer.Print( - "namespace ^name^;\n\n", - "name", fullname.substr(0, lastindex)); - } - - GenerateUseDeclaration(is_descriptor, &printer); - - GenerateMessageDocComment(&printer, message, is_descriptor); - if (lastindex != string::npos) { - fullname = fullname.substr(lastindex + 1); - } - - printer.Print( - "class ^name^ extends \\Google\\Protobuf\\Internal\\Message\n" - "{\n", - "name", fullname); - Indent(&printer); - - // Field and oneof definitions. - for (int i = 0; i < message->field_count(); i++) { - const FieldDescriptor* field = message->field(i); - GenerateField(field, &printer, is_descriptor); - } - for (int i = 0; i < message->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = message->oneof_decl(i); - GenerateOneofField(oneof, &printer); - } - printer.Print("\n"); - - GenerateMessageConstructorDocComment(&printer, message, is_descriptor); - printer.Print( - "public function __construct($data = NULL) {\n"); - Indent(&printer); - - std::string metadata_filename = - GeneratedMetadataFileName(file, is_descriptor); - std::string metadata_fullname = FilenameToClassname(metadata_filename); - printer.Print( - "\\^fullname^::initOnce();\n" - "parent::__construct($data);\n", - "fullname", metadata_fullname); - - Outdent(&printer); - printer.Print("}\n\n"); - - // Field and oneof accessors. - for (int i = 0; i < message->field_count(); i++) { - const FieldDescriptor* field = message->field(i); - GenerateFieldAccessor(field, is_descriptor, &printer); - } - for (int i = 0; i < message->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = message->oneof_decl(i); - printer.Print( - "/**\n" - " * @return string\n" - " */\n" - "public function get^camel_name^()\n" - "{\n" - " return $this->whichOneof(\"^name^\");\n" - "}\n\n", - "camel_name", UnderscoresToCamelCase(oneof->name(), true), "name", - oneof->name()); - } - - Outdent(&printer); - printer.Print("}\n\n"); - - // write legacy file for backwards compatiblity with nested messages and enums - if (message->containing_type() != NULL) { - printer.Print( - "// Adding a class alias for backwards compatibility with the previous class name.\n"); - printer.Print( - "class_alias(^new^::class, \\^old^::class);\n\n", - "new", fullname, - "old", LegacyFullClassName(message, is_descriptor)); - LegacyGenerateClassFile(file, message, is_descriptor, generator_context); - } - - // Nested messages and enums. - for (int i = 0; i < message->nested_type_count(); i++) { - GenerateMessageFile(file, message->nested_type(i), is_descriptor, - generator_context); - } - for (int i = 0; i < message->enum_type_count(); i++) { - GenerateEnumFile(file, message->enum_type(i), is_descriptor, - generator_context); - } -} - -void GenerateServiceFile(const FileDescriptor* file, - const ServiceDescriptor* service, bool is_descriptor, - GeneratorContext* generator_context) { - std::string filename = GeneratedServiceFileName(service, is_descriptor); - std::unique_ptr output( - generator_context->Open(filename)); - io::Printer printer(output.get(), '^'); - - GenerateHead(file, &printer); - - std::string fullname = FilenameToClassname(filename); - int lastindex = fullname.find_last_of("\\"); - - if (!file->options().php_namespace().empty() || - (!file->options().has_php_namespace() && !file->package().empty()) || - lastindex != string::npos) { - printer.Print( - "namespace ^name^;\n\n", - "name", fullname.substr(0, lastindex)); - } - - GenerateServiceDocComment(&printer, service); - - if (lastindex != string::npos) { - printer.Print( - "interface ^name^\n" - "{\n", - "name", fullname.substr(lastindex + 1)); - } else { - printer.Print( - "interface ^name^\n" - "{\n", - "name", fullname); - } - - Indent(&printer); - - for (int i = 0; i < service->method_count(); i++) { - const MethodDescriptor* method = service->method(i); - GenerateServiceMethodDocComment(&printer, method); - GenerateServiceMethod(method, &printer); - } - - Outdent(&printer); - printer.Print("}\n\n"); -} - -void GenerateFile(const FileDescriptor* file, bool is_descriptor, - GeneratorContext* generator_context) { - GenerateMetadataFile(file, is_descriptor, generator_context); - for (int i = 0; i < file->message_type_count(); i++) { - GenerateMessageFile(file, file->message_type(i), is_descriptor, - generator_context); - } - for (int i = 0; i < file->enum_type_count(); i++) { - GenerateEnumFile(file, file->enum_type(i), is_descriptor, - generator_context); - } - if (file->options().php_generic_services()) { - for (int i = 0; i < file->service_count(); i++) { - GenerateServiceFile(file, file->service(i), is_descriptor, - generator_context); - } - } -} - -static string EscapePhpdoc(const string& input) { - string result; - result.reserve(input.size() * 2); - - char prev = '*'; - - for (string::size_type i = 0; i < input.size(); i++) { - char c = input[i]; - switch (c) { - case '*': - // Avoid "/*". - if (prev == '/') { - result.append("*"); - } else { - result.push_back(c); - } - break; - case '/': - // Avoid "*/". - if (prev == '*') { - result.append("/"); - } else { - result.push_back(c); - } - break; - case '@': - // '@' starts phpdoc tags including the @deprecated tag, which will - // cause a compile-time error if inserted before a declaration that - // does not have a corresponding @Deprecated annotation. - result.append("@"); - break; - default: - result.push_back(c); - break; - } - - prev = c; - } - - return result; -} - -static void GenerateDocCommentBodyForLocation( - io::Printer* printer, const SourceLocation& location, bool trailingNewline, - int indentCount) { - string comments = location.leading_comments.empty() ? - location.trailing_comments : location.leading_comments; - if (!comments.empty()) { - // TODO(teboring): Ideally we should parse the comment text as Markdown and - // write it back as HTML, but this requires a Markdown parser. For now - // we just use the proto comments unchanged. - - // If the comment itself contains block comment start or end markers, - // HTML-escape them so that they don't accidentally close the doc comment. - comments = EscapePhpdoc(comments); - - std::vector lines = Split(comments, "\n"); - while (!lines.empty() && lines.back().empty()) { - lines.pop_back(); - } - - for (int i = 0; i < lines.size(); i++) { - // Most lines should start with a space. Watch out for lines that start - // with a /, since putting that right after the leading asterisk will - // close the comment. - if (indentCount == 0 && !lines[i].empty() && lines[i][0] == '/') { - printer->Print(" * ^line^\n", "line", lines[i]); - } else { - std::string indent = std::string(indentCount, ' '); - printer->Print(" *^ind^^line^\n", "ind", indent, "line", lines[i]); - } - } - if (trailingNewline) { - printer->Print(" *\n"); - } - } -} - -template -static void GenerateDocCommentBody( - io::Printer* printer, const DescriptorType* descriptor) { - SourceLocation location; - if (descriptor->GetSourceLocation(&location)) { - GenerateDocCommentBodyForLocation(printer, location, true, 0); - } -} - -static string FirstLineOf(const string& value) { - string result = value; - - string::size_type pos = result.find_first_of('\n'); - if (pos != string::npos) { - result.erase(pos); - } - - return result; -} - -void GenerateMessageDocComment(io::Printer* printer, - const Descriptor* message, int is_descriptor) { - printer->Print("/**\n"); - GenerateDocCommentBody(printer, message); - printer->Print( - " * Generated from protobuf message ^messagename^\n" - " */\n", - "fullname", EscapePhpdoc(FullClassName(message, is_descriptor)), - "messagename", EscapePhpdoc(message->full_name())); -} - -void GenerateMessageConstructorDocComment(io::Printer* printer, - const Descriptor* message, - int is_descriptor) { - // In theory we should have slightly different comments for setters, getters, - // etc., but in practice everyone already knows the difference between these - // so it's redundant information. - - // We start the comment with the main body based on the comments from the - // .proto file (if present). We then end with the field declaration, e.g.: - // optional string foo = 5; - // If the field is a group, the debug string might end with {. - printer->Print("/**\n"); - printer->Print(" * Constructor.\n"); - printer->Print(" *\n"); - printer->Print(" * @param array $data {\n"); - printer->Print(" * Optional. Data for populating the Message object.\n"); - printer->Print(" *\n"); - for (int i = 0; i < message->field_count(); i++) { - const FieldDescriptor* field = message->field(i); - printer->Print(" * @type ^php_type^ $^var^\n", - "php_type", PhpSetterTypeName(field, is_descriptor), - "var", field->name()); - SourceLocation location; - if (field->GetSourceLocation(&location)) { - GenerateDocCommentBodyForLocation(printer, location, false, 10); - } - } - printer->Print(" * }\n"); - printer->Print(" */\n"); -} - -void GenerateServiceDocComment(io::Printer* printer, - const ServiceDescriptor* service) { - printer->Print("/**\n"); - GenerateDocCommentBody(printer, service); - printer->Print( - " * Protobuf type ^fullname^\n" - " */\n", - "fullname", EscapePhpdoc(service->full_name())); -} - -void GenerateFieldDocComment(io::Printer* printer, const FieldDescriptor* field, - int is_descriptor, int function_type) { - // In theory we should have slightly different comments for setters, getters, - // etc., but in practice everyone already knows the difference between these - // so it's redundant information. - - // We start the comment with the main body based on the comments from the - // .proto file (if present). We then end with the field declaration, e.g.: - // optional string foo = 5; - // If the field is a group, the debug string might end with {. - printer->Print("/**\n"); - GenerateDocCommentBody(printer, field); - printer->Print( - " * Generated from protobuf field ^def^\n", - "def", EscapePhpdoc(FirstLineOf(field->DebugString()))); - if (function_type == kFieldSetter) { - printer->Print(" * @param ^php_type^ $var\n", - "php_type", PhpSetterTypeName(field, is_descriptor)); - printer->Print(" * @return $this\n"); - } else if (function_type == kFieldGetter) { - printer->Print(" * @return ^php_type^\n", - "php_type", PhpGetterTypeName(field, is_descriptor)); - } - printer->Print(" */\n"); -} - -void GenerateEnumDocComment(io::Printer* printer, const EnumDescriptor* enum_, - int is_descriptor) { - printer->Print("/**\n"); - GenerateDocCommentBody(printer, enum_); - printer->Print( - " * Protobuf type ^fullname^\n" - " */\n", - "fullname", EscapePhpdoc(enum_->full_name())); -} - -void GenerateEnumValueDocComment(io::Printer* printer, - const EnumValueDescriptor* value) { - printer->Print("/**\n"); - GenerateDocCommentBody(printer, value); - printer->Print( - " * Generated from protobuf enum ^def^\n" - " */\n", - "def", EscapePhpdoc(FirstLineOf(value->DebugString()))); -} - -void GenerateServiceMethodDocComment(io::Printer* printer, - const MethodDescriptor* method) { - printer->Print("/**\n"); - GenerateDocCommentBody(printer, method); - printer->Print( - " * Method ^method_name^\n" - " *\n", - "method_name", EscapePhpdoc(UnderscoresToCamelCase(method->name(), false))); - printer->Print( - " * @param \\^input_type^ $request\n", - "input_type", EscapePhpdoc(FullClassName(method->input_type(), false))); - printer->Print( - " * @return \\^return_type^\n" - " */\n", - "return_type", EscapePhpdoc(FullClassName(method->output_type(), false))); -} - -bool Generator::Generate(const FileDescriptor* file, const string& parameter, - GeneratorContext* generator_context, - string* error) const { - bool is_descriptor = parameter == "internal"; - - if (is_descriptor && file->name() != kDescriptorFile) { - *error = - "Can only generate PHP code for google/protobuf/descriptor.proto.\n"; - return false; - } - - if (!is_descriptor && file->syntax() != FileDescriptor::SYNTAX_PROTO3) { - *error = - "Can only generate PHP code for proto3 .proto files.\n" - "Please add 'syntax = \"proto3\";' to the top of your .proto file.\n"; - return false; - } - - GenerateFile(file, is_descriptor, generator_context); - - return true; -} - -} // namespace php -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/php/php_generator.h b/windows/include/google/protobuf/compiler/php/php_generator.h index b851d9b4a..17cb59c08 100644 --- a/windows/include/google/protobuf/compiler/php/php_generator.h +++ b/windows/include/google/protobuf/compiler/php/php_generator.h @@ -36,33 +36,57 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { namespace php { -class LIBPROTOC_EXPORT Generator - : public google::protobuf::compiler::CodeGenerator { +struct Options; + +class PROTOC_EXPORT Generator : public CodeGenerator { + public: virtual bool Generate( const FileDescriptor* file, - const string& parameter, + const std::string& parameter, GeneratorContext* generator_context, - string* error) const; + std::string* error) const override; + + bool GenerateAll(const std::vector& files, + const std::string& parameter, + GeneratorContext* generator_context, + std::string* error) const override; + + uint64_t GetSupportedFeatures() const override { + return FEATURE_PROTO3_OPTIONAL; + } + + private: + bool Generate( + const FileDescriptor* file, + const Options& options, + GeneratorContext* generator_context, + std::string* error) const; }; // To skip reserved keywords in php, some generated classname are prefixed. // Other code generators may need following API to figure out the actual // classname. -LIBPROTOC_EXPORT std::string GeneratedClassName( - const google::protobuf::Descriptor* desc); -LIBPROTOC_EXPORT std::string GeneratedClassName( - const google::protobuf::EnumDescriptor* desc); -LIBPROTOC_EXPORT std::string GeneratedClassName( - const google::protobuf::ServiceDescriptor* desc); +PROTOC_EXPORT std::string GeneratedClassName(const Descriptor* desc); +PROTOC_EXPORT std::string GeneratedClassName(const EnumDescriptor* desc); +PROTOC_EXPORT std::string GeneratedClassName(const ServiceDescriptor* desc); + +inline bool IsWrapperType(const FieldDescriptor* descriptor) { + return descriptor->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + descriptor->message_type()->file()->name() == "google/protobuf/wrappers.proto"; +} } // namespace php } // namespace compiler } // namespace protobuf } // namespace google +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PHP_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/plugin.cc b/windows/include/google/protobuf/compiler/plugin.cc deleted file mode 100644 index 9c1c757c9..000000000 --- a/windows/include/google/protobuf/compiler/plugin.cc +++ /dev/null @@ -1,185 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) - -#include - -#include -#include - -#ifdef _WIN32 -#include -#else -#include -#endif - -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { - -#if defined(_WIN32) -// DO NOT include , instead create functions in io_win32.{h,cc} and import -// them like we do below. -using google::protobuf::internal::win32::setmode; -#endif - -class GeneratorResponseContext : public GeneratorContext { - public: - GeneratorResponseContext( - const Version& compiler_version, - CodeGeneratorResponse* response, - const std::vector& parsed_files) - : compiler_version_(compiler_version), - response_(response), - parsed_files_(parsed_files) {} - virtual ~GeneratorResponseContext() {} - - // implements GeneratorContext -------------------------------------- - - virtual io::ZeroCopyOutputStream* Open(const string& filename) { - CodeGeneratorResponse::File* file = response_->add_file(); - file->set_name(filename); - return new io::StringOutputStream(file->mutable_content()); - } - - virtual io::ZeroCopyOutputStream* OpenForInsert( - const string& filename, const string& insertion_point) { - CodeGeneratorResponse::File* file = response_->add_file(); - file->set_name(filename); - file->set_insertion_point(insertion_point); - return new io::StringOutputStream(file->mutable_content()); - } - - void ListParsedFiles(std::vector* output) { - *output = parsed_files_; - } - - void GetCompilerVersion(Version* version) const { - *version = compiler_version_; - } - - private: - Version compiler_version_; - CodeGeneratorResponse* response_; - const std::vector& parsed_files_; -}; - -bool GenerateCode(const CodeGeneratorRequest& request, - const CodeGenerator& generator, CodeGeneratorResponse* response, - string* error_msg) { - DescriptorPool pool; - for (int i = 0; i < request.proto_file_size(); i++) { - const FileDescriptor* file = pool.BuildFile(request.proto_file(i)); - if (file == NULL) { - // BuildFile() already wrote an error message. - return false; - } - } - - std::vector parsed_files; - for (int i = 0; i < request.file_to_generate_size(); i++) { - parsed_files.push_back(pool.FindFileByName(request.file_to_generate(i))); - if (parsed_files.back() == NULL) { - *error_msg = "protoc asked plugin to generate a file but " - "did not provide a descriptor for the file: " + - request.file_to_generate(i); - return false; - } - } - - GeneratorResponseContext context( - request.compiler_version(), response, parsed_files); - - - string error; - bool succeeded = generator.GenerateAll( - parsed_files, request.parameter(), &context, &error); - - if (!succeeded && error.empty()) { - error = "Code generator returned false but provided no error " - "description."; - } - if (!error.empty()) { - response->set_error(error); - } - - return true; -} - -int PluginMain(int argc, char* argv[], const CodeGenerator* generator) { - - if (argc > 1) { - std::cerr << argv[0] << ": Unknown option: " << argv[1] << std::endl; - return 1; - } - -#ifdef _WIN32 - setmode(STDIN_FILENO, _O_BINARY); - setmode(STDOUT_FILENO, _O_BINARY); -#endif - - CodeGeneratorRequest request; - if (!request.ParseFromFileDescriptor(STDIN_FILENO)) { - std::cerr << argv[0] << ": protoc sent unparseable request to plugin." - << std::endl; - return 1; - } - - string error_msg; - CodeGeneratorResponse response; - - if (GenerateCode(request, *generator, &response, &error_msg)) { - if (!response.SerializeToFileDescriptor(STDOUT_FILENO)) { - std::cerr << argv[0] << ": Error writing to stdout." << std::endl; - return 1; - } - } else { - if (!error_msg.empty()) { - std::cerr << argv[0] << ": " << error_msg << std::endl; - } - return 1; - } - - return 0; -} - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/plugin.h b/windows/include/google/protobuf/compiler/plugin.h index d2793a9ff..7d1bf4508 100644 --- a/windows/include/google/protobuf/compiler/plugin.h +++ b/windows/include/google/protobuf/compiler/plugin.h @@ -64,27 +64,32 @@ #include -#include +#include + namespace google { namespace protobuf { namespace compiler { -class CodeGenerator; // code_generator.h +class CodeGenerator; // code_generator.h class CodeGeneratorRequest; class CodeGeneratorResponse; // Implements main() for a protoc plugin exposing the given code generator. -LIBPROTOC_EXPORT int PluginMain(int argc, char* argv[], const CodeGenerator* generator); +PROTOC_EXPORT int PluginMain(int argc, char* argv[], + const CodeGenerator* generator); + // Generates code using the given code generator. Returns true if the code -// generation is successful. If the code geneartion fails, error_msg may be +// generation is successful. If the code generation fails, error_msg may be // populated to describe the failure cause. bool GenerateCode(const CodeGeneratorRequest& request, - const CodeGenerator& generator, CodeGeneratorResponse* response, - string* error_msg); + const CodeGenerator& generator, + CodeGeneratorResponse* response, std::string* error_msg); } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PLUGIN_H__ diff --git a/windows/include/google/protobuf/compiler/plugin.pb.cc b/windows/include/google/protobuf/compiler/plugin.pb.cc deleted file mode 100644 index ef52def36..000000000 --- a/windows/include/google/protobuf/compiler/plugin.pb.cc +++ /dev/null @@ -1,1720 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: google/protobuf/compiler/plugin.proto - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -// This is a temporary google only hack -#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS -#include "third_party/protobuf/version.h" -#endif -// @@protoc_insertion_point(includes) - -namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File; -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Version; -} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto -namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto { -extern PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fdescriptor_2eproto ::google::protobuf::internal::SCCInfo<6> scc_info_FileDescriptorProto; -} // namespace protobuf_google_2fprotobuf_2fdescriptor_2eproto -namespace google { -namespace protobuf { -namespace compiler { -class VersionDefaultTypeInternal { - public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; -} _Version_default_instance_; -class CodeGeneratorRequestDefaultTypeInternal { - public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; -} _CodeGeneratorRequest_default_instance_; -class CodeGeneratorResponse_FileDefaultTypeInternal { - public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; -} _CodeGeneratorResponse_File_default_instance_; -class CodeGeneratorResponseDefaultTypeInternal { - public: - ::google::protobuf::internal::ExplicitlyConstructed - _instance; -} _CodeGeneratorResponse_default_instance_; -} // namespace compiler -} // namespace protobuf -} // namespace google -namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { -static void InitDefaultsVersion() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - { - void* ptr = &::google::protobuf::compiler::_Version_default_instance_; - new (ptr) ::google::protobuf::compiler::Version(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); - } - ::google::protobuf::compiler::Version::InitAsDefaultInstance(); -} - -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_Version = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsVersion}, {}}; - -static void InitDefaultsCodeGeneratorRequest() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - { - void* ptr = &::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_; - new (ptr) ::google::protobuf::compiler::CodeGeneratorRequest(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); - } - ::google::protobuf::compiler::CodeGeneratorRequest::InitAsDefaultInstance(); -} - -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<2> scc_info_CodeGeneratorRequest = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsCodeGeneratorRequest}, { - &protobuf_google_2fprotobuf_2fdescriptor_2eproto::scc_info_FileDescriptorProto.base, - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base,}}; - -static void InitDefaultsCodeGeneratorResponse_File() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - { - void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_; - new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse_File(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); - } - ::google::protobuf::compiler::CodeGeneratorResponse_File::InitAsDefaultInstance(); -} - -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<0> scc_info_CodeGeneratorResponse_File = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCodeGeneratorResponse_File}, {}}; - -static void InitDefaultsCodeGeneratorResponse() { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - { - void* ptr = &::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_; - new (ptr) ::google::protobuf::compiler::CodeGeneratorResponse(); - ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); - } - ::google::protobuf::compiler::CodeGeneratorResponse::InitAsDefaultInstance(); -} - -LIBPROTOC_EXPORT ::google::protobuf::internal::SCCInfo<1> scc_info_CodeGeneratorResponse = - {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCodeGeneratorResponse}, { - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base,}}; - -void InitDefaults() { - ::google::protobuf::internal::InitSCC(&scc_info_Version.base); - ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorRequest.base); - ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse_File.base); - ::google::protobuf::internal::InitSCC(&scc_info_CodeGeneratorResponse.base); -} - -::google::protobuf::Metadata file_level_metadata[4]; - -const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, major_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, minor_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, patch_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::Version, suffix_), - 1, - 2, - 3, - 0, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, file_to_generate_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, parameter_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, proto_file_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorRequest, compiler_version_), - ~0u, - 0, - ~0u, - 1, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, insertion_point_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse_File, content_), - 0, - 1, - 2, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _has_bits_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, _internal_metadata_), - ~0u, // no _extensions_ - ~0u, // no _oneof_case_ - ~0u, // no _weak_field_map_ - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, error_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::compiler::CodeGeneratorResponse, file_), - 0, - ~0u, -}; -static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - { 0, 9, sizeof(::google::protobuf::compiler::Version)}, - { 13, 22, sizeof(::google::protobuf::compiler::CodeGeneratorRequest)}, - { 26, 34, sizeof(::google::protobuf::compiler::CodeGeneratorResponse_File)}, - { 37, 44, sizeof(::google::protobuf::compiler::CodeGeneratorResponse)}, -}; - -static ::google::protobuf::Message const * const file_default_instances[] = { - reinterpret_cast(&::google::protobuf::compiler::_Version_default_instance_), - reinterpret_cast(&::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_), - reinterpret_cast(&::google::protobuf::compiler::_CodeGeneratorResponse_File_default_instance_), - reinterpret_cast(&::google::protobuf::compiler::_CodeGeneratorResponse_default_instance_), -}; - -void protobuf_AssignDescriptors() { - AddDescriptors(); - AssignDescriptors( - "google/protobuf/compiler/plugin.proto", schemas, file_default_instances, TableStruct::offsets, - file_level_metadata, NULL, NULL); -} - -void protobuf_AssignDescriptorsOnce() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); -} - -void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 4); -} - -void AddDescriptorsImpl() { - InitDefaults(); - static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { - "\n%google/protobuf/compiler/plugin.proto\022" - "\030google.protobuf.compiler\032 google/protob" - "uf/descriptor.proto\"F\n\007Version\022\r\n\005major\030" - "\001 \001(\005\022\r\n\005minor\030\002 \001(\005\022\r\n\005patch\030\003 \001(\005\022\016\n\006s" - "uffix\030\004 \001(\t\"\272\001\n\024CodeGeneratorRequest\022\030\n\020" - "file_to_generate\030\001 \003(\t\022\021\n\tparameter\030\002 \001(" - "\t\0228\n\nproto_file\030\017 \003(\0132$.google.protobuf." - "FileDescriptorProto\022;\n\020compiler_version\030" - "\003 \001(\0132!.google.protobuf.compiler.Version" - "\"\252\001\n\025CodeGeneratorResponse\022\r\n\005error\030\001 \001(" - "\t\022B\n\004file\030\017 \003(\01324.google.protobuf.compil" - "er.CodeGeneratorResponse.File\032>\n\004File\022\014\n" - "\004name\030\001 \001(\t\022\027\n\017insertion_point\030\002 \001(\t\022\017\n\007" - "content\030\017 \001(\tBg\n\034com.google.protobuf.com" - "pilerB\014PluginProtosZ9github.com/golang/p" - "rotobuf/protoc-gen-go/plugin;plugin_go" - }; - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - descriptor, 638); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/compiler/plugin.proto", &protobuf_RegisterTypes); - ::protobuf_google_2fprotobuf_2fdescriptor_2eproto::AddDescriptors(); -} - -void AddDescriptors() { - static ::google::protobuf::internal::once_flag once; - ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); -} -// Force AddDescriptors() to be called at dynamic initialization time. -struct StaticDescriptorInitializer { - StaticDescriptorInitializer() { - AddDescriptors(); - } -} static_descriptor_initializer; -} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto -namespace google { -namespace protobuf { -namespace compiler { - -// =================================================================== - -void Version::InitAsDefaultInstance() { -} -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int Version::kMajorFieldNumber; -const int Version::kMinorFieldNumber; -const int Version::kPatchFieldNumber; -const int Version::kSuffixFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -Version::Version() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base); - SharedCtor(); - // @@protoc_insertion_point(constructor:google.protobuf.compiler.Version) -} -Version::Version(const Version& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _has_bits_(from._has_bits_) { - _internal_metadata_.MergeFrom(from._internal_metadata_); - suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.has_suffix()) { - suffix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.suffix_); - } - ::memcpy(&major_, &from.major_, - static_cast(reinterpret_cast(&patch_) - - reinterpret_cast(&major_)) + sizeof(patch_)); - // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.Version) -} - -void Version::SharedCtor() { - suffix_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - ::memset(&major_, 0, static_cast( - reinterpret_cast(&patch_) - - reinterpret_cast(&major_)) + sizeof(patch_)); -} - -Version::~Version() { - // @@protoc_insertion_point(destructor:google.protobuf.compiler.Version) - SharedDtor(); -} - -void Version::SharedDtor() { - suffix_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void Version::SetCachedSize(int size) const { - _cached_size_.Set(size); -} -const ::google::protobuf::Descriptor* Version::descriptor() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - -const Version& Version::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_Version.base); - return *internal_default_instance(); -} - - -void Version::Clear() { -// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.Version) - ::google::protobuf::uint32 cached_has_bits = 0; - // Prevent compiler warnings about cached_has_bits being unused - (void) cached_has_bits; - - cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 0x00000001u) { - suffix_.ClearNonDefaultToEmptyNoArena(); - } - if (cached_has_bits & 14u) { - ::memset(&major_, 0, static_cast( - reinterpret_cast(&patch_) - - reinterpret_cast(&major_)) + sizeof(patch_)); - } - _has_bits_.Clear(); - _internal_metadata_.Clear(); -} - -bool Version::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:google.protobuf.compiler.Version) - for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional int32 major = 1; - case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { - set_has_major(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &major_))); - } else { - goto handle_unusual; - } - break; - } - - // optional int32 minor = 2; - case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { - set_has_minor(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &minor_))); - } else { - goto handle_unusual; - } - break; - } - - // optional int32 patch = 3; - case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { - set_has_patch(); - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &patch_))); - } else { - goto handle_unusual; - } - break; - } - - // optional string suffix = 4; - case 4: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(34u /* 34 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_suffix())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->suffix().data(), static_cast(this->suffix().length()), - ::google::protobuf::internal::WireFormat::PARSE, - "google.protobuf.compiler.Version.suffix"); - } else { - goto handle_unusual; - } - break; - } - - default: { - handle_unusual: - if (tag == 0) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, _internal_metadata_.mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:google.protobuf.compiler.Version) - return true; -failure: - // @@protoc_insertion_point(parse_failure:google.protobuf.compiler.Version) - return false; -#undef DO_ -} - -void Version::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:google.protobuf.compiler.Version) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - cached_has_bits = _has_bits_[0]; - // optional int32 major = 1; - if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->major(), output); - } - - // optional int32 minor = 2; - if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->minor(), output); - } - - // optional int32 patch = 3; - if (cached_has_bits & 0x00000008u) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->patch(), output); - } - - // optional string suffix = 4; - if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->suffix().data(), static_cast(this->suffix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.Version.suffix"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 4, this->suffix(), output); - } - - if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - _internal_metadata_.unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:google.protobuf.compiler.Version) -} - -::google::protobuf::uint8* Version::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.Version) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - cached_has_bits = _has_bits_[0]; - // optional int32 major = 1; - if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->major(), target); - } - - // optional int32 minor = 2; - if (cached_has_bits & 0x00000004u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->minor(), target); - } - - // optional int32 patch = 3; - if (cached_has_bits & 0x00000008u) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->patch(), target); - } - - // optional string suffix = 4; - if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->suffix().data(), static_cast(this->suffix().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.Version.suffix"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 4, this->suffix(), target); - } - - if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - _internal_metadata_.unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.Version) - return target; -} - -size_t Version::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:google.protobuf.compiler.Version) - size_t total_size = 0; - - if (_internal_metadata_.have_unknown_fields()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - _internal_metadata_.unknown_fields()); - } - if (_has_bits_[0 / 32] & 15u) { - // optional string suffix = 4; - if (has_suffix()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->suffix()); - } - - // optional int32 major = 1; - if (has_major()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->major()); - } - - // optional int32 minor = 2; - if (has_minor()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->minor()); - } - - // optional int32 patch = 3; - if (has_patch()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->patch()); - } - - } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - SetCachedSize(cached_size); - return total_size; -} - -void Version::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.Version) - GOOGLE_DCHECK_NE(&from, this); - const Version* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.Version) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.Version) - MergeFrom(*source); - } -} - -void Version::MergeFrom(const Version& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.Version) - GOOGLE_DCHECK_NE(&from, this); - _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 15u) { - if (cached_has_bits & 0x00000001u) { - set_has_suffix(); - suffix_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.suffix_); - } - if (cached_has_bits & 0x00000002u) { - major_ = from.major_; - } - if (cached_has_bits & 0x00000004u) { - minor_ = from.minor_; - } - if (cached_has_bits & 0x00000008u) { - patch_ = from.patch_; - } - _has_bits_[0] |= cached_has_bits; - } -} - -void Version::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.compiler.Version) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void Version::CopyFrom(const Version& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.compiler.Version) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool Version::IsInitialized() const { - return true; -} - -void Version::Swap(Version* other) { - if (other == this) return; - InternalSwap(other); -} -void Version::InternalSwap(Version* other) { - using std::swap; - suffix_.Swap(&other->suffix_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - swap(major_, other->major_); - swap(minor_, other->minor_); - swap(patch_, other->patch_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); -} - -::google::protobuf::Metadata Version::GetMetadata() const { - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages]; -} - - -// =================================================================== - -void CodeGeneratorRequest::InitAsDefaultInstance() { - ::google::protobuf::compiler::_CodeGeneratorRequest_default_instance_._instance.get_mutable()->compiler_version_ = const_cast< ::google::protobuf::compiler::Version*>( - ::google::protobuf::compiler::Version::internal_default_instance()); -} -void CodeGeneratorRequest::clear_proto_file() { - proto_file_.Clear(); -} -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int CodeGeneratorRequest::kFileToGenerateFieldNumber; -const int CodeGeneratorRequest::kParameterFieldNumber; -const int CodeGeneratorRequest::kProtoFileFieldNumber; -const int CodeGeneratorRequest::kCompilerVersionFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -CodeGeneratorRequest::CodeGeneratorRequest() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base); - SharedCtor(); - // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorRequest) -} -CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - file_to_generate_(from.file_to_generate_), - proto_file_(from.proto_file_) { - _internal_metadata_.MergeFrom(from._internal_metadata_); - parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.has_parameter()) { - parameter_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.parameter_); - } - if (from.has_compiler_version()) { - compiler_version_ = new ::google::protobuf::compiler::Version(*from.compiler_version_); - } else { - compiler_version_ = NULL; - } - // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorRequest) -} - -void CodeGeneratorRequest::SharedCtor() { - parameter_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - compiler_version_ = NULL; -} - -CodeGeneratorRequest::~CodeGeneratorRequest() { - // @@protoc_insertion_point(destructor:google.protobuf.compiler.CodeGeneratorRequest) - SharedDtor(); -} - -void CodeGeneratorRequest::SharedDtor() { - parameter_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (this != internal_default_instance()) delete compiler_version_; -} - -void CodeGeneratorRequest::SetCachedSize(int size) const { - _cached_size_.Set(size); -} -const ::google::protobuf::Descriptor* CodeGeneratorRequest::descriptor() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - -const CodeGeneratorRequest& CodeGeneratorRequest::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorRequest.base); - return *internal_default_instance(); -} - - -void CodeGeneratorRequest::Clear() { -// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorRequest) - ::google::protobuf::uint32 cached_has_bits = 0; - // Prevent compiler warnings about cached_has_bits being unused - (void) cached_has_bits; - - file_to_generate_.Clear(); - proto_file_.Clear(); - cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 3u) { - if (cached_has_bits & 0x00000001u) { - parameter_.ClearNonDefaultToEmptyNoArena(); - } - if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(compiler_version_ != NULL); - compiler_version_->Clear(); - } - } - _has_bits_.Clear(); - _internal_metadata_.Clear(); -} - -bool CodeGeneratorRequest::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorRequest) - for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated string file_to_generate = 1; - case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->add_file_to_generate())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->file_to_generate(this->file_to_generate_size() - 1).data(), - static_cast(this->file_to_generate(this->file_to_generate_size() - 1).length()), - ::google::protobuf::internal::WireFormat::PARSE, - "google.protobuf.compiler.CodeGeneratorRequest.file_to_generate"); - } else { - goto handle_unusual; - } - break; - } - - // optional string parameter = 2; - case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_parameter())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->parameter().data(), static_cast(this->parameter().length()), - ::google::protobuf::internal::WireFormat::PARSE, - "google.protobuf.compiler.CodeGeneratorRequest.parameter"); - } else { - goto handle_unusual; - } - break; - } - - // optional .google.protobuf.compiler.Version compiler_version = 3; - case 3: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( - input, mutable_compiler_version())); - } else { - goto handle_unusual; - } - break; - } - - // repeated .google.protobuf.FileDescriptorProto proto_file = 15; - case 15: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( - input, add_proto_file())); - } else { - goto handle_unusual; - } - break; - } - - default: { - handle_unusual: - if (tag == 0) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, _internal_metadata_.mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:google.protobuf.compiler.CodeGeneratorRequest) - return true; -failure: - // @@protoc_insertion_point(parse_failure:google.protobuf.compiler.CodeGeneratorRequest) - return false; -#undef DO_ -} - -void CodeGeneratorRequest::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorRequest) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // repeated string file_to_generate = 1; - for (int i = 0, n = this->file_to_generate_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->file_to_generate(i).data(), static_cast(this->file_to_generate(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorRequest.file_to_generate"); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->file_to_generate(i), output); - } - - cached_has_bits = _has_bits_[0]; - // optional string parameter = 2; - if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->parameter().data(), static_cast(this->parameter().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorRequest.parameter"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 2, this->parameter(), output); - } - - // optional .google.protobuf.compiler.Version compiler_version = 3; - if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->_internal_compiler_version(), output); - } - - // repeated .google.protobuf.FileDescriptorProto proto_file = 15; - for (unsigned int i = 0, - n = static_cast(this->proto_file_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 15, - this->proto_file(static_cast(i)), - output); - } - - if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - _internal_metadata_.unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorRequest) -} - -::google::protobuf::uint8* CodeGeneratorRequest::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorRequest) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - // repeated string file_to_generate = 1; - for (int i = 0, n = this->file_to_generate_size(); i < n; i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->file_to_generate(i).data(), static_cast(this->file_to_generate(i).length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorRequest.file_to_generate"); - target = ::google::protobuf::internal::WireFormatLite:: - WriteStringToArray(1, this->file_to_generate(i), target); - } - - cached_has_bits = _has_bits_[0]; - // optional string parameter = 2; - if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->parameter().data(), static_cast(this->parameter().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorRequest.parameter"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->parameter(), target); - } - - // optional .google.protobuf.compiler.Version compiler_version = 3; - if (cached_has_bits & 0x00000002u) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageToArray( - 3, this->_internal_compiler_version(), deterministic, target); - } - - // repeated .google.protobuf.FileDescriptorProto proto_file = 15; - for (unsigned int i = 0, - n = static_cast(this->proto_file_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageToArray( - 15, this->proto_file(static_cast(i)), deterministic, target); - } - - if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - _internal_metadata_.unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorRequest) - return target; -} - -size_t CodeGeneratorRequest::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:google.protobuf.compiler.CodeGeneratorRequest) - size_t total_size = 0; - - if (_internal_metadata_.have_unknown_fields()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - _internal_metadata_.unknown_fields()); - } - // repeated string file_to_generate = 1; - total_size += 1 * - ::google::protobuf::internal::FromIntSize(this->file_to_generate_size()); - for (int i = 0, n = this->file_to_generate_size(); i < n; i++) { - total_size += ::google::protobuf::internal::WireFormatLite::StringSize( - this->file_to_generate(i)); - } - - // repeated .google.protobuf.FileDescriptorProto proto_file = 15; - { - unsigned int count = static_cast(this->proto_file_size()); - total_size += 1UL * count; - for (unsigned int i = 0; i < count; i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( - this->proto_file(static_cast(i))); - } - } - - if (_has_bits_[0 / 32] & 3u) { - // optional string parameter = 2; - if (has_parameter()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->parameter()); - } - - // optional .google.protobuf.compiler.Version compiler_version = 3; - if (has_compiler_version()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSize( - *compiler_version_); - } - - } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - SetCachedSize(cached_size); - return total_size; -} - -void CodeGeneratorRequest::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest) - GOOGLE_DCHECK_NE(&from, this); - const CodeGeneratorRequest* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorRequest) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorRequest) - MergeFrom(*source); - } -} - -void CodeGeneratorRequest::MergeFrom(const CodeGeneratorRequest& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorRequest) - GOOGLE_DCHECK_NE(&from, this); - _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - file_to_generate_.MergeFrom(from.file_to_generate_); - proto_file_.MergeFrom(from.proto_file_); - cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 3u) { - if (cached_has_bits & 0x00000001u) { - set_has_parameter(); - parameter_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.parameter_); - } - if (cached_has_bits & 0x00000002u) { - mutable_compiler_version()->::google::protobuf::compiler::Version::MergeFrom(from.compiler_version()); - } - } -} - -void CodeGeneratorRequest::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.compiler.CodeGeneratorRequest) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void CodeGeneratorRequest::CopyFrom(const CodeGeneratorRequest& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.compiler.CodeGeneratorRequest) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool CodeGeneratorRequest::IsInitialized() const { - if (!::google::protobuf::internal::AllAreInitialized(this->proto_file())) return false; - return true; -} - -void CodeGeneratorRequest::Swap(CodeGeneratorRequest* other) { - if (other == this) return; - InternalSwap(other); -} -void CodeGeneratorRequest::InternalSwap(CodeGeneratorRequest* other) { - using std::swap; - file_to_generate_.InternalSwap(CastToBase(&other->file_to_generate_)); - CastToBase(&proto_file_)->InternalSwap(CastToBase(&other->proto_file_)); - parameter_.Swap(&other->parameter_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - swap(compiler_version_, other->compiler_version_); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); -} - -::google::protobuf::Metadata CodeGeneratorRequest::GetMetadata() const { - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages]; -} - - -// =================================================================== - -void CodeGeneratorResponse_File::InitAsDefaultInstance() { -} -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int CodeGeneratorResponse_File::kNameFieldNumber; -const int CodeGeneratorResponse_File::kInsertionPointFieldNumber; -const int CodeGeneratorResponse_File::kContentFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -CodeGeneratorResponse_File::CodeGeneratorResponse_File() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base); - SharedCtor(); - // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse.File) -} -CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _has_bits_(from._has_bits_) { - _internal_metadata_.MergeFrom(from._internal_metadata_); - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.has_name()) { - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.has_insertion_point()) { - insertion_point_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.insertion_point_); - } - content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.has_content()) { - content_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_); - } - // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse.File) -} - -void CodeGeneratorResponse_File::SharedCtor() { - name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - insertion_point_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - content_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -CodeGeneratorResponse_File::~CodeGeneratorResponse_File() { - // @@protoc_insertion_point(destructor:google.protobuf.compiler.CodeGeneratorResponse.File) - SharedDtor(); -} - -void CodeGeneratorResponse_File::SharedDtor() { - name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - insertion_point_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - content_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void CodeGeneratorResponse_File::SetCachedSize(int size) const { - _cached_size_.Set(size); -} -const ::google::protobuf::Descriptor* CodeGeneratorResponse_File::descriptor() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - -const CodeGeneratorResponse_File& CodeGeneratorResponse_File::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse_File.base); - return *internal_default_instance(); -} - - -void CodeGeneratorResponse_File::Clear() { -// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorResponse.File) - ::google::protobuf::uint32 cached_has_bits = 0; - // Prevent compiler warnings about cached_has_bits being unused - (void) cached_has_bits; - - cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 7u) { - if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmptyNoArena(); - } - if (cached_has_bits & 0x00000002u) { - insertion_point_.ClearNonDefaultToEmptyNoArena(); - } - if (cached_has_bits & 0x00000004u) { - content_.ClearNonDefaultToEmptyNoArena(); - } - } - _has_bits_.Clear(); - _internal_metadata_.Clear(); -} - -bool CodeGeneratorResponse_File::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse.File) - for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::PARSE, - "google.protobuf.compiler.CodeGeneratorResponse.File.name"); - } else { - goto handle_unusual; - } - break; - } - - // optional string insertion_point = 2; - case 2: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_insertion_point())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->insertion_point().data(), static_cast(this->insertion_point().length()), - ::google::protobuf::internal::WireFormat::PARSE, - "google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point"); - } else { - goto handle_unusual; - } - break; - } - - // optional string content = 15; - case 15: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_content())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->content().data(), static_cast(this->content().length()), - ::google::protobuf::internal::WireFormat::PARSE, - "google.protobuf.compiler.CodeGeneratorResponse.File.content"); - } else { - goto handle_unusual; - } - break; - } - - default: { - handle_unusual: - if (tag == 0) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, _internal_metadata_.mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:google.protobuf.compiler.CodeGeneratorResponse.File) - return true; -failure: - // @@protoc_insertion_point(parse_failure:google.protobuf.compiler.CodeGeneratorResponse.File) - return false; -#undef DO_ -} - -void CodeGeneratorResponse_File::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorResponse.File) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - cached_has_bits = _has_bits_[0]; - // optional string name = 1; - if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorResponse.File.name"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->name(), output); - } - - // optional string insertion_point = 2; - if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->insertion_point().data(), static_cast(this->insertion_point().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 2, this->insertion_point(), output); - } - - // optional string content = 15; - if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->content().data(), static_cast(this->content().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorResponse.File.content"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 15, this->content(), output); - } - - if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - _internal_metadata_.unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorResponse.File) -} - -::google::protobuf::uint8* CodeGeneratorResponse_File::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorResponse.File) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - cached_has_bits = _has_bits_[0]; - // optional string name = 1; - if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->name().data(), static_cast(this->name().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorResponse.File.name"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // optional string insertion_point = 2; - if (cached_has_bits & 0x00000002u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->insertion_point().data(), static_cast(this->insertion_point().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->insertion_point(), target); - } - - // optional string content = 15; - if (cached_has_bits & 0x00000004u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->content().data(), static_cast(this->content().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorResponse.File.content"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 15, this->content(), target); - } - - if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - _internal_metadata_.unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorResponse.File) - return target; -} - -size_t CodeGeneratorResponse_File::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:google.protobuf.compiler.CodeGeneratorResponse.File) - size_t total_size = 0; - - if (_internal_metadata_.have_unknown_fields()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - _internal_metadata_.unknown_fields()); - } - if (_has_bits_[0 / 32] & 7u) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional string insertion_point = 2; - if (has_insertion_point()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->insertion_point()); - } - - // optional string content = 15; - if (has_content()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->content()); - } - - } - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - SetCachedSize(cached_size); - return total_size; -} - -void CodeGeneratorResponse_File::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File) - GOOGLE_DCHECK_NE(&from, this); - const CodeGeneratorResponse_File* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorResponse.File) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorResponse.File) - MergeFrom(*source); - } -} - -void CodeGeneratorResponse_File::MergeFrom(const CodeGeneratorResponse_File& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse.File) - GOOGLE_DCHECK_NE(&from, this); - _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - cached_has_bits = from._has_bits_[0]; - if (cached_has_bits & 7u) { - if (cached_has_bits & 0x00000001u) { - set_has_name(); - name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); - } - if (cached_has_bits & 0x00000002u) { - set_has_insertion_point(); - insertion_point_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.insertion_point_); - } - if (cached_has_bits & 0x00000004u) { - set_has_content(); - content_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.content_); - } - } -} - -void CodeGeneratorResponse_File::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.compiler.CodeGeneratorResponse.File) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void CodeGeneratorResponse_File::CopyFrom(const CodeGeneratorResponse_File& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.compiler.CodeGeneratorResponse.File) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool CodeGeneratorResponse_File::IsInitialized() const { - return true; -} - -void CodeGeneratorResponse_File::Swap(CodeGeneratorResponse_File* other) { - if (other == this) return; - InternalSwap(other); -} -void CodeGeneratorResponse_File::InternalSwap(CodeGeneratorResponse_File* other) { - using std::swap; - name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - insertion_point_.Swap(&other->insertion_point_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - content_.Swap(&other->content_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); -} - -::google::protobuf::Metadata CodeGeneratorResponse_File::GetMetadata() const { - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages]; -} - - -// =================================================================== - -void CodeGeneratorResponse::InitAsDefaultInstance() { -} -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int CodeGeneratorResponse::kErrorFieldNumber; -const int CodeGeneratorResponse::kFileFieldNumber; -#endif // !defined(_MSC_VER) || _MSC_VER >= 1900 - -CodeGeneratorResponse::CodeGeneratorResponse() - : ::google::protobuf::Message(), _internal_metadata_(NULL) { - ::google::protobuf::internal::InitSCC( - &protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base); - SharedCtor(); - // @@protoc_insertion_point(constructor:google.protobuf.compiler.CodeGeneratorResponse) -} -CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from) - : ::google::protobuf::Message(), - _internal_metadata_(NULL), - _has_bits_(from._has_bits_), - file_(from.file_) { - _internal_metadata_.MergeFrom(from._internal_metadata_); - error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - if (from.has_error()) { - error_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.error_); - } - // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse) -} - -void CodeGeneratorResponse::SharedCtor() { - error_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -CodeGeneratorResponse::~CodeGeneratorResponse() { - // @@protoc_insertion_point(destructor:google.protobuf.compiler.CodeGeneratorResponse) - SharedDtor(); -} - -void CodeGeneratorResponse::SharedDtor() { - error_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); -} - -void CodeGeneratorResponse::SetCachedSize(int size) const { - _cached_size_.Set(size); -} -const ::google::protobuf::Descriptor* CodeGeneratorResponse::descriptor() { - ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; -} - -const CodeGeneratorResponse& CodeGeneratorResponse::default_instance() { - ::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::scc_info_CodeGeneratorResponse.base); - return *internal_default_instance(); -} - - -void CodeGeneratorResponse::Clear() { -// @@protoc_insertion_point(message_clear_start:google.protobuf.compiler.CodeGeneratorResponse) - ::google::protobuf::uint32 cached_has_bits = 0; - // Prevent compiler warnings about cached_has_bits being unused - (void) cached_has_bits; - - file_.Clear(); - cached_has_bits = _has_bits_[0]; - if (cached_has_bits & 0x00000001u) { - error_.ClearNonDefaultToEmptyNoArena(); - } - _has_bits_.Clear(); - _internal_metadata_.Clear(); -} - -bool CodeGeneratorResponse::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure - ::google::protobuf::uint32 tag; - // @@protoc_insertion_point(parse_start:google.protobuf.compiler.CodeGeneratorResponse) - for (;;) { - ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); - tag = p.first; - if (!p.second) goto handle_unusual; - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string error = 1; - case 1: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_error())); - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->error().data(), static_cast(this->error().length()), - ::google::protobuf::internal::WireFormat::PARSE, - "google.protobuf.compiler.CodeGeneratorResponse.error"); - } else { - goto handle_unusual; - } - break; - } - - // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; - case 15: { - if (static_cast< ::google::protobuf::uint8>(tag) == - static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { - DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( - input, add_file())); - } else { - goto handle_unusual; - } - break; - } - - default: { - handle_unusual: - if (tag == 0) { - goto success; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, _internal_metadata_.mutable_unknown_fields())); - break; - } - } - } -success: - // @@protoc_insertion_point(parse_success:google.protobuf.compiler.CodeGeneratorResponse) - return true; -failure: - // @@protoc_insertion_point(parse_failure:google.protobuf.compiler.CodeGeneratorResponse) - return false; -#undef DO_ -} - -void CodeGeneratorResponse::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // @@protoc_insertion_point(serialize_start:google.protobuf.compiler.CodeGeneratorResponse) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - cached_has_bits = _has_bits_[0]; - // optional string error = 1; - if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->error().data(), static_cast(this->error().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorResponse.error"); - ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( - 1, this->error(), output); - } - - // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; - for (unsigned int i = 0, - n = static_cast(this->file_size()); i < n; i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 15, - this->file(static_cast(i)), - output); - } - - if (_internal_metadata_.have_unknown_fields()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - _internal_metadata_.unknown_fields(), output); - } - // @@protoc_insertion_point(serialize_end:google.protobuf.compiler.CodeGeneratorResponse) -} - -::google::protobuf::uint8* CodeGeneratorResponse::InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const { - (void)deterministic; // Unused - // @@protoc_insertion_point(serialize_to_array_start:google.protobuf.compiler.CodeGeneratorResponse) - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - cached_has_bits = _has_bits_[0]; - // optional string error = 1; - if (cached_has_bits & 0x00000001u) { - ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( - this->error().data(), static_cast(this->error().length()), - ::google::protobuf::internal::WireFormat::SERIALIZE, - "google.protobuf.compiler.CodeGeneratorResponse.error"); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->error(), target); - } - - // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; - for (unsigned int i = 0, - n = static_cast(this->file_size()); i < n; i++) { - target = ::google::protobuf::internal::WireFormatLite:: - InternalWriteMessageToArray( - 15, this->file(static_cast(i)), deterministic, target); - } - - if (_internal_metadata_.have_unknown_fields()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - _internal_metadata_.unknown_fields(), target); - } - // @@protoc_insertion_point(serialize_to_array_end:google.protobuf.compiler.CodeGeneratorResponse) - return target; -} - -size_t CodeGeneratorResponse::ByteSizeLong() const { -// @@protoc_insertion_point(message_byte_size_start:google.protobuf.compiler.CodeGeneratorResponse) - size_t total_size = 0; - - if (_internal_metadata_.have_unknown_fields()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - _internal_metadata_.unknown_fields()); - } - // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; - { - unsigned int count = static_cast(this->file_size()); - total_size += 1UL * count; - for (unsigned int i = 0; i < count; i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSize( - this->file(static_cast(i))); - } - } - - // optional string error = 1; - if (has_error()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->error()); - } - - int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); - SetCachedSize(cached_size); - return total_size; -} - -void CodeGeneratorResponse::MergeFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse) - GOOGLE_DCHECK_NE(&from, this); - const CodeGeneratorResponse* source = - ::google::protobuf::internal::DynamicCastToGenerated( - &from); - if (source == NULL) { - // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.compiler.CodeGeneratorResponse) - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - // @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.compiler.CodeGeneratorResponse) - MergeFrom(*source); - } -} - -void CodeGeneratorResponse::MergeFrom(const CodeGeneratorResponse& from) { -// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.compiler.CodeGeneratorResponse) - GOOGLE_DCHECK_NE(&from, this); - _internal_metadata_.MergeFrom(from._internal_metadata_); - ::google::protobuf::uint32 cached_has_bits = 0; - (void) cached_has_bits; - - file_.MergeFrom(from.file_); - if (from.has_error()) { - set_has_error(); - error_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.error_); - } -} - -void CodeGeneratorResponse::CopyFrom(const ::google::protobuf::Message& from) { -// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.compiler.CodeGeneratorResponse) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void CodeGeneratorResponse::CopyFrom(const CodeGeneratorResponse& from) { -// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.compiler.CodeGeneratorResponse) - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool CodeGeneratorResponse::IsInitialized() const { - return true; -} - -void CodeGeneratorResponse::Swap(CodeGeneratorResponse* other) { - if (other == this) return; - InternalSwap(other); -} -void CodeGeneratorResponse::InternalSwap(CodeGeneratorResponse* other) { - using std::swap; - CastToBase(&file_)->InternalSwap(CastToBase(&other->file_)); - error_.Swap(&other->error_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), - GetArenaNoVirtual()); - swap(_has_bits_[0], other->_has_bits_[0]); - _internal_metadata_.Swap(&other->_internal_metadata_); -} - -::google::protobuf::Metadata CodeGeneratorResponse::GetMetadata() const { - protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::protobuf_AssignDescriptorsOnce(); - return ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::file_level_metadata[kIndexInFileMessages]; -} - - -// @@protoc_insertion_point(namespace_scope) -} // namespace compiler -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage< ::google::protobuf::compiler::Version >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::compiler::Version >(arena); -} -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorRequest >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorRequest >(arena); -} -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse_File >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse_File >(arena); -} -template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage< ::google::protobuf::compiler::CodeGeneratorResponse >(Arena* arena) { - return Arena::CreateInternal< ::google::protobuf::compiler::CodeGeneratorResponse >(arena); -} -} // namespace protobuf -} // namespace google - -// @@protoc_insertion_point(global_scope) diff --git a/windows/include/google/protobuf/compiler/plugin.pb.h b/windows/include/google/protobuf/compiler/plugin.pb.h index 78d3bba3b..569bb30a6 100644 --- a/windows/include/google/protobuf/compiler/plugin.pb.h +++ b/windows/include/google/protobuf/compiler/plugin.pb.h @@ -1,126 +1,166 @@ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/compiler/plugin.proto -#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto -#define PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#ifndef GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#define GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#include #include -#include - -#if GOOGLE_PROTOBUF_VERSION < 3006001 +#include +#if PROTOBUF_VERSION < 3019000 #error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update +#error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif -#if 3006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION +#if 3019001 < 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 incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif +#include #include #include #include #include #include -#include -#include +#include +#include #include #include // IWYU pragma: export #include // IWYU pragma: export +#include #include #include // @@protoc_insertion_point(includes) -#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto LIBPROTOC_EXPORT +#include +#define PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fcompiler_2fplugin_2eproto PROTOC_EXPORT #ifdef major #undef major #endif #ifdef minor #undef minor #endif +PROTOBUF_NAMESPACE_OPEN +namespace internal { +class AnyMetadata; +} // namespace internal +PROTOBUF_NAMESPACE_CLOSE -namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto { // Internal implementation detail -- do not use these members. -struct LIBPROTOC_EXPORT TableStruct { - static const ::google::protobuf::internal::ParseTableField entries[]; - static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; - static const ::google::protobuf::internal::ParseTable schema[4]; - static const ::google::protobuf::internal::FieldMetadata field_metadata[]; - static const ::google::protobuf::internal::SerializationTable serialization_table[]; - static const ::google::protobuf::uint32 offsets[]; +struct PROTOC_EXPORT TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto { + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[4] + PROTOBUF_SECTION_VARIABLE(protodesc_cold); + static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; + static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; + static const uint32_t offsets[]; }; -void LIBPROTOC_EXPORT AddDescriptors(); -} // namespace protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto -namespace google { -namespace protobuf { +PROTOC_EXPORT extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto; +PROTOBUF_NAMESPACE_OPEN namespace compiler { class CodeGeneratorRequest; -class CodeGeneratorRequestDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_; +struct CodeGeneratorRequestDefaultTypeInternal; +PROTOC_EXPORT extern CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_; class CodeGeneratorResponse; -class CodeGeneratorResponseDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_; +struct CodeGeneratorResponseDefaultTypeInternal; +PROTOC_EXPORT extern CodeGeneratorResponseDefaultTypeInternal _CodeGeneratorResponse_default_instance_; class CodeGeneratorResponse_File; -class CodeGeneratorResponse_FileDefaultTypeInternal; -LIBPROTOC_EXPORT extern CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_; +struct CodeGeneratorResponse_FileDefaultTypeInternal; +PROTOC_EXPORT extern CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_; class Version; -class VersionDefaultTypeInternal; -LIBPROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_; +struct VersionDefaultTypeInternal; +PROTOC_EXPORT extern VersionDefaultTypeInternal _Version_default_instance_; } // namespace compiler -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorRequest>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::google::protobuf::compiler::CodeGeneratorResponse_File>(Arena*); -template<> LIBPROTOC_EXPORT ::google::protobuf::compiler::Version* Arena::CreateMaybeMessage<::google::protobuf::compiler::Version>(Arena*); -} // namespace protobuf -} // namespace google -namespace google { -namespace protobuf { +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN +template<> PROTOC_EXPORT ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest>(Arena*); +template<> PROTOC_EXPORT ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse>(Arena*); +template<> PROTOC_EXPORT ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File>(Arena*); +template<> PROTOC_EXPORT ::PROTOBUF_NAMESPACE_ID::compiler::Version* Arena::CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::compiler::Version>(Arena*); +PROTOBUF_NAMESPACE_CLOSE +PROTOBUF_NAMESPACE_OPEN namespace compiler { +enum CodeGeneratorResponse_Feature : int { + CodeGeneratorResponse_Feature_FEATURE_NONE = 0, + CodeGeneratorResponse_Feature_FEATURE_PROTO3_OPTIONAL = 1 +}; +PROTOC_EXPORT bool CodeGeneratorResponse_Feature_IsValid(int value); +constexpr CodeGeneratorResponse_Feature CodeGeneratorResponse_Feature_Feature_MIN = CodeGeneratorResponse_Feature_FEATURE_NONE; +constexpr CodeGeneratorResponse_Feature CodeGeneratorResponse_Feature_Feature_MAX = CodeGeneratorResponse_Feature_FEATURE_PROTO3_OPTIONAL; +constexpr int CodeGeneratorResponse_Feature_Feature_ARRAYSIZE = CodeGeneratorResponse_Feature_Feature_MAX + 1; + +PROTOC_EXPORT const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* CodeGeneratorResponse_Feature_descriptor(); +template +inline const std::string& CodeGeneratorResponse_Feature_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function CodeGeneratorResponse_Feature_Name."); + return ::PROTOBUF_NAMESPACE_ID::internal::NameOfEnum( + CodeGeneratorResponse_Feature_descriptor(), enum_t_value); +} +inline bool CodeGeneratorResponse_Feature_Parse( + ::PROTOBUF_NAMESPACE_ID::ConstStringParam name, CodeGeneratorResponse_Feature* value) { + return ::PROTOBUF_NAMESPACE_ID::internal::ParseNamedEnum( + CodeGeneratorResponse_Feature_descriptor(), name, value); +} // =================================================================== -class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ { +class PROTOC_EXPORT Version final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.Version) */ { public: - Version(); - virtual ~Version(); + inline Version() : Version(nullptr) {} + ~Version() override; + explicit constexpr Version(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); Version(const Version& from); - - inline Version& operator=(const Version& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 Version(Version&& from) noexcept : Version() { *this = ::std::move(from); } + inline Version& operator=(const Version& from) { + CopyFrom(from); + return *this; + } inline Version& operator=(Version&& from) noexcept { - if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { - if (this != &from) InternalSwap(&from); + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); } else { CopyFrom(from); } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _internal_metadata_.unknown_fields(); + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { + return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return _internal_metadata_.mutable_unknown_fields(); + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { + return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } - static const ::google::protobuf::Descriptor* descriptor(); - static const Version& default_instance(); - - static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const Version& default_instance() { + return *internal_default_instance(); + } static inline const Version* internal_default_instance() { return reinterpret_cast( &_Version_default_instance_); @@ -128,34 +168,47 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ static constexpr int kIndexInFileMessages = 0; - void Swap(Version* other); friend void swap(Version& a, Version& b) { a.Swap(&b); } + inline void Swap(Version* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(Version* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } // implements Message ---------------------------------------------- - inline Version* New() const final { - return CreateMaybeMessage(NULL); - } - - Version* New(::google::protobuf::Arena* arena) const final { + Version* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const Version& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const Version& from); - void Clear() final; + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: @@ -163,116 +216,159 @@ class LIBPROTOC_EXPORT Version : public ::google::protobuf::Message /* @@protoc_ void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Version* other); + private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; - } - inline void* MaybeArenaPtr() const { - return NULL; + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.compiler.Version"; } + protected: + explicit Version(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: - ::google::protobuf::Metadata GetMetadata() const final; + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- + enum : int { + kSuffixFieldNumber = 4, + kMajorFieldNumber = 1, + kMinorFieldNumber = 2, + kPatchFieldNumber = 3, + }; // optional string suffix = 4; bool has_suffix() const; + private: + bool _internal_has_suffix() const; + public: void clear_suffix(); - static const int kSuffixFieldNumber = 4; - const ::std::string& suffix() const; - void set_suffix(const ::std::string& value); - #if LANG_CXX11 - void set_suffix(::std::string&& value); - #endif - void set_suffix(const char* value); - void set_suffix(const char* value, size_t size); - ::std::string* mutable_suffix(); - ::std::string* release_suffix(); - void set_allocated_suffix(::std::string* suffix); + const std::string& suffix() const; + template + void set_suffix(ArgT0&& arg0, ArgT... args); + std::string* mutable_suffix(); + PROTOBUF_NODISCARD std::string* release_suffix(); + void set_allocated_suffix(std::string* suffix); + private: + const std::string& _internal_suffix() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_suffix(const std::string& value); + std::string* _internal_mutable_suffix(); + public: // optional int32 major = 1; bool has_major() const; + private: + bool _internal_has_major() const; + public: void clear_major(); - static const int kMajorFieldNumber = 1; - ::google::protobuf::int32 major() const; - void set_major(::google::protobuf::int32 value); + int32_t major() const; + void set_major(int32_t value); + private: + int32_t _internal_major() const; + void _internal_set_major(int32_t value); + public: // optional int32 minor = 2; bool has_minor() const; + private: + bool _internal_has_minor() const; + public: void clear_minor(); - static const int kMinorFieldNumber = 2; - ::google::protobuf::int32 minor() const; - void set_minor(::google::protobuf::int32 value); + int32_t minor() const; + void set_minor(int32_t value); + private: + int32_t _internal_minor() const; + void _internal_set_minor(int32_t value); + public: // optional int32 patch = 3; bool has_patch() const; + private: + bool _internal_has_patch() const; + public: void clear_patch(); - static const int kPatchFieldNumber = 3; - ::google::protobuf::int32 patch() const; - void set_patch(::google::protobuf::int32 value); + int32_t patch() const; + void set_patch(int32_t value); + private: + int32_t _internal_patch() const; + void _internal_set_patch(int32_t value); + public: // @@protoc_insertion_point(class_scope:google.protobuf.compiler.Version) private: - void set_has_major(); - void clear_has_major(); - void set_has_minor(); - void clear_has_minor(); - void set_has_patch(); - void clear_has_patch(); - void set_has_suffix(); - void clear_has_suffix(); + class _Internal; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr suffix_; - ::google::protobuf::int32 major_; - ::google::protobuf::int32 minor_; - ::google::protobuf::int32 patch_; - friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr suffix_; + int32_t major_; + int32_t minor_; + int32_t patch_; + friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ { +class PROTOC_EXPORT CodeGeneratorRequest final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorRequest) */ { public: - CodeGeneratorRequest(); - virtual ~CodeGeneratorRequest(); + inline CodeGeneratorRequest() : CodeGeneratorRequest(nullptr) {} + ~CodeGeneratorRequest() override; + explicit constexpr CodeGeneratorRequest(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CodeGeneratorRequest(const CodeGeneratorRequest& from); - - inline CodeGeneratorRequest& operator=(const CodeGeneratorRequest& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 CodeGeneratorRequest(CodeGeneratorRequest&& from) noexcept : CodeGeneratorRequest() { *this = ::std::move(from); } + inline CodeGeneratorRequest& operator=(const CodeGeneratorRequest& from) { + CopyFrom(from); + return *this; + } inline CodeGeneratorRequest& operator=(CodeGeneratorRequest&& from) noexcept { - if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { - if (this != &from) InternalSwap(&from); + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); } else { CopyFrom(from); } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _internal_metadata_.unknown_fields(); + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { + return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return _internal_metadata_.mutable_unknown_fields(); + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { + return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } - static const ::google::protobuf::Descriptor* descriptor(); - static const CodeGeneratorRequest& default_instance(); - - static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const CodeGeneratorRequest& default_instance() { + return *internal_default_instance(); + } static inline const CodeGeneratorRequest* internal_default_instance() { return reinterpret_cast( &_CodeGeneratorRequest_default_instance_); @@ -280,34 +376,47 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message static constexpr int kIndexInFileMessages = 1; - void Swap(CodeGeneratorRequest* other); friend void swap(CodeGeneratorRequest& a, CodeGeneratorRequest& b) { a.Swap(&b); } + inline void Swap(CodeGeneratorRequest* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(CodeGeneratorRequest* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } // implements Message ---------------------------------------------- - inline CodeGeneratorRequest* New() const final { - return CreateMaybeMessage(NULL); - } - - CodeGeneratorRequest* New(::google::protobuf::Arena* arena) const final { + CodeGeneratorRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CodeGeneratorRequest& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const CodeGeneratorRequest& from); - void Clear() final; + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: @@ -315,137 +424,180 @@ class LIBPROTOC_EXPORT CodeGeneratorRequest : public ::google::protobuf::Message void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorRequest* other); + private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; - } - inline void* MaybeArenaPtr() const { - return NULL; + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.compiler.CodeGeneratorRequest"; } + protected: + explicit CodeGeneratorRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: - ::google::protobuf::Metadata GetMetadata() const final; + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- + enum : int { + kFileToGenerateFieldNumber = 1, + kProtoFileFieldNumber = 15, + kParameterFieldNumber = 2, + kCompilerVersionFieldNumber = 3, + }; // repeated string file_to_generate = 1; int file_to_generate_size() const; + private: + int _internal_file_to_generate_size() const; + public: void clear_file_to_generate(); - static const int kFileToGenerateFieldNumber = 1; - const ::std::string& file_to_generate(int index) const; - ::std::string* mutable_file_to_generate(int index); - void set_file_to_generate(int index, const ::std::string& value); - #if LANG_CXX11 - void set_file_to_generate(int index, ::std::string&& value); - #endif + const std::string& file_to_generate(int index) const; + std::string* mutable_file_to_generate(int index); + void set_file_to_generate(int index, const std::string& value); + void set_file_to_generate(int index, std::string&& value); void set_file_to_generate(int index, const char* value); void set_file_to_generate(int index, const char* value, size_t size); - ::std::string* add_file_to_generate(); - void add_file_to_generate(const ::std::string& value); - #if LANG_CXX11 - void add_file_to_generate(::std::string&& value); - #endif + std::string* add_file_to_generate(); + void add_file_to_generate(const std::string& value); + void add_file_to_generate(std::string&& value); void add_file_to_generate(const char* value); void add_file_to_generate(const char* value, size_t size); - const ::google::protobuf::RepeatedPtrField< ::std::string>& file_to_generate() const; - ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_file_to_generate(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& file_to_generate() const; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* mutable_file_to_generate(); + private: + const std::string& _internal_file_to_generate(int index) const; + std::string* _internal_add_file_to_generate(); + public: // repeated .google.protobuf.FileDescriptorProto proto_file = 15; int proto_file_size() const; + private: + int _internal_proto_file_size() const; + public: void clear_proto_file(); - static const int kProtoFileFieldNumber = 15; - ::google::protobuf::FileDescriptorProto* mutable_proto_file(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >* + ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* mutable_proto_file(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto >* mutable_proto_file(); - const ::google::protobuf::FileDescriptorProto& proto_file(int index) const; - ::google::protobuf::FileDescriptorProto* add_proto_file(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >& + private: + const ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto& _internal_proto_file(int index) const; + ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* _internal_add_proto_file(); + public: + const ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto& proto_file(int index) const; + ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* add_proto_file(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto >& proto_file() const; // optional string parameter = 2; bool has_parameter() const; + private: + bool _internal_has_parameter() const; + public: void clear_parameter(); - static const int kParameterFieldNumber = 2; - const ::std::string& parameter() const; - void set_parameter(const ::std::string& value); - #if LANG_CXX11 - void set_parameter(::std::string&& value); - #endif - void set_parameter(const char* value); - void set_parameter(const char* value, size_t size); - ::std::string* mutable_parameter(); - ::std::string* release_parameter(); - void set_allocated_parameter(::std::string* parameter); + const std::string& parameter() const; + template + void set_parameter(ArgT0&& arg0, ArgT... args); + std::string* mutable_parameter(); + PROTOBUF_NODISCARD std::string* release_parameter(); + void set_allocated_parameter(std::string* parameter); + private: + const std::string& _internal_parameter() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_parameter(const std::string& value); + std::string* _internal_mutable_parameter(); + public: // optional .google.protobuf.compiler.Version compiler_version = 3; bool has_compiler_version() const; - void clear_compiler_version(); - static const int kCompilerVersionFieldNumber = 3; private: - const ::google::protobuf::compiler::Version& _internal_compiler_version() const; + bool _internal_has_compiler_version() const; public: - const ::google::protobuf::compiler::Version& compiler_version() const; - ::google::protobuf::compiler::Version* release_compiler_version(); - ::google::protobuf::compiler::Version* mutable_compiler_version(); - void set_allocated_compiler_version(::google::protobuf::compiler::Version* compiler_version); + void clear_compiler_version(); + const ::PROTOBUF_NAMESPACE_ID::compiler::Version& compiler_version() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::compiler::Version* release_compiler_version(); + ::PROTOBUF_NAMESPACE_ID::compiler::Version* mutable_compiler_version(); + void set_allocated_compiler_version(::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version); + private: + const ::PROTOBUF_NAMESPACE_ID::compiler::Version& _internal_compiler_version() const; + ::PROTOBUF_NAMESPACE_ID::compiler::Version* _internal_mutable_compiler_version(); + public: + void unsafe_arena_set_allocated_compiler_version( + ::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version); + ::PROTOBUF_NAMESPACE_ID::compiler::Version* unsafe_arena_release_compiler_version(); // @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorRequest) private: - void set_has_parameter(); - void clear_has_parameter(); - void set_has_compiler_version(); - void clear_has_compiler_version(); + class _Internal; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::std::string> file_to_generate_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > proto_file_; - ::google::protobuf::internal::ArenaStringPtr parameter_; - ::google::protobuf::compiler::Version* compiler_version_; - friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField file_to_generate_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto > proto_file_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr parameter_; + ::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version_; + friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ { +class PROTOC_EXPORT CodeGeneratorResponse_File final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse.File) */ { public: - CodeGeneratorResponse_File(); - virtual ~CodeGeneratorResponse_File(); + inline CodeGeneratorResponse_File() : CodeGeneratorResponse_File(nullptr) {} + ~CodeGeneratorResponse_File() override; + explicit constexpr CodeGeneratorResponse_File(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from); - - inline CodeGeneratorResponse_File& operator=(const CodeGeneratorResponse_File& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 CodeGeneratorResponse_File(CodeGeneratorResponse_File&& from) noexcept : CodeGeneratorResponse_File() { *this = ::std::move(from); } + inline CodeGeneratorResponse_File& operator=(const CodeGeneratorResponse_File& from) { + CopyFrom(from); + return *this; + } inline CodeGeneratorResponse_File& operator=(CodeGeneratorResponse_File&& from) noexcept { - if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { - if (this != &from) InternalSwap(&from); + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); } else { CopyFrom(from); } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _internal_metadata_.unknown_fields(); + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { + return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return _internal_metadata_.mutable_unknown_fields(); + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { + return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } - static const ::google::protobuf::Descriptor* descriptor(); - static const CodeGeneratorResponse_File& default_instance(); - - static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const CodeGeneratorResponse_File& default_instance() { + return *internal_default_instance(); + } static inline const CodeGeneratorResponse_File* internal_default_instance() { return reinterpret_cast( &_CodeGeneratorResponse_File_default_instance_); @@ -453,34 +605,47 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M static constexpr int kIndexInFileMessages = 2; - void Swap(CodeGeneratorResponse_File* other); friend void swap(CodeGeneratorResponse_File& a, CodeGeneratorResponse_File& b) { a.Swap(&b); } + inline void Swap(CodeGeneratorResponse_File* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(CodeGeneratorResponse_File* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } // implements Message ---------------------------------------------- - inline CodeGeneratorResponse_File* New() const final { - return CreateMaybeMessage(NULL); - } - - CodeGeneratorResponse_File* New(::google::protobuf::Arena* arena) const final { + CodeGeneratorResponse_File* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CodeGeneratorResponse_File& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const CodeGeneratorResponse_File& from); - void Clear() final; + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: @@ -488,122 +653,174 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse_File : public ::google::protobuf::M void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse_File* other); + private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; - } - inline void* MaybeArenaPtr() const { - return NULL; + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.compiler.CodeGeneratorResponse.File"; } + protected: + explicit CodeGeneratorResponse_File(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: - ::google::protobuf::Metadata GetMetadata() const final; + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- + enum : int { + kNameFieldNumber = 1, + kInsertionPointFieldNumber = 2, + kContentFieldNumber = 15, + kGeneratedCodeInfoFieldNumber = 16, + }; // optional string name = 1; bool has_name() const; + private: + bool _internal_has_name() const; + public: void clear_name(); - static const int kNameFieldNumber = 1; - const ::std::string& name() const; - void set_name(const ::std::string& value); - #if LANG_CXX11 - void set_name(::std::string&& value); - #endif - void set_name(const char* value); - void set_name(const char* value, size_t size); - ::std::string* mutable_name(); - ::std::string* release_name(); - void set_allocated_name(::std::string* name); + const std::string& name() const; + template + void set_name(ArgT0&& arg0, ArgT... args); + std::string* mutable_name(); + PROTOBUF_NODISCARD std::string* release_name(); + void set_allocated_name(std::string* name); + private: + const std::string& _internal_name() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_name(const std::string& value); + std::string* _internal_mutable_name(); + public: // optional string insertion_point = 2; bool has_insertion_point() const; + private: + bool _internal_has_insertion_point() const; + public: void clear_insertion_point(); - static const int kInsertionPointFieldNumber = 2; - const ::std::string& insertion_point() const; - void set_insertion_point(const ::std::string& value); - #if LANG_CXX11 - void set_insertion_point(::std::string&& value); - #endif - void set_insertion_point(const char* value); - void set_insertion_point(const char* value, size_t size); - ::std::string* mutable_insertion_point(); - ::std::string* release_insertion_point(); - void set_allocated_insertion_point(::std::string* insertion_point); + const std::string& insertion_point() const; + template + void set_insertion_point(ArgT0&& arg0, ArgT... args); + std::string* mutable_insertion_point(); + PROTOBUF_NODISCARD std::string* release_insertion_point(); + void set_allocated_insertion_point(std::string* insertion_point); + private: + const std::string& _internal_insertion_point() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_insertion_point(const std::string& value); + std::string* _internal_mutable_insertion_point(); + public: // optional string content = 15; bool has_content() const; + private: + bool _internal_has_content() const; + public: void clear_content(); - static const int kContentFieldNumber = 15; - const ::std::string& content() const; - void set_content(const ::std::string& value); - #if LANG_CXX11 - void set_content(::std::string&& value); - #endif - void set_content(const char* value); - void set_content(const char* value, size_t size); - ::std::string* mutable_content(); - ::std::string* release_content(); - void set_allocated_content(::std::string* content); + const std::string& content() const; + template + void set_content(ArgT0&& arg0, ArgT... args); + std::string* mutable_content(); + PROTOBUF_NODISCARD std::string* release_content(); + void set_allocated_content(std::string* content); + private: + const std::string& _internal_content() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_content(const std::string& value); + std::string* _internal_mutable_content(); + public: + + // optional .google.protobuf.GeneratedCodeInfo generated_code_info = 16; + bool has_generated_code_info() const; + private: + bool _internal_has_generated_code_info() const; + public: + void clear_generated_code_info(); + const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo& generated_code_info() const; + PROTOBUF_NODISCARD ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* release_generated_code_info(); + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* mutable_generated_code_info(); + void set_allocated_generated_code_info(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info); + private: + const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo& _internal_generated_code_info() const; + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* _internal_mutable_generated_code_info(); + public: + void unsafe_arena_set_allocated_generated_code_info( + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info); + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* unsafe_arena_release_generated_code_info(); // @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse.File) private: - void set_has_name(); - void clear_has_name(); - void set_has_insertion_point(); - void clear_has_insertion_point(); - void set_has_content(); - void clear_has_content(); + class _Internal; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::internal::ArenaStringPtr name_; - ::google::protobuf::internal::ArenaStringPtr insertion_point_; - ::google::protobuf::internal::ArenaStringPtr content_; - friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr insertion_point_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr content_; + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info_; + friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- -class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ { +class PROTOC_EXPORT CodeGeneratorResponse final : + public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:google.protobuf.compiler.CodeGeneratorResponse) */ { public: - CodeGeneratorResponse(); - virtual ~CodeGeneratorResponse(); + inline CodeGeneratorResponse() : CodeGeneratorResponse(nullptr) {} + ~CodeGeneratorResponse() override; + explicit constexpr CodeGeneratorResponse(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CodeGeneratorResponse(const CodeGeneratorResponse& from); - - inline CodeGeneratorResponse& operator=(const CodeGeneratorResponse& from) { - CopyFrom(from); - return *this; - } - #if LANG_CXX11 CodeGeneratorResponse(CodeGeneratorResponse&& from) noexcept : CodeGeneratorResponse() { *this = ::std::move(from); } + inline CodeGeneratorResponse& operator=(const CodeGeneratorResponse& from) { + CopyFrom(from); + return *this; + } inline CodeGeneratorResponse& operator=(CodeGeneratorResponse&& from) noexcept { - if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { - if (this != &from) InternalSwap(&from); + if (this == &from) return *this; + if (GetOwningArena() == from.GetOwningArena() + #ifdef PROTOBUF_FORCE_COPY_IN_MOVE + && GetOwningArena() != nullptr + #endif // !PROTOBUF_FORCE_COPY_IN_MOVE + ) { + InternalSwap(&from); } else { CopyFrom(from); } return *this; } - #endif - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _internal_metadata_.unknown_fields(); + + inline const ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet& unknown_fields() const { + return _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance); } - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return _internal_metadata_.mutable_unknown_fields(); + inline ::PROTOBUF_NAMESPACE_ID::UnknownFieldSet* mutable_unknown_fields() { + return _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } - static const ::google::protobuf::Descriptor* descriptor(); - static const CodeGeneratorResponse& default_instance(); - - static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { + return GetDescriptor(); + } + static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { + return default_instance().GetMetadata().descriptor; + } + static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { + return default_instance().GetMetadata().reflection; + } + static const CodeGeneratorResponse& default_instance() { + return *internal_default_instance(); + } static inline const CodeGeneratorResponse* internal_default_instance() { return reinterpret_cast( &_CodeGeneratorResponse_default_instance_); @@ -611,34 +828,47 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag static constexpr int kIndexInFileMessages = 3; - void Swap(CodeGeneratorResponse* other); friend void swap(CodeGeneratorResponse& a, CodeGeneratorResponse& b) { a.Swap(&b); } + inline void Swap(CodeGeneratorResponse* other) { + if (other == this) return; + #ifdef PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() != nullptr && + GetOwningArena() == other->GetOwningArena()) { + #else // PROTOBUF_FORCE_COPY_IN_SWAP + if (GetOwningArena() == other->GetOwningArena()) { + #endif // !PROTOBUF_FORCE_COPY_IN_SWAP + InternalSwap(other); + } else { + ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); + } + } + void UnsafeArenaSwap(CodeGeneratorResponse* other) { + if (other == this) return; + GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena()); + InternalSwap(other); + } // implements Message ---------------------------------------------- - inline CodeGeneratorResponse* New() const final { - return CreateMaybeMessage(NULL); - } - - CodeGeneratorResponse* New(::google::protobuf::Arena* arena) const final { + CodeGeneratorResponse* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final { return CreateMaybeMessage(arena); } - void CopyFrom(const ::google::protobuf::Message& from) final; - void MergeFrom(const ::google::protobuf::Message& from) final; + using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom; void CopyFrom(const CodeGeneratorResponse& from); + using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom; void MergeFrom(const CodeGeneratorResponse& from); - void Clear() final; + private: + static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message* to, const ::PROTOBUF_NAMESPACE_ID::Message& from); + public: + PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) final; - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const final; - ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( - bool deterministic, ::google::protobuf::uint8* target) const final; + const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; + uint8_t* _InternalSerialize( + uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: @@ -646,61 +876,128 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse* other); + private: - inline ::google::protobuf::Arena* GetArenaNoVirtual() const { - return NULL; - } - inline void* MaybeArenaPtr() const { - return NULL; + friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; + static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { + return "google.protobuf.compiler.CodeGeneratorResponse"; } + protected: + explicit CodeGeneratorResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena, + bool is_message_owned = false); + private: + static void ArenaDtor(void* object); + inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: - ::google::protobuf::Metadata GetMetadata() const final; + static const ClassData _class_data_; + const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final; + + ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; // nested types ---------------------------------------------------- typedef CodeGeneratorResponse_File File; + typedef CodeGeneratorResponse_Feature Feature; + static constexpr Feature FEATURE_NONE = + CodeGeneratorResponse_Feature_FEATURE_NONE; + static constexpr Feature FEATURE_PROTO3_OPTIONAL = + CodeGeneratorResponse_Feature_FEATURE_PROTO3_OPTIONAL; + static inline bool Feature_IsValid(int value) { + return CodeGeneratorResponse_Feature_IsValid(value); + } + static constexpr Feature Feature_MIN = + CodeGeneratorResponse_Feature_Feature_MIN; + static constexpr Feature Feature_MAX = + CodeGeneratorResponse_Feature_Feature_MAX; + static constexpr int Feature_ARRAYSIZE = + CodeGeneratorResponse_Feature_Feature_ARRAYSIZE; + static inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptor* + Feature_descriptor() { + return CodeGeneratorResponse_Feature_descriptor(); + } + template + static inline const std::string& Feature_Name(T enum_t_value) { + static_assert(::std::is_same::value || + ::std::is_integral::value, + "Incorrect type passed to function Feature_Name."); + return CodeGeneratorResponse_Feature_Name(enum_t_value); + } + static inline bool Feature_Parse(::PROTOBUF_NAMESPACE_ID::ConstStringParam name, + Feature* value) { + return CodeGeneratorResponse_Feature_Parse(name, value); + } + // accessors ------------------------------------------------------- + enum : int { + kFileFieldNumber = 15, + kErrorFieldNumber = 1, + kSupportedFeaturesFieldNumber = 2, + }; // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; int file_size() const; + private: + int _internal_file_size() const; + public: void clear_file(); - static const int kFileFieldNumber = 15; - ::google::protobuf::compiler::CodeGeneratorResponse_File* mutable_file(int index); - ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >* + ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* mutable_file(int index); + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >* mutable_file(); - const ::google::protobuf::compiler::CodeGeneratorResponse_File& file(int index) const; - ::google::protobuf::compiler::CodeGeneratorResponse_File* add_file(); - const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >& + private: + const ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File& _internal_file(int index) const; + ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* _internal_add_file(); + public: + const ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File& file(int index) const; + ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* add_file(); + const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >& file() const; // optional string error = 1; bool has_error() const; + private: + bool _internal_has_error() const; + public: void clear_error(); - static const int kErrorFieldNumber = 1; - const ::std::string& error() const; - void set_error(const ::std::string& value); - #if LANG_CXX11 - void set_error(::std::string&& value); - #endif - void set_error(const char* value); - void set_error(const char* value, size_t size); - ::std::string* mutable_error(); - ::std::string* release_error(); - void set_allocated_error(::std::string* error); + const std::string& error() const; + template + void set_error(ArgT0&& arg0, ArgT... args); + std::string* mutable_error(); + PROTOBUF_NODISCARD std::string* release_error(); + void set_allocated_error(std::string* error); + private: + const std::string& _internal_error() const; + inline PROTOBUF_ALWAYS_INLINE void _internal_set_error(const std::string& value); + std::string* _internal_mutable_error(); + public: + + // optional uint64 supported_features = 2; + bool has_supported_features() const; + private: + bool _internal_has_supported_features() const; + public: + void clear_supported_features(); + uint64_t supported_features() const; + void set_supported_features(uint64_t value); + private: + uint64_t _internal_supported_features() const; + void _internal_set_supported_features(uint64_t value); + public: // @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse) private: - void set_has_error(); - void clear_has_error(); + class _Internal; - ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; - ::google::protobuf::internal::HasBits<1> _has_bits_; - mutable ::google::protobuf::internal::CachedSize _cached_size_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File > file_; - ::google::protobuf::internal::ArenaStringPtr error_; - friend struct ::protobuf_google_2fprotobuf_2fcompiler_2fplugin_2eproto::TableStruct; + template friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; + typedef void InternalArenaConstructable_; + typedef void DestructorSkippable_; + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File > file_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr error_; + uint64_t supported_features_; + friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // =================================================================== @@ -714,140 +1011,155 @@ class LIBPROTOC_EXPORT CodeGeneratorResponse : public ::google::protobuf::Messag // Version // optional int32 major = 1; +inline bool Version::_internal_has_major() const { + bool value = (_has_bits_[0] & 0x00000002u) != 0; + return value; +} inline bool Version::has_major() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void Version::set_has_major() { - _has_bits_[0] |= 0x00000002u; -} -inline void Version::clear_has_major() { - _has_bits_[0] &= ~0x00000002u; + return _internal_has_major(); } inline void Version::clear_major() { major_ = 0; - clear_has_major(); + _has_bits_[0] &= ~0x00000002u; } -inline ::google::protobuf::int32 Version::major() const { - // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.major) +inline int32_t Version::_internal_major() const { return major_; } -inline void Version::set_major(::google::protobuf::int32 value) { - set_has_major(); +inline int32_t Version::major() const { + // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.major) + return _internal_major(); +} +inline void Version::_internal_set_major(int32_t value) { + _has_bits_[0] |= 0x00000002u; major_ = value; +} +inline void Version::set_major(int32_t value) { + _internal_set_major(value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.major) } // optional int32 minor = 2; +inline bool Version::_internal_has_minor() const { + bool value = (_has_bits_[0] & 0x00000004u) != 0; + return value; +} inline bool Version::has_minor() const { - return (_has_bits_[0] & 0x00000004u) != 0; -} -inline void Version::set_has_minor() { - _has_bits_[0] |= 0x00000004u; -} -inline void Version::clear_has_minor() { - _has_bits_[0] &= ~0x00000004u; + return _internal_has_minor(); } inline void Version::clear_minor() { minor_ = 0; - clear_has_minor(); + _has_bits_[0] &= ~0x00000004u; } -inline ::google::protobuf::int32 Version::minor() const { - // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.minor) +inline int32_t Version::_internal_minor() const { return minor_; } -inline void Version::set_minor(::google::protobuf::int32 value) { - set_has_minor(); +inline int32_t Version::minor() const { + // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.minor) + return _internal_minor(); +} +inline void Version::_internal_set_minor(int32_t value) { + _has_bits_[0] |= 0x00000004u; minor_ = value; +} +inline void Version::set_minor(int32_t value) { + _internal_set_minor(value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.minor) } // optional int32 patch = 3; +inline bool Version::_internal_has_patch() const { + bool value = (_has_bits_[0] & 0x00000008u) != 0; + return value; +} inline bool Version::has_patch() const { - return (_has_bits_[0] & 0x00000008u) != 0; -} -inline void Version::set_has_patch() { - _has_bits_[0] |= 0x00000008u; -} -inline void Version::clear_has_patch() { - _has_bits_[0] &= ~0x00000008u; + return _internal_has_patch(); } inline void Version::clear_patch() { patch_ = 0; - clear_has_patch(); + _has_bits_[0] &= ~0x00000008u; } -inline ::google::protobuf::int32 Version::patch() const { - // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.patch) +inline int32_t Version::_internal_patch() const { return patch_; } -inline void Version::set_patch(::google::protobuf::int32 value) { - set_has_patch(); +inline int32_t Version::patch() const { + // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.patch) + return _internal_patch(); +} +inline void Version::_internal_set_patch(int32_t value) { + _has_bits_[0] |= 0x00000008u; patch_ = value; +} +inline void Version::set_patch(int32_t value) { + _internal_set_patch(value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.patch) } // optional string suffix = 4; +inline bool Version::_internal_has_suffix() const { + bool value = (_has_bits_[0] & 0x00000001u) != 0; + return value; +} inline bool Version::has_suffix() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void Version::set_has_suffix() { - _has_bits_[0] |= 0x00000001u; -} -inline void Version::clear_has_suffix() { - _has_bits_[0] &= ~0x00000001u; + return _internal_has_suffix(); } inline void Version::clear_suffix() { - suffix_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_suffix(); + suffix_.ClearToEmpty(); + _has_bits_[0] &= ~0x00000001u; } -inline const ::std::string& Version::suffix() const { +inline const std::string& Version::suffix() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.suffix) - return suffix_.GetNoArena(); + return _internal_suffix(); } -inline void Version::set_suffix(const ::std::string& value) { - set_has_suffix(); - suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void Version::set_suffix(ArgT0&& arg0, ArgT... args) { + _has_bits_[0] |= 0x00000001u; + suffix_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.suffix) } -#if LANG_CXX11 -inline void Version::set_suffix(::std::string&& value) { - set_has_suffix(); - suffix_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.Version.suffix) -} -#endif -inline void Version::set_suffix(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_suffix(); - suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.Version.suffix) -} -inline void Version::set_suffix(const char* value, size_t size) { - set_has_suffix(); - suffix_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.Version.suffix) -} -inline ::std::string* Version::mutable_suffix() { - set_has_suffix(); +inline std::string* Version::mutable_suffix() { + std::string* _s = _internal_mutable_suffix(); // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.Version.suffix) - return suffix_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* Version::release_suffix() { +inline const std::string& Version::_internal_suffix() const { + return suffix_.Get(); +} +inline void Version::_internal_set_suffix(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + suffix_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); +} +inline std::string* Version::_internal_mutable_suffix() { + _has_bits_[0] |= 0x00000001u; + return suffix_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* Version::release_suffix() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.Version.suffix) - if (!has_suffix()) { - return NULL; + if (!_internal_has_suffix()) { + return nullptr; } - clear_has_suffix(); - return suffix_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000001u; + auto* p = suffix_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (suffix_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + suffix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + return p; } -inline void Version::set_allocated_suffix(::std::string* suffix) { - if (suffix != NULL) { - set_has_suffix(); +inline void Version::set_allocated_suffix(std::string* suffix) { + if (suffix != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_suffix(); + _has_bits_[0] &= ~0x00000001u; } - suffix_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), suffix); + suffix_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), suffix, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (suffix_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + suffix_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.Version.suffix) } @@ -856,32 +1168,41 @@ inline void Version::set_allocated_suffix(::std::string* suffix) { // CodeGeneratorRequest // repeated string file_to_generate = 1; -inline int CodeGeneratorRequest::file_to_generate_size() const { +inline int CodeGeneratorRequest::_internal_file_to_generate_size() const { return file_to_generate_.size(); } +inline int CodeGeneratorRequest::file_to_generate_size() const { + return _internal_file_to_generate_size(); +} inline void CodeGeneratorRequest::clear_file_to_generate() { file_to_generate_.Clear(); } -inline const ::std::string& CodeGeneratorRequest::file_to_generate(int index) const { - // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) +inline std::string* CodeGeneratorRequest::add_file_to_generate() { + std::string* _s = _internal_add_file_to_generate(); + // @@protoc_insertion_point(field_add_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) + return _s; +} +inline const std::string& CodeGeneratorRequest::_internal_file_to_generate(int index) const { return file_to_generate_.Get(index); } -inline ::std::string* CodeGeneratorRequest::mutable_file_to_generate(int index) { +inline const std::string& CodeGeneratorRequest::file_to_generate(int index) const { + // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) + return _internal_file_to_generate(index); +} +inline std::string* CodeGeneratorRequest::mutable_file_to_generate(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) return file_to_generate_.Mutable(index); } -inline void CodeGeneratorRequest::set_file_to_generate(int index, const ::std::string& value) { - // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) +inline void CodeGeneratorRequest::set_file_to_generate(int index, const std::string& value) { file_to_generate_.Mutable(index)->assign(value); -} -#if LANG_CXX11 -inline void CodeGeneratorRequest::set_file_to_generate(int index, ::std::string&& value) { // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) - file_to_generate_.Mutable(index)->assign(std::move(value)); } -#endif +inline void CodeGeneratorRequest::set_file_to_generate(int index, std::string&& value) { + file_to_generate_.Mutable(index)->assign(std::move(value)); + // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) +} inline void CodeGeneratorRequest::set_file_to_generate(int index, const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); file_to_generate_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } @@ -890,22 +1211,19 @@ inline void CodeGeneratorRequest::set_file_to_generate(int index, const char* va reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } -inline ::std::string* CodeGeneratorRequest::add_file_to_generate() { - // @@protoc_insertion_point(field_add_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) +inline std::string* CodeGeneratorRequest::_internal_add_file_to_generate() { return file_to_generate_.Add(); } -inline void CodeGeneratorRequest::add_file_to_generate(const ::std::string& value) { +inline void CodeGeneratorRequest::add_file_to_generate(const std::string& value) { file_to_generate_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } -#if LANG_CXX11 -inline void CodeGeneratorRequest::add_file_to_generate(::std::string&& value) { +inline void CodeGeneratorRequest::add_file_to_generate(std::string&& value) { file_to_generate_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } -#endif inline void CodeGeneratorRequest::add_file_to_generate(const char* value) { - GOOGLE_DCHECK(value != NULL); + GOOGLE_DCHECK(value != nullptr); file_to_generate_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } @@ -913,163 +1231,208 @@ inline void CodeGeneratorRequest::add_file_to_generate(const char* value, size_t file_to_generate_.Add()->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField& CodeGeneratorRequest::file_to_generate() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) return file_to_generate_; } -inline ::google::protobuf::RepeatedPtrField< ::std::string>* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField* CodeGeneratorRequest::mutable_file_to_generate() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) return &file_to_generate_; } // optional string parameter = 2; +inline bool CodeGeneratorRequest::_internal_has_parameter() const { + bool value = (_has_bits_[0] & 0x00000001u) != 0; + return value; +} inline bool CodeGeneratorRequest::has_parameter() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void CodeGeneratorRequest::set_has_parameter() { - _has_bits_[0] |= 0x00000001u; -} -inline void CodeGeneratorRequest::clear_has_parameter() { - _has_bits_[0] &= ~0x00000001u; + return _internal_has_parameter(); } inline void CodeGeneratorRequest::clear_parameter() { - parameter_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_parameter(); + parameter_.ClearToEmpty(); + _has_bits_[0] &= ~0x00000001u; } -inline const ::std::string& CodeGeneratorRequest::parameter() const { +inline const std::string& CodeGeneratorRequest::parameter() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.parameter) - return parameter_.GetNoArena(); + return _internal_parameter(); } -inline void CodeGeneratorRequest::set_parameter(const ::std::string& value) { - set_has_parameter(); - parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void CodeGeneratorRequest::set_parameter(ArgT0&& arg0, ArgT... args) { + _has_bits_[0] |= 0x00000001u; + parameter_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.parameter) } -#if LANG_CXX11 -inline void CodeGeneratorRequest::set_parameter(::std::string&& value) { - set_has_parameter(); - parameter_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorRequest.parameter) -} -#endif -inline void CodeGeneratorRequest::set_parameter(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_parameter(); - parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.parameter) -} -inline void CodeGeneratorRequest::set_parameter(const char* value, size_t size) { - set_has_parameter(); - parameter_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.parameter) -} -inline ::std::string* CodeGeneratorRequest::mutable_parameter() { - set_has_parameter(); +inline std::string* CodeGeneratorRequest::mutable_parameter() { + std::string* _s = _internal_mutable_parameter(); // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.parameter) - return parameter_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* CodeGeneratorRequest::release_parameter() { +inline const std::string& CodeGeneratorRequest::_internal_parameter() const { + return parameter_.Get(); +} +inline void CodeGeneratorRequest::_internal_set_parameter(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + parameter_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorRequest::_internal_mutable_parameter() { + _has_bits_[0] |= 0x00000001u; + return parameter_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorRequest::release_parameter() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter) - if (!has_parameter()) { - return NULL; + if (!_internal_has_parameter()) { + return nullptr; } - clear_has_parameter(); - return parameter_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000001u; + auto* p = parameter_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (parameter_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + parameter_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + return p; } -inline void CodeGeneratorRequest::set_allocated_parameter(::std::string* parameter) { - if (parameter != NULL) { - set_has_parameter(); +inline void CodeGeneratorRequest::set_allocated_parameter(std::string* parameter) { + if (parameter != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_parameter(); + _has_bits_[0] &= ~0x00000001u; } - parameter_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), parameter); + parameter_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), parameter, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (parameter_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + parameter_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.parameter) } // repeated .google.protobuf.FileDescriptorProto proto_file = 15; -inline int CodeGeneratorRequest::proto_file_size() const { +inline int CodeGeneratorRequest::_internal_proto_file_size() const { return proto_file_.size(); } -inline ::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::mutable_proto_file(int index) { +inline int CodeGeneratorRequest::proto_file_size() const { + return _internal_proto_file_size(); +} +inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* CodeGeneratorRequest::mutable_proto_file(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return proto_file_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto >* CodeGeneratorRequest::mutable_proto_file() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return &proto_file_; } -inline const ::google::protobuf::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const { - // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.proto_file) +inline const ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto& CodeGeneratorRequest::_internal_proto_file(int index) const { return proto_file_.Get(index); } -inline ::google::protobuf::FileDescriptorProto* CodeGeneratorRequest::add_proto_file() { - // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.proto_file) +inline const ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const { + // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.proto_file) + return _internal_proto_file(index); +} +inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* CodeGeneratorRequest::_internal_add_proto_file() { return proto_file_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >& +inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* CodeGeneratorRequest::add_proto_file() { + ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* _add = _internal_add_proto_file(); + // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.proto_file) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto >& CodeGeneratorRequest::proto_file() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return proto_file_; } // optional .google.protobuf.compiler.Version compiler_version = 3; +inline bool CodeGeneratorRequest::_internal_has_compiler_version() const { + bool value = (_has_bits_[0] & 0x00000002u) != 0; + PROTOBUF_ASSUME(!value || compiler_version_ != nullptr); + return value; +} inline bool CodeGeneratorRequest::has_compiler_version() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void CodeGeneratorRequest::set_has_compiler_version() { - _has_bits_[0] |= 0x00000002u; -} -inline void CodeGeneratorRequest::clear_has_compiler_version() { - _has_bits_[0] &= ~0x00000002u; + return _internal_has_compiler_version(); } inline void CodeGeneratorRequest::clear_compiler_version() { - if (compiler_version_ != NULL) compiler_version_->Clear(); - clear_has_compiler_version(); + if (compiler_version_ != nullptr) compiler_version_->Clear(); + _has_bits_[0] &= ~0x00000002u; } -inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::_internal_compiler_version() const { - return *compiler_version_; +inline const ::PROTOBUF_NAMESPACE_ID::compiler::Version& CodeGeneratorRequest::_internal_compiler_version() const { + const ::PROTOBUF_NAMESPACE_ID::compiler::Version* p = compiler_version_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::compiler::_Version_default_instance_); } -inline const ::google::protobuf::compiler::Version& CodeGeneratorRequest::compiler_version() const { - const ::google::protobuf::compiler::Version* p = compiler_version_; +inline const ::PROTOBUF_NAMESPACE_ID::compiler::Version& CodeGeneratorRequest::compiler_version() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) - return p != NULL ? *p : *reinterpret_cast( - &::google::protobuf::compiler::_Version_default_instance_); + return _internal_compiler_version(); } -inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::release_compiler_version() { - // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) - clear_has_compiler_version(); - ::google::protobuf::compiler::Version* temp = compiler_version_; - compiler_version_ = NULL; +inline void CodeGeneratorRequest::unsafe_arena_set_allocated_compiler_version( + ::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(compiler_version_); + } + compiler_version_ = compiler_version; + if (compiler_version) { + _has_bits_[0] |= 0x00000002u; + } else { + _has_bits_[0] &= ~0x00000002u; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) +} +inline ::PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::release_compiler_version() { + _has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::compiler::Version* temp = compiler_version_; + compiler_version_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE return temp; } -inline ::google::protobuf::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() { - set_has_compiler_version(); - if (compiler_version_ == NULL) { - auto* p = CreateMaybeMessage<::google::protobuf::compiler::Version>(GetArenaNoVirtual()); +inline ::PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::unsafe_arena_release_compiler_version() { + // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) + _has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::compiler::Version* temp = compiler_version_; + compiler_version_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::_internal_mutable_compiler_version() { + _has_bits_[0] |= 0x00000002u; + if (compiler_version_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::compiler::Version>(GetArenaForAllocation()); compiler_version_ = p; } - // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) return compiler_version_; } -inline void CodeGeneratorRequest::set_allocated_compiler_version(::google::protobuf::compiler::Version* compiler_version) { - ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); - if (message_arena == NULL) { +inline ::PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() { + ::PROTOBUF_NAMESPACE_ID::compiler::Version* _msg = _internal_mutable_compiler_version(); + // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) + return _msg; +} +inline void CodeGeneratorRequest::set_allocated_compiler_version(::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { delete compiler_version_; } if (compiler_version) { - ::google::protobuf::Arena* submessage_arena = NULL; + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper<::PROTOBUF_NAMESPACE_ID::compiler::Version>::GetOwningArena(compiler_version); if (message_arena != submessage_arena) { - compiler_version = ::google::protobuf::internal::GetOwnedMessage( + compiler_version = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, compiler_version, submessage_arena); } - set_has_compiler_version(); + _has_bits_[0] |= 0x00000002u; } else { - clear_has_compiler_version(); + _has_bits_[0] &= ~0x00000002u; } compiler_version_ = compiler_version; // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) @@ -1080,298 +1443,436 @@ inline void CodeGeneratorRequest::set_allocated_compiler_version(::google::proto // CodeGeneratorResponse_File // optional string name = 1; +inline bool CodeGeneratorResponse_File::_internal_has_name() const { + bool value = (_has_bits_[0] & 0x00000001u) != 0; + return value; +} inline bool CodeGeneratorResponse_File::has_name() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void CodeGeneratorResponse_File::set_has_name() { - _has_bits_[0] |= 0x00000001u; -} -inline void CodeGeneratorResponse_File::clear_has_name() { - _has_bits_[0] &= ~0x00000001u; + return _internal_has_name(); } inline void CodeGeneratorResponse_File::clear_name() { - name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_name(); + name_.ClearToEmpty(); + _has_bits_[0] &= ~0x00000001u; } -inline const ::std::string& CodeGeneratorResponse_File::name() const { +inline const std::string& CodeGeneratorResponse_File::name() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.name) - return name_.GetNoArena(); + return _internal_name(); } -inline void CodeGeneratorResponse_File::set_name(const ::std::string& value) { - set_has_name(); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void CodeGeneratorResponse_File::set_name(ArgT0&& arg0, ArgT... args) { + _has_bits_[0] |= 0x00000001u; + name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.name) } -#if LANG_CXX11 -inline void CodeGeneratorResponse_File::set_name(::std::string&& value) { - set_has_name(); - name_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.name) -} -#endif -inline void CodeGeneratorResponse_File::set_name(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_name(); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.name) -} -inline void CodeGeneratorResponse_File::set_name(const char* value, size_t size) { - set_has_name(); - name_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.name) -} -inline ::std::string* CodeGeneratorResponse_File::mutable_name() { - set_has_name(); +inline std::string* CodeGeneratorResponse_File::mutable_name() { + std::string* _s = _internal_mutable_name(); // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.name) - return name_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* CodeGeneratorResponse_File::release_name() { +inline const std::string& CodeGeneratorResponse_File::_internal_name() const { + return name_.Get(); +} +inline void CodeGeneratorResponse_File::_internal_set_name(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorResponse_File::_internal_mutable_name() { + _has_bits_[0] |= 0x00000001u; + return name_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorResponse_File::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name) - if (!has_name()) { - return NULL; + if (!_internal_has_name()) { + return nullptr; } - clear_has_name(); - return name_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000001u; + auto* p = name_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (name_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + return p; } -inline void CodeGeneratorResponse_File::set_allocated_name(::std::string* name) { - if (name != NULL) { - set_has_name(); +inline void CodeGeneratorResponse_File::set_allocated_name(std::string* name) { + if (name != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_name(); + _has_bits_[0] &= ~0x00000001u; } - name_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), name); + name_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), name, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (name_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + name_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.name) } // optional string insertion_point = 2; +inline bool CodeGeneratorResponse_File::_internal_has_insertion_point() const { + bool value = (_has_bits_[0] & 0x00000002u) != 0; + return value; +} inline bool CodeGeneratorResponse_File::has_insertion_point() const { - return (_has_bits_[0] & 0x00000002u) != 0; -} -inline void CodeGeneratorResponse_File::set_has_insertion_point() { - _has_bits_[0] |= 0x00000002u; -} -inline void CodeGeneratorResponse_File::clear_has_insertion_point() { - _has_bits_[0] &= ~0x00000002u; + return _internal_has_insertion_point(); } inline void CodeGeneratorResponse_File::clear_insertion_point() { - insertion_point_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_insertion_point(); + insertion_point_.ClearToEmpty(); + _has_bits_[0] &= ~0x00000002u; } -inline const ::std::string& CodeGeneratorResponse_File::insertion_point() const { +inline const std::string& CodeGeneratorResponse_File::insertion_point() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) - return insertion_point_.GetNoArena(); + return _internal_insertion_point(); } -inline void CodeGeneratorResponse_File::set_insertion_point(const ::std::string& value) { - set_has_insertion_point(); - insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void CodeGeneratorResponse_File::set_insertion_point(ArgT0&& arg0, ArgT... args) { + _has_bits_[0] |= 0x00000002u; + insertion_point_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) } -#if LANG_CXX11 -inline void CodeGeneratorResponse_File::set_insertion_point(::std::string&& value) { - set_has_insertion_point(); - insertion_point_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) -} -#endif -inline void CodeGeneratorResponse_File::set_insertion_point(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_insertion_point(); - insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) -} -inline void CodeGeneratorResponse_File::set_insertion_point(const char* value, size_t size) { - set_has_insertion_point(); - insertion_point_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) -} -inline ::std::string* CodeGeneratorResponse_File::mutable_insertion_point() { - set_has_insertion_point(); +inline std::string* CodeGeneratorResponse_File::mutable_insertion_point() { + std::string* _s = _internal_mutable_insertion_point(); // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) - return insertion_point_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* CodeGeneratorResponse_File::release_insertion_point() { +inline const std::string& CodeGeneratorResponse_File::_internal_insertion_point() const { + return insertion_point_.Get(); +} +inline void CodeGeneratorResponse_File::_internal_set_insertion_point(const std::string& value) { + _has_bits_[0] |= 0x00000002u; + insertion_point_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorResponse_File::_internal_mutable_insertion_point() { + _has_bits_[0] |= 0x00000002u; + return insertion_point_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorResponse_File::release_insertion_point() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) - if (!has_insertion_point()) { - return NULL; + if (!_internal_has_insertion_point()) { + return nullptr; } - clear_has_insertion_point(); - return insertion_point_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000002u; + auto* p = insertion_point_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (insertion_point_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + insertion_point_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + return p; } -inline void CodeGeneratorResponse_File::set_allocated_insertion_point(::std::string* insertion_point) { - if (insertion_point != NULL) { - set_has_insertion_point(); +inline void CodeGeneratorResponse_File::set_allocated_insertion_point(std::string* insertion_point) { + if (insertion_point != nullptr) { + _has_bits_[0] |= 0x00000002u; } else { - clear_has_insertion_point(); + _has_bits_[0] &= ~0x00000002u; } - insertion_point_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), insertion_point); + insertion_point_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), insertion_point, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (insertion_point_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + insertion_point_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) } // optional string content = 15; +inline bool CodeGeneratorResponse_File::_internal_has_content() const { + bool value = (_has_bits_[0] & 0x00000004u) != 0; + return value; +} inline bool CodeGeneratorResponse_File::has_content() const { - return (_has_bits_[0] & 0x00000004u) != 0; -} -inline void CodeGeneratorResponse_File::set_has_content() { - _has_bits_[0] |= 0x00000004u; -} -inline void CodeGeneratorResponse_File::clear_has_content() { - _has_bits_[0] &= ~0x00000004u; + return _internal_has_content(); } inline void CodeGeneratorResponse_File::clear_content() { - content_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_content(); + content_.ClearToEmpty(); + _has_bits_[0] &= ~0x00000004u; } -inline const ::std::string& CodeGeneratorResponse_File::content() const { +inline const std::string& CodeGeneratorResponse_File::content() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.content) - return content_.GetNoArena(); + return _internal_content(); } -inline void CodeGeneratorResponse_File::set_content(const ::std::string& value) { - set_has_content(); - content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void CodeGeneratorResponse_File::set_content(ArgT0&& arg0, ArgT... args) { + _has_bits_[0] |= 0x00000004u; + content_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.content) } -#if LANG_CXX11 -inline void CodeGeneratorResponse_File::set_content(::std::string&& value) { - set_has_content(); - content_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.File.content) -} -#endif -inline void CodeGeneratorResponse_File::set_content(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_content(); - content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.File.content) -} -inline void CodeGeneratorResponse_File::set_content(const char* value, size_t size) { - set_has_content(); - content_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.File.content) -} -inline ::std::string* CodeGeneratorResponse_File::mutable_content() { - set_has_content(); +inline std::string* CodeGeneratorResponse_File::mutable_content() { + std::string* _s = _internal_mutable_content(); // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.content) - return content_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* CodeGeneratorResponse_File::release_content() { +inline const std::string& CodeGeneratorResponse_File::_internal_content() const { + return content_.Get(); +} +inline void CodeGeneratorResponse_File::_internal_set_content(const std::string& value) { + _has_bits_[0] |= 0x00000004u; + content_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorResponse_File::_internal_mutable_content() { + _has_bits_[0] |= 0x00000004u; + return content_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorResponse_File::release_content() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content) - if (!has_content()) { - return NULL; + if (!_internal_has_content()) { + return nullptr; } - clear_has_content(); - return content_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000004u; + auto* p = content_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (content_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + content_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + return p; } -inline void CodeGeneratorResponse_File::set_allocated_content(::std::string* content) { - if (content != NULL) { - set_has_content(); +inline void CodeGeneratorResponse_File::set_allocated_content(std::string* content) { + if (content != nullptr) { + _has_bits_[0] |= 0x00000004u; } else { - clear_has_content(); + _has_bits_[0] &= ~0x00000004u; } - content_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), content); + content_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), content, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (content_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + content_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content) } +// optional .google.protobuf.GeneratedCodeInfo generated_code_info = 16; +inline bool CodeGeneratorResponse_File::_internal_has_generated_code_info() const { + bool value = (_has_bits_[0] & 0x00000008u) != 0; + PROTOBUF_ASSUME(!value || generated_code_info_ != nullptr); + return value; +} +inline bool CodeGeneratorResponse_File::has_generated_code_info() const { + return _internal_has_generated_code_info(); +} +inline const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo& CodeGeneratorResponse_File::_internal_generated_code_info() const { + const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* p = generated_code_info_; + return p != nullptr ? *p : reinterpret_cast( + ::PROTOBUF_NAMESPACE_ID::_GeneratedCodeInfo_default_instance_); +} +inline const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo& CodeGeneratorResponse_File::generated_code_info() const { + // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) + return _internal_generated_code_info(); +} +inline void CodeGeneratorResponse_File::unsafe_arena_set_allocated_generated_code_info( + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info) { + if (GetArenaForAllocation() == nullptr) { + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(generated_code_info_); + } + generated_code_info_ = generated_code_info; + if (generated_code_info) { + _has_bits_[0] |= 0x00000008u; + } else { + _has_bits_[0] &= ~0x00000008u; + } + // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) +} +inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* CodeGeneratorResponse_File::release_generated_code_info() { + _has_bits_[0] &= ~0x00000008u; + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* temp = generated_code_info_; + generated_code_info_ = nullptr; +#ifdef PROTOBUF_FORCE_COPY_IN_RELEASE + auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + if (GetArenaForAllocation() == nullptr) { delete old; } +#else // PROTOBUF_FORCE_COPY_IN_RELEASE + if (GetArenaForAllocation() != nullptr) { + temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); + } +#endif // !PROTOBUF_FORCE_COPY_IN_RELEASE + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* CodeGeneratorResponse_File::unsafe_arena_release_generated_code_info() { + // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) + _has_bits_[0] &= ~0x00000008u; + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* temp = generated_code_info_; + generated_code_info_ = nullptr; + return temp; +} +inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* CodeGeneratorResponse_File::_internal_mutable_generated_code_info() { + _has_bits_[0] |= 0x00000008u; + if (generated_code_info_ == nullptr) { + auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo>(GetArenaForAllocation()); + generated_code_info_ = p; + } + return generated_code_info_; +} +inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* CodeGeneratorResponse_File::mutable_generated_code_info() { + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* _msg = _internal_mutable_generated_code_info(); + // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) + return _msg; +} +inline void CodeGeneratorResponse_File::set_allocated_generated_code_info(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); + if (message_arena == nullptr) { + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(generated_code_info_); + } + if (generated_code_info) { + ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = + ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper< + ::PROTOBUF_NAMESPACE_ID::MessageLite>::GetOwningArena( + reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(generated_code_info)); + if (message_arena != submessage_arena) { + generated_code_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( + message_arena, generated_code_info, submessage_arena); + } + _has_bits_[0] |= 0x00000008u; + } else { + _has_bits_[0] &= ~0x00000008u; + } + generated_code_info_ = generated_code_info; + // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) +} + // ------------------------------------------------------------------- // CodeGeneratorResponse // optional string error = 1; +inline bool CodeGeneratorResponse::_internal_has_error() const { + bool value = (_has_bits_[0] & 0x00000001u) != 0; + return value; +} inline bool CodeGeneratorResponse::has_error() const { - return (_has_bits_[0] & 0x00000001u) != 0; -} -inline void CodeGeneratorResponse::set_has_error() { - _has_bits_[0] |= 0x00000001u; -} -inline void CodeGeneratorResponse::clear_has_error() { - _has_bits_[0] &= ~0x00000001u; + return _internal_has_error(); } inline void CodeGeneratorResponse::clear_error() { - error_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); - clear_has_error(); + error_.ClearToEmpty(); + _has_bits_[0] &= ~0x00000001u; } -inline const ::std::string& CodeGeneratorResponse::error() const { +inline const std::string& CodeGeneratorResponse::error() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.error) - return error_.GetNoArena(); + return _internal_error(); } -inline void CodeGeneratorResponse::set_error(const ::std::string& value) { - set_has_error(); - error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); +template +inline PROTOBUF_ALWAYS_INLINE +void CodeGeneratorResponse::set_error(ArgT0&& arg0, ArgT... args) { + _has_bits_[0] |= 0x00000001u; + error_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, static_cast(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.error) } -#if LANG_CXX11 -inline void CodeGeneratorResponse::set_error(::std::string&& value) { - set_has_error(); - error_.SetNoArena( - &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); - // @@protoc_insertion_point(field_set_rvalue:google.protobuf.compiler.CodeGeneratorResponse.error) -} -#endif -inline void CodeGeneratorResponse::set_error(const char* value) { - GOOGLE_DCHECK(value != NULL); - set_has_error(); - error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); - // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorResponse.error) -} -inline void CodeGeneratorResponse::set_error(const char* value, size_t size) { - set_has_error(); - error_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), - ::std::string(reinterpret_cast(value), size)); - // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorResponse.error) -} -inline ::std::string* CodeGeneratorResponse::mutable_error() { - set_has_error(); +inline std::string* CodeGeneratorResponse::mutable_error() { + std::string* _s = _internal_mutable_error(); // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.error) - return error_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + return _s; } -inline ::std::string* CodeGeneratorResponse::release_error() { +inline const std::string& CodeGeneratorResponse::_internal_error() const { + return error_.Get(); +} +inline void CodeGeneratorResponse::_internal_set_error(const std::string& value) { + _has_bits_[0] |= 0x00000001u; + error_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorResponse::_internal_mutable_error() { + _has_bits_[0] |= 0x00000001u; + return error_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArenaForAllocation()); +} +inline std::string* CodeGeneratorResponse::release_error() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error) - if (!has_error()) { - return NULL; + if (!_internal_has_error()) { + return nullptr; } - clear_has_error(); - return error_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); + _has_bits_[0] &= ~0x00000001u; + auto* p = error_.ReleaseNonDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (error_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + error_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + return p; } -inline void CodeGeneratorResponse::set_allocated_error(::std::string* error) { - if (error != NULL) { - set_has_error(); +inline void CodeGeneratorResponse::set_allocated_error(std::string* error) { + if (error != nullptr) { + _has_bits_[0] |= 0x00000001u; } else { - clear_has_error(); + _has_bits_[0] &= ~0x00000001u; } - error_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), error); + error_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), error, + GetArenaForAllocation()); +#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + if (error_.IsDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited())) { + error_.Set(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), "", GetArenaForAllocation()); + } +#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.error) } +// optional uint64 supported_features = 2; +inline bool CodeGeneratorResponse::_internal_has_supported_features() const { + bool value = (_has_bits_[0] & 0x00000002u) != 0; + return value; +} +inline bool CodeGeneratorResponse::has_supported_features() const { + return _internal_has_supported_features(); +} +inline void CodeGeneratorResponse::clear_supported_features() { + supported_features_ = uint64_t{0u}; + _has_bits_[0] &= ~0x00000002u; +} +inline uint64_t CodeGeneratorResponse::_internal_supported_features() const { + return supported_features_; +} +inline uint64_t CodeGeneratorResponse::supported_features() const { + // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.supported_features) + return _internal_supported_features(); +} +inline void CodeGeneratorResponse::_internal_set_supported_features(uint64_t value) { + _has_bits_[0] |= 0x00000002u; + supported_features_ = value; +} +inline void CodeGeneratorResponse::set_supported_features(uint64_t value) { + _internal_set_supported_features(value); + // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.supported_features) +} + // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; -inline int CodeGeneratorResponse::file_size() const { +inline int CodeGeneratorResponse::_internal_file_size() const { return file_.size(); } +inline int CodeGeneratorResponse::file_size() const { + return _internal_file_size(); +} inline void CodeGeneratorResponse::clear_file() { file_.Clear(); } -inline ::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::mutable_file(int index) { +inline ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::mutable_file(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.file) return file_.Mutable(index); } -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >* +inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >* CodeGeneratorResponse::mutable_file() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorResponse.file) return &file_; } -inline const ::google::protobuf::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::file(int index) const { - // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.file) +inline const ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::_internal_file(int index) const { return file_.Get(index); } -inline ::google::protobuf::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::add_file() { - // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorResponse.file) +inline const ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::file(int index) const { + // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.file) + return _internal_file(index); +} +inline ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::_internal_add_file() { return file_.Add(); } -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::compiler::CodeGeneratorResponse_File >& +inline ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::add_file() { + ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* _add = _internal_add_file(); + // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorResponse.file) + return _add; +} +inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >& CodeGeneratorResponse::file() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorResponse.file) return file_; @@ -1390,9 +1891,19 @@ CodeGeneratorResponse::file() const { // @@protoc_insertion_point(namespace_scope) } // namespace compiler -} // namespace protobuf -} // namespace google +PROTOBUF_NAMESPACE_CLOSE + +PROTOBUF_NAMESPACE_OPEN + +template <> struct is_proto_enum< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_Feature> : ::std::true_type {}; +template <> +inline const EnumDescriptor* GetEnumDescriptor< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_Feature>() { + return ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_Feature_descriptor(); +} + +PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) -#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto +#include +#endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_google_2fprotobuf_2fcompiler_2fplugin_2eproto diff --git a/windows/include/google/protobuf/compiler/plugin.proto b/windows/include/google/protobuf/compiler/plugin.proto index 5b5574529..9242aacc5 100644 --- a/windows/include/google/protobuf/compiler/plugin.proto +++ b/windows/include/google/protobuf/compiler/plugin.proto @@ -45,11 +45,12 @@ // flag "--${NAME}_out" is passed to protoc. syntax = "proto2"; + package google.protobuf.compiler; option java_package = "com.google.protobuf.compiler"; option java_outer_classname = "PluginProtos"; -option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go"; +option go_package = "google.golang.org/protobuf/types/pluginpb"; import "google/protobuf/descriptor.proto"; @@ -106,6 +107,16 @@ message CodeGeneratorResponse { // exiting with a non-zero status code. optional string error = 1; + // A bitmask of supported features that the code generator supports. + // This is a bitwise "or" of values from the Feature enum. + optional uint64 supported_features = 2; + + // Sync with code_generator.h. + enum Feature { + FEATURE_NONE = 0; + FEATURE_PROTO3_OPTIONAL = 1; + } + // Represents a single generated file. message File { // The file name, relative to the output directory. The name must not @@ -162,6 +173,11 @@ message CodeGeneratorResponse { // The file contents. optional string content = 15; + + // Information describing the file content being inserted. If an insertion + // point is used, this information will be appropriately offset and inserted + // into the code generation metadata for the generated files. + optional GeneratedCodeInfo generated_code_info = 16; } repeated File file = 15; } diff --git a/windows/include/google/protobuf/compiler/python/python_generator.cc b/windows/include/google/protobuf/compiler/python/python_generator.cc deleted file mode 100644 index 01f28b372..000000000 --- a/windows/include/google/protobuf/compiler/python/python_generator.cc +++ /dev/null @@ -1,1421 +0,0 @@ -// 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. - -//#PY25 compatible generated code for GAE. -// Copyright 2007 Google Inc. All Rights Reserved. -// Author: robinson@google.com (Will Robinson) -// -// This module outputs pure-Python protocol message classes that will -// largely be constructed at runtime via the metaclass in reflection.py. -// In other words, our job is basically to output a Python equivalent -// of the C++ *Descriptor objects, and fix up all circular references -// within these objects. -// -// Note that the runtime performance of protocol message classes created in -// this way is expected to be lousy. The plan is to create an alternate -// generator that outputs a Python/C extension module that lets -// performance-minded Python code leverage the fast C++ implementation -// directly. - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace compiler { -namespace python { - -namespace { - -// Reimplemented here because we can't bring in -// absl/strings/string_view_utils.h because it needs C++11. -bool StrStartsWith(StringPiece sp, StringPiece x) { - return sp.size() >= x.size() && sp.substr(0, x.size()) == x; -} -bool StrEndsWith(StringPiece sp, StringPiece x) { - return sp.size() >= x.size() && sp.substr(sp.size() - x.size()) == x; -} - -// Returns a copy of |filename| with any trailing ".protodevel" or ".proto -// suffix stripped. -// TODO(robinson): Unify with copy in compiler/cpp/internal/helpers.cc. -string StripProto(const string& filename) { - const char* suffix = - StrEndsWith(filename, ".protodevel") ? ".protodevel" : ".proto"; - return StripSuffixString(filename, suffix); -} - - -// Returns the Python module name expected for a given .proto filename. -string ModuleName(const string& filename) { - string basename = StripProto(filename); - ReplaceCharacters(&basename, "-", '_'); - ReplaceCharacters(&basename, "/", '.'); - return basename + "_pb2"; -} - - -// Returns the alias we assign to the module of the given .proto filename -// when importing. See testPackageInitializationImport in -// google/protobuf/python/reflection_test.py -// to see why we need the alias. -string ModuleAlias(const string& filename) { - string module_name = ModuleName(filename); - // We can't have dots in the module name, so we replace each with _dot_. - // But that could lead to a collision between a.b and a_dot_b, so we also - // duplicate each underscore. - GlobalReplaceSubstring("_", "__", &module_name); - GlobalReplaceSubstring(".", "_dot_", &module_name); - return module_name; -} - -// Keywords reserved by the Python language. -const char* const kKeywords[] = { - "False", "None", "True", "and", "as", "assert", "break", - "class", "continue", "def", "del", "elif", "else", "except", - "finally", "for", "from", "global", "if", "import", "in", - "is", "lambda", "nonlocal", "not", "or", "pass", "raise", - "return", "try", "while", "with", "yield", -}; -const char* const* kKeywordsEnd = - kKeywords + (sizeof(kKeywords) / sizeof(kKeywords[0])); - -bool ContainsPythonKeyword(const string& module_name) { - std::vector tokens = Split(module_name, "."); - for (int i = 0; i < tokens.size(); ++i) { - if (std::find(kKeywords, kKeywordsEnd, tokens[i]) != kKeywordsEnd) { - return true; - } - } - return false; -} - - -// Returns the name of all containing types for descriptor, -// in order from outermost to innermost, followed by descriptor's -// own name. Each name is separated by |separator|. -template -string NamePrefixedWithNestedTypes(const DescriptorT& descriptor, - const string& separator) { - string name = descriptor.name(); - for (const Descriptor* current = descriptor.containing_type(); - current != NULL; current = current->containing_type()) { - name = current->name() + separator + name; - } - return name; -} - - -// Name of the class attribute where we store the Python -// descriptor.Descriptor instance for the generated class. -// Must stay consistent with the _DESCRIPTOR_KEY constant -// in proto2/public/reflection.py. -const char kDescriptorKey[] = "DESCRIPTOR"; - - -// Does the file have top-level enums? -inline bool HasTopLevelEnums(const FileDescriptor *file) { - return file->enum_type_count() > 0; -} - - -// Should we generate generic services for this file? -inline bool HasGenericServices(const FileDescriptor *file) { - return file->service_count() > 0 && - file->options().py_generic_services(); -} - - -// Prints the common boilerplate needed at the top of every .py -// file output by this generator. -void PrintTopBoilerplate( - io::Printer* printer, const FileDescriptor* file, bool descriptor_proto) { - // TODO(robinson): Allow parameterization of Python version? - printer->Print( - "# Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "# source: $filename$\n" - "\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))" //##PY25 - "\n", - "filename", file->name()); - if (HasTopLevelEnums(file)) { - printer->Print( - "from google.protobuf.internal import enum_type_wrapper\n"); - } - printer->Print( - "from google.protobuf import descriptor as _descriptor\n" - "from google.protobuf import message as _message\n" - "from google.protobuf import reflection as _reflection\n" - "from google.protobuf import symbol_database as " - "_symbol_database\n"); - if (HasGenericServices(file)) { - printer->Print( - "from google.protobuf import service as _service\n" - "from google.protobuf import service_reflection\n"); - } - - printer->Print( - "# @@protoc_insertion_point(imports)\n\n" - "_sym_db = _symbol_database.Default()\n"); - printer->Print("\n\n"); -} - - -// Returns a Python literal giving the default value for a field. -// If the field specifies no explicit default value, we'll return -// the default default value for the field type (zero for numbers, -// empty string for strings, empty list for repeated fields, and -// None for non-repeated, composite fields). -// -// TODO(robinson): Unify with code from -// //compiler/cpp/internal/primitive_field.cc -// //compiler/cpp/internal/enum_field.cc -// //compiler/cpp/internal/string_field.cc -string StringifyDefaultValue(const FieldDescriptor& field) { - if (field.is_repeated()) { - return "[]"; - } - - switch (field.cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - return SimpleItoa(field.default_value_int32()); - case FieldDescriptor::CPPTYPE_UINT32: - return SimpleItoa(field.default_value_uint32()); - case FieldDescriptor::CPPTYPE_INT64: - return SimpleItoa(field.default_value_int64()); - case FieldDescriptor::CPPTYPE_UINT64: - return SimpleItoa(field.default_value_uint64()); - case FieldDescriptor::CPPTYPE_DOUBLE: { - double value = field.default_value_double(); - if (value == std::numeric_limits::infinity()) { - // Python pre-2.6 on Windows does not parse "inf" correctly. However, - // a numeric literal that is too big for a double will become infinity. - return "1e10000"; - } else if (value == -std::numeric_limits::infinity()) { - // See above. - return "-1e10000"; - } else if (value != value) { - // infinity * 0 = nan - return "(1e10000 * 0)"; - } else { - return "float(" + SimpleDtoa(value) + ")"; - } - } - case FieldDescriptor::CPPTYPE_FLOAT: { - float value = field.default_value_float(); - if (value == std::numeric_limits::infinity()) { - // Python pre-2.6 on Windows does not parse "inf" correctly. However, - // a numeric literal that is too big for a double will become infinity. - return "1e10000"; - } else if (value == -std::numeric_limits::infinity()) { - // See above. - return "-1e10000"; - } else if (value != value) { - // infinity - infinity = nan - return "(1e10000 * 0)"; - } else { - return "float(" + SimpleFtoa(value) + ")"; - } - } - case FieldDescriptor::CPPTYPE_BOOL: - return field.default_value_bool() ? "True" : "False"; - case FieldDescriptor::CPPTYPE_ENUM: - return SimpleItoa(field.default_value_enum()->number()); - case FieldDescriptor::CPPTYPE_STRING: -//##!PY25 return "b\"" + CEscape(field.default_value_string()) + -//##!PY25 (field.type() != FieldDescriptor::TYPE_STRING ? "\"" : -//##!PY25 "\".decode('utf-8')"); - return "_b(\"" + CEscape(field.default_value_string()) + //##PY25 - (field.type() != FieldDescriptor::TYPE_STRING ? "\")" : //##PY25 - "\").decode('utf-8')"); //##PY25 - case FieldDescriptor::CPPTYPE_MESSAGE: - return "None"; - } - // (We could add a default case above but then we wouldn't get the nice - // compiler warning when a new type is added.) - GOOGLE_LOG(FATAL) << "Not reached."; - return ""; -} - -string StringifySyntax(FileDescriptor::Syntax syntax) { - switch (syntax) { - case FileDescriptor::SYNTAX_PROTO2: - return "proto2"; - case FileDescriptor::SYNTAX_PROTO3: - return "proto3"; - case FileDescriptor::SYNTAX_UNKNOWN: - default: - GOOGLE_LOG(FATAL) << "Unsupported syntax; this generator only supports proto2 " - "and proto3 syntax."; - return ""; - } -} - - -} // namespace - - -Generator::Generator() : file_(NULL) { -} - -Generator::~Generator() { -} - -bool Generator::Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - - // Completely serialize all Generate() calls on this instance. The - // thread-safety constraints of the CodeGenerator interface aren't clear so - // just be as conservative as possible. It's easier to relax this later if - // we need to, but I doubt it will be an issue. - // TODO(kenton): The proper thing to do would be to allocate any state on - // the stack and use that, so that the Generator class itself does not need - // to have any mutable members. Then it is implicitly thread-safe. - MutexLock lock(&mutex_); - file_ = file; - string module_name = ModuleName(file->name()); - string filename = module_name; - ReplaceCharacters(&filename, ".", '/'); - filename += ".py"; - - FileDescriptorProto fdp; - file_->CopyTo(&fdp); - fdp.SerializeToString(&file_descriptor_serialized_); - - - std::unique_ptr output(context->Open(filename)); - GOOGLE_CHECK(output.get()); - io::Printer printer(output.get(), '$'); - printer_ = &printer; - - PrintTopBoilerplate(printer_, file_, GeneratingDescriptorProto()); - PrintImports(); - PrintFileDescriptor(); - PrintTopLevelEnums(); - PrintTopLevelExtensions(); - PrintAllNestedEnumsInFile(); - PrintMessageDescriptors(); - FixForeignFieldsInDescriptors(); - PrintMessages(); - // We have to fix up the extensions after the message classes themselves, - // since they need to call static RegisterExtension() methods on these - // classes. - FixForeignFieldsInExtensions(); - // Descriptor options may have custom extensions. These custom options - // can only be successfully parsed after we register corresponding - // extensions. Therefore we parse all options again here to recognize - // custom options that may be unknown when we define the descriptors. - // This does not apply to services because they are not used by extensions. - FixAllDescriptorOptions(); - PrintServiceDescriptors(); - if (HasGenericServices(file)) { - PrintServices(); - } - - printer.Print( - "# @@protoc_insertion_point(module_scope)\n"); - - return !printer.failed(); -} - -// Prints Python imports for all modules imported by |file|. -void Generator::PrintImports() const { - for (int i = 0; i < file_->dependency_count(); ++i) { - const string& filename = file_->dependency(i)->name(); - - string module_name = ModuleName(filename); - string module_alias = ModuleAlias(filename); - if (ContainsPythonKeyword(module_name)) { - // If the module path contains a Python keyword, we have to quote the - // module name and import it using importlib. Otherwise the usual kind of - // import statement would result in a syntax error from the presence of - // the keyword. - printer_->Print("import importlib\n"); - printer_->Print("$alias$ = importlib.import_module('$name$')\n", "alias", - module_alias, "name", module_name); - } else { - int last_dot_pos = module_name.rfind('.'); - string import_statement; - if (last_dot_pos == string::npos) { - // NOTE(petya): this is not tested as it would require a protocol buffer - // outside of any package, and I don't think that is easily achievable. - import_statement = "import " + module_name; - } else { - import_statement = "from " + module_name.substr(0, last_dot_pos) + - " import " + module_name.substr(last_dot_pos + 1); - } - printer_->Print("$statement$ as $alias$\n", "statement", import_statement, - "alias", module_alias); - } - - CopyPublicDependenciesAliases(module_alias, file_->dependency(i)); - } - printer_->Print("\n"); - - // Print public imports. - for (int i = 0; i < file_->public_dependency_count(); ++i) { - string module_name = ModuleName(file_->public_dependency(i)->name()); - printer_->Print("from $module$ import *\n", "module", module_name); - } - printer_->Print("\n"); -} - -// Prints the single file descriptor for this file. -void Generator::PrintFileDescriptor() const { - std::map m; - m["descriptor_name"] = kDescriptorKey; - m["name"] = file_->name(); - m["package"] = file_->package(); - m["syntax"] = StringifySyntax(file_->syntax()); - m["options"] = OptionsValue(file_->options().SerializeAsString()); - const char file_descriptor_template[] = - "$descriptor_name$ = _descriptor.FileDescriptor(\n" - " name='$name$',\n" - " package='$package$',\n" - " syntax='$syntax$',\n" - " serialized_options=$options$,\n"; - printer_->Print(m, file_descriptor_template); - printer_->Indent(); - printer_->Print( -//##!PY25 "serialized_pb=b'$value$'\n", - "serialized_pb=_b('$value$')\n", //##PY25 - "value", strings::CHexEscape(file_descriptor_serialized_)); - if (file_->dependency_count() != 0) { - printer_->Print(",\ndependencies=["); - for (int i = 0; i < file_->dependency_count(); ++i) { - string module_alias = ModuleAlias(file_->dependency(i)->name()); - printer_->Print("$module_alias$.DESCRIPTOR,", "module_alias", - module_alias); - } - printer_->Print("]"); - } - if (file_->public_dependency_count() > 0) { - printer_->Print(",\npublic_dependencies=["); - for (int i = 0; i < file_->public_dependency_count(); ++i) { - string module_alias = ModuleAlias(file_->public_dependency(i)->name()); - printer_->Print("$module_alias$.DESCRIPTOR,", "module_alias", - module_alias); - } - printer_->Print("]"); - } - - // TODO(falk): Also print options and fix the message_type, enum_type, - // service and extension later in the generation. - - printer_->Outdent(); - printer_->Print(")\n"); - printer_->Print("\n"); -} - -// Prints descriptors and module-level constants for all top-level -// enums defined in |file|. -void Generator::PrintTopLevelEnums() const { - std::vector > top_level_enum_values; - for (int i = 0; i < file_->enum_type_count(); ++i) { - const EnumDescriptor& enum_descriptor = *file_->enum_type(i); - PrintEnum(enum_descriptor); - printer_->Print("$name$ = " - "enum_type_wrapper.EnumTypeWrapper($descriptor_name$)", - "name", enum_descriptor.name(), - "descriptor_name", - ModuleLevelDescriptorName(enum_descriptor)); - printer_->Print("\n"); - - for (int j = 0; j < enum_descriptor.value_count(); ++j) { - const EnumValueDescriptor& value_descriptor = *enum_descriptor.value(j); - top_level_enum_values.push_back( - std::make_pair(value_descriptor.name(), value_descriptor.number())); - } - } - - for (int i = 0; i < top_level_enum_values.size(); ++i) { - printer_->Print("$name$ = $value$\n", - "name", top_level_enum_values[i].first, - "value", SimpleItoa(top_level_enum_values[i].second)); - } - printer_->Print("\n"); -} - -// Prints all enums contained in all message types in |file|. -void Generator::PrintAllNestedEnumsInFile() const { - for (int i = 0; i < file_->message_type_count(); ++i) { - PrintNestedEnums(*file_->message_type(i)); - } -} - -// Prints a Python statement assigning the appropriate module-level -// enum name to a Python EnumDescriptor object equivalent to -// enum_descriptor. -void Generator::PrintEnum(const EnumDescriptor& enum_descriptor) const { - std::map m; - string module_level_descriptor_name = - ModuleLevelDescriptorName(enum_descriptor); - m["descriptor_name"] = module_level_descriptor_name; - m["name"] = enum_descriptor.name(); - m["full_name"] = enum_descriptor.full_name(); - m["file"] = kDescriptorKey; - const char enum_descriptor_template[] = - "$descriptor_name$ = _descriptor.EnumDescriptor(\n" - " name='$name$',\n" - " full_name='$full_name$',\n" - " filename=None,\n" - " file=$file$,\n" - " values=[\n"; - string options_string; - enum_descriptor.options().SerializeToString(&options_string); - printer_->Print(m, enum_descriptor_template); - printer_->Indent(); - printer_->Indent(); - for (int i = 0; i < enum_descriptor.value_count(); ++i) { - PrintEnumValueDescriptor(*enum_descriptor.value(i)); - printer_->Print(",\n"); - } - printer_->Outdent(); - printer_->Print("],\n"); - printer_->Print("containing_type=None,\n"); - printer_->Print("serialized_options=$options_value$,\n", - "options_value", - OptionsValue(options_string)); - EnumDescriptorProto edp; - PrintSerializedPbInterval(enum_descriptor, edp); - printer_->Outdent(); - printer_->Print(")\n"); - printer_->Print("_sym_db.RegisterEnumDescriptor($name$)\n", "name", - module_level_descriptor_name); - printer_->Print("\n"); -} - -// Recursively prints enums in nested types within descriptor, then -// prints enums contained at the top level in descriptor. -void Generator::PrintNestedEnums(const Descriptor& descriptor) const { - for (int i = 0; i < descriptor.nested_type_count(); ++i) { - PrintNestedEnums(*descriptor.nested_type(i)); - } - - for (int i = 0; i < descriptor.enum_type_count(); ++i) { - PrintEnum(*descriptor.enum_type(i)); - } -} - -void Generator::PrintTopLevelExtensions() const { - const bool is_extension = true; - for (int i = 0; i < file_->extension_count(); ++i) { - const FieldDescriptor& extension_field = *file_->extension(i); - string constant_name = extension_field.name() + "_FIELD_NUMBER"; - UpperString(&constant_name); - printer_->Print("$constant_name$ = $number$\n", - "constant_name", constant_name, - "number", SimpleItoa(extension_field.number())); - printer_->Print("$name$ = ", "name", extension_field.name()); - PrintFieldDescriptor(extension_field, is_extension); - printer_->Print("\n"); - } - printer_->Print("\n"); -} - -// Prints Python equivalents of all Descriptors in |file|. -void Generator::PrintMessageDescriptors() const { - for (int i = 0; i < file_->message_type_count(); ++i) { - PrintDescriptor(*file_->message_type(i)); - printer_->Print("\n"); - } -} - -void Generator::PrintServiceDescriptors() const { - for (int i = 0; i < file_->service_count(); ++i) { - PrintServiceDescriptor(*file_->service(i)); - AddServiceToFileDescriptor(*file_->service(i)); - printer_->Print("\n"); - } -} - -void Generator::PrintServices() const { - for (int i = 0; i < file_->service_count(); ++i) { - PrintServiceClass(*file_->service(i)); - PrintServiceStub(*file_->service(i)); - printer_->Print("\n"); - } -} - -void Generator::PrintServiceDescriptor( - const ServiceDescriptor& descriptor) const { - printer_->Print("\n"); - string service_name = ModuleLevelServiceDescriptorName(descriptor); - string options_string; - descriptor.options().SerializeToString(&options_string); - - printer_->Print( - "$service_name$ = _descriptor.ServiceDescriptor(\n", - "service_name", service_name); - printer_->Indent(); - std::map m; - m["name"] = descriptor.name(); - m["full_name"] = descriptor.full_name(); - m["file"] = kDescriptorKey; - m["index"] = SimpleItoa(descriptor.index()); - m["options_value"] = OptionsValue(options_string); - const char required_function_arguments[] = - "name='$name$',\n" - "full_name='$full_name$',\n" - "file=$file$,\n" - "index=$index$,\n" - "serialized_options=$options_value$,\n"; - printer_->Print(m, required_function_arguments); - - ServiceDescriptorProto sdp; - PrintSerializedPbInterval(descriptor, sdp); - - printer_->Print("methods=[\n"); - for (int i = 0; i < descriptor.method_count(); ++i) { - const MethodDescriptor* method = descriptor.method(i); - method->options().SerializeToString(&options_string); - - m.clear(); - m["name"] = method->name(); - m["full_name"] = method->full_name(); - m["index"] = SimpleItoa(method->index()); - m["serialized_options"] = CEscape(options_string); - m["input_type"] = ModuleLevelDescriptorName(*(method->input_type())); - m["output_type"] = ModuleLevelDescriptorName(*(method->output_type())); - m["options_value"] = OptionsValue(options_string); - printer_->Print("_descriptor.MethodDescriptor(\n"); - printer_->Indent(); - printer_->Print( - m, - "name='$name$',\n" - "full_name='$full_name$',\n" - "index=$index$,\n" - "containing_service=None,\n" - "input_type=$input_type$,\n" - "output_type=$output_type$,\n" - "serialized_options=$options_value$,\n"); - printer_->Outdent(); - printer_->Print("),\n"); - } - - printer_->Outdent(); - printer_->Print("])\n"); - printer_->Print("_sym_db.RegisterServiceDescriptor($name$)\n", "name", - service_name); - printer_->Print("\n"); -} - - -void Generator::PrintDescriptorKeyAndModuleName( - const ServiceDescriptor& descriptor) const { - printer_->Print( - "$descriptor_key$ = $descriptor_name$,\n", - "descriptor_key", kDescriptorKey, - "descriptor_name", ModuleLevelServiceDescriptorName(descriptor)); - printer_->Print( - "__module__ = '$module_name$'\n", - "module_name", ModuleName(file_->name())); -} - -void Generator::PrintServiceClass(const ServiceDescriptor& descriptor) const { - // Print the service. - printer_->Print("$class_name$ = service_reflection.GeneratedServiceType(" - "'$class_name$', (_service.Service,), dict(\n", - "class_name", descriptor.name()); - printer_->Indent(); - Generator::PrintDescriptorKeyAndModuleName(descriptor); - printer_->Print("))\n\n"); - printer_->Outdent(); -} - -void Generator::PrintServiceStub(const ServiceDescriptor& descriptor) const { - // Print the service stub. - printer_->Print("$class_name$_Stub = " - "service_reflection.GeneratedServiceStubType(" - "'$class_name$_Stub', ($class_name$,), dict(\n", - "class_name", descriptor.name()); - printer_->Indent(); - Generator::PrintDescriptorKeyAndModuleName(descriptor); - printer_->Print("))\n\n"); - printer_->Outdent(); -} - -// Prints statement assigning ModuleLevelDescriptorName(message_descriptor) -// to a Python Descriptor object for message_descriptor. -// -// Mutually recursive with PrintNestedDescriptors(). -void Generator::PrintDescriptor(const Descriptor& message_descriptor) const { - PrintNestedDescriptors(message_descriptor); - - printer_->Print("\n"); - printer_->Print("$descriptor_name$ = _descriptor.Descriptor(\n", - "descriptor_name", - ModuleLevelDescriptorName(message_descriptor)); - printer_->Indent(); - std::map m; - m["name"] = message_descriptor.name(); - m["full_name"] = message_descriptor.full_name(); - m["file"] = kDescriptorKey; - const char required_function_arguments[] = - "name='$name$',\n" - "full_name='$full_name$',\n" - "filename=None,\n" - "file=$file$,\n" - "containing_type=None,\n"; - printer_->Print(m, required_function_arguments); - PrintFieldsInDescriptor(message_descriptor); - PrintExtensionsInDescriptor(message_descriptor); - - // Nested types - printer_->Print("nested_types=["); - for (int i = 0; i < message_descriptor.nested_type_count(); ++i) { - const string nested_name = ModuleLevelDescriptorName( - *message_descriptor.nested_type(i)); - printer_->Print("$name$, ", "name", nested_name); - } - printer_->Print("],\n"); - - // Enum types - printer_->Print("enum_types=[\n"); - printer_->Indent(); - for (int i = 0; i < message_descriptor.enum_type_count(); ++i) { - const string descriptor_name = ModuleLevelDescriptorName( - *message_descriptor.enum_type(i)); - printer_->Print(descriptor_name.c_str()); - printer_->Print(",\n"); - } - printer_->Outdent(); - printer_->Print("],\n"); - string options_string; - message_descriptor.options().SerializeToString(&options_string); - printer_->Print( - "serialized_options=$options_value$,\n" - "is_extendable=$extendable$,\n" - "syntax='$syntax$'", - "options_value", OptionsValue(options_string), - "extendable", message_descriptor.extension_range_count() > 0 ? - "True" : "False", - "syntax", StringifySyntax(message_descriptor.file()->syntax())); - printer_->Print(",\n"); - - // Extension ranges - printer_->Print("extension_ranges=["); - for (int i = 0; i < message_descriptor.extension_range_count(); ++i) { - const Descriptor::ExtensionRange* range = - message_descriptor.extension_range(i); - printer_->Print("($start$, $end$), ", - "start", SimpleItoa(range->start), - "end", SimpleItoa(range->end)); - } - printer_->Print("],\n"); - printer_->Print("oneofs=[\n"); - printer_->Indent(); - for (int i = 0; i < message_descriptor.oneof_decl_count(); ++i) { - const OneofDescriptor* desc = message_descriptor.oneof_decl(i); - std::map m; - m["name"] = desc->name(); - m["full_name"] = desc->full_name(); - m["index"] = SimpleItoa(desc->index()); - string options_string = - OptionsValue(desc->options().SerializeAsString()); - if (options_string == "None") { - m["serialized_options"] = ""; - } else { - m["serialized_options"] = ", serialized_options=" + options_string; - } - printer_->Print( - m, - "_descriptor.OneofDescriptor(\n" - " name='$name$', full_name='$full_name$',\n" - " index=$index$, containing_type=None, " - "fields=[]$serialized_options$),\n"); - } - printer_->Outdent(); - printer_->Print("],\n"); - // Serialization of proto - DescriptorProto edp; - PrintSerializedPbInterval(message_descriptor, edp); - - printer_->Outdent(); - printer_->Print(")\n"); -} - -// Prints Python Descriptor objects for all nested types contained in -// message_descriptor. -// -// Mutually recursive with PrintDescriptor(). -void Generator::PrintNestedDescriptors( - const Descriptor& containing_descriptor) const { - for (int i = 0; i < containing_descriptor.nested_type_count(); ++i) { - PrintDescriptor(*containing_descriptor.nested_type(i)); - } -} - -// Prints all messages in |file|. -void Generator::PrintMessages() const { - for (int i = 0; i < file_->message_type_count(); ++i) { - std::vector to_register; - PrintMessage(*file_->message_type(i), "", &to_register); - for (int j = 0; j < to_register.size(); ++j) { - printer_->Print("_sym_db.RegisterMessage($name$)\n", "name", - to_register[j]); - } - printer_->Print("\n"); - } -} - -// Prints a Python class for the given message descriptor. We defer to the -// metaclass to do almost all of the work of actually creating a useful class. -// The purpose of this function and its many helper functions above is merely -// to output a Python version of the descriptors, which the metaclass in -// reflection.py will use to construct the meat of the class itself. -// -// Mutually recursive with PrintNestedMessages(). -// Collect nested message names to_register for the symbol_database. -void Generator::PrintMessage(const Descriptor& message_descriptor, - const string& prefix, - std::vector* to_register) const { - string qualified_name(prefix + message_descriptor.name()); - to_register->push_back(qualified_name); - printer_->Print( - "$name$ = _reflection.GeneratedProtocolMessageType('$name$', " - "(_message.Message,), dict(\n", - "name", message_descriptor.name()); - printer_->Indent(); - - PrintNestedMessages(message_descriptor, qualified_name + ".", to_register); - std::map m; - m["descriptor_key"] = kDescriptorKey; - m["descriptor_name"] = ModuleLevelDescriptorName(message_descriptor); - printer_->Print(m, "$descriptor_key$ = $descriptor_name$,\n"); - printer_->Print("__module__ = '$module_name$'\n", - "module_name", ModuleName(file_->name())); - printer_->Print("# @@protoc_insertion_point(class_scope:$full_name$)\n", - "full_name", message_descriptor.full_name()); - printer_->Print("))\n"); - printer_->Outdent(); -} - -// Prints all nested messages within |containing_descriptor|. -// Mutually recursive with PrintMessage(). -void Generator::PrintNestedMessages(const Descriptor& containing_descriptor, - const string& prefix, - std::vector* to_register) const { - for (int i = 0; i < containing_descriptor.nested_type_count(); ++i) { - printer_->Print("\n"); - PrintMessage(*containing_descriptor.nested_type(i), prefix, to_register); - printer_->Print(",\n"); - } -} - -// Recursively fixes foreign fields in all nested types in |descriptor|, then -// sets the message_type and enum_type of all message and enum fields to point -// to their respective descriptors. -// Args: -// descriptor: descriptor to print fields for. -// containing_descriptor: if descriptor is a nested type, this is its -// containing type, or NULL if this is a root/top-level type. -void Generator::FixForeignFieldsInDescriptor( - const Descriptor& descriptor, - const Descriptor* containing_descriptor) const { - for (int i = 0; i < descriptor.nested_type_count(); ++i) { - FixForeignFieldsInDescriptor(*descriptor.nested_type(i), &descriptor); - } - - for (int i = 0; i < descriptor.field_count(); ++i) { - const FieldDescriptor& field_descriptor = *descriptor.field(i); - FixForeignFieldsInField(&descriptor, field_descriptor, "fields_by_name"); - } - - FixContainingTypeInDescriptor(descriptor, containing_descriptor); - for (int i = 0; i < descriptor.enum_type_count(); ++i) { - const EnumDescriptor& enum_descriptor = *descriptor.enum_type(i); - FixContainingTypeInDescriptor(enum_descriptor, &descriptor); - } - for (int i = 0; i < descriptor.oneof_decl_count(); ++i) { - std::map m; - const OneofDescriptor* oneof = descriptor.oneof_decl(i); - m["descriptor_name"] = ModuleLevelDescriptorName(descriptor); - m["oneof_name"] = oneof->name(); - for (int j = 0; j < oneof->field_count(); ++j) { - m["field_name"] = oneof->field(j)->name(); - printer_->Print( - m, - "$descriptor_name$.oneofs_by_name['$oneof_name$'].fields.append(\n" - " $descriptor_name$.fields_by_name['$field_name$'])\n"); - printer_->Print( - m, - "$descriptor_name$.fields_by_name['$field_name$'].containing_oneof = " - "$descriptor_name$.oneofs_by_name['$oneof_name$']\n"); - } - } -} - -void Generator::AddMessageToFileDescriptor(const Descriptor& descriptor) const { - std::map m; - m["descriptor_name"] = kDescriptorKey; - m["message_name"] = descriptor.name(); - m["message_descriptor_name"] = ModuleLevelDescriptorName(descriptor); - const char file_descriptor_template[] = - "$descriptor_name$.message_types_by_name['$message_name$'] = " - "$message_descriptor_name$\n"; - printer_->Print(m, file_descriptor_template); -} - -void Generator::AddServiceToFileDescriptor( - const ServiceDescriptor& descriptor) const { - std::map m; - m["descriptor_name"] = kDescriptorKey; - m["service_name"] = descriptor.name(); - m["service_descriptor_name"] = ModuleLevelServiceDescriptorName(descriptor); - const char file_descriptor_template[] = - "$descriptor_name$.services_by_name['$service_name$'] = " - "$service_descriptor_name$\n"; - printer_->Print(m, file_descriptor_template); -} - -void Generator::AddEnumToFileDescriptor( - const EnumDescriptor& descriptor) const { - std::map m; - m["descriptor_name"] = kDescriptorKey; - m["enum_name"] = descriptor.name(); - m["enum_descriptor_name"] = ModuleLevelDescriptorName(descriptor); - const char file_descriptor_template[] = - "$descriptor_name$.enum_types_by_name['$enum_name$'] = " - "$enum_descriptor_name$\n"; - printer_->Print(m, file_descriptor_template); -} - -void Generator::AddExtensionToFileDescriptor( - const FieldDescriptor& descriptor) const { - std::map m; - m["descriptor_name"] = kDescriptorKey; - m["field_name"] = descriptor.name(); - const char file_descriptor_template[] = - "$descriptor_name$.extensions_by_name['$field_name$'] = " - "$field_name$\n"; - printer_->Print(m, file_descriptor_template); -} - -// Sets any necessary message_type and enum_type attributes -// for the Python version of |field|. -// -// containing_type may be NULL, in which case this is a module-level field. -// -// python_dict_name is the name of the Python dict where we should -// look the field up in the containing type. (e.g., fields_by_name -// or extensions_by_name). We ignore python_dict_name if containing_type -// is NULL. -void Generator::FixForeignFieldsInField(const Descriptor* containing_type, - const FieldDescriptor& field, - const string& python_dict_name) const { - const string field_referencing_expression = FieldReferencingExpression( - containing_type, field, python_dict_name); - std::map m; - m["field_ref"] = field_referencing_expression; - const Descriptor* foreign_message_type = field.message_type(); - if (foreign_message_type) { - m["foreign_type"] = ModuleLevelDescriptorName(*foreign_message_type); - printer_->Print(m, "$field_ref$.message_type = $foreign_type$\n"); - } - const EnumDescriptor* enum_type = field.enum_type(); - if (enum_type) { - m["enum_type"] = ModuleLevelDescriptorName(*enum_type); - printer_->Print(m, "$field_ref$.enum_type = $enum_type$\n"); - } -} - -// Returns the module-level expression for the given FieldDescriptor. -// Only works for fields in the .proto file this Generator is generating for. -// -// containing_type may be NULL, in which case this is a module-level field. -// -// python_dict_name is the name of the Python dict where we should -// look the field up in the containing type. (e.g., fields_by_name -// or extensions_by_name). We ignore python_dict_name if containing_type -// is NULL. -string Generator::FieldReferencingExpression( - const Descriptor* containing_type, - const FieldDescriptor& field, - const string& python_dict_name) const { - // We should only ever be looking up fields in the current file. - // The only things we refer to from other files are message descriptors. - GOOGLE_CHECK_EQ(field.file(), file_) << field.file()->name() << " vs. " - << file_->name(); - if (!containing_type) { - return field.name(); - } - return strings::Substitute( - "$0.$1['$2']", - ModuleLevelDescriptorName(*containing_type), - python_dict_name, field.name()); -} - -// Prints containing_type for nested descriptors or enum descriptors. -template -void Generator::FixContainingTypeInDescriptor( - const DescriptorT& descriptor, - const Descriptor* containing_descriptor) const { - if (containing_descriptor != NULL) { - const string nested_name = ModuleLevelDescriptorName(descriptor); - const string parent_name = ModuleLevelDescriptorName( - *containing_descriptor); - printer_->Print( - "$nested_name$.containing_type = $parent_name$\n", - "nested_name", nested_name, - "parent_name", parent_name); - } -} - -// Prints statements setting the message_type and enum_type fields in the -// Python descriptor objects we've already output in ths file. We must -// do this in a separate step due to circular references (otherwise, we'd -// just set everything in the initial assignment statements). -void Generator::FixForeignFieldsInDescriptors() const { - for (int i = 0; i < file_->message_type_count(); ++i) { - FixForeignFieldsInDescriptor(*file_->message_type(i), NULL); - } - for (int i = 0; i < file_->message_type_count(); ++i) { - AddMessageToFileDescriptor(*file_->message_type(i)); - } - for (int i = 0; i < file_->enum_type_count(); ++i) { - AddEnumToFileDescriptor(*file_->enum_type(i)); - } - for (int i = 0; i < file_->extension_count(); ++i) { - AddExtensionToFileDescriptor(*file_->extension(i)); - } - // TODO(jieluo): Move this register to PrintFileDescriptor() when - // FieldDescriptor.file is added in generated file. - printer_->Print("_sym_db.RegisterFileDescriptor($name$)\n", "name", - kDescriptorKey); - printer_->Print("\n"); -} - -// We need to not only set any necessary message_type fields, but -// also need to call RegisterExtension() on each message we're -// extending. -void Generator::FixForeignFieldsInExtensions() const { - // Top-level extensions. - for (int i = 0; i < file_->extension_count(); ++i) { - FixForeignFieldsInExtension(*file_->extension(i)); - } - // Nested extensions. - for (int i = 0; i < file_->message_type_count(); ++i) { - FixForeignFieldsInNestedExtensions(*file_->message_type(i)); - } - printer_->Print("\n"); -} - -void Generator::FixForeignFieldsInExtension( - const FieldDescriptor& extension_field) const { - GOOGLE_CHECK(extension_field.is_extension()); - // extension_scope() will be NULL for top-level extensions, which is - // exactly what FixForeignFieldsInField() wants. - FixForeignFieldsInField(extension_field.extension_scope(), extension_field, - "extensions_by_name"); - - std::map m; - // Confusingly, for FieldDescriptors that happen to be extensions, - // containing_type() means "extended type." - // On the other hand, extension_scope() will give us what we normally - // mean by containing_type(). - m["extended_message_class"] = ModuleLevelMessageName( - *extension_field.containing_type()); - m["field"] = FieldReferencingExpression(extension_field.extension_scope(), - extension_field, - "extensions_by_name"); - printer_->Print(m, "$extended_message_class$.RegisterExtension($field$)\n"); -} - -void Generator::FixForeignFieldsInNestedExtensions( - const Descriptor& descriptor) const { - // Recursively fix up extensions in all nested types. - for (int i = 0; i < descriptor.nested_type_count(); ++i) { - FixForeignFieldsInNestedExtensions(*descriptor.nested_type(i)); - } - // Fix up extensions directly contained within this type. - for (int i = 0; i < descriptor.extension_count(); ++i) { - FixForeignFieldsInExtension(*descriptor.extension(i)); - } -} - -// Returns a Python expression that instantiates a Python EnumValueDescriptor -// object for the given C++ descriptor. -void Generator::PrintEnumValueDescriptor( - const EnumValueDescriptor& descriptor) const { - // TODO(robinson): Fix up EnumValueDescriptor "type" fields. - // More circular references. ::sigh:: - string options_string; - descriptor.options().SerializeToString(&options_string); - std::map m; - m["name"] = descriptor.name(); - m["index"] = SimpleItoa(descriptor.index()); - m["number"] = SimpleItoa(descriptor.number()); - m["options"] = OptionsValue(options_string); - printer_->Print( - m, - "_descriptor.EnumValueDescriptor(\n" - " name='$name$', index=$index$, number=$number$,\n" - " serialized_options=$options$,\n" - " type=None)"); -} - -// Returns a CEscaped string of serialized_options. -string Generator::OptionsValue(const string& serialized_options) const { - if (serialized_options.length() == 0 || GeneratingDescriptorProto()) { - return "None"; - } else { -//##!PY25 return "b'('" + CEscape(serialized_options)+ "')"; - return "_b('"+ CEscape(serialized_options) + "')"; //##PY25 - } -} - -// Prints an expression for a Python FieldDescriptor for |field|. -void Generator::PrintFieldDescriptor( - const FieldDescriptor& field, bool is_extension) const { - string options_string; - field.options().SerializeToString(&options_string); - std::map m; - m["name"] = field.name(); - m["full_name"] = field.full_name(); - m["index"] = SimpleItoa(field.index()); - m["number"] = SimpleItoa(field.number()); - m["type"] = SimpleItoa(field.type()); - m["cpp_type"] = SimpleItoa(field.cpp_type()); - m["label"] = SimpleItoa(field.label()); - m["has_default_value"] = field.has_default_value() ? "True" : "False"; - m["default_value"] = StringifyDefaultValue(field); - m["is_extension"] = is_extension ? "True" : "False"; - m["serialized_options"] = OptionsValue(options_string); - m["json_name"] = field.has_json_name() ? - ", json_name='" + field.json_name() + "'": ""; - // We always set message_type and enum_type to None at this point, and then - // these fields in correctly after all referenced descriptors have been - // defined and/or imported (see FixForeignFieldsInDescriptors()). - const char field_descriptor_decl[] = - "_descriptor.FieldDescriptor(\n" - " name='$name$', full_name='$full_name$', index=$index$,\n" - " number=$number$, type=$type$, cpp_type=$cpp_type$, label=$label$,\n" - " has_default_value=$has_default_value$, default_value=$default_value$,\n" - " message_type=None, enum_type=None, containing_type=None,\n" - " is_extension=$is_extension$, extension_scope=None,\n" - " serialized_options=$serialized_options$$json_name$, file=DESCRIPTOR)"; - printer_->Print(m, field_descriptor_decl); -} - -// Helper for Print{Fields,Extensions}InDescriptor(). -void Generator::PrintFieldDescriptorsInDescriptor( - const Descriptor& message_descriptor, - bool is_extension, - const string& list_variable_name, - int (Descriptor::*CountFn)() const, - const FieldDescriptor* (Descriptor::*GetterFn)(int) const) const { - printer_->Print("$list$=[\n", "list", list_variable_name); - printer_->Indent(); - for (int i = 0; i < (message_descriptor.*CountFn)(); ++i) { - PrintFieldDescriptor(*(message_descriptor.*GetterFn)(i), - is_extension); - printer_->Print(",\n"); - } - printer_->Outdent(); - printer_->Print("],\n"); -} - -// Prints a statement assigning "fields" to a list of Python FieldDescriptors, -// one for each field present in message_descriptor. -void Generator::PrintFieldsInDescriptor( - const Descriptor& message_descriptor) const { - const bool is_extension = false; - PrintFieldDescriptorsInDescriptor( - message_descriptor, is_extension, "fields", - &Descriptor::field_count, &Descriptor::field); -} - -// Prints a statement assigning "extensions" to a list of Python -// FieldDescriptors, one for each extension present in message_descriptor. -void Generator::PrintExtensionsInDescriptor( - const Descriptor& message_descriptor) const { - const bool is_extension = true; - PrintFieldDescriptorsInDescriptor( - message_descriptor, is_extension, "extensions", - &Descriptor::extension_count, &Descriptor::extension); -} - -bool Generator::GeneratingDescriptorProto() const { - return file_->name() == "google/protobuf/descriptor.proto"; -} - -// Returns the unique Python module-level identifier given to a descriptor. -// This name is module-qualified iff the given descriptor describes an -// entity that doesn't come from the current file. -template -string Generator::ModuleLevelDescriptorName( - const DescriptorT& descriptor) const { - // FIXME(robinson): - // We currently don't worry about collisions with underscores in the type - // names, so these would collide in nasty ways if found in the same file: - // OuterProto.ProtoA.ProtoB - // OuterProto_ProtoA.ProtoB # Underscore instead of period. - // As would these: - // OuterProto.ProtoA_.ProtoB - // OuterProto.ProtoA._ProtoB # Leading vs. trailing underscore. - // (Contrived, but certainly possible). - // - // The C++ implementation doesn't guard against this either. Leaving - // it for now... - string name = NamePrefixedWithNestedTypes(descriptor, "_"); - UpperString(&name); - // Module-private for now. Easy to make public later; almost impossible - // to make private later. - name = "_" + name; - // We now have the name relative to its own module. Also qualify with - // the module name iff this descriptor is from a different .proto file. - if (descriptor.file() != file_) { - name = ModuleAlias(descriptor.file()->name()) + "." + name; - } - return name; -} - -// Returns the name of the message class itself, not the descriptor. -// Like ModuleLevelDescriptorName(), module-qualifies the name iff -// the given descriptor describes an entity that doesn't come from -// the current file. -string Generator::ModuleLevelMessageName(const Descriptor& descriptor) const { - string name = NamePrefixedWithNestedTypes(descriptor, "."); - if (descriptor.file() != file_) { - name = ModuleAlias(descriptor.file()->name()) + "." + name; - } - return name; -} - -// Returns the unique Python module-level identifier given to a service -// descriptor. -string Generator::ModuleLevelServiceDescriptorName( - const ServiceDescriptor& descriptor) const { - string name = descriptor.name(); - UpperString(&name); - name = "_" + name; - if (descriptor.file() != file_) { - name = ModuleAlias(descriptor.file()->name()) + "." + name; - } - return name; -} - -// Prints standard constructor arguments serialized_start and serialized_end. -// Args: -// descriptor: The cpp descriptor to have a serialized reference. -// proto: A proto -// Example printer output: -// serialized_start=41, -// serialized_end=43, -// -template -void Generator::PrintSerializedPbInterval( - const DescriptorT& descriptor, DescriptorProtoT& proto) const { - descriptor.CopyTo(&proto); - string sp; - proto.SerializeToString(&sp); - int offset = file_descriptor_serialized_.find(sp); - GOOGLE_CHECK_GE(offset, 0); - - printer_->Print("serialized_start=$serialized_start$,\n" - "serialized_end=$serialized_end$,\n", - "serialized_start", SimpleItoa(offset), - "serialized_end", SimpleItoa(offset + sp.size())); -} - -namespace { -void PrintDescriptorOptionsFixingCode(const string& descriptor, - const string& options, - io::Printer* printer) { - // Reset the _options to None thus DescriptorBase.GetOptions() can - // parse _options again after extensions are registered. - printer->Print( - "$descriptor$._options = None\n", - "descriptor", descriptor); -} -} // namespace - -// Prints expressions that set the options field of all descriptors. -void Generator::FixAllDescriptorOptions() const { - // Prints an expression that sets the file descriptor's options. - string file_options = OptionsValue(file_->options().SerializeAsString()); - if (file_options != "None") { - PrintDescriptorOptionsFixingCode(kDescriptorKey, file_options, printer_); - } - // Prints expressions that set the options for all top level enums. - for (int i = 0; i < file_->enum_type_count(); ++i) { - const EnumDescriptor& enum_descriptor = *file_->enum_type(i); - FixOptionsForEnum(enum_descriptor); - } - // Prints expressions that set the options for all top level extensions. - for (int i = 0; i < file_->extension_count(); ++i) { - const FieldDescriptor& field = *file_->extension(i); - FixOptionsForField(field); - } - // Prints expressions that set the options for all messages, nested enums, - // nested extensions and message fields. - for (int i = 0; i < file_->message_type_count(); ++i) { - FixOptionsForMessage(*file_->message_type(i)); - } -} - -void Generator::FixOptionsForOneof(const OneofDescriptor& oneof) const { - string oneof_options = OptionsValue(oneof.options().SerializeAsString()); - if (oneof_options != "None") { - string oneof_name = strings::Substitute( - "$0.$1['$2']", - ModuleLevelDescriptorName(*oneof.containing_type()), - "oneofs_by_name", oneof.name()); - PrintDescriptorOptionsFixingCode(oneof_name, oneof_options, printer_); - } -} - -// Prints expressions that set the options for an enum descriptor and its -// value descriptors. -void Generator::FixOptionsForEnum(const EnumDescriptor& enum_descriptor) const { - string descriptor_name = ModuleLevelDescriptorName(enum_descriptor); - string enum_options = OptionsValue( - enum_descriptor.options().SerializeAsString()); - if (enum_options != "None") { - PrintDescriptorOptionsFixingCode(descriptor_name, enum_options, printer_); - } - for (int i = 0; i < enum_descriptor.value_count(); ++i) { - const EnumValueDescriptor& value_descriptor = *enum_descriptor.value(i); - string value_options = OptionsValue( - value_descriptor.options().SerializeAsString()); - if (value_options != "None") { - PrintDescriptorOptionsFixingCode( - StringPrintf("%s.values_by_name[\"%s\"]", descriptor_name.c_str(), - value_descriptor.name().c_str()), - value_options, printer_); - } - } -} - -// Prints expressions that set the options for field descriptors (including -// extensions). -void Generator::FixOptionsForField( - const FieldDescriptor& field) const { - string field_options = OptionsValue(field.options().SerializeAsString()); - if (field_options != "None") { - string field_name; - if (field.is_extension()) { - if (field.extension_scope() == NULL) { - // Top level extensions. - field_name = field.name(); - } else { - field_name = FieldReferencingExpression( - field.extension_scope(), field, "extensions_by_name"); - } - } else { - field_name = FieldReferencingExpression( - field.containing_type(), field, "fields_by_name"); - } - PrintDescriptorOptionsFixingCode(field_name, field_options, printer_); - } -} - -// Prints expressions that set the options for a message and all its inner -// types (nested messages, nested enums, extensions, fields). -void Generator::FixOptionsForMessage(const Descriptor& descriptor) const { - // Nested messages. - for (int i = 0; i < descriptor.nested_type_count(); ++i) { - FixOptionsForMessage(*descriptor.nested_type(i)); - } - // Oneofs. - for (int i = 0; i < descriptor.oneof_decl_count(); ++i) { - FixOptionsForOneof(*descriptor.oneof_decl(i)); - } - // Enums. - for (int i = 0; i < descriptor.enum_type_count(); ++i) { - FixOptionsForEnum(*descriptor.enum_type(i)); - } - // Fields. - for (int i = 0; i < descriptor.field_count(); ++i) { - const FieldDescriptor& field = *descriptor.field(i); - FixOptionsForField(field); - } - // Extensions. - for (int i = 0; i < descriptor.extension_count(); ++i) { - const FieldDescriptor& field = *descriptor.extension(i); - FixOptionsForField(field); - } - // Message option for this message. - string message_options = OptionsValue( - descriptor.options().SerializeAsString()); - if (message_options != "None") { - string descriptor_name = ModuleLevelDescriptorName(descriptor); - PrintDescriptorOptionsFixingCode(descriptor_name, - message_options, - printer_); - } -} - -// If a dependency forwards other files through public dependencies, let's -// copy over the corresponding module aliases. -void Generator::CopyPublicDependenciesAliases( - const string& copy_from, const FileDescriptor* file) const { - for (int i = 0; i < file->public_dependency_count(); ++i) { - string module_name = ModuleName(file->public_dependency(i)->name()); - string module_alias = ModuleAlias(file->public_dependency(i)->name()); - // There's no module alias in the dependent file if it was generated by - // an old protoc (less than 3.0.0-alpha-1). Use module name in this - // situation. - printer_->Print("try:\n" - " $alias$ = $copy_from$.$alias$\n" - "except AttributeError:\n" - " $alias$ = $copy_from$.$module$\n", - "alias", module_alias, - "module", module_name, - "copy_from", copy_from); - CopyPublicDependenciesAliases(copy_from, file->public_dependency(i)); - } -} - -} // namespace python -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/python/python_generator.h b/windows/include/google/protobuf/compiler/python/python_generator.h index 8e4050de8..3b4c1323b 100644 --- a/windows/include/google/protobuf/compiler/python/python_generator.h +++ b/windows/include/google/protobuf/compiler/python/python_generator.h @@ -39,7 +39,8 @@ #include #include -#include + +#include namespace google { namespace protobuf { @@ -51,56 +52,65 @@ class FieldDescriptor; class OneofDescriptor; class ServiceDescriptor; -namespace io { class Printer; } +namespace io { +class Printer; +} namespace compiler { namespace python { +enum class StripPrintDescriptor { kCreate, kFind }; + // CodeGenerator implementation for generated Python protocol buffer classes. // If you create your own protocol compiler binary and you want it to support // Python output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator : public CodeGenerator { +class PROTOC_EXPORT Generator : public CodeGenerator { public: Generator(); virtual ~Generator(); // CodeGenerator methods. - virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* generator_context, - string* error) const; + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* generator_context, + std::string* error) const override; + + uint64_t GetSupportedFeatures() const override; private: void PrintImports() const; void PrintFileDescriptor() const; void PrintTopLevelEnums() const; - void PrintAllNestedEnumsInFile() const; - void PrintNestedEnums(const Descriptor& descriptor) const; - void PrintEnum(const EnumDescriptor& enum_descriptor) const; + void PrintAllNestedEnumsInFile(StripPrintDescriptor print_mode) const; + void PrintNestedEnums(const Descriptor& descriptor, + StripPrintDescriptor print_mode) const; + void PrintCreateEnum(const EnumDescriptor& enum_descriptor) const; + void PrintFindEnum(const EnumDescriptor& enum_descriptor) const; void PrintTopLevelExtensions() const; - void PrintFieldDescriptor( - const FieldDescriptor& field, bool is_extension) const; + void PrintFieldDescriptor(const FieldDescriptor& field, + bool is_extension) const; void PrintFieldDescriptorsInDescriptor( - const Descriptor& message_descriptor, - bool is_extension, - const string& list_variable_name, - int (Descriptor::*CountFn)() const, - const FieldDescriptor* (Descriptor::*GetterFn)(int) const) const; + const Descriptor& message_descriptor, bool is_extension, + const std::string& list_variable_name, int (Descriptor::*CountFn)() const, + const FieldDescriptor* (Descriptor::*GetterFn)(int)const) const; void PrintFieldsInDescriptor(const Descriptor& message_descriptor) const; void PrintExtensionsInDescriptor(const Descriptor& message_descriptor) const; - void PrintMessageDescriptors() const; - void PrintDescriptor(const Descriptor& message_descriptor) const; - void PrintNestedDescriptors(const Descriptor& containing_descriptor) const; + void PrintMessageDescriptors(StripPrintDescriptor print_mode) const; + void PrintCreateDescriptor(const Descriptor& message_descriptor) const; + void PrintFindDescriptor(const Descriptor& message_descriptor) const; + void PrintNestedDescriptors(const Descriptor& containing_descriptor, + StripPrintDescriptor print_mode) const; void PrintMessages() const; - void PrintMessage(const Descriptor& message_descriptor, const string& prefix, - std::vector* to_register) const; + void PrintMessage(const Descriptor& message_descriptor, + const std::string& prefix, + std::vector* to_register, + bool is_nested) const; void PrintNestedMessages(const Descriptor& containing_descriptor, - const string& prefix, - std::vector* to_register) const; + const std::string& prefix, + std::vector* to_register) const; void FixForeignFieldsInDescriptors() const; void FixForeignFieldsInDescriptor( @@ -108,14 +118,14 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const Descriptor* containing_descriptor) const; void FixForeignFieldsInField(const Descriptor* containing_type, const FieldDescriptor& field, - const string& python_dict_name) const; + const std::string& python_dict_name) const; void AddMessageToFileDescriptor(const Descriptor& descriptor) const; void AddEnumToFileDescriptor(const EnumDescriptor& descriptor) const; void AddExtensionToFileDescriptor(const FieldDescriptor& descriptor) const; void AddServiceToFileDescriptor(const ServiceDescriptor& descriptor) const; - string FieldReferencingExpression(const Descriptor* containing_type, - const FieldDescriptor& field, - const string& python_dict_name) const; + std::string FieldReferencingExpression( + const Descriptor* containing_type, const FieldDescriptor& field, + const std::string& python_dict_name) const; template void FixContainingTypeInDescriptor( const DescriptorT& descriptor, @@ -135,34 +145,40 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { const ServiceDescriptor& descriptor) const; void PrintEnumValueDescriptor(const EnumValueDescriptor& descriptor) const; - string OptionsValue(const string& serialized_options) const; + std::string OptionsValue(const std::string& serialized_options) const; bool GeneratingDescriptorProto() const; template - string ModuleLevelDescriptorName(const DescriptorT& descriptor) const; - string ModuleLevelMessageName(const Descriptor& descriptor) const; - string ModuleLevelServiceDescriptorName( + std::string ModuleLevelDescriptorName(const DescriptorT& descriptor) const; + std::string ModuleLevelMessageName(const Descriptor& descriptor) const; + std::string ModuleLevelServiceDescriptorName( const ServiceDescriptor& descriptor) const; template - void PrintSerializedPbInterval( - const DescriptorT& descriptor, DescriptorProtoT& proto) const; + void PrintSerializedPbInterval(const DescriptorT& descriptor, + DescriptorProtoT& proto, + const std::string& name) const; void FixAllDescriptorOptions() const; void FixOptionsForField(const FieldDescriptor& field) const; void FixOptionsForOneof(const OneofDescriptor& oneof) const; void FixOptionsForEnum(const EnumDescriptor& descriptor) const; + void FixOptionsForService(const ServiceDescriptor& descriptor) const; void FixOptionsForMessage(const Descriptor& descriptor) const; - void CopyPublicDependenciesAliases( - const string& copy_from, const FileDescriptor* file) const; + void SetSerializedPbInterval() const; + void SetMessagePbInterval(const Descriptor& descriptor) const; + + void CopyPublicDependenciesAliases(const std::string& copy_from, + const FileDescriptor* file) const; // Very coarse-grained lock to ensure that Generate() is reentrant. // Guards file_, printer_ and file_descriptor_serialized_. mutable Mutex mutex_; mutable const FileDescriptor* file_; // Set in Generate(). Under mutex_. - mutable string file_descriptor_serialized_; + mutable std::string file_descriptor_serialized_; mutable io::Printer* printer_; // Set in Generate(). Under mutex_. + mutable bool pure_python_workable_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Generator); }; @@ -170,6 +186,8 @@ class LIBPROTOC_EXPORT Generator : public CodeGenerator { } // namespace python } // namespace compiler } // namespace protobuf - } // namespace google + +#include + #endif // GOOGLE_PROTOBUF_COMPILER_PYTHON_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/python/python_plugin_unittest.cc b/windows/include/google/protobuf/compiler/python/python_plugin_unittest.cc deleted file mode 100644 index 2f096808a..000000000 --- a/windows/include/google/protobuf/compiler/python/python_plugin_unittest.cc +++ /dev/null @@ -1,167 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// -// TODO(kenton): Share code with the versions of this test in other languages? -// It seemed like parameterizing it would add more complexity than it is -// worth. - -#include - -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace python { -namespace { - -class TestGenerator : public CodeGenerator { - public: - TestGenerator() {} - ~TestGenerator() {} - - virtual bool Generate(const FileDescriptor* file, - const string& parameter, - GeneratorContext* context, - string* error) const { - TryInsert("test_pb2.py", "imports", context); - TryInsert("test_pb2.py", "module_scope", context); - TryInsert("test_pb2.py", "class_scope:foo.Bar", context); - TryInsert("test_pb2.py", "class_scope:foo.Bar.Baz", context); - return true; - } - - void TryInsert(const string& filename, const string& insertion_point, - GeneratorContext* context) const { - std::unique_ptr output( - context->OpenForInsert(filename, insertion_point)); - io::Printer printer(output.get(), '$'); - printer.Print("// inserted $name$\n", "name", insertion_point); - } -}; - -// This test verifies that all the expected insertion points exist. It does -// not verify that they are correctly-placed; that would require actually -// compiling the output which is a bit more than I care to do for this test. -TEST(PythonPluginTest, PluginTest) { - GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/test.proto", - "syntax = \"proto2\";\n" - "package foo;\n" - "message Bar {\n" - " message Baz {}\n" - "}\n", - true)); - - google::protobuf::compiler::CommandLineInterface cli; - cli.SetInputsAreProtoPathRelative(true); - - python::Generator python_generator; - TestGenerator test_generator; - cli.RegisterGenerator("--python_out", &python_generator, ""); - cli.RegisterGenerator("--test_out", &test_generator, ""); - - string proto_path = "-I" + TestTempDir(); - string python_out = "--python_out=" + TestTempDir(); - string test_out = "--test_out=" + TestTempDir(); - - const char* argv[] = { - "protoc", - proto_path.c_str(), - python_out.c_str(), - test_out.c_str(), - "test.proto" - }; - - EXPECT_EQ(0, cli.Run(5, argv)); -} - -// This test verifies that the generated Python output uses regular imports (as -// opposed to importlib) in the usual case where the .proto file paths do not -// not contain any Python keywords. -TEST(PythonPluginTest, ImportTest) { - // Create files test1.proto and test2.proto with the former importing the - // latter. - GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/test1.proto", - "syntax = \"proto3\";\n" - "package foo;\n" - "import \"test2.proto\";" - "message Message1 {\n" - " Message2 message_2 = 1;\n" - "}\n", - true)); - GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/test2.proto", - "syntax = \"proto3\";\n" - "package foo;\n" - "message Message2 {}\n", - true)); - - google::protobuf::compiler::CommandLineInterface cli; - cli.SetInputsAreProtoPathRelative(true); - python::Generator python_generator; - cli.RegisterGenerator("--python_out", &python_generator, ""); - string proto_path = "-I" + TestTempDir(); - string python_out = "--python_out=" + TestTempDir(); - const char* argv[] = {"protoc", proto_path.c_str(), "-I.", python_out.c_str(), - "test1.proto"}; - ASSERT_EQ(0, cli.Run(5, argv)); - - // Loop over the lines of the generated code and verify that we find an - // ordinary Python import but do not find the string "importlib". - string output; - GOOGLE_CHECK_OK(File::GetContents(TestTempDir() + "/test1_pb2.py", &output, - true)); - std::vector lines = Split(output, "\n"); - string expected_import = "import test2_pb2"; - bool found_expected_import = false; - for (int i = 0; i < lines.size(); ++i) { - if (lines[i].find(expected_import) != string::npos) { - found_expected_import = true; - } - EXPECT_EQ(string::npos, lines[i].find("importlib")); - } - EXPECT_TRUE(found_expected_import); -} - -} // namespace -} // namespace python -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/ruby/ruby_generated_code.proto b/windows/include/google/protobuf/compiler/ruby/ruby_generated_code.proto deleted file mode 100644 index 42d82a6ba..000000000 --- a/windows/include/google/protobuf/compiler/ruby/ruby_generated_code.proto +++ /dev/null @@ -1,67 +0,0 @@ -syntax = "proto3"; - -package A.B.C; - -message TestMessage { - int32 optional_int32 = 1; - int64 optional_int64 = 2; - uint32 optional_uint32 = 3; - uint64 optional_uint64 = 4; - bool optional_bool = 5; - double optional_double = 6; - float optional_float = 7; - string optional_string = 8; - bytes optional_bytes = 9; - TestEnum optional_enum = 10; - TestMessage optional_msg = 11; - - repeated int32 repeated_int32 = 21; - repeated int64 repeated_int64 = 22; - repeated uint32 repeated_uint32 = 23; - repeated uint64 repeated_uint64 = 24; - repeated bool repeated_bool = 25; - repeated double repeated_double = 26; - repeated float repeated_float = 27; - repeated string repeated_string = 28; - repeated bytes repeated_bytes = 29; - repeated TestEnum repeated_enum = 30; - repeated TestMessage repeated_msg = 31; - - oneof my_oneof { - int32 oneof_int32 = 41; - int64 oneof_int64 = 42; - uint32 oneof_uint32 = 43; - uint64 oneof_uint64 = 44; - bool oneof_bool = 45; - double oneof_double = 46; - float oneof_float = 47; - string oneof_string = 48; - bytes oneof_bytes = 49; - TestEnum oneof_enum = 50; - TestMessage oneof_msg = 51; - } - - map map_int32_string = 61; - map map_int64_string = 62; - map map_uint32_string = 63; - map map_uint64_string = 64; - map map_bool_string = 65; - map map_string_string = 66; - map map_string_msg = 67; - map map_string_enum = 68; - map map_string_int32 = 69; - map map_string_bool = 70; - - message NestedMessage { - int32 foo = 1; - } - - NestedMessage nested_message = 80; -} - -enum TestEnum { - Default = 0; - A = 1; - B = 2; - C = 3; -} diff --git a/windows/include/google/protobuf/compiler/ruby/ruby_generated_code_pb.rb b/windows/include/google/protobuf/compiler/ruby/ruby_generated_code_pb.rb deleted file mode 100644 index 49b23fbe8..000000000 --- a/windows/include/google/protobuf/compiler/ruby/ruby_generated_code_pb.rb +++ /dev/null @@ -1,74 +0,0 @@ -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: ruby_generated_code.proto - -require 'google/protobuf' - -Google::Protobuf::DescriptorPool.generated_pool.build do - add_message "A.B.C.TestMessage" do - optional :optional_int32, :int32, 1 - optional :optional_int64, :int64, 2 - optional :optional_uint32, :uint32, 3 - optional :optional_uint64, :uint64, 4 - optional :optional_bool, :bool, 5 - optional :optional_double, :double, 6 - optional :optional_float, :float, 7 - optional :optional_string, :string, 8 - optional :optional_bytes, :bytes, 9 - optional :optional_enum, :enum, 10, "A.B.C.TestEnum" - optional :optional_msg, :message, 11, "A.B.C.TestMessage" - repeated :repeated_int32, :int32, 21 - repeated :repeated_int64, :int64, 22 - repeated :repeated_uint32, :uint32, 23 - repeated :repeated_uint64, :uint64, 24 - repeated :repeated_bool, :bool, 25 - repeated :repeated_double, :double, 26 - repeated :repeated_float, :float, 27 - repeated :repeated_string, :string, 28 - repeated :repeated_bytes, :bytes, 29 - repeated :repeated_enum, :enum, 30, "A.B.C.TestEnum" - repeated :repeated_msg, :message, 31, "A.B.C.TestMessage" - map :map_int32_string, :int32, :string, 61 - map :map_int64_string, :int64, :string, 62 - map :map_uint32_string, :uint32, :string, 63 - map :map_uint64_string, :uint64, :string, 64 - map :map_bool_string, :bool, :string, 65 - map :map_string_string, :string, :string, 66 - map :map_string_msg, :string, :message, 67, "A.B.C.TestMessage" - map :map_string_enum, :string, :enum, 68, "A.B.C.TestEnum" - map :map_string_int32, :string, :int32, 69 - map :map_string_bool, :string, :bool, 70 - optional :nested_message, :message, 80, "A.B.C.TestMessage.NestedMessage" - oneof :my_oneof do - optional :oneof_int32, :int32, 41 - optional :oneof_int64, :int64, 42 - optional :oneof_uint32, :uint32, 43 - optional :oneof_uint64, :uint64, 44 - optional :oneof_bool, :bool, 45 - optional :oneof_double, :double, 46 - optional :oneof_float, :float, 47 - optional :oneof_string, :string, 48 - optional :oneof_bytes, :bytes, 49 - optional :oneof_enum, :enum, 50, "A.B.C.TestEnum" - optional :oneof_msg, :message, 51, "A.B.C.TestMessage" - end - end - add_message "A.B.C.TestMessage.NestedMessage" do - optional :foo, :int32, 1 - end - add_enum "A.B.C.TestEnum" do - value :Default, 0 - value :A, 1 - value :B, 2 - value :C, 3 - end -end - -module A - module B - module C - TestMessage = Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestMessage").msgclass - TestMessage::NestedMessage = Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestMessage.NestedMessage").msgclass - TestEnum = Google::Protobuf::DescriptorPool.generated_pool.lookup("A.B.C.TestEnum").enummodule - end - end -end diff --git a/windows/include/google/protobuf/compiler/ruby/ruby_generator.cc b/windows/include/google/protobuf/compiler/ruby/ruby_generator.cc deleted file mode 100644 index bd737c027..000000000 --- a/windows/include/google/protobuf/compiler/ruby/ruby_generator.cc +++ /dev/null @@ -1,512 +0,0 @@ -// 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. - -#include - -#include -#include -#include -#include -#include -#include - -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace ruby { - -// Forward decls. -std::string IntToString(int32 value); -std::string GetRequireName(const std::string& proto_file); -std::string LabelForField(google::protobuf::FieldDescriptor* field); -std::string TypeName(google::protobuf::FieldDescriptor* field); -void GenerateMessage(const google::protobuf::Descriptor* message, - google::protobuf::io::Printer* printer); -void GenerateEnum(const google::protobuf::EnumDescriptor* en, - google::protobuf::io::Printer* printer); -void GenerateMessageAssignment( - const std::string& prefix, - const google::protobuf::Descriptor* message, - google::protobuf::io::Printer* printer); -void GenerateEnumAssignment( - const std::string& prefix, - const google::protobuf::EnumDescriptor* en, - google::protobuf::io::Printer* printer); - -std::string IntToString(int32 value) { - std::ostringstream os; - os << value; - return os.str(); -} - -std::string GetRequireName(const std::string& proto_file) { - int lastindex = proto_file.find_last_of("."); - return proto_file.substr(0, lastindex) + "_pb"; -} - -std::string GetOutputFilename(const std::string& proto_file) { - return GetRequireName(proto_file) + ".rb"; -} - -std::string LabelForField(const google::protobuf::FieldDescriptor* field) { - switch (field->label()) { - case FieldDescriptor::LABEL_OPTIONAL: return "optional"; - case FieldDescriptor::LABEL_REQUIRED: return "required"; - case FieldDescriptor::LABEL_REPEATED: return "repeated"; - default: assert(false); return ""; - } -} - -std::string TypeName(const google::protobuf::FieldDescriptor* field) { - switch (field->type()) { - case FieldDescriptor::TYPE_INT32: return "int32"; - case FieldDescriptor::TYPE_INT64: return "int64"; - case FieldDescriptor::TYPE_UINT32: return "uint32"; - case FieldDescriptor::TYPE_UINT64: return "uint64"; - case FieldDescriptor::TYPE_SINT32: return "sint32"; - case FieldDescriptor::TYPE_SINT64: return "sint64"; - case FieldDescriptor::TYPE_FIXED32: return "fixed32"; - case FieldDescriptor::TYPE_FIXED64: return "fixed64"; - case FieldDescriptor::TYPE_SFIXED32: return "sfixed32"; - case FieldDescriptor::TYPE_SFIXED64: return "sfixed64"; - case FieldDescriptor::TYPE_DOUBLE: return "double"; - case FieldDescriptor::TYPE_FLOAT: return "float"; - case FieldDescriptor::TYPE_BOOL: return "bool"; - case FieldDescriptor::TYPE_ENUM: return "enum"; - case FieldDescriptor::TYPE_STRING: return "string"; - case FieldDescriptor::TYPE_BYTES: return "bytes"; - case FieldDescriptor::TYPE_MESSAGE: return "message"; - case FieldDescriptor::TYPE_GROUP: return "group"; - default: assert(false); return ""; - } -} - -void GenerateField(const google::protobuf::FieldDescriptor* field, - google::protobuf::io::Printer* printer) { - - if (field->is_map()) { - const FieldDescriptor* key_field = - field->message_type()->FindFieldByNumber(1); - const FieldDescriptor* value_field = - field->message_type()->FindFieldByNumber(2); - - printer->Print( - "map :$name$, :$key_type$, :$value_type$, $number$", - "name", field->name(), - "key_type", TypeName(key_field), - "value_type", TypeName(value_field), - "number", IntToString(field->number())); - - if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - printer->Print( - ", \"$subtype$\"\n", - "subtype", value_field->message_type()->full_name()); - } else if (value_field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - printer->Print( - ", \"$subtype$\"\n", - "subtype", value_field->enum_type()->full_name()); - } else { - printer->Print("\n"); - } - } else { - - printer->Print( - "$label$ :$name$, ", - "label", LabelForField(field), - "name", field->name()); - printer->Print( - ":$type$, $number$", - "type", TypeName(field), - "number", IntToString(field->number())); - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - printer->Print( - ", \"$subtype$\"\n", - "subtype", field->message_type()->full_name()); - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - printer->Print( - ", \"$subtype$\"\n", - "subtype", field->enum_type()->full_name()); - } else { - printer->Print("\n"); - } - } -} - -void GenerateOneof(const google::protobuf::OneofDescriptor* oneof, - google::protobuf::io::Printer* printer) { - printer->Print( - "oneof :$name$ do\n", - "name", oneof->name()); - printer->Indent(); - - for (int i = 0; i < oneof->field_count(); i++) { - const FieldDescriptor* field = oneof->field(i); - GenerateField(field, printer); - } - - printer->Outdent(); - printer->Print("end\n"); -} - -void GenerateMessage(const google::protobuf::Descriptor* message, - google::protobuf::io::Printer* printer) { - - // Don't generate MapEntry messages -- we use the Ruby extension's native - // support for map fields instead. - if (message->options().map_entry()) { - return; - } - - printer->Print( - "add_message \"$name$\" do\n", - "name", message->full_name()); - printer->Indent(); - - for (int i = 0; i < message->field_count(); i++) { - const FieldDescriptor* field = message->field(i); - if (!field->containing_oneof()) { - GenerateField(field, printer); - } - } - - for (int i = 0; i < message->oneof_decl_count(); i++) { - const OneofDescriptor* oneof = message->oneof_decl(i); - GenerateOneof(oneof, printer); - } - - printer->Outdent(); - printer->Print("end\n"); - - for (int i = 0; i < message->nested_type_count(); i++) { - GenerateMessage(message->nested_type(i), printer); - } - for (int i = 0; i < message->enum_type_count(); i++) { - GenerateEnum(message->enum_type(i), printer); - } -} - -void GenerateEnum(const google::protobuf::EnumDescriptor* en, - google::protobuf::io::Printer* printer) { - printer->Print( - "add_enum \"$name$\" do\n", - "name", en->full_name()); - printer->Indent(); - - for (int i = 0; i < en->value_count(); i++) { - const EnumValueDescriptor* value = en->value(i); - printer->Print( - "value :$name$, $number$\n", - "name", value->name(), - "number", IntToString(value->number())); - } - - printer->Outdent(); - printer->Print( - "end\n"); -} - -// Locale-agnostic utility functions. -bool IsLower(char ch) { return ch >= 'a' && ch <= 'z'; } - -bool IsUpper(char ch) { return ch >= 'A' && ch <= 'Z'; } - -bool IsAlpha(char ch) { return IsLower(ch) || IsUpper(ch); } - -char ToUpper(char ch) { return IsLower(ch) ? (ch - 'a' + 'A') : ch; } - - -// Package names in protobuf are snake_case by convention, but Ruby module -// names must be PascalCased. -// -// foo_bar_baz -> FooBarBaz -std::string PackageToModule(const std::string& name) { - bool next_upper = true; - std::string result; - result.reserve(name.size()); - - for (int i = 0; i < name.size(); i++) { - if (name[i] == '_') { - next_upper = true; - } else { - if (next_upper) { - result.push_back(ToUpper(name[i])); - } else { - result.push_back(name[i]); - } - next_upper = false; - } - } - - return result; -} - -// Class and enum names in protobuf should be PascalCased by convention, but -// since there is nothing enforcing this we need to ensure that they are valid -// Ruby constants. That mainly means making sure that the first character is -// an upper-case letter. -std::string RubifyConstant(const std::string& name) { - std::string ret = name; - if (!ret.empty()) { - if (IsLower(ret[0])) { - // If it starts with a lowercase letter, capitalize it. - ret[0] = ToUpper(ret[0]); - } else if (!IsAlpha(ret[0])) { - // Otherwise (e.g. if it begins with an underscore), we need to come up - // with some prefix that starts with a capital letter. We could be smarter - // here, e.g. try to strip leading underscores, but this may cause other - // problems if the user really intended the name. So let's just prepend a - // well-known suffix. - ret = "PB_" + ret; - } - } - - return ret; -} - -void GenerateMessageAssignment( - const std::string& prefix, - const google::protobuf::Descriptor* message, - google::protobuf::io::Printer* printer) { - - // Don't generate MapEntry messages -- we use the Ruby extension's native - // support for map fields instead. - if (message->options().map_entry()) { - return; - } - - printer->Print( - "$prefix$$name$ = ", - "prefix", prefix, - "name", RubifyConstant(message->name())); - printer->Print( - "Google::Protobuf::DescriptorPool.generated_pool." - "lookup(\"$full_name$\").msgclass\n", - "full_name", message->full_name()); - - std::string nested_prefix = prefix + message->name() + "::"; - for (int i = 0; i < message->nested_type_count(); i++) { - GenerateMessageAssignment(nested_prefix, message->nested_type(i), printer); - } - for (int i = 0; i < message->enum_type_count(); i++) { - GenerateEnumAssignment(nested_prefix, message->enum_type(i), printer); - } -} - -void GenerateEnumAssignment( - const std::string& prefix, - const google::protobuf::EnumDescriptor* en, - google::protobuf::io::Printer* printer) { - printer->Print( - "$prefix$$name$ = ", - "prefix", prefix, - "name", RubifyConstant(en->name())); - printer->Print( - "Google::Protobuf::DescriptorPool.generated_pool." - "lookup(\"$full_name$\").enummodule\n", - "full_name", en->full_name()); -} - -int GeneratePackageModules( - const FileDescriptor* file, - google::protobuf::io::Printer* printer) { - int levels = 0; - bool need_change_to_module; - std::string package_name; - - if (file->options().has_ruby_package()) { - package_name = file->options().ruby_package(); - need_change_to_module = false; - } else { - package_name = file->package(); - need_change_to_module = true; - } - - while (!package_name.empty()) { - size_t dot_index = package_name.find("."); - string component; - if (dot_index == string::npos) { - component = package_name; - package_name = ""; - } else { - component = package_name.substr(0, dot_index); - package_name = package_name.substr(dot_index + 1); - } - if (need_change_to_module) { - component = PackageToModule(component); - } - printer->Print( - "module $name$\n", - "name", component); - printer->Indent(); - levels++; - } - return levels; -} - -void EndPackageModules( - int levels, - google::protobuf::io::Printer* printer) { - while (levels > 0) { - levels--; - printer->Outdent(); - printer->Print( - "end\n"); - } -} - -bool UsesTypeFromFile(const Descriptor* message, const FileDescriptor* file, - string* error) { - for (int i = 0; i < message->field_count(); i++) { - const FieldDescriptor* field = message->field(i); - if ((field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - field->message_type()->file() == file) || - (field->type() == FieldDescriptor::TYPE_ENUM && - field->enum_type()->file() == file)) { - *error = "proto3 message field " + field->full_name() + " in file " + - file->name() + " has a dependency on a type from proto2 file " + - file->name() + - ". Ruby doesn't support proto2 yet, so we must fail."; - return true; - } - } - - for (int i = 0; i < message->nested_type_count(); i++) { - if (UsesTypeFromFile(message->nested_type(i), file, error)) { - return true; - } - } - - return false; -} - -// Ruby doesn't currently support proto2. This causes a failure even for proto3 -// files that import proto2. But in some cases, the proto2 file is only being -// imported to extend another proto2 message. The prime example is declaring -// custom options by extending FileOptions/FieldOptions/etc. -// -// If the proto3 messages don't have any proto2 submessages, it is safe to omit -// the dependency completely. Users won't be able to use any proto2 extensions, -// but they already couldn't because proto2 messages aren't supported. -// -// If/when we add proto2 support, we should remove this. -bool MaybeEmitDependency(const FileDescriptor* import, - const FileDescriptor* from, - io::Printer* printer, - string* error) { - if (import->syntax() == FileDescriptor::SYNTAX_PROTO2) { - for (int i = 0; i < from->message_type_count(); i++) { - if (UsesTypeFromFile(from->message_type(i), import, error)) { - // Error text was already set by UsesTypeFromFile(). - return false; - } - } - - // Ok to omit this proto2 dependency -- so we won't print anything. - GOOGLE_LOG(WARNING) << "Omitting proto2 dependency '" << import->name() - << "' from proto3 output file '" - << GetOutputFilename(from->name()) - << "' because we don't support proto2 and no proto2 " - "types from that file are being used."; - return true; - } else { - printer->Print( - "require '$name$'\n", "name", GetRequireName(import->name())); - return true; - } -} - -bool GenerateFile(const FileDescriptor* file, io::Printer* printer, - string* error) { - printer->Print( - "# Generated by the protocol buffer compiler. DO NOT EDIT!\n" - "# source: $filename$\n" - "\n", - "filename", file->name()); - - printer->Print( - "require 'google/protobuf'\n\n"); - - for (int i = 0; i < file->dependency_count(); i++) { - if (!MaybeEmitDependency(file->dependency(i), file, printer, error)) { - return false; - } - } - - printer->Print( - "Google::Protobuf::DescriptorPool.generated_pool.build do\n"); - printer->Indent(); - for (int i = 0; i < file->message_type_count(); i++) { - GenerateMessage(file->message_type(i), printer); - } - for (int i = 0; i < file->enum_type_count(); i++) { - GenerateEnum(file->enum_type(i), printer); - } - printer->Outdent(); - printer->Print( - "end\n\n"); - - int levels = GeneratePackageModules(file, printer); - for (int i = 0; i < file->message_type_count(); i++) { - GenerateMessageAssignment("", file->message_type(i), printer); - } - for (int i = 0; i < file->enum_type_count(); i++) { - GenerateEnumAssignment("", file->enum_type(i), printer); - } - EndPackageModules(levels, printer); - return true; -} - -bool Generator::Generate( - const FileDescriptor* file, - const string& parameter, - GeneratorContext* generator_context, - string* error) const { - - if (file->syntax() != FileDescriptor::SYNTAX_PROTO3) { - *error = - "Can only generate Ruby code for proto3 .proto files.\n" - "Please add 'syntax = \"proto3\";' to the top of your .proto file.\n"; - return false; - } - - std::unique_ptr output( - generator_context->Open(GetOutputFilename(file->name()))); - io::Printer printer(output.get(), '$'); - - return GenerateFile(file, &printer, error); -} - -} // namespace ruby -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/ruby/ruby_generator.h b/windows/include/google/protobuf/compiler/ruby/ruby_generator.h index 8c1dfa267..647bb8360 100644 --- a/windows/include/google/protobuf/compiler/ruby/ruby_generator.h +++ b/windows/include/google/protobuf/compiler/ruby/ruby_generator.h @@ -37,6 +37,8 @@ #include +#include + namespace google { namespace protobuf { namespace compiler { @@ -46,13 +48,13 @@ namespace ruby { // If you create your own protocol compiler binary and you want it to support // Ruby output, you can do so by registering an instance of this // CodeGenerator with the CommandLineInterface in your main() function. -class LIBPROTOC_EXPORT Generator - : public google::protobuf::compiler::CodeGenerator { - virtual bool Generate( - const FileDescriptor* file, - const string& parameter, - GeneratorContext* generator_context, - string* error) const; +class PROTOC_EXPORT Generator : public CodeGenerator { + bool Generate(const FileDescriptor* file, const std::string& parameter, + GeneratorContext* generator_context, + std::string* error) const override; + uint64_t GetSupportedFeatures() const override { + return FEATURE_PROTO3_OPTIONAL; + } }; } // namespace ruby @@ -60,5 +62,6 @@ class LIBPROTOC_EXPORT Generator } // namespace protobuf } // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_RUBY_GENERATOR_H__ +#include +#endif // GOOGLE_PROTOBUF_COMPILER_RUBY_GENERATOR_H__ diff --git a/windows/include/google/protobuf/compiler/ruby/ruby_generator_unittest.cc b/windows/include/google/protobuf/compiler/ruby/ruby_generator_unittest.cc deleted file mode 100644 index 1aabe8aa9..000000000 --- a/windows/include/google/protobuf/compiler/ruby/ruby_generator_unittest.cc +++ /dev/null @@ -1,109 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2014 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. - -#include - -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace ruby { -namespace { - -string FindRubyTestDir() { - return TestSourceDir() + "/google/protobuf/compiler/ruby"; -} - -// This test is a simple golden-file test over the output of the Ruby code -// generator. When we make changes to the Ruby extension and alter the Ruby code -// generator to use those changes, we should (i) manually test the output of the -// code generator with the extension, and (ii) update the golden output above. -// Some day, we may integrate build systems between protoc and the language -// extensions to the point where we can do this test in a more automated way. - -TEST(RubyGeneratorTest, GeneratorTest) { - string ruby_tests = FindRubyTestDir(); - - google::protobuf::compiler::CommandLineInterface cli; - cli.SetInputsAreProtoPathRelative(true); - - ruby::Generator ruby_generator; - cli.RegisterGenerator("--ruby_out", &ruby_generator, ""); - - // Copy generated_code.proto to the temporary test directory. - string test_input; - GOOGLE_CHECK_OK(File::GetContents( - ruby_tests + "/ruby_generated_code.proto", - &test_input, - true)); - GOOGLE_CHECK_OK(File::SetContents( - TestTempDir() + "/ruby_generated_code.proto", - test_input, - true)); - - // Invoke the proto compiler (we will be inside TestTempDir() at this point). - string ruby_out = "--ruby_out=" + TestTempDir(); - string proto_path = "--proto_path=" + TestTempDir(); - const char* argv[] = { - "protoc", - ruby_out.c_str(), - proto_path.c_str(), - "ruby_generated_code.proto", - }; - - EXPECT_EQ(0, cli.Run(4, argv)); - - // Load the generated output and compare to the expected result. - string output; - GOOGLE_CHECK_OK(File::GetContents( - TestTempDir() + "/ruby_generated_code_pb.rb", - &output, - true)); - string expected_output; - GOOGLE_CHECK_OK(File::GetContents( - ruby_tests + "/ruby_generated_code_pb.rb", - &expected_output, - true)); - EXPECT_EQ(expected_output, output); -} - -} // namespace -} // namespace ruby -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/subprocess.cc b/windows/include/google/protobuf/compiler/subprocess.cc deleted file mode 100644 index 2e5a89ac4..000000000 --- a/windows/include/google/protobuf/compiler/subprocess.cc +++ /dev/null @@ -1,473 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) - -#include - -#include -#include -#include - -#ifndef _WIN32 -#include -#include -#include -#include -#endif - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { - -namespace { -char* portable_strdup(const char* s) { - char* ns = (char*) malloc(strlen(s) + 1); - if (ns != NULL) { - strcpy(ns, s); - } - return ns; -} -} // namespace - -#ifdef _WIN32 - -static void CloseHandleOrDie(HANDLE handle) { - if (!CloseHandle(handle)) { - GOOGLE_LOG(FATAL) << "CloseHandle: " - << Subprocess::Win32ErrorMessage(GetLastError()); - } -} - -Subprocess::Subprocess() - : process_start_error_(ERROR_SUCCESS), - child_handle_(NULL), child_stdin_(NULL), child_stdout_(NULL) {} - -Subprocess::~Subprocess() { - if (child_stdin_ != NULL) { - CloseHandleOrDie(child_stdin_); - } - if (child_stdout_ != NULL) { - CloseHandleOrDie(child_stdout_); - } -} - -void Subprocess::Start(const string& program, SearchMode search_mode) { - // Create the pipes. - HANDLE stdin_pipe_read; - HANDLE stdin_pipe_write; - HANDLE stdout_pipe_read; - HANDLE stdout_pipe_write; - - if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, NULL, 0)) { - GOOGLE_LOG(FATAL) << "CreatePipe: " << Win32ErrorMessage(GetLastError()); - } - if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, NULL, 0)) { - GOOGLE_LOG(FATAL) << "CreatePipe: " << Win32ErrorMessage(GetLastError()); - } - - // Make child side of the pipes inheritable. - if (!SetHandleInformation(stdin_pipe_read, - HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) { - GOOGLE_LOG(FATAL) << "SetHandleInformation: " - << Win32ErrorMessage(GetLastError()); - } - if (!SetHandleInformation(stdout_pipe_write, - HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT)) { - GOOGLE_LOG(FATAL) << "SetHandleInformation: " - << Win32ErrorMessage(GetLastError()); - } - - // Setup STARTUPINFO to redirect handles. - STARTUPINFOA startup_info; - ZeroMemory(&startup_info, sizeof(startup_info)); - startup_info.cb = sizeof(startup_info); - startup_info.dwFlags = STARTF_USESTDHANDLES; - startup_info.hStdInput = stdin_pipe_read; - startup_info.hStdOutput = stdout_pipe_write; - startup_info.hStdError = GetStdHandle(STD_ERROR_HANDLE); - - if (startup_info.hStdError == INVALID_HANDLE_VALUE) { - GOOGLE_LOG(FATAL) << "GetStdHandle: " - << Win32ErrorMessage(GetLastError()); - } - - // CreateProcess() mutates its second parameter. WTF? - char* name_copy = portable_strdup(program.c_str()); - - // Create the process. - PROCESS_INFORMATION process_info; - - if (CreateProcessA((search_mode == SEARCH_PATH) ? NULL : program.c_str(), - (search_mode == SEARCH_PATH) ? name_copy : NULL, - NULL, // process security attributes - NULL, // thread security attributes - TRUE, // inherit handles? - 0, // obscure creation flags - NULL, // environment (inherit from parent) - NULL, // current directory (inherit from parent) - &startup_info, - &process_info)) { - child_handle_ = process_info.hProcess; - CloseHandleOrDie(process_info.hThread); - child_stdin_ = stdin_pipe_write; - child_stdout_ = stdout_pipe_read; - } else { - process_start_error_ = GetLastError(); - CloseHandleOrDie(stdin_pipe_write); - CloseHandleOrDie(stdout_pipe_read); - } - - CloseHandleOrDie(stdin_pipe_read); - CloseHandleOrDie(stdout_pipe_write); - free(name_copy); -} - -bool Subprocess::Communicate(const Message& input, Message* output, - string* error) { - if (process_start_error_ != ERROR_SUCCESS) { - *error = Win32ErrorMessage(process_start_error_); - return false; - } - - GOOGLE_CHECK(child_handle_ != NULL) << "Must call Start() first."; - - string input_data = input.SerializeAsString(); - string output_data; - - int input_pos = 0; - - while (child_stdout_ != NULL) { - HANDLE handles[2]; - int handle_count = 0; - - if (child_stdin_ != NULL) { - handles[handle_count++] = child_stdin_; - } - if (child_stdout_ != NULL) { - handles[handle_count++] = child_stdout_; - } - - DWORD wait_result = - WaitForMultipleObjects(handle_count, handles, FALSE, INFINITE); - - HANDLE signaled_handle = NULL; - if (wait_result >= WAIT_OBJECT_0 && - wait_result < WAIT_OBJECT_0 + handle_count) { - signaled_handle = handles[wait_result - WAIT_OBJECT_0]; - } else if (wait_result == WAIT_FAILED) { - GOOGLE_LOG(FATAL) << "WaitForMultipleObjects: " - << Win32ErrorMessage(GetLastError()); - } else { - GOOGLE_LOG(FATAL) << "WaitForMultipleObjects: Unexpected return code: " - << wait_result; - } - - if (signaled_handle == child_stdin_) { - DWORD n; - if (!WriteFile(child_stdin_, - input_data.data() + input_pos, - input_data.size() - input_pos, - &n, NULL)) { - // Child closed pipe. Presumably it will report an error later. - // Pretend we're done for now. - input_pos = input_data.size(); - } else { - input_pos += n; - } - - if (input_pos == input_data.size()) { - // We're done writing. Close. - CloseHandleOrDie(child_stdin_); - child_stdin_ = NULL; - } - } else if (signaled_handle == child_stdout_) { - char buffer[4096]; - DWORD n; - - if (!ReadFile(child_stdout_, buffer, sizeof(buffer), &n, NULL)) { - // We're done reading. Close. - CloseHandleOrDie(child_stdout_); - child_stdout_ = NULL; - } else { - output_data.append(buffer, n); - } - } - } - - if (child_stdin_ != NULL) { - // Child did not finish reading input before it closed the output. - // Presumably it exited with an error. - CloseHandleOrDie(child_stdin_); - child_stdin_ = NULL; - } - - DWORD wait_result = WaitForSingleObject(child_handle_, INFINITE); - - if (wait_result == WAIT_FAILED) { - GOOGLE_LOG(FATAL) << "WaitForSingleObject: " - << Win32ErrorMessage(GetLastError()); - } else if (wait_result != WAIT_OBJECT_0) { - GOOGLE_LOG(FATAL) << "WaitForSingleObject: Unexpected return code: " - << wait_result; - } - - DWORD exit_code; - if (!GetExitCodeProcess(child_handle_, &exit_code)) { - GOOGLE_LOG(FATAL) << "GetExitCodeProcess: " - << Win32ErrorMessage(GetLastError()); - } - - CloseHandleOrDie(child_handle_); - child_handle_ = NULL; - - if (exit_code != 0) { - *error = strings::Substitute( - "Plugin failed with status code $0.", exit_code); - return false; - } - - if (!output->ParseFromString(output_data)) { - *error = "Plugin output is unparseable: " + CEscape(output_data); - return false; - } - - return true; -} - -string Subprocess::Win32ErrorMessage(DWORD error_code) { - char* message; - - // WTF? - FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, error_code, 0, - (LPSTR)&message, // NOT A BUG! - 0, NULL); - - string result = message; - LocalFree(message); - return result; -} - -// =================================================================== - -#else // _WIN32 - -Subprocess::Subprocess() - : child_pid_(-1), child_stdin_(-1), child_stdout_(-1) {} - -Subprocess::~Subprocess() { - if (child_stdin_ != -1) { - close(child_stdin_); - } - if (child_stdout_ != -1) { - close(child_stdout_); - } -} - -void Subprocess::Start(const string& program, SearchMode search_mode) { - // Note that we assume that there are no other threads, thus we don't have to - // do crazy stuff like using socket pairs or avoiding libc locks. - - // [0] is read end, [1] is write end. - int stdin_pipe[2]; - int stdout_pipe[2]; - - GOOGLE_CHECK(pipe(stdin_pipe) != -1); - GOOGLE_CHECK(pipe(stdout_pipe) != -1); - - char* argv[2] = { portable_strdup(program.c_str()), NULL }; - - child_pid_ = fork(); - if (child_pid_ == -1) { - GOOGLE_LOG(FATAL) << "fork: " << strerror(errno); - } else if (child_pid_ == 0) { - // We are the child. - dup2(stdin_pipe[0], STDIN_FILENO); - dup2(stdout_pipe[1], STDOUT_FILENO); - - close(stdin_pipe[0]); - close(stdin_pipe[1]); - close(stdout_pipe[0]); - close(stdout_pipe[1]); - - switch (search_mode) { - case SEARCH_PATH: - execvp(argv[0], argv); - break; - case EXACT_NAME: - execv(argv[0], argv); - break; - } - - // Write directly to STDERR_FILENO to avoid stdio code paths that may do - // stuff that is unsafe here. - int ignored; - ignored = write(STDERR_FILENO, argv[0], strlen(argv[0])); - const char* message = ": program not found or is not executable\n"; - ignored = write(STDERR_FILENO, message, strlen(message)); - (void) ignored; - - // Must use _exit() rather than exit() to avoid flushing output buffers - // that will also be flushed by the parent. - _exit(1); - } else { - free(argv[0]); - - close(stdin_pipe[0]); - close(stdout_pipe[1]); - - child_stdin_ = stdin_pipe[1]; - child_stdout_ = stdout_pipe[0]; - } -} - -bool Subprocess::Communicate(const Message& input, Message* output, - string* error) { - GOOGLE_CHECK_NE(child_stdin_, -1) << "Must call Start() first."; - - // The "sighandler_t" typedef is GNU-specific, so define our own. - typedef void SignalHandler(int); - - // Make sure SIGPIPE is disabled so that if the child dies it doesn't kill us. - SignalHandler* old_pipe_handler = signal(SIGPIPE, SIG_IGN); - - string input_data = input.SerializeAsString(); - string output_data; - - int input_pos = 0; - int max_fd = std::max(child_stdin_, child_stdout_); - - while (child_stdout_ != -1) { - fd_set read_fds; - fd_set write_fds; - FD_ZERO(&read_fds); - FD_ZERO(&write_fds); - if (child_stdout_ != -1) { - FD_SET(child_stdout_, &read_fds); - } - if (child_stdin_ != -1) { - FD_SET(child_stdin_, &write_fds); - } - - if (select(max_fd + 1, &read_fds, &write_fds, NULL, NULL) < 0) { - if (errno == EINTR) { - // Interrupted by signal. Try again. - continue; - } else { - GOOGLE_LOG(FATAL) << "select: " << strerror(errno); - } - } - - if (child_stdin_ != -1 && FD_ISSET(child_stdin_, &write_fds)) { - int n = write(child_stdin_, input_data.data() + input_pos, - input_data.size() - input_pos); - if (n < 0) { - // Child closed pipe. Presumably it will report an error later. - // Pretend we're done for now. - input_pos = input_data.size(); - } else { - input_pos += n; - } - - if (input_pos == input_data.size()) { - // We're done writing. Close. - close(child_stdin_); - child_stdin_ = -1; - } - } - - if (child_stdout_ != -1 && FD_ISSET(child_stdout_, &read_fds)) { - char buffer[4096]; - int n = read(child_stdout_, buffer, sizeof(buffer)); - - if (n > 0) { - output_data.append(buffer, n); - } else { - // We're done reading. Close. - close(child_stdout_); - child_stdout_ = -1; - } - } - } - - if (child_stdin_ != -1) { - // Child did not finish reading input before it closed the output. - // Presumably it exited with an error. - close(child_stdin_); - child_stdin_ = -1; - } - - int status; - while (waitpid(child_pid_, &status, 0) == -1) { - if (errno != EINTR) { - GOOGLE_LOG(FATAL) << "waitpid: " << strerror(errno); - } - } - - // Restore SIGPIPE handling. - signal(SIGPIPE, old_pipe_handler); - - if (WIFEXITED(status)) { - if (WEXITSTATUS(status) != 0) { - int error_code = WEXITSTATUS(status); - *error = strings::Substitute( - "Plugin failed with status code $0.", error_code); - return false; - } - } else if (WIFSIGNALED(status)) { - int signal = WTERMSIG(status); - *error = strings::Substitute( - "Plugin killed by signal $0.", signal); - return false; - } else { - *error = "Neither WEXITSTATUS nor WTERMSIG is true?"; - return false; - } - - if (!output->ParseFromString(output_data)) { - *error = "Plugin output is unparseable: " + CEscape(output_data); - return false; - } - - return true; -} - -#endif // !_WIN32 - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/subprocess.h b/windows/include/google/protobuf/compiler/subprocess.h deleted file mode 100644 index 9d980b060..000000000 --- a/windows/include/google/protobuf/compiler/subprocess.h +++ /dev/null @@ -1,107 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) - -#ifndef GOOGLE_PROTOBUF_COMPILER_SUBPROCESS_H__ -#define GOOGLE_PROTOBUF_COMPILER_SUBPROCESS_H__ - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN // right... -#include -#else // _WIN32 -#include -#include -#endif // !_WIN32 -#include - -#include - -namespace google { -namespace protobuf { - -class Message; - -namespace compiler { - -// Utility class for launching sub-processes. -class LIBPROTOC_EXPORT Subprocess { - public: - Subprocess(); - ~Subprocess(); - - enum SearchMode { - SEARCH_PATH, // Use PATH environment variable. - EXACT_NAME // Program is an exact file name; don't use the PATH. - }; - - // Start the subprocess. Currently we don't provide a way to specify - // arguments as protoc plugins don't have any. - void Start(const string& program, SearchMode search_mode); - - // Serialize the input message and pipe it to the subprocess's stdin, then - // close the pipe. Meanwhile, read from the subprocess's stdout and parse - // the data into *output. All this is done carefully to avoid deadlocks. - // Returns true if successful. On any sort of error, returns false and sets - // *error to a description of the problem. - bool Communicate(const Message& input, Message* output, string* error); - -#ifdef _WIN32 - // Given an error code, returns a human-readable error message. This is - // defined here so that CommandLineInterface can share it. - static string Win32ErrorMessage(DWORD error_code); -#endif - - private: -#ifdef _WIN32 - DWORD process_start_error_; - HANDLE child_handle_; - - // The file handles for our end of the child's pipes. We close each and - // set it to NULL when no longer needed. - HANDLE child_stdin_; - HANDLE child_stdout_; - -#else // _WIN32 - pid_t child_pid_; - - // The file descriptors for our end of the child's pipes. We close each and - // set it to -1 when no longer needed. - int child_stdin_; - int child_stdout_; - -#endif // !_WIN32 -}; - -} // namespace compiler -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_SUBPROCESS_H__ diff --git a/windows/include/google/protobuf/compiler/test_plugin.cc b/windows/include/google/protobuf/compiler/test_plugin.cc deleted file mode 100644 index c676ce8ce..000000000 --- a/windows/include/google/protobuf/compiler/test_plugin.cc +++ /dev/null @@ -1,50 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// -// This is a dummy code generator plugin used by -// command_line_interface_unittest. - -#include -#include -#include -#include - -int main(int argc, char* argv[]) { -#ifdef _MSC_VER - // Don't print a silly message or stick a modal dialog box in my face, - // please. - _set_abort_behavior(0, ~0); -#endif // !_MSC_VER - - google::protobuf::compiler::MockCodeGenerator generator("test_plugin"); - return google::protobuf::compiler::PluginMain(argc, argv, &generator); -} diff --git a/windows/include/google/protobuf/compiler/zip_output_unittest.sh b/windows/include/google/protobuf/compiler/zip_output_unittest.sh deleted file mode 100644 index f85979128..000000000 --- a/windows/include/google/protobuf/compiler/zip_output_unittest.sh +++ /dev/null @@ -1,100 +0,0 @@ -#!/bin/sh -# -# Protocol Buffers - Google's data interchange format -# Copyright 2009 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. - -# Author: kenton@google.com (Kenton Varda) -# -# Test protoc's zip output mode. - -fail() { - echo "$@" >&2 - exit 1 -} - -TEST_TMPDIR=. -PROTOC=./protoc -JAR=jar -UNZIP=unzip - -echo ' - syntax = "proto2"; - option java_multiple_files = true; - option java_package = "test.jar"; - option java_outer_classname = "Outer"; - message Foo {} - message Bar {} -' > $TEST_TMPDIR/testzip.proto - -$PROTOC \ - --cpp_out=$TEST_TMPDIR/testzip.zip --python_out=$TEST_TMPDIR/testzip.zip \ - --java_out=$TEST_TMPDIR/testzip.jar -I$TEST_TMPDIR testzip.proto \ - || fail 'protoc failed.' - -echo "Testing output to zip..." -if $UNZIP -h > /dev/null; then - $UNZIP -t $TEST_TMPDIR/testzip.zip > $TEST_TMPDIR/testzip.list \ - || fail 'unzip failed.' - - grep 'testing: testzip\.pb\.cc *OK$' $TEST_TMPDIR/testzip.list > /dev/null \ - || fail 'testzip.pb.cc not found in output zip.' - grep 'testing: testzip\.pb\.h *OK$' $TEST_TMPDIR/testzip.list > /dev/null \ - || fail 'testzip.pb.h not found in output zip.' - grep 'testing: testzip_pb2\.py *OK$' $TEST_TMPDIR/testzip.list > /dev/null \ - || fail 'testzip_pb2.py not found in output zip.' - grep -i 'manifest' $TEST_TMPDIR/testzip.list > /dev/null \ - && fail 'Zip file contained manifest.' -else - echo "Warning: 'unzip' command not available. Skipping test." -fi - -echo "Testing output to jar..." -if $JAR c $TEST_TMPDIR/testzip.proto > /dev/null; then - $JAR tf $TEST_TMPDIR/testzip.jar > $TEST_TMPDIR/testzip.list \ - || fail 'jar failed.' - - # Check that -interface.jar timestamps are normalized: - if [[ "$(TZ=UTC $JAR tvf $TEST_TMPDIR/testzip.jar)" != *'Tue Jan 01 00:00:00 UTC 1980'* ]]; then - fail 'Zip did not contain normalized timestamps' - fi - - grep '^test/jar/Foo\.java$' $TEST_TMPDIR/testzip.list > /dev/null \ - || fail 'Foo.java not found in output jar.' - grep '^test/jar/Bar\.java$' $TEST_TMPDIR/testzip.list > /dev/null \ - || fail 'Bar.java not found in output jar.' - grep '^test/jar/Outer\.java$' $TEST_TMPDIR/testzip.list > /dev/null \ - || fail 'Outer.java not found in output jar.' - grep '^META-INF/MANIFEST\.MF$' $TEST_TMPDIR/testzip.list > /dev/null \ - || fail 'Manifest not found in output jar.' -else - echo "Warning: 'jar' command not available. Skipping test." -fi - -echo PASS diff --git a/windows/include/google/protobuf/compiler/zip_writer.cc b/windows/include/google/protobuf/compiler/zip_writer.cc deleted file mode 100644 index 1799af6a4..000000000 --- a/windows/include/google/protobuf/compiler/zip_writer.cc +++ /dev/null @@ -1,222 +0,0 @@ -// 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. - -// 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. - -// Author: ambrose@google.com (Ambrose Feinstein), -// kenton@google.com (Kenton Varda) -// -// Based on http://www.pkware.com/documents/casestudies/APPNOTE.TXT - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { - -// January 1, 1980 as a DOS date. -// see https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx -static const uint16 kDosEpoch = 1 << 5 | 1; - -static const uint32 kCRC32Table[256] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, - 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d -}; - -static uint32 ComputeCRC32(const string &buf) { - uint32 x = ~0U; - for (int i = 0; i < buf.size(); ++i) { - unsigned char c = buf[i]; - x = kCRC32Table[(x ^ c) & 0xff] ^ (x >> 8); - } - return ~x; -} - -static void WriteShort(io::CodedOutputStream *out, uint16 val) { - uint8 p[2]; - p[0] = static_cast(val); - p[1] = static_cast(val >> 8); - out->WriteRaw(p, 2); -} - -ZipWriter::ZipWriter(io::ZeroCopyOutputStream* raw_output) - : raw_output_(raw_output) {} -ZipWriter::~ZipWriter() {} - -bool ZipWriter::Write(const string& filename, const string& contents) { - FileInfo info; - - info.name = filename; - uint16 filename_size = filename.size(); - info.offset = raw_output_->ByteCount(); - info.size = contents.size(); - info.crc32 = ComputeCRC32(contents); - - files_.push_back(info); - - // write file header - io::CodedOutputStream output(raw_output_); - output.WriteLittleEndian32(0x04034b50); // magic - WriteShort(&output, 10); // version needed to extract - WriteShort(&output, 0); // flags - WriteShort(&output, 0); // compression method: stored - WriteShort(&output, 0); // last modified time - WriteShort(&output, kDosEpoch); // last modified date - output.WriteLittleEndian32(info.crc32); // crc-32 - output.WriteLittleEndian32(info.size); // compressed size - output.WriteLittleEndian32(info.size); // uncompressed size - WriteShort(&output, filename_size); // file name length - WriteShort(&output, 0); // extra field length - output.WriteString(filename); // file name - output.WriteString(contents); // file data - - return !output.HadError(); -} - -bool ZipWriter::WriteDirectory() { - uint16 num_entries = files_.size(); - uint32 dir_ofs = raw_output_->ByteCount(); - - // write central directory - io::CodedOutputStream output(raw_output_); - for (int i = 0; i < num_entries; ++i) { - const string &filename = files_[i].name; - uint16 filename_size = filename.size(); - uint32 crc32 = files_[i].crc32; - uint32 size = files_[i].size; - uint32 offset = files_[i].offset; - - output.WriteLittleEndian32(0x02014b50); // magic - WriteShort(&output, 10); // version made by - WriteShort(&output, 10); // version needed to extract - WriteShort(&output, 0); // flags - WriteShort(&output, 0); // compression method: stored - WriteShort(&output, 0); // last modified time - WriteShort(&output, kDosEpoch); // last modified date - output.WriteLittleEndian32(crc32); // crc-32 - output.WriteLittleEndian32(size); // compressed size - output.WriteLittleEndian32(size); // uncompressed size - WriteShort(&output, filename_size); // file name length - WriteShort(&output, 0); // extra field length - WriteShort(&output, 0); // file comment length - WriteShort(&output, 0); // starting disk number - WriteShort(&output, 0); // internal file attributes - output.WriteLittleEndian32(0); // external file attributes - output.WriteLittleEndian32(offset); // local header offset - output.WriteString(filename); // file name - } - uint32 dir_len = output.ByteCount(); - - // write end of central directory marker - output.WriteLittleEndian32(0x06054b50); // magic - WriteShort(&output, 0); // disk number - WriteShort(&output, 0); // disk with start of central directory - WriteShort(&output, num_entries); // central directory entries (this disk) - WriteShort(&output, num_entries); // central directory entries (total) - output.WriteLittleEndian32(dir_len); // central directory byte size - output.WriteLittleEndian32(dir_ofs); // central directory offset - WriteShort(&output, 0); // comment length - - return output.HadError(); -} - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/compiler/zip_writer.h b/windows/include/google/protobuf/compiler/zip_writer.h deleted file mode 100644 index 03db4d573..000000000 --- a/windows/include/google/protobuf/compiler/zip_writer.h +++ /dev/null @@ -1,93 +0,0 @@ -// 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. - -// 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. - -// Author: kenton@google.com (Kenton Varda) - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { - -class ZipWriter { - public: - ZipWriter(io::ZeroCopyOutputStream* raw_output); - ~ZipWriter(); - - bool Write(const string& filename, const string& contents); - bool WriteDirectory(); - - private: - struct FileInfo { - string name; - uint32 offset; - uint32 size; - uint32 crc32; - }; - - io::ZeroCopyOutputStream* raw_output_; - std::vector files_; -}; - -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/descriptor.cc b/windows/include/google/protobuf/descriptor.cc deleted file mode 100644 index fc3a9c777..000000000 --- a/windows/include/google/protobuf/descriptor.cc +++ /dev/null @@ -1,7276 +0,0 @@ -// 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#include -#include - -#undef PACKAGE // autoheader #defines this. :( - -namespace google { - -namespace protobuf { - -struct Symbol { - enum Type { - NULL_SYMBOL, - MESSAGE, - FIELD, - ONEOF, - ENUM, - ENUM_VALUE, - SERVICE, - METHOD, - PACKAGE - }; - Type type; - union { - const Descriptor* descriptor; - const FieldDescriptor* field_descriptor; - const OneofDescriptor* oneof_descriptor; - const EnumDescriptor* enum_descriptor; - const EnumValueDescriptor* enum_value_descriptor; - const ServiceDescriptor* service_descriptor; - const MethodDescriptor* method_descriptor; - const FileDescriptor* package_file_descriptor; - }; - - inline Symbol() : type(NULL_SYMBOL) { descriptor = NULL; } - inline bool IsNull() const { return type == NULL_SYMBOL; } - inline bool IsType() const { return type == MESSAGE || type == ENUM; } - inline bool IsAggregate() const { - return type == MESSAGE || type == PACKAGE || type == ENUM || - type == SERVICE; - } - -#define CONSTRUCTOR(TYPE, TYPE_CONSTANT, FIELD) \ - inline explicit Symbol(const TYPE* value) { \ - type = TYPE_CONSTANT; \ - this->FIELD = value; \ - } - - CONSTRUCTOR(Descriptor, MESSAGE, descriptor) - CONSTRUCTOR(FieldDescriptor, FIELD, field_descriptor) - CONSTRUCTOR(OneofDescriptor, ONEOF, oneof_descriptor) - CONSTRUCTOR(EnumDescriptor, ENUM, enum_descriptor) - CONSTRUCTOR(EnumValueDescriptor, ENUM_VALUE, enum_value_descriptor) - CONSTRUCTOR(ServiceDescriptor, SERVICE, service_descriptor) - CONSTRUCTOR(MethodDescriptor, METHOD, method_descriptor) - CONSTRUCTOR(FileDescriptor, PACKAGE, package_file_descriptor) -#undef CONSTRUCTOR - - const FileDescriptor* GetFile() const { - switch (type) { - case NULL_SYMBOL: - return NULL; - case MESSAGE: - return descriptor->file(); - case FIELD: - return field_descriptor->file(); - case ONEOF: - return oneof_descriptor->containing_type()->file(); - case ENUM: - return enum_descriptor->file(); - case ENUM_VALUE: - return enum_value_descriptor->type()->file(); - case SERVICE: - return service_descriptor->file(); - case METHOD: - return method_descriptor->service()->file(); - case PACKAGE: - return package_file_descriptor; - } - return NULL; - } -}; - -const FieldDescriptor::CppType -FieldDescriptor::kTypeToCppTypeMap[MAX_TYPE + 1] = { - static_cast(0), // 0 is reserved for errors - - CPPTYPE_DOUBLE, // TYPE_DOUBLE - CPPTYPE_FLOAT, // TYPE_FLOAT - CPPTYPE_INT64, // TYPE_INT64 - CPPTYPE_UINT64, // TYPE_UINT64 - CPPTYPE_INT32, // TYPE_INT32 - CPPTYPE_UINT64, // TYPE_FIXED64 - CPPTYPE_UINT32, // TYPE_FIXED32 - CPPTYPE_BOOL, // TYPE_BOOL - CPPTYPE_STRING, // TYPE_STRING - CPPTYPE_MESSAGE, // TYPE_GROUP - CPPTYPE_MESSAGE, // TYPE_MESSAGE - CPPTYPE_STRING, // TYPE_BYTES - CPPTYPE_UINT32, // TYPE_UINT32 - CPPTYPE_ENUM, // TYPE_ENUM - CPPTYPE_INT32, // TYPE_SFIXED32 - CPPTYPE_INT64, // TYPE_SFIXED64 - CPPTYPE_INT32, // TYPE_SINT32 - CPPTYPE_INT64, // TYPE_SINT64 -}; - -const char * const FieldDescriptor::kTypeToName[MAX_TYPE + 1] = { - "ERROR", // 0 is reserved for errors - - "double", // TYPE_DOUBLE - "float", // TYPE_FLOAT - "int64", // TYPE_INT64 - "uint64", // TYPE_UINT64 - "int32", // TYPE_INT32 - "fixed64", // TYPE_FIXED64 - "fixed32", // TYPE_FIXED32 - "bool", // TYPE_BOOL - "string", // TYPE_STRING - "group", // TYPE_GROUP - "message", // TYPE_MESSAGE - "bytes", // TYPE_BYTES - "uint32", // TYPE_UINT32 - "enum", // TYPE_ENUM - "sfixed32", // TYPE_SFIXED32 - "sfixed64", // TYPE_SFIXED64 - "sint32", // TYPE_SINT32 - "sint64", // TYPE_SINT64 -}; - -const char * const FieldDescriptor::kCppTypeToName[MAX_CPPTYPE + 1] = { - "ERROR", // 0 is reserved for errors - - "int32", // CPPTYPE_INT32 - "int64", // CPPTYPE_INT64 - "uint32", // CPPTYPE_UINT32 - "uint64", // CPPTYPE_UINT64 - "double", // CPPTYPE_DOUBLE - "float", // CPPTYPE_FLOAT - "bool", // CPPTYPE_BOOL - "enum", // CPPTYPE_ENUM - "string", // CPPTYPE_STRING - "message", // CPPTYPE_MESSAGE -}; - -const char * const FieldDescriptor::kLabelToName[MAX_LABEL + 1] = { - "ERROR", // 0 is reserved for errors - - "optional", // LABEL_OPTIONAL - "required", // LABEL_REQUIRED - "repeated", // LABEL_REPEATED -}; - -const char* FileDescriptor::SyntaxName(FileDescriptor::Syntax syntax) { - switch (syntax) { - case SYNTAX_PROTO2: - return "proto2"; - case SYNTAX_PROTO3: - return "proto3"; - case SYNTAX_UNKNOWN: - return "unknown"; - } - GOOGLE_LOG(FATAL) << "can't reach here."; - return NULL; -} - -static const char * const kNonLinkedWeakMessageReplacementName = "google.protobuf.Empty"; - -#if !defined(_MSC_VER) || _MSC_VER >= 1900 -const int FieldDescriptor::kMaxNumber; -const int FieldDescriptor::kFirstReservedNumber; -const int FieldDescriptor::kLastReservedNumber; -#endif - -namespace { - -// Note: I distrust ctype.h due to locales. -char ToUpper(char ch) { - return (ch >= 'a' && ch <= 'z') ? (ch - 'a' + 'A') : ch; -} - -char ToLower(char ch) { - return (ch >= 'A' && ch <= 'Z') ? (ch - 'A' + 'a') : ch; -} - -string ToCamelCase(const string& input, bool lower_first) { - bool capitalize_next = !lower_first; - string result; - result.reserve(input.size()); - - for (int i = 0; i < input.size(); i++) { - if (input[i] == '_') { - capitalize_next = true; - } else if (capitalize_next) { - result.push_back(ToUpper(input[i])); - capitalize_next = false; - } else { - result.push_back(input[i]); - } - } - - // Lower-case the first letter. - if (lower_first && !result.empty()) { - result[0] = ToLower(result[0]); - } - - return result; -} - -string ToJsonName(const string& input) { - bool capitalize_next = false; - string result; - result.reserve(input.size()); - - for (int i = 0; i < input.size(); i++) { - if (input[i] == '_') { - capitalize_next = true; - } else if (capitalize_next) { - result.push_back(ToUpper(input[i])); - capitalize_next = false; - } else { - result.push_back(input[i]); - } - } - - return result; -} - -string EnumValueToPascalCase(const string& input) { - bool next_upper = true; - string result; - result.reserve(input.size()); - - for (int i = 0; i < input.size(); i++) { - if (input[i] == '_') { - next_upper = true; - } else { - if (next_upper) { - result.push_back(ToUpper(input[i])); - } else { - result.push_back(ToLower(input[i])); - } - next_upper = false; - } - } - - return result; -} - -// Class to remove an enum prefix from enum values. -class PrefixRemover { - public: - PrefixRemover(StringPiece prefix) { - // Strip underscores and lower-case the prefix. - for (int i = 0; i < prefix.size(); i++) { - if (prefix[i] != '_') { - prefix_ += ascii_tolower(prefix[i]); - } - } - } - - // Tries to remove the enum prefix from this enum value. - // If this is not possible, returns the input verbatim. - string MaybeRemove(StringPiece str) { - // We can't just lowercase and strip str and look for a prefix. - // We need to properly recognize the difference between: - // - // enum Foo { - // FOO_BAR_BAZ = 0; - // FOO_BARBAZ = 1; - // } - // - // This is acceptable (though perhaps not advisable) because even when - // we PascalCase, these two will still be distinct (BarBaz vs. Barbaz). - size_t i, j; - - // Skip past prefix_ in str if we can. - for (i = 0, j = 0; i < str.size() && j < prefix_.size(); i++) { - if (str[i] == '_') { - continue; - } - - if (ascii_tolower(str[i]) != prefix_[j++]) { - return string(str); - } - } - - // If we didn't make it through the prefix, we've failed to strip the - // prefix. - if (j < prefix_.size()) { - return string(str); - } - - // Skip underscores between prefix and further characters. - while (i < str.size() && str[i] == '_') { - i++; - } - - // Enum label can't be the empty string. - if (i == str.size()) { - return string(str); - } - - // We successfully stripped the prefix. - str.remove_prefix(i); - return string(str); - } - - private: - string prefix_; -}; - -// A DescriptorPool contains a bunch of hash-maps to implement the -// various Find*By*() methods. Since hashtable lookups are O(1), it's -// most efficient to construct a fixed set of large hash-maps used by -// all objects in the pool rather than construct one or more small -// hash-maps for each object. -// -// The keys to these hash-maps are (parent, name) or (parent, number) pairs. -// -// TODO(kenton): Use StringPiece rather than const char* in keys? It would -// be a lot cleaner but we'd just have to convert it back to const char* -// for the open source release. - -typedef std::pair PointerStringPair; - -struct PointerStringPairEqual { - inline bool operator()(const PointerStringPair& a, - const PointerStringPair& b) const { - return a.first == b.first && strcmp(a.second, b.second) == 0; - } -}; - -typedef std::pair DescriptorIntPair; -typedef std::pair EnumIntPair; - -#define HASH_MAP hash_map -#define HASH_SET hash_set -#define HASH_FXN hash - -template -struct PointerIntegerPairHash { - size_t operator()(const PairType& p) const { - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. - return reinterpret_cast(p.first) * ((1 << 16) - 1) + p.second; - } - -#ifdef _MSC_VER - // Used only by MSVC and platforms where hash_map is not available. - static const size_t bucket_size = 4; - static const size_t min_buckets = 8; -#endif - inline bool operator()(const PairType& a, const PairType& b) const { - return a.first < b.first || - (a.first == b.first && a.second < b.second); - } -}; - -struct PointerStringPairHash { - size_t operator()(const PointerStringPair& p) const { - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. - hash cstring_hash; - return reinterpret_cast(p.first) * ((1 << 16) - 1) + - cstring_hash(p.second); - } - -#ifdef _MSC_VER - // Used only by MSVC and platforms where hash_map is not available. - static const size_t bucket_size = 4; - static const size_t min_buckets = 8; -#endif - inline bool operator()(const PointerStringPair& a, - const PointerStringPair& b) const { - if (a.first < b.first) return true; - if (a.first > b.first) return false; - return strcmp(a.second, b.second) < 0; - } -}; - - -const Symbol kNullSymbol; - -typedef HASH_MAP, streq> - SymbolsByNameMap; - -typedef HASH_MAP - SymbolsByParentMap; - -typedef HASH_MAP, - streq> - FilesByNameMap; - -typedef HASH_MAP - FieldsByNameMap; - -typedef HASH_MAP, - std::equal_to > - FieldsByNumberMap; - -typedef HASH_MAP, - std::equal_to > - EnumValuesByNumberMap; -// This is a map rather than a hash-map, since we use it to iterate -// through all the extensions that extend a given Descriptor, and an -// ordered data structure that implements lower_bound is convenient -// for that. -typedef std::map - ExtensionsGroupedByDescriptorMap; -typedef HASH_MAP LocationsByPathMap; - -std::set* NewAllowedProto3Extendee() { - auto allowed_proto3_extendees = new std::set; - const char* kOptionNames[] = { - "FileOptions", "MessageOptions", "FieldOptions", "EnumOptions", - "EnumValueOptions", "ServiceOptions", "MethodOptions", "OneofOptions"}; - for (int i = 0; i < GOOGLE_ARRAYSIZE(kOptionNames); ++i) { - // descriptor.proto has a different package name in opensource. We allow - // both so the opensource protocol compiler can also compile internal - // proto3 files with custom options. See: b/27567912 - allowed_proto3_extendees->insert(string("google.protobuf.") + - kOptionNames[i]); - // Split the word to trick the opensource processing scripts so they - // will keep the origial package name. - allowed_proto3_extendees->insert(string("proto") + "2." + kOptionNames[i]); - } - return allowed_proto3_extendees; -} - -// Checks whether the extendee type is allowed in proto3. -// Only extensions to descriptor options are allowed. We use name comparison -// instead of comparing the descriptor directly because the extensions may be -// defined in a different pool. -bool AllowedExtendeeInProto3(const string& name) { - static auto allowed_proto3_extendees = - internal::OnShutdownDelete(NewAllowedProto3Extendee()); - return allowed_proto3_extendees->find(name) != - allowed_proto3_extendees->end(); -} - -} // anonymous namespace - -// =================================================================== -// DescriptorPool::Tables - -class DescriptorPool::Tables { - public: - Tables(); - ~Tables(); - - // Record the current state of the tables to the stack of checkpoints. - // Each call to AddCheckpoint() must be paired with exactly one call to either - // ClearLastCheckpoint() or RollbackToLastCheckpoint(). - // - // This is used when building files, since some kinds of validation errors - // cannot be detected until the file's descriptors have already been added to - // the tables. - // - // This supports recursive checkpoints, since building a file may trigger - // recursive building of other files. Note that recursive checkpoints are not - // normally necessary; explicit dependencies are built prior to checkpointing. - // So although we recursively build transitive imports, there is at most one - // checkpoint in the stack during dependency building. - // - // Recursive checkpoints only arise during cross-linking of the descriptors. - // Symbol references must be resolved, via DescriptorBuilder::FindSymbol and - // friends. If the pending file references an unknown symbol - // (e.g., it is not defined in the pending file's explicit dependencies), and - // the pool is using a fallback database, and that database contains a file - // defining that symbol, and that file has not yet been built by the pool, - // the pool builds the file during cross-linking, leading to another - // checkpoint. - void AddCheckpoint(); - - // Mark the last checkpoint as having cleared successfully, removing it from - // the stack. If the stack is empty, all pending symbols will be committed. - // - // Note that this does not guarantee that the symbols added since the last - // checkpoint won't be rolled back: if a checkpoint gets rolled back, - // everything past that point gets rolled back, including symbols added after - // checkpoints that were pushed onto the stack after it and marked as cleared. - void ClearLastCheckpoint(); - - // Roll back the Tables to the state of the checkpoint at the top of the - // stack, removing everything that was added after that point. - void RollbackToLastCheckpoint(); - - // The stack of files which are currently being built. Used to detect - // cyclic dependencies when loading files from a DescriptorDatabase. Not - // used when fallback_database_ == NULL. - std::vector pending_files_; - - // A set of files which we have tried to load from the fallback database - // and encountered errors. We will not attempt to load them again during - // execution of the current public API call, but for compatibility with - // legacy clients, this is cleared at the beginning of each public API call. - // Not used when fallback_database_ == NULL. - HASH_SET known_bad_files_; - - // A set of symbols which we have tried to load from the fallback database - // and encountered errors. We will not attempt to load them again during - // execution of the current public API call, but for compatibility with - // legacy clients, this is cleared at the beginning of each public API call. - HASH_SET known_bad_symbols_; - - // The set of descriptors for which we've already loaded the full - // set of extensions numbers from fallback_database_. - HASH_SET extensions_loaded_from_db_; - - // ----------------------------------------------------------------- - // Finding items. - - // Find symbols. This returns a null Symbol (symbol.IsNull() is true) - // if not found. - inline Symbol FindSymbol(const string& key) const; - - // This implements the body of DescriptorPool::Find*ByName(). It should - // really be a private method of DescriptorPool, but that would require - // declaring Symbol in descriptor.h, which would drag all kinds of other - // stuff into the header. Yay C++. - Symbol FindByNameHelper( - const DescriptorPool* pool, const string& name); - - // These return NULL if not found. - inline const FileDescriptor* FindFile(const string& key) const; - inline const FieldDescriptor* FindExtension(const Descriptor* extendee, - int number) const; - inline void FindAllExtensions(const Descriptor* extendee, - std::vector* out) const; - - // ----------------------------------------------------------------- - // Adding items. - - // These add items to the corresponding tables. They return false if - // the key already exists in the table. For AddSymbol(), the string passed - // in must be one that was constructed using AllocateString(), as it will - // be used as a key in the symbols_by_name_ map without copying. - bool AddSymbol(const string& full_name, Symbol symbol); - bool AddFile(const FileDescriptor* file); - bool AddExtension(const FieldDescriptor* field); - - // ----------------------------------------------------------------- - // Allocating memory. - - // Allocate an object which will be reclaimed when the pool is - // destroyed. Note that the object's destructor will never be called, - // so its fields must be plain old data (primitive data types and - // pointers). All of the descriptor types are such objects. - template Type* Allocate(); - - // Allocate an array of objects which will be reclaimed when the - // pool in destroyed. Again, destructors are never called. - template Type* AllocateArray(int count); - - // Allocate a string which will be destroyed when the pool is destroyed. - // The string is initialized to the given value for convenience. - string* AllocateString(const string& value); - - // Allocate a GoogleOnceDynamic which will be destroyed when the pool is - // destroyed. - GoogleOnceDynamic* AllocateOnceDynamic(); - - // Allocate a protocol message object. Some older versions of GCC have - // trouble understanding explicit template instantiations in some cases, so - // in those cases we have to pass a dummy pointer of the right type as the - // parameter instead of specifying the type explicitly. - template Type* AllocateMessage(Type* dummy = NULL); - - // Allocate a FileDescriptorTables object. - FileDescriptorTables* AllocateFileTables(); - - private: - std::vector strings_; // All strings in the pool. - std::vector messages_; // All messages in the pool. - std::vector - once_dynamics_; // All GoogleOnceDynamics in the pool. - std::vector - file_tables_; // All file tables in the pool. - std::vector allocations_; // All other memory allocated in the pool. - - SymbolsByNameMap symbols_by_name_; - FilesByNameMap files_by_name_; - ExtensionsGroupedByDescriptorMap extensions_; - - struct CheckPoint { - explicit CheckPoint(const Tables* tables) - : strings_before_checkpoint(tables->strings_.size()), - messages_before_checkpoint(tables->messages_.size()), - once_dynamics_before_checkpoint(tables->once_dynamics_.size()), - file_tables_before_checkpoint(tables->file_tables_.size()), - allocations_before_checkpoint(tables->allocations_.size()), - pending_symbols_before_checkpoint( - tables->symbols_after_checkpoint_.size()), - pending_files_before_checkpoint( - tables->files_after_checkpoint_.size()), - pending_extensions_before_checkpoint( - tables->extensions_after_checkpoint_.size()) {} - int strings_before_checkpoint; - int messages_before_checkpoint; - int once_dynamics_before_checkpoint; - int file_tables_before_checkpoint; - int allocations_before_checkpoint; - int pending_symbols_before_checkpoint; - int pending_files_before_checkpoint; - int pending_extensions_before_checkpoint; - }; - std::vector checkpoints_; - std::vector symbols_after_checkpoint_; - std::vector files_after_checkpoint_; - std::vector extensions_after_checkpoint_; - - // Allocate some bytes which will be reclaimed when the pool is - // destroyed. - void* AllocateBytes(int size); -}; - -// Contains tables specific to a particular file. These tables are not -// modified once the file has been constructed, so they need not be -// protected by a mutex. This makes operations that depend only on the -// contents of a single file -- e.g. Descriptor::FindFieldByName() -- -// lock-free. -// -// For historical reasons, the definitions of the methods of -// FileDescriptorTables and DescriptorPool::Tables are interleaved below. -// These used to be a single class. -class FileDescriptorTables { - public: - FileDescriptorTables(); - ~FileDescriptorTables(); - - // Empty table, used with placeholder files. - inline static const FileDescriptorTables& GetEmptyInstance(); - - // ----------------------------------------------------------------- - // Finding items. - - // Find symbols. These return a null Symbol (symbol.IsNull() is true) - // if not found. - inline Symbol FindNestedSymbol(const void* parent, - const string& name) const; - inline Symbol FindNestedSymbolOfType(const void* parent, - const string& name, - const Symbol::Type type) const; - - // These return NULL if not found. - inline const FieldDescriptor* FindFieldByNumber( - const Descriptor* parent, int number) const; - inline const FieldDescriptor* FindFieldByLowercaseName( - const void* parent, const string& lowercase_name) const; - inline const FieldDescriptor* FindFieldByCamelcaseName( - const void* parent, const string& camelcase_name) const; - inline const EnumValueDescriptor* FindEnumValueByNumber( - const EnumDescriptor* parent, int number) const; - // This creates a new EnumValueDescriptor if not found, in a thread-safe way. - inline const EnumValueDescriptor* FindEnumValueByNumberCreatingIfUnknown( - const EnumDescriptor* parent, int number) const; - - // ----------------------------------------------------------------- - // Adding items. - - // These add items to the corresponding tables. They return false if - // the key already exists in the table. For AddAliasUnderParent(), the - // string passed in must be one that was constructed using AllocateString(), - // as it will be used as a key in the symbols_by_parent_ map without copying. - bool AddAliasUnderParent(const void* parent, const string& name, - Symbol symbol); - bool AddFieldByNumber(const FieldDescriptor* field); - bool AddEnumValueByNumber(const EnumValueDescriptor* value); - - // Adds the field to the lowercase_name and camelcase_name maps. Never - // fails because we allow duplicates; the first field by the name wins. - void AddFieldByStylizedNames(const FieldDescriptor* field); - - // Populates p->first->locations_by_path_ from p->second. - // Unusual signature dictated by GoogleOnceDynamic. - static void BuildLocationsByPath( - std::pair* p); - - // Returns the location denoted by the specified path through info, - // or NULL if not found. - // The value of info must be that of the corresponding FileDescriptor. - // (Conceptually a pure function, but stateful as an optimisation.) - const SourceCodeInfo_Location* GetSourceLocation( - const std::vector& path, const SourceCodeInfo* info) const; - - // Must be called after BuildFileImpl(), even if the build failed and - // we are going to roll back to the last checkpoint. - void FinalizeTables(); - - private: - const void* FindParentForFieldsByMap(const FieldDescriptor* field) const; - static void FieldsByLowercaseNamesLazyInitStatic( - const FileDescriptorTables* tables); - void FieldsByLowercaseNamesLazyInitInternal() const; - static void FieldsByCamelcaseNamesLazyInitStatic( - const FileDescriptorTables* tables); - void FieldsByCamelcaseNamesLazyInitInternal() const; - - SymbolsByParentMap symbols_by_parent_; - mutable FieldsByNameMap fields_by_lowercase_name_; - std::unique_ptr fields_by_lowercase_name_tmp_; - mutable GoogleOnceDynamic fields_by_lowercase_name_once_; - mutable FieldsByNameMap fields_by_camelcase_name_; - std::unique_ptr fields_by_camelcase_name_tmp_; - mutable GoogleOnceDynamic fields_by_camelcase_name_once_; - FieldsByNumberMap fields_by_number_; // Not including extensions. - EnumValuesByNumberMap enum_values_by_number_; - mutable EnumValuesByNumberMap unknown_enum_values_by_number_ - GOOGLE_GUARDED_BY(unknown_enum_values_mu_); - - // Populated on first request to save space, hence constness games. - mutable GoogleOnceDynamic locations_by_path_once_; - mutable LocationsByPathMap locations_by_path_; - - // Mutex to protect the unknown-enum-value map due to dynamic - // EnumValueDescriptor creation on unknown values. - mutable Mutex unknown_enum_values_mu_; -}; - -DescriptorPool::Tables::Tables() - // Start some hash-map and hash-set objects with a small # of buckets - : known_bad_files_(3), - known_bad_symbols_(3), - extensions_loaded_from_db_(3), - symbols_by_name_(3), - files_by_name_(3) {} - -DescriptorPool::Tables::~Tables() { - GOOGLE_DCHECK(checkpoints_.empty()); - // Note that the deletion order is important, since the destructors of some - // messages may refer to objects in allocations_. - STLDeleteElements(&messages_); - for (int i = 0; i < allocations_.size(); i++) { - operator delete(allocations_[i]); - } - STLDeleteElements(&strings_); - STLDeleteElements(&file_tables_); - STLDeleteElements(&once_dynamics_); -} - -FileDescriptorTables::FileDescriptorTables() - // Initialize all the hash tables to start out with a small # of buckets. - : symbols_by_parent_(3), - fields_by_lowercase_name_(3), - fields_by_lowercase_name_tmp_(new FieldsByNameMap()), - fields_by_camelcase_name_(3), - fields_by_camelcase_name_tmp_(new FieldsByNameMap()), - fields_by_number_(3), - enum_values_by_number_(3), - unknown_enum_values_by_number_(3), - locations_by_path_(3) {} - -FileDescriptorTables::~FileDescriptorTables() {} - -inline const FileDescriptorTables& FileDescriptorTables::GetEmptyInstance() { - static auto file_descriptor_tables = - internal::OnShutdownDelete(new FileDescriptorTables()); - return *file_descriptor_tables; -} - -void DescriptorPool::Tables::AddCheckpoint() { - checkpoints_.push_back(CheckPoint(this)); -} - -void DescriptorPool::Tables::ClearLastCheckpoint() { - GOOGLE_DCHECK(!checkpoints_.empty()); - checkpoints_.pop_back(); - if (checkpoints_.empty()) { - // All checkpoints have been cleared: we can now commit all of the pending - // data. - symbols_after_checkpoint_.clear(); - files_after_checkpoint_.clear(); - extensions_after_checkpoint_.clear(); - } -} - -void DescriptorPool::Tables::RollbackToLastCheckpoint() { - GOOGLE_DCHECK(!checkpoints_.empty()); - const CheckPoint& checkpoint = checkpoints_.back(); - - for (int i = checkpoint.pending_symbols_before_checkpoint; - i < symbols_after_checkpoint_.size(); - i++) { - symbols_by_name_.erase(symbols_after_checkpoint_[i]); - } - for (int i = checkpoint.pending_files_before_checkpoint; - i < files_after_checkpoint_.size(); - i++) { - files_by_name_.erase(files_after_checkpoint_[i]); - } - for (int i = checkpoint.pending_extensions_before_checkpoint; - i < extensions_after_checkpoint_.size(); - i++) { - extensions_.erase(extensions_after_checkpoint_[i]); - } - - symbols_after_checkpoint_.resize( - checkpoint.pending_symbols_before_checkpoint); - files_after_checkpoint_.resize(checkpoint.pending_files_before_checkpoint); - extensions_after_checkpoint_.resize( - checkpoint.pending_extensions_before_checkpoint); - - STLDeleteContainerPointers( - strings_.begin() + checkpoint.strings_before_checkpoint, strings_.end()); - STLDeleteContainerPointers( - messages_.begin() + checkpoint.messages_before_checkpoint, - messages_.end()); - STLDeleteContainerPointers( - once_dynamics_.begin() + checkpoint.once_dynamics_before_checkpoint, - once_dynamics_.end()); - STLDeleteContainerPointers( - file_tables_.begin() + checkpoint.file_tables_before_checkpoint, - file_tables_.end()); - for (int i = checkpoint.allocations_before_checkpoint; - i < allocations_.size(); - i++) { - operator delete(allocations_[i]); - } - - strings_.resize(checkpoint.strings_before_checkpoint); - messages_.resize(checkpoint.messages_before_checkpoint); - once_dynamics_.resize(checkpoint.once_dynamics_before_checkpoint); - file_tables_.resize(checkpoint.file_tables_before_checkpoint); - allocations_.resize(checkpoint.allocations_before_checkpoint); - checkpoints_.pop_back(); -} - -// ------------------------------------------------------------------- - -inline Symbol DescriptorPool::Tables::FindSymbol(const string& key) const { - const Symbol* result = FindOrNull(symbols_by_name_, key.c_str()); - if (result == NULL) { - return kNullSymbol; - } else { - return *result; - } -} - -inline Symbol FileDescriptorTables::FindNestedSymbol( - const void* parent, const string& name) const { - const Symbol* result = - FindOrNull(symbols_by_parent_, PointerStringPair(parent, name.c_str())); - if (result == NULL) { - return kNullSymbol; - } else { - return *result; - } -} - -inline Symbol FileDescriptorTables::FindNestedSymbolOfType( - const void* parent, const string& name, const Symbol::Type type) const { - Symbol result = FindNestedSymbol(parent, name); - if (result.type != type) return kNullSymbol; - return result; -} - -Symbol DescriptorPool::Tables::FindByNameHelper( - const DescriptorPool* pool, const string& name) { - MutexLockMaybe lock(pool->mutex_); - if (pool->fallback_database_ != NULL) { - known_bad_symbols_.clear(); - known_bad_files_.clear(); - } - Symbol result = FindSymbol(name); - - if (result.IsNull() && pool->underlay_ != NULL) { - // Symbol not found; check the underlay. - result = - pool->underlay_->tables_->FindByNameHelper(pool->underlay_, name); - } - - if (result.IsNull()) { - // Symbol still not found, so check fallback database. - if (pool->TryFindSymbolInFallbackDatabase(name)) { - result = FindSymbol(name); - } - } - - return result; -} - -inline const FileDescriptor* DescriptorPool::Tables::FindFile( - const string& key) const { - return FindPtrOrNull(files_by_name_, key.c_str()); -} - -inline const FieldDescriptor* FileDescriptorTables::FindFieldByNumber( - const Descriptor* parent, int number) const { - return FindPtrOrNull(fields_by_number_, std::make_pair(parent, number)); -} - -const void* FileDescriptorTables::FindParentForFieldsByMap( - const FieldDescriptor* field) const { - if (field->is_extension()) { - if (field->extension_scope() == NULL) { - return field->file(); - } else { - return field->extension_scope(); - } - } else { - return field->containing_type(); - } -} - -void FileDescriptorTables::FieldsByLowercaseNamesLazyInitStatic( - const FileDescriptorTables* tables) { - tables->FieldsByLowercaseNamesLazyInitInternal(); -} - -void FileDescriptorTables::FieldsByLowercaseNamesLazyInitInternal() const { - for (FieldsByNumberMap::const_iterator it = fields_by_number_.begin(); - it != fields_by_number_.end(); it++) { - PointerStringPair lowercase_key(FindParentForFieldsByMap(it->second), - it->second->lowercase_name().c_str()); - InsertIfNotPresent(&fields_by_lowercase_name_, lowercase_key, it->second); - } -} - -inline const FieldDescriptor* FileDescriptorTables::FindFieldByLowercaseName( - const void* parent, const string& lowercase_name) const { - fields_by_lowercase_name_once_.Init( - &FileDescriptorTables::FieldsByLowercaseNamesLazyInitStatic, this); - return FindPtrOrNull(fields_by_lowercase_name_, - PointerStringPair(parent, lowercase_name.c_str())); -} - -void FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic( - const FileDescriptorTables* tables) { - tables->FieldsByCamelcaseNamesLazyInitInternal(); -} - -void FileDescriptorTables::FieldsByCamelcaseNamesLazyInitInternal() const { - for (FieldsByNumberMap::const_iterator it = fields_by_number_.begin(); - it != fields_by_number_.end(); it++) { - PointerStringPair camelcase_key(FindParentForFieldsByMap(it->second), - it->second->camelcase_name().c_str()); - InsertIfNotPresent(&fields_by_camelcase_name_, camelcase_key, it->second); - } -} - -inline const FieldDescriptor* FileDescriptorTables::FindFieldByCamelcaseName( - const void* parent, const string& camelcase_name) const { - fields_by_camelcase_name_once_.Init( - &FileDescriptorTables::FieldsByCamelcaseNamesLazyInitStatic, this); - return FindPtrOrNull(fields_by_camelcase_name_, - PointerStringPair(parent, camelcase_name.c_str())); -} - -inline const EnumValueDescriptor* FileDescriptorTables::FindEnumValueByNumber( - const EnumDescriptor* parent, int number) const { - return FindPtrOrNull(enum_values_by_number_, std::make_pair(parent, number)); -} - -inline const EnumValueDescriptor* -FileDescriptorTables::FindEnumValueByNumberCreatingIfUnknown( - const EnumDescriptor* parent, int number) const { - // First try, with map of compiled-in values. - { - const EnumValueDescriptor* desc = - FindPtrOrNull(enum_values_by_number_, std::make_pair(parent, number)); - if (desc != NULL) { - return desc; - } - } - // Second try, with reader lock held on unknown enum values: common case. - { - ReaderMutexLock l(&unknown_enum_values_mu_); - const EnumValueDescriptor* desc = FindPtrOrNull( - unknown_enum_values_by_number_, std::make_pair(parent, number)); - if (desc != NULL) { - return desc; - } - } - // If not found, try again with writer lock held, and create new descriptor if - // necessary. - { - WriterMutexLock l(&unknown_enum_values_mu_); - const EnumValueDescriptor* desc = FindPtrOrNull( - unknown_enum_values_by_number_, std::make_pair(parent, number)); - if (desc != NULL) { - return desc; - } - - // Create an EnumValueDescriptor dynamically. We don't insert it into the - // 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. - string enum_value_name = StringPrintf( - "UNKNOWN_ENUM_VALUE_%s_%d", parent->name().c_str(), number); - DescriptorPool::Tables* tables = - const_cast(DescriptorPool::generated_pool()-> - tables_.get()); - EnumValueDescriptor* result = tables->Allocate(); - result->name_ = tables->AllocateString(enum_value_name); - result->full_name_ = tables->AllocateString(parent->full_name() + - "." + enum_value_name); - result->number_ = number; - result->type_ = parent; - result->options_ = &EnumValueOptions::default_instance(); - InsertIfNotPresent(&unknown_enum_values_by_number_, - std::make_pair(parent, number), result); - return result; - } -} - - -inline const FieldDescriptor* DescriptorPool::Tables::FindExtension( - const Descriptor* extendee, int number) const { - return FindPtrOrNull(extensions_, std::make_pair(extendee, number)); -} - -inline void DescriptorPool::Tables::FindAllExtensions( - const Descriptor* extendee, - std::vector* out) const { - ExtensionsGroupedByDescriptorMap::const_iterator it = - extensions_.lower_bound(std::make_pair(extendee, 0)); - for (; it != extensions_.end() && it->first.first == extendee; ++it) { - out->push_back(it->second); - } -} - -// ------------------------------------------------------------------- - -bool DescriptorPool::Tables::AddSymbol( - const string& full_name, Symbol symbol) { - if (InsertIfNotPresent(&symbols_by_name_, full_name.c_str(), symbol)) { - symbols_after_checkpoint_.push_back(full_name.c_str()); - return true; - } else { - return false; - } -} - -bool FileDescriptorTables::AddAliasUnderParent( - const void* parent, const string& name, Symbol symbol) { - PointerStringPair by_parent_key(parent, name.c_str()); - return InsertIfNotPresent(&symbols_by_parent_, by_parent_key, symbol); -} - -bool DescriptorPool::Tables::AddFile(const FileDescriptor* file) { - if (InsertIfNotPresent(&files_by_name_, file->name().c_str(), file)) { - files_after_checkpoint_.push_back(file->name().c_str()); - return true; - } else { - return false; - } -} - -void FileDescriptorTables::FinalizeTables() { - // Clean up the temporary maps used by AddFieldByStylizedNames(). - fields_by_lowercase_name_tmp_ = nullptr; - fields_by_camelcase_name_tmp_ = nullptr; -} - -void FileDescriptorTables::AddFieldByStylizedNames( - const FieldDescriptor* field) { - const void* parent = FindParentForFieldsByMap(field); - - // We want fields_by_{lower,camel}case_name_ to be lazily built, but - // cross-link order determines which entry will be present in the case of a - // conflict. So we use the temporary maps that get destroyed after - // BuildFileImpl() to detect the conflicts, and only store the conflicts in - // the map that will persist. We will then lazily populate the rest of the - // entries from fields_by_number_. - - PointerStringPair lowercase_key(parent, field->lowercase_name().c_str()); - if (!InsertIfNotPresent(fields_by_lowercase_name_tmp_.get(), lowercase_key, - field)) { - InsertIfNotPresent( - &fields_by_lowercase_name_, lowercase_key, - FindPtrOrNull(*fields_by_lowercase_name_tmp_, lowercase_key)); - } - - PointerStringPair camelcase_key(parent, field->camelcase_name().c_str()); - if (!InsertIfNotPresent(fields_by_camelcase_name_tmp_.get(), camelcase_key, - field)) { - InsertIfNotPresent( - &fields_by_camelcase_name_, camelcase_key, - FindPtrOrNull(*fields_by_camelcase_name_tmp_, camelcase_key)); - } -} - -bool FileDescriptorTables::AddFieldByNumber(const FieldDescriptor* field) { - DescriptorIntPair key(field->containing_type(), field->number()); - return InsertIfNotPresent(&fields_by_number_, key, field); -} - -bool FileDescriptorTables::AddEnumValueByNumber( - const EnumValueDescriptor* value) { - EnumIntPair key(value->type(), value->number()); - return InsertIfNotPresent(&enum_values_by_number_, key, value); -} - -bool DescriptorPool::Tables::AddExtension(const FieldDescriptor* field) { - DescriptorIntPair key(field->containing_type(), field->number()); - if (InsertIfNotPresent(&extensions_, key, field)) { - extensions_after_checkpoint_.push_back(key); - return true; - } else { - return false; - } -} - -// ------------------------------------------------------------------- - -template -Type* DescriptorPool::Tables::Allocate() { - return reinterpret_cast(AllocateBytes(sizeof(Type))); -} - -template -Type* DescriptorPool::Tables::AllocateArray(int count) { - return reinterpret_cast(AllocateBytes(sizeof(Type) * count)); -} - -string* DescriptorPool::Tables::AllocateString(const string& value) { - string* result = new string(value); - strings_.push_back(result); - return result; -} - -GoogleOnceDynamic* DescriptorPool::Tables::AllocateOnceDynamic() { - GoogleOnceDynamic* result = new GoogleOnceDynamic(); - once_dynamics_.push_back(result); - return result; -} - -template -Type* DescriptorPool::Tables::AllocateMessage(Type* /* dummy */) { - Type* result = new Type; - messages_.push_back(result); - return result; -} - -FileDescriptorTables* DescriptorPool::Tables::AllocateFileTables() { - FileDescriptorTables* result = new FileDescriptorTables; - file_tables_.push_back(result); - return result; -} - -void* DescriptorPool::Tables::AllocateBytes(int size) { - // TODO(kenton): Would it be worthwhile to implement this in some more - // sophisticated way? Probably not for the open source release, but for - // internal use we could easily plug in one of our existing memory pool - // allocators... - if (size == 0) return NULL; - - void* result = operator new(size); - allocations_.push_back(result); - return result; -} - -void FileDescriptorTables::BuildLocationsByPath( - std::pair* p) { - for (int i = 0, len = p->second->location_size(); i < len; ++i) { - const SourceCodeInfo_Location* loc = &p->second->location().Get(i); - p->first->locations_by_path_[Join(loc->path(), ",")] = loc; - } -} - -const SourceCodeInfo_Location* FileDescriptorTables::GetSourceLocation( - const std::vector& path, const SourceCodeInfo* info) const { - std::pair p( - std::make_pair(this, info)); - locations_by_path_once_.Init(&FileDescriptorTables::BuildLocationsByPath, &p); - return FindPtrOrNull(locations_by_path_, Join(path, ",")); -} - -// =================================================================== -// DescriptorPool - -DescriptorPool::ErrorCollector::~ErrorCollector() {} - -DescriptorPool::DescriptorPool() - : mutex_(NULL), - fallback_database_(NULL), - default_error_collector_(NULL), - underlay_(NULL), - tables_(new Tables), - enforce_dependencies_(true), - lazily_build_dependencies_(false), - allow_unknown_(false), - enforce_weak_(false), - disallow_enforce_utf8_(false) {} - -DescriptorPool::DescriptorPool(DescriptorDatabase* fallback_database, - ErrorCollector* error_collector) - : mutex_(new Mutex), - fallback_database_(fallback_database), - default_error_collector_(error_collector), - underlay_(NULL), - tables_(new Tables), - enforce_dependencies_(true), - lazily_build_dependencies_(false), - allow_unknown_(false), - enforce_weak_(false), - disallow_enforce_utf8_(false) { -} - -DescriptorPool::DescriptorPool(const DescriptorPool* underlay) - : mutex_(NULL), - fallback_database_(NULL), - default_error_collector_(NULL), - underlay_(underlay), - tables_(new Tables), - enforce_dependencies_(true), - lazily_build_dependencies_(false), - allow_unknown_(false), - enforce_weak_(false), - disallow_enforce_utf8_(false) {} - -DescriptorPool::~DescriptorPool() { - if (mutex_ != NULL) delete mutex_; -} - -// DescriptorPool::BuildFile() defined later. -// DescriptorPool::BuildFileCollectingErrors() defined later. - -void DescriptorPool::InternalDontEnforceDependencies() { - enforce_dependencies_ = false; -} - -void DescriptorPool::AddUnusedImportTrackFile(const string& file_name) { - unused_import_track_files_.insert(file_name); -} - -void DescriptorPool::ClearUnusedImportTrackFiles() { - unused_import_track_files_.clear(); -} - -bool DescriptorPool::InternalIsFileLoaded(const string& filename) const { - MutexLockMaybe lock(mutex_); - return tables_->FindFile(filename) != NULL; -} - -// generated_pool ==================================================== - -namespace { - -EncodedDescriptorDatabase* GeneratedDatabase() { - static auto generated_database = - internal::OnShutdownDelete(new EncodedDescriptorDatabase()); - return generated_database; -} - -DescriptorPool* NewGeneratedPool() { - auto generated_pool = new DescriptorPool(GeneratedDatabase()); - generated_pool->InternalSetLazilyBuildDependencies(); - return generated_pool; -} - -} // anonymous namespace - -DescriptorPool* DescriptorPool::internal_generated_pool() { - static DescriptorPool* generated_pool = - internal::OnShutdownDelete(NewGeneratedPool()); - return generated_pool; -} - -const DescriptorPool* DescriptorPool::generated_pool() { - return internal_generated_pool(); -} - -void DescriptorPool::InternalAddGeneratedFile( - const void* encoded_file_descriptor, int size) { - // So, this function is called in the process of initializing the - // descriptors for generated proto classes. Each generated .pb.cc file - // has an internal procedure called AddDescriptors() which is called at - // process startup, and that function calls this one in order to register - // the raw bytes of the FileDescriptorProto representing the file. - // - // We do not actually construct the descriptor objects right away. We just - // hang on to the bytes until they are actually needed. We actually construct - // the descriptor the first time one of the following things happens: - // * Someone calls a method like descriptor(), GetDescriptor(), or - // GetReflection() on the generated types, which requires returning the - // descriptor or an object based on it. - // * Someone looks up the descriptor in DescriptorPool::generated_pool(). - // - // Once one of these happens, the DescriptorPool actually parses the - // FileDescriptorProto and generates a FileDescriptor (and all its children) - // based on it. - // - // Note that FileDescriptorProto is itself a generated protocol message. - // Therefore, when we parse one, we have to be very careful to avoid using - // any descriptor-based operations, since this might cause infinite recursion - // or deadlock. - GOOGLE_CHECK(GeneratedDatabase()->Add(encoded_file_descriptor, size)); -} - - -// Find*By* methods ================================================== - -// TODO(kenton): There's a lot of repeated code here, but I'm not sure if -// there's any good way to factor it out. Think about this some time when -// there's nothing more important to do (read: never). - -const FileDescriptor* DescriptorPool::FindFileByName(const string& name) const { - MutexLockMaybe lock(mutex_); - if (fallback_database_ != NULL) { - tables_->known_bad_symbols_.clear(); - tables_->known_bad_files_.clear(); - } - const FileDescriptor* result = tables_->FindFile(name); - if (result != NULL) return result; - if (underlay_ != NULL) { - result = underlay_->FindFileByName(name); - if (result != NULL) return result; - } - if (TryFindFileInFallbackDatabase(name)) { - result = tables_->FindFile(name); - if (result != NULL) return result; - } - return NULL; -} - -const FileDescriptor* DescriptorPool::FindFileContainingSymbol( - const string& symbol_name) const { - MutexLockMaybe lock(mutex_); - if (fallback_database_ != NULL) { - tables_->known_bad_symbols_.clear(); - tables_->known_bad_files_.clear(); - } - Symbol result = tables_->FindSymbol(symbol_name); - if (!result.IsNull()) return result.GetFile(); - if (underlay_ != NULL) { - const FileDescriptor* file_result = - underlay_->FindFileContainingSymbol(symbol_name); - if (file_result != NULL) return file_result; - } - if (TryFindSymbolInFallbackDatabase(symbol_name)) { - result = tables_->FindSymbol(symbol_name); - if (!result.IsNull()) return result.GetFile(); - } - return NULL; -} - -const Descriptor* DescriptorPool::FindMessageTypeByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::MESSAGE) ? result.descriptor : NULL; -} - -const FieldDescriptor* DescriptorPool::FindFieldByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - if (result.type == Symbol::FIELD && - !result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* DescriptorPool::FindExtensionByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - if (result.type == Symbol::FIELD && - result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const OneofDescriptor* DescriptorPool::FindOneofByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::ONEOF) ? result.oneof_descriptor : NULL; -} - -const EnumDescriptor* DescriptorPool::FindEnumTypeByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::ENUM) ? result.enum_descriptor : NULL; -} - -const EnumValueDescriptor* DescriptorPool::FindEnumValueByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::ENUM_VALUE) ? - result.enum_value_descriptor : NULL; -} - -const ServiceDescriptor* DescriptorPool::FindServiceByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::SERVICE) ? result.service_descriptor : NULL; -} - -const MethodDescriptor* DescriptorPool::FindMethodByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::METHOD) ? result.method_descriptor : NULL; -} - -const FieldDescriptor* DescriptorPool::FindExtensionByNumber( - const Descriptor* extendee, int number) const { - // A faster path to reduce lock contention in finding extensions, assuming - // most extensions will be cache hit. - if (mutex_ != NULL) { - ReaderMutexLock lock(mutex_); - const FieldDescriptor* result = tables_->FindExtension(extendee, number); - if (result != NULL) { - return result; - } - } - MutexLockMaybe lock(mutex_); - if (fallback_database_ != NULL) { - tables_->known_bad_symbols_.clear(); - tables_->known_bad_files_.clear(); - } - const FieldDescriptor* result = tables_->FindExtension(extendee, number); - if (result != NULL) { - return result; - } - if (underlay_ != NULL) { - result = underlay_->FindExtensionByNumber(extendee, number); - if (result != NULL) return result; - } - if (TryFindExtensionInFallbackDatabase(extendee, number)) { - result = tables_->FindExtension(extendee, number); - if (result != NULL) { - return result; - } - } - return NULL; -} - -void DescriptorPool::FindAllExtensions( - const Descriptor* extendee, - std::vector* out) const { - MutexLockMaybe lock(mutex_); - if (fallback_database_ != NULL) { - tables_->known_bad_symbols_.clear(); - tables_->known_bad_files_.clear(); - } - - // Initialize tables_->extensions_ from the fallback database first - // (but do this only once per descriptor). - if (fallback_database_ != NULL && - tables_->extensions_loaded_from_db_.count(extendee) == 0) { - std::vector numbers; - if (fallback_database_->FindAllExtensionNumbers(extendee->full_name(), - &numbers)) { - for (int i = 0; i < numbers.size(); ++i) { - int number = numbers[i]; - if (tables_->FindExtension(extendee, number) == NULL) { - TryFindExtensionInFallbackDatabase(extendee, number); - } - } - tables_->extensions_loaded_from_db_.insert(extendee); - } - } - - tables_->FindAllExtensions(extendee, out); - if (underlay_ != NULL) { - underlay_->FindAllExtensions(extendee, out); - } -} - - -// ------------------------------------------------------------------- - -const FieldDescriptor* -Descriptor::FindFieldByNumber(int key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByNumber(this, key); - if (result == NULL || result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -Descriptor::FindFieldByLowercaseName(const string& key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByLowercaseName(this, key); - if (result == NULL || result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -Descriptor::FindFieldByCamelcaseName(const string& key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByCamelcaseName(this, key); - if (result == NULL || result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -Descriptor::FindFieldByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); - if (!result.IsNull() && !result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const OneofDescriptor* -Descriptor::FindOneofByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ONEOF); - if (!result.IsNull()) { - return result.oneof_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* -Descriptor::FindExtensionByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); - if (!result.IsNull() && result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* -Descriptor::FindExtensionByLowercaseName(const string& key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByLowercaseName(this, key); - if (result == NULL || !result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -Descriptor::FindExtensionByCamelcaseName(const string& key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByCamelcaseName(this, key); - if (result == NULL || !result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const Descriptor* -Descriptor::FindNestedTypeByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE); - if (!result.IsNull()) { - return result.descriptor; - } else { - return NULL; - } -} - -const EnumDescriptor* -Descriptor::FindEnumTypeByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM); - if (!result.IsNull()) { - return result.enum_descriptor; - } else { - return NULL; - } -} - -const EnumValueDescriptor* -Descriptor::FindEnumValueByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); - if (!result.IsNull()) { - return result.enum_value_descriptor; - } else { - return NULL; - } -} - -const EnumValueDescriptor* -EnumDescriptor::FindValueByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); - if (!result.IsNull()) { - return result.enum_value_descriptor; - } else { - return NULL; - } -} - -const EnumValueDescriptor* -EnumDescriptor::FindValueByNumber(int key) const { - return file()->tables_->FindEnumValueByNumber(this, key); -} - -const EnumValueDescriptor* -EnumDescriptor::FindValueByNumberCreatingIfUnknown(int key) const { - return file()->tables_->FindEnumValueByNumberCreatingIfUnknown(this, key); -} - -const MethodDescriptor* -ServiceDescriptor::FindMethodByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::METHOD); - if (!result.IsNull()) { - return result.method_descriptor; - } else { - return NULL; - } -} - -const Descriptor* -FileDescriptor::FindMessageTypeByName(const string& key) const { - Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE); - if (!result.IsNull()) { - return result.descriptor; - } else { - return NULL; - } -} - -const EnumDescriptor* -FileDescriptor::FindEnumTypeByName(const string& key) const { - Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM); - if (!result.IsNull()) { - return result.enum_descriptor; - } else { - return NULL; - } -} - -const EnumValueDescriptor* -FileDescriptor::FindEnumValueByName(const string& key) const { - Symbol result = - tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); - if (!result.IsNull()) { - return result.enum_value_descriptor; - } else { - return NULL; - } -} - -const ServiceDescriptor* -FileDescriptor::FindServiceByName(const string& key) const { - Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::SERVICE); - if (!result.IsNull()) { - return result.service_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* -FileDescriptor::FindExtensionByName(const string& key) const { - Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); - if (!result.IsNull() && result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* -FileDescriptor::FindExtensionByLowercaseName(const string& key) const { - const FieldDescriptor* result = tables_->FindFieldByLowercaseName(this, key); - if (result == NULL || !result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -FileDescriptor::FindExtensionByCamelcaseName(const string& key) const { - const FieldDescriptor* result = tables_->FindFieldByCamelcaseName(this, key); - if (result == NULL || !result->is_extension()) { - return NULL; - } else { - return result; - } -} - -void Descriptor::ExtensionRange::CopyTo( - DescriptorProto_ExtensionRange* proto) const { - proto->set_start(this->start); - proto->set_end(this->end); - if (options_ != &google::protobuf::ExtensionRangeOptions::default_instance()) { - *proto->mutable_options() = *options_; - } -} - -const Descriptor::ExtensionRange* -Descriptor::FindExtensionRangeContainingNumber(int number) const { - // Linear search should be fine because we don't expect a message to have - // more than a couple extension ranges. - for (int i = 0; i < extension_range_count(); i++) { - if (number >= extension_range(i)->start && - number < extension_range(i)->end) { - return extension_range(i); - } - } - return NULL; -} - -const Descriptor::ReservedRange* -Descriptor::FindReservedRangeContainingNumber(int number) const { - // TODO(chrisn): Consider a non-linear search. - for (int i = 0; i < reserved_range_count(); i++) { - if (number >= reserved_range(i)->start && - number < reserved_range(i)->end) { - return reserved_range(i); - } - } - return NULL; -} - -const EnumDescriptor::ReservedRange* -EnumDescriptor::FindReservedRangeContainingNumber(int number) const { - // TODO(chrisn): Consider a non-linear search. - for (int i = 0; i < reserved_range_count(); i++) { - if (number >= reserved_range(i)->start && - number <= reserved_range(i)->end) { - return reserved_range(i); - } - } - return NULL; -} - -// ------------------------------------------------------------------- - -bool DescriptorPool::TryFindFileInFallbackDatabase(const string& name) const { - if (fallback_database_ == NULL) return false; - - if (tables_->known_bad_files_.count(name) > 0) return false; - - FileDescriptorProto file_proto; - if (!fallback_database_->FindFileByName(name, &file_proto) || - BuildFileFromDatabase(file_proto) == NULL) { - tables_->known_bad_files_.insert(name); - return false; - } - return true; -} - -bool DescriptorPool::IsSubSymbolOfBuiltType(const string& name) const { - string prefix = name; - for (;;) { - string::size_type dot_pos = prefix.find_last_of('.'); - if (dot_pos == string::npos) { - break; - } - prefix = prefix.substr(0, dot_pos); - Symbol symbol = tables_->FindSymbol(prefix); - // If the symbol type is anything other than PACKAGE, then its complete - // definition is already known. - if (!symbol.IsNull() && symbol.type != Symbol::PACKAGE) { - return true; - } - } - if (underlay_ != NULL) { - // Check to see if any prefix of this symbol exists in the underlay. - return underlay_->IsSubSymbolOfBuiltType(name); - } - return false; -} - -bool DescriptorPool::TryFindSymbolInFallbackDatabase(const string& name) const { - if (fallback_database_ == NULL) return false; - - if (tables_->known_bad_symbols_.count(name) > 0) return false; - - FileDescriptorProto file_proto; - if (// We skip looking in the fallback database if the name is a sub-symbol - // of any descriptor that already exists in the descriptor pool (except - // for package descriptors). This is valid because all symbols except - // for packages are defined in a single file, so if the symbol exists - // then we should already have its definition. - // - // The other reason to do this is to support "overriding" type - // definitions by merging two databases that define the same type. (Yes, - // people do this.) The main difficulty with making this work is that - // FindFileContainingSymbol() is allowed to return both false positives - // (e.g., SimpleDescriptorDatabase, UpgradedDescriptorDatabase) and false - // negatives (e.g. ProtoFileParser, SourceTreeDescriptorDatabase). - // When two such databases are merged, looking up a non-existent - // sub-symbol of a type that already exists in the descriptor pool can - // result in an attempt to load multiple definitions of the same type. - // The check below avoids this. - IsSubSymbolOfBuiltType(name) - - // Look up file containing this symbol in fallback database. - || !fallback_database_->FindFileContainingSymbol(name, &file_proto) - - // Check if we've already built this file. If so, it apparently doesn't - // contain the symbol we're looking for. Some DescriptorDatabases - // return false positives. - || tables_->FindFile(file_proto.name()) != NULL - - // Build the file. - || BuildFileFromDatabase(file_proto) == NULL) { - tables_->known_bad_symbols_.insert(name); - return false; - } - - return true; -} - -bool DescriptorPool::TryFindExtensionInFallbackDatabase( - const Descriptor* containing_type, int field_number) const { - if (fallback_database_ == NULL) return false; - - FileDescriptorProto file_proto; - if (!fallback_database_->FindFileContainingExtension( - containing_type->full_name(), field_number, &file_proto)) { - return false; - } - - if (tables_->FindFile(file_proto.name()) != NULL) { - // We've already loaded this file, and it apparently doesn't contain the - // extension we're looking for. Some DescriptorDatabases return false - // positives. - return false; - } - - if (BuildFileFromDatabase(file_proto) == NULL) { - return false; - } - - return true; -} - -// =================================================================== - -bool FieldDescriptor::is_map_message_type() const { - return message_type_->options().map_entry(); -} - -string FieldDescriptor::DefaultValueAsString(bool quote_string_type) const { - GOOGLE_CHECK(has_default_value()) << "No default value"; - switch (cpp_type()) { - case CPPTYPE_INT32: - return SimpleItoa(default_value_int32()); - break; - case CPPTYPE_INT64: - return SimpleItoa(default_value_int64()); - break; - case CPPTYPE_UINT32: - return SimpleItoa(default_value_uint32()); - break; - case CPPTYPE_UINT64: - return SimpleItoa(default_value_uint64()); - break; - case CPPTYPE_FLOAT: - return SimpleFtoa(default_value_float()); - break; - case CPPTYPE_DOUBLE: - return SimpleDtoa(default_value_double()); - break; - case CPPTYPE_BOOL: - return default_value_bool() ? "true" : "false"; - break; - case CPPTYPE_STRING: - if (quote_string_type) { - return "\"" + CEscape(default_value_string()) + "\""; - } else { - if (type() == TYPE_BYTES) { - return CEscape(default_value_string()); - } else { - return default_value_string(); - } - } - break; - case CPPTYPE_ENUM: - return default_value_enum()->name(); - break; - case CPPTYPE_MESSAGE: - GOOGLE_LOG(DFATAL) << "Messages can't have default values!"; - break; - } - GOOGLE_LOG(FATAL) << "Can't get here: failed to get default value as string"; - return ""; -} - -// CopyTo methods ==================================================== - -void FileDescriptor::CopyTo(FileDescriptorProto* proto) const { - proto->set_name(name()); - if (!package().empty()) proto->set_package(package()); - // TODO(liujisi): Also populate when syntax="proto2". - if (syntax() == SYNTAX_PROTO3) proto->set_syntax(SyntaxName(syntax())); - - for (int i = 0; i < dependency_count(); i++) { - proto->add_dependency(dependency(i)->name()); - } - - for (int i = 0; i < public_dependency_count(); i++) { - proto->add_public_dependency(public_dependencies_[i]); - } - - for (int i = 0; i < weak_dependency_count(); i++) { - proto->add_weak_dependency(weak_dependencies_[i]); - } - - for (int i = 0; i < message_type_count(); i++) { - message_type(i)->CopyTo(proto->add_message_type()); - } - for (int i = 0; i < enum_type_count(); i++) { - enum_type(i)->CopyTo(proto->add_enum_type()); - } - for (int i = 0; i < service_count(); i++) { - service(i)->CopyTo(proto->add_service()); - } - for (int i = 0; i < extension_count(); i++) { - extension(i)->CopyTo(proto->add_extension()); - } - - if (&options() != &FileOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void FileDescriptor::CopyJsonNameTo(FileDescriptorProto* proto) const { - if (message_type_count() != proto->message_type_size() || - extension_count() != proto->extension_size()) { - GOOGLE_LOG(ERROR) << "Cannot copy json_name to a proto of a different size."; - return; - } - for (int i = 0; i < message_type_count(); i++) { - message_type(i)->CopyJsonNameTo(proto->mutable_message_type(i)); - } - for (int i = 0; i < extension_count(); i++) { - extension(i)->CopyJsonNameTo(proto->mutable_extension(i)); - } -} - -void FileDescriptor::CopySourceCodeInfoTo(FileDescriptorProto* proto) const { - if (source_code_info_ && - source_code_info_ != &SourceCodeInfo::default_instance()) { - proto->mutable_source_code_info()->CopyFrom(*source_code_info_); - } -} - -void Descriptor::CopyTo(DescriptorProto* proto) const { - proto->set_name(name()); - - for (int i = 0; i < field_count(); i++) { - field(i)->CopyTo(proto->add_field()); - } - for (int i = 0; i < oneof_decl_count(); i++) { - oneof_decl(i)->CopyTo(proto->add_oneof_decl()); - } - for (int i = 0; i < nested_type_count(); i++) { - nested_type(i)->CopyTo(proto->add_nested_type()); - } - for (int i = 0; i < enum_type_count(); i++) { - enum_type(i)->CopyTo(proto->add_enum_type()); - } - for (int i = 0; i < extension_range_count(); i++) { - extension_range(i)->CopyTo(proto->add_extension_range()); - } - for (int i = 0; i < extension_count(); i++) { - extension(i)->CopyTo(proto->add_extension()); - } - for (int i = 0; i < reserved_range_count(); i++) { - DescriptorProto::ReservedRange* range = proto->add_reserved_range(); - range->set_start(reserved_range(i)->start); - range->set_end(reserved_range(i)->end); - } - for (int i = 0; i < reserved_name_count(); i++) { - proto->add_reserved_name(reserved_name(i)); - } - - if (&options() != &MessageOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void Descriptor::CopyJsonNameTo(DescriptorProto* proto) const { - if (field_count() != proto->field_size() || - nested_type_count() != proto->nested_type_size() || - extension_count() != proto->extension_size()) { - GOOGLE_LOG(ERROR) << "Cannot copy json_name to a proto of a different size."; - return; - } - for (int i = 0; i < field_count(); i++) { - field(i)->CopyJsonNameTo(proto->mutable_field(i)); - } - for (int i = 0; i < nested_type_count(); i++) { - nested_type(i)->CopyJsonNameTo(proto->mutable_nested_type(i)); - } - for (int i = 0; i < extension_count(); i++) { - extension(i)->CopyJsonNameTo(proto->mutable_extension(i)); - } -} - -void FieldDescriptor::CopyTo(FieldDescriptorProto* proto) const { - proto->set_name(name()); - proto->set_number(number()); - if (has_json_name_) { - proto->set_json_name(json_name()); - } - - // Some compilers do not allow static_cast directly between two enum types, - // so we must cast to int first. - proto->set_label(static_cast( - implicit_cast(label()))); - proto->set_type(static_cast( - implicit_cast(type()))); - - if (is_extension()) { - if (!containing_type()->is_unqualified_placeholder_) { - proto->set_extendee("."); - } - proto->mutable_extendee()->append(containing_type()->full_name()); - } - - if (cpp_type() == CPPTYPE_MESSAGE) { - if (message_type()->is_placeholder_) { - // We don't actually know if the type is a message type. It could be - // an enum. - proto->clear_type(); - } - - if (!message_type()->is_unqualified_placeholder_) { - proto->set_type_name("."); - } - proto->mutable_type_name()->append(message_type()->full_name()); - } else if (cpp_type() == CPPTYPE_ENUM) { - if (!enum_type()->is_unqualified_placeholder_) { - proto->set_type_name("."); - } - proto->mutable_type_name()->append(enum_type()->full_name()); - } - - if (has_default_value()) { - proto->set_default_value(DefaultValueAsString(false)); - } - - if (containing_oneof() != NULL && !is_extension()) { - proto->set_oneof_index(containing_oneof()->index()); - } - - if (&options() != &FieldOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void FieldDescriptor::CopyJsonNameTo(FieldDescriptorProto* proto) const { - proto->set_json_name(json_name()); -} - -void OneofDescriptor::CopyTo(OneofDescriptorProto* proto) const { - proto->set_name(name()); - if (&options() != &OneofOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void EnumDescriptor::CopyTo(EnumDescriptorProto* proto) const { - proto->set_name(name()); - - for (int i = 0; i < value_count(); i++) { - value(i)->CopyTo(proto->add_value()); - } - for (int i = 0; i < reserved_range_count(); i++) { - EnumDescriptorProto::EnumReservedRange* range = proto->add_reserved_range(); - range->set_start(reserved_range(i)->start); - range->set_end(reserved_range(i)->end); - } - for (int i = 0; i < reserved_name_count(); i++) { - proto->add_reserved_name(reserved_name(i)); - } - - if (&options() != &EnumOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void EnumValueDescriptor::CopyTo(EnumValueDescriptorProto* proto) const { - proto->set_name(name()); - proto->set_number(number()); - - if (&options() != &EnumValueOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void ServiceDescriptor::CopyTo(ServiceDescriptorProto* proto) const { - proto->set_name(name()); - - for (int i = 0; i < method_count(); i++) { - method(i)->CopyTo(proto->add_method()); - } - - if (&options() != &ServiceOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void MethodDescriptor::CopyTo(MethodDescriptorProto* proto) const { - proto->set_name(name()); - - if (!input_type()->is_unqualified_placeholder_) { - proto->set_input_type("."); - } - proto->mutable_input_type()->append(input_type()->full_name()); - - if (!output_type()->is_unqualified_placeholder_) { - proto->set_output_type("."); - } - proto->mutable_output_type()->append(output_type()->full_name()); - - if (&options() != &MethodOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } - - if (client_streaming_) { - proto->set_client_streaming(true); - } - if (server_streaming_) { - proto->set_server_streaming(true); - } -} - -// DebugString methods =============================================== - -namespace { - -bool RetrieveOptionsAssumingRightPool(int depth, const Message& options, - std::vector* option_entries) { - option_entries->clear(); - const Reflection* reflection = options.GetReflection(); - std::vector fields; - reflection->ListFields(options, &fields); - for (int i = 0; i < fields.size(); i++) { - int count = 1; - bool repeated = false; - if (fields[i]->is_repeated()) { - count = reflection->FieldSize(options, fields[i]); - repeated = true; - } - for (int j = 0; j < count; j++) { - string fieldval; - if (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - string tmp; - TextFormat::Printer printer; - printer.SetInitialIndentLevel(depth + 1); - printer.PrintFieldValueToString(options, fields[i], - repeated ? j : -1, &tmp); - fieldval.append("{\n"); - fieldval.append(tmp); - fieldval.append(depth * 2, ' '); - fieldval.append("}"); - } else { - TextFormat::PrintFieldValueToString(options, fields[i], - repeated ? j : -1, &fieldval); - } - string name; - if (fields[i]->is_extension()) { - name = "(." + fields[i]->full_name() + ")"; - } else { - name = fields[i]->name(); - } - option_entries->push_back(name + " = " + fieldval); - } - } - return !option_entries->empty(); -} - -// Used by each of the option formatters. -bool RetrieveOptions(int depth, const Message& options, - const DescriptorPool* pool, - std::vector* option_entries) { - // When printing custom options for a descriptor, we must use an options - // message built on top of the same DescriptorPool where the descriptor - // is coming from. This is to ensure we are interpreting custom options - // against the right pool. - if (options.GetDescriptor()->file()->pool() == pool) { - return RetrieveOptionsAssumingRightPool(depth, options, option_entries); - } else { - const Descriptor* option_descriptor = - pool->FindMessageTypeByName(options.GetDescriptor()->full_name()); - if (option_descriptor == NULL) { - // google/protobuf/descriptor.proto is not in the pool. This means no - // custom options are used so we are safe to proceed with the compiled - // options message type. - return RetrieveOptionsAssumingRightPool(depth, options, option_entries); - } - DynamicMessageFactory factory; - std::unique_ptr dynamic_options( - factory.GetPrototype(option_descriptor)->New()); - if (dynamic_options->ParseFromString(options.SerializeAsString())) { - return RetrieveOptionsAssumingRightPool(depth, *dynamic_options, - option_entries); - } else { - GOOGLE_LOG(ERROR) << "Found invalid proto option data for: " - << options.GetDescriptor()->full_name(); - return RetrieveOptionsAssumingRightPool(depth, options, option_entries); - } - } -} - -// Formats options that all appear together in brackets. Does not include -// brackets. -bool FormatBracketedOptions(int depth, const Message& options, - const DescriptorPool* pool, string* output) { - std::vector all_options; - if (RetrieveOptions(depth, options, pool, &all_options)) { - output->append(Join(all_options, ", ")); - } - return !all_options.empty(); -} - -// Formats options one per line -bool FormatLineOptions(int depth, const Message& options, - const DescriptorPool* pool, string* output) { - string prefix(depth * 2, ' '); - std::vector all_options; - if (RetrieveOptions(depth, options, pool, &all_options)) { - for (int i = 0; i < all_options.size(); i++) { - strings::SubstituteAndAppend(output, "$0option $1;\n", - prefix, all_options[i]); - } - } - return !all_options.empty(); -} - -class SourceLocationCommentPrinter { - public: - template - SourceLocationCommentPrinter(const DescType* desc, - const string& prefix, - const DebugStringOptions& options) - : options_(options), prefix_(prefix) { - // Perform the SourceLocation lookup only if we're including user comments, - // because the lookup is fairly expensive. - have_source_loc_ = options.include_comments && - desc->GetSourceLocation(&source_loc_); - } - SourceLocationCommentPrinter(const FileDescriptor* file, - const std::vector& path, - const string& prefix, - const DebugStringOptions& options) - : options_(options), prefix_(prefix) { - // Perform the SourceLocation lookup only if we're including user comments, - // because the lookup is fairly expensive. - have_source_loc_ = options.include_comments && - file->GetSourceLocation(path, &source_loc_); - } - void AddPreComment(string* output) { - if (have_source_loc_) { - // Detached leading comments. - for (int i = 0 ; i < source_loc_.leading_detached_comments.size(); ++i) { - *output += FormatComment(source_loc_.leading_detached_comments[i]); - *output += "\n"; - } - // Attached leading comments. - if (!source_loc_.leading_comments.empty()) { - *output += FormatComment(source_loc_.leading_comments); - } - } - } - void AddPostComment(string* output) { - if (have_source_loc_ && source_loc_.trailing_comments.size() > 0) { - *output += FormatComment(source_loc_.trailing_comments); - } - } - - // Format comment such that each line becomes a full-line C++-style comment in - // the DebugString() output. - string FormatComment(const string& comment_text) { - string stripped_comment = comment_text; - StripWhitespace(&stripped_comment); - std::vector lines = Split(stripped_comment, "\n"); - string output; - for (int i = 0; i < lines.size(); ++i) { - const string& line = lines[i]; - strings::SubstituteAndAppend(&output, "$0// $1\n", prefix_, line); - } - return output; - } - - private: - - bool have_source_loc_; - SourceLocation source_loc_; - DebugStringOptions options_; - string prefix_; -}; - -} // anonymous namespace - -string FileDescriptor::DebugString() const { - DebugStringOptions options; // default options - return DebugStringWithOptions(options); -} - -string FileDescriptor::DebugStringWithOptions( - const DebugStringOptions& debug_string_options) const { - string contents; - { - std::vector path; - path.push_back(FileDescriptorProto::kSyntaxFieldNumber); - SourceLocationCommentPrinter syntax_comment( - this, path, "", debug_string_options); - syntax_comment.AddPreComment(&contents); - strings::SubstituteAndAppend(&contents, "syntax = \"$0\";\n\n", - SyntaxName(syntax())); - syntax_comment.AddPostComment(&contents); - } - - SourceLocationCommentPrinter - comment_printer(this, "", debug_string_options); - comment_printer.AddPreComment(&contents); - - std::set public_dependencies; - std::set weak_dependencies; - public_dependencies.insert(public_dependencies_, - public_dependencies_ + public_dependency_count_); - weak_dependencies.insert(weak_dependencies_, - weak_dependencies_ + weak_dependency_count_); - - for (int i = 0; i < dependency_count(); i++) { - if (public_dependencies.count(i) > 0) { - strings::SubstituteAndAppend(&contents, "import public \"$0\";\n", - dependency(i)->name()); - } else if (weak_dependencies.count(i) > 0) { - strings::SubstituteAndAppend(&contents, "import weak \"$0\";\n", - dependency(i)->name()); - } else { - strings::SubstituteAndAppend(&contents, "import \"$0\";\n", - dependency(i)->name()); - } - } - - if (!package().empty()) { - std::vector path; - path.push_back(FileDescriptorProto::kPackageFieldNumber); - SourceLocationCommentPrinter package_comment( - this, path, "", debug_string_options); - package_comment.AddPreComment(&contents); - strings::SubstituteAndAppend(&contents, "package $0;\n\n", package()); - package_comment.AddPostComment(&contents); - } - - if (FormatLineOptions(0, options(), pool(), &contents)) { - contents.append("\n"); // add some space if we had options - } - - for (int i = 0; i < enum_type_count(); i++) { - enum_type(i)->DebugString(0, &contents, debug_string_options); - contents.append("\n"); - } - - // Find all the 'group' type extensions; we will not output their nested - // definitions (those will be done with their group field descriptor). - std::set groups; - for (int i = 0; i < extension_count(); i++) { - if (extension(i)->type() == FieldDescriptor::TYPE_GROUP) { - groups.insert(extension(i)->message_type()); - } - } - - for (int i = 0; i < message_type_count(); i++) { - if (groups.count(message_type(i)) == 0) { - message_type(i)->DebugString(0, &contents, debug_string_options, - /* include_opening_clause */ true); - contents.append("\n"); - } - } - - for (int i = 0; i < service_count(); i++) { - service(i)->DebugString(&contents, debug_string_options); - contents.append("\n"); - } - - const Descriptor* containing_type = NULL; - for (int i = 0; i < extension_count(); i++) { - if (extension(i)->containing_type() != containing_type) { - if (i > 0) contents.append("}\n\n"); - containing_type = extension(i)->containing_type(); - strings::SubstituteAndAppend(&contents, "extend .$0 {\n", - containing_type->full_name()); - } - extension(i)->DebugString(1, FieldDescriptor::PRINT_LABEL, &contents, - debug_string_options); - } - if (extension_count() > 0) contents.append("}\n\n"); - - comment_printer.AddPostComment(&contents); - - return contents; -} - -string Descriptor::DebugString() const { - DebugStringOptions options; // default options - return DebugStringWithOptions(options); -} - -string Descriptor::DebugStringWithOptions( - const DebugStringOptions& options) const { - string contents; - DebugString(0, &contents, options, /* include_opening_clause */ true); - return contents; -} - -void Descriptor::DebugString(int depth, string *contents, - const DebugStringOptions& - debug_string_options, - bool include_opening_clause) const { - if (options().map_entry()) { - // Do not generate debug string for auto-generated map-entry type. - return; - } - string prefix(depth * 2, ' '); - ++depth; - - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); - comment_printer.AddPreComment(contents); - - if (include_opening_clause) { - strings::SubstituteAndAppend(contents, "$0message $1", prefix, name()); - } - contents->append(" {\n"); - - FormatLineOptions(depth, options(), file()->pool(), contents); - - // Find all the 'group' types for fields and extensions; we will not output - // their nested definitions (those will be done with their group field - // descriptor). - std::set groups; - for (int i = 0; i < field_count(); i++) { - if (field(i)->type() == FieldDescriptor::TYPE_GROUP) { - groups.insert(field(i)->message_type()); - } - } - for (int i = 0; i < extension_count(); i++) { - if (extension(i)->type() == FieldDescriptor::TYPE_GROUP) { - groups.insert(extension(i)->message_type()); - } - } - - for (int i = 0; i < nested_type_count(); i++) { - if (groups.count(nested_type(i)) == 0) { - nested_type(i)->DebugString(depth, contents, debug_string_options, - /* include_opening_clause */ true); - } - } - for (int i = 0; i < enum_type_count(); i++) { - enum_type(i)->DebugString(depth, contents, debug_string_options); - } - for (int i = 0; i < field_count(); i++) { - if (field(i)->containing_oneof() == NULL) { - field(i)->DebugString(depth, FieldDescriptor::PRINT_LABEL, contents, - debug_string_options); - } else if (field(i)->containing_oneof()->field(0) == field(i)) { - // This is the first field in this oneof, so print the whole oneof. - field(i)->containing_oneof()->DebugString(depth, contents, - debug_string_options); - } - } - - for (int i = 0; i < extension_range_count(); i++) { - strings::SubstituteAndAppend(contents, "$0 extensions $1 to $2;\n", - prefix, - extension_range(i)->start, - extension_range(i)->end - 1); - } - - // Group extensions by what they extend, so they can be printed out together. - const Descriptor* containing_type = NULL; - for (int i = 0; i < extension_count(); i++) { - if (extension(i)->containing_type() != containing_type) { - if (i > 0) strings::SubstituteAndAppend(contents, "$0 }\n", prefix); - containing_type = extension(i)->containing_type(); - strings::SubstituteAndAppend(contents, "$0 extend .$1 {\n", - prefix, containing_type->full_name()); - } - extension(i)->DebugString( - depth + 1, FieldDescriptor::PRINT_LABEL, contents, - debug_string_options); - } - if (extension_count() > 0) - strings::SubstituteAndAppend(contents, "$0 }\n", prefix); - - if (reserved_range_count() > 0) { - strings::SubstituteAndAppend(contents, "$0 reserved ", prefix); - for (int i = 0; i < reserved_range_count(); i++) { - const Descriptor::ReservedRange* range = reserved_range(i); - if (range->end == range->start + 1) { - strings::SubstituteAndAppend(contents, "$0, ", range->start); - } else { - strings::SubstituteAndAppend(contents, "$0 to $1, ", - range->start, range->end - 1); - } - } - contents->replace(contents->size() - 2, 2, ";\n"); - } - - if (reserved_name_count() > 0) { - strings::SubstituteAndAppend(contents, "$0 reserved ", prefix); - for (int i = 0; i < reserved_name_count(); i++) { - strings::SubstituteAndAppend(contents, "\"$0\", ", - CEscape(reserved_name(i))); - } - contents->replace(contents->size() - 2, 2, ";\n"); - } - - strings::SubstituteAndAppend(contents, "$0}\n", prefix); - comment_printer.AddPostComment(contents); -} - -string FieldDescriptor::DebugString() const { - DebugStringOptions options; // default options - return DebugStringWithOptions(options); -} - -string FieldDescriptor::DebugStringWithOptions( - const DebugStringOptions& debug_string_options) const { - string contents; - int depth = 0; - if (is_extension()) { - strings::SubstituteAndAppend(&contents, "extend .$0 {\n", - containing_type()->full_name()); - depth = 1; - } - DebugString(depth, PRINT_LABEL, &contents, debug_string_options); - if (is_extension()) { - contents.append("}\n"); - } - return contents; -} - -// The field type string used in FieldDescriptor::DebugString() -string FieldDescriptor::FieldTypeNameDebugString() const { - switch(type()) { - case TYPE_MESSAGE: - return "." + message_type()->full_name(); - case TYPE_ENUM: - return "." + enum_type()->full_name(); - default: - return kTypeToName[type()]; - } -} - -void FieldDescriptor::DebugString(int depth, - PrintLabelFlag print_label_flag, - string *contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); - string field_type; - - // Special case map fields. - if (is_map()) { - strings::SubstituteAndAppend( - &field_type, "map<$0, $1>", - message_type()->field(0)->FieldTypeNameDebugString(), - message_type()->field(1)->FieldTypeNameDebugString()); - } else { - field_type = FieldTypeNameDebugString(); - } - - bool print_label = true; - // Determine whether to omit label: - // 1. For an optional field, omit label if it's in oneof or in proto3. - // 2. For a repeated field, omit label if it's a map. - if (is_optional() && (print_label_flag == OMIT_LABEL || - file()->syntax() == FileDescriptor::SYNTAX_PROTO3)) { - print_label = false; - } else if (is_map()) { - print_label = false; - } - string label; - if (print_label) { - label = kLabelToName[this->label()]; - label.push_back(' '); - } - - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); - comment_printer.AddPreComment(contents); - - strings::SubstituteAndAppend(contents, "$0$1$2 $3 = $4", - prefix, - label, - field_type, - type() == TYPE_GROUP ? message_type()->name() : - name(), - number()); - - bool bracketed = false; - if (has_default_value()) { - bracketed = true; - strings::SubstituteAndAppend(contents, " [default = $0", - DefaultValueAsString(true)); - } - if (has_json_name_) { - if (!bracketed) { - bracketed = true; - contents->append("["); - } else { - contents->append(", "); - } - contents->append("json_name = \""); - contents->append(CEscape(json_name())); - contents->append("\""); - } - - string formatted_options; - if (FormatBracketedOptions(depth, options(), file()->pool(), - &formatted_options)) { - contents->append(bracketed ? ", " : " ["); - bracketed = true; - contents->append(formatted_options); - } - - if (bracketed) { - contents->append("]"); - } - - if (type() == TYPE_GROUP) { - if (debug_string_options.elide_group_body) { - contents->append(" { ... };\n"); - } else { - message_type()->DebugString(depth, contents, debug_string_options, - /* include_opening_clause */ false); - } - } else { - contents->append(";\n"); - } - - comment_printer.AddPostComment(contents); -} - -string OneofDescriptor::DebugString() const { - DebugStringOptions options; // default values - return DebugStringWithOptions(options); -} - -string OneofDescriptor::DebugStringWithOptions( - const DebugStringOptions& options) const { - string contents; - DebugString(0, &contents, options); - return contents; -} - -void OneofDescriptor::DebugString(int depth, string* contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); - ++depth; - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); - comment_printer.AddPreComment(contents); - strings::SubstituteAndAppend(contents, "$0oneof $1 {", prefix, name()); - - FormatLineOptions(depth, options(), containing_type()->file()->pool(), - contents); - - if (debug_string_options.elide_oneof_body) { - contents->append(" ... }\n"); - } else { - contents->append("\n"); - for (int i = 0; i < field_count(); i++) { - field(i)->DebugString(depth, FieldDescriptor::OMIT_LABEL, contents, - debug_string_options); - } - strings::SubstituteAndAppend(contents, "$0}\n", prefix); - } - comment_printer.AddPostComment(contents); -} - -string EnumDescriptor::DebugString() const { - DebugStringOptions options; // default values - return DebugStringWithOptions(options); -} - -string EnumDescriptor::DebugStringWithOptions( - const DebugStringOptions& options) const { - string contents; - DebugString(0, &contents, options); - return contents; -} - -void EnumDescriptor::DebugString(int depth, string *contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); - ++depth; - - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); - comment_printer.AddPreComment(contents); - - strings::SubstituteAndAppend(contents, "$0enum $1 {\n", - prefix, name()); - - FormatLineOptions(depth, options(), file()->pool(), contents); - - for (int i = 0; i < value_count(); i++) { - value(i)->DebugString(depth, contents, debug_string_options); - } - - if (reserved_range_count() > 0) { - strings::SubstituteAndAppend(contents, "$0 reserved ", prefix); - for (int i = 0; i < reserved_range_count(); i++) { - const EnumDescriptor::ReservedRange* range = reserved_range(i); - if (range->end == range->start) { - strings::SubstituteAndAppend(contents, "$0, ", range->start); - } else { - strings::SubstituteAndAppend(contents, "$0 to $1, ", - range->start, range->end); - } - } - contents->replace(contents->size() - 2, 2, ";\n"); - } - - if (reserved_name_count() > 0) { - strings::SubstituteAndAppend(contents, "$0 reserved ", prefix); - for (int i = 0; i < reserved_name_count(); i++) { - strings::SubstituteAndAppend(contents, "\"$0\", ", - CEscape(reserved_name(i))); - } - contents->replace(contents->size() - 2, 2, ";\n"); - } - - strings::SubstituteAndAppend(contents, "$0}\n", prefix); - - comment_printer.AddPostComment(contents); -} - -string EnumValueDescriptor::DebugString() const { - DebugStringOptions options; // default values - return DebugStringWithOptions(options); -} - -string EnumValueDescriptor::DebugStringWithOptions( - const DebugStringOptions& options) const { - string contents; - DebugString(0, &contents, options); - return contents; -} - -void EnumValueDescriptor::DebugString(int depth, string *contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); - - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); - comment_printer.AddPreComment(contents); - - strings::SubstituteAndAppend(contents, "$0$1 = $2", - prefix, name(), number()); - - string formatted_options; - if (FormatBracketedOptions(depth, options(), type()->file()->pool(), - &formatted_options)) { - strings::SubstituteAndAppend(contents, " [$0]", formatted_options); - } - contents->append(";\n"); - - comment_printer.AddPostComment(contents); -} - -string ServiceDescriptor::DebugString() const { - DebugStringOptions options; // default values - return DebugStringWithOptions(options); -} - -string ServiceDescriptor::DebugStringWithOptions( - const DebugStringOptions& options) const { - string contents; - DebugString(&contents, options); - return contents; -} - -void ServiceDescriptor::DebugString(string *contents, - const DebugStringOptions& - debug_string_options) const { - SourceLocationCommentPrinter - comment_printer(this, /* prefix */ "", debug_string_options); - comment_printer.AddPreComment(contents); - - strings::SubstituteAndAppend(contents, "service $0 {\n", name()); - - FormatLineOptions(1, options(), file()->pool(), contents); - - for (int i = 0; i < method_count(); i++) { - method(i)->DebugString(1, contents, debug_string_options); - } - - contents->append("}\n"); - - comment_printer.AddPostComment(contents); -} - -string MethodDescriptor::DebugString() const { - DebugStringOptions options; // default values - return DebugStringWithOptions(options); -} - -string MethodDescriptor::DebugStringWithOptions( - const DebugStringOptions& options) const { - string contents; - DebugString(0, &contents, options); - return contents; -} - -void MethodDescriptor::DebugString(int depth, string *contents, - const DebugStringOptions& - debug_string_options) const { - string prefix(depth * 2, ' '); - ++depth; - - SourceLocationCommentPrinter - comment_printer(this, prefix, debug_string_options); - comment_printer.AddPreComment(contents); - - strings::SubstituteAndAppend(contents, "$0rpc $1($4.$2) returns ($5.$3)", - prefix, name(), - input_type()->full_name(), - output_type()->full_name(), - client_streaming() ? "stream " : "", - server_streaming() ? "stream " : ""); - - string formatted_options; - if (FormatLineOptions(depth, options(), service()->file()->pool(), - &formatted_options)) { - strings::SubstituteAndAppend(contents, " {\n$0$1}\n", - formatted_options, prefix); - } else { - contents->append(";\n"); - } - - comment_printer.AddPostComment(contents); -} - - -// Location methods =============================================== - -bool FileDescriptor::GetSourceLocation(const std::vector& path, - SourceLocation* out_location) const { - GOOGLE_CHECK_NOTNULL(out_location); - if (source_code_info_) { - if (const SourceCodeInfo_Location* loc = - tables_->GetSourceLocation(path, source_code_info_)) { - const RepeatedField& span = loc->span(); - if (span.size() == 3 || span.size() == 4) { - out_location->start_line = span.Get(0); - out_location->start_column = span.Get(1); - out_location->end_line = span.Get(span.size() == 3 ? 0 : 2); - out_location->end_column = span.Get(span.size() - 1); - - out_location->leading_comments = loc->leading_comments(); - out_location->trailing_comments = loc->trailing_comments(); - out_location->leading_detached_comments.assign( - loc->leading_detached_comments().begin(), - loc->leading_detached_comments().end()); - return true; - } - } - } - return false; -} - -bool FileDescriptor::GetSourceLocation(SourceLocation* out_location) const { - std::vector path; // empty path for root FileDescriptor - return GetSourceLocation(path, out_location); -} - -bool FieldDescriptor::is_packed() const { - if (!is_packable()) return false; - if (file_->syntax() == FileDescriptor::SYNTAX_PROTO2) { - return (options_ != NULL) && options_->packed(); - } else { - return options_ == NULL || !options_->has_packed() || options_->packed(); - } -} - -bool Descriptor::GetSourceLocation(SourceLocation* out_location) const { - std::vector path; - GetLocationPath(&path); - return file()->GetSourceLocation(path, out_location); -} - -bool FieldDescriptor::GetSourceLocation(SourceLocation* out_location) const { - std::vector path; - GetLocationPath(&path); - return file()->GetSourceLocation(path, out_location); -} - -bool OneofDescriptor::GetSourceLocation(SourceLocation* out_location) const { - std::vector path; - GetLocationPath(&path); - return containing_type()->file()->GetSourceLocation(path, out_location); -} - -bool EnumDescriptor::GetSourceLocation(SourceLocation* out_location) const { - std::vector path; - GetLocationPath(&path); - return file()->GetSourceLocation(path, out_location); -} - -bool MethodDescriptor::GetSourceLocation(SourceLocation* out_location) const { - std::vector path; - GetLocationPath(&path); - return service()->file()->GetSourceLocation(path, out_location); -} - -bool ServiceDescriptor::GetSourceLocation(SourceLocation* out_location) const { - std::vector path; - GetLocationPath(&path); - return file()->GetSourceLocation(path, out_location); -} - -bool EnumValueDescriptor::GetSourceLocation( - SourceLocation* out_location) const { - std::vector path; - GetLocationPath(&path); - return type()->file()->GetSourceLocation(path, out_location); -} - -void Descriptor::GetLocationPath(std::vector* output) const { - if (containing_type()) { - containing_type()->GetLocationPath(output); - output->push_back(DescriptorProto::kNestedTypeFieldNumber); - output->push_back(index()); - } else { - output->push_back(FileDescriptorProto::kMessageTypeFieldNumber); - output->push_back(index()); - } -} - -void FieldDescriptor::GetLocationPath(std::vector* output) const { - if (is_extension()) { - if (extension_scope() == NULL) { - output->push_back(FileDescriptorProto::kExtensionFieldNumber); - output->push_back(index()); - } else { - extension_scope()->GetLocationPath(output); - output->push_back(DescriptorProto::kExtensionFieldNumber); - output->push_back(index()); - } - } else { - containing_type()->GetLocationPath(output); - output->push_back(DescriptorProto::kFieldFieldNumber); - output->push_back(index()); - } -} - -void OneofDescriptor::GetLocationPath(std::vector* output) const { - containing_type()->GetLocationPath(output); - output->push_back(DescriptorProto::kOneofDeclFieldNumber); - output->push_back(index()); -} - -void EnumDescriptor::GetLocationPath(std::vector* output) const { - if (containing_type()) { - containing_type()->GetLocationPath(output); - output->push_back(DescriptorProto::kEnumTypeFieldNumber); - output->push_back(index()); - } else { - output->push_back(FileDescriptorProto::kEnumTypeFieldNumber); - output->push_back(index()); - } -} - -void EnumValueDescriptor::GetLocationPath(std::vector* output) const { - type()->GetLocationPath(output); - output->push_back(EnumDescriptorProto::kValueFieldNumber); - output->push_back(index()); -} - -void ServiceDescriptor::GetLocationPath(std::vector* output) const { - output->push_back(FileDescriptorProto::kServiceFieldNumber); - output->push_back(index()); -} - -void MethodDescriptor::GetLocationPath(std::vector* output) const { - service()->GetLocationPath(output); - output->push_back(ServiceDescriptorProto::kMethodFieldNumber); - output->push_back(index()); -} - -// =================================================================== - -namespace { - -// Represents an options message to interpret. Extension names in the option -// name are resolved relative to name_scope. element_name and orig_opt are -// used only for error reporting (since the parser records locations against -// pointers in the original options, not the mutable copy). The Message must be -// one of the Options messages in descriptor.proto. -struct OptionsToInterpret { - OptionsToInterpret(const string& ns, - const string& el, - std::vector& path, - const Message* orig_opt, - Message* opt) - : name_scope(ns), - element_name(el), - element_path(path), - original_options(orig_opt), - options(opt) { - } - string name_scope; - string element_name; - std::vector element_path; - const Message* original_options; - Message* options; -}; - -} // namespace - -class DescriptorBuilder { - public: - DescriptorBuilder(const DescriptorPool* pool, - DescriptorPool::Tables* tables, - DescriptorPool::ErrorCollector* error_collector); - ~DescriptorBuilder(); - - const FileDescriptor* BuildFile(const FileDescriptorProto& proto); - - private: - friend class OptionInterpreter; - - // Non-recursive part of BuildFile functionality. - FileDescriptor* BuildFileImpl(const FileDescriptorProto& proto); - - const DescriptorPool* pool_; - DescriptorPool::Tables* tables_; // for convenience - DescriptorPool::ErrorCollector* error_collector_; - - // As we build descriptors we store copies of the options messages in - // them. We put pointers to those copies in this vector, as we build, so we - // can later (after cross-linking) interpret those options. - std::vector options_to_interpret_; - - bool had_errors_; - string filename_; - FileDescriptor* file_; - FileDescriptorTables* file_tables_; - std::set dependencies_; - - // unused_dependency_ is used to record the unused imported files. - // Note: public import is not considered. - std::set unused_dependency_; - - // If LookupSymbol() finds a symbol that is in a file which is not a declared - // dependency of this file, it will fail, but will set - // possible_undeclared_dependency_ to point at that file. This is only used - // by AddNotDefinedError() to report a more useful error message. - // possible_undeclared_dependency_name_ is the name of the symbol that was - // actually found in possible_undeclared_dependency_, which may be a parent - // of the symbol actually looked for. - const FileDescriptor* possible_undeclared_dependency_; - string possible_undeclared_dependency_name_; - - // If LookupSymbol() could resolve a symbol which is not defined, - // record the resolved name. This is only used by AddNotDefinedError() - // to report a more useful error message. - string undefine_resolved_name_; - - void AddError(const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error); - void AddError(const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const char* error); - void AddRecursiveImportError(const FileDescriptorProto& proto, int from_here); - void AddTwiceListedError(const FileDescriptorProto& proto, int index); - void AddImportError(const FileDescriptorProto& proto, int index); - - // Adds an error indicating that undefined_symbol was not defined. Must - // only be called after LookupSymbol() fails. - void AddNotDefinedError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& undefined_symbol); - - void AddWarning(const string& element_name, const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error); - - // Silly helper which determines if the given file is in the given package. - // I.e., either file->package() == package_name or file->package() is a - // nested package within package_name. - bool IsInPackage(const FileDescriptor* file, const string& package_name); - - // Helper function which finds all public dependencies of the given file, and - // stores the them in the dependencies_ set in the builder. - void RecordPublicDependencies(const FileDescriptor* file); - - // Like tables_->FindSymbol(), but additionally: - // - Search the pool's underlay if not found in tables_. - // - Insure that the resulting Symbol is from one of the file's declared - // dependencies. - Symbol FindSymbol(const string& name, bool build_it = true); - - // Like FindSymbol() but does not require that the symbol is in one of the - // file's declared dependencies. - Symbol FindSymbolNotEnforcingDeps(const string& name, bool build_it = true); - - // This implements the body of FindSymbolNotEnforcingDeps(). - Symbol FindSymbolNotEnforcingDepsHelper(const DescriptorPool* pool, - const string& name, - bool build_it = true); - - // Like FindSymbol(), but looks up the name relative to some other symbol - // name. This first searches siblings of relative_to, then siblings of its - // parents, etc. For example, LookupSymbol("foo.bar", "baz.qux.corge") makes - // the following calls, returning the first non-null result: - // FindSymbol("baz.qux.foo.bar"), FindSymbol("baz.foo.bar"), - // FindSymbol("foo.bar"). If AllowUnknownDependencies() has been called - // on the DescriptorPool, this will generate a placeholder type if - // the name is not found (unless the name itself is malformed). The - // placeholder_type parameter indicates what kind of placeholder should be - // constructed in this case. The resolve_mode parameter determines whether - // any symbol is returned, or only symbols that are types. Note, however, - // that LookupSymbol may still return a non-type symbol in LOOKUP_TYPES mode, - // if it believes that's all it could refer to. The caller should always - // check that it receives the type of symbol it was expecting. - enum ResolveMode { - LOOKUP_ALL, LOOKUP_TYPES - }; - Symbol LookupSymbol(const string& name, const string& relative_to, - DescriptorPool::PlaceholderType placeholder_type = - DescriptorPool::PLACEHOLDER_MESSAGE, - ResolveMode resolve_mode = LOOKUP_ALL, - bool build_it = true); - - // Like LookupSymbol() but will not return a placeholder even if - // AllowUnknownDependencies() has been used. - Symbol LookupSymbolNoPlaceholder(const string& name, - const string& relative_to, - ResolveMode resolve_mode = LOOKUP_ALL, - bool build_it = true); - - // Calls tables_->AddSymbol() and records an error if it fails. Returns - // true if successful or false if failed, though most callers can ignore - // the return value since an error has already been recorded. - bool AddSymbol(const string& full_name, - const void* parent, const string& name, - const Message& proto, Symbol symbol); - - // Like AddSymbol(), but succeeds if the symbol is already defined as long - // as the existing definition is also a package (because it's OK to define - // the same package in two different files). Also adds all parents of the - // packgae to the symbol table (e.g. AddPackage("foo.bar", ...) will add - // "foo.bar" and "foo" to the table). - void AddPackage(const string& name, const Message& proto, - const FileDescriptor* file); - - // Checks that the symbol name contains only alphanumeric characters and - // underscores. Records an error otherwise. - void ValidateSymbolName(const string& name, const string& full_name, - const Message& proto); - - // Used by BUILD_ARRAY macro (below) to avoid having to have the type - // specified as a macro parameter. - template - inline void AllocateArray(int size, Type** output) { - *output = tables_->AllocateArray(size); - } - - // Allocates a copy of orig_options in tables_ and stores it in the - // descriptor. Remembers its uninterpreted options, to be interpreted - // later. DescriptorT must be one of the Descriptor messages from - // descriptor.proto. - template void AllocateOptions( - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor, int options_field_tag); - // Specialization for FileOptions. - void AllocateOptions(const FileOptions& orig_options, - FileDescriptor* descriptor); - - // Implementation for AllocateOptions(). Don't call this directly. - template void AllocateOptionsImpl( - const string& name_scope, - const string& element_name, - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor, - std::vector& options_path); - - // These methods all have the same signature for the sake of the BUILD_ARRAY - // macro, below. - void BuildMessage(const DescriptorProto& proto, - const Descriptor* parent, - Descriptor* result); - void BuildFieldOrExtension(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result, - bool is_extension); - void BuildField(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result) { - BuildFieldOrExtension(proto, parent, result, false); - } - void BuildExtension(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result) { - BuildFieldOrExtension(proto, parent, result, true); - } - void BuildExtensionRange(const DescriptorProto::ExtensionRange& proto, - const Descriptor* parent, - Descriptor::ExtensionRange* result); - void BuildReservedRange(const DescriptorProto::ReservedRange& proto, - const Descriptor* parent, - Descriptor::ReservedRange* result); - void BuildReservedRange(const EnumDescriptorProto::EnumReservedRange& proto, - const EnumDescriptor* parent, - EnumDescriptor::ReservedRange* result); - void BuildOneof(const OneofDescriptorProto& proto, - Descriptor* parent, - OneofDescriptor* result); - void CheckEnumValueUniqueness(const EnumDescriptorProto& proto, - const EnumDescriptor* result); - void BuildEnum(const EnumDescriptorProto& proto, - const Descriptor* parent, - EnumDescriptor* result); - void BuildEnumValue(const EnumValueDescriptorProto& proto, - const EnumDescriptor* parent, - EnumValueDescriptor* result); - void BuildService(const ServiceDescriptorProto& proto, - const void* dummy, - ServiceDescriptor* result); - void BuildMethod(const MethodDescriptorProto& proto, - const ServiceDescriptor* parent, - MethodDescriptor* result); - - void LogUnusedDependency(const FileDescriptorProto& proto, - const FileDescriptor* result); - - // Must be run only after building. - // - // NOTE: Options will not be available during cross-linking, as they - // have not yet been interpreted. Defer any handling of options to the - // Validate*Options methods. - void CrossLinkFile(FileDescriptor* file, const FileDescriptorProto& proto); - void CrossLinkMessage(Descriptor* message, const DescriptorProto& proto); - void CrossLinkField(FieldDescriptor* field, - const FieldDescriptorProto& proto); - void CrossLinkExtensionRange(Descriptor::ExtensionRange* range, - const DescriptorProto::ExtensionRange& proto); - void CrossLinkEnum(EnumDescriptor* enum_type, - const EnumDescriptorProto& proto); - void CrossLinkEnumValue(EnumValueDescriptor* enum_value, - const EnumValueDescriptorProto& proto); - void CrossLinkService(ServiceDescriptor* service, - const ServiceDescriptorProto& proto); - void CrossLinkMethod(MethodDescriptor* method, - const MethodDescriptorProto& proto); - - // Must be run only after cross-linking. - void InterpretOptions(); - - // A helper class for interpreting options. - class OptionInterpreter { - public: - // Creates an interpreter that operates in the context of the pool of the - // specified builder, which must not be NULL. We don't take ownership of the - // builder. - explicit OptionInterpreter(DescriptorBuilder* builder); - - ~OptionInterpreter(); - - // Interprets the uninterpreted options in the specified Options message. - // On error, calls AddError() on the underlying builder and returns false. - // Otherwise returns true. - bool InterpretOptions(OptionsToInterpret* options_to_interpret); - - // Updates the given source code info by re-writing uninterpreted option - // locations to refer to the corresponding interpreted option. - void UpdateSourceCodeInfo(SourceCodeInfo* info); - - class AggregateOptionFinder; - - private: - // Interprets uninterpreted_option_ on the specified message, which - // must be the mutable copy of the original options message to which - // uninterpreted_option_ belongs. The given src_path is the source - // location path to the uninterpreted option, and options_path is the - // source location path to the options message. The location paths are - // recorded and then used in UpdateSourceCodeInfo. - bool InterpretSingleOption(Message* options, std::vector& src_path, - std::vector& options_path); - - // Adds the uninterpreted_option to the given options message verbatim. - // Used when AllowUnknownDependencies() is in effect and we can't find - // the option's definition. - void AddWithoutInterpreting(const UninterpretedOption& uninterpreted_option, - Message* options); - - // A recursive helper function that drills into the intermediate fields - // in unknown_fields to check if field innermost_field is set on the - // innermost message. Returns false and sets an error if so. - bool ExamineIfOptionIsSet( - std::vector::const_iterator - intermediate_fields_iter, - std::vector::const_iterator - intermediate_fields_end, - const FieldDescriptor* innermost_field, const string& debug_msg_name, - const UnknownFieldSet& unknown_fields); - - // Validates the value for the option field of the currently interpreted - // option and then sets it on the unknown_field. - bool SetOptionValue(const FieldDescriptor* option_field, - UnknownFieldSet* unknown_fields); - - // Parses an aggregate value for a CPPTYPE_MESSAGE option and - // saves it into *unknown_fields. - bool SetAggregateOption(const FieldDescriptor* option_field, - UnknownFieldSet* unknown_fields); - - // Convenience functions to set an int field the right way, depending on - // its wire type (a single int CppType can represent multiple wire types). - void SetInt32(int number, int32 value, FieldDescriptor::Type type, - UnknownFieldSet* unknown_fields); - void SetInt64(int number, int64 value, FieldDescriptor::Type type, - UnknownFieldSet* unknown_fields); - void SetUInt32(int number, uint32 value, FieldDescriptor::Type type, - UnknownFieldSet* unknown_fields); - void SetUInt64(int number, uint64 value, FieldDescriptor::Type type, - UnknownFieldSet* unknown_fields); - - // A helper function that adds an error at the specified location of the - // option we're currently interpreting, and returns false. - bool AddOptionError(DescriptorPool::ErrorCollector::ErrorLocation location, - const string& msg) { - builder_->AddError(options_to_interpret_->element_name, - *uninterpreted_option_, location, msg); - return false; - } - - // A helper function that adds an error at the location of the option name - // and returns false. - bool AddNameError(const string& msg) { - return AddOptionError(DescriptorPool::ErrorCollector::OPTION_NAME, msg); - } - - // A helper function that adds an error at the location of the option name - // and returns false. - bool AddValueError(const string& msg) { - return AddOptionError(DescriptorPool::ErrorCollector::OPTION_VALUE, msg); - } - - // We interpret against this builder's pool. Is never NULL. We don't own - // this pointer. - DescriptorBuilder* builder_; - - // The options we're currently interpreting, or NULL if we're not in a call - // to InterpretOptions. - const OptionsToInterpret* options_to_interpret_; - - // The option we're currently interpreting within options_to_interpret_, or - // NULL if we're not in a call to InterpretOptions(). This points to a - // submessage of the original option, not the mutable copy. Therefore we - // can use it to find locations recorded by the parser. - const UninterpretedOption* uninterpreted_option_; - - // This maps the element path of uninterpreted options to the element path - // of the resulting interpreted option. This is used to modify a file's - // source code info to account for option interpretation. - std::map, std::vector> interpreted_paths_; - - // This maps the path to a repeated option field to the known number of - // elements the field contains. This is used to track the compute the - // index portion of the element path when interpreting a single option. - std::map, int> repeated_option_counts_; - - // Factory used to create the dynamic messages we need to parse - // any aggregate option values we encounter. - DynamicMessageFactory dynamic_factory_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OptionInterpreter); - }; - - // Work-around for broken compilers: According to the C++ standard, - // OptionInterpreter should have access to the private members of any class - // which has declared DescriptorBuilder as a friend. Unfortunately some old - // versions of GCC and other compilers do not implement this correctly. So, - // we have to have these intermediate methods to provide access. We also - // redundantly declare OptionInterpreter a friend just to make things extra - // clear for these bad compilers. - friend class OptionInterpreter; - friend class OptionInterpreter::AggregateOptionFinder; - - static inline bool get_allow_unknown(const DescriptorPool* pool) { - return pool->allow_unknown_; - } - static inline bool get_enforce_weak(const DescriptorPool* pool) { - return pool->enforce_weak_; - } - static inline bool get_is_placeholder(const Descriptor* descriptor) { - return descriptor->is_placeholder_; - } - static inline void assert_mutex_held(const DescriptorPool* pool) { - if (pool->mutex_ != NULL) { - pool->mutex_->AssertHeld(); - } - } - - // Must be run only after options have been interpreted. - // - // NOTE: Validation code must only reference the options in the mutable - // descriptors, which are the ones that have been interpreted. The const - // proto references are passed in only so they can be provided to calls to - // AddError(). Do not look at their options, which have not been interpreted. - void ValidateFileOptions(FileDescriptor* file, - const FileDescriptorProto& proto); - void ValidateMessageOptions(Descriptor* message, - const DescriptorProto& proto); - void ValidateFieldOptions(FieldDescriptor* field, - const FieldDescriptorProto& proto); - void ValidateEnumOptions(EnumDescriptor* enm, - const EnumDescriptorProto& proto); - void ValidateEnumValueOptions(EnumValueDescriptor* enum_value, - const EnumValueDescriptorProto& proto); - void ValidateServiceOptions(ServiceDescriptor* service, - const ServiceDescriptorProto& proto); - void ValidateMethodOptions(MethodDescriptor* method, - const MethodDescriptorProto& proto); - void ValidateProto3(FileDescriptor* file, - const FileDescriptorProto& proto); - void ValidateProto3Message(Descriptor* message, - const DescriptorProto& proto); - void ValidateProto3Field(FieldDescriptor* field, - const FieldDescriptorProto& proto); - void ValidateProto3Enum(EnumDescriptor* enm, - const EnumDescriptorProto& proto); - - // Returns true if the map entry message is compatible with the - // auto-generated entry message from map fields syntax. - bool ValidateMapEntry(FieldDescriptor* field, - const FieldDescriptorProto& proto); - - // Recursively detects naming conflicts with map entry types for a - // better error message. - void DetectMapConflicts(const Descriptor* message, - const DescriptorProto& proto); - - void ValidateJSType(FieldDescriptor* field, - const FieldDescriptorProto& proto); -}; - -const FileDescriptor* DescriptorPool::BuildFile( - const FileDescriptorProto& proto) { - GOOGLE_CHECK(fallback_database_ == NULL) - << "Cannot call BuildFile on a DescriptorPool that uses a " - "DescriptorDatabase. You must instead find a way to get your file " - "into the underlying database."; - GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK. - tables_->known_bad_symbols_.clear(); - tables_->known_bad_files_.clear(); - return DescriptorBuilder(this, tables_.get(), NULL).BuildFile(proto); -} - -const FileDescriptor* DescriptorPool::BuildFileCollectingErrors( - const FileDescriptorProto& proto, - ErrorCollector* error_collector) { - GOOGLE_CHECK(fallback_database_ == NULL) - << "Cannot call BuildFile on a DescriptorPool that uses a " - "DescriptorDatabase. You must instead find a way to get your file " - "into the underlying database."; - GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK. - tables_->known_bad_symbols_.clear(); - tables_->known_bad_files_.clear(); - return DescriptorBuilder(this, tables_.get(), - error_collector).BuildFile(proto); -} - -const FileDescriptor* DescriptorPool::BuildFileFromDatabase( - const FileDescriptorProto& proto) const { - mutex_->AssertHeld(); - if (tables_->known_bad_files_.count(proto.name()) > 0) { - return NULL; - } - const FileDescriptor* result = - DescriptorBuilder(this, tables_.get(), - default_error_collector_).BuildFile(proto); - if (result == NULL) { - tables_->known_bad_files_.insert(proto.name()); - } - return result; -} - -DescriptorBuilder::DescriptorBuilder( - const DescriptorPool* pool, - DescriptorPool::Tables* tables, - DescriptorPool::ErrorCollector* error_collector) - : pool_(pool), - tables_(tables), - error_collector_(error_collector), - had_errors_(false), - possible_undeclared_dependency_(NULL), - undefine_resolved_name_("") {} - -DescriptorBuilder::~DescriptorBuilder() {} - -void DescriptorBuilder::AddError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error) { - if (error_collector_ == NULL) { - if (!had_errors_) { - GOOGLE_LOG(ERROR) << "Invalid proto descriptor for file \"" << filename_ - << "\":"; - } - GOOGLE_LOG(ERROR) << " " << element_name << ": " << error; - } else { - error_collector_->AddError(filename_, element_name, - &descriptor, location, error); - } - had_errors_ = true; -} - -void DescriptorBuilder::AddError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const char* error) { - AddError(element_name, descriptor, location, string(error)); -} - -void DescriptorBuilder::AddNotDefinedError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& undefined_symbol) { - if (possible_undeclared_dependency_ == NULL && - undefine_resolved_name_.empty()) { - AddError(element_name, descriptor, location, - "\"" + undefined_symbol + "\" is not defined."); - } else { - if (possible_undeclared_dependency_ != NULL) { - AddError(element_name, descriptor, location, - "\"" + possible_undeclared_dependency_name_ + - "\" seems to be defined in \"" + - possible_undeclared_dependency_->name() + "\", which is not " - "imported by \"" + filename_ + "\". To use it here, please " - "add the necessary import."); - } - if (!undefine_resolved_name_.empty()) { - AddError(element_name, descriptor, location, - "\"" + undefined_symbol + "\" is resolved to \"" + - undefine_resolved_name_ + "\", which is not defined. " - "The innermost scope is searched first in name resolution. " - "Consider using a leading '.'(i.e., \"." - + undefined_symbol + - "\") to start from the outermost scope."); - } - } -} - -void DescriptorBuilder::AddWarning( - const string& element_name, const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error) { - if (error_collector_ == NULL) { - GOOGLE_LOG(WARNING) << filename_ << " " << element_name << ": " << error; - } else { - error_collector_->AddWarning(filename_, element_name, &descriptor, location, - error); - } -} - -bool DescriptorBuilder::IsInPackage(const FileDescriptor* file, - const string& package_name) { - return HasPrefixString(file->package(), package_name) && - (file->package().size() == package_name.size() || - file->package()[package_name.size()] == '.'); -} - -void DescriptorBuilder::RecordPublicDependencies(const FileDescriptor* file) { - if (file == NULL || !dependencies_.insert(file).second) return; - for (int i = 0; file != NULL && i < file->public_dependency_count(); i++) { - RecordPublicDependencies(file->public_dependency(i)); - } -} - -Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper( - const DescriptorPool* pool, const string& name, bool build_it) { - // If we are looking at an underlay, we must lock its mutex_, since we are - // accessing the underlay's tables_ directly. - MutexLockMaybe lock((pool == pool_) ? NULL : pool->mutex_); - - Symbol result = pool->tables_->FindSymbol(name); - if (result.IsNull() && pool->underlay_ != NULL) { - // Symbol not found; check the underlay. - result = FindSymbolNotEnforcingDepsHelper(pool->underlay_, name); - } - - if (result.IsNull()) { - // With lazily_build_dependencies_, a symbol lookup at cross link time is - // not guaranteed to be successful. In most cases, build_it will be false, - // which intentionally prevents us from building an import until it's - // actually needed. In some cases, like registering an extension, we want - // to build the file containing the symbol, and build_it will be set. - // Also, build_it will be true when !lazily_build_dependencies_, to provide - // better error reporting of missing dependencies. - if (build_it && pool->TryFindSymbolInFallbackDatabase(name)) { - result = pool->tables_->FindSymbol(name); - } - } - - return result; -} - -Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const string& name, - bool build_it) { - return FindSymbolNotEnforcingDepsHelper(pool_, name, build_it); -} - -Symbol DescriptorBuilder::FindSymbol(const string& name, bool build_it) { - Symbol result = FindSymbolNotEnforcingDeps(name, build_it); - - if (result.IsNull()) return result; - - if (!pool_->enforce_dependencies_) { - // Hack for CompilerUpgrader, and also used for lazily_build_dependencies_ - return result; - } - - // Only find symbols which were defined in this file or one of its - // dependencies. - const FileDescriptor* file = result.GetFile(); - if (file == file_ || dependencies_.count(file) > 0) { - unused_dependency_.erase(file); - return result; - } - - if (result.type == Symbol::PACKAGE) { - // Arg, this is overcomplicated. The symbol is a package name. It could - // be that the package was defined in multiple files. result.GetFile() - // returns the first file we saw that used this package. We've determined - // that that file is not a direct dependency of the file we are currently - // building, but it could be that some other file which *is* a direct - // dependency also defines the same package. We can't really rule out this - // symbol unless none of the dependencies define it. - if (IsInPackage(file_, name)) return result; - for (std::set::const_iterator it = - dependencies_.begin(); - it != dependencies_.end(); ++it) { - // Note: A dependency may be NULL if it was not found or had errors. - if (*it != NULL && IsInPackage(*it, name)) return result; - } - } - - possible_undeclared_dependency_ = file; - possible_undeclared_dependency_name_ = name; - return kNullSymbol; -} - -Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(const string& name, - const string& relative_to, - ResolveMode resolve_mode, - bool build_it) { - possible_undeclared_dependency_ = NULL; - undefine_resolved_name_.clear(); - - if (!name.empty() && name[0] == '.') { - // Fully-qualified name. - return FindSymbol(name.substr(1), build_it); - } - - // If name is something like "Foo.Bar.baz", and symbols named "Foo" are - // defined in multiple parent scopes, we only want to find "Bar.baz" in the - // innermost one. E.g., the following should produce an error: - // message Bar { message Baz {} } - // message Foo { - // message Bar { - // } - // optional Bar.Baz baz = 1; - // } - // So, we look for just "Foo" first, then look for "Bar.baz" within it if - // found. - string::size_type name_dot_pos = name.find_first_of('.'); - string first_part_of_name; - if (name_dot_pos == string::npos) { - first_part_of_name = name; - } else { - first_part_of_name = name.substr(0, name_dot_pos); - } - - string scope_to_try(relative_to); - - while (true) { - // Chop off the last component of the scope. - string::size_type dot_pos = scope_to_try.find_last_of('.'); - if (dot_pos == string::npos) { - return FindSymbol(name, build_it); - } else { - scope_to_try.erase(dot_pos); - } - - // Append ".first_part_of_name" and try to find. - string::size_type old_size = scope_to_try.size(); - scope_to_try.append(1, '.'); - scope_to_try.append(first_part_of_name); - Symbol result = FindSymbol(scope_to_try, build_it); - if (!result.IsNull()) { - if (first_part_of_name.size() < name.size()) { - // name is a compound symbol, of which we only found the first part. - // Now try to look up the rest of it. - if (result.IsAggregate()) { - scope_to_try.append(name, first_part_of_name.size(), - name.size() - first_part_of_name.size()); - result = FindSymbol(scope_to_try, build_it); - if (result.IsNull()) { - undefine_resolved_name_ = scope_to_try; - } - return result; - } else { - // We found a symbol but it's not an aggregate. Continue the loop. - } - } else { - if (resolve_mode == LOOKUP_TYPES && !result.IsType()) { - // We found a symbol but it's not a type. Continue the loop. - } else { - return result; - } - } - } - - // Not found. Remove the name so we can try again. - scope_to_try.erase(old_size); - } -} - -Symbol DescriptorBuilder::LookupSymbol( - const string& name, const string& relative_to, - DescriptorPool::PlaceholderType placeholder_type, ResolveMode resolve_mode, - bool build_it) { - Symbol result = - LookupSymbolNoPlaceholder(name, relative_to, resolve_mode, build_it); - if (result.IsNull() && pool_->allow_unknown_) { - // Not found, but AllowUnknownDependencies() is enabled. Return a - // placeholder instead. - result = pool_->NewPlaceholderWithMutexHeld(name, placeholder_type); - } - return result; -} - -static bool ValidateQualifiedName(const string& name) { - bool last_was_period = false; - - for (int i = 0; i < name.size(); i++) { - // I don't trust isalnum() due to locales. :( - if (('a' <= name[i] && name[i] <= 'z') || - ('A' <= name[i] && name[i] <= 'Z') || - ('0' <= name[i] && name[i] <= '9') || (name[i] == '_')) { - last_was_period = false; - } else if (name[i] == '.') { - if (last_was_period) return false; - last_was_period = true; - } else { - return false; - } - } - - return !name.empty() && !last_was_period; -} - -Symbol DescriptorPool::NewPlaceholder(const string& name, - PlaceholderType placeholder_type) const { - MutexLockMaybe lock(mutex_); - return NewPlaceholderWithMutexHeld(name, placeholder_type); -} - -Symbol DescriptorPool::NewPlaceholderWithMutexHeld( - const string& name, PlaceholderType placeholder_type) const { - if (mutex_) { - mutex_->AssertHeld(); - } - // Compute names. - const string* placeholder_full_name; - const string* placeholder_name; - const string* placeholder_package; - - if (!ValidateQualifiedName(name)) return kNullSymbol; - if (name[0] == '.') { - // Fully-qualified. - placeholder_full_name = tables_->AllocateString(name.substr(1)); - } else { - placeholder_full_name = tables_->AllocateString(name); - } - - string::size_type dotpos = placeholder_full_name->find_last_of('.'); - if (dotpos != string::npos) { - placeholder_package = tables_->AllocateString( - placeholder_full_name->substr(0, dotpos)); - placeholder_name = tables_->AllocateString( - placeholder_full_name->substr(dotpos + 1)); - } else { - placeholder_package = &internal::GetEmptyString(); - placeholder_name = placeholder_full_name; - } - - // Create the placeholders. - FileDescriptor* placeholder_file = NewPlaceholderFileWithMutexHeld( - *placeholder_full_name + ".placeholder.proto"); - placeholder_file->package_ = placeholder_package; - - if (placeholder_type == PLACEHOLDER_ENUM) { - placeholder_file->enum_type_count_ = 1; - placeholder_file->enum_types_ = - tables_->AllocateArray(1); - - EnumDescriptor* placeholder_enum = &placeholder_file->enum_types_[0]; - memset(placeholder_enum, 0, sizeof(*placeholder_enum)); - - placeholder_enum->full_name_ = placeholder_full_name; - placeholder_enum->name_ = placeholder_name; - placeholder_enum->file_ = placeholder_file; - placeholder_enum->options_ = &EnumOptions::default_instance(); - placeholder_enum->is_placeholder_ = true; - placeholder_enum->is_unqualified_placeholder_ = (name[0] != '.'); - - // Enums must have at least one value. - placeholder_enum->value_count_ = 1; - placeholder_enum->values_ = tables_->AllocateArray(1); - - EnumValueDescriptor* placeholder_value = &placeholder_enum->values_[0]; - memset(placeholder_value, 0, sizeof(*placeholder_value)); - - placeholder_value->name_ = tables_->AllocateString("PLACEHOLDER_VALUE"); - // Note that enum value names are siblings of their type, not children. - placeholder_value->full_name_ = - placeholder_package->empty() ? placeholder_value->name_ : - tables_->AllocateString(*placeholder_package + ".PLACEHOLDER_VALUE"); - - placeholder_value->number_ = 0; - placeholder_value->type_ = placeholder_enum; - placeholder_value->options_ = &EnumValueOptions::default_instance(); - - return Symbol(placeholder_enum); - } else { - placeholder_file->message_type_count_ = 1; - placeholder_file->message_types_ = - tables_->AllocateArray(1); - - Descriptor* placeholder_message = &placeholder_file->message_types_[0]; - memset(placeholder_message, 0, sizeof(*placeholder_message)); - - placeholder_message->full_name_ = placeholder_full_name; - placeholder_message->name_ = placeholder_name; - placeholder_message->file_ = placeholder_file; - placeholder_message->options_ = &MessageOptions::default_instance(); - placeholder_message->is_placeholder_ = true; - placeholder_message->is_unqualified_placeholder_ = (name[0] != '.'); - - if (placeholder_type == PLACEHOLDER_EXTENDABLE_MESSAGE) { - placeholder_message->extension_range_count_ = 1; - placeholder_message->extension_ranges_ = - tables_->AllocateArray(1); - placeholder_message->extension_ranges_->start = 1; - // kMaxNumber + 1 because ExtensionRange::end is exclusive. - placeholder_message->extension_ranges_->end = - FieldDescriptor::kMaxNumber + 1; - } - - return Symbol(placeholder_message); - } -} - -FileDescriptor* DescriptorPool::NewPlaceholderFile(const string& name) const { - MutexLockMaybe lock(mutex_); - return NewPlaceholderFileWithMutexHeld(name); -} - -FileDescriptor* DescriptorPool::NewPlaceholderFileWithMutexHeld( - const string& name) const { - if (mutex_) { - mutex_->AssertHeld(); - } - FileDescriptor* placeholder = tables_->Allocate(); - memset(placeholder, 0, sizeof(*placeholder)); - - placeholder->name_ = tables_->AllocateString(name); - placeholder->package_ = &internal::GetEmptyString(); - placeholder->pool_ = this; - placeholder->options_ = &FileOptions::default_instance(); - placeholder->tables_ = &FileDescriptorTables::GetEmptyInstance(); - placeholder->source_code_info_ = &SourceCodeInfo::default_instance(); - placeholder->is_placeholder_ = true; - placeholder->syntax_ = FileDescriptor::SYNTAX_PROTO2; - placeholder->finished_building_ = true; - // All other fields are zero or NULL. - - return placeholder; -} - -bool DescriptorBuilder::AddSymbol( - const string& full_name, const void* parent, const string& name, - const Message& proto, Symbol symbol) { - // If the caller passed NULL for the parent, the symbol is at file scope. - // Use its file as the parent instead. - if (parent == NULL) parent = file_; - - if (tables_->AddSymbol(full_name, symbol)) { - if (!file_tables_->AddAliasUnderParent(parent, name, symbol)) { - // This is only possible if there was already an error adding something of - // the same name. - if (!had_errors_) { - GOOGLE_LOG(DFATAL) << "\"" << full_name << "\" not previously defined in " - "symbols_by_name_, but was defined in " - "symbols_by_parent_; this shouldn't be possible."; - } - return false; - } - return true; - } else { - const FileDescriptor* other_file = tables_->FindSymbol(full_name).GetFile(); - if (other_file == file_) { - string::size_type dot_pos = full_name.find_last_of('.'); - if (dot_pos == string::npos) { - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + full_name + "\" is already defined."); - } else { - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + full_name.substr(dot_pos + 1) + - "\" is already defined in \"" + - full_name.substr(0, dot_pos) + "\"."); - } - } else { - // Symbol seems to have been defined in a different file. - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + full_name + "\" is already defined in file \"" + - other_file->name() + "\"."); - } - return false; - } -} - -void DescriptorBuilder::AddPackage( - const string& name, const Message& proto, const FileDescriptor* file) { - if (tables_->AddSymbol(name, Symbol(file))) { - // Success. Also add parent package, if any. - string::size_type dot_pos = name.find_last_of('.'); - if (dot_pos == string::npos) { - // No parents. - ValidateSymbolName(name, name, proto); - } else { - // Has parent. - string* parent_name = tables_->AllocateString(name.substr(0, dot_pos)); - AddPackage(*parent_name, proto, file); - ValidateSymbolName(name.substr(dot_pos + 1), name, proto); - } - } else { - Symbol existing_symbol = tables_->FindSymbol(name); - // It's OK to redefine a package. - if (existing_symbol.type != Symbol::PACKAGE) { - // Symbol seems to have been defined in a different file. - AddError(name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + name + "\" is already defined (as something other than " - "a package) in file \"" + existing_symbol.GetFile()->name() + - "\"."); - } - } -} - -void DescriptorBuilder::ValidateSymbolName( - const string& name, const string& full_name, const Message& proto) { - if (name.empty()) { - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "Missing name."); - } else { - for (int i = 0; i < name.size(); i++) { - // I don't trust isalnum() due to locales. :( - if ((name[i] < 'a' || 'z' < name[i]) && - (name[i] < 'A' || 'Z' < name[i]) && - (name[i] < '0' || '9' < name[i]) && - (name[i] != '_')) { - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + name + "\" is not a valid identifier."); - } - } - } -} - -// ------------------------------------------------------------------- - -// This generic implementation is good for all descriptors except -// FileDescriptor. -template void DescriptorBuilder::AllocateOptions( - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor, int options_field_tag) { - std::vector options_path; - descriptor->GetLocationPath(&options_path); - options_path.push_back(options_field_tag); - AllocateOptionsImpl(descriptor->full_name(), descriptor->full_name(), - orig_options, descriptor, options_path); -} - -// We specialize for FileDescriptor. -void DescriptorBuilder::AllocateOptions(const FileOptions& orig_options, - FileDescriptor* descriptor) { - std::vector options_path; - options_path.push_back(FileDescriptorProto::kOptionsFieldNumber); - // We add the dummy token so that LookupSymbol does the right thing. - AllocateOptionsImpl(descriptor->package() + ".dummy", descriptor->name(), - orig_options, descriptor, options_path); -} - -template void DescriptorBuilder::AllocateOptionsImpl( - const string& name_scope, - const string& element_name, - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor, - std::vector& options_path) { - // We need to use a dummy pointer to work around a bug in older versions of - // GCC. Otherwise, the following two lines could be replaced with: - // typename DescriptorT::OptionsType* options = - // tables_->AllocateMessage(); - typename DescriptorT::OptionsType* const dummy = NULL; - typename DescriptorT::OptionsType* options = tables_->AllocateMessage(dummy); - // Avoid using MergeFrom()/CopyFrom() in this class to make it -fno-rtti - // friendly. Without RTTI, MergeFrom() and CopyFrom() will fallback to the - // reflection based method, which requires the Descriptor. However, we are in - // the middle of building the descriptors, thus the deadlock. - options->ParseFromString(orig_options.SerializeAsString()); - descriptor->options_ = options; - - // Don't add to options_to_interpret_ unless there were uninterpreted - // options. This not only avoids unnecessary work, but prevents a - // bootstrapping problem when building descriptors for descriptor.proto. - // descriptor.proto does not contain any uninterpreted options, but - // attempting to interpret options anyway will cause - // OptionsType::GetDescriptor() to be called which may then deadlock since - // we're still trying to build it. - if (options->uninterpreted_option_size() > 0) { - options_to_interpret_.push_back( - OptionsToInterpret(name_scope, element_name, options_path, - &orig_options, options)); - } -} - - -// A common pattern: We want to convert a repeated field in the descriptor -// to an array of values, calling some method to build each value. -#define BUILD_ARRAY(INPUT, OUTPUT, NAME, METHOD, PARENT) \ - OUTPUT->NAME##_count_ = INPUT.NAME##_size(); \ - AllocateArray(INPUT.NAME##_size(), &OUTPUT->NAME##s_); \ - for (int i = 0; i < INPUT.NAME##_size(); i++) { \ - METHOD(INPUT.NAME(i), PARENT, OUTPUT->NAME##s_ + i); \ - } - -void DescriptorBuilder::AddRecursiveImportError( - const FileDescriptorProto& proto, int from_here) { - string error_message("File recursively imports itself: "); - for (int i = from_here; i < tables_->pending_files_.size(); i++) { - error_message.append(tables_->pending_files_[i]); - error_message.append(" -> "); - } - error_message.append(proto.name()); - - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, - error_message); -} - -void DescriptorBuilder::AddTwiceListedError(const FileDescriptorProto& proto, - int index) { - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, - "Import \"" + proto.dependency(index) + "\" was listed twice."); -} - -void DescriptorBuilder::AddImportError(const FileDescriptorProto& proto, - int index) { - string message; - if (pool_->fallback_database_ == NULL) { - message = "Import \"" + proto.dependency(index) + - "\" has not been loaded."; - } else { - message = "Import \"" + proto.dependency(index) + - "\" was not found or had errors."; - } - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, message); -} - -static bool ExistingFileMatchesProto(const FileDescriptor* existing_file, - const FileDescriptorProto& proto) { - FileDescriptorProto existing_proto; - existing_file->CopyTo(&existing_proto); - // TODO(liujisi): Remove it when CopyTo supports copying syntax params when - // syntax="proto2". - if (existing_file->syntax() == FileDescriptor::SYNTAX_PROTO2 && - proto.has_syntax()) { - existing_proto.set_syntax( - existing_file->SyntaxName(existing_file->syntax())); - } - - return existing_proto.SerializeAsString() == proto.SerializeAsString(); -} - -const FileDescriptor* DescriptorBuilder::BuildFile( - const FileDescriptorProto& proto) { - filename_ = proto.name(); - - // Check if the file already exists and is identical to the one being built. - // Note: This only works if the input is canonical -- that is, it - // fully-qualifies all type names, has no UninterpretedOptions, etc. - // This is fine, because this idempotency "feature" really only exists to - // accommodate one hack in the proto1->proto2 migration layer. - const FileDescriptor* existing_file = tables_->FindFile(filename_); - if (existing_file != NULL) { - // File already in pool. Compare the existing one to the input. - if (ExistingFileMatchesProto(existing_file, proto)) { - // They're identical. Return the existing descriptor. - return existing_file; - } - - // Not a match. The error will be detected and handled later. - } - - // Check to see if this file is already on the pending files list. - // TODO(kenton): Allow recursive imports? It may not work with some - // (most?) programming languages. E.g., in C++, a forward declaration - // of a type is not sufficient to allow it to be used even in a - // generated header file due to inlining. This could perhaps be - // worked around using tricks involving inserting #include statements - // mid-file, but that's pretty ugly, and I'm pretty sure there are - // some languages out there that do not allow recursive dependencies - // at all. - for (int i = 0; i < tables_->pending_files_.size(); i++) { - if (tables_->pending_files_[i] == proto.name()) { - AddRecursiveImportError(proto, i); - return NULL; - } - } - - // If we have a fallback_database_, and we aren't doing lazy import building, - // attempt to load all dependencies now, before checkpointing tables_. This - // avoids confusion with recursive checkpoints. - if (!pool_->lazily_build_dependencies_) { - if (pool_->fallback_database_ != NULL) { - tables_->pending_files_.push_back(proto.name()); - for (int i = 0; i < proto.dependency_size(); i++) { - if (tables_->FindFile(proto.dependency(i)) == NULL && - (pool_->underlay_ == NULL || - pool_->underlay_->FindFileByName(proto.dependency(i)) == NULL)) { - // We don't care what this returns since we'll find out below anyway. - pool_->TryFindFileInFallbackDatabase(proto.dependency(i)); - } - } - tables_->pending_files_.pop_back(); - } - } - - // Checkpoint the tables so that we can roll back if something goes wrong. - tables_->AddCheckpoint(); - - FileDescriptor* result = BuildFileImpl(proto); - - file_tables_->FinalizeTables(); - if (result) { - tables_->ClearLastCheckpoint(); - result->finished_building_ = true; - } else { - tables_->RollbackToLastCheckpoint(); - } - - return result; -} - -FileDescriptor* DescriptorBuilder::BuildFileImpl( - const FileDescriptorProto& proto) { - FileDescriptor* result = tables_->Allocate(); - file_ = result; - - result->is_placeholder_ = false; - result->finished_building_ = false; - SourceCodeInfo *info = NULL; - if (proto.has_source_code_info()) { - info = tables_->AllocateMessage(); - info->CopyFrom(proto.source_code_info()); - result->source_code_info_ = info; - } else { - result->source_code_info_ = &SourceCodeInfo::default_instance(); - } - - file_tables_ = tables_->AllocateFileTables(); - file_->tables_ = file_tables_; - - if (!proto.has_name()) { - AddError("", proto, DescriptorPool::ErrorCollector::OTHER, - "Missing field: FileDescriptorProto.name."); - } - - // TODO(liujisi): Report error when the syntax is empty after all the protos - // have added the syntax statement. - if (proto.syntax().empty() || proto.syntax() == "proto2") { - file_->syntax_ = FileDescriptor::SYNTAX_PROTO2; - } else if (proto.syntax() == "proto3") { - file_->syntax_ = FileDescriptor::SYNTAX_PROTO3; - } else { - file_->syntax_ = FileDescriptor::SYNTAX_UNKNOWN; - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, - "Unrecognized syntax: " + proto.syntax()); - } - - result->name_ = tables_->AllocateString(proto.name()); - if (proto.has_package()) { - result->package_ = tables_->AllocateString(proto.package()); - } else { - // We cannot rely on proto.package() returning a valid string if - // proto.has_package() is false, because we might be running at static - // initialization time, in which case default values have not yet been - // initialized. - result->package_ = tables_->AllocateString(""); - } - result->pool_ = pool_; - - // Add to tables. - if (!tables_->AddFile(result)) { - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, - "A file with this name is already in the pool."); - // Bail out early so that if this is actually the exact same file, we - // don't end up reporting that every single symbol is already defined. - return NULL; - } - if (!result->package().empty()) { - AddPackage(result->package(), proto, result); - } - - // Make sure all dependencies are loaded. - std::set seen_dependencies; - result->dependency_count_ = proto.dependency_size(); - result->dependencies_ = - tables_->AllocateArray(proto.dependency_size()); - if (pool_->lazily_build_dependencies_) { - result->dependencies_once_ = tables_->AllocateOnceDynamic(); - result->dependencies_names_ = - tables_->AllocateArray(proto.dependency_size()); - if (proto.dependency_size() > 0) { - memset(result->dependencies_names_, 0, - sizeof(*result->dependencies_names_) * proto.dependency_size()); - } - } else { - result->dependencies_once_ = NULL; - result->dependencies_names_ = NULL; - } - unused_dependency_.clear(); - std::set weak_deps; - for (int i = 0; i < proto.weak_dependency_size(); ++i) { - weak_deps.insert(proto.weak_dependency(i)); - } - for (int i = 0; i < proto.dependency_size(); i++) { - if (!seen_dependencies.insert(proto.dependency(i)).second) { - AddTwiceListedError(proto, i); - } - - const FileDescriptor* dependency = tables_->FindFile(proto.dependency(i)); - if (dependency == NULL && pool_->underlay_ != NULL) { - dependency = pool_->underlay_->FindFileByName(proto.dependency(i)); - } - - if (dependency == result) { - // Recursive import. dependency/result is not fully initialized, and it's - // dangerous to try to do anything with it. The recursive import error - // will be detected and reported in DescriptorBuilder::BuildFile(). - return NULL; - } - - if (dependency == NULL) { - if (!pool_->lazily_build_dependencies_) { - if (pool_->allow_unknown_ || - (!pool_->enforce_weak_ && weak_deps.find(i) != weak_deps.end())) { - dependency = - pool_->NewPlaceholderFileWithMutexHeld(proto.dependency(i)); - } else { - AddImportError(proto, i); - } - } - } else { - // Add to unused_dependency_ to track unused imported files. - // Note: do not track unused imported files for public import. - if (pool_->enforce_dependencies_ && - (pool_->unused_import_track_files_.find(proto.name()) != - pool_->unused_import_track_files_.end()) && - (dependency->public_dependency_count() == 0)) { - unused_dependency_.insert(dependency); - } - } - - result->dependencies_[i] = dependency; - if (pool_->lazily_build_dependencies_ && !dependency) { - result->dependencies_names_[i] = - tables_->AllocateString(proto.dependency(i)); - } - } - - // Check public dependencies. - int public_dependency_count = 0; - result->public_dependencies_ = tables_->AllocateArray( - proto.public_dependency_size()); - for (int i = 0; i < proto.public_dependency_size(); i++) { - // Only put valid public dependency indexes. - int index = proto.public_dependency(i); - if (index >= 0 && index < proto.dependency_size()) { - result->public_dependencies_[public_dependency_count++] = index; - // Do not track unused imported files for public import. - // Calling dependency(i) builds that file when doing lazy imports, - // need to avoid doing this. Unused dependency detection isn't done - // when building lazily, anyways. - if (!pool_->lazily_build_dependencies_) { - unused_dependency_.erase(result->dependency(index)); - } - } else { - AddError(proto.name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Invalid public dependency index."); - } - } - result->public_dependency_count_ = public_dependency_count; - - // Build dependency set - dependencies_.clear(); - // We don't/can't do proper dependency error checking when - // lazily_build_dependencies_, and calling dependency(i) will force - // a dependency to be built, which we don't want. - if (!pool_->lazily_build_dependencies_) { - for (int i = 0; i < result->dependency_count(); i++) { - RecordPublicDependencies(result->dependency(i)); - } - } - - // Check weak dependencies. - int weak_dependency_count = 0; - result->weak_dependencies_ = tables_->AllocateArray( - proto.weak_dependency_size()); - for (int i = 0; i < proto.weak_dependency_size(); i++) { - int index = proto.weak_dependency(i); - if (index >= 0 && index < proto.dependency_size()) { - result->weak_dependencies_[weak_dependency_count++] = index; - } else { - AddError(proto.name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Invalid weak dependency index."); - } - } - result->weak_dependency_count_ = weak_dependency_count; - - // Convert children. - BUILD_ARRAY(proto, result, message_type, BuildMessage , NULL); - BUILD_ARRAY(proto, result, enum_type , BuildEnum , NULL); - BUILD_ARRAY(proto, result, service , BuildService , NULL); - BUILD_ARRAY(proto, result, extension , BuildExtension, NULL); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result); - } - - // Note that the following steps must occur in exactly the specified order. - - // Cross-link. - CrossLinkFile(result, proto); - - // Interpret any remaining uninterpreted options gathered into - // options_to_interpret_ during descriptor building. Cross-linking has made - // extension options known, so all interpretations should now succeed. - if (!had_errors_) { - OptionInterpreter option_interpreter(this); - for (std::vector::iterator iter = - options_to_interpret_.begin(); - iter != options_to_interpret_.end(); ++iter) { - option_interpreter.InterpretOptions(&(*iter)); - } - options_to_interpret_.clear(); - - if (info != NULL) { - option_interpreter.UpdateSourceCodeInfo(info); - } - } - - // Validate options. See comments at InternalSetLazilyBuildDependencies about - // error checking and lazy import building. - if (!had_errors_ && !pool_->lazily_build_dependencies_) { - ValidateFileOptions(result, proto); - } - - // Additional naming conflict check for map entry types. Only need to check - // this if there are already errors. - if (had_errors_) { - for (int i = 0; i < proto.message_type_size(); ++i) { - DetectMapConflicts(result->message_type(i), proto.message_type(i)); - } - } - - - // Again, see comments at InternalSetLazilyBuildDependencies about error - // checking. - if (!unused_dependency_.empty() && !pool_->lazily_build_dependencies_) { - LogUnusedDependency(proto, result); - } - - if (had_errors_) { - return NULL; - } else { - return result; - } -} - -void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, - const Descriptor* parent, - Descriptor* result) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); - if (!full_name->empty()) full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - result->containing_type_ = parent; - result->is_placeholder_ = false; - result->is_unqualified_placeholder_ = false; - - // Build oneofs first so that fields and extension ranges can refer to them. - BUILD_ARRAY(proto, result, oneof_decl , BuildOneof , result); - BUILD_ARRAY(proto, result, field , BuildField , result); - BUILD_ARRAY(proto, result, nested_type , BuildMessage , result); - BUILD_ARRAY(proto, result, enum_type , BuildEnum , result); - BUILD_ARRAY(proto, result, extension_range, BuildExtensionRange, result); - BUILD_ARRAY(proto, result, extension , BuildExtension , result); - BUILD_ARRAY(proto, result, reserved_range , BuildReservedRange , result); - - // Copy reserved names. - int reserved_name_count = proto.reserved_name_size(); - result->reserved_name_count_ = reserved_name_count; - result->reserved_names_ = - tables_->AllocateArray(reserved_name_count); - for (int i = 0; i < reserved_name_count; ++i) { - result->reserved_names_[i] = - tables_->AllocateString(proto.reserved_name(i)); - } - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result, - DescriptorProto::kOptionsFieldNumber); - } - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); - - for (int i = 0; i < proto.reserved_range_size(); i++) { - const DescriptorProto_ReservedRange& range1 = proto.reserved_range(i); - for (int j = i + 1; j < proto.reserved_range_size(); j++) { - const DescriptorProto_ReservedRange& range2 = proto.reserved_range(j); - if (range1.end() > range2.start() && range2.end() > range1.start()) { - AddError(result->full_name(), proto.reserved_range(i), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Reserved range $0 to $1 overlaps with " - "already-defined range $2 to $3.", - range2.start(), range2.end() - 1, - range1.start(), range1.end() - 1)); - } - } - } - - HASH_SET reserved_name_set; - for (int i = 0; i < proto.reserved_name_size(); i++) { - const string& name = proto.reserved_name(i); - if (reserved_name_set.find(name) == reserved_name_set.end()) { - reserved_name_set.insert(name); - } else { - AddError(name, proto, DescriptorPool::ErrorCollector::NAME, - strings::Substitute( - "Field name \"$0\" is reserved multiple times.", - name)); - } - } - - 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++) { - const Descriptor::ExtensionRange* range = result->extension_range(j); - if (range->start <= field->number() && field->number() < range->end) { - AddError(field->full_name(), proto.extension_range(j), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Extension range $0 to $1 includes field \"$2\" ($3).", - range->start, range->end - 1, - field->name(), field->number())); - } - } - for (int j = 0; j < result->reserved_range_count(); j++) { - const Descriptor::ReservedRange* range = result->reserved_range(j); - if (range->start <= field->number() && field->number() < range->end) { - AddError(field->full_name(), proto.reserved_range(j), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Field \"$0\" uses reserved number $1.", - field->name(), field->number())); - } - } - if (reserved_name_set.find(field->name()) != reserved_name_set.end()) { - AddError(field->full_name(), proto.field(i), - DescriptorPool::ErrorCollector::NAME, - strings::Substitute( - "Field name \"$0\" is reserved.", field->name())); - } - } - - // Check that extension ranges don't overlap and don't include - // reserved field numbers. - for (int i = 0; i < result->extension_range_count(); i++) { - const Descriptor::ExtensionRange* range1 = result->extension_range(i); - for (int j = 0; j < result->reserved_range_count(); j++) { - const Descriptor::ReservedRange* range2 = result->reserved_range(j); - if (range1->end > range2->start && range2->end > range1->start) { - AddError(result->full_name(), proto.extension_range(i), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Extension range $0 to $1 overlaps with " - "reserved range $2 to $3.", - range1->start, range1->end - 1, - range2->start, range2->end - 1)); - } - } - for (int j = i + 1; j < result->extension_range_count(); j++) { - const Descriptor::ExtensionRange* range2 = result->extension_range(j); - if (range1->end > range2->start && range2->end > range1->start) { - AddError(result->full_name(), proto.extension_range(i), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Extension range $0 to $1 overlaps with " - "already-defined range $2 to $3.", - range2->start, range2->end - 1, - range1->start, range1->end - 1)); - } - } - } -} - - -void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result, - bool is_extension) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); - if (!full_name->empty()) full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - result->number_ = proto.number(); - result->is_extension_ = is_extension; - - // If .proto files follow the style guide then the name should already be - // lower-cased. If that's the case we can just reuse the string we already - // allocated rather than allocate a new one. - string lowercase_name(proto.name()); - LowerString(&lowercase_name); - if (lowercase_name == proto.name()) { - result->lowercase_name_ = result->name_; - } else { - result->lowercase_name_ = tables_->AllocateString(lowercase_name); - } - - // Don't bother with the above optimization for camel-case names since - // .proto files that follow the guide shouldn't be using names in this - // format, so the optimization wouldn't help much. - result->camelcase_name_ = - tables_->AllocateString(ToCamelCase(proto.name(), - /* lower_first = */ true)); - - if (proto.has_json_name()) { - result->has_json_name_ = true; - result->json_name_ = tables_->AllocateString(proto.json_name()); - } else { - result->has_json_name_ = false; - result->json_name_ = tables_->AllocateString(ToJsonName(proto.name())); - } - - // Some compilers do not allow static_cast directly between two enum types, - // so we must cast to int first. - result->type_ = static_cast( - implicit_cast(proto.type())); - result->label_ = static_cast( - implicit_cast(proto.label())); - - // An extension cannot have a required field (b/13365836). - if (result->is_extension_ && - result->label_ == FieldDescriptor::LABEL_REQUIRED) { - AddError(result->full_name(), proto, - // Error location `TYPE`: we would really like to indicate - // `LABEL`, but the `ErrorLocation` enum has no entry for this, and - // we don't necessarily know about all implementations of the - // `ErrorCollector` interface to extend them to handle the new - // error location type properly. - DescriptorPool::ErrorCollector::TYPE, - "Message extensions cannot have required fields."); - } - - // Some of these may be filled in when cross-linking. - result->containing_type_ = NULL; - result->extension_scope_ = NULL; - result->message_type_ = NULL; - result->enum_type_ = NULL; - result->type_name_ = NULL; - result->type_once_ = NULL; - result->default_value_enum_ = NULL; - result->default_value_enum_name_ = NULL; - - result->has_default_value_ = proto.has_default_value(); - if (proto.has_default_value() && result->is_repeated()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Repeated fields can't have default values."); - } - - if (proto.has_type()) { - if (proto.has_default_value()) { - char* end_pos = NULL; - switch (result->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - result->default_value_int32_ = - strtol(proto.default_value().c_str(), &end_pos, 0); - break; - case FieldDescriptor::CPPTYPE_INT64: - result->default_value_int64_ = - strto64(proto.default_value().c_str(), &end_pos, 0); - break; - case FieldDescriptor::CPPTYPE_UINT32: - result->default_value_uint32_ = - strtoul(proto.default_value().c_str(), &end_pos, 0); - break; - case FieldDescriptor::CPPTYPE_UINT64: - result->default_value_uint64_ = - strtou64(proto.default_value().c_str(), &end_pos, 0); - break; - case FieldDescriptor::CPPTYPE_FLOAT: - if (proto.default_value() == "inf") { - result->default_value_float_ = - std::numeric_limits::infinity(); - } else if (proto.default_value() == "-inf") { - result->default_value_float_ = - -std::numeric_limits::infinity(); - } else if (proto.default_value() == "nan") { - result->default_value_float_ = - std::numeric_limits::quiet_NaN(); - } else { - result->default_value_float_ = io::SafeDoubleToFloat( - io::NoLocaleStrtod(proto.default_value().c_str(), &end_pos)); - } - break; - case FieldDescriptor::CPPTYPE_DOUBLE: - if (proto.default_value() == "inf") { - result->default_value_double_ = - std::numeric_limits::infinity(); - } else if (proto.default_value() == "-inf") { - result->default_value_double_ = - -std::numeric_limits::infinity(); - } else if (proto.default_value() == "nan") { - result->default_value_double_ = - std::numeric_limits::quiet_NaN(); - } else { - result->default_value_double_ = - io::NoLocaleStrtod(proto.default_value().c_str(), &end_pos); - } - break; - case FieldDescriptor::CPPTYPE_BOOL: - if (proto.default_value() == "true") { - result->default_value_bool_ = true; - } else if (proto.default_value() == "false") { - result->default_value_bool_ = false; - } else { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Boolean default must be true or false."); - } - break; - case FieldDescriptor::CPPTYPE_ENUM: - // This will be filled in when cross-linking. - result->default_value_enum_ = NULL; - break; - case FieldDescriptor::CPPTYPE_STRING: - if (result->type() == FieldDescriptor::TYPE_BYTES) { - result->default_value_string_ = tables_->AllocateString( - UnescapeCEscapeString(proto.default_value())); - } else { - result->default_value_string_ = - tables_->AllocateString(proto.default_value()); - } - break; - case FieldDescriptor::CPPTYPE_MESSAGE: - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Messages can't have default values."); - result->has_default_value_ = false; - break; - } - - if (end_pos != NULL) { - // end_pos is only set non-NULL by the parsers for numeric types, above. - // This checks that the default was non-empty and had no extra junk - // after the end of the number. - if (proto.default_value().empty() || *end_pos != '\0') { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Couldn't parse default value \"" + proto.default_value() + - "\"."); - } - } - } else { - // No explicit default value - switch (result->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - result->default_value_int32_ = 0; - break; - case FieldDescriptor::CPPTYPE_INT64: - result->default_value_int64_ = 0; - break; - case FieldDescriptor::CPPTYPE_UINT32: - result->default_value_uint32_ = 0; - break; - case FieldDescriptor::CPPTYPE_UINT64: - result->default_value_uint64_ = 0; - break; - case FieldDescriptor::CPPTYPE_FLOAT: - result->default_value_float_ = 0.0f; - break; - case FieldDescriptor::CPPTYPE_DOUBLE: - result->default_value_double_ = 0.0; - break; - case FieldDescriptor::CPPTYPE_BOOL: - result->default_value_bool_ = false; - break; - case FieldDescriptor::CPPTYPE_ENUM: - // This will be filled in when cross-linking. - result->default_value_enum_ = NULL; - break; - case FieldDescriptor::CPPTYPE_STRING: - result->default_value_string_ = &internal::GetEmptyString(); - break; - case FieldDescriptor::CPPTYPE_MESSAGE: - break; - } - } - } - - if (result->number() <= 0) { - AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, - "Field numbers must be positive integers."); - } else if (!is_extension && result->number() > FieldDescriptor::kMaxNumber) { - // Only validate that the number is within the valid field range if it is - // not an extension. Since extension numbers are validated with the - // extendee's valid set of extension numbers, and those are in turn - // validated against the max allowed number, the check is unnecessary for - // extension fields. - // This avoids cross-linking issues that arise when attempting to check if - // the extendee is a message_set_wire_format message, which has a higher max - // on extension numbers. - AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Field numbers cannot be greater than $0.", - FieldDescriptor::kMaxNumber)); - } else if (result->number() >= FieldDescriptor::kFirstReservedNumber && - result->number() <= FieldDescriptor::kLastReservedNumber) { - AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Field numbers $0 through $1 are reserved for the protocol " - "buffer library implementation.", - FieldDescriptor::kFirstReservedNumber, - FieldDescriptor::kLastReservedNumber)); - } - - if (is_extension) { - if (!proto.has_extendee()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - "FieldDescriptorProto.extendee not set for extension field."); - } - - result->extension_scope_ = parent; - - if (proto.has_oneof_index()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "FieldDescriptorProto.oneof_index should not be set for " - "extensions."); - } - - // Fill in later (maybe). - result->containing_oneof_ = NULL; - } else { - if (proto.has_extendee()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - "FieldDescriptorProto.extendee set for non-extension field."); - } - - result->containing_type_ = parent; - - if (proto.has_oneof_index()) { - if (proto.oneof_index() < 0 || - proto.oneof_index() >= parent->oneof_decl_count()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, - strings::Substitute("FieldDescriptorProto.oneof_index $0 is " - "out of range for type \"$1\".", - proto.oneof_index(), - parent->name())); - result->containing_oneof_ = NULL; - } else { - result->containing_oneof_ = parent->oneof_decl(proto.oneof_index()); - } - } else { - result->containing_oneof_ = NULL; - } - } - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result, - FieldDescriptorProto::kOptionsFieldNumber); - } - - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); -} - -void DescriptorBuilder::BuildExtensionRange( - const DescriptorProto::ExtensionRange& proto, - const Descriptor* parent, - Descriptor::ExtensionRange* result) { - result->start = proto.start(); - result->end = proto.end(); - if (result->start <= 0) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - "Extension numbers must be positive integers."); - } - - // Checking of the upper bound of the extension range is deferred until after - // options interpreting. This allows messages with message_set_wire_format to - // have extensions beyond FieldDescriptor::kMaxNumber, since the extension - // numbers are actually used as int32s in the message_set_wire_format. - - if (result->start >= result->end) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - "Extension range end number must be greater than start number."); - } - - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - std::vector options_path; - parent->GetLocationPath(&options_path); - options_path.push_back(DescriptorProto::kExtensionRangeFieldNumber); - // find index of this extension range in order to compute path - int index; - for (index = 0; parent->extension_ranges_ + index != result; index++); - options_path.push_back(index); - options_path.push_back(DescriptorProto_ExtensionRange::kOptionsFieldNumber); - AllocateOptionsImpl(parent->full_name(), parent->full_name(), - proto.options(), result, options_path); - } -} - -void DescriptorBuilder::BuildReservedRange( - const DescriptorProto::ReservedRange& proto, - const Descriptor* parent, - Descriptor::ReservedRange* result) { - result->start = proto.start(); - result->end = proto.end(); - if (result->start <= 0) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - "Reserved numbers must be positive integers."); - } -} - -void DescriptorBuilder::BuildReservedRange( - const EnumDescriptorProto::EnumReservedRange& proto, - const EnumDescriptor* parent, EnumDescriptor::ReservedRange* result) { - result->start = proto.start(); - result->end = proto.end(); - - if (result->start > result->end) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - "Reserved range end number must be greater than start number."); - } -} - -void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto, - Descriptor* parent, - OneofDescriptor* result) { - string* full_name = tables_->AllocateString(parent->full_name()); - full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - - result->containing_type_ = parent; - - // We need to fill these in later. - result->field_count_ = 0; - result->fields_ = NULL; - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result, - OneofDescriptorProto::kOptionsFieldNumber); - } - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); -} - -void DescriptorBuilder::CheckEnumValueUniqueness( - const EnumDescriptorProto& proto, const EnumDescriptor* result) { - - // Check that enum labels are still unique when we remove the enum prefix from - // values that have it. - // - // This will fail for something like: - // - // enum MyEnum { - // MY_ENUM_FOO = 0; - // FOO = 1; - // } - // - // By enforcing this reasonable constraint, we allow code generators to strip - // the prefix and/or PascalCase it without creating conflicts. This can lead - // to much nicer language-specific enums like: - // - // enum NameType { - // FirstName = 1, - // LastName = 2, - // } - // - // Instead of: - // - // enum NameType { - // NAME_TYPE_FIRST_NAME = 1, - // NAME_TYPE_LAST_NAME = 2, - // } - PrefixRemover remover(result->name()); - std::map values; - for (int i = 0; i < result->value_count(); i++) { - const google::protobuf::EnumValueDescriptor* value = result->value(i); - string stripped = - EnumValueToPascalCase(remover.MaybeRemove(value->name())); - std::pair::iterator, - bool> - 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 - // if they map to the same number. In the former case, the normal symbol - // duplication error will fire so we don't need to (and its error message - // will make more sense). We allow the latter case so users can create - // aliases which add or remove the prefix (code generators that do prefix - // 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()) { - string error_message = - "When enum name is stripped and label is PascalCased (" + stripped + - "), this value label conflicts with " + values[stripped]->name() + - ". This will make the proto fail to compile for some languages, such " - "as C#."; - // 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 { - AddError(value->full_name(), proto.value(i), - DescriptorPool::ErrorCollector::NAME, error_message); - } - } - } -} - -void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, - const Descriptor* parent, - EnumDescriptor* result) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); - if (!full_name->empty()) full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - result->containing_type_ = parent; - result->is_placeholder_ = false; - result->is_unqualified_placeholder_ = false; - - if (proto.value_size() == 0) { - // We cannot allow enums with no values because this would mean there - // would be no valid default value for fields of this type. - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Enums must contain at least one value."); - } - - BUILD_ARRAY(proto, result, value, BuildEnumValue, result); - BUILD_ARRAY(proto, result, reserved_range, BuildReservedRange, result); - - // Copy reserved names. - int reserved_name_count = proto.reserved_name_size(); - result->reserved_name_count_ = reserved_name_count; - result->reserved_names_ = - tables_->AllocateArray(reserved_name_count); - for (int i = 0; i < reserved_name_count; ++i) { - result->reserved_names_[i] = - tables_->AllocateString(proto.reserved_name(i)); - } - - CheckEnumValueUniqueness(proto, result); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result, - EnumDescriptorProto::kOptionsFieldNumber); - } - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); - - for (int i = 0; i < proto.reserved_range_size(); i++) { - const EnumDescriptorProto_EnumReservedRange& range1 = - proto.reserved_range(i); - for (int j = i + 1; j < proto.reserved_range_size(); j++) { - const EnumDescriptorProto_EnumReservedRange& range2 = - proto.reserved_range(j); - if (range1.end() >= range2.start() && range2.end() >= range1.start()) { - AddError(result->full_name(), proto.reserved_range(i), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Reserved range $0 to $1 overlaps with " - "already-defined range $2 to $3.", - range2.start(), range2.end(), - range1.start(), range1.end())); - } - } - } - - HASH_SET reserved_name_set; - for (int i = 0; i < proto.reserved_name_size(); i++) { - const string& name = proto.reserved_name(i); - if (reserved_name_set.find(name) == reserved_name_set.end()) { - reserved_name_set.insert(name); - } else { - AddError(name, proto, DescriptorPool::ErrorCollector::NAME, - strings::Substitute( - "Enum value \"$0\" is reserved multiple times.", - name)); - } - } - - for (int i = 0; i < result->value_count(); i++) { - const EnumValueDescriptor* value = result->value(i); - for (int j = 0; j < result->reserved_range_count(); j++) { - const EnumDescriptor::ReservedRange* range = result->reserved_range(j); - if (range->start <= value->number() && value->number() <= range->end) { - AddError(value->full_name(), proto.reserved_range(j), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Enum value \"$0\" uses reserved number $1.", - value->name(), value->number())); - } - } - if (reserved_name_set.find(value->name()) != reserved_name_set.end()) { - AddError(value->full_name(), proto.value(i), - DescriptorPool::ErrorCollector::NAME, - strings::Substitute( - "Enum value \"$0\" is reserved.", value->name())); - } - } -} - -void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto, - const EnumDescriptor* parent, - EnumValueDescriptor* result) { - result->name_ = tables_->AllocateString(proto.name()); - result->number_ = proto.number(); - result->type_ = parent; - - // Note: full_name for enum values is a sibling to the parent's name, not a - // child of it. - string* full_name = tables_->AllocateString(*parent->full_name_); - full_name->resize(full_name->size() - parent->name_->size()); - full_name->append(*result->name_); - result->full_name_ = full_name; - - ValidateSymbolName(proto.name(), *full_name, proto); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result, - EnumValueDescriptorProto::kOptionsFieldNumber); - } - - // Again, enum values are weird because we makes them appear as siblings - // of the enum type instead of children of it. So, we use - // parent->containing_type() as the value's parent. - bool added_to_outer_scope = - AddSymbol(result->full_name(), parent->containing_type(), result->name(), - proto, Symbol(result)); - - // However, we also want to be able to search for values within a single - // enum type, so we add it as a child of the enum type itself, too. - // Note: This could fail, but if it does, the error has already been - // reported by the above AddSymbol() call, so we ignore the return code. - bool added_to_inner_scope = - file_tables_->AddAliasUnderParent(parent, result->name(), Symbol(result)); - - if (added_to_inner_scope && !added_to_outer_scope) { - // This value did not conflict with any values defined in the same enum, - // but it did conflict with some other symbol defined in the enum type's - // scope. Let's print an additional error to explain this. - string outer_scope; - if (parent->containing_type() == NULL) { - outer_scope = file_->package(); - } else { - outer_scope = parent->containing_type()->full_name(); - } - - if (outer_scope.empty()) { - outer_scope = "the global scope"; - } else { - outer_scope = "\"" + outer_scope + "\""; - } - - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Note that enum values use C++ scoping rules, meaning that " - "enum values are siblings of their type, not children of it. " - "Therefore, \"" + result->name() + "\" must be unique within " - + outer_scope + ", not just within \"" + parent->name() + "\"."); - } - - // An enum is allowed to define two numbers that refer to the same value. - // FindValueByNumber() should return the first such value, so we simply - // ignore AddEnumValueByNumber()'s return code. - file_tables_->AddEnumValueByNumber(result); -} - -void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto, - const void* /* dummy */, - ServiceDescriptor* result) { - string* full_name = tables_->AllocateString(file_->package()); - if (!full_name->empty()) full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - - BUILD_ARRAY(proto, result, method, BuildMethod, result); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result, - ServiceDescriptorProto::kOptionsFieldNumber); - } - - AddSymbol(result->full_name(), NULL, result->name(), - proto, Symbol(result)); -} - -void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto, - const ServiceDescriptor* parent, - MethodDescriptor* result) { - result->name_ = tables_->AllocateString(proto.name()); - result->service_ = parent; - - string* full_name = tables_->AllocateString(parent->full_name()); - full_name->append(1, '.'); - full_name->append(*result->name_); - result->full_name_ = full_name; - - ValidateSymbolName(proto.name(), *full_name, proto); - - // These will be filled in when cross-linking. - result->input_type_.Init(); - result->output_type_.Init(); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result, - MethodDescriptorProto::kOptionsFieldNumber); - } - - result->client_streaming_ = proto.client_streaming(); - result->server_streaming_ = proto.server_streaming(); - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); -} - -#undef BUILD_ARRAY - -// ------------------------------------------------------------------- - -void DescriptorBuilder::CrossLinkFile( - FileDescriptor* file, const FileDescriptorProto& proto) { - if (file->options_ == NULL) { - file->options_ = &FileOptions::default_instance(); - } - - for (int i = 0; i < file->message_type_count(); i++) { - CrossLinkMessage(&file->message_types_[i], proto.message_type(i)); - } - - for (int i = 0; i < file->extension_count(); i++) { - CrossLinkField(&file->extensions_[i], proto.extension(i)); - } - - for (int i = 0; i < file->enum_type_count(); i++) { - CrossLinkEnum(&file->enum_types_[i], proto.enum_type(i)); - } - - for (int i = 0; i < file->service_count(); i++) { - CrossLinkService(&file->services_[i], proto.service(i)); - } -} - -void DescriptorBuilder::CrossLinkMessage( - Descriptor* message, const DescriptorProto& proto) { - if (message->options_ == NULL) { - message->options_ = &MessageOptions::default_instance(); - } - - for (int i = 0; i < message->nested_type_count(); i++) { - CrossLinkMessage(&message->nested_types_[i], proto.nested_type(i)); - } - - for (int i = 0; i < message->enum_type_count(); i++) { - CrossLinkEnum(&message->enum_types_[i], proto.enum_type(i)); - } - - for (int i = 0; i < message->field_count(); i++) { - CrossLinkField(&message->fields_[i], proto.field(i)); - } - - for (int i = 0; i < message->extension_count(); i++) { - CrossLinkField(&message->extensions_[i], proto.extension(i)); - } - - for (int i = 0; i < message->extension_range_count(); i++) { - CrossLinkExtensionRange(&message->extension_ranges_[i], - proto.extension_range(i)); - } - - // Set up field array for each oneof. - - // First count the number of fields per oneof. - for (int i = 0; i < message->field_count(); i++) { - const OneofDescriptor* oneof_decl = message->field(i)->containing_oneof(); - if (oneof_decl != NULL) { - // Make sure fields belonging to the same oneof are defined consecutively. - // This enables optimizations in codegens and reflection libraries to - // skip fields in the oneof group, as only one of the field can be set. - // Note that field_count() returns how many fields in this oneof we have - // seen so far. field_count() > 0 guarantees that i > 0, so field(i-1) is - // safe. - if (oneof_decl->field_count() > 0 && - message->field(i - 1)->containing_oneof() != oneof_decl) { - AddError( - message->full_name() + "." + message->field(i - 1)->name(), - proto.field(i - 1), DescriptorPool::ErrorCollector::OTHER, - strings::Substitute( - "Fields in the same oneof must be defined consecutively. " - "\"$0\" cannot be defined before the completion of the " - "\"$1\" oneof definition.", - message->field(i - 1)->name(), oneof_decl->name())); - } - // Must go through oneof_decls_ array to get a non-const version of the - // OneofDescriptor. - ++message->oneof_decls_[oneof_decl->index()].field_count_; - } - } - - // Then allocate the arrays. - for (int i = 0; i < message->oneof_decl_count(); i++) { - OneofDescriptor* oneof_decl = &message->oneof_decls_[i]; - - if (oneof_decl->field_count() == 0) { - AddError(message->full_name() + "." + oneof_decl->name(), - proto.oneof_decl(i), - DescriptorPool::ErrorCollector::NAME, - "Oneof must have at least one field."); - } - - oneof_decl->fields_ = - tables_->AllocateArray(oneof_decl->field_count_); - oneof_decl->field_count_ = 0; - - if (oneof_decl->options_ == NULL) { - oneof_decl->options_ = &OneofOptions::default_instance(); - } - } - - // Then fill them in. - for (int i = 0; i < message->field_count(); i++) { - const OneofDescriptor* oneof_decl = message->field(i)->containing_oneof(); - if (oneof_decl != NULL) { - OneofDescriptor* mutable_oneof_decl = - &message->oneof_decls_[oneof_decl->index()]; - message->fields_[i].index_in_oneof_ = mutable_oneof_decl->field_count_; - mutable_oneof_decl->fields_[mutable_oneof_decl->field_count_++] = - message->field(i); - } - } -} - -void DescriptorBuilder::CrossLinkExtensionRange( - Descriptor::ExtensionRange* range, - const DescriptorProto::ExtensionRange& proto) { - if (range->options_ == NULL) { - range->options_ = &ExtensionRangeOptions::default_instance(); - } -} - -void DescriptorBuilder::CrossLinkField( - FieldDescriptor* field, const FieldDescriptorProto& proto) { - if (field->options_ == NULL) { - field->options_ = &FieldOptions::default_instance(); - } - - // Add the field to the lowercase-name and camelcase-name tables. - file_tables_->AddFieldByStylizedNames(field); - - if (proto.has_extendee()) { - Symbol extendee = - LookupSymbol(proto.extendee(), field->full_name(), - DescriptorPool::PLACEHOLDER_EXTENDABLE_MESSAGE); - if (extendee.IsNull()) { - AddNotDefinedError(field->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - proto.extendee()); - return; - } else if (extendee.type != Symbol::MESSAGE) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - "\"" + proto.extendee() + "\" is not a message type."); - return; - } - field->containing_type_ = extendee.descriptor; - - const Descriptor::ExtensionRange* extension_range = field->containing_type() - ->FindExtensionRangeContainingNumber(field->number()); - - if (extension_range == NULL) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("\"$0\" does not declare $1 as an " - "extension number.", - field->containing_type()->full_name(), - field->number())); - } - } - - if (field->containing_oneof() != NULL) { - if (field->label() != FieldDescriptor::LABEL_OPTIONAL) { - // Note that this error will never happen when parsing .proto files. - // It can only happen if you manually construct a FileDescriptorProto - // that is incorrect. - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Fields of oneofs must themselves have label LABEL_OPTIONAL."); - } - } - - if (proto.has_type_name()) { - // Assume we are expecting a message type unless the proto contains some - // evidence that it expects an enum type. This only makes a difference if - // we end up creating a placeholder. - bool expecting_enum = (proto.type() == FieldDescriptorProto::TYPE_ENUM) || - proto.has_default_value(); - - // In case of weak fields we force building the dependency. We need to know - // if the type exist or not. If it doesnt exist we substitute Empty which - // should only be done if the type can't be found in the generated pool. - // TODO(gerbens) Ideally we should query the database directly to check - // if weak fields exist or not so that we don't need to force building - // weak dependencies. However the name lookup rules for symbols are - // somewhat complicated, so I defer it too another CL. - bool is_weak = !pool_->enforce_weak_ && proto.options().weak(); - bool is_lazy = pool_->lazily_build_dependencies_ && !is_weak; - - Symbol type = - LookupSymbol(proto.type_name(), field->full_name(), - expecting_enum ? DescriptorPool::PLACEHOLDER_ENUM - : DescriptorPool::PLACEHOLDER_MESSAGE, - LOOKUP_TYPES, !is_lazy); - - if (type.IsNull()) { - if (is_lazy) { - // Save the symbol names for later for lookup, and allocate the once - // object needed for the accessors. - string name = proto.type_name(); - field->type_once_ = tables_->AllocateOnceDynamic(); - field->type_name_ = tables_->AllocateString(name); - if (proto.has_default_value()) { - field->default_value_enum_name_ = - tables_->AllocateString(proto.default_value()); - } - // AddFieldByNumber and AddExtension are done later in this function, - // and can/must be done if the field type was not found. The related - // error checking is not necessary when in lazily_build_dependencies_ - // mode, and can't be done without building the type's descriptor, - // which we don't want to do. - file_tables_->AddFieldByNumber(field); - if (field->is_extension()) { - tables_->AddExtension(field); - } - return; - } else { - // If the type is a weak type, we change the type to a google.protobuf.Empty - // field. - if (is_weak) { - type = FindSymbol(kNonLinkedWeakMessageReplacementName); - } - if (type.IsNull()) { - AddNotDefinedError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - proto.type_name()); - return; - } - } - } - - if (!proto.has_type()) { - // Choose field type based on symbol. - if (type.type == Symbol::MESSAGE) { - field->type_ = FieldDescriptor::TYPE_MESSAGE; - } else if (type.type == Symbol::ENUM) { - field->type_ = FieldDescriptor::TYPE_ENUM; - } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "\"" + proto.type_name() + "\" is not a type."); - return; - } - } - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (type.type != Symbol::MESSAGE) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "\"" + proto.type_name() + "\" is not a message type."); - return; - } - field->message_type_ = type.descriptor; - - if (field->has_default_value()) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Messages can't have default values."); - } - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - if (type.type != Symbol::ENUM) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "\"" + proto.type_name() + "\" is not an enum type."); - return; - } - field->enum_type_ = type.enum_descriptor; - - if (field->enum_type()->is_placeholder_) { - // We can't look up default values for placeholder types. We'll have - // to just drop them. - field->has_default_value_ = false; - } - - if (field->has_default_value()) { - // Ensure that the default value is an identifier. Parser cannot always - // verify this because it does not have complete type information. - // N.B. that this check yields better error messages but is not - // necessary for correctness (an enum symbol must be a valid identifier - // anyway), only for better errors. - if (!io::Tokenizer::IsIdentifier(proto.default_value())) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Default value for an enum field must be an identifier."); - } else { - // We can't just use field->enum_type()->FindValueByName() here - // because that locks the pool's mutex, which we have already locked - // at this point. - Symbol default_value = - LookupSymbolNoPlaceholder(proto.default_value(), - field->enum_type()->full_name()); - - if (default_value.type == Symbol::ENUM_VALUE && - default_value.enum_value_descriptor->type() == - field->enum_type()) { - field->default_value_enum_ = default_value.enum_value_descriptor; - } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Enum type \"" + field->enum_type()->full_name() + - "\" has no value named \"" + proto.default_value() + - "\"."); - } - } - } else if (field->enum_type()->value_count() > 0) { - // All enums must have at least one value, or we would have reported - // an error elsewhere. We use the first defined value as the default - // if a default is not explicitly defined. - field->default_value_enum_ = field->enum_type()->value(0); - } - } else { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Field with primitive type has type_name."); - } - } else { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE || - field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Field with message or enum type missing type_name."); - } - } - - // Add the field to the fields-by-number table. - // Note: We have to do this *after* cross-linking because extensions do not - // know their containing type until now. If we're in - // lazily_build_dependencies_ mode, we're guaranteed there's no errors, so no - // risk to calling containing_type() or other accessors that will build - // dependencies. - if (!file_tables_->AddFieldByNumber(field)) { - const FieldDescriptor* conflicting_field = - file_tables_->FindFieldByNumber(field->containing_type(), - field->number()); - string containing_type_name = field->containing_type() == NULL - ? "unknown" - : field->containing_type()->full_name(); - if (field->is_extension()) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Extension number $0 has already been used " - "in \"$1\" by extension \"$2\".", - field->number(), - containing_type_name, - conflicting_field->full_name())); - } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Field number $0 has already been used in " - "\"$1\" by field \"$2\".", - field->number(), - containing_type_name, - conflicting_field->name())); - } - } else { - if (field->is_extension()) { - if (!tables_->AddExtension(field)) { - const FieldDescriptor* conflicting_field = - tables_->FindExtension(field->containing_type(), field->number()); - string containing_type_name = - field->containing_type() == NULL - ? "unknown" - : field->containing_type()->full_name(); - string error_msg = strings::Substitute( - "Extension number $0 has already been used in \"$1\" by extension " - "\"$2\" defined in $3.", - field->number(), containing_type_name, - conflicting_field->full_name(), conflicting_field->file()->name()); - // Conflicting extension numbers should be an error. However, before - // turning this into an error we need to fix all existing broken - // protos first. - // TODO(xiaofeng): Change this to an error. - AddWarning(field->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, error_msg); - } - } - } -} - -void DescriptorBuilder::CrossLinkEnum( - EnumDescriptor* enum_type, const EnumDescriptorProto& proto) { - if (enum_type->options_ == NULL) { - enum_type->options_ = &EnumOptions::default_instance(); - } - - for (int i = 0; i < enum_type->value_count(); i++) { - CrossLinkEnumValue(&enum_type->values_[i], proto.value(i)); - } -} - -void DescriptorBuilder::CrossLinkEnumValue( - EnumValueDescriptor* enum_value, - const EnumValueDescriptorProto& /* proto */) { - if (enum_value->options_ == NULL) { - enum_value->options_ = &EnumValueOptions::default_instance(); - } -} - -void DescriptorBuilder::CrossLinkService( - ServiceDescriptor* service, const ServiceDescriptorProto& proto) { - if (service->options_ == NULL) { - service->options_ = &ServiceOptions::default_instance(); - } - - for (int i = 0; i < service->method_count(); i++) { - CrossLinkMethod(&service->methods_[i], proto.method(i)); - } -} - -void DescriptorBuilder::CrossLinkMethod( - MethodDescriptor* method, const MethodDescriptorProto& proto) { - if (method->options_ == NULL) { - method->options_ = &MethodOptions::default_instance(); - } - - Symbol input_type = - LookupSymbol(proto.input_type(), method->full_name(), - DescriptorPool::PLACEHOLDER_MESSAGE, LOOKUP_ALL, - !pool_->lazily_build_dependencies_); - if (input_type.IsNull()) { - if (!pool_->lazily_build_dependencies_) { - AddNotDefinedError(method->full_name(), proto, - DescriptorPool::ErrorCollector::INPUT_TYPE, - proto.input_type()); - } else { - method->input_type_.SetLazy(proto.input_type(), file_); - } - } else if (input_type.type != Symbol::MESSAGE) { - AddError(method->full_name(), proto, - DescriptorPool::ErrorCollector::INPUT_TYPE, - "\"" + proto.input_type() + "\" is not a message type."); - } else { - method->input_type_.Set(input_type.descriptor); - } - - Symbol output_type = - LookupSymbol(proto.output_type(), method->full_name(), - DescriptorPool::PLACEHOLDER_MESSAGE, LOOKUP_ALL, - !pool_->lazily_build_dependencies_); - if (output_type.IsNull()) { - if (!pool_->lazily_build_dependencies_) { - AddNotDefinedError(method->full_name(), proto, - DescriptorPool::ErrorCollector::OUTPUT_TYPE, - proto.output_type()); - } else { - method->output_type_.SetLazy(proto.output_type(), file_); - } - } else if (output_type.type != Symbol::MESSAGE) { - AddError(method->full_name(), proto, - DescriptorPool::ErrorCollector::OUTPUT_TYPE, - "\"" + proto.output_type() + "\" is not a message type."); - } else { - method->output_type_.Set(output_type.descriptor); - } -} - -// ------------------------------------------------------------------- - -#define VALIDATE_OPTIONS_FROM_ARRAY(descriptor, array_name, type) \ - for (int i = 0; i < descriptor->array_name##_count(); ++i) { \ - Validate##type##Options(descriptor->array_name##s_ + i, \ - proto.array_name(i)); \ - } - -// Determine if the file uses optimize_for = LITE_RUNTIME, being careful to -// avoid problems that exist at init time. -static bool IsLite(const FileDescriptor* file) { - // TODO(kenton): I don't even remember how many of these conditions are - // actually possible. I'm just being super-safe. - return file != NULL && - &file->options() != &FileOptions::default_instance() && - file->options().optimize_for() == FileOptions::LITE_RUNTIME; -} - -void DescriptorBuilder::ValidateFileOptions(FileDescriptor* file, - const FileDescriptorProto& proto) { - VALIDATE_OPTIONS_FROM_ARRAY(file, message_type, Message); - VALIDATE_OPTIONS_FROM_ARRAY(file, enum_type, Enum); - VALIDATE_OPTIONS_FROM_ARRAY(file, service, Service); - VALIDATE_OPTIONS_FROM_ARRAY(file, extension, Field); - - // Lite files can only be imported by other Lite files. - if (!IsLite(file)) { - for (int i = 0; i < file->dependency_count(); i++) { - if (IsLite(file->dependency(i))) { - AddError( - file->name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Files that do not use optimize_for = LITE_RUNTIME cannot import " - "files which do use this option. This file is not lite, but it " - "imports \"" + file->dependency(i)->name() + "\" which is."); - break; - } - } - } - if (file->syntax() == FileDescriptor::SYNTAX_PROTO3) { - ValidateProto3(file, proto); - } -} - -void DescriptorBuilder::ValidateProto3( - FileDescriptor* file, const FileDescriptorProto& proto) { - for (int i = 0; i < file->extension_count(); ++i) { - ValidateProto3Field(file->extensions_ + i, proto.extension(i)); - } - for (int i = 0; i < file->message_type_count(); ++i) { - ValidateProto3Message(file->message_types_ + i, proto.message_type(i)); - } - for (int i = 0; i < file->enum_type_count(); ++i) { - ValidateProto3Enum(file->enum_types_ + i, proto.enum_type(i)); - } -} - -static string ToLowercaseWithoutUnderscores(const string& name) { - string result; - for (int i = 0; i < name.size(); ++i) { - if (name[i] != '_') { - if (name[i] >= 'A' && name[i] <= 'Z') { - result.push_back(name[i] - 'A' + 'a'); - } else { - result.push_back(name[i]); - } - } - } - return result; -} - -void DescriptorBuilder::ValidateProto3Message( - Descriptor* message, const DescriptorProto& proto) { - for (int i = 0; i < message->nested_type_count(); ++i) { - ValidateProto3Message(message->nested_types_ + i, - proto.nested_type(i)); - } - for (int i = 0; i < message->enum_type_count(); ++i) { - ValidateProto3Enum(message->enum_types_ + i, - proto.enum_type(i)); - } - for (int i = 0; i < message->field_count(); ++i) { - ValidateProto3Field(message->fields_ + i, proto.field(i)); - } - for (int i = 0; i < message->extension_count(); ++i) { - ValidateProto3Field(message->extensions_ +i, proto.extension(i)); - } - if (message->extension_range_count() > 0) { - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Extension ranges are not allowed in proto3."); - } - if (message->options().message_set_wire_format()) { - // Using MessageSet doesn't make sense since we disallow extensions. - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "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) { - string lowercase_name = ToLowercaseWithoutUnderscores( - message->field(i)->name()); - if (name_to_field.find(lowercase_name) != name_to_field.end()) { - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "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, const FieldDescriptorProto& proto) { - if (field->is_extension() && - !AllowedExtendeeInProto3(field->containing_type()->full_name())) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Extensions in proto3 are only allowed for defining options."); - } - if (field->is_required()) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Required fields are not allowed in proto3."); - } - if (field->has_default_value()) { - AddError( - field->full_name(), proto, DescriptorPool::ErrorCollector::OTHER, - "Explicit default values are not allowed in proto3."); - } - if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM && - field->enum_type() && - field->enum_type()->file()->syntax() != FileDescriptor::SYNTAX_PROTO3) { - // Proto3 messages can only use Proto3 enum types; otherwise we can't - // guarantee that the default value is zero. - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "Enum type \"" + field->enum_type()->full_name() + - "\" is not a proto3 enum, but is used in \"" + - field->containing_type()->full_name() + - "\" which is a proto3 message type."); - } - if (field->type() == FieldDescriptor::TYPE_GROUP) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "Groups are not supported in proto3 syntax."); - } -} - -void DescriptorBuilder::ValidateProto3Enum( - EnumDescriptor* enm, const EnumDescriptorProto& proto) { - if (enm->value_count() > 0 && enm->value(0)->number() != 0) { - AddError( - enm->full_name(), proto, DescriptorPool::ErrorCollector::OTHER, - "The first enum value must be zero in proto3."); - } -} - -void DescriptorBuilder::ValidateMessageOptions(Descriptor* message, - const DescriptorProto& proto) { - VALIDATE_OPTIONS_FROM_ARRAY(message, field, Field); - VALIDATE_OPTIONS_FROM_ARRAY(message, nested_type, Message); - VALIDATE_OPTIONS_FROM_ARRAY(message, enum_type, Enum); - VALIDATE_OPTIONS_FROM_ARRAY(message, extension, Field); - - const int64 max_extension_range = - static_cast(message->options().message_set_wire_format() ? - kint32max : - FieldDescriptor::kMaxNumber); - for (int i = 0; i < message->extension_range_count(); ++i) { - if (message->extension_range(i)->end > max_extension_range + 1) { - AddError( - message->full_name(), proto.extension_range(i), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Extension numbers cannot be greater than $0.", - max_extension_range)); - } - } -} - - -void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field, - const FieldDescriptorProto& proto) { - if (pool_->lazily_build_dependencies_ && (!field || !field->message_type())) { - return; - } - // Only message type fields may be lazy. - if (field->options().lazy()) { - if (field->type() != FieldDescriptor::TYPE_MESSAGE) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "[lazy = true] can only be specified for submessage fields."); - } - } - - // Only repeated primitive fields may be packed. - if (field->options().packed() && !field->is_packable()) { - AddError( - field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "[packed = true] can only be specified for repeated primitive fields."); - } - - // Note: Default instance may not yet be initialized here, so we have to - // avoid reading from it. - if (field->containing_type_ != NULL && - &field->containing_type()->options() != - &MessageOptions::default_instance() && - field->containing_type()->options().message_set_wire_format()) { - if (field->is_extension()) { - if (!field->is_optional() || - field->type() != FieldDescriptor::TYPE_MESSAGE) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "Extensions of MessageSets must be optional messages."); - } - } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "MessageSets cannot have fields, only extensions."); - } - } - - // Lite extensions can only be of Lite types. - if (IsLite(field->file()) && - field->containing_type_ != NULL && - !IsLite(field->containing_type()->file())) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - "Extensions to non-lite types can only be declared in non-lite " - "files. Note that you cannot extend a non-lite type to contain " - "a lite type, but the reverse is allowed."); - } - - // Validate map types. - if (field->is_map()) { - if (!ValidateMapEntry(field, proto)) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "map_entry should not be set explicitly. Use map instead."); - } - } - - ValidateJSType(field, proto); - -} - -void DescriptorBuilder::ValidateEnumOptions(EnumDescriptor* enm, - const EnumDescriptorProto& proto) { - VALIDATE_OPTIONS_FROM_ARRAY(enm, value, EnumValue); - if (!enm->options().has_allow_alias() || !enm->options().allow_alias()) { - std::map used_values; - for (int i = 0; i < enm->value_count(); ++i) { - const EnumValueDescriptor* enum_value = enm->value(i); - if (used_values.find(enum_value->number()) != used_values.end()) { - string error = - "\"" + enum_value->full_name() + - "\" uses the same enum value as \"" + - used_values[enum_value->number()] + "\". If this is intended, set " - "'option allow_alias = true;' to the enum definition."; - if (!enm->options().allow_alias()) { - // Generate error if duplicated enum values are explicitly disallowed. - AddError(enm->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - error); - } else { - // Generate warning if duplicated values are found but the option - // isn't set. - GOOGLE_LOG(ERROR) << error; - } - } else { - used_values[enum_value->number()] = enum_value->full_name(); - } - } - } -} - -void DescriptorBuilder::ValidateEnumValueOptions( - EnumValueDescriptor* /* enum_value */, - const EnumValueDescriptorProto& /* proto */) { - // Nothing to do so far. -} -void DescriptorBuilder::ValidateServiceOptions(ServiceDescriptor* service, - const ServiceDescriptorProto& proto) { - if (IsLite(service->file()) && - (service->file()->options().cc_generic_services() || - service->file()->options().java_generic_services())) { - AddError(service->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Files with optimize_for = LITE_RUNTIME cannot define services " - "unless you set both options cc_generic_services and " - "java_generic_sevices to false."); - } - - VALIDATE_OPTIONS_FROM_ARRAY(service, method, Method); -} - -void DescriptorBuilder::ValidateMethodOptions(MethodDescriptor* /* method */, - const MethodDescriptorProto& /* proto */) { - // Nothing to do so far. -} - -bool DescriptorBuilder::ValidateMapEntry(FieldDescriptor* field, - const FieldDescriptorProto& proto) { - const Descriptor* message = field->message_type(); - if (// Must not contain extensions, extension range or nested message or - // enums - message->extension_count() != 0 || - field->label() != FieldDescriptor::LABEL_REPEATED || - message->extension_range_count() != 0 || - message->nested_type_count() != 0 || message->enum_type_count() != 0 || - // Must contain exactly two fields - message->field_count() != 2 || - // Field name and message name must match - message->name() != ToCamelCase(field->name(), false) + "Entry" || - // Entry message must be in the same containing type of the field. - field->containing_type() != message->containing_type()) { - return false; - } - - const FieldDescriptor* key = message->field(0); - const FieldDescriptor* value = message->field(1); - if (key->label() != FieldDescriptor::LABEL_OPTIONAL || key->number() != 1 || - key->name() != "key") { - return false; - } - if (value->label() != FieldDescriptor::LABEL_OPTIONAL || - value->number() != 2 || value->name() != "value") { - return false; - } - - // Check key types are legal. - switch (key->type()) { - case FieldDescriptor::TYPE_ENUM: - AddError( - field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Key in map fields cannot be enum types."); - break; - case FieldDescriptor::TYPE_FLOAT: - case FieldDescriptor::TYPE_DOUBLE: - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_BYTES: - AddError( - field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Key in map fields cannot be float/double, bytes or message types."); - break; - case FieldDescriptor::TYPE_BOOL: - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_SFIXED32: - case FieldDescriptor::TYPE_SFIXED64: - // Legal cases - break; - // Do not add a default, so that the compiler will complain when new types - // are added. - } - - if (value->type() == FieldDescriptor::TYPE_ENUM) { - if (value->enum_type()->value(0)->number() != 0) { - AddError( - field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Enum value in map must define 0 as the first value."); - } - } - - return true; -} - -void DescriptorBuilder::DetectMapConflicts(const Descriptor* message, - const DescriptorProto& proto) { - std::map seen_types; - for (int i = 0; i < message->nested_type_count(); ++i) { - const Descriptor* nested = message->nested_type(i); - std::pair::iterator, bool> result = - seen_types.insert(std::make_pair(nested->name(), nested)); - if (!result.second) { - if (result.first->second->options().map_entry() || - nested->options().map_entry()) { - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Expanded map entry type " + nested->name() + - " conflicts with an existing nested message type."); - } - } - // Recursively test on the nested types. - DetectMapConflicts(message->nested_type(i), proto.nested_type(i)); - } - // Check for conflicted field names. - for (int i = 0; i < message->field_count(); ++i) { - const FieldDescriptor* field = message->field(i); - std::map::iterator iter = - seen_types.find(field->name()); - if (iter != seen_types.end() && iter->second->options().map_entry()) { - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Expanded map entry type " + iter->second->name() + - " conflicts with an existing field."); - } - } - // Check for conflicted enum names. - for (int i = 0; i < message->enum_type_count(); ++i) { - const EnumDescriptor* enum_desc = message->enum_type(i); - std::map::iterator iter = - seen_types.find(enum_desc->name()); - if (iter != seen_types.end() && iter->second->options().map_entry()) { - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Expanded map entry type " + iter->second->name() + - " conflicts with an existing enum type."); - } - } - // Check for conflicted oneof names. - for (int i = 0; i < message->oneof_decl_count(); ++i) { - const OneofDescriptor* oneof_desc = message->oneof_decl(i); - std::map::iterator iter = - seen_types.find(oneof_desc->name()); - if (iter != seen_types.end() && iter->second->options().map_entry()) { - AddError(message->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Expanded map entry type " + iter->second->name() + - " conflicts with an existing oneof type."); - } - } -} - -void DescriptorBuilder::ValidateJSType(FieldDescriptor* field, - const FieldDescriptorProto& proto) { - FieldOptions::JSType jstype = field->options().jstype(); - // The default is always acceptable. - if (jstype == FieldOptions::JS_NORMAL) { - return; - } - - switch (field->type()) { - // Integral 64-bit types may be represented as JavaScript numbers or - // strings. - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_SFIXED64: - if (jstype == FieldOptions::JS_STRING || - jstype == FieldOptions::JS_NUMBER) { - return; - } - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Illegal jstype for int64, uint64, sint64, fixed64 " - "or sfixed64 field: " + - FieldOptions_JSType_descriptor()->value(jstype)->name()); - break; - - // No other types permit a jstype option. - default: - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "jstype is only allowed on int64, uint64, sint64, fixed64 " - "or sfixed64 fields."); - break; - } -} - -#undef VALIDATE_OPTIONS_FROM_ARRAY - -// ------------------------------------------------------------------- - -DescriptorBuilder::OptionInterpreter::OptionInterpreter( - DescriptorBuilder* builder) : builder_(builder) { - GOOGLE_CHECK(builder_); -} - -DescriptorBuilder::OptionInterpreter::~OptionInterpreter() { -} - -bool DescriptorBuilder::OptionInterpreter::InterpretOptions( - OptionsToInterpret* options_to_interpret) { - // Note that these may be in different pools, so we can't use the same - // descriptor and reflection objects on both. - Message* options = options_to_interpret->options; - const Message* original_options = options_to_interpret->original_options; - - bool failed = false; - options_to_interpret_ = options_to_interpret; - - // Find the uninterpreted_option field in the mutable copy of the options - // and clear them, since we're about to interpret them. - const FieldDescriptor* uninterpreted_options_field = - options->GetDescriptor()->FindFieldByName("uninterpreted_option"); - GOOGLE_CHECK(uninterpreted_options_field != NULL) - << "No field named \"uninterpreted_option\" in the Options proto."; - options->GetReflection()->ClearField(options, uninterpreted_options_field); - - std::vector src_path = options_to_interpret->element_path; - src_path.push_back(uninterpreted_options_field->number()); - - // Find the uninterpreted_option field in the original options. - const FieldDescriptor* original_uninterpreted_options_field = - original_options->GetDescriptor()-> - FindFieldByName("uninterpreted_option"); - GOOGLE_CHECK(original_uninterpreted_options_field != NULL) - << "No field named \"uninterpreted_option\" in the Options proto."; - - const int num_uninterpreted_options = original_options->GetReflection()-> - FieldSize(*original_options, original_uninterpreted_options_field); - for (int i = 0; i < num_uninterpreted_options; ++i) { - src_path.push_back(i); - uninterpreted_option_ = down_cast( - &original_options->GetReflection()->GetRepeatedMessage( - *original_options, original_uninterpreted_options_field, i)); - if (!InterpretSingleOption(options, src_path, - options_to_interpret->element_path)) { - // Error already added by InterpretSingleOption(). - failed = true; - break; - } - src_path.pop_back(); - } - // Reset these, so we don't have any dangling pointers. - uninterpreted_option_ = NULL; - options_to_interpret_ = NULL; - - if (!failed) { - // InterpretSingleOption() added the interpreted options in the - // UnknownFieldSet, in case the option isn't yet known to us. Now we - // serialize the options message and deserialize it back. That way, any - // option fields that we do happen to know about will get moved from the - // UnknownFieldSet into the real fields, and thus be available right away. - // If they are not known, that's OK too. They will get reparsed into the - // UnknownFieldSet and wait there until the message is parsed by something - // that does know about the options. - string buf; - GOOGLE_CHECK(options->AppendPartialToString(&buf)) - << "Protocol message could not be serialized."; - GOOGLE_CHECK(options->ParsePartialFromString(buf)) - << "Protocol message serialized itself in invalid fashion."; - if (!options->IsInitialized()) { - builder_->AddWarning( - options_to_interpret->element_name, *original_options, - DescriptorPool::ErrorCollector::OTHER, - "Options could not be fully parsed using the proto descriptors " - "compiled into this binary. Missing required fields: " + - options->InitializationErrorString()); - } - } - return !failed; -} - -bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( - Message* options, std::vector& src_path, std::vector& opts_path) { - // First do some basic validation. - if (uninterpreted_option_->name_size() == 0) { - // This should never happen unless the parser has gone seriously awry or - // someone has manually created the uninterpreted option badly. - return AddNameError("Option must have a name."); - } - if (uninterpreted_option_->name(0).name_part() == "uninterpreted_option") { - return AddNameError("Option must not use reserved name " - "\"uninterpreted_option\"."); - } - - const Descriptor* options_descriptor = NULL; - // Get the options message's descriptor from the builder's pool, so that we - // get the version that knows about any extension options declared in the - // file we're currently building. The descriptor should be there as long as - // the file we're building imported "google/protobuf/descriptors.proto". - - // Note that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not - // DescriptorPool::FindMessageTypeByName() because we're already holding the - // pool's mutex, and the latter method locks it again. We don't use - // FindSymbol() because files that use custom options only need to depend on - // the file that defines the option, not descriptor.proto itself. - Symbol symbol = builder_->FindSymbolNotEnforcingDeps( - options->GetDescriptor()->full_name()); - if (!symbol.IsNull() && symbol.type == Symbol::MESSAGE) { - options_descriptor = symbol.descriptor; - } else { - // The options message's descriptor was not in the builder's pool, so use - // the standard version from the generated pool. We're not holding the - // generated pool's mutex, so we can search it the straightforward way. - options_descriptor = options->GetDescriptor(); - } - GOOGLE_CHECK(options_descriptor); - - // We iterate over the name parts to drill into the submessages until we find - // the leaf field for the option. As we drill down we remember the current - // submessage's descriptor in |descriptor| and the next field in that - // submessage in |field|. We also track the fields we're drilling down - // through in |intermediate_fields|. As we go, we reconstruct the full option - // name in |debug_msg_name|, for use in error messages. - const Descriptor* descriptor = options_descriptor; - const FieldDescriptor* field = NULL; - std::vector intermediate_fields; - string debug_msg_name = ""; - - std::vector dest_path = opts_path; - - for (int i = 0; i < uninterpreted_option_->name_size(); ++i) { - const string& name_part = uninterpreted_option_->name(i).name_part(); - if (debug_msg_name.size() > 0) { - debug_msg_name += "."; - } - if (uninterpreted_option_->name(i).is_extension()) { - debug_msg_name += "(" + name_part + ")"; - // Search for the extension's descriptor as an extension in the builder's - // pool. Note that we use DescriptorBuilder::LookupSymbol(), not - // DescriptorPool::FindExtensionByName(), for two reasons: 1) It allows - // relative lookups, and 2) because we're already holding the pool's - // mutex, and the latter method locks it again. - symbol = builder_->LookupSymbol(name_part, - options_to_interpret_->name_scope); - if (!symbol.IsNull() && symbol.type == Symbol::FIELD) { - field = symbol.field_descriptor; - } - // If we don't find the field then the field's descriptor was not in the - // builder's pool, but there's no point in looking in the generated - // pool. We require that you import the file that defines any extensions - // you use, so they must be present in the builder's pool. - } else { - debug_msg_name += name_part; - // Search for the field's descriptor as a regular field. - field = descriptor->FindFieldByName(name_part); - } - - if (field == NULL) { - if (get_allow_unknown(builder_->pool_)) { - // We can't find the option, but AllowUnknownDependencies() is enabled, - // so we will just leave it as uninterpreted. - AddWithoutInterpreting(*uninterpreted_option_, options); - return true; - } else if (!(builder_->undefine_resolved_name_).empty()) { - // Option is resolved to a name which is not defined. - return AddNameError( - "Option \"" + debug_msg_name + "\" is resolved to \"(" + - builder_->undefine_resolved_name_ + - ")\", which is not defined. The innermost scope is searched first " - "in name resolution. Consider using a leading '.'(i.e., \"(." + - debug_msg_name.substr(1) + - "\") to start from the outermost scope."); - } else { - return AddNameError("Option \"" + debug_msg_name + "\" unknown."); - } - } else if (field->containing_type() != descriptor) { - if (get_is_placeholder(field->containing_type())) { - // The field is an extension of a placeholder type, so we can't - // reliably verify whether it is a valid extension to use here (e.g. - // we don't know if it is an extension of the correct *Options message, - // or if it has a valid field number, etc.). Just leave it as - // uninterpreted instead. - AddWithoutInterpreting(*uninterpreted_option_, options); - return true; - } else { - // This can only happen if, due to some insane misconfiguration of the - // pools, we find the options message in one pool but the field in - // another. This would probably imply a hefty bug somewhere. - return AddNameError("Option field \"" + debug_msg_name + - "\" is not a field or extension of message \"" + - descriptor->name() + "\"."); - } - } else { - // accumulate field numbers to form path to interpreted option - dest_path.push_back(field->number()); - - if (i < uninterpreted_option_->name_size() - 1) { - if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - return AddNameError("Option \"" + debug_msg_name + - "\" is an atomic type, not a message."); - } else if (field->is_repeated()) { - return AddNameError("Option field \"" + debug_msg_name + - "\" is a repeated message. Repeated message " - "options must be initialized using an " - "aggregate value."); - } else { - // Drill down into the submessage. - intermediate_fields.push_back(field); - descriptor = field->message_type(); - } - } - } - } - - // We've found the leaf field. Now we use UnknownFieldSets to set its value - // on the options message. We do so because the message may not yet know - // about its extension fields, so we may not be able to set the fields - // directly. But the UnknownFieldSets will serialize to the same wire-format - // message, so reading that message back in once the extension fields are - // known will populate them correctly. - - // First see if the option is already set. - if (!field->is_repeated() && !ExamineIfOptionIsSet( - intermediate_fields.begin(), - intermediate_fields.end(), - field, debug_msg_name, - options->GetReflection()->GetUnknownFields(*options))) { - return false; // ExamineIfOptionIsSet() already added the error. - } - - // First set the value on the UnknownFieldSet corresponding to the - // innermost message. - std::unique_ptr unknown_fields(new UnknownFieldSet()); - if (!SetOptionValue(field, unknown_fields.get())) { - return false; // SetOptionValue() already added the error. - } - - // Now wrap the UnknownFieldSet with UnknownFieldSets corresponding to all - // the intermediate messages. - for (std::vector::reverse_iterator iter = - intermediate_fields.rbegin(); - iter != intermediate_fields.rend(); ++iter) { - std::unique_ptr parent_unknown_fields( - new UnknownFieldSet()); - switch ((*iter)->type()) { - case FieldDescriptor::TYPE_MESSAGE: { - io::StringOutputStream outstr( - parent_unknown_fields->AddLengthDelimited((*iter)->number())); - io::CodedOutputStream out(&outstr); - internal::WireFormat::SerializeUnknownFields(*unknown_fields, &out); - GOOGLE_CHECK(!out.HadError()) - << "Unexpected failure while serializing option submessage " - << debug_msg_name << "\"."; - break; - } - - case FieldDescriptor::TYPE_GROUP: { - parent_unknown_fields->AddGroup((*iter)->number()) - ->MergeFrom(*unknown_fields); - break; - } - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_MESSAGE: " - << (*iter)->type(); - return false; - } - unknown_fields.reset(parent_unknown_fields.release()); - } - - // Now merge the UnknownFieldSet corresponding to the top-level message into - // the options message. - options->GetReflection()->MutableUnknownFields(options)->MergeFrom( - *unknown_fields); - - // record the element path of the interpreted option - if (field->is_repeated()) { - int index = repeated_option_counts_[dest_path]++; - dest_path.push_back(index); - } - interpreted_paths_[src_path] = dest_path; - - return true; -} - -void DescriptorBuilder::OptionInterpreter::UpdateSourceCodeInfo( - SourceCodeInfo* info) { - - if (interpreted_paths_.empty()) { - // nothing to do! - return; - } - - // We find locations that match keys in interpreted_paths_ and - // 1) replace the path with the corresponding value in interpreted_paths_ - // 2) remove any subsequent sub-locations (sub-location is one whose path - // has the parent path as a prefix) - // - // To avoid quadratic behavior of removing interior rows as we go, - // we keep a copy. But we don't actually copy anything until we've - // found the first match (so if the source code info has no locations - // that need to be changed, there is zero copy overhead). - - RepeatedPtrField* locs = info->mutable_location(); - RepeatedPtrField new_locs; - bool copying = false; - - std::vector pathv; - bool matched = false; - - for (RepeatedPtrField::iterator loc = locs->begin(); - loc != locs->end(); loc++) { - - if (matched) { - // see if this location is in the range to remove - bool loc_matches = true; - if (loc->path_size() < pathv.size()) { - loc_matches = false; - } else { - for (int j = 0; j < pathv.size(); j++) { - if (loc->path(j) != pathv[j]) { - loc_matches = false; - break; - } - } - } - - if (loc_matches) { - // don't copy this row since it is a sub-location that we're removing - continue; - } - - matched = false; - } - - pathv.clear(); - for (int j = 0; j < loc->path_size(); j++) { - pathv.push_back(loc->path(j)); - } - - std::map, std::vector>::iterator entry = - interpreted_paths_.find(pathv); - - if (entry == interpreted_paths_.end()) { - // not a match - if (copying) { - new_locs.Add()->CopyFrom(*loc); - } - continue; - } - - matched = true; - - if (!copying) { - // initialize the copy we are building - copying = true; - new_locs.Reserve(locs->size()); - for (RepeatedPtrField::iterator it = - locs->begin(); it != loc; it++) { - new_locs.Add()->CopyFrom(*it); - } - } - - // add replacement and update its path - SourceCodeInfo_Location* replacement = new_locs.Add(); - replacement->CopyFrom(*loc); - replacement->clear_path(); - for (std::vector::iterator rit = entry->second.begin(); - rit != entry->second.end(); rit++) { - replacement->add_path(*rit); - } - } - - // if we made a changed copy, put it in place - if (copying) { - *locs = new_locs; - } -} - -void DescriptorBuilder::OptionInterpreter::AddWithoutInterpreting( - const UninterpretedOption& uninterpreted_option, Message* options) { - const FieldDescriptor* field = - options->GetDescriptor()->FindFieldByName("uninterpreted_option"); - GOOGLE_CHECK(field != NULL); - - options->GetReflection()->AddMessage(options, field) - ->CopyFrom(uninterpreted_option); -} - -bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( - std::vector::const_iterator - intermediate_fields_iter, - std::vector::const_iterator intermediate_fields_end, - const FieldDescriptor* innermost_field, const string& debug_msg_name, - const UnknownFieldSet& unknown_fields) { - // We do linear searches of the UnknownFieldSet and its sub-groups. This - // should be fine since it's unlikely that any one options structure will - // contain more than a handful of options. - - if (intermediate_fields_iter == intermediate_fields_end) { - // We're at the innermost submessage. - for (int i = 0; i < unknown_fields.field_count(); i++) { - if (unknown_fields.field(i).number() == innermost_field->number()) { - return AddNameError("Option \"" + debug_msg_name + - "\" was already set."); - } - } - return true; - } - - for (int i = 0; i < unknown_fields.field_count(); i++) { - if (unknown_fields.field(i).number() == - (*intermediate_fields_iter)->number()) { - const UnknownField* unknown_field = &unknown_fields.field(i); - FieldDescriptor::Type type = (*intermediate_fields_iter)->type(); - // Recurse into the next submessage. - switch (type) { - case FieldDescriptor::TYPE_MESSAGE: - if (unknown_field->type() == UnknownField::TYPE_LENGTH_DELIMITED) { - UnknownFieldSet intermediate_unknown_fields; - if (intermediate_unknown_fields.ParseFromString( - unknown_field->length_delimited()) && - !ExamineIfOptionIsSet(intermediate_fields_iter + 1, - intermediate_fields_end, - innermost_field, debug_msg_name, - intermediate_unknown_fields)) { - return false; // Error already added. - } - } - break; - - case FieldDescriptor::TYPE_GROUP: - if (unknown_field->type() == UnknownField::TYPE_GROUP) { - if (!ExamineIfOptionIsSet(intermediate_fields_iter + 1, - intermediate_fields_end, - innermost_field, debug_msg_name, - unknown_field->group())) { - return false; // Error already added. - } - } - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_MESSAGE: " << type; - return false; - } - } - } - return true; -} - -bool DescriptorBuilder::OptionInterpreter::SetOptionValue( - const FieldDescriptor* option_field, - UnknownFieldSet* unknown_fields) { - // We switch on the CppType to validate. - switch (option_field->cpp_type()) { - - case FieldDescriptor::CPPTYPE_INT32: - if (uninterpreted_option_->has_positive_int_value()) { - if (uninterpreted_option_->positive_int_value() > - static_cast(kint32max)) { - return AddValueError("Value out of range for int32 option \"" + - option_field->full_name() + "\"."); - } else { - SetInt32(option_field->number(), - uninterpreted_option_->positive_int_value(), - option_field->type(), unknown_fields); - } - } else if (uninterpreted_option_->has_negative_int_value()) { - if (uninterpreted_option_->negative_int_value() < - static_cast(kint32min)) { - return AddValueError("Value out of range for int32 option \"" + - 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 for int32 option \"" + - option_field->full_name() + "\"."); - } - break; - - case FieldDescriptor::CPPTYPE_INT64: - if (uninterpreted_option_->has_positive_int_value()) { - if (uninterpreted_option_->positive_int_value() > - static_cast(kint64max)) { - return AddValueError("Value out of range for int64 option \"" + - option_field->full_name() + "\"."); - } else { - SetInt64(option_field->number(), - uninterpreted_option_->positive_int_value(), - option_field->type(), unknown_fields); - } - } else if (uninterpreted_option_->has_negative_int_value()) { - SetInt64(option_field->number(), - uninterpreted_option_->negative_int_value(), - option_field->type(), unknown_fields); - } else { - return AddValueError("Value must be integer for int64 option \"" + - option_field->full_name() + "\"."); - } - break; - - case FieldDescriptor::CPPTYPE_UINT32: - if (uninterpreted_option_->has_positive_int_value()) { - if (uninterpreted_option_->positive_int_value() > kuint32max) { - return AddValueError("Value out of range for uint32 option \"" + - option_field->name() + "\"."); - } else { - SetUInt32(option_field->number(), - uninterpreted_option_->positive_int_value(), - option_field->type(), unknown_fields); - } - } else { - return AddValueError("Value must be non-negative integer for uint32 " - "option \"" + option_field->full_name() + "\"."); - } - break; - - case FieldDescriptor::CPPTYPE_UINT64: - if (uninterpreted_option_->has_positive_int_value()) { - SetUInt64(option_field->number(), - uninterpreted_option_->positive_int_value(), - option_field->type(), unknown_fields); - } else { - return AddValueError("Value must be non-negative integer for uint64 " - "option \"" + option_field->full_name() + "\"."); - } - break; - - case FieldDescriptor::CPPTYPE_FLOAT: { - float value; - if (uninterpreted_option_->has_double_value()) { - value = uninterpreted_option_->double_value(); - } else if (uninterpreted_option_->has_positive_int_value()) { - value = uninterpreted_option_->positive_int_value(); - } else if (uninterpreted_option_->has_negative_int_value()) { - value = uninterpreted_option_->negative_int_value(); - } else { - return AddValueError("Value must be number for float option \"" + - option_field->full_name() + "\"."); - } - unknown_fields->AddFixed32(option_field->number(), - google::protobuf::internal::WireFormatLite::EncodeFloat(value)); - break; - } - - case FieldDescriptor::CPPTYPE_DOUBLE: { - double value; - if (uninterpreted_option_->has_double_value()) { - value = uninterpreted_option_->double_value(); - } else if (uninterpreted_option_->has_positive_int_value()) { - value = uninterpreted_option_->positive_int_value(); - } else if (uninterpreted_option_->has_negative_int_value()) { - value = uninterpreted_option_->negative_int_value(); - } else { - return AddValueError("Value must be number for double option \"" + - option_field->full_name() + "\"."); - } - unknown_fields->AddFixed64(option_field->number(), - google::protobuf::internal::WireFormatLite::EncodeDouble(value)); - break; - } - - case FieldDescriptor::CPPTYPE_BOOL: - uint64 value; - if (!uninterpreted_option_->has_identifier_value()) { - return AddValueError("Value must be identifier for boolean option " - "\"" + option_field->full_name() + "\"."); - } - if (uninterpreted_option_->identifier_value() == "true") { - value = 1; - } else if (uninterpreted_option_->identifier_value() == "false") { - value = 0; - } else { - return AddValueError("Value must be \"true\" or \"false\" for boolean " - "option \"" + option_field->full_name() + "\"."); - } - unknown_fields->AddVarint(option_field->number(), value); - break; - - case FieldDescriptor::CPPTYPE_ENUM: { - if (!uninterpreted_option_->has_identifier_value()) { - return AddValueError("Value must be identifier for enum-valued option " - "\"" + option_field->full_name() + "\"."); - } - const EnumDescriptor* enum_type = option_field->enum_type(); - const string& value_name = uninterpreted_option_->identifier_value(); - const EnumValueDescriptor* enum_value = NULL; - - if (enum_type->file()->pool() != DescriptorPool::generated_pool()) { - // Note that the enum value's fully-qualified name is a sibling of the - // enum's name, not a child of it. - string fully_qualified_name = enum_type->full_name(); - fully_qualified_name.resize(fully_qualified_name.size() - - enum_type->name().size()); - fully_qualified_name += value_name; - - // Search for the enum value's descriptor in the builder's pool. Note - // that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not - // DescriptorPool::FindEnumValueByName() because we're already holding - // the pool's mutex, and the latter method locks it again. - Symbol symbol = - builder_->FindSymbolNotEnforcingDeps(fully_qualified_name); - if (!symbol.IsNull() && symbol.type == Symbol::ENUM_VALUE) { - if (symbol.enum_value_descriptor->type() != enum_type) { - return AddValueError("Enum type \"" + enum_type->full_name() + - "\" has no value named \"" + value_name + "\" for option \"" + - option_field->full_name() + - "\". This appears to be a value from a sibling type."); - } else { - enum_value = symbol.enum_value_descriptor; - } - } - } else { - // The enum type is in the generated pool, so we can search for the - // value there. - enum_value = enum_type->FindValueByName(value_name); - } - - if (enum_value == NULL) { - return AddValueError("Enum type \"" + - option_field->enum_type()->full_name() + - "\" has no value named \"" + value_name + "\" for " - "option \"" + option_field->full_name() + "\"."); - } else { - // Sign-extension is not a problem, since we cast directly from int32 to - // uint64, without first going through uint32. - unknown_fields->AddVarint(option_field->number(), - static_cast(static_cast(enum_value->number()))); - } - break; - } - - case FieldDescriptor::CPPTYPE_STRING: - if (!uninterpreted_option_->has_string_value()) { - return AddValueError("Value must be quoted string for string option " - "\"" + option_field->full_name() + "\"."); - } - // The string has already been unquoted and unescaped by the parser. - unknown_fields->AddLengthDelimited(option_field->number(), - uninterpreted_option_->string_value()); - break; - - case FieldDescriptor::CPPTYPE_MESSAGE: - if (!SetAggregateOption(option_field, unknown_fields)) { - return false; - } - break; - } - - return true; -} - -class DescriptorBuilder::OptionInterpreter::AggregateOptionFinder - : public TextFormat::Finder { - public: - DescriptorBuilder* builder_; - - virtual const FieldDescriptor* FindExtension( - Message* message, const string& name) const { - assert_mutex_held(builder_->pool_); - const Descriptor* descriptor = message->GetDescriptor(); - Symbol result = builder_->LookupSymbolNoPlaceholder( - name, descriptor->full_name()); - if (result.type == Symbol::FIELD && - result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else if (result.type == Symbol::MESSAGE && - descriptor->options().message_set_wire_format()) { - const Descriptor* foreign_type = result.descriptor; - // The text format allows MessageSet items to be specified using - // the type name, rather than the extension identifier. If the symbol - // lookup returned a Message, and the enclosing Message has - // message_set_wire_format = true, then return the message set - // extension, if one exists. - for (int i = 0; i < foreign_type->extension_count(); i++) { - const FieldDescriptor* extension = foreign_type->extension(i); - if (extension->containing_type() == descriptor && - extension->type() == FieldDescriptor::TYPE_MESSAGE && - extension->is_optional() && - extension->message_type() == foreign_type) { - // Found it. - return extension; - } - } - } - return NULL; - } -}; - -// A custom error collector to record any text-format parsing errors -namespace { -class AggregateErrorCollector : public io::ErrorCollector { - public: - string error_; - - virtual void AddError(int /* line */, int /* column */, - const string& message) { - if (!error_.empty()) { - error_ += "; "; - } - error_ += message; - } - - virtual void AddWarning(int /* line */, int /* column */, - const string& /* message */) { - // Ignore warnings - } -}; -} - -// We construct a dynamic message of the type corresponding to -// option_field, parse the supplied text-format string into this -// message, and serialize the resulting message to produce the value. -bool DescriptorBuilder::OptionInterpreter::SetAggregateOption( - const FieldDescriptor* option_field, - UnknownFieldSet* unknown_fields) { - if (!uninterpreted_option_->has_aggregate_value()) { - return AddValueError("Option \"" + option_field->full_name() + - "\" is a message. To set the entire message, use " - "syntax like \"" + option_field->name() + - " = { }\". " - "To set fields within it, use " - "syntax like \"" + option_field->name() + - ".foo = value\"."); - } - - const Descriptor* type = option_field->message_type(); - std::unique_ptr dynamic(dynamic_factory_.GetPrototype(type)->New()); - GOOGLE_CHECK(dynamic.get() != NULL) - << "Could not create an instance of " << option_field->DebugString(); - - AggregateErrorCollector collector; - AggregateOptionFinder finder; - finder.builder_ = builder_; - TextFormat::Parser parser; - parser.RecordErrorsTo(&collector); - parser.SetFinder(&finder); - if (!parser.ParseFromString(uninterpreted_option_->aggregate_value(), - dynamic.get())) { - AddValueError("Error while parsing option value for \"" + - option_field->name() + "\": " + collector.error_); - return false; - } else { - string serial; - dynamic->SerializeToString(&serial); // Never fails - if (option_field->type() == FieldDescriptor::TYPE_MESSAGE) { - unknown_fields->AddLengthDelimited(option_field->number(), serial); - } else { - GOOGLE_CHECK_EQ(option_field->type(), FieldDescriptor::TYPE_GROUP); - UnknownFieldSet* group = unknown_fields->AddGroup(option_field->number()); - group->ParseFromString(serial); - } - return true; - } -} - -void DescriptorBuilder::OptionInterpreter::SetInt32(int number, int32 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { - switch (type) { - case FieldDescriptor::TYPE_INT32: - unknown_fields->AddVarint(number, - static_cast(static_cast(value))); - break; - - case FieldDescriptor::TYPE_SFIXED32: - unknown_fields->AddFixed32(number, static_cast(value)); - break; - - case FieldDescriptor::TYPE_SINT32: - unknown_fields->AddVarint(number, - google::protobuf::internal::WireFormatLite::ZigZagEncode32(value)); - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_INT32: " << type; - break; - } -} - -void DescriptorBuilder::OptionInterpreter::SetInt64(int number, int64 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { - switch (type) { - case FieldDescriptor::TYPE_INT64: - unknown_fields->AddVarint(number, static_cast(value)); - break; - - case FieldDescriptor::TYPE_SFIXED64: - unknown_fields->AddFixed64(number, static_cast(value)); - break; - - case FieldDescriptor::TYPE_SINT64: - unknown_fields->AddVarint(number, - google::protobuf::internal::WireFormatLite::ZigZagEncode64(value)); - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_INT64: " << type; - break; - } -} - -void DescriptorBuilder::OptionInterpreter::SetUInt32(int number, uint32 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { - switch (type) { - case FieldDescriptor::TYPE_UINT32: - unknown_fields->AddVarint(number, static_cast(value)); - break; - - case FieldDescriptor::TYPE_FIXED32: - unknown_fields->AddFixed32(number, static_cast(value)); - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_UINT32: " << type; - break; - } -} - -void DescriptorBuilder::OptionInterpreter::SetUInt64(int number, uint64 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { - switch (type) { - case FieldDescriptor::TYPE_UINT64: - unknown_fields->AddVarint(number, value); - break; - - case FieldDescriptor::TYPE_FIXED64: - unknown_fields->AddFixed64(number, value); - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_UINT64: " << type; - break; - } -} - -void DescriptorBuilder::LogUnusedDependency(const FileDescriptorProto& proto, - const FileDescriptor* result) { - - if (!unused_dependency_.empty()) { - std::set annotation_extensions; - annotation_extensions.insert("google.protobuf.MessageOptions"); - annotation_extensions.insert("google.protobuf.FileOptions"); - annotation_extensions.insert("google.protobuf.FieldOptions"); - annotation_extensions.insert("google.protobuf.EnumOptions"); - annotation_extensions.insert("google.protobuf.EnumValueOptions"); - annotation_extensions.insert("google.protobuf.EnumValueOptions"); - annotation_extensions.insert("google.protobuf.ServiceOptions"); - annotation_extensions.insert("google.protobuf.MethodOptions"); - annotation_extensions.insert("google.protobuf.StreamOptions"); - for (std::set::const_iterator - it = unused_dependency_.begin(); - it != unused_dependency_.end(); ++it) { - // Do not log warnings for proto files which extend annotations. - int i; - for (i = 0 ; i < (*it)->extension_count(); ++i) { - if (annotation_extensions.find( - (*it)->extension(i)->containing_type()->full_name()) - != annotation_extensions.end()) { - break; - } - } - // Log warnings for unused imported files. - if (i == (*it)->extension_count()) { - string error_message = "Import " + (*it)->name() + " but not used."; - AddWarning((*it)->name(), proto, DescriptorPool::ErrorCollector::OTHER, - error_message); - } - } - } -} - -Symbol DescriptorPool::CrossLinkOnDemandHelper(const string& name, - bool expecting_enum) const { - string lookup_name = name; - if (!lookup_name.empty() && lookup_name[0] == '.') { - lookup_name = lookup_name.substr(1); - } - Symbol result = tables_->FindByNameHelper(this, lookup_name); - return result; -} - -// Handle the lazy import building for a message field whose type wasn't built -// at cross link time. If that was the case, we saved the name of the type to -// be looked up when the accessor for the type was called. Set type_, -// enum_type_, message_type_, and default_value_enum_ appropriately. -void FieldDescriptor::InternalTypeOnceInit() const { - GOOGLE_CHECK(file()->finished_building_ == true); - if (type_name_) { - Symbol result = file()->pool()->CrossLinkOnDemandHelper( - *type_name_, type_ == FieldDescriptor::TYPE_ENUM); - if (result.type == Symbol::MESSAGE) { - type_ = FieldDescriptor::TYPE_MESSAGE; - message_type_ = result.descriptor; - } else if (result.type == Symbol::ENUM) { - type_ = FieldDescriptor::TYPE_ENUM; - enum_type_ = result.enum_descriptor; - } - } - if (enum_type_ && !default_value_enum_) { - if (default_value_enum_name_) { - // Have to build the full name now instead of at CrossLink time, - // because enum_type_ may not be known at the time. - string name = enum_type_->full_name(); - // Enum values reside in the same scope as the enum type. - string::size_type last_dot = name.find_last_of('.'); - if (last_dot != string::npos) { - name = name.substr(0, last_dot) + "." + *default_value_enum_name_; - } else { - name = *default_value_enum_name_; - } - Symbol result = file()->pool()->CrossLinkOnDemandHelper(name, true); - if (result.type == Symbol::ENUM_VALUE) { - default_value_enum_ = result.enum_value_descriptor; - } - } - if (!default_value_enum_) { - // We use the first defined value as the default - // if a default is not explicitly defined. - GOOGLE_CHECK(enum_type_->value_count()); - default_value_enum_ = enum_type_->value(0); - } - } -} - -void FieldDescriptor::TypeOnceInit(const FieldDescriptor* to_init) { - to_init->InternalTypeOnceInit(); -} - -// message_type(), enum_type(), default_value_enum(), and type() -// all share the same GoogleOnceDynamic init path to do lazy -// import building and cross linking of a field of a message. -const Descriptor* FieldDescriptor::message_type() const { - if (type_once_) { - type_once_->Init(&FieldDescriptor::TypeOnceInit, this); - } - return message_type_; -} - -const EnumDescriptor* FieldDescriptor::enum_type() const { - if (type_once_) { - type_once_->Init(&FieldDescriptor::TypeOnceInit, this); - } - return enum_type_; -} - -const EnumValueDescriptor* FieldDescriptor::default_value_enum() const { - if (type_once_) { - type_once_->Init(&FieldDescriptor::TypeOnceInit, this); - } - return default_value_enum_; -} - -void FileDescriptor::InternalDependenciesOnceInit() const { - GOOGLE_CHECK(finished_building_ == true); - for (int i = 0; i < dependency_count(); i++) { - if (dependencies_names_[i]) { - dependencies_[i] = pool_->FindFileByName(*dependencies_names_[i]); - } - } -} - -void FileDescriptor::DependenciesOnceInit(const FileDescriptor* to_init) { - to_init->InternalDependenciesOnceInit(); -} - -const FileDescriptor* FileDescriptor::dependency(int index) const { - if (dependencies_once_) { - // Do once init for all indicies, as it's unlikely only a single index would - // be called, and saves on GoogleOnceDynamic allocations. - dependencies_once_->Init(&FileDescriptor::DependenciesOnceInit, this); - } - return dependencies_[index]; -} - -const Descriptor* MethodDescriptor::input_type() const { - return input_type_.Get(); -} - -const Descriptor* MethodDescriptor::output_type() const { - return output_type_.Get(); -} - - -namespace internal { -void LazyDescriptor::Set(const Descriptor* descriptor) { - GOOGLE_CHECK(!name_); - GOOGLE_CHECK(!once_); - GOOGLE_CHECK(!file_); - descriptor_ = descriptor; -} - -void LazyDescriptor::SetLazy(const string& name, const FileDescriptor* file) { - // verify Init() has been called and Set hasn't been called yet. - GOOGLE_CHECK(!descriptor_); - GOOGLE_CHECK(!file_); - GOOGLE_CHECK(!name_); - GOOGLE_CHECK(!once_); - GOOGLE_CHECK(file && file->pool_); - GOOGLE_CHECK(file->pool_->lazily_build_dependencies_); - GOOGLE_CHECK(!file->finished_building_); - file_ = file; - name_ = file->pool_->tables_->AllocateString(name); - once_ = file->pool_->tables_->AllocateOnceDynamic(); -} - -void LazyDescriptor::Once() { - if (once_) { - once_->Init(&LazyDescriptor::OnceStatic, this); - } -} - -void LazyDescriptor::OnceStatic(LazyDescriptor* lazy) { lazy->OnceInternal(); } - -void LazyDescriptor::OnceInternal() { - GOOGLE_CHECK(file_->finished_building_); - if (!descriptor_ && name_) { - Symbol result = file_->pool_->CrossLinkOnDemandHelper(*name_, false); - if (!result.IsNull() && result.type == Symbol::MESSAGE) { - descriptor_ = result.descriptor; - } - } -} -} // namespace internal - -} // namespace protobuf -} // namespace google diff --git a/windows/include/google/protobuf/descriptor.h b/windows/include/google/protobuf/descriptor.h index 115d4ddc2..e74e355b5 100644 --- a/windows/include/google/protobuf/descriptor.h +++ b/windows/include/google/protobuf/descriptor.h @@ -54,19 +54,30 @@ #ifndef GOOGLE_PROTOBUF_DESCRIPTOR_H__ #define GOOGLE_PROTOBUF_DESCRIPTOR_H__ +#include +#include #include #include #include #include + #include +#include #include #include +#include +#include // TYPE_BOOL is defined in the MacOS's ConditionalMacros.h. #ifdef TYPE_BOOL #undef TYPE_BOOL #endif // TYPE_BOOL +#ifdef SWIG +#define PROTOBUF_EXPORT +#endif + + namespace google { namespace protobuf { @@ -106,23 +117,23 @@ class SourceCodeInfo; // Defined in message.h class Message; +class Reflection; // Defined in descriptor.cc class DescriptorBuilder; class FileDescriptorTables; -struct Symbol; +class Symbol; // Defined in unknown_field_set.h. class UnknownField; -// Defined in generated_message_reflection.h. -namespace internal { -class GeneratedMessageReflection; -} // namespace internal - // Defined in command_line_interface.cc namespace compiler { class CommandLineInterface; +namespace cpp { +// Defined in helpers.h +class Formatter; +} // namespace cpp } // namespace compiler namespace descriptor_unittest { @@ -143,9 +154,9 @@ struct SourceLocation { // Doc comments found at the source location. // See the comments in SourceCodeInfo.Location (descriptor.proto) for details. - string leading_comments; - string trailing_comments; - std::vector leading_detached_comments; + std::string leading_comments; + std::string trailing_comments; + std::vector leading_detached_comments; }; // Options when generating machine-parsable output from a descriptor with @@ -163,7 +174,8 @@ struct DebugStringOptions { DebugStringOptions() : include_comments(false), elide_group_body(false), - elide_oneof_body(false) {} + elide_oneof_body(false) { + } }; // A class to handle the simplest cases of a lazily linked descriptor @@ -171,15 +183,14 @@ struct DebugStringOptions { // which is needed when a pool has lazily_build_dependencies_ set. // Must be instantiated as mutable in a descriptor. namespace internal { -class LIBPROTOBUF_EXPORT LazyDescriptor { + +class PROTOBUF_EXPORT LazyDescriptor { public: // Init function to be called at init time of a descriptor containing // a LazyDescriptor. void Init() { - descriptor_ = NULL; - name_ = NULL; - once_ = NULL; - file_ = NULL; + descriptor_ = nullptr; + once_ = nullptr; } // Sets the value of the descriptor if it is known during the descriptor @@ -193,26 +204,39 @@ class LIBPROTOBUF_EXPORT LazyDescriptor { // build time if the symbol wasn't found and building of the file containing // that type is delayed because lazily_build_dependencies_ is set on the pool. // Should not be called after Set() has been called. - void SetLazy(const string& name, const FileDescriptor* file); + void SetLazy(StringPiece name, const FileDescriptor* file); // Returns the current value of the descriptor, thread-safe. If SetLazy(...) // has been called, will do a one-time cross link of the type specified, // building the descriptor file that contains the type if necessary. - inline const Descriptor* Get() { - Once(); + inline const Descriptor* Get(const ServiceDescriptor* service) { + Once(service); return descriptor_; } private: - static void OnceStatic(LazyDescriptor* lazy); - void OnceInternal(); - void Once(); + void Once(const ServiceDescriptor* service); - const Descriptor* descriptor_; - const string* name_; - GoogleOnceDynamic* once_; - const FileDescriptor* file_; + union { + const Descriptor* descriptor_; + const char* lazy_name_; + }; + internal::once_flag* once_; }; + +class PROTOBUF_EXPORT SymbolBase { + private: + friend class google::protobuf::Symbol; + uint8_t symbol_type_; +}; + +// Some types have more than one SymbolBase because they have multiple +// identities in the table. We can't have duplicate direct bases, so we use this +// intermediate base to do so. +// See BuildEnumValue for details. +template +class PROTOBUF_EXPORT SymbolBaseN : public SymbolBase {}; + } // namespace internal // Describes a type of protocol message, or a particular group within a @@ -220,34 +244,35 @@ class LIBPROTOBUF_EXPORT LazyDescriptor { // Message::GetDescriptor(). Generated message classes also have a // static method called descriptor() which returns the type's descriptor. // Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT Descriptor { +class PROTOBUF_EXPORT Descriptor : private internal::SymbolBase { public: + typedef DescriptorProto Proto; + // The name of the message type, not including its scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the message type, scope delimited by // periods. For example, message type "Foo" which is declared in package // "bar" has full name "bar.Foo". If a type "Baz" is nested within // Foo, Baz's full_name is "bar.Foo.Baz". To get only the part that // comes after the last '.', use name(). - const string& full_name() const; + const std::string& full_name() const; // Index of this descriptor within the file or containing type's message // type array. int index() const; - // The .proto file in which this message type was defined. Never NULL. + // The .proto file in which this message type was defined. Never nullptr. const FileDescriptor* file() const; // If this Descriptor describes a nested type, this returns the type - // in which it is nested. Otherwise, returns NULL. + // in which it is nested. Otherwise, returns nullptr. const Descriptor* containing_type() const; // Get options for this message type. These are specified in the .proto file // by placing lines like "option foo = 1234;" in the message definition. - // Allowed options are defined by MessageOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // Allowed options are defined by MessageOptions in descriptor.proto, and any + // available extensions of that message. const MessageOptions& options() const; // Write the contents of this Descriptor into the given DescriptorProto. @@ -255,19 +280,49 @@ class LIBPROTOBUF_EXPORT Descriptor { // isn't, the result may be garbage. void CopyTo(DescriptorProto* proto) const; - // Write the contents of this decriptor in a human-readable form. Output + // Write the contents of this descriptor in a human-readable form. Output // will be suitable for re-parsing. - string DebugString() const; + std::string DebugString() const; // Similar to DebugString(), but additionally takes options (e.g., // include original user comments in output). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown type. This will // only be the case if this descriptor comes from a DescriptorPool // with AllowUnknownDependencies() set. bool is_placeholder() const; + enum WellKnownType { + WELLKNOWNTYPE_UNSPECIFIED, // Not a well-known type. + + // Wrapper types. + WELLKNOWNTYPE_DOUBLEVALUE, // google.protobuf.DoubleValue + WELLKNOWNTYPE_FLOATVALUE, // google.protobuf.FloatValue + WELLKNOWNTYPE_INT64VALUE, // google.protobuf.Int64Value + WELLKNOWNTYPE_UINT64VALUE, // google.protobuf.UInt64Value + WELLKNOWNTYPE_INT32VALUE, // google.protobuf.Int32Value + WELLKNOWNTYPE_UINT32VALUE, // google.protobuf.UInt32Value + WELLKNOWNTYPE_STRINGVALUE, // google.protobuf.StringValue + WELLKNOWNTYPE_BYTESVALUE, // google.protobuf.BytesValue + WELLKNOWNTYPE_BOOLVALUE, // google.protobuf.BoolValue + + // Other well known types. + WELLKNOWNTYPE_ANY, // google.protobuf.Any + WELLKNOWNTYPE_FIELDMASK, // google.protobuf.FieldMask + WELLKNOWNTYPE_DURATION, // google.protobuf.Duration + WELLKNOWNTYPE_TIMESTAMP, // google.protobuf.Timestamp + WELLKNOWNTYPE_VALUE, // google.protobuf.Value + WELLKNOWNTYPE_LISTVALUE, // google.protobuf.ListValue + WELLKNOWNTYPE_STRUCT, // google.protobuf.Struct + + // New well-known types may be added in the future. + // Please make sure any switch() statements have a 'default' case. + __WELLKNOWNTYPE__DO_NOT_USE__ADD_DEFAULT_INSTEAD__, + }; + + WellKnownType well_known_type() const; + // Field stuff ----------------------------------------------------- // The number of fields in this message type. @@ -276,33 +331,37 @@ class LIBPROTOBUF_EXPORT Descriptor { // These are returned in the order they were defined in the .proto file. const FieldDescriptor* field(int index) const; - // Looks up a field by declared tag number. Returns NULL if no such field + // Looks up a field by declared tag number. Returns nullptr if no such field // exists. const FieldDescriptor* FindFieldByNumber(int number) const; - // Looks up a field by name. Returns NULL if no such field exists. - const FieldDescriptor* FindFieldByName(const string& name) const; + // Looks up a field by name. Returns nullptr if no such field exists. + const FieldDescriptor* FindFieldByName(ConstStringParam name) const; // Looks up a field by lowercased name (as returned by lowercase_name()). // This lookup may be ambiguous if multiple field names differ only by case, // in which case the field returned is chosen arbitrarily from the matches. const FieldDescriptor* FindFieldByLowercaseName( - const string& lowercase_name) const; + ConstStringParam lowercase_name) const; // Looks up a field by camel-case name (as returned by camelcase_name()). // This lookup may be ambiguous if multiple field names differ in a way that // leads them to have identical camel-case names, in which case the field // returned is chosen arbitrarily from the matches. const FieldDescriptor* FindFieldByCamelcaseName( - const string& camelcase_name) const; + ConstStringParam camelcase_name) const; // The number of oneofs in this message type. int oneof_decl_count() const; + // The number of oneofs in this message type, excluding synthetic oneofs. + // Real oneofs always come first, so iterating up to real_oneof_decl_cout() + // will yield all real oneofs. + int real_oneof_decl_count() const; // Get a oneof by index, where 0 <= index < oneof_decl_count(). // These are returned in the order they were defined in the .proto file. const OneofDescriptor* oneof_decl(int index) const; - // Looks up a oneof by name. Returns NULL if no such oneof exists. - const OneofDescriptor* FindOneofByName(const string& name) const; + // Looks up a oneof by name. Returns nullptr if no such oneof exists. + const OneofDescriptor* FindOneofByName(ConstStringParam name) const; // Nested type stuff ----------------------------------------------- @@ -312,9 +371,9 @@ class LIBPROTOBUF_EXPORT Descriptor { // These are returned in the order they were defined in the .proto file. const Descriptor* nested_type(int index) const; - // Looks up a nested type by name. Returns NULL if no such nested type + // Looks up a nested type by name. Returns nullptr if no such nested type // exists. - const Descriptor* FindNestedTypeByName(const string& name) const; + const Descriptor* FindNestedTypeByName(ConstStringParam name) const; // Enum stuff ------------------------------------------------------ @@ -324,18 +383,21 @@ class LIBPROTOBUF_EXPORT Descriptor { // These are returned in the order they were defined in the .proto file. const EnumDescriptor* enum_type(int index) const; - // Looks up an enum type by name. Returns NULL if no such enum type exists. - const EnumDescriptor* FindEnumTypeByName(const string& name) const; + // Looks up an enum type by name. Returns nullptr if no such enum type + // exists. + const EnumDescriptor* FindEnumTypeByName(ConstStringParam name) const; // Looks up an enum value by name, among all enum types in this message. - // Returns NULL if no such value exists. - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; + // Returns nullptr if no such value exists. + const EnumValueDescriptor* FindEnumValueByName(ConstStringParam name) const; // Extensions ------------------------------------------------------ // A range of field numbers which are designated for third-party // extensions. struct ExtensionRange { + typedef DescriptorProto_ExtensionRange Proto; + typedef ExtensionRangeOptions OptionsType; // See Descriptor::CopyTo(). @@ -357,11 +419,33 @@ class LIBPROTOBUF_EXPORT Descriptor { // Returns true if the number is in one of the extension ranges. bool IsExtensionNumber(int number) const; - // Returns NULL if no extension range contains the given number. + // Returns nullptr if no extension range contains the given number. const ExtensionRange* FindExtensionRangeContainingNumber(int number) const; - // The number of extensions -- extending *other* messages -- that were - // defined nested within this message type's scope. + // The number of extensions defined nested within this message type's scope. + // See doc: + // https://developers.google.com/protocol-buffers/docs/proto#nested-extensions + // + // Note that the extensions may be extending *other* messages. + // + // For example: + // message M1 { + // extensions 1 to max; + // } + // + // message M2 { + // extend M1 { + // optional int32 foo = 1; + // } + // } + // + // In this case, + // DescriptorPool::generated_pool() + // ->FindMessageTypeByName("M2") + // ->extension(0) + // will return "foo", even though "foo" is an extension of M1. + // To find all known extensions of a given message, instead use + // DescriptorPool::FindAllExtensions. int extension_count() const; // Get an extension by index, where 0 <= index < extension_count(). // These are returned in the order they were defined in the .proto file. @@ -369,15 +453,17 @@ class LIBPROTOBUF_EXPORT Descriptor { // Looks up a named extension (which extends some *other* message type) // defined within this message type's scope. - const FieldDescriptor* FindExtensionByName(const string& name) const; + const FieldDescriptor* FindExtensionByName(ConstStringParam name) const; // Similar to FindFieldByLowercaseName(), but finds extensions defined within // this message type's scope. - const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const; + const FieldDescriptor* FindExtensionByLowercaseName( + ConstStringParam name) const; // Similar to FindFieldByCamelcaseName(), but finds extensions defined within // this message type's scope. - const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const; + const FieldDescriptor* FindExtensionByCamelcaseName( + ConstStringParam name) const; // Reserved fields ------------------------------------------------- @@ -397,17 +483,17 @@ class LIBPROTOBUF_EXPORT Descriptor { // Returns true if the number is in one of the reserved ranges. bool IsReservedNumber(int number) const; - // Returns NULL if no reserved range contains the given number. + // Returns nullptr if no reserved range contains the given number. const ReservedRange* FindReservedRangeContainingNumber(int number) const; // The number of reserved field names in this message type. int reserved_name_count() const; // Gets a reserved name by index, where 0 <= index < reserved_name_count(). - const string& reserved_name(int index) const; + const std::string& reserved_name(int index) const; // Returns true if the field name is reserved. - bool IsReservedName(const string& name) const; + bool IsReservedName(ConstStringParam name) const; // Source Location --------------------------------------------------- @@ -416,14 +502,26 @@ class LIBPROTOBUF_EXPORT Descriptor { // |*out_location| unchanged iff location information was not available. bool GetSourceLocation(SourceLocation* out_location) const; + // Maps -------------------------------------------------------------- + + // Returns the FieldDescriptor for the "key" field. If this isn't a map entry + // field, returns nullptr. + const FieldDescriptor* map_key() const; + + // Returns the FieldDescriptor for the "value" field. If this isn't a map + // entry field, returns nullptr. + const FieldDescriptor* map_value() const; + private: + friend class Symbol; typedef MessageOptions OptionsType; // Allows tests to test CopyTo(proto, true). - friend class ::google::protobuf::descriptor_unittest::DescriptorTest; + friend class descriptor_unittest::DescriptorTest; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // Fill the json_name field of FieldDescriptorProto. void CopyJsonNameTo(DescriptorProto* proto) const; @@ -432,7 +530,7 @@ class LIBPROTOBUF_EXPORT Descriptor { // correct depth. Takes |options| to control debug-string options, and // |include_opening_clause| to indicate whether the "message ... " part of the // clause has already been generated (this varies depending on context). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options, bool include_opening_clause) const; @@ -440,8 +538,26 @@ class LIBPROTOBUF_EXPORT Descriptor { // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + // True if this is a placeholder for an unknown type. + bool is_placeholder_ : 1; + // True if this is a placeholder and the type name wasn't fully-qualified. + bool is_unqualified_placeholder_ : 1; + // Well known type. Stored like this to conserve space. + uint8_t well_known_type_ : 5; + + // This points to the last field _number_ that is part of the sequence + // starting at 1, where + // `desc->field(i)->number() == i + 1` + // A value of `0` means no field matches. That is, there are no fields or the + // first field is not field `1`. + // Uses 16-bit to avoid extra padding. Unlikely to have more than 2^16 + // sequentially numbered fields in a message. + uint16_t sequential_field_limit_; + + int field_count_; + + // all_names_ = [name, full_name] + const std::string* all_names_; const FileDescriptor* file_; const Descriptor* containing_type_; const MessageOptions* options_; @@ -454,10 +570,10 @@ class LIBPROTOBUF_EXPORT Descriptor { ExtensionRange* extension_ranges_; FieldDescriptor* extensions_; ReservedRange* reserved_ranges_; - const string** reserved_names_; + const std::string** reserved_names_; - int field_count_; int oneof_decl_count_; + int real_oneof_decl_count_; int nested_type_count_; int enum_type_count_; int extension_range_count_; @@ -465,11 +581,6 @@ class LIBPROTOBUF_EXPORT Descriptor { int reserved_range_count_; int reserved_name_count_; - // True if this is a placeholder for an unknown type. - bool is_placeholder_; - // True if this is a placeholder and the type name wasn't fully-qualified. - bool is_unqualified_placeholder_; - // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() in descriptor.cc // and update them to initialize the field. @@ -480,6 +591,7 @@ class LIBPROTOBUF_EXPORT Descriptor { friend class DescriptorPool; friend class EnumDescriptor; friend class FieldDescriptor; + friend class FileDescriptorTables; friend class OneofDescriptor; friend class MethodDescriptor; friend class FileDescriptor; @@ -494,72 +606,72 @@ class LIBPROTOBUF_EXPORT Descriptor { // - Get the Descriptor or FileDescriptor for its containing scope, then // call Descriptor::FindExtensionByName() or // FileDescriptor::FindExtensionByName(). -// - Given a DescriptorPool, call DescriptorPool::FindExtensionByNumber(). -// - Given a Reflection for a message object, call -// Reflection::FindKnownExtensionByName() or -// Reflection::FindKnownExtensionByNumber(). +// - Given a DescriptorPool, call DescriptorPool::FindExtensionByNumber() or +// DescriptorPool::FindExtensionByPrintableName(). // Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT FieldDescriptor { +class PROTOBUF_EXPORT FieldDescriptor : private internal::SymbolBase { public: + typedef FieldDescriptorProto Proto; + // Identifies a field type. 0 is reserved for errors. The order is weird // for historical reasons. Types 12 and up are new in proto2. enum Type { - TYPE_DOUBLE = 1, // double, exactly eight bytes on the wire. - TYPE_FLOAT = 2, // float, exactly four bytes on the wire. - TYPE_INT64 = 3, // int64, varint on the wire. Negative numbers - // take 10 bytes. Use TYPE_SINT64 if negative - // values are likely. - TYPE_UINT64 = 4, // uint64, varint on the wire. - TYPE_INT32 = 5, // int32, varint on the wire. Negative numbers - // take 10 bytes. Use TYPE_SINT32 if negative - // values are likely. - TYPE_FIXED64 = 6, // uint64, exactly eight bytes on the wire. - TYPE_FIXED32 = 7, // uint32, exactly four bytes on the wire. - TYPE_BOOL = 8, // bool, varint on the wire. - TYPE_STRING = 9, // UTF-8 text. - TYPE_GROUP = 10, // Tag-delimited message. Deprecated. - TYPE_MESSAGE = 11, // Length-delimited message. + TYPE_DOUBLE = 1, // double, exactly eight bytes on the wire. + TYPE_FLOAT = 2, // float, exactly four bytes on the wire. + TYPE_INT64 = 3, // int64, varint on the wire. Negative numbers + // take 10 bytes. Use TYPE_SINT64 if negative + // values are likely. + TYPE_UINT64 = 4, // uint64, varint on the wire. + TYPE_INT32 = 5, // int32, varint on the wire. Negative numbers + // take 10 bytes. Use TYPE_SINT32 if negative + // values are likely. + TYPE_FIXED64 = 6, // uint64, exactly eight bytes on the wire. + TYPE_FIXED32 = 7, // uint32, exactly four bytes on the wire. + TYPE_BOOL = 8, // bool, varint on the wire. + TYPE_STRING = 9, // UTF-8 text. + TYPE_GROUP = 10, // Tag-delimited message. Deprecated. + TYPE_MESSAGE = 11, // Length-delimited message. - TYPE_BYTES = 12, // Arbitrary byte array. - TYPE_UINT32 = 13, // uint32, varint on the wire - TYPE_ENUM = 14, // Enum, varint on the wire - TYPE_SFIXED32 = 15, // int32, exactly four bytes on the wire - TYPE_SFIXED64 = 16, // int64, exactly eight bytes on the wire - TYPE_SINT32 = 17, // int32, ZigZag-encoded varint on the wire - TYPE_SINT64 = 18, // int64, ZigZag-encoded varint on the wire + TYPE_BYTES = 12, // Arbitrary byte array. + TYPE_UINT32 = 13, // uint32, varint on the wire + TYPE_ENUM = 14, // Enum, varint on the wire + TYPE_SFIXED32 = 15, // int32, exactly four bytes on the wire + TYPE_SFIXED64 = 16, // int64, exactly eight bytes on the wire + TYPE_SINT32 = 17, // int32, ZigZag-encoded varint on the wire + TYPE_SINT64 = 18, // int64, ZigZag-encoded varint on the wire - MAX_TYPE = 18, // Constant useful for defining lookup tables - // indexed by Type. + MAX_TYPE = 18, // Constant useful for defining lookup tables + // indexed by Type. }; // Specifies the C++ data type used to represent the field. There is a // fixed mapping from Type to CppType where each Type maps to exactly one // CppType. 0 is reserved for errors. enum CppType { - CPPTYPE_INT32 = 1, // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32 - CPPTYPE_INT64 = 2, // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64 - CPPTYPE_UINT32 = 3, // TYPE_UINT32, TYPE_FIXED32 - CPPTYPE_UINT64 = 4, // TYPE_UINT64, TYPE_FIXED64 - CPPTYPE_DOUBLE = 5, // TYPE_DOUBLE - CPPTYPE_FLOAT = 6, // TYPE_FLOAT - CPPTYPE_BOOL = 7, // TYPE_BOOL - CPPTYPE_ENUM = 8, // TYPE_ENUM - CPPTYPE_STRING = 9, // TYPE_STRING, TYPE_BYTES - CPPTYPE_MESSAGE = 10, // TYPE_MESSAGE, TYPE_GROUP + CPPTYPE_INT32 = 1, // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32 + CPPTYPE_INT64 = 2, // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64 + CPPTYPE_UINT32 = 3, // TYPE_UINT32, TYPE_FIXED32 + CPPTYPE_UINT64 = 4, // TYPE_UINT64, TYPE_FIXED64 + CPPTYPE_DOUBLE = 5, // TYPE_DOUBLE + CPPTYPE_FLOAT = 6, // TYPE_FLOAT + CPPTYPE_BOOL = 7, // TYPE_BOOL + CPPTYPE_ENUM = 8, // TYPE_ENUM + CPPTYPE_STRING = 9, // TYPE_STRING, TYPE_BYTES + CPPTYPE_MESSAGE = 10, // TYPE_MESSAGE, TYPE_GROUP - MAX_CPPTYPE = 10, // Constant useful for defining lookup tables - // indexed by CppType. + MAX_CPPTYPE = 10, // Constant useful for defining lookup tables + // indexed by CppType. }; // Identifies whether the field is optional, required, or repeated. 0 is // reserved for errors. enum Label { - LABEL_OPTIONAL = 1, // optional - LABEL_REQUIRED = 2, // required - LABEL_REPEATED = 3, // repeated + LABEL_OPTIONAL = 1, // optional + LABEL_REQUIRED = 2, // required + LABEL_REPEATED = 3, // repeated - MAX_LABEL = 3, // Constant useful for defining lookup tables - // indexed by Label. + MAX_LABEL = 3, // Constant useful for defining lookup tables + // indexed by Label. }; // Valid field numbers are positive integers up to kMaxNumber. @@ -570,14 +682,14 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { static const int kFirstReservedNumber = 19000; // Last field number reserved for the protocol buffer library implementation. // Users may not declare fields that use reserved numbers. - static const int kLastReservedNumber = 19999; + static const int kLastReservedNumber = 19999; - const string& name() const; // Name of this field within the message. - const string& full_name() const; // Fully-qualified name of the field. - const string& json_name() const; // JSON name of this field. - const FileDescriptor* file() const;// File in which this field was defined. - bool is_extension() const; // Is this an extension field? - int number() const; // Declared tag number. + const std::string& name() const; // Name of this field within the message. + const std::string& full_name() const; // Fully-qualified name of the field. + const std::string& json_name() const; // JSON name of this field. + const FileDescriptor* file() const; // File in which this field was defined. + bool is_extension() const; // Is this an extension field? + int number() const; // Declared tag number. // Same as name() except converted to lower-case. This (and especially the // FindFieldByLowercaseName() method) can be useful when parsing formats @@ -585,7 +697,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // field names should be lowercased anyway according to the protobuf style // guide, so this only makes a difference when dealing with old .proto files // which do not follow the guide.) - const string& lowercase_name() const; + const std::string& lowercase_name() const; // Same as name() except converted to camel-case. In this conversion, any // time an underscore appears in the name, it is removed and the next @@ -596,7 +708,7 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // fooBar -> fooBar // This (and especially the FindFieldByCamelcaseName() method) can be useful // when parsing formats which prefer to use camel-case naming style. - const string& camelcase_name() const; + const std::string& camelcase_name() const; Type type() const; // Declared type of this field. const char* type_name() const; // Name of the declared type. @@ -604,15 +716,28 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { const char* cpp_type_name() const; // Name of the C++ type. Label label() const; // optional/required/repeated - bool is_required() const; // shorthand for label() == LABEL_REQUIRED - bool is_optional() const; // shorthand for label() == LABEL_OPTIONAL - bool is_repeated() const; // shorthand for label() == LABEL_REPEATED - bool is_packable() const; // shorthand for is_repeated() && - // IsTypePackable(type()) - bool is_packed() const; // shorthand for is_packable() && - // options().packed() - bool is_map() const; // shorthand for type() == TYPE_MESSAGE && - // message_type()->options().map_entry() + bool is_required() const; // shorthand for label() == LABEL_REQUIRED + bool is_optional() const; // shorthand for label() == LABEL_OPTIONAL + bool is_repeated() const; // shorthand for label() == LABEL_REPEATED + bool is_packable() const; // shorthand for is_repeated() && + // IsTypePackable(type()) + bool is_packed() const; // shorthand for is_packable() && + // options().packed() + bool is_map() const; // shorthand for type() == TYPE_MESSAGE && + // message_type()->options().map_entry() + + // Returns true if this field was syntactically written with "optional" in the + // .proto file. Excludes singular proto3 fields that do not have a label. + bool has_optional_keyword() const; + + // Returns true if this field tracks presence, ie. does the field + // distinguish between "unset" and "present with default value." + // This includes required, optional, and oneof fields. It excludes maps, + // repeated fields, and singular proto3 fields without "optional". + // + // For fields where has_presence() == true, the return value of + // Reflection::HasField() is semantically meaningful. + bool has_presence() const; // Index of this field within the message's field array, or the file or // extension scope's extensions array. @@ -627,16 +752,20 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Get the field default value if cpp_type() == CPPTYPE_INT32. If no // explicit default was defined, the default is 0. - int32 default_value_int32() const; + int32_t default_value_int32_t() const; + int32_t default_value_int32() const { return default_value_int32_t(); } // Get the field default value if cpp_type() == CPPTYPE_INT64. If no // explicit default was defined, the default is 0. - int64 default_value_int64() const; + int64_t default_value_int64_t() const; + int64_t default_value_int64() const { return default_value_int64_t(); } // Get the field default value if cpp_type() == CPPTYPE_UINT32. If no // explicit default was defined, the default is 0. - uint32 default_value_uint32() const; + uint32_t default_value_uint32_t() const; + uint32_t default_value_uint32() const { return default_value_uint32_t(); } // Get the field default value if cpp_type() == CPPTYPE_UINT64. If no // explicit default was defined, the default is 0. - uint64 default_value_uint64() const; + uint64_t default_value_uint64_t() const; + uint64_t default_value_uint64() const { return default_value_uint64_t(); } // Get the field default value if cpp_type() == CPPTYPE_FLOAT. If no // explicit default was defined, the default is 0.0. float default_value_float() const; @@ -649,26 +778,30 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Get the field default value if cpp_type() == CPPTYPE_ENUM. If no // explicit default was defined, the default is the first value defined // in the enum type (all enum types are required to have at least one value). - // This never returns NULL. + // This never returns nullptr. const EnumValueDescriptor* default_value_enum() const; // Get the field default value if cpp_type() == CPPTYPE_STRING. If no // explicit default was defined, the default is the empty string. - const string& default_value_string() const; + const std::string& default_value_string() const; // The Descriptor for the message of which this is a field. For extensions, - // this is the extended type. Never NULL. + // this is the extended type. Never nullptr. const Descriptor* containing_type() const; // If the field is a member of a oneof, this is the one, otherwise this is - // NULL. + // nullptr. const OneofDescriptor* containing_oneof() const; + // If the field is a member of a non-synthetic oneof, returns the descriptor + // for the oneof, otherwise returns nullptr. + const OneofDescriptor* real_containing_oneof() const; + // If the field is a member of a oneof, returns the index in that oneof. int index_in_oneof() const; // An extension may be declared within the scope of another message. If this // field is an extension (is_extension() is true), then extension_scope() - // returns that message, or NULL if the extension was declared at global + // returns that message, or nullptr if the extension was declared at global // scope. If this is not an extension, extension_scope() is undefined (may // assert-fail). const Descriptor* extension_scope() const; @@ -683,19 +816,18 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Get the FieldOptions for this field. This includes things listed in // square brackets after the field definition. E.g., the field: // optional string text = 1 [ctype=CORD]; - // has the "ctype" option set. Allowed options are defined by FieldOptions - // in google/protobuf/descriptor.proto, and any available extensions of that - // message. + // has the "ctype" option set. Allowed options are defined by FieldOptions in + // descriptor.proto, and any available extensions of that message. const FieldOptions& options() const; // See Descriptor::CopyTo(). void CopyTo(FieldDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Helper method to get the CppType for a particular Type. static CppType TypeToCppType(Type type); @@ -709,6 +841,21 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Return true iff [packed = true] is valid for fields of this type. static inline bool IsTypePackable(Type field_type); + // Returns full_name() except if the field is a MessageSet extension, + // in which case it returns the full_name() of the containing message type + // for backwards compatibility with proto1. + // + // A MessageSet extension is defined as an optional message extension + // whose containing type has the message_set_wire_format option set. + // This should be true of extensions of google.protobuf.bridge.MessageSet; + // by convention, such extensions are named "message_set_extension". + // + // The opposite operation (looking up an extension's FieldDescriptor given + // its printable name) can be accomplished with + // message->file()->pool()->FindExtensionByPrintableName(message, name) + // where the extension extends "message". + const std::string& PrintableNameForExtension() const; + // Source Location --------------------------------------------------- // Updates |*out_location| to the source location of the complete @@ -717,26 +864,28 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { bool GetSourceLocation(SourceLocation* out_location) const; private: + friend class Symbol; typedef FieldOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; + friend class Reflection; // Fill the json_name field of FieldDescriptorProto. void CopyJsonNameTo(FieldDescriptorProto* proto) const; // See Descriptor::DebugString(). - enum PrintLabelFlag { PRINT_LABEL, OMIT_LABEL }; - void DebugString(int depth, PrintLabelFlag print_label_flag, - string* contents, const DebugStringOptions& options) const; + void DebugString(int depth, std::string* contents, + const DebugStringOptions& options) const; // formats the default value appropriately and returns it as a string. // Must have a default value to call this. If quote_string_type is true, then // types of CPPTYPE_STRING whill be surrounded by quotes and CEscaped. - string DefaultValueAsString(bool quote_string_type) const; + std::string DefaultValueAsString(bool quote_string_type) const; // Helper function that returns the field type name for DebugString. - string FieldTypeNameDebugString() const; + std::string FieldTypeNameDebugString() const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. @@ -745,58 +894,76 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Returns true if this is a map message type. bool is_map_message_type() const; - const string* name_; - const string* full_name_; - const string* lowercase_name_; - const string* camelcase_name_; - // If has_json_name_ is true, it's the value specified by the user. - // Otherwise, it has the same value as camelcase_name_. - const string* json_name_; - const FileDescriptor* file_; - GoogleOnceDynamic* type_once_; - static void TypeOnceInit(const FieldDescriptor* to_init); - void InternalTypeOnceInit() const; - mutable Type type_; - Label label_; - bool has_default_value_; + bool has_default_value_ : 1; + bool proto3_optional_ : 1; // Whether the user has specified the json_name field option in the .proto // file. - bool has_json_name_; - bool is_extension_; + bool has_json_name_ : 1; + bool is_extension_ : 1; + bool is_oneof_ : 1; + + // Actually a `Label` but stored as uint8_t to save space. + uint8_t label_ : 2; + + // Actually a `Type`, but stored as uint8_t to save space. + mutable uint8_t type_; + + // Logically: + // all_names_ = [name, full_name, lower, camel, json] + // However: + // duplicates will be omitted, so lower/camel/json might be in the same + // position. + // We store the true offset for each name here, and the bit width must be + // large enough to account for the worst case where all names are present. + uint8_t lowercase_name_index_ : 2; + uint8_t camelcase_name_index_ : 2; + uint8_t json_name_index_ : 3; + // Sadly, `number_` located here to reduce padding. Unrelated to all_names_ + // and its indices above. int number_; - int index_in_oneof_; + const std::string* all_names_; + const FileDescriptor* file_; + + internal::once_flag* type_once_; + static void TypeOnceInit(const FieldDescriptor* to_init); + void InternalTypeOnceInit() const; const Descriptor* containing_type_; - const OneofDescriptor* containing_oneof_; - const Descriptor* extension_scope_; - mutable const Descriptor* message_type_; - mutable const EnumDescriptor* enum_type_; + union { + const OneofDescriptor* containing_oneof; + const Descriptor* extension_scope; + } scope_; + union { + mutable const Descriptor* message_type; + mutable const EnumDescriptor* enum_type; + const char* lazy_type_name; + } type_descriptor_; const FieldOptions* options_; - const string* type_name_; - const string* default_value_enum_name_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() in // descriptor.cc and update them to initialize the field. union { - int32 default_value_int32_; - int64 default_value_int64_; - uint32 default_value_uint32_; - uint64 default_value_uint64_; - float default_value_float_; + int32_t default_value_int32_t_; + int64_t default_value_int64_t_; + uint32_t default_value_uint32_t_; + uint64_t default_value_uint64_t_; + float default_value_float_; double default_value_double_; - bool default_value_bool_; + bool default_value_bool_; mutable const EnumValueDescriptor* default_value_enum_; - const string* default_value_string_; + const char* lazy_default_value_enum_name_; + const std::string* default_value_string_; + mutable std::atomic default_generated_instance_; }; static const CppType kTypeToCppTypeMap[MAX_TYPE + 1]; - static const char * const kTypeToName[MAX_TYPE + 1]; + static const char* const kTypeToName[MAX_TYPE + 1]; - static const char * const kCppTypeToName[MAX_CPPTYPE + 1]; + static const char* const kCppTypeToName[MAX_CPPTYPE + 1]; - static const char * const kLabelToName[MAX_LABEL + 1]; + static const char* const kLabelToName[MAX_LABEL + 1]; // Must be constructed using DescriptorPool. FieldDescriptor() {} @@ -809,15 +976,21 @@ class LIBPROTOBUF_EXPORT FieldDescriptor { // Describes a oneof defined in a message type. -class LIBPROTOBUF_EXPORT OneofDescriptor { +class PROTOBUF_EXPORT OneofDescriptor : private internal::SymbolBase { public: - const string& name() const; // Name of this oneof. - const string& full_name() const; // Fully-qualified name of the oneof. + typedef OneofDescriptorProto Proto; + + const std::string& name() const; // Name of this oneof. + const std::string& full_name() const; // Fully-qualified name of the oneof. // Index of this oneof within the message's oneof array. int index() const; - // The .proto file in which this oneof was defined. Never NULL. + // Returns whether this oneof was inserted by the compiler to wrap a proto3 + // optional field. If this returns true, code generators should *not* emit it. + bool is_synthetic() const; + + // The .proto file in which this oneof was defined. Never nullptr. const FileDescriptor* file() const; // The Descriptor for the message containing this oneof. const Descriptor* containing_type() const; @@ -834,10 +1007,10 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { void CopyTo(OneofDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -847,26 +1020,28 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { bool GetSourceLocation(SourceLocation* out_location) const; private: + friend class Symbol; typedef OneofOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string* contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; - const Descriptor* containing_type_; - bool is_extendable_; int field_count_; - const FieldDescriptor** fields_; + + // all_names_ = [name, full_name] + const std::string* all_names_; + const Descriptor* containing_type_; const OneofOptions* options_; + const FieldDescriptor* fields_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() @@ -882,18 +1057,20 @@ class LIBPROTOBUF_EXPORT OneofDescriptor { // Describes an enum type defined in a .proto file. To get the EnumDescriptor // for a generated enum type, call TypeName_descriptor(). Use DescriptorPool // to construct your own descriptors. -class LIBPROTOBUF_EXPORT EnumDescriptor { +class PROTOBUF_EXPORT EnumDescriptor : private internal::SymbolBase { public: + typedef EnumDescriptorProto Proto; + // The name of this enum type in the containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the enum type, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index of this enum within the file or containing message's enum array. int index() const; - // The .proto file in which this enum type was defined. Never NULL. + // The .proto file in which this enum type was defined. Never nullptr. const FileDescriptor* file() const; // The number of values for this EnumDescriptor. Guaranteed to be greater @@ -903,30 +1080,30 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { // These are returned in the order they were defined in the .proto file. const EnumValueDescriptor* value(int index) const; - // Looks up a value by name. Returns NULL if no such value exists. - const EnumValueDescriptor* FindValueByName(const string& name) const; - // Looks up a value by number. Returns NULL if no such value exists. If + // Looks up a value by name. Returns nullptr if no such value exists. + const EnumValueDescriptor* FindValueByName(ConstStringParam name) const; + // Looks up a value by number. Returns nullptr if no such value exists. If // multiple values have this number, the first one defined is returned. const EnumValueDescriptor* FindValueByNumber(int number) const; // If this enum type is nested in a message type, this is that message type. - // Otherwise, NULL. + // Otherwise, nullptr. const Descriptor* containing_type() const; // Get options for this enum type. These are specified in the .proto file by // placing lines like "option foo = 1234;" in the enum definition. Allowed - // options are defined by EnumOptions in google/protobuf/descriptor.proto, - // and any available extensions of that message. + // options are defined by EnumOptions in descriptor.proto, and any available + // extensions of that message. const EnumOptions& options() const; // See Descriptor::CopyTo(). void CopyTo(EnumDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown enum. This will // only be the case if this descriptor comes from a DescriptorPool @@ -951,18 +1128,18 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { // Returns true if the number is in one of the reserved ranges. bool IsReservedNumber(int number) const; - // Returns NULL if no reserved range contains the given number. - const EnumDescriptor::ReservedRange* - FindReservedRangeContainingNumber(int number) const; + // Returns nullptr if no reserved range contains the given number. + const EnumDescriptor::ReservedRange* FindReservedRangeContainingNumber( + int number) const; // The number of reserved field names in this message type. int reserved_name_count() const; // Gets a reserved name by index, where 0 <= index < reserved_name_count(). - const string& reserved_name(int index) const; + const std::string& reserved_name(int index) const; // Returns true if the field name is reserved. - bool IsReservedName(const string& name) const; + bool IsReservedName(ConstStringParam name) const; // Source Location --------------------------------------------------- @@ -972,49 +1149,62 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { bool GetSourceLocation(SourceLocation* out_location) const; private: + friend class Symbol; typedef EnumOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; + + // Allow access to FindValueByNumberCreatingIfUnknown. + friend class descriptor_unittest::DescriptorTest; // Looks up a value by number. If the value does not exist, dynamically // creates a new EnumValueDescriptor for that value, assuming that it was // unknown. If a new descriptor is created, this is done in a thread-safe way, // and future calls will return the same value descriptor pointer. // - // This is private but is used by GeneratedMessageReflection (which is - // friended below) to return a valid EnumValueDescriptor from GetEnum() when - // this feature is enabled. - const EnumValueDescriptor* - FindValueByNumberCreatingIfUnknown(int number) const; - + // This is private but is used by Reflection (which is friended below) to + // return a valid EnumValueDescriptor from GetEnum() when this feature is + // enabled. + const EnumValueDescriptor* FindValueByNumberCreatingIfUnknown( + int number) const; // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + // True if this is a placeholder for an unknown type. + bool is_placeholder_ : 1; + // True if this is a placeholder and the type name wasn't fully-qualified. + bool is_unqualified_placeholder_ : 1; + + // This points to the last value _index_ that is part of the sequence starting + // with the first label, where + // `enum->value(i)->number() == enum->value(0)->number() + i` + // We measure relative to the first label to adapt to enum labels starting at + // 0 or 1. + // Uses 16-bit to avoid extra padding. Unlikely to have more than 2^15 + // sequentially numbered labels in an enum. + int16_t sequential_value_limit_; + + int value_count_; + + // all_names_ = [name, full_name] + const std::string* all_names_; const FileDescriptor* file_; const Descriptor* containing_type_; const EnumOptions* options_; - - // True if this is a placeholder for an unknown type. - bool is_placeholder_; - // True if this is a placeholder and the type name wasn't fully-qualified. - bool is_unqualified_placeholder_; - - int value_count_; EnumValueDescriptor* values_; int reserved_range_count_; int reserved_name_count_; EnumDescriptor::ReservedRange* reserved_ranges_; - const string** reserved_names_; + const std::string** reserved_names_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() in @@ -1025,10 +1215,11 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { friend class DescriptorBuilder; friend class Descriptor; friend class FieldDescriptor; + friend class FileDescriptorTables; friend class EnumValueDescriptor; friend class FileDescriptor; friend class DescriptorPool; - friend class internal::GeneratedMessageReflection; + friend class Reflection; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumDescriptor); }; @@ -1037,40 +1228,41 @@ class LIBPROTOBUF_EXPORT EnumDescriptor { // for its type, then use EnumDescriptor::FindValueByName() or // EnumDescriptor::FindValueByNumber(). Use DescriptorPool to construct // your own descriptors. -class LIBPROTOBUF_EXPORT EnumValueDescriptor { +class PROTOBUF_EXPORT EnumValueDescriptor : private internal::SymbolBaseN<0>, + private internal::SymbolBaseN<1> { public: - const string& name() const; // Name of this enum constant. - int index() const; // Index within the enums's Descriptor. - int number() const; // Numeric value of this enum constant. + typedef EnumValueDescriptorProto Proto; + + const std::string& name() const; // Name of this enum constant. + int index() const; // Index within the enums's Descriptor. + int number() const; // Numeric value of this enum constant. // The full_name of an enum value is a sibling symbol of the enum type. // e.g. the full name of FieldDescriptorProto::TYPE_INT32 is actually // "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT // "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32". This is to conform // with C++ scoping rules for enums. - const string& full_name() const; + const std::string& full_name() const; - // The .proto file in which this value was defined. Never NULL. + // The .proto file in which this value was defined. Never nullptr. const FileDescriptor* file() const; - // The type of this value. Never NULL. + // The type of this value. Never nullptr. const EnumDescriptor* type() const; - // Get options for this enum value. These are specified in the .proto file - // by adding text like "[foo = 1234]" after an enum value definition. - // Allowed options are defined by EnumValueOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // Get options for this enum value. These are specified in the .proto file by + // adding text like "[foo = 1234]" after an enum value definition. Allowed + // options are defined by EnumValueOptions in descriptor.proto, and any + // available extensions of that message. const EnumValueOptions& options() const; // See Descriptor::CopyTo(). void CopyTo(EnumValueDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; - + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1080,22 +1272,24 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor { bool GetSourceLocation(SourceLocation* out_location) const; private: + friend class Symbol; typedef EnumValueOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; int number_; + // all_names_ = [name, full_name] + const std::string* all_names_; const EnumDescriptor* type_; const EnumValueOptions* options_; // IMPORTANT: If you add a new field, make sure to search for all instances @@ -1108,30 +1302,30 @@ class LIBPROTOBUF_EXPORT EnumValueDescriptor { friend class EnumDescriptor; friend class DescriptorPool; friend class FileDescriptorTables; + friend class Reflection; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumValueDescriptor); }; -// Describes an RPC service. To get the ServiceDescriptor for a service, -// call Service::GetDescriptor(). Generated service classes also have a -// static method called descriptor() which returns the type's -// ServiceDescriptor. Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT ServiceDescriptor { +// Describes an RPC service. Use DescriptorPool to construct your own +// descriptors. +class PROTOBUF_EXPORT ServiceDescriptor : private internal::SymbolBase { public: + typedef ServiceDescriptorProto Proto; + // The name of the service, not including its containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the service, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index of this service within the file's services array. int index() const; - // The .proto file in which this service was defined. Never NULL. + // The .proto file in which this service was defined. Never nullptr. const FileDescriptor* file() const; // Get options for this service type. These are specified in the .proto file // by placing lines like "option foo = 1234;" in the service definition. - // Allowed options are defined by ServiceOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // Allowed options are defined by ServiceOptions in descriptor.proto, and any + // available extensions of that message. const ServiceOptions& options() const; // The number of methods this service defines. @@ -1141,16 +1335,15 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { const MethodDescriptor* method(int index) const; // Look up a MethodDescriptor by name. - const MethodDescriptor* FindMethodByName(const string& name) const; + const MethodDescriptor* FindMethodByName(ConstStringParam name) const; // See Descriptor::CopyTo(). void CopyTo(ServiceDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; - + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1160,20 +1353,23 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { bool GetSourceLocation(SourceLocation* out_location) const; private: + friend class Symbol; typedef ServiceOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(string *contents, const DebugStringOptions& options) const; + void DebugString(std::string* contents, + const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + // all_names_ = [name, full_name] + const std::string* all_names_; const FileDescriptor* file_; const ServiceOptions* options_; MethodDescriptor* methods_; @@ -1195,18 +1391,20 @@ class LIBPROTOBUF_EXPORT ServiceDescriptor { // a service, first get its ServiceDescriptor, then call // ServiceDescriptor::FindMethodByName(). Use DescriptorPool to construct your // own descriptors. -class LIBPROTOBUF_EXPORT MethodDescriptor { +class PROTOBUF_EXPORT MethodDescriptor : private internal::SymbolBase { public: + typedef MethodDescriptorProto Proto; + // Name of this method, not including containing scope. - const string& name() const; + const std::string& name() const; // The fully-qualified name of the method, scope delimited by periods. - const string& full_name() const; + const std::string& full_name() const; // Index within the service's Descriptor. int index() const; - // The .proto file in which this method was defined. Never NULL. + // The .proto file in which this method was defined. Never nullptr. const FileDescriptor* file() const; - // Gets the service to which this method belongs. Never NULL. + // Gets the service to which this method belongs. Never nullptr. const ServiceDescriptor* service() const; // Gets the type of protocol message which this method accepts as input. @@ -1222,19 +1420,17 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { // Get options for this method. These are specified in the .proto file by // placing lines like "option foo = 1234;" in curly-braces after a method // declaration. Allowed options are defined by MethodOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // descriptor.proto, and any available extensions of that message. const MethodOptions& options() const; // See Descriptor::CopyTo(). void CopyTo(MethodDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; - + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Source Location --------------------------------------------------- @@ -1244,27 +1440,29 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { bool GetSourceLocation(SourceLocation* out_location) const; private: + friend class Symbol; typedef MethodOptions OptionsType; // Allows access to GetLocationPath for annotations. - friend class ::google::protobuf::io::Printer; + friend class io::Printer; + friend class compiler::cpp::Formatter; // See Descriptor::DebugString(). - void DebugString(int depth, string *contents, + void DebugString(int depth, std::string* contents, const DebugStringOptions& options) const; // Walks up the descriptor tree to generate the source location path // to this descriptor from the file root. void GetLocationPath(std::vector* output) const; - const string* name_; - const string* full_name_; + bool client_streaming_; + bool server_streaming_; + // all_names_ = [name, full_name] + const std::string* all_names_; const ServiceDescriptor* service_; mutable internal::LazyDescriptor input_type_; mutable internal::LazyDescriptor output_type_; const MethodOptions* options_; - bool client_streaming_; - bool server_streaming_; // IMPORTANT: If you add a new field, make sure to search for all instances // of Allocate() and AllocateArray() in // descriptor.cc and update them to initialize the field. @@ -1280,17 +1478,19 @@ class LIBPROTOBUF_EXPORT MethodDescriptor { // Describes a whole .proto file. To get the FileDescriptor for a compiled-in // file, get the descriptor for something defined in that file and call // descriptor->file(). Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT FileDescriptor { +class PROTOBUF_EXPORT FileDescriptor { public: + typedef FileDescriptorProto Proto; + // The filename, relative to the source tree. - // e.g. "google/protobuf/descriptor.proto" - const string& name() const; + // e.g. "foo/bar/baz.proto" + const std::string& name() const; // The package, e.g. "google.protobuf.compiler". - const string& package() const; + const std::string& package() const; // The DescriptorPool in which this FileDescriptor and all its contents were - // allocated. Never NULL. + // allocated. Never nullptr. const DescriptorPool* pool() const; // The number of files imported by this one. @@ -1345,36 +1545,39 @@ class LIBPROTOBUF_EXPORT FileDescriptor { // Get options for this file. These are specified in the .proto file by // placing lines like "option foo = 1234;" at the top level, outside of any // other definitions. Allowed options are defined by FileOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. + // descriptor.proto, and any available extensions of that message. const FileOptions& options() const; // Syntax of this file. enum Syntax { SYNTAX_UNKNOWN = 0, - SYNTAX_PROTO2 = 2, - SYNTAX_PROTO3 = 3, + SYNTAX_PROTO2 = 2, + SYNTAX_PROTO3 = 3, }; Syntax syntax() const; static const char* SyntaxName(Syntax syntax); - // Find a top-level message type by name. Returns NULL if not found. - const Descriptor* FindMessageTypeByName(const string& name) const; - // Find a top-level enum type by name. Returns NULL if not found. - const EnumDescriptor* FindEnumTypeByName(const string& name) const; - // Find an enum value defined in any top-level enum by name. Returns NULL if + // Find a top-level message type by name (not full_name). Returns nullptr if // not found. - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; - // Find a service definition by name. Returns NULL if not found. - const ServiceDescriptor* FindServiceByName(const string& name) const; - // Find a top-level extension definition by name. Returns NULL if not found. - const FieldDescriptor* FindExtensionByName(const string& name) const; + const Descriptor* FindMessageTypeByName(ConstStringParam name) const; + // Find a top-level enum type by name. Returns nullptr if not found. + const EnumDescriptor* FindEnumTypeByName(ConstStringParam name) const; + // Find an enum value defined in any top-level enum by name. Returns nullptr + // if not found. + const EnumValueDescriptor* FindEnumValueByName(ConstStringParam name) const; + // Find a service definition by name. Returns nullptr if not found. + const ServiceDescriptor* FindServiceByName(ConstStringParam name) const; + // Find a top-level extension definition by name. Returns nullptr if not + // found. + const FieldDescriptor* FindExtensionByName(ConstStringParam name) const; // Similar to FindExtensionByName(), but searches by lowercased-name. See // Descriptor::FindFieldByLowercaseName(). - const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const; + const FieldDescriptor* FindExtensionByLowercaseName( + ConstStringParam name) const; // Similar to FindExtensionByName(), but searches by camelcased-name. See // Descriptor::FindFieldByCamelcaseName(). - const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const; + const FieldDescriptor* FindExtensionByCamelcaseName( + ConstStringParam name) const; // See Descriptor::CopyTo(). // Notes: @@ -1389,10 +1592,10 @@ class LIBPROTOBUF_EXPORT FileDescriptor { void CopyJsonNameTo(FileDescriptorProto* proto) const; // See Descriptor::DebugString(). - string DebugString() const; + std::string DebugString() const; // See Descriptor::DebugStringWithOptions(). - string DebugStringWithOptions(const DebugStringOptions& options) const; + std::string DebugStringWithOptions(const DebugStringOptions& options) const; // Returns true if this is a placeholder for an unknown file. This will // only be the case if this descriptor comes from a DescriptorPool @@ -1414,31 +1617,41 @@ class LIBPROTOBUF_EXPORT FileDescriptor { private: typedef FileOptions OptionsType; - const string* name_; - const string* package_; + const std::string* name_; + const std::string* package_; const DescriptorPool* pool_; - GoogleOnceDynamic* dependencies_once_; + + // Data required to do lazy initialization. + struct PROTOBUF_EXPORT LazyInitData { +#ifndef SWIG + internal::once_flag once; +#endif + const char** dependencies_names; + }; + + LazyInitData* dependencies_once_; static void DependenciesOnceInit(const FileDescriptor* to_init); void InternalDependenciesOnceInit() const; - // These are arranged to minimze padding on 64-bit. + // These are arranged to minimize padding on 64-bit. int dependency_count_; int public_dependency_count_; int weak_dependency_count_; int message_type_count_; int enum_type_count_; int service_count_; - int extension_count_; - Syntax syntax_; - bool is_placeholder_; + bool is_placeholder_; // Indicates the FileDescriptor is completed building. Used to verify // that type accessor functions that can possibly build a dependent file // aren't called during the process of building the file. bool finished_building_; + // Actually a `Syntax` but stored as uint8_t to save space. + uint8_t syntax_; + // This one is here to fill the padding. + int extension_count_; mutable const FileDescriptor** dependencies_; - const string** dependencies_names_; int* public_dependencies_; int* weak_dependencies_; Descriptor* message_types_; @@ -1495,7 +1708,7 @@ class LIBPROTOBUF_EXPORT FileDescriptor { // // You can also search for descriptors within a DescriptorPool by name, and // extensions by number. -class LIBPROTOBUF_EXPORT DescriptorPool { +class PROTOBUF_EXPORT DescriptorPool { public: // Create a normal, empty DescriptorPool. DescriptorPool(); @@ -1525,7 +1738,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // in subsequent lookups in the DescriptorPool. class ErrorCollector; explicit DescriptorPool(DescriptorDatabase* fallback_database, - ErrorCollector* error_collector = NULL); + ErrorCollector* error_collector = nullptr); ~DescriptorPool(); @@ -1535,36 +1748,44 @@ class LIBPROTOBUF_EXPORT DescriptorPool { static const DescriptorPool* generated_pool(); - // Find a FileDescriptor in the pool by file name. Returns NULL if not + // Find a FileDescriptor in the pool by file name. Returns nullptr if not // found. - const FileDescriptor* FindFileByName(const string& name) const; + const FileDescriptor* FindFileByName(ConstStringParam name) const; // Find the FileDescriptor in the pool which defines the given symbol. // If any of the Find*ByName() methods below would succeed, then this is // equivalent to calling that method and calling the result's file() method. - // Otherwise this returns NULL. + // Otherwise this returns nullptr. const FileDescriptor* FindFileContainingSymbol( - const string& symbol_name) const; + ConstStringParam symbol_name) const; // Looking up descriptors ------------------------------------------ // These find descriptors by fully-qualified name. These will find both - // top-level descriptors and nested descriptors. They return NULL if not + // top-level descriptors and nested descriptors. They return nullptr if not // found. - const Descriptor* FindMessageTypeByName(const string& name) const; - const FieldDescriptor* FindFieldByName(const string& name) const; - const FieldDescriptor* FindExtensionByName(const string& name) const; - const OneofDescriptor* FindOneofByName(const string& name) const; - const EnumDescriptor* FindEnumTypeByName(const string& name) const; - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; - const ServiceDescriptor* FindServiceByName(const string& name) const; - const MethodDescriptor* FindMethodByName(const string& name) const; + const Descriptor* FindMessageTypeByName(ConstStringParam name) const; + const FieldDescriptor* FindFieldByName(ConstStringParam name) const; + const FieldDescriptor* FindExtensionByName(ConstStringParam name) const; + const OneofDescriptor* FindOneofByName(ConstStringParam name) const; + const EnumDescriptor* FindEnumTypeByName(ConstStringParam name) const; + const EnumValueDescriptor* FindEnumValueByName(ConstStringParam name) const; + const ServiceDescriptor* FindServiceByName(ConstStringParam name) const; + const MethodDescriptor* FindMethodByName(ConstStringParam name) const; // Finds an extension of the given type by number. The extendee must be // a member of this DescriptorPool or one of its underlays. const FieldDescriptor* FindExtensionByNumber(const Descriptor* extendee, int number) const; + // Finds an extension of the given type by its printable name. + // See comments above PrintableNameForExtension() for the definition of + // "printable name". The extendee must be a member of this DescriptorPool + // or one of its underlays. Returns nullptr if there is no known message + // extension with the given printable name. + const FieldDescriptor* FindExtensionByPrintableName( + const Descriptor* extendee, ConstStringParam printable_name) const; + // Finds extensions of extendee. The extensions will be appended to // out in an undefined order. Only extensions defined directly in // this DescriptorPool or one of its underlays are guaranteed to be @@ -1578,7 +1799,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // When converting a FileDescriptorProto to a FileDescriptor, various // errors might be detected in the input. The caller may handle these // programmatically by implementing an ErrorCollector. - class LIBPROTOBUF_EXPORT ErrorCollector { + class PROTOBUF_EXPORT ErrorCollector { public: inline ErrorCollector() {} virtual ~ErrorCollector(); @@ -1587,37 +1808,40 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // This is useful e.g. for mapping the error back to an exact location // in a .proto file. enum ErrorLocation { - NAME, // the symbol name, or the package name for files - NUMBER, // field or extension range number - TYPE, // field type - EXTENDEE, // field extendee - DEFAULT_VALUE, // field default value - INPUT_TYPE, // method input type - OUTPUT_TYPE, // method output type - OPTION_NAME, // name in assignment - OPTION_VALUE, // value in option assignment - OTHER // some other problem + NAME, // the symbol name, or the package name for files + NUMBER, // field or extension range number + TYPE, // field type + EXTENDEE, // field extendee + DEFAULT_VALUE, // field default value + INPUT_TYPE, // method input type + OUTPUT_TYPE, // method output type + OPTION_NAME, // name in assignment + OPTION_VALUE, // value in option assignment + IMPORT, // import error + OTHER // some other problem }; // Reports an error in the FileDescriptorProto. Use this function if the // problem occurred should interrupt building the FileDescriptorProto. virtual void AddError( - const string& filename, // File name in which the error occurred. - const string& element_name, // Full name of the erroneous element. - const Message* descriptor, // Descriptor of the erroneous element. - ErrorLocation location, // One of the location constants, above. - const string& message // Human-readable error message. - ) = 0; + const std::string& filename, // File name in which the error occurred. + const std::string& element_name, // Full name of the erroneous element. + const Message* descriptor, // Descriptor of the erroneous element. + ErrorLocation location, // One of the location constants, above. + const std::string& message // Human-readable error message. + ) = 0; // Reports a warning in the FileDescriptorProto. Use this function if the // problem occurred should NOT interrupt building the FileDescriptorProto. virtual void AddWarning( - const string& /*filename*/, // File name in which the error occurred. - const string& /*element_name*/, // Full name of the erroneous element. - const Message* /*descriptor*/, // Descriptor of the erroneous element. - ErrorLocation /*location*/, // One of the location constants, above. - const string& /*message*/ // Human-readable error message. - ) {} + const std::string& /*filename*/, // File name in which the error + // occurred. + const std::string& /*element_name*/, // Full name of the erroneous + // element. + const Message* /*descriptor*/, // Descriptor of the erroneous element. + ErrorLocation /*location*/, // One of the location constants, above. + const std::string& /*message*/ // Human-readable error message. + ) {} private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector); @@ -1625,15 +1849,14 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Convert the FileDescriptorProto to real descriptors and place them in // this DescriptorPool. All dependencies of the file must already be in - // the pool. Returns the resulting FileDescriptor, or NULL if there were + // the pool. Returns the resulting FileDescriptor, or nullptr if there were // problems with the input (e.g. the message was invalid, or dependencies // were missing). Details about the errors are written to GOOGLE_LOG(ERROR). const FileDescriptor* BuildFile(const FileDescriptorProto& proto); // Same as BuildFile() except errors are sent to the given ErrorCollector. const FileDescriptor* BuildFileCollectingErrors( - const FileDescriptorProto& proto, - ErrorCollector* error_collector); + const FileDescriptorProto& proto, ErrorCollector* error_collector); // By default, it is an error if a FileDescriptorProto contains references // to types or other files that are not found in the DescriptorPool (or its @@ -1688,8 +1911,8 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Called by generated classes at init time to add their descriptors to // generated_pool. Do NOT call this in your own code! filename must be a // permanent string (e.g. a string literal). - static void InternalAddGeneratedFile( - const void* encoded_file_descriptor, int size); + static void InternalAddGeneratedFile(const void* encoded_file_descriptor, + int size); // Disallow [enforce_utf8 = false] in .proto files. void DisallowEnforceUtf8() { disallow_enforce_utf8_ = true; } @@ -1701,6 +1924,11 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // the underlay takes precedence. static DescriptorPool* internal_generated_pool(); + // For internal use only: Gets a non-const pointer to the generated + // descriptor database. + // Only used for testing. + static DescriptorDatabase* internal_generated_database(); + // For internal use only: Changes the behavior of BuildFile() such that it // allows the file to make reference to message types declared in other files // which it did not officially declare as dependencies. @@ -1710,7 +1938,7 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Delay the building of dependencies of a file descriptor until absolutely // necessary, like when message_type() is called on a field that is defined // in that dependency's file. This will cause functional issues if a proto - // or one of it's dependencies has errors. Should only be enabled for the + // or one of its dependencies has errors. Should only be enabled for the // generated_pool_ (because no descriptor build errors are guaranteed by // the compilation generation process), testing, or if a lack of descriptor // build errors can be guaranteed for a pool. @@ -1729,12 +1957,12 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // For internal (unit test) use only: Returns true if a FileDescriptor has // been constructed for the given file, false otherwise. Useful for testing // lazy descriptor initialization behavior. - bool InternalIsFileLoaded(const string& filename) const; - + bool InternalIsFileLoaded(ConstStringParam filename) const; // Add a file to unused_import_track_files_. DescriptorBuilder will log - // warnings for those files if there is any unused import. - void AddUnusedImportTrackFile(const string& file_name); + // warnings or errors for those files if there is any unused import. + void AddUnusedImportTrackFile(ConstStringParam file_name, + bool is_error = false); void ClearUnusedImportTrackFiles(); private: @@ -1752,33 +1980,40 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Return true if the given name is a sub-symbol of any non-package // descriptor that already exists in the descriptor pool. (The full // definition of such types is already known.) - bool IsSubSymbolOfBuiltType(const string& name) const; + bool IsSubSymbolOfBuiltType(StringPiece name) const; // Tries to find something in the fallback database and link in the // corresponding proto file. Returns true if successful, in which case // the caller should search for the thing again. These are declared // const because they are called by (semantically) const methods. - bool TryFindFileInFallbackDatabase(const string& name) const; - bool TryFindSymbolInFallbackDatabase(const string& name) const; + bool TryFindFileInFallbackDatabase(StringPiece name) const; + bool TryFindSymbolInFallbackDatabase(StringPiece name) const; bool TryFindExtensionInFallbackDatabase(const Descriptor* containing_type, int field_number) const; + // This internal find extension method only check with its table and underlay + // descriptor_pool's table. It does not check with fallback DB and no + // additional proto file will be build in this method. + const FieldDescriptor* InternalFindExtensionByNumberNoLock( + const Descriptor* extendee, int number) const; + // Like BuildFile() but called internally when the file has been loaded from // fallback_database_. Declared const because it is called by (semantically) // const methods. const FileDescriptor* BuildFileFromDatabase( - const FileDescriptorProto& proto) const; + const FileDescriptorProto& proto) const; // Helper for when lazily_build_dependencies_ is set, can look up a symbol // after the file's descriptor is built, and can build the file where that // symbol is defined if necessary. Will create a placeholder if the type // doesn't exist in the fallback database, or the file doesn't build // successfully. - Symbol CrossLinkOnDemandHelper(const string& name, bool expecting_enum) const; + Symbol CrossLinkOnDemandHelper(StringPiece name, + bool expecting_enum) const; // Create a placeholder FileDescriptor of the specified name - FileDescriptor* NewPlaceholderFile(const string& name) const; - FileDescriptor* NewPlaceholderFileWithMutexHeld(const string& name) const; + FileDescriptor* NewPlaceholderFile(StringPiece name) const; + FileDescriptor* NewPlaceholderFileWithMutexHeld(StringPiece name) const; enum PlaceholderType { PLACEHOLDER_MESSAGE, @@ -1786,14 +2021,14 @@ class LIBPROTOBUF_EXPORT DescriptorPool { PLACEHOLDER_EXTENDABLE_MESSAGE }; // Create a placeholder Descriptor of the specified name - Symbol NewPlaceholder(const string& name, + Symbol NewPlaceholder(StringPiece name, PlaceholderType placeholder_type) const; - Symbol NewPlaceholderWithMutexHeld(const string& name, + Symbol NewPlaceholderWithMutexHeld(StringPiece name, PlaceholderType placeholder_type) const; - // If fallback_database_ is NULL, this is NULL. Otherwise, this is a mutex - // which must be locked while accessing tables_. - Mutex* mutex_; + // If fallback_database_ is nullptr, this is nullptr. Otherwise, this is a + // mutex which must be locked while accessing tables_. + internal::WrappedMutex* mutex_; // See constructor. DescriptorDatabase* fallback_database_; @@ -1810,7 +2045,10 @@ class LIBPROTOBUF_EXPORT DescriptorPool { bool allow_unknown_; bool enforce_weak_; bool disallow_enforce_utf8_; - std::set unused_import_track_files_; + + // Set of files to track for unused imports. The bool value when true means + // unused imports are treated as errors (and as warnings when false). + std::map unused_import_track_files_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPool); }; @@ -1824,7 +2062,12 @@ class LIBPROTOBUF_EXPORT DescriptorPool { // Strings fields are stored as pointers but returned as const references. #define PROTOBUF_DEFINE_STRING_ACCESSOR(CLASS, FIELD) \ - inline const string& CLASS::FIELD() const { return *FIELD##_; } + inline const std::string& CLASS::FIELD() const { return *FIELD##_; } + +// Name and full name are stored in a single array to save space. +#define PROTOBUF_DEFINE_NAME_ACCESSOR(CLASS) \ + inline const std::string& CLASS::name() const { return all_names_[0]; } \ + inline const std::string& CLASS::full_name() const { return all_names_[1]; } // Arrays take an index parameter, obviously. #define PROTOBUF_DEFINE_ARRAY_ACCESSOR(CLASS, FIELD, TYPE) \ @@ -1833,13 +2076,13 @@ class LIBPROTOBUF_EXPORT DescriptorPool { #define PROTOBUF_DEFINE_OPTIONS_ACCESSOR(CLASS, TYPE) \ inline const TYPE& CLASS::options() const { return *options_; } -PROTOBUF_DEFINE_STRING_ACCESSOR(Descriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(Descriptor, full_name) +PROTOBUF_DEFINE_NAME_ACCESSOR(Descriptor) PROTOBUF_DEFINE_ACCESSOR(Descriptor, file, const FileDescriptor*) PROTOBUF_DEFINE_ACCESSOR(Descriptor, containing_type, const Descriptor*) PROTOBUF_DEFINE_ACCESSOR(Descriptor, field_count, int) PROTOBUF_DEFINE_ACCESSOR(Descriptor, oneof_decl_count, int) +PROTOBUF_DEFINE_ACCESSOR(Descriptor, real_oneof_decl_count, int) PROTOBUF_DEFINE_ACCESSOR(Descriptor, nested_type_count, int) PROTOBUF_DEFINE_ACCESSOR(Descriptor, enum_type_count, int) @@ -1852,8 +2095,7 @@ PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_range_count, int) PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_count, int) PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension_range, const Descriptor::ExtensionRange*) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension, - const FieldDescriptor*) +PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension, const FieldDescriptor*) PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_range_count, int) PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, reserved_range, @@ -1863,40 +2105,30 @@ PROTOBUF_DEFINE_ACCESSOR(Descriptor, reserved_name_count, int) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(Descriptor, MessageOptions) PROTOBUF_DEFINE_ACCESSOR(Descriptor, is_placeholder, bool) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, full_name) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, json_name) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, lowercase_name) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, camelcase_name) +PROTOBUF_DEFINE_NAME_ACCESSOR(FieldDescriptor) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, file, const FileDescriptor*) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, number, int) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, is_extension, bool) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, label, FieldDescriptor::Label) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_type, const Descriptor*) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_oneof, - const OneofDescriptor*) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, index_in_oneof, int) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, extension_scope, const Descriptor*) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_json_name, bool) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32 , int32 ) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64 , int64 ) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint32, uint32) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint64, uint64) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float , float ) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32_t, int32_t) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64_t, int64_t) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint32_t, uint32_t) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint64_t, uint64_t) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float, float) PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_double, double) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool , bool ) +PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool, bool) PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, default_value_string) -PROTOBUF_DEFINE_STRING_ACCESSOR(OneofDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(OneofDescriptor, full_name) +PROTOBUF_DEFINE_NAME_ACCESSOR(OneofDescriptor) PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, containing_type, const Descriptor*) PROTOBUF_DEFINE_ACCESSOR(OneofDescriptor, field_count, int) +PROTOBUF_DEFINE_ARRAY_ACCESSOR(OneofDescriptor, field, const FieldDescriptor*) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(OneofDescriptor, OneofOptions) -PROTOBUF_DEFINE_STRING_ACCESSOR(EnumDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(EnumDescriptor, full_name) +PROTOBUF_DEFINE_NAME_ACCESSOR(EnumDescriptor) PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, file, const FileDescriptor*) PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, containing_type, const Descriptor*) PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, value_count, int) @@ -1909,22 +2141,19 @@ PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, reserved_range, const EnumDescriptor::ReservedRange*) PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, reserved_name_count, int) -PROTOBUF_DEFINE_STRING_ACCESSOR(EnumValueDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(EnumValueDescriptor, full_name) +PROTOBUF_DEFINE_NAME_ACCESSOR(EnumValueDescriptor) PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, number, int) PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, type, const EnumDescriptor*) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumValueDescriptor, EnumValueOptions) -PROTOBUF_DEFINE_STRING_ACCESSOR(ServiceDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(ServiceDescriptor, full_name) +PROTOBUF_DEFINE_NAME_ACCESSOR(ServiceDescriptor) PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, file, const FileDescriptor*) PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, method_count, int) PROTOBUF_DEFINE_ARRAY_ACCESSOR(ServiceDescriptor, method, const MethodDescriptor*) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(ServiceDescriptor, ServiceOptions) -PROTOBUF_DEFINE_STRING_ACCESSOR(MethodDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(MethodDescriptor, full_name) +PROTOBUF_DEFINE_NAME_ACCESSOR(MethodDescriptor) PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, service, const ServiceDescriptor*) PROTOBUF_DEFINE_OPTIONS_ACCESSOR(MethodDescriptor, MethodOptions) PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, client_streaming, bool) @@ -1956,17 +2185,21 @@ PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, extension, // A few accessors differ from the macros... +inline Descriptor::WellKnownType Descriptor::well_known_type() const { + return static_cast(well_known_type_); +} + inline bool Descriptor::IsExtensionNumber(int number) const { - return FindExtensionRangeContainingNumber(number) != NULL; + return FindExtensionRangeContainingNumber(number) != nullptr; } inline bool Descriptor::IsReservedNumber(int number) const { - return FindReservedRangeContainingNumber(number) != NULL; + return FindReservedRangeContainingNumber(number) != nullptr; } -inline bool Descriptor::IsReservedName(const string& name) const { +inline bool Descriptor::IsReservedName(ConstStringParam name) const { for (int i = 0; i < reserved_name_count(); i++) { - if (name == reserved_name(i)) { + if (name == static_cast(reserved_name(i))) { return true; } } @@ -1975,17 +2208,17 @@ inline bool Descriptor::IsReservedName(const string& name) const { // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually // an array of pointers rather than the usual array of objects. -inline const string& Descriptor::reserved_name(int index) const { +inline const std::string& Descriptor::reserved_name(int index) const { return *reserved_names_[index]; } inline bool EnumDescriptor::IsReservedNumber(int number) const { - return FindReservedRangeContainingNumber(number) != NULL; + return FindReservedRangeContainingNumber(number) != nullptr; } -inline bool EnumDescriptor::IsReservedName(const string& name) const { +inline bool EnumDescriptor::IsReservedName(ConstStringParam name) const { for (int i = 0; i < reserved_name_count(); i++) { - if (name == reserved_name(i)) { + if (name == static_cast(reserved_name(i))) { return true; } } @@ -1994,15 +2227,45 @@ inline bool EnumDescriptor::IsReservedName(const string& name) const { // Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually // an array of pointers rather than the usual array of objects. -inline const string& EnumDescriptor::reserved_name(int index) const { +inline const std::string& EnumDescriptor::reserved_name(int index) const { return *reserved_names_[index]; } +inline const std::string& FieldDescriptor::lowercase_name() const { + return all_names_[lowercase_name_index_]; +} + +inline const std::string& FieldDescriptor::camelcase_name() const { + return all_names_[camelcase_name_index_]; +} + +inline const std::string& FieldDescriptor::json_name() const { + return all_names_[json_name_index_]; +} + +inline const OneofDescriptor* FieldDescriptor::containing_oneof() const { + return is_oneof_ ? scope_.containing_oneof : nullptr; +} + +inline int FieldDescriptor::index_in_oneof() const { + GOOGLE_DCHECK(is_oneof_); + return static_cast(this - scope_.containing_oneof->field(0)); +} + +inline const Descriptor* FieldDescriptor::extension_scope() const { + GOOGLE_CHECK(is_extension_); + return scope_.extension_scope; +} + +inline FieldDescriptor::Label FieldDescriptor::label() const { + return static_cast