This commit is contained in:
Kevin Darby committed 2019-01-02 16:52:09 -05:00
1 parent a28e541be0
commit e2dd18b3fa
421 files changed
+23599 -30913

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
$protobuf = "protobuf-3.5.0"
$protobuf = "protobuf-3.6.0"
$root = Resolve-Path "../.."
$work = Join-Path $root "work"
$src = Join-Path $root src
+1 -1
View File
@@ -1,6 +1,6 @@
#!/bin/bash
protobuf="protobuf-3.5.0"
protobuf="protobuf-3.6.0"
root=`realpath ../..`
work=$root/work
src=$root/src
+6
View File
@@ -4,6 +4,12 @@ then from
\spark\externals\src\protobuf> powershell -executionpolicy remotesigned -File build_protobuf.ps1
you will want to undelete (using git):
externals/windows/bin/protobuf-net.Reflection.dll
externals/windows/bin/protobuf-net.dll
externals/windows/bin/protogen.exe
you will probably want to put
#pragma warning( push )
Binary file not shown.
+10 -1
View File
@@ -32,6 +32,7 @@
#include <google/protobuf/generated_message_util.h>
namespace google {
namespace protobuf {
namespace internal {
@@ -84,15 +85,23 @@ bool AnyMetadata::InternalIs(const Descriptor* descriptor) const {
return full_name == descriptor->full_name();
}
bool ParseAnyTypeUrl(const string& type_url, string* full_type_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,
+11
View File
@@ -92,8 +92,19 @@ extern const char kTypeGoogleProdComPrefix[]; // "type.googleprod.com/".
// "type.googleapis.com/rpc.QueryOrigin" will return "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.
//
// 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);
// 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);
// See if message is of type google.protobuf.Any, if so, return the descriptors
// for "type_url" and "value" fields.
bool GetAnyFieldDescriptors(const Message& message,
+34 -39
View File
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,7 @@
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace google {
namespace protobuf {
class AnyDefaultTypeInternal {
@@ -29,14 +29,9 @@ class AnyDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fany_2eproto {
void InitDefaultsAnyImpl() {
static void InitDefaultsAny() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Any_default_instance_;
new (ptr) ::google::protobuf::Any();
@@ -45,9 +40,11 @@ void InitDefaultsAnyImpl() {
::google::protobuf::Any::InitAsDefaultInstance();
}
void InitDefaultsAny() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAnyImpl);
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];
@@ -71,15 +68,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets, factory,
"google/protobuf/any.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
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;
@@ -105,8 +101,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
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 {
@@ -134,6 +130,11 @@ void Any::PackFrom(const ::google::protobuf::Message& message,
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;
@@ -142,16 +143,14 @@ const int Any::kValueFieldNumber;
Any::Any()
: ::google::protobuf::Message(), _internal_metadata_(NULL), _any_metadata_(&type_url_, &value_) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
}
::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),
_cached_size_(0),
_any_metadata_(&type_url_, &value_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
@@ -168,7 +167,6 @@ Any::Any(const Any& from)
void Any::SharedCtor() {
type_url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_cached_size_ = 0;
}
Any::~Any() {
@@ -182,9 +180,7 @@ void Any::SharedDtor() {
}
void Any::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Any::descriptor() {
::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
@@ -192,17 +188,10 @@ const ::google::protobuf::Descriptor* Any::descriptor() {
}
const Any& Any::default_instance() {
::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fany_2eproto::scc_info_Any.base);
return *internal_default_instance();
}
Any* Any::New(::google::protobuf::Arena* arena) const {
Any* n = new Any;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Any::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Any)
@@ -221,7 +210,7 @@ bool Any::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Any)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
::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)) {
@@ -359,9 +348,7 @@ size_t Any::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
SetCachedSize(cached_size);
return total_size;
}
@@ -421,10 +408,11 @@ void Any::Swap(Any* other) {
}
void Any::InternalSwap(Any* other) {
using std::swap;
type_url_.Swap(&other->type_url_);
value_.Swap(&other->value_);
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_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Any::GetMetadata() const {
@@ -436,5 +424,12 @@ void Any::InternalSwap(Any* other) {
// @@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)
+34 -26
View File
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/any.proto
#ifndef PROTOBUF_google_2fprotobuf_2fany_2eproto__INCLUDED
#define PROTOBUF_google_2fprotobuf_2fany_2eproto__INCLUDED
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3005000
#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,6 +24,7 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -31,6 +32,7 @@
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/any.h>
// @@protoc_insertion_point(includes)
#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fany_2eproto LIBPROTOBUF_EXPORT
namespace protobuf_google_2fprotobuf_2fany_2eproto {
// Internal implementation detail -- do not use these members.
@@ -43,11 +45,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
void LIBPROTOBUF_EXPORT InitDefaultsAnyImpl();
void LIBPROTOBUF_EXPORT InitDefaultsAny();
inline void LIBPROTOBUF_EXPORT InitDefaults() {
InitDefaultsAny();
}
} // namespace protobuf_google_2fprotobuf_2fany_2eproto
namespace google {
namespace protobuf {
@@ -58,6 +55,11 @@ LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
} // 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 {
// ===================================================================
@@ -95,7 +97,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
return reinterpret_cast<const Any*>(
&_Any_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
static constexpr int kIndexInFileMessages =
0;
// implements Any -----------------------------------------------
@@ -107,6 +109,8 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
template<typename T> bool Is() const {
return _any_metadata_.Is<T>();
}
static bool ParseAnyTypeUrl(const string& type_url,
string* full_type_name);
void Swap(Any* other);
friend void swap(Any& a, Any& b) {
@@ -115,28 +119,33 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
// implements Message ----------------------------------------------
inline Any* New() const PROTOBUF_FINAL { return New(NULL); }
inline Any* New() const final {
return CreateMaybeMessage<Any>(NULL);
}
Any* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
Any* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<Any>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Any& from);
void MergeFrom(const Any& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const PROTOBUF_FINAL;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void SetCachedSize(int size) const final;
void InternalSwap(Any* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -147,7 +156,7 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -187,10 +196,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr type_url_;
::google::protobuf::internal::ArenaStringPtr value_;
mutable int _cached_size_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
::google::protobuf::internal::AnyMetadata _any_metadata_;
friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct;
friend void ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAnyImpl();
};
// ===================================================================
@@ -320,4 +328,4 @@ inline void Any::set_allocated_value(::std::string* value) {
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_google_2fprotobuf_2fany_2eproto__INCLUDED
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fany_2eproto
+13 -8
View File
@@ -120,17 +120,18 @@ option objc_class_prefix = "GPB";
// }
//
message Any {
// A URL/resource name whose content describes the type of the
// serialized protocol buffer message.
// 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
// 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).
//
// For URLs which use the scheme `http`, `https`, or no scheme, the
// following restrictions and interpretations apply:
// In practice, teams usually precompile into the binary all types that they
// expect it to use in the context of Any. However, for URLs which use the
// scheme `http`, `https`, or no scheme, one can optionally set up a type
// server that maps type URLs to message definitions as follows:
//
// * If no scheme is provided, `https` is assumed.
// * 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).
// * An HTTP GET on the URL must yield a [google.protobuf.Type][]
// value in binary format, or produce an error.
// * Applications are allowed to cache lookup results based on the
@@ -139,6 +140,10 @@ message Any {
// on changes to types. (Use versioned type names to manage
// breaking changes.)
//
// Note: this functionality is not currently available in the official
// protobuf release, and it is not used for type URLs beginning with
// type.googleapis.com.
//
// Schemes other than `http`, `https` (or the empty scheme) might be
// used with implementation specific semantics.
//
+110 -129
View File
@@ -7,7 +7,6 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
@@ -19,6 +18,17 @@
#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 {
@@ -39,18 +49,9 @@ class MixinDefaultTypeInternal {
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fapi_2eproto {
void InitDefaultsApiImpl() {
static void InitDefaultsApi() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
protobuf_google_2fprotobuf_2fsource_5fcontext_2eproto::InitDefaultsSourceContext();
protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
{
void* ptr = &::google::protobuf::_Api_default_instance_;
new (ptr) ::google::protobuf::Api();
@@ -59,20 +60,16 @@ void InitDefaultsApiImpl() {
::google::protobuf::Api::InitAsDefaultInstance();
}
void InitDefaultsApi() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsApiImpl);
}
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,}};
void InitDefaultsMethodImpl() {
static void InitDefaultsMethod() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
protobuf_google_2fprotobuf_2ftype_2eproto::InitDefaultsOption();
{
void* ptr = &::google::protobuf::_Method_default_instance_;
new (ptr) ::google::protobuf::Method();
@@ -81,19 +78,13 @@ void InitDefaultsMethodImpl() {
::google::protobuf::Method::InitAsDefaultInstance();
}
void InitDefaultsMethod() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMethodImpl);
}
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,}};
void InitDefaultsMixinImpl() {
static void InitDefaultsMixin() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
::google::protobuf::internal::InitProtobufDefaultsForceUnique();
#else
::google::protobuf::internal::InitProtobufDefaults();
#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
{
void* ptr = &::google::protobuf::_Mixin_default_instance_;
new (ptr) ::google::protobuf::Mixin();
@@ -102,9 +93,13 @@ void InitDefaultsMixinImpl() {
::google::protobuf::Mixin::InitAsDefaultInstance();
}
void InitDefaultsMixin() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsMixinImpl);
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];
@@ -156,15 +151,14 @@ static ::google::protobuf::Message const * const file_default_instances[] = {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
AssignDescriptors(
"google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets, factory,
"google/protobuf/api.proto", schemas, file_default_instances, TableStruct::offsets,
file_level_metadata, NULL, NULL);
}
void protobuf_AssignDescriptorsOnce() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
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;
@@ -205,8 +199,8 @@ void AddDescriptorsImpl() {
}
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
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 {
@@ -245,9 +239,8 @@ const int Api::kSyntaxFieldNumber;
Api::Api()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi();
}
::google::protobuf::internal::InitSCC(
&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base);
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Api)
}
@@ -256,8 +249,7 @@ Api::Api(const Api& from)
_internal_metadata_(NULL),
methods_(from.methods_),
options_(from.options_),
mixins_(from.mixins_),
_cached_size_(0) {
mixins_(from.mixins_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -282,7 +274,6 @@ void Api::SharedCtor() {
::memset(&source_context_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_));
_cached_size_ = 0;
}
Api::~Api() {
@@ -297,9 +288,7 @@ void Api::SharedDtor() {
}
void Api::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Api::descriptor() {
::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
@@ -307,17 +296,10 @@ const ::google::protobuf::Descriptor* Api::descriptor() {
}
const Api& Api::default_instance() {
::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApi();
::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Api.base);
return *internal_default_instance();
}
Api* Api::New(::google::protobuf::Arena* arena) const {
Api* n = new Api;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Api::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Api)
@@ -344,7 +326,7 @@ bool Api::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Api)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
::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)) {
@@ -368,7 +350,8 @@ bool Api::MergePartialFromCodedStream(
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()));
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_methods()));
} else {
goto handle_unusual;
}
@@ -379,7 +362,8 @@ bool Api::MergePartialFromCodedStream(
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()));
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
goto handle_unusual;
}
@@ -418,7 +402,8 @@ bool Api::MergePartialFromCodedStream(
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()));
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_mixins()));
} else {
goto handle_unusual;
}
@@ -480,14 +465,18 @@ void Api::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->methods_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, this->methods(static_cast<int>(i)), output);
2,
this->methods(static_cast<int>(i)),
output);
}
// repeated .google.protobuf.Option options = 3;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
3, this->options(static_cast<int>(i)), output);
3,
this->options(static_cast<int>(i)),
output);
}
// string version = 4;
@@ -503,14 +492,16 @@ void Api::SerializeWithCachedSizes(
// .google.protobuf.SourceContext source_context = 5;
if (this->has_source_context()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
5, *this->source_context_, output);
5, this->_internal_source_context(), output);
}
// repeated .google.protobuf.Mixin mixins = 6;
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->mixins_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6, this->mixins(static_cast<int>(i)), output);
6,
this->mixins(static_cast<int>(i)),
output);
}
// .google.protobuf.Syntax syntax = 7;
@@ -575,7 +566,7 @@ void Api::SerializeWithCachedSizes(
if (this->has_source_context()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageToArray(
5, *this->source_context_, deterministic, target);
5, this->_internal_source_context(), deterministic, target);
}
// repeated .google.protobuf.Mixin mixins = 6;
@@ -660,7 +651,7 @@ size_t Api::ByteSizeLong() const {
if (this->has_source_context()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSize(
*this->source_context_);
*source_context_);
}
// .google.protobuf.Syntax syntax = 7;
@@ -670,9 +661,7 @@ size_t Api::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
SetCachedSize(cached_size);
return total_size;
}
@@ -741,15 +730,16 @@ void Api::Swap(Api* other) {
}
void Api::InternalSwap(Api* other) {
using std::swap;
methods_.InternalSwap(&other->methods_);
options_.InternalSwap(&other->options_);
mixins_.InternalSwap(&other->mixins_);
name_.Swap(&other->name_);
version_.Swap(&other->version_);
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_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Api::GetMetadata() const {
@@ -777,17 +767,15 @@ const int Method::kSyntaxFieldNumber;
Method::Method()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
}
::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_),
_cached_size_(0) {
options_(from.options_) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -814,7 +802,6 @@ void Method::SharedCtor() {
::memset(&request_streaming_, 0, static_cast<size_t>(
reinterpret_cast<char*>(&syntax_) -
reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_));
_cached_size_ = 0;
}
Method::~Method() {
@@ -829,9 +816,7 @@ void Method::SharedDtor() {
}
void Method::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Method::descriptor() {
::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
@@ -839,17 +824,10 @@ const ::google::protobuf::Descriptor* Method::descriptor() {
}
const Method& Method::default_instance() {
::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethod();
::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Method.base);
return *internal_default_instance();
}
Method* Method::New(::google::protobuf::Arena* arena) const {
Method* n = new Method;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Method::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Method)
@@ -873,7 +851,7 @@ bool Method::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Method)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
::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)) {
@@ -957,7 +935,8 @@ bool Method::MergePartialFromCodedStream(
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()));
DO_(::google::protobuf::internal::WireFormatLite::ReadMessage(
input, add_options()));
} else {
goto handle_unusual;
}
@@ -1049,7 +1028,9 @@ void Method::SerializeWithCachedSizes(
for (unsigned int i = 0,
n = static_cast<unsigned int>(this->options_size()); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
6, this->options(static_cast<int>(i)), output);
6,
this->options(static_cast<int>(i)),
output);
}
// .google.protobuf.Syntax syntax = 7;
@@ -1195,9 +1176,7 @@ size_t Method::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
SetCachedSize(cached_size);
return total_size;
}
@@ -1271,15 +1250,17 @@ void Method::Swap(Method* other) {
}
void Method::InternalSwap(Method* other) {
using std::swap;
options_.InternalSwap(&other->options_);
name_.Swap(&other->name_);
request_type_url_.Swap(&other->request_type_url_);
response_type_url_.Swap(&other->response_type_url_);
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_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Method::GetMetadata() const {
@@ -1299,16 +1280,14 @@ const int Mixin::kRootFieldNumber;
Mixin::Mixin()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) {
::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
}
::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),
_cached_size_(0) {
_internal_metadata_(NULL) {
_internal_metadata_.MergeFrom(from._internal_metadata_);
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
if (from.name().size() > 0) {
@@ -1324,7 +1303,6 @@ Mixin::Mixin(const Mixin& from)
void Mixin::SharedCtor() {
name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
root_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_cached_size_ = 0;
}
Mixin::~Mixin() {
@@ -1338,9 +1316,7 @@ void Mixin::SharedDtor() {
}
void Mixin::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
_cached_size_.Set(size);
}
const ::google::protobuf::Descriptor* Mixin::descriptor() {
::protobuf_google_2fprotobuf_2fapi_2eproto::protobuf_AssignDescriptorsOnce();
@@ -1348,17 +1324,10 @@ const ::google::protobuf::Descriptor* Mixin::descriptor() {
}
const Mixin& Mixin::default_instance() {
::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixin();
::google::protobuf::internal::InitSCC(&protobuf_google_2fprotobuf_2fapi_2eproto::scc_info_Mixin.base);
return *internal_default_instance();
}
Mixin* Mixin::New(::google::protobuf::Arena* arena) const {
Mixin* n = new Mixin;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Mixin::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Mixin)
@@ -1377,7 +1346,7 @@ bool Mixin::MergePartialFromCodedStream(
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.Mixin)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u);
::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)) {
@@ -1527,9 +1496,7 @@ size_t Mixin::ByteSizeLong() const {
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
SetCachedSize(cached_size);
return total_size;
}
@@ -1589,10 +1556,11 @@ void Mixin::Swap(Mixin* other) {
}
void Mixin::InternalSwap(Mixin* other) {
using std::swap;
name_.Swap(&other->name_);
root_.Swap(&other->root_);
name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
root_.Swap(&other->root_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(),
GetArenaNoVirtual());
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Mixin::GetMetadata() const {
@@ -1604,5 +1572,18 @@ void Mixin::InternalSwap(Mixin* other) {
// @@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)
+122 -105
View File
@@ -1,19 +1,19 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/api.proto
#ifndef PROTOBUF_google_2fprotobuf_2fapi_2eproto__INCLUDED
#define PROTOBUF_google_2fprotobuf_2fapi_2eproto__INCLUDED
#ifndef PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
#define PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3005000
#if GOOGLE_PROTOBUF_VERSION < 3006000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#if 3006000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
@@ -24,6 +24,7 @@
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/inlined_string_field.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
@@ -32,6 +33,7 @@
#include <google/protobuf/source_context.pb.h>
#include <google/protobuf/type.pb.h>
// @@protoc_insertion_point(includes)
#define PROTOBUF_INTERNAL_EXPORT_protobuf_google_2fprotobuf_2fapi_2eproto LIBPROTOBUF_EXPORT
namespace protobuf_google_2fprotobuf_2fapi_2eproto {
// Internal implementation detail -- do not use these members.
@@ -44,17 +46,6 @@ struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::uint32 offsets[];
};
void LIBPROTOBUF_EXPORT AddDescriptors();
void LIBPROTOBUF_EXPORT InitDefaultsApiImpl();
void LIBPROTOBUF_EXPORT InitDefaultsApi();
void LIBPROTOBUF_EXPORT InitDefaultsMethodImpl();
void LIBPROTOBUF_EXPORT InitDefaultsMethod();
void LIBPROTOBUF_EXPORT InitDefaultsMixinImpl();
void LIBPROTOBUF_EXPORT InitDefaultsMixin();
inline void LIBPROTOBUF_EXPORT InitDefaults() {
InitDefaultsApi();
InitDefaultsMethod();
InitDefaultsMixin();
}
} // namespace protobuf_google_2fprotobuf_2fapi_2eproto
namespace google {
namespace protobuf {
@@ -71,6 +62,13 @@ LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_;
} // 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 {
// ===================================================================
@@ -108,7 +106,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
return reinterpret_cast<const Api*>(
&_Api_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
static constexpr int kIndexInFileMessages =
0;
void Swap(Api* other);
@@ -118,28 +116,33 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
// implements Message ----------------------------------------------
inline Api* New() const PROTOBUF_FINAL { return New(NULL); }
inline Api* New() const final {
return CreateMaybeMessage<Api>(NULL);
}
Api* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
Api* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<Api>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Api& from);
void MergeFrom(const Api& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const PROTOBUF_FINAL;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void SetCachedSize(int size) const final;
void InternalSwap(Api* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -150,7 +153,7 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -160,11 +163,11 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
int methods_size() const;
void clear_methods();
static const int kMethodsFieldNumber = 2;
const ::google::protobuf::Method& methods(int index) const;
::google::protobuf::Method* mutable_methods(int index);
::google::protobuf::Method* add_methods();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >*
mutable_methods();
const ::google::protobuf::Method& methods(int index) const;
::google::protobuf::Method* add_methods();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >&
methods() const;
@@ -172,11 +175,11 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
int options_size() const;
void clear_options();
static const int kOptionsFieldNumber = 3;
const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* mutable_options(int index);
::google::protobuf::Option* add_options();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
mutable_options();
const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* add_options();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
@@ -184,11 +187,11 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
int mixins_size() const;
void clear_mixins();
static const int kMixinsFieldNumber = 6;
const ::google::protobuf::Mixin& mixins(int index) const;
::google::protobuf::Mixin* mutable_mixins(int index);
::google::protobuf::Mixin* add_mixins();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >*
mutable_mixins();
const ::google::protobuf::Mixin& mixins(int index) const;
::google::protobuf::Mixin* add_mixins();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >&
mixins() const;
@@ -224,6 +227,9 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
bool has_source_context() const;
void clear_source_context();
static const int kSourceContextFieldNumber = 5;
private:
const ::google::protobuf::SourceContext& _internal_source_context() const;
public:
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* release_source_context();
::google::protobuf::SourceContext* mutable_source_context();
@@ -246,9 +252,8 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::internal::ArenaStringPtr version_;
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable int _cached_size_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApiImpl();
};
// -------------------------------------------------------------------
@@ -286,7 +291,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
return reinterpret_cast<const Method*>(
&_Method_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
static constexpr int kIndexInFileMessages =
1;
void Swap(Method* other);
@@ -296,28 +301,33 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
// implements Message ----------------------------------------------
inline Method* New() const PROTOBUF_FINAL { return New(NULL); }
inline Method* New() const final {
return CreateMaybeMessage<Method>(NULL);
}
Method* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
Method* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<Method>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Method& from);
void MergeFrom(const Method& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const PROTOBUF_FINAL;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void SetCachedSize(int size) const final;
void InternalSwap(Method* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -328,7 +338,7 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -338,11 +348,11 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
int options_size() const;
void clear_options();
static const int kOptionsFieldNumber = 6;
const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* mutable_options(int index);
::google::protobuf::Option* add_options();
::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >*
mutable_options();
const ::google::protobuf::Option& options(int index) const;
::google::protobuf::Option* add_options();
const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
options() const;
@@ -417,9 +427,8 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
bool request_streaming_;
bool response_streaming_;
int syntax_;
mutable int _cached_size_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethodImpl();
};
// -------------------------------------------------------------------
@@ -457,7 +466,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
return reinterpret_cast<const Mixin*>(
&_Mixin_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
static constexpr int kIndexInFileMessages =
2;
void Swap(Mixin* other);
@@ -467,28 +476,33 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
// implements Message ----------------------------------------------
inline Mixin* New() const PROTOBUF_FINAL { return New(NULL); }
inline Mixin* New() const final {
return CreateMaybeMessage<Mixin>(NULL);
}
Mixin* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
Mixin* New(::google::protobuf::Arena* arena) const final {
return CreateMaybeMessage<Mixin>(arena);
}
void CopyFrom(const ::google::protobuf::Message& from) final;
void MergeFrom(const ::google::protobuf::Message& from) final;
void CopyFrom(const Mixin& from);
void MergeFrom(const Mixin& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
void Clear() final;
bool IsInitialized() const final;
size_t ByteSizeLong() const PROTOBUF_FINAL;
size_t ByteSizeLong() const final;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
::google::protobuf::io::CodedInputStream* input) final;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
::google::protobuf::io::CodedOutputStream* output) const final;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
bool deterministic, ::google::protobuf::uint8* target) const final;
int GetCachedSize() const final { return _cached_size_.Get(); }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const PROTOBUF_FINAL;
void SetCachedSize(int size) const final;
void InternalSwap(Mixin* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
@@ -499,7 +513,7 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
}
public:
::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;
::google::protobuf::Metadata GetMetadata() const final;
// nested types ----------------------------------------------------
@@ -539,9 +553,8 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr root_;
mutable int _cached_size_;
mutable ::google::protobuf::internal::CachedSize _cached_size_;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixinImpl();
};
// ===================================================================
@@ -614,23 +627,23 @@ inline int Api::methods_size() const {
inline void Api::clear_methods() {
methods_.Clear();
}
inline const ::google::protobuf::Method& Api::methods(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.methods)
return methods_.Get(index);
}
inline ::google::protobuf::Method* Api::mutable_methods(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.methods)
return methods_.Mutable(index);
}
inline ::google::protobuf::Method* Api::add_methods() {
// @@protoc_insertion_point(field_add:google.protobuf.Api.methods)
return methods_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::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)
return methods_.Get(index);
}
inline ::google::protobuf::Method* Api::add_methods() {
// @@protoc_insertion_point(field_add:google.protobuf.Api.methods)
return methods_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Method >&
Api::methods() const {
// @@protoc_insertion_point(field_list:google.protobuf.Api.methods)
@@ -641,23 +654,23 @@ Api::methods() const {
inline int Api::options_size() const {
return options_.size();
}
inline const ::google::protobuf::Option& Api::options(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.options)
return options_.Get(index);
}
inline ::google::protobuf::Option* Api::mutable_options(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.options)
return options_.Mutable(index);
}
inline ::google::protobuf::Option* Api::add_options() {
// @@protoc_insertion_point(field_add:google.protobuf.Api.options)
return options_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::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)
return options_.Get(index);
}
inline ::google::protobuf::Option* Api::add_options() {
// @@protoc_insertion_point(field_add:google.protobuf.Api.options)
return options_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
Api::options() const {
// @@protoc_insertion_point(field_list:google.protobuf.Api.options)
@@ -721,6 +734,9 @@ inline void Api::set_allocated_version(::std::string* version) {
inline bool Api::has_source_context() const {
return this != internal_default_instance() && source_context_ != NULL;
}
inline const ::google::protobuf::SourceContext& Api::_internal_source_context() const {
return *source_context_;
}
inline const ::google::protobuf::SourceContext& Api::source_context() const {
const ::google::protobuf::SourceContext* p = source_context_;
// @@protoc_insertion_point(field_get:google.protobuf.Api.source_context)
@@ -737,7 +753,8 @@ inline ::google::protobuf::SourceContext* Api::release_source_context() {
inline ::google::protobuf::SourceContext* Api::mutable_source_context() {
if (source_context_ == NULL) {
source_context_ = new ::google::protobuf::SourceContext;
auto* p = CreateMaybeMessage<::google::protobuf::SourceContext>(GetArenaNoVirtual());
source_context_ = p;
}
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context)
return source_context_;
@@ -768,23 +785,23 @@ inline int Api::mixins_size() const {
inline void Api::clear_mixins() {
mixins_.Clear();
}
inline const ::google::protobuf::Mixin& Api::mixins(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.mixins)
return mixins_.Get(index);
}
inline ::google::protobuf::Mixin* Api::mutable_mixins(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.mixins)
return mixins_.Mutable(index);
}
inline ::google::protobuf::Mixin* Api::add_mixins() {
// @@protoc_insertion_point(field_add:google.protobuf.Api.mixins)
return mixins_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::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)
return mixins_.Get(index);
}
inline ::google::protobuf::Mixin* Api::add_mixins() {
// @@protoc_insertion_point(field_add:google.protobuf.Api.mixins)
return mixins_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Mixin >&
Api::mixins() const {
// @@protoc_insertion_point(field_list:google.protobuf.Api.mixins)
@@ -1000,23 +1017,23 @@ inline void Method::set_response_streaming(bool value) {
inline int Method::options_size() const {
return options_.size();
}
inline const ::google::protobuf::Option& Method::options(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.options)
return options_.Get(index);
}
inline ::google::protobuf::Option* Method::mutable_options(int index) {
// @@protoc_insertion_point(field_mutable:google.protobuf.Method.options)
return options_.Mutable(index);
}
inline ::google::protobuf::Option* Method::add_options() {
// @@protoc_insertion_point(field_add:google.protobuf.Method.options)
return options_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::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)
return options_.Get(index);
}
inline ::google::protobuf::Option* Method::add_options() {
// @@protoc_insertion_point(field_add:google.protobuf.Method.options)
return options_.Add();
}
inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Option >&
Method::options() const {
// @@protoc_insertion_point(field_list:google.protobuf.Method.options)
@@ -1162,4 +1179,4 @@ inline void Mixin::set_allocated_root(::std::string* root) {
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_google_2fprotobuf_2fapi_2eproto__INCLUDED
#endif // PROTOBUF_INCLUDED_google_2fprotobuf_2fapi_2eproto
+215 -185
View File
@@ -48,7 +48,7 @@ namespace protobuf {
namespace internal {
google::protobuf::internal::SequenceNumber ArenaImpl::lifecycle_id_generator_;
std::atomic<int64> ArenaImpl::lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
ArenaImpl::ThreadCache& ArenaImpl::thread_cache() {
static internal::ThreadLocalStorage<ThreadCache>* thread_cache_ =
@@ -65,24 +65,25 @@ GOOGLE_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1, NULL}
#endif
void ArenaImpl::Init() {
lifecycle_id_ = lifecycle_id_generator_.GetNext();
google::protobuf::internal::NoBarrier_Store(&hint_, 0);
google::protobuf::internal::NoBarrier_Store(&threads_, 0);
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.
InitBlock(initial_block_, &thread_cache(), options_.initial_block_size);
ThreadInfo* info = NewThreadInfo(initial_block_);
info->next = NULL;
google::protobuf::internal::NoBarrier_Store(&threads_,
reinterpret_cast<google::protobuf::internal::AtomicWord>(info));
google::protobuf::internal::NoBarrier_Store(&space_allocated_,
options_.initial_block_size);
CacheBlock(initial_block_);
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 {
google::protobuf::internal::NoBarrier_Store(&space_allocated_, 0);
space_allocated_.store(0, std::memory_order_relaxed);
}
}
@@ -103,164 +104,158 @@ uint64 ArenaImpl::Reset() {
return space_allocated;
}
ArenaImpl::Block* ArenaImpl::NewBlock(void* me, Block* my_last_block,
size_t min_bytes) {
ArenaImpl::Block* ArenaImpl::NewBlock(Block* last_block, size_t min_bytes) {
size_t size;
if (my_last_block != NULL) {
if (last_block) {
// Double the current block size, up to a limit.
size = std::min(2 * my_last_block->size, options_.max_block_size);
size = std::min(2 * last_block->size(), options_.max_block_size);
} else {
size = options_.start_block_size;
}
// Verify that min_bytes + kHeaderSize won't overflow.
GOOGLE_CHECK_LE(min_bytes, std::numeric_limits<size_t>::max() - kHeaderSize);
size = std::max(size, kHeaderSize + min_bytes);
// Verify that min_bytes + kBlockHeaderSize won't overflow.
GOOGLE_CHECK_LE(min_bytes, std::numeric_limits<size_t>::max() - kBlockHeaderSize);
size = std::max(size, kBlockHeaderSize + min_bytes);
Block* b = reinterpret_cast<Block*>(options_.block_alloc(size));
InitBlock(b, me, size);
google::protobuf::internal::NoBarrier_AtomicIncrement(&space_allocated_, size);
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;
}
void ArenaImpl::InitBlock(Block* b, void *me, size_t size) {
b->pos = kHeaderSize;
b->size = size;
b->owner = me;
b->next = NULL;
#ifdef ADDRESS_SANITIZER
// Poison the rest of the block for ASAN. It was unpoisoned by the underlying
// malloc but it's not yet usable until we return it as part of an allocation.
ASAN_POISON_MEMORY_REGION(
reinterpret_cast<char*>(b) + b->pos, b->size - b->pos);
#endif // ADDRESS_SANITIZER
}
ArenaImpl::Block::Block(size_t size, Block* next)
: next_(next), pos_(kBlockHeaderSize), size_(size) {}
ArenaImpl::CleanupChunk* ArenaImpl::ExpandCleanupList(CleanupChunk* cleanup,
Block* b) {
size_t size = cleanup ? cleanup->size * 2 : kMinCleanupListElements;
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));
if (b->avail() < bytes) {
b = GetBlock(bytes);
}
CleanupChunk* list =
reinterpret_cast<CleanupChunk*>(AllocFromBlock(b, bytes));
list->next = b->thread_info->cleanup;
CleanupChunk* list = reinterpret_cast<CleanupChunk*>(AllocateAligned(bytes));
list->next = cleanup_;
list->size = size;
list->len = 0;
b->thread_info->cleanup = list;
return list;
}
inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void ArenaImpl::AddCleanupInBlock(
Block* b, void* elem, void (*func)(void*)) {
CleanupChunk* cleanup = b->thread_info->cleanup;
if (cleanup == NULL || cleanup->len == cleanup->size) {
cleanup = ExpandCleanupList(cleanup, b);
}
cleanup_ = list;
cleanup_ptr_ = &list->nodes[0];
cleanup_limit_ = &list->nodes[size];
CleanupNode* node = &cleanup->nodes[cleanup->len++];
node->elem = elem;
node->cleanup = func;
}
void ArenaImpl::AddCleanup(void* elem, void (*cleanup)(void*)) {
return AddCleanupInBlock(GetBlock(0), elem, cleanup);
AddCleanup(elem, cleanup);
}
GOOGLE_PROTOBUF_ATTRIBUTE_FUNC_ALIGN(32)
void* ArenaImpl::AllocateAligned(size_t n) {
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
return AllocFromBlock(GetBlock(n), 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*)) {
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
SerialArena* arena;
if (GOOGLE_PREDICT_TRUE(GetSerialArenaFast(&arena))) {
return arena->AllocateAlignedAndAddCleanup(n, cleanup);
} else {
return AllocateAlignedAndAddCleanupFallback(n, cleanup);
}
}
Block* b = GetBlock(n);
void* mem = AllocFromBlock(b, n);
AddCleanupInBlock(b, mem, cleanup);
return mem;
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
ArenaImpl::Block* ArenaImpl::GetBlock(size_t n) {
Block* my_block = NULL;
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 (tc->last_lifecycle_id_seen == lifecycle_id_) {
my_block = tc->last_block_used_;
if (my_block->avail() >= n) {
return my_block;
}
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 block on this arena.
// This fast path optimizes the case where a single thread uses multiple
// arenas.
Block* b = reinterpret_cast<Block*>(google::protobuf::internal::Acquire_Load(&hint_));
if (b != NULL && b->owner == tc) {
my_block = b;
if (my_block->avail() >= n) {
return my_block;
}
// 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 GetBlockSlow(tc, my_block, n);
return false;
}
inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void* ArenaImpl::AllocFromBlock(Block* b, size_t n) {
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(b->pos), b->pos); // Must be already aligned.
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
GOOGLE_DCHECK_GE(b->avail(), n);
size_t p = b->pos;
b->pos = p + n;
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_UNPOISON_MEMORY_REGION(reinterpret_cast<char*>(b) + p, n);
ASAN_POISON_MEMORY_REGION(ptr_, limit_ - ptr_);
#endif // ADDRESS_SANITIZER
return reinterpret_cast<char*>(b) + p;
}
ArenaImpl::Block* ArenaImpl::GetBlockSlow(void* me, Block* my_full_block,
size_t n) {
ThreadInfo* info =
my_full_block ? my_full_block->thread_info : GetThreadInfo(me, n);
GOOGLE_DCHECK(info != NULL);
Block* b = info->head;
if (b->avail() < n) {
Block* new_b = NewBlock(me, b, n);
new_b->thread_info = info;
new_b->next = b;
info->head = new_b;
b = new_b;
}
CacheBlock(b);
return b;
return AllocateAligned(n);
}
uint64 ArenaImpl::SpaceAllocated() const {
return google::protobuf::internal::NoBarrier_Load(&space_allocated_);
return space_allocated_.load(std::memory_order_relaxed);
}
uint64 ArenaImpl::SpaceUsed() const {
ThreadInfo* info =
reinterpret_cast<ThreadInfo*>(google::protobuf::internal::Acquire_Load(&threads_));
SerialArena* serial = threads_.load(std::memory_order_acquire);
uint64 space_used = 0;
for ( ; info; info = info->next) {
// Remove the overhead of the ThreadInfo itself.
space_used -= sizeof(ThreadInfo);
for (Block* b = info->head; b; b = b->next) {
space_used += (b->pos - kHeaderSize);
}
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;
}
@@ -268,30 +263,44 @@ 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.
ThreadInfo* info =
reinterpret_cast<ThreadInfo*>(google::protobuf::internal::NoBarrier_Load(&threads_));
SerialArena* serial = threads_.load(std::memory_order_relaxed);
while (info) {
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.
ThreadInfo* next_info = info->next;
for (Block* b = info->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);
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(reinterpret_cast<char*>(b), b->size);
// 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_) {
options_.block_dealloc(b, b->size);
}
b = next_block;
if (b != initial_block) {
block_dealloc(b, b->size());
}
info = next_info;
b = next_block;
}
return space_allocated;
@@ -300,63 +309,84 @@ uint64 ArenaImpl::FreeBlocks() {
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.
ThreadInfo* info =
reinterpret_cast<ThreadInfo*>(google::protobuf::internal::NoBarrier_Load(&threads_));
SerialArena* serial = threads_.load(std::memory_order_relaxed);
for ( ; info; info = info->next) {
CleanupChunk* list = info->cleanup;
while (list) {
size_t n = list->len;
CleanupNode* node = &list->nodes[list->len - 1];
for (size_t i = 0; i < n; i++, node--) {
node->cleanup(node->elem);
}
list = list->next;
}
for ( ; serial; serial = serial->next()) {
serial->CleanupList();
}
}
ArenaImpl::ThreadInfo* ArenaImpl::NewThreadInfo(Block* b) {
GOOGLE_DCHECK(FindThreadInfo(b->owner) == NULL);
ThreadInfo* info =
reinterpret_cast<ThreadInfo*>(AllocFromBlock(b, sizeof(ThreadInfo)));
b->thread_info = info;
info->owner = b->owner;
info->head = b;
info->cleanup = NULL;
return info;
void ArenaImpl::SerialArena::CleanupList() {
if (cleanup_ != NULL) {
CleanupListFallback();
}
}
ArenaImpl::ThreadInfo* ArenaImpl::FindThreadInfo(void* me) {
ThreadInfo* info =
reinterpret_cast<ThreadInfo*>(google::protobuf::internal::Acquire_Load(&threads_));
for ( ; info; info = info->next) {
if (info->owner == me) {
return info;
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<SerialArena*>(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;
}
}
return NULL;
}
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);
ArenaImpl::ThreadInfo* ArenaImpl::GetThreadInfo(void* me, size_t n) {
ThreadInfo* info = FindThreadInfo(me);
if (!info) {
// This thread doesn't have any ThreadInfo, which also means it doesn't have
// any blocks yet. So we'll allocate its first block now.
Block* b = NewBlock(me, NULL, sizeof(ThreadInfo) + n);
info = NewThreadInfo(b);
google::protobuf::internal::AtomicWord head;
SerialArena* head = threads_.load(std::memory_order_relaxed);
do {
head = google::protobuf::internal::NoBarrier_Load(&threads_);
info->next = reinterpret_cast<ThreadInfo*>(head);
} while (google::protobuf::internal::Release_CompareAndSwap(
&threads_, head, reinterpret_cast<google::protobuf::internal::AtomicWord>(info)) != head);
serial->set_next(head);
} while (!threads_.compare_exchange_weak(
head, serial, std::memory_order_release, std::memory_order_relaxed));
}
return info;
CacheSerialArena(serial);
return serial;
}
} // namespace internal
+204 -435
View File
@@ -37,10 +37,7 @@
#ifdef max
#undef max // Visual Studio defines this macro
#endif
#if LANG_CXX11
#include <google/protobuf/stubs/type_traits.h>
#endif
#if defined(_MSC_VER) && !_HAS_EXCEPTIONS
#if defined(_MSC_VER) && !defined(_LIBCPP_STD_VER) && !_HAS_EXCEPTIONS
// Work around bugs in MSVC <typeinfo> header when _HAS_EXCEPTIONS=0.
#include <exception>
#include <typeinfo>
@@ -53,25 +50,48 @@ using type_info = ::type_info;
#include <google/protobuf/arena_impl.h>
#include <google/protobuf/stubs/port.h>
#include <type_traits>
namespace google {
namespace protobuf {
class Arena; // defined below
class Message; // message.h
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 MessageLite;
namespace arena_metrics {
void EnableArenaMetrics(::google::protobuf::ArenaOptions* options);
} // namespace arena_metrics
namespace internal {
struct ArenaStringPtr; // arenastring.h
class LazyField; // lazy_field.h
template<typename Type>
class GenericTypeHandler; // repeated_field.h
struct ArenaStringPtr; // defined in arenastring.h
class LazyField; // defined in lazy_field.h
template <typename Type>
class GenericTypeHandler; // defined in repeated_field.h
// Templated cleanup methods.
template<typename T> void arena_destruct_object(void* object) {
template <typename T>
void arena_destruct_object(void* object) {
reinterpret_cast<T*>(object)->~T();
}
template<typename T> void arena_delete_object(void* object) {
template <typename T>
void arena_delete_object(void* object) {
delete reinterpret_cast<T*>(object);
}
inline void arena_free(void* object, size_t size) {
@@ -117,6 +137,20 @@ struct ArenaOptions {
// from the arena. By default, it contains a ptr to a wrapper function that
// calls free.
void (*block_dealloc)(void*, size_t);
ArenaOptions()
: start_block_size(kDefaultStartBlockSize),
max_block_size(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) {}
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.
@@ -136,25 +170,17 @@ struct ArenaOptions {
// 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);
uint64 alloc_size, void* cookie);
ArenaOptions()
: start_block_size(kDefaultStartBlockSize),
max_block_size(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) {}
private:
// 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;
static const size_t kDefaultMaxBlockSize = 8192;
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
@@ -229,14 +255,15 @@ 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::kHeaderSize;
static const size_t kBlockOverhead = internal::ArenaImpl::kBlockHeaderSize +
internal::ArenaImpl::kSerialArenaSize;
// Default constructor with sensible default options, tuned for average
// use-cases.
Arena() : impl_(ArenaOptions()) { Init(ArenaOptions()); }
~Arena() {
if (on_arena_reset_ != NULL || on_arena_destruction_ != NULL) {
if (hooks_cookie_) {
CallDestructorHooks();
}
}
@@ -263,69 +290,16 @@ class LIBPROTOBUF_EXPORT Arena {
//
// This function also accepts any type T that satisfies the arena message
// allocation protocol, documented above.
#if LANG_CXX11
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage(
::google::protobuf::Arena* arena, Args&&... args) {
Arena* arena, Args&&... args) {
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
if (arena == NULL) {
return new T(NULL, std::forward<Args>(args)...);
} else {
return arena->CreateMessageInternal<T>(std::forward<Args>(args)...);
}
}
#endif
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMessage(::google::protobuf::Arena* arena) {
#if LANG_CXX11
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
#endif
if (arena == NULL) {
return new T;
} else {
return arena->CreateMessageInternal<T>();
}
}
// One-argument form of CreateMessage. This is useful for constructing objects
// that implement the arena message construction protocol described above but
// take additional constructor arguments.
template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMessage(::google::protobuf::Arena* arena, const Arg& arg) {
#if LANG_CXX11
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
#endif
if (arena == NULL) {
return new T(NULL, arg);
} else {
return arena->CreateMessageInternal<T>(arg);
}
}
// Two-argument form of CreateMessage. This is useful for constructing objects
// that implement the arena message construction protocol described above but
// take additional constructor arguments.
template <typename T, typename Arg1, typename Arg2>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMessage(::google::protobuf::Arena* arena,
const Arg1& arg1,
const Arg2& arg2) {
#if LANG_CXX11
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
#endif
if (arena == NULL) {
return new T(NULL, arg1, arg2);
} else {
return arena->CreateMessageInternal<T>(arg1, arg2);
}
// 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<T>(arena, std::forward<Args>(args)...);
}
// API to create any objects on the arena. Note that only the object will
@@ -343,152 +317,11 @@ class LIBPROTOBUF_EXPORT Arena {
// (unless the destructor is trivial). Hence, from T's point of view, it is as
// if the object were allocated on the heap (except that the underlying memory
// is obtained from the arena).
#if LANG_CXX11
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena, Args&&... args) {
if (arena == NULL) {
return new T(std::forward<Args>(args)...);
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
std::forward<Args>(args)...);
}
}
#endif
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena) {
if (arena == NULL) {
return new T();
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value);
}
}
// Version of the above with one constructor argument for the created object.
template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena, const Arg& arg) {
if (arena == NULL) {
return new T(arg);
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
arg);
}
}
// Version of the above with two constructor arguments for the created object.
template <typename T, typename Arg1, typename Arg2>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena, const Arg1& arg1, const Arg2& arg2) {
if (arena == NULL) {
return new T(arg1, arg2);
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
arg1, arg2);
}
}
// Version of the above with three constructor arguments for the created
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3) {
if (arena == NULL) {
return new T(arg1, arg2, arg3);
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
arg1, arg2, arg3);
}
}
// Version of the above with four constructor arguments for the created
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena,
const Arg1& arg1, const Arg2& arg2,
const Arg3& arg3, const Arg4& arg4) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4);
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
arg1, arg2, arg3, arg4);
}
}
// Version of the above with five constructor arguments for the created
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena,
const Arg1& arg1, const Arg2& arg2,
const Arg3& arg3, const Arg4& arg4,
const Arg5& arg5) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4, arg5);
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
arg1, arg2, arg3, arg4, arg5);
}
}
// Version of the above with six constructor arguments for the created
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena,
const Arg1& arg1, const Arg2& arg2,
const Arg3& arg3, const Arg4& arg4,
const Arg5& arg5, const Arg6& arg6) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4, arg5, arg6);
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
arg1, arg2, arg3, arg4, arg5, arg6);
}
}
// Version of the above with seven constructor arguments for the created
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena,
const Arg1& arg1, const Arg2& arg2,
const Arg3& arg3, const Arg4& arg4,
const Arg5& arg5, const Arg6& arg6,
const Arg7& arg7) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
} else {
return arena->CreateInternal<T>(google::protobuf::internal::has_trivial_destructor<T>::value,
arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
}
// Version of the above with eight constructor arguments for the created
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7,
typename Arg8>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena,
const Arg1& arg1, const Arg2& arg2,
const Arg3& arg3, const Arg4& arg4,
const Arg5& arg5, const Arg6& arg6,
const Arg7& arg7, const Arg8& arg8) {
if (arena == NULL) {
return new T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
} else {
return arena->CreateInternal<T>(
google::protobuf::internal::has_trivial_destructor<T>::value,
arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* Create(Arena* arena,
Args&&... args) {
return CreateNoMessage<T>(arena, is_arena_constructable<T>(),
std::forward<Args>(args)...);
}
// Create an array of object type T on the arena *without* invoking the
@@ -497,10 +330,14 @@ class LIBPROTOBUF_EXPORT Arena {
// To ensure safe uses, this function checks at compile time
// (when compiled as C++11) that T is trivially default-constructible and
// trivially destructible.
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateArray(::google::protobuf::Arena* arena, size_t num_elements) {
GOOGLE_CHECK_LE(num_elements,
std::numeric_limits<size_t>::max() / sizeof(T))
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateArray(
Arena* arena, size_t num_elements) {
static_assert(std::is_pod<T>::value,
"CreateArray requires a trivially constructible type");
static_assert(std::is_trivially_destructible<T>::value,
"CreateArray requires a trivially destructible type");
GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::max() / sizeof(T))
<< "Requested size is too large to fit into size_t.";
if (arena == NULL) {
return static_cast<T*>(::operator new[](num_elements * sizeof(T)));
@@ -522,6 +359,7 @@ class LIBPROTOBUF_EXPORT Arena {
//
// Combines SpaceAllocated and SpaceUsed. Returns a pair of
// <space_allocated, space_used>.
PROTOBUF_RUNTIME_DEPRECATED("Please use SpaceAllocated() and SpaceUsed()")
std::pair<uint64, uint64> SpaceAllocatedAndUsed() const {
return std::make_pair(SpaceAllocated(), SpaceUsed());
}
@@ -541,9 +379,9 @@ class LIBPROTOBUF_EXPORT Arena {
// Adds |object| to a list of heap-allocated objects to be freed with |delete|
// when the arena is destroyed or reset.
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void Own(T* object) {
OwnInternal(object, google::protobuf::internal::is_convertible<T*, ::google::protobuf::Message*>());
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void Own(T* object) {
OwnInternal(object, std::is_convertible<T*, Message*>());
}
// Adds |object| to a list of objects whose destructors will be manually
@@ -551,8 +389,8 @@ class LIBPROTOBUF_EXPORT Arena {
// that it does not free the underlying memory with |delete|; hence, it is
// normally only used for objects that are placement-newed into
// arena-allocated memory.
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void OwnDestructor(T* object) {
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnDestructor(T* object) {
if (object != NULL) {
impl_.AddCleanup(object, &internal::arena_destruct_object<T>);
}
@@ -571,8 +409,9 @@ class LIBPROTOBUF_EXPORT Arena {
// 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.
template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArena(const T* value) {
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArena(
const T* value) {
return GetArenaInternal(value, is_arena_constructable<T>());
}
@@ -583,60 +422,92 @@ class LIBPROTOBUF_EXPORT Arena {
template <typename U>
static double DestructorSkippable(...);
typedef google::protobuf::internal::integral_constant<
typedef std::integral_constant<
bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) ==
sizeof(char) ||
google::protobuf::internal::has_trivial_destructor<T>::value>
std::is_trivially_destructible<T>::value>
is_destructor_skippable;
template<typename U>
template <typename U>
static char ArenaConstructable(
const typename U::InternalArenaConstructable_*);
template<typename U>
template <typename U>
static double ArenaConstructable(...);
typedef google::protobuf::internal::integral_constant<bool, sizeof(ArenaConstructable<T>(
static_cast<const T*>(0))) ==
sizeof(char)>
typedef std::integral_constant<bool, sizeof(ArenaConstructable<T>(
static_cast<const T*>(0))) ==
sizeof(char)>
is_arena_constructable;
#if LANG_CXX11
template <typename... Args>
static T* Construct(void* ptr, Args&&... args) {
return new (ptr) T(std::forward<Args>(args)...);
}
#else
template <typename Arg1>
static T* Construct(void* ptr, const Arg1& arg1) {
return new (ptr) T(arg1);
}
template <typename Arg1, typename Arg2>
static T* Construct(void* ptr, const Arg1& arg1, const Arg2& arg2) {
return new (ptr) T(arg1, arg2);
}
template <typename Arg1, typename Arg2, typename Arg3>
static T* Construct(void* ptr, const Arg1& arg1,
const Arg2& arg2, const Arg3& arg3) {
return new (ptr) T(arg1, arg2, arg3);
}
#endif // LANG_CXX11
static Arena* GetArena(const T* p) { return p->GetArenaNoVirtual(); }
friend class Arena;
};
// Helper typetrait that indicates support for arenas in a type T at compile
// Helper typetraits that indicates support for arenas in a type T at compile
// time. This is public only to allow construction of higher-level templated
// utilities. is_arena_constructable<T>::value is true if the message type T
// has arena support enabled, and false otherwise.
// utilities.
//
// is_arena_constructable<T>::value is true if the message type T has arena
// support enabled, and false otherwise.
//
// is_destructor_skippable<T>::value is true if the message type T has told
// the arena that it is safe to skip the destructor, and false otherwise.
//
// This is inside Arena because only Arena has the friend relationships
// necessary to see the underlying generated code traits.
template <typename T>
struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {};
template <typename T>
struct is_destructor_skippable : InternalHelper<T>::is_destructor_skippable {
};
private:
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal(
Arena* arena, Args&&... args) {
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
if (arena == NULL) {
return new T(nullptr, std::forward<Args>(args)...);
} else {
return arena->DoCreateMessage<T>(std::forward<Args>(args)...);
}
}
// This specialization for no arguments is necessary, because its behavior is
// slightly different. When the arena pointer is nullptr, it calls T()
// instead of T(nullptr).
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessageInternal(
Arena* arena) {
static_assert(
InternalHelper<T>::is_arena_constructable::value,
"CreateMessage can only construct types that are ArenaConstructable");
if (arena == NULL) {
return new T();
} else {
return arena->DoCreateMessage<T>();
}
}
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateInternal(
Arena* arena, Args&&... args) {
if (arena == NULL) {
return new T(std::forward<Args>(args)...);
} else {
return arena->DoCreate<T>(std::is_trivially_destructible<T>::value,
std::forward<Args>(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 {
@@ -648,8 +519,9 @@ class LIBPROTOBUF_EXPORT Arena {
// 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<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void* AllocateInternal(bool skip_explicit_ownership) {
template <typename T>
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);
// Monitor allocation if needed.
@@ -666,27 +538,49 @@ class LIBPROTOBUF_EXPORT Arena {
// as it can cause confusing API usages, and end up having double free in
// user code. These are used only internally from LazyField and Repeated
// fields, since they are designed to work in all mode combinations.
template <typename Msg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static Msg* CreateMaybeMessage(Arena* arena, google::protobuf::internal::true_type) {
return CreateMessage<Msg>(arena);
template <typename Msg, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Msg* DoCreateMaybeMessage(
Arena* arena, std::true_type, Args&&... args) {
return CreateMessageInternal<Msg>(arena, std::forward<Args>(args)...);
}
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMaybeMessage(Arena* arena, google::protobuf::internal::false_type) {
return Create<T>(arena);
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* DoCreateMaybeMessage(
Arena* arena, std::false_type, Args&&... args) {
return CreateInternal<T>(arena, std::forward<Args>(args)...);
}
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMaybeMessage(Arena* arena) {
return CreateMaybeMessage<T>(arena, is_arena_constructable<T>());
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMaybeMessage(
Arena* arena, Args&&... args) {
return DoCreateMaybeMessage<T>(arena, is_arena_constructable<T>(),
std::forward<Args>(args)...);
}
template <typename T, typename... Args>
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<T>(arena, std::forward<Args>(args)...);
}
template <typename T, typename... Args>
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<T>(arena, std::forward<Args>(args)...);
}
// Just allocate the required size for the given type assuming the
// type has a trivial constructor.
template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternalRawArray(size_t num_elements) {
GOOGLE_CHECK_LE(num_elements,
std::numeric_limits<size_t>::max() / sizeof(T))
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateInternalRawArray(
size_t num_elements) {
GOOGLE_CHECK_LE(num_elements, std::numeric_limits<size_t>::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.
@@ -694,143 +588,18 @@ class LIBPROTOBUF_EXPORT Arena {
return static_cast<T*>(impl_.AllocateAligned(n));
}
#if LANG_CXX11
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership, Args&&... args) {
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreate(
bool skip_explicit_ownership, Args&&... args) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(std::forward<Args>(args)...);
}
#else
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership) {
return new (AllocateInternal<T>(skip_explicit_ownership)) T();
}
template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership, const Arg& arg) {
return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg);
}
template <typename T, typename Arg1, typename Arg2>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2) {
return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg1, arg2);
}
template <typename T, typename Arg1, typename Arg2, typename Arg3>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3);
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3,
const Arg4& arg4) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4);
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3,
const Arg4& arg4,
const Arg5& arg5) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4, arg5);
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3,
const Arg4& arg4,
const Arg5& arg5,
const Arg6& arg6) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4, arg5, arg6);
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3,
const Arg4& arg4,
const Arg5& arg5,
const Arg6& arg6,
const Arg7& arg7) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7,
typename Arg8>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3,
const Arg4& arg4,
const Arg5& arg5,
const Arg6& arg6,
const Arg7& arg7,
const Arg8& arg8) {
return new (AllocateInternal<T>(skip_explicit_ownership))
T(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
}
#endif
#if LANG_CXX11
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal(
Args&&... args) {
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* DoCreateMessage(Args&&... args) {
return InternalHelper<T>::Construct(
AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
this, std::forward<Args>(args)...);
}
#endif
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal() {
return InternalHelper<T>::Construct(
AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
this);
}
template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateMessageInternal(const Arg& arg) {
return InternalHelper<T>::Construct(
AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
this, arg);
}
template <typename T, typename Arg1, typename Arg2>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateMessageInternal(const Arg1& arg1, const Arg2& arg2) {
return InternalHelper<T>::Construct(
AllocateInternal<T>(InternalHelper<T>::is_destructor_skippable::value),
this, arg1, arg2);
}
// CreateInArenaStorage is used to implement map field. Without it,
// google::protobuf::Map need to call generated message's protected arena constructor,
@@ -845,22 +614,22 @@ class LIBPROTOBUF_EXPORT Arena {
}
template <typename T>
static void CreateInArenaStorageInternal(
T* ptr, Arena* arena, google::protobuf::internal::true_type) {
static void CreateInArenaStorageInternal(T* ptr, Arena* arena,
std::true_type) {
InternalHelper<T>::Construct(ptr, arena);
}
template <typename T>
static void CreateInArenaStorageInternal(
T* ptr, Arena* /* arena */, google::protobuf::internal::false_type) {
static void CreateInArenaStorageInternal(T* ptr, Arena* /* arena */,
std::false_type) {
new (ptr) T();
}
template <typename T>
static void RegisterDestructorInternal(
T* /* ptr */, Arena* /* arena */, google::protobuf::internal::true_type) {}
static void RegisterDestructorInternal(T* /* ptr */, Arena* /* arena */,
std::true_type) {}
template <typename T>
static void RegisterDestructorInternal(
T* ptr, Arena* arena, google::protobuf::internal::false_type) {
static void RegisterDestructorInternal(T* ptr, Arena* arena,
std::false_type) {
arena->OwnDestructor(ptr);
}
@@ -869,15 +638,16 @@ class LIBPROTOBUF_EXPORT Arena {
// is a subtype of ::google::protobuf::Message and 'false_type' otherwise. Collapsing
// all template instantiations to one for generic Message reduces code size,
// using the virtual destructor instead.
template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void OwnInternal(T* object, google::protobuf::internal::true_type) {
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object,
std::true_type) {
if (object != NULL) {
impl_.AddCleanup(object,
&internal::arena_delete_object< ::google::protobuf::Message>);
impl_.AddCleanup(object, &internal::arena_delete_object<Message>);
}
}
template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void OwnInternal(T* object, google::protobuf::internal::false_type) {
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void OwnInternal(T* object,
std::false_type) {
if (object != NULL) {
impl_.AddCleanup(object, &internal::arena_delete_object<T>);
}
@@ -886,16 +656,15 @@ 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 <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArenaInternal(
const T* value, google::protobuf::internal::true_type) {
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal(
const T* value, std::true_type) {
return InternalHelper<T>::GetArena(value);
}
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArenaInternal(
const T* /* value */, google::protobuf::internal::false_type) {
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static Arena* GetArenaInternal(
const T* /* value */, std::false_type) {
return NULL;
}
@@ -907,7 +676,6 @@ class LIBPROTOBUF_EXPORT Arena {
internal::ArenaImpl impl_;
void* (*on_arena_init_)(Arena* arena);
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);
@@ -918,9 +686,10 @@ class LIBPROTOBUF_EXPORT Arena {
void* hooks_cookie_;
template <typename Type>
friend class ::google::protobuf::internal::GenericTypeHandler;
friend class internal::GenericTypeHandler;
friend struct internal::ArenaStringPtr; // For AllocateAligned.
friend class internal::LazyField; // For CreateMaybeMessage.
friend class internal::LazyField; // For CreateMaybeMessage.
friend class MessageLite;
template <typename Key, typename T>
friend class Map;
};
+128 -49
View File
@@ -33,17 +33,18 @@
#ifndef GOOGLE_PROTOBUF_ARENA_IMPL_H__
#define GOOGLE_PROTOBUF_ARENA_IMPL_H__
#include <atomic>
#include <limits>
#include <google/protobuf/stubs/atomic_sequence_num.h>
#include <google/protobuf/stubs/atomicops.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/mutex.h>
#include <google/protobuf/stubs/type_traits.h>
#include <google/protobuf/stubs/port.h>
#ifdef ADDRESS_SANITIZER
#include <sanitizer/asan_interface.h>
#endif // ADDRESS_SANITIZER
namespace google {
namespace protobuf {
@@ -112,6 +113,10 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
void AddCleanup(void* elem, void (*cleanup)(void*));
private:
void* AllocateAlignedFallback(size_t n);
void* AllocateAlignedAndAddCleanupFallback(size_t n, void (*cleanup)(void*));
void AddCleanupFallback(void* elem, void (*cleanup)(void*));
// Node contains the ptr of the object to be cleaned up and the associated
// cleanup function ptr.
struct CleanupNode {
@@ -124,34 +129,107 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
static size_t SizeOf(size_t i) {
return sizeof(CleanupChunk) + (sizeof(CleanupNode) * (i - 1));
}
size_t len; // Number of elements currently present.
size_t size; // Total elements in the list.
CleanupChunk* next; // Next node in the list.
CleanupNode nodes[1]; // True length is |size|.
};
struct Block;
class Block;
// Tracks per-thread info. ThreadInfos are kept in a linked list.
struct ThreadInfo {
void *owner; // &ThreadCache of this thread;
Block* head; // Head of linked list of blocks.
CleanupChunk* cleanup; // Head of cleanup list.
ThreadInfo* next; // Next ThreadInfo in this linked list.
// 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<size_t>(limit_ - ptr_) < n)) {
return AllocateAlignedFallback(n);
}
void* ret = ptr_;
ptr_ += n;
#ifdef ADDRESS_SANITIZER
ASAN_UNPOISON_MEMORY_REGION(ret, n);
#endif // ADDRESS_SANITIZER
return ret;
}
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_++;
}
void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*)) {
void* ret = AllocateAligned(n);
AddCleanup(ret, cleanup);
return ret;
}
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();
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_;
};
// Blocks are variable length malloc-ed objects. The following structure
// describes the common header for all blocks.
struct Block {
void* owner; // &ThreadCache of thread that owns this block.
ThreadInfo* thread_info; // ThreadInfo of thread that owns this block.
Block* next; // Next block in arena (may have different owner)
// ((char*) &block) + pos is next available byte. It is always
// aligned at a multiple of 8 bytes.
size_t pos;
size_t size; // total size of the block.
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
size_t avail() const { return size - pos; }
class LIBPROTOBUF_EXPORT Block {
public:
Block(size_t size, Block* next);
char* Pointer(size_t n) {
GOOGLE_DCHECK(n <= size_);
return reinterpret_cast<char*>(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_;
// data follows
};
@@ -160,15 +238,15 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
// 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_block_used_(NULL) {}
ThreadCache() : last_lifecycle_id_seen(-1), last_serial_arena(NULL) {}
#endif
// The ThreadCache is considered valid as long as this matches the
// lifecycle_id of the arena being used.
int64 last_lifecycle_id_seen;
Block* last_block_used_;
SerialArena* last_serial_arena;
};
static google::protobuf::internal::SequenceNumber lifecycle_id_generator_;
static std::atomic<int64> 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.
@@ -188,51 +266,52 @@ class LIBPROTOBUF_EXPORT ArenaImpl {
// Free all blocks and return the total space used which is the sums of sizes
// of the all the allocated blocks.
uint64 FreeBlocks();
void AddCleanupInBlock(Block* b, void* elem, void (*func)(void*));
CleanupChunk* ExpandCleanupList(CleanupChunk* cleanup, Block* b);
// Delete or Destruct all objects owned by the arena.
void CleanupList();
inline void CacheBlock(Block* block) {
thread_cache().last_block_used_ = block;
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.
google::protobuf::internal::Release_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(block));
hint_.store(serial, std::memory_order_release);
}
google::protobuf::internal::AtomicWord threads_; // Pointer to a linked list of ThreadInfo.
google::protobuf::internal::AtomicWord hint_; // Fast thread-local block access
google::protobuf::internal::AtomicWord space_allocated_; // Sum of sizes of all allocated blocks.
std::atomic<SerialArena*>
threads_; // Pointer to a linked list of SerialArena.
std::atomic<SerialArena*> hint_; // Fast thread-local block access
std::atomic<size_t> space_allocated_; // Total size of all allocated blocks.
Block *initial_block_; // If non-NULL, points to the block that came from
// user data.
// Returns a block owned by this thread.
Block* GetBlock(size_t n);
Block* GetBlockSlow(void* me, Block* my_full_block, size_t n);
Block* NewBlock(void* me, Block* my_last_block, size_t min_bytes);
void InitBlock(Block* b, void *me, size_t size);
static void* AllocFromBlock(Block* b, size_t n);
ThreadInfo* NewThreadInfo(Block* b);
ThreadInfo* FindThreadInfo(void* me);
ThreadInfo* GetThreadInfo(void* me, size_t n);
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);
// All protos have pointers back to the arena hence Arena must have
// pointer stability.
ArenaImpl(ArenaImpl&&) = delete;
ArenaImpl& operator=(ArenaImpl&&) = delete;
public:
// kHeaderSize 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 kHeaderSize = (sizeof(Block) + 7) & -8;
#if LANG_CXX11
static_assert(kHeaderSize % 8 == 0, "kHeaderSize must be a multiple of 8.");
#endif
// 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_assert(kBlockHeaderSize % 8 == 0,
"kBlockHeaderSize must be a multiple of 8.");
static_assert(kSerialArenaSize % 8 == 0,
"kSerialArenaSize must be a multiple of 8.");
};
} // namespace internal
@@ -50,7 +50,7 @@ void TestParseCorruptedString(const T& message) {
s[i] ^= c;
google::protobuf::Arena arena;
T* message =
google::protobuf::Arena::CreateMessage<T>(use_arena ? &arena : NULL);
google::protobuf::Arena::CreateMessage<T>(use_arena ? &arena : nullptr);
if (message->ParseFromString(s)) {
++success_count;
}
@@ -33,10 +33,8 @@
#include <algorithm>
#include <cstring>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <string>
#include <type_traits>
#include <typeinfo>
#include <vector>
@@ -67,7 +65,6 @@ using protobuf_unittest::TestOneof2;
using protobuf_unittest::TestEmptyMessage;
namespace protobuf {
namespace {
class Notifier {
public:
@@ -154,9 +151,19 @@ class MustBeConstructedWithOneThroughEight {
TEST(ArenaTest, ArenaConstructable) {
EXPECT_TRUE(Arena::is_arena_constructable<TestAllTypes>::type::value);
EXPECT_TRUE(Arena::is_arena_constructable<const TestAllTypes>::type::value);
EXPECT_FALSE(Arena::is_arena_constructable<
protobuf_unittest_no_arena::TestNoArenaMessage>::type::value);
EXPECT_FALSE(Arena::is_arena_constructable<Arena>::type::value);
}
TEST(ArenaTest, DestructorSkippable) {
EXPECT_TRUE(Arena::is_destructor_skippable<TestAllTypes>::type::value);
EXPECT_TRUE(Arena::is_destructor_skippable<const TestAllTypes>::type::value);
EXPECT_FALSE(Arena::is_destructor_skippable<
protobuf_unittest_no_arena::TestNoArenaMessage>::type::value);
EXPECT_FALSE(Arena::is_destructor_skippable<Arena>::type::value);
}
TEST(ArenaTest, BasicCreate) {
Arena arena;
EXPECT_TRUE(Arena::Create<int32>(&arena) != NULL);
@@ -198,7 +205,6 @@ TEST(ArenaTest, CreateAndNonConstCopy) {
EXPECT_EQ("foo", *s_copy);
}
#if LANG_CXX11
TEST(ArenaTest, CreateAndMove) {
Arena arena;
string s("foo");
@@ -207,7 +213,6 @@ TEST(ArenaTest, CreateAndMove) {
EXPECT_TRUE(s.empty()); // NOLINT
EXPECT_EQ("foo", *s_move);
}
#endif
TEST(ArenaTest, CreateWithFourConstructorArguments) {
Arena arena;
@@ -243,7 +248,6 @@ TEST(ArenaTest, CreateWithEightConstructorArguments) {
ASSERT_EQ("8", new_object->eight_);
}
#if LANG_CXX11
class PleaseMoveMe {
public:
explicit PleaseMoveMe(const string& value) : value_(value) {}
@@ -264,13 +268,12 @@ TEST(ArenaTest, CreateWithMoveArguments) {
EXPECT_TRUE(new_object);
ASSERT_EQ("1", new_object->value());
}
#endif
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<char> arena_block(72);
std::vector<char> arena_block(96);
ArenaOptions options;
options.initial_block = &arena_block[0];
options.initial_block_size = arena_block.size();
@@ -443,7 +446,7 @@ TEST(ArenaTest, ReflectionSwapFields) {
TestUtil::SetAllFields(arena1_message);
reflection->SwapFields(arena1_message, &message, fields);
EXPECT_EQ(&arena1, arena1_message->GetArena());
EXPECT_EQ(NULL, message.GetArena());
EXPECT_EQ(nullptr, message.GetArena());
arena1_message->SerializeToString(&output);
EXPECT_EQ(0, output.size());
TestUtil::ExpectAllFieldsSet(message);
@@ -469,7 +472,7 @@ TEST(ArenaTest, ReleaseMessage) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->mutable_optional_nested_message()->set_bb(118);
google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested(
std::unique_ptr<TestAllTypes::NestedMessage> nested(
arena_message->release_optional_nested_message());
EXPECT_EQ(118, nested->bb());
@@ -490,7 +493,7 @@ TEST(ArenaTest, ReleaseString) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
arena_message->set_optional_string("hello");
google::protobuf::scoped_ptr<string> released_str(
std::unique_ptr<string> released_str(
arena_message->release_optional_string());
EXPECT_EQ("hello", *released_str);
@@ -601,25 +604,6 @@ TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) {
}
#endif // !GOOGLE_PROTOBUF_NO_RTTI
TEST(ArenaTest, UnsafeArenaReleaseDoesNotMakeCopy) {
Arena arena;
TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
TestAllTypes::NestedMessage* nested_msg = NULL;
TestAllTypes::NestedMessage* orig_nested_msg = NULL;
string* nested_string = NULL;
string* orig_nested_string = NULL;
arena_message->mutable_optional_nested_message()->set_bb(42);
*arena_message->mutable_optional_string() = "Hello";
orig_nested_msg = arena_message->mutable_optional_nested_message();
orig_nested_string = arena_message->mutable_optional_string();
nested_msg = arena_message->unsafe_arena_release_optional_nested_message();
nested_string = arena_message->unsafe_arena_release_optional_string();
EXPECT_EQ(orig_nested_msg, nested_msg);
EXPECT_EQ(orig_nested_string, nested_string);
// Released pointers still on arena; no 'delete' calls needed here.
}
TEST(ArenaTest, SetAllocatedAcrossArenas) {
Arena arena1;
TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
@@ -899,17 +883,18 @@ TEST(ArenaTest, ReleaseLastRepeatedField) {
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<TestAllTypes>(&arena);
TestAllTypes* message2 = Arena::CreateMessage<TestAllTypes>(&arena);
string* arena_string = Arena::Create<string>(&arena);
*arena_string = "Test content";
*arena_string = kContent;
message1->unsafe_arena_set_allocated_optional_string(arena_string);
EXPECT_EQ(arena_string, message1->mutable_optional_string());
message2->unsafe_arena_set_allocated_optional_string(
message1->unsafe_arena_release_optional_string());
EXPECT_EQ(arena_string, message2->mutable_optional_string());
EXPECT_EQ(kContent, message2->optional_string());
}
TEST(ArenaTest, UnsafeArenaAddAllocated) {
@@ -1299,12 +1284,12 @@ TEST(ArenaTest, SpaceAllocated_and_Used) {
options.initial_block_size = 0;
Arena arena_3(options);
EXPECT_EQ(0, arena_3.SpaceUsed());
::google::protobuf::Arena::CreateArray<char>(&arena_3, 182);
::google::protobuf::Arena::CreateArray<char>(&arena_3, 160);
EXPECT_EQ(256, arena_3.SpaceAllocated());
EXPECT_EQ(Align8(182), arena_3.SpaceUsed());
EXPECT_EQ(Align8(160), arena_3.SpaceUsed());
::google::protobuf::Arena::CreateArray<char>(&arena_3, 70);
EXPECT_EQ(256 + 512, arena_3.SpaceAllocated());
EXPECT_EQ(Align8(182) + Align8(70), arena_3.SpaceUsed());
EXPECT_EQ(Align8(160) + Align8(70), arena_3.SpaceUsed());
EXPECT_EQ(256 + 512, arena_3.Reset());
}
@@ -1347,6 +1332,13 @@ TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaAllocatedMessages) {
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<TestAllTypes>(&arena);
@@ -1405,13 +1397,20 @@ 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;
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;
ArenaOptionsTestFriend::Set(&options);
// Scope for defining the arena
{
@@ -1419,7 +1418,7 @@ TEST(ArenaTest, ArenaHooksSanity) {
EXPECT_EQ(1, ArenaHooksTestUtil::num_init);
EXPECT_EQ(0, ArenaHooksTestUtil::num_allocations);
::google::protobuf::Arena::Create<uint64>(&arena);
if (google::protobuf::internal::has_trivial_destructor<uint64>::value) {
if (std::is_trivially_destructible<uint64>::value) {
EXPECT_EQ(1, ArenaHooksTestUtil::num_allocations);
} else {
EXPECT_EQ(2, ArenaHooksTestUtil::num_allocations);
@@ -1433,6 +1432,5 @@ TEST(ArenaTest, ArenaHooksSanity) {
}
} // namespace
} // namespace protobuf
} // namespace google
+72 -7
View File
@@ -51,6 +51,18 @@ namespace google {
namespace protobuf {
namespace internal {
template <typename T>
class TaggedPtr {
public:
void Set(T* p) { ptr_ = reinterpret_cast<uintptr_t>(p); }
T* Get() const { return reinterpret_cast<T*>(ptr_); }
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) {
@@ -87,6 +99,13 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
if (ptr_ == default_value) {
return NULL;
}
return ReleaseNonDefault(default_value, 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.
@@ -152,6 +171,29 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
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
}
// Frees storage (if not on an arena).
inline void Destroy(const ::std::string* default_value,
@@ -174,6 +216,15 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
}
}
// 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, 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|.
@@ -241,12 +292,19 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
if (ptr_ == default_value) {
return NULL;
} else {
::std::string* released = ptr_;
ptr_ = const_cast< ::std::string* >(default_value);
return released;
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) {
@@ -294,6 +352,15 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
return ptr_ == default_value;
}
// Internal accessors!!!!
void UnsafeSetTaggedPointer(TaggedPtr< ::std::string> value) {
ptr_ = value.Get();
}
// Generated code only! An optimization, in certain cases the generated
// code is certain we can obtain a string with no default checks and
// tag tests.
::std::string* UnsafeMutablePointer() { return ptr_; }
private:
::std::string* ptr_;
@@ -301,10 +368,8 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
void CreateInstance(::google::protobuf::Arena* arena,
const ::std::string* initial_value) {
GOOGLE_DCHECK(initial_value != NULL);
ptr_ = new ::std::string(*initial_value);
if (arena != NULL) {
arena->Own(ptr_);
}
// 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) {
@@ -35,9 +35,6 @@
#include <algorithm>
#include <cstdlib>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <string>
#include <vector>
@@ -31,9 +31,6 @@
#include <google/protobuf/compiler/annotation_test_util.h>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/io/printer.h>
@@ -76,10 +73,9 @@ void AddFile(const string& filename, const string& data) {
true));
}
bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
const string& meta_file_suffix, CommandLineInterface* cli,
FileDescriptorProto* file,
std::vector<ExpectedOutput>* outputs) {
bool RunProtoCompiler(const string& filename,
const string& plugin_specific_args,
CommandLineInterface* cli, FileDescriptorProto* file) {
cli->SetInputsAreProtoPathRelative(true);
DescriptorCapturingGenerator capturing_generator(file);
@@ -92,24 +88,7 @@ bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
plugin_specific_args.c_str(), capture_out.c_str(),
filename.c_str()};
if (cli->Run(5, argv) != 0) {
return false;
}
if (outputs != NULL) {
for (std::vector<ExpectedOutput>::iterator i = outputs->begin();
i != outputs->end(); ++i) {
GOOGLE_CHECK_OK(File::GetContents(TestTempDir() + "/" + i->file_path,
&i->file_content, true));
if (!DecodeMetadata(
TestTempDir() + "/" + i->file_path + meta_file_suffix,
&i->file_info)) {
return false;
}
}
}
return true;
return cli->Run(5, argv) == 0;
}
bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) {
@@ -59,25 +59,20 @@ struct ExpectedOutput {
// directory.
void AddFile(const string& filename, const string& data);
// Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output
// code from the previously added file with name `filename`.
// 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"
// meta_file_suffix: suffix of meta files that contain annotations. For Java
// it is ".pb.meta" because for file Foo.java meta file is Foo.java.pb.meta
// 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.
// outputs: output parameter. If not NULL, each ExpectedOutput in the vector
// should have its file_path set; CaptureMetadata will fill the rest of
// the fields appropriately.
bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
const string& meta_file_suffix, CommandLineInterface* cli,
FileDescriptorProto* file,
std::vector<ExpectedOutput>* outputs);
bool RunProtoCompiler(const string& filename,
const string& plugin_specific_args,
CommandLineInterface* cli, FileDescriptorProto* file);
bool DecodeMetadata(const string& path, GeneratedCodeInfo* info);
@@ -34,9 +34,9 @@
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
@@ -166,7 +166,7 @@ typedef GeneratorContext OutputDirectory;
// "foo=bar,baz,qux=corge"
// parses to the pairs:
// ("foo", "bar"), ("baz", ""), ("qux", "corge")
void ParseGeneratorParameter(
LIBPROTOC_EXPORT void ParseGeneratorParameter(
const string&, std::vector<std::pair<string, string> >*);
} // namespace compiler
@@ -58,9 +58,6 @@
#include <limits.h> //For PATH_MAX
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
@@ -171,8 +168,7 @@ bool VerifyDirectoryExists(const string& path) {
// directories listed in |filename|.
bool TryCreateParentDirectory(const string& prefix, const string& filename) {
// Recursively create parent directories to the output file.
std::vector<string> parts =
Split(filename, "/", true);
std::vector<string> parts = Split(filename, "/", true);
string path_so_far = prefix;
for (int i = 0; i < parts.size() - 1; i++) {
path_so_far += parts[i];
@@ -226,7 +222,7 @@ bool IsInstalledProtoPath(const string& path) {
// Add the paths where google/protobuf/descriptor.proto and other well-known
// type protos are installed.
void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
void AddDefaultProtoPaths(std::vector<std::pair<string, string> >* 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.
@@ -242,12 +238,12 @@ void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
path = path.substr(0, pos);
// Check the binary's directory.
if (IsInstalledProtoPath(path)) {
paths->push_back(pair<string, string>("", path));
paths->push_back(std::pair<string, string>("", path));
return;
}
// Check if there is an include subdirectory.
if (IsInstalledProtoPath(path + "/include")) {
paths->push_back(pair<string, string>("", path + "/include"));
paths->push_back(std::pair<string, string>("", path + "/include"));
return;
}
// Check if the upper level directory has an "include" subdirectory.
@@ -257,7 +253,7 @@ void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
}
path = path.substr(0, pos);
if (IsInstalledProtoPath(path + "/include")) {
paths->push_back(pair<string, string>("", path + "/include"));
paths->push_back(std::pair<string, string>("", path + "/include"));
return;
}
}
@@ -440,7 +436,7 @@ class CommandLineInterface::MemoryOutputStream
bool append_mode_;
// StringOutputStream writing to data_.
google::protobuf::scoped_ptr<io::StringOutputStream> inner_;
std::unique_ptr<io::StringOutputStream> inner_;
};
// -------------------------------------------------------------------
@@ -835,10 +831,10 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
std::vector<const FileDescriptor*> parsed_files;
// null unless descriptor_set_in_names_.empty()
google::protobuf::scoped_ptr<DiskSourceTree> disk_source_tree;
google::protobuf::scoped_ptr<ErrorPrinter> error_collector;
google::protobuf::scoped_ptr<DescriptorPool> descriptor_pool;
google::protobuf::scoped_ptr<DescriptorDatabase> descriptor_database;
std::unique_ptr<DiskSourceTree> disk_source_tree;
std::unique_ptr<ErrorPrinter> error_collector;
std::unique_ptr<DescriptorPool> descriptor_pool;
std::unique_ptr<DescriptorDatabase> descriptor_database;
if (descriptor_set_in_names_.empty()) {
disk_source_tree.reset(new DiskSourceTree());
if (!InitializeDiskSourceTree(disk_source_tree.get())) {
@@ -1395,8 +1391,7 @@ CommandLineInterface::InterpretArgument(const string& name,
// with colons. Let's accept that syntax too just to make things more
// intuitive.
std::vector<string> parts = Split(
value,
CommandLineInterface::kPathSeparator,
value, CommandLineInterface::kPathSeparator,
true);
for (int i = 0; i < parts.size(); i++) {
@@ -1421,7 +1416,7 @@ CommandLineInterface::InterpretArgument(const string& name,
// Make sure disk path exists, warn otherwise.
if (access(disk_path.c_str(), F_OK) < 0) {
// Try the original path; it may have just happed to have a '=' in it.
// 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;
@@ -1447,8 +1442,7 @@ CommandLineInterface::InterpretArgument(const string& name,
}
direct_dependencies_explicitly_set_ = true;
std::vector<string> direct = Split(
value, ":", true);
std::vector<string> direct = Split(value, ":", true);
GOOGLE_DCHECK(direct_dependencies_.empty());
direct_dependencies_.insert(direct.begin(), direct.end());
@@ -1481,9 +1475,8 @@ CommandLineInterface::InterpretArgument(const string& name,
}
descriptor_set_in_names_ = Split(
value,
CommandLineInterface::kPathSeparator,
true);
value, CommandLineInterface::kPathSeparator,
true);
} else if (name == "-o" || name == "--descriptor_set_out") {
if (!descriptor_set_out_name_.empty()) {
@@ -1629,7 +1622,6 @@ CommandLineInterface::InterpretArgument(const string& name,
}
mode_ = MODE_PRINT;
print_mode_ = PRINT_FREE_FIELDS;
} else if (name == "--profile_path") {
} else {
// Some other flag. Look it up in the generators list.
const GeneratorInfo* generator_info =
@@ -1908,10 +1900,12 @@ bool CommandLineInterface::GeneratePluginOutput(
string* error) {
CodeGeneratorRequest request;
CodeGeneratorResponse response;
string processed_parameter = parameter;
// Build the request.
if (!parameter.empty()) {
request.set_parameter(parameter);
if (!processed_parameter.empty()) {
request.set_parameter(processed_parameter);
}
@@ -1948,17 +1942,18 @@ bool CommandLineInterface::GeneratePluginOutput(
// Write the files. We do this even if there was a generator error in order
// to match the behavior of a compiled-in generator.
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> current_output;
std::unique_ptr<io::ZeroCopyOutputStream> 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(
output_file.name(), output_file.insertion_point()));
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
@@ -1997,7 +1992,7 @@ bool CommandLineInterface::EncodeOrDecode(const DescriptorPool* pool) {
}
DynamicMessageFactory dynamic_factory(pool);
google::protobuf::scoped_ptr<Message> message(dynamic_factory.GetPrototype(type)->New());
std::unique_ptr<Message> message(dynamic_factory.GetPrototype(type)->New());
if (mode_ == MODE_ENCODE) {
SetFdToTextMode(STDIN_FILENO);
@@ -413,11 +413,6 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// dependency file will be written. Otherwise, empty.
string dependency_out_name_;
// Path to a file that contains serialized AccessInfo which provides
// relative hotness of fields per message. This helps protoc to generate
// better code.
string profile_path_;
// True if --include_imports was given, meaning that we should
// write all transitive dependencies to the DescriptorSet. Otherwise, only
// the .proto files listed on the command-line are added.
@@ -40,9 +40,6 @@
#include <unistd.h>
#endif
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <vector>
#include <google/protobuf/stubs/stringprintf.h>
@@ -344,7 +341,7 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector<string> args) {
}
}
google::protobuf::scoped_array<const char * > argv(new const char* [args.size()]);
std::unique_ptr<const char * []> argv(new const char* [args.size()]);
for (int i = 0; i < args.size(); i++) {
args[i] = StringReplace(args[i], "$tmpdir", temp_directory_, true);
@@ -2298,7 +2295,7 @@ class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam();
}
google::protobuf::scoped_array<const char * > argv(new const char* [args.size()]);
std::unique_ptr<const char * []> argv(new const char* [args.size()]);
for (int i = 0; i < args.size(); i++) {
argv[i] = args[i].c_str();
}
@@ -44,6 +44,7 @@
#include <map>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
@@ -97,9 +98,10 @@ class MockGeneratorContext : public GeneratorContext {
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.";
<< physical_filename
<< " needs to be regenerated. Please run "
"generate_descriptor_proto.sh. "
"Then add this file to your CL.";
}
// implements GeneratorContext --------------------------------------
@@ -116,37 +118,50 @@ class MockGeneratorContext : public GeneratorContext {
std::map<string, string*> files_;
};
TEST(BootstrapTest, GeneratedDescriptorMatches) {
MockErrorCollector error_collector;
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<string, string> vpath_map;
std::map<string, string> 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());
Importer importer(&source_tree, &error_collector);
const FileDescriptor* proto_file =
importer.Import("google/protobuf/descriptor.proto");
const FileDescriptor* plugin_proto_file =
importer.Import("google/protobuf/compiler/plugin.proto");
EXPECT_EQ("", error_collector.text_);
ASSERT_TRUE(proto_file != NULL);
ASSERT_TRUE(plugin_proto_file != NULL);
CppGenerator generator;
MockGeneratorContext context;
string error;
string parameter = "dllexport_decl=LIBPROTOBUF_EXPORT";
ASSERT_TRUE(generator.Generate(proto_file, parameter,
&context, &error));
parameter = "dllexport_decl=LIBPROTOC_EXPORT";
ASSERT_TRUE(generator.Generate(plugin_proto_file, parameter,
&context, &error));
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));
context.ExpectFileMatches("google/protobuf/descriptor.pb.h",
"google/protobuf/descriptor.pb.h");
context.ExpectFileMatches("google/protobuf/descriptor.pb.cc",
"google/protobuf/descriptor.pb.cc");
context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.h",
"google/protobuf/compiler/plugin.pb.h");
context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.cc",
"google/protobuf/compiler/plugin.pb.cc");
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
@@ -179,7 +179,7 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
void EnumGenerator::
GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
printer->Print(
"template <> struct is_proto_enum< $classname$> : ::google::protobuf::internal::true_type "
"template <> struct is_proto_enum< $classname$> : ::std::true_type "
"{};\n",
"classname", ClassName(descriptor_, true));
if (HasDescriptorMethods(descriptor_->file(), options_)) {
@@ -195,7 +195,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return static_cast< $type$ >($oneof_prefix$$name$_);\n"
" return static_cast< $type$ >($field_member$);\n"
" }\n"
" return static_cast< $type$ >($default$);\n"
"}\n"
@@ -209,14 +209,14 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" }\n"
" $oneof_prefix$$name$_ = value;\n"
" $field_member$ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n");
}
void EnumOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$oneof_prefix$$name$_ = $default$;\n");
printer->Print(variables_, "$field_member$ = $default$;\n");
}
void EnumOneofFieldGenerator::
@@ -35,8 +35,8 @@
#include <google/protobuf/compiler/cpp/cpp_extension.h>
#include <map>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
@@ -120,7 +120,6 @@ void ExtensionGenerator::GenerateDeclaration(io::Printer* printer) {
" ::google::protobuf::internal::$type_traits$, $field_type$, $packed$ >\n"
" $name$;\n"
);
}
void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
@@ -34,21 +34,18 @@
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_primitive_field.h>
#include <google/protobuf/compiler/cpp/cpp_string_field.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_enum_field.h>
#include <google/protobuf/compiler/cpp/cpp_map_field.h>
#include <google/protobuf/compiler/cpp/cpp_message_field.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -67,12 +64,7 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
(*variables)["number"] = SimpleItoa(descriptor->number());
(*variables)["classname"] = ClassName(FieldScope(descriptor), false);
(*variables)["declared_type"] = DeclaredTypeMethodName(descriptor->type());
// non_null_ptr_to_name is usable only if has_$name$ is true. It yields a
// pointer that will not be NULL. Subclasses of FieldGenerator may set
// (*variables)["non_null_ptr_to_name"] differently.
(*variables)["non_null_ptr_to_name"] =
StrCat("&this->", FieldName(descriptor), "()");
(*variables)["field_member"] = FieldName(descriptor) + "_";
(*variables)["tag_size"] = SimpleItoa(
WireFormat::TagSize(descriptor->number(), descriptor->type()));
@@ -81,8 +73,6 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
(*variables)["deprecated_attr"] = descriptor->options().deprecated()
? "GOOGLE_PROTOBUF_DEPRECATED_ATTR " : "";
(*variables)["cppget"] = "Get";
if (HasFieldPresence(descriptor->file())) {
(*variables)["set_hasbit"] =
"set_has_" + FieldName(descriptor) + "();";
@@ -93,10 +83,6 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
(*variables)["clear_hasbit"] = "";
}
// By default, empty string, so that generic code used for both oneofs and
// singular fields can be written.
(*variables)["oneof_prefix"] = "";
// 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
@@ -108,10 +94,8 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables) {
const string prefix = descriptor->containing_oneof()->name() + "_.";
(*variables)["oneof_prefix"] = prefix;
(*variables)["oneof_name"] = descriptor->containing_oneof()->name();
(*variables)["non_null_ptr_to_name"] =
StrCat(prefix, (*variables)["name"], "_");
(*variables)["field_member"] = StrCat(prefix, (*variables)["name"], "_");
}
FieldGenerator::~FieldGenerator() {}
@@ -129,26 +113,29 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
}
FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor,
const Options& options)
const Options& options,
SCCAnalyzer* scc_analyzer)
: descriptor_(descriptor),
options_(options),
field_generators_(
new google::protobuf::scoped_ptr<FieldGenerator>[descriptor->field_count()]) {
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));
field_generators_[i].reset(
MakeGenerator(descriptor->field(i), options, scc_analyzer));
}
}
FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
const Options& options) {
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);
return new RepeatedMessageFieldGenerator(field, options,
scc_analyzer);
}
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
@@ -164,7 +151,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
} else if (field->containing_oneof()) {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
return new MessageOneofFieldGenerator(field, options);
return new MessageOneofFieldGenerator(field, options, scc_analyzer);
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // StringOneofFieldGenerator handles unknown ctypes.
@@ -179,7 +166,7 @@ FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
} else {
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_MESSAGE:
return new MessageFieldGenerator(field, options);
return new MessageFieldGenerator(field, options, scc_analyzer);
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // StringFieldGenerator handles unknown ctypes.
@@ -37,13 +37,11 @@
#include <map>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <string>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_options.h>
#include <google/protobuf/descriptor.h>
namespace google {
namespace protobuf {
@@ -82,38 +80,12 @@ class FieldGenerator {
// implementation is empty.
virtual void GenerateStaticMembers(io::Printer* /*printer*/) const {}
// Generate prototypes for accessors that will manipulate imported
// messages inline. These are for .proto.h headers.
//
// In .proto.h mode, the headers of imports are not #included. However,
// functions that manipulate the imported message types need access to
// the class definition of the imported message, meaning that the headers
// must be #included. To get around this, functions that manipulate
// imported message objects are defined as dependent functions in a base
// template class. By making them dependent template functions, the
// function templates will not be instantiated until they are called, so
// we can defer to those translation units to #include the necessary
// generated headers.
//
// See:
// http://en.cppreference.com/w/cpp/language/class_template#Implicit_instantiation
//
// Most field types don't need this, so the default implementation is empty.
virtual void GenerateDependentAccessorDeclarations(
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 depenent accessor functions for this field.
// These are placed inside the header after all class definitions.
virtual void GenerateDependentInlineAccessorDefinitions(
io::Printer* printer) const {}
// Generate inline definitions of accessor functions for this field.
// These are placed inside the header after all class definitions.
// In non-.proto.h mode, this generates dependent accessor functions as well.
virtual void GenerateInlineAccessorDefinitions(
io::Printer* printer) const = 0;
@@ -184,6 +156,10 @@ class FieldGenerator {
// 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)
@@ -203,6 +179,11 @@ class FieldGenerator {
// 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_;
@@ -213,7 +194,8 @@ class FieldGenerator {
// Convenience class which constructs FieldGenerators for a Descriptor.
class FieldGeneratorMap {
public:
FieldGeneratorMap(const Descriptor* descriptor, const Options& options);
FieldGeneratorMap(const Descriptor* descriptor, const Options& options,
SCCAnalyzer* scc_analyzer);
~FieldGeneratorMap();
const FieldGenerator& get(const FieldDescriptor* field) const;
@@ -221,10 +203,11 @@ class FieldGeneratorMap {
private:
const Descriptor* descriptor_;
const Options& options_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<FieldGenerator> > field_generators_;
std::vector<std::unique_ptr<FieldGenerator>> field_generators_;
static FieldGenerator* MakeGenerator(const FieldDescriptor* field,
const Options& options);
const Options& options,
SCCAnalyzer* scc_analyzer);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
@@ -35,20 +35,17 @@
#include <google/protobuf/compiler/cpp/cpp_file.h>
#include <map>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <set>
#include <vector>
#include <google/protobuf/compiler/cpp/cpp_enum.h>
#include <google/protobuf/compiler/cpp/cpp_service.h>
#include <google/protobuf/compiler/cpp/cpp_extension.h>
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_message.h>
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/compiler/cpp/cpp_service.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -61,11 +58,11 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options)
options_(options),
scc_analyzer_(options),
enum_generators_owner_(
new google::protobuf::scoped_ptr<EnumGenerator>[file->enum_type_count()]),
new std::unique_ptr<EnumGenerator>[file->enum_type_count()]),
service_generators_owner_(
new google::protobuf::scoped_ptr<ServiceGenerator>[file->service_count()]),
new std::unique_ptr<ServiceGenerator>[file->service_count()]),
extension_generators_owner_(
new google::protobuf::scoped_ptr<ExtensionGenerator>[file->extension_count()]) {
new std::unique_ptr<ExtensionGenerator>[file->extension_count()]) {
std::vector<const Descriptor*> msgs = FlattenMessagesInFile(file);
for (int i = 0; i < msgs.size(); i++) {
// Deleted in destructor
@@ -141,6 +138,9 @@ 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);
@@ -223,8 +223,9 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
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", StripProto(file_->name()));
"basename", target_basename);
} else {
GenerateLibraryIncludes(printer);
}
@@ -256,9 +257,10 @@ void FileGenerator::GeneratePBHeader(io::Printer* printer,
}
void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
string target_basename = StripProto(file_->name());
const bool use_system_include = IsWellKnownMessage(file_);
string header =
StripProto(file_->name()) + (options_.proto_h ? ".proto.h" : ".pb.h");
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"
@@ -269,7 +271,6 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
"\n"
"#include <google/protobuf/stubs/common.h>\n"
"#include <google/protobuf/stubs/port.h>\n"
"#include <google/protobuf/stubs/once.h>\n"
"#include <google/protobuf/io/coded_stream.h>\n"
"#include <google/protobuf/wire_format_lite_inl.h>\n",
"filename", file_->name(),
@@ -296,7 +297,8 @@ void FileGenerator::GenerateSourceIncludes(io::Printer* printer) {
for (int i = 0; i < file_->dependency_count(); i++) {
const FileDescriptor* dep = file_->dependency(i);
const char* extension = ".proto.h";
string dependency = StripProto(dep->name()) + extension;
string basename = StripProto(dep->name());
string dependency = basename + extension;
printer->Print(
"#include \"$dependency$\"\n",
"dependency", dependency);
@@ -338,33 +340,34 @@ namespace {
// Generates weak symbol declarations for types that are to be considered weakly
// referenced.
void GenerateWeakDeclarations(
const FileDescriptor* file, const Options& options,
SCCAnalyzer* scc_analyzer,
io::Printer* printer) {
std::vector<const FieldDescriptor*> fields;
ListAllFields(file, &fields);
void GenerateInternalForwardDeclarations(
const std::vector<const FieldDescriptor*>& 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<std::pair<string, string> > messages;
std::set<std::pair<string, string> > sccs;
std::set<std::pair<string, string> > inits;
for (int i = 0; i < fields.size(); ++i) {
const FieldDescriptor* field = fields[i];
bool is_weak = IsImplicitWeakField(field, options);
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) {
const Descriptor* msg = field->message_type();
string flns = FileLevelNamespace(msg);
string repr = ClassName(scc_analyzer->GetSCC(msg)->GetRepresentative());
inits.insert(std::make_pair(flns, "InitDefaults" + repr));
inits.insert(std::make_pair(flns, "AddDescriptors"));
messages.insert(std::make_pair(Namespace(msg), ClassName(msg)));
weak_attr = " __attribute__((weak))";
}
}
if (messages.empty()) {
return;
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");
@@ -384,20 +387,40 @@ void GenerateWeakDeclarations(
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);
GenerateWeakDeclarations(file_, options_, &scc_analyzer_, 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<const FieldDescriptor*> 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 (UsingImplicitWeakFields(file_, options_)) {
if (options_.lite_implicit_weak_fields) {
printer->Print("void $classname$_ReferenceStrong() {}\n", "classname",
message_generators_[idx]->classname_);
}
@@ -411,10 +434,11 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
"// @@protoc_insertion_point(namespace_scope)\n");
} // end package namespace
if (IsSCCRepresentative(message_generators_[idx]->descriptor_)) {
NamespaceOpener ns(FileLevelNamespace(file_), printer);
GenerateInitForSCC(GetSCC(message_generators_[idx]->descriptor_), printer);
}
printer->Print(
"namespace google {\nnamespace protobuf {\n");
message_generators_[idx]->GenerateSourceInProto2Namespace(printer);
printer->Print(
"} // namespace protobuf\n} // namespace google\n");
printer->Print(
"\n"
@@ -423,15 +447,16 @@ void FileGenerator::GenerateSourceForMessage(int idx, io::Printer* printer) {
void FileGenerator::GenerateGlobalSource(io::Printer* printer) {
GenerateSourceIncludes(printer);
GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer);
// TODO(gerbens) Generate tables here
// 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_)) {
{
NamespaceOpener ns(FileLevelNamespace(file_), printer);
GenerateReflectionInitializationCode(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);
@@ -459,7 +484,10 @@ void FileGenerator::GenerateGlobalSource(io::Printer* printer) {
void FileGenerator::GenerateSource(io::Printer* printer) {
GenerateSourceIncludes(printer);
GenerateWeakDeclarations(file_, options_, &scc_analyzer_, printer);
std::vector<const FieldDescriptor*> fields;
ListAllFields(file_, &fields);
GenerateInternalForwardDeclarations(fields, options_, &scc_analyzer_,
printer);
{
NamespaceOpener ns(Namespace(file_), printer);
@@ -467,7 +495,7 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
// Define default instances
for (int i = 0; i < message_generators_.size(); i++) {
GenerateSourceDefaultInstance(i, printer);
if (UsingImplicitWeakFields(file_, options_)) {
if (options_.lite_implicit_weak_fields) {
printer->Print("void $classname$_ReferenceStrong() {}\n", "classname",
message_generators_[i]->classname_);
}
@@ -476,9 +504,25 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
{
NamespaceOpener ns(FileLevelNamespace(file_), printer);
// Define the initialization code to initialize the default instances.
// This code doesn't use a global constructor.
GenerateInitializationCode(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.
@@ -525,6 +569,15 @@ void FileGenerator::GenerateSource(io::Printer* printer) {
"\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");
@@ -544,7 +597,7 @@ class FileGenerator::ForwardDeclarations {
ForwardDeclarations* AddOrGetNamespace(const string& ns_name) {
ForwardDeclarations*& ns = namespaces_[ns_name];
if (ns == NULL) {
if (ns == nullptr) {
ns = new ForwardDeclarations;
}
return ns;
@@ -553,7 +606,42 @@ class FileGenerator::ForwardDeclarations {
std::map<string, const Descriptor*>& classes() { return classes_; }
std::map<string, const EnumDescriptor*>& enums() { return enums_; }
void Print(io::Printer* printer, const Options& options) const {
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<string, ForwardDeclarations *>::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<string, ForwardDeclarations *>::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<string, const EnumDescriptor *>::const_iterator
it = enums_.begin(),
end = enums_.end();
@@ -584,20 +672,31 @@ class FileGenerator::ForwardDeclarations {
"classname", it->first);
}
}
for (std::map<string, ForwardDeclarations *>::const_iterator
it = namespaces_.begin(),
end = namespaces_.end();
it != end; ++it) {
printer->Print("namespace $nsname$ {\n",
"nsname", it->first);
it->second->Print(printer, options);
printer->Print("} // namespace $nsname$\n",
"nsname", 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<string, const Descriptor*>::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");
}
private:
std::map<string, ForwardDeclarations*> namespaces_;
std::map<string, const Descriptor*> classes_;
std::map<string, const EnumDescriptor*> enums_;
@@ -691,7 +790,6 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
// protobuf_AssignDescriptorsOnce(): The first time it is called, calls
// AssignDescriptors(). All later times, waits for the first call to
// complete and then returns.
string message_factory = "NULL";
printer->Print(
"void protobuf_AssignDescriptors() {\n"
// Make sure the file has found its way into the pool. If a descriptor
@@ -699,10 +797,9 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
// been called yet, so we call it manually. Note that it's fine if
// AddDescriptors() is called multiple times.
" AddDescriptors();\n"
" ::google::protobuf::MessageFactory* factory = $factory$;\n"
" AssignDescriptors(\n"
" \"$filename$\", schemas, file_default_instances, "
"TableStruct::offsets, factory,\n"
"TableStruct::offsets,\n"
" $metadata$, $enum_descriptors$, $service_descriptors$);\n",
"filename", file_->name(), "metadata",
!message_generators_.empty() ? "file_level_metadata" : "NULL",
@@ -711,14 +808,13 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
"service_descriptors",
HasGenericServices(file_, options_) && file_->service_count() > 0
? "file_level_service_descriptors"
: "NULL",
"factory", message_factory);
: "NULL");
printer->Print(
"}\n"
"\n"
"void protobuf_AssignDescriptorsOnce() {\n"
" static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
" ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);\n"
" static ::google::protobuf::internal::once_flag once;\n"
" ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors);\n"
"}\n"
"\n",
"filename", file_->name(), "metadata",
@@ -728,8 +824,7 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
"service_descriptors",
HasGenericServices(file_, options_) && file_->service_count() > 0
? "file_level_service_descriptors"
: "NULL",
"factory", message_factory);
: "NULL");
// Only here because of useless string reference that we don't want in
// protobuf_AssignDescriptorsOnce, because that is called from all the
@@ -824,8 +919,8 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
"}\n"
"\n"
"void AddDescriptors() {\n"
" static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
" ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);\n"
" static ::google::protobuf::internal::once_flag once;\n"
" ::google::protobuf::internal::call_once(once, AddDescriptorsImpl);\n"
"}\n");
printer->Print(
@@ -840,47 +935,16 @@ void FileGenerator::GenerateReflectionInitializationCode(io::Printer* printer) {
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(
"void InitDefaults$scc_name$Impl() {\n"
"static void InitDefaults$scc_name$() {\n"
" GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n"
"#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n"
" ::google::protobuf::internal::InitProtobufDefaultsForceUnique();\n"
"#else\n"
" ::google::protobuf::internal::InitProtobufDefaults();\n"
"#endif // GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS\n",
// Force initialization of primitive values we depend on.
, // awkward comma due to macro
"scc_name", scc_name);
printer->Indent();
// Call the InitDefaults() methods for all of our dependencies, to make
// sure they get added first.
for (int i = 0; i < scc->children.size(); i++) {
const SCC* child_scc = scc->children[i];
const FileDescriptor* dependency = child_scc->GetRepresentative()->file();
// Print the namespace prefix for the dependency.
string file_namespace = FileLevelNamespace(dependency);
std::map<string, string> variables;
variables["file_namespace"] = file_namespace;
variables["scc_name"] = ClassName(child_scc->GetRepresentative(), false);
bool using_weak_fields = UsingImplicitWeakFields(file_, options_);
if (using_weak_fields) {
// We're building for lite with implicit weak fields, so we need to handle
// the possibility that this InitDefaults function is not linked into the
// binary. Some of these might actually be guaranteed to be non-null since
// we might have a strong reference to the dependency (via a required
// field, for example), but it's simplest to just assume that any of them
// could be null.
printer->Print(
variables,
"if (&$file_namespace$::InitDefaults$scc_name$ != NULL) {\n"
" $file_namespace$::InitDefaults$scc_name$();\n"
"}\n");
} else {
printer->Print(variables,
"$file_namespace$::InitDefaults$scc_name$();\n");
}
}
// First construct all the necessary default instances.
for (int i = 0; i < message_generators_.size(); i++) {
@@ -915,23 +979,24 @@ void FileGenerator::GenerateInitForSCC(const SCC* scc, io::Printer* printer) {
}
printer->Outdent();
printer->Print("}\n\n");
printer->Print(
"void InitDefaults$scc_name$() {\n"
" static GOOGLE_PROTOBUF_DECLARE_ONCE(once);\n"
" ::google::protobuf::GoogleOnceInit(&once, "
"&InitDefaults$scc_name$Impl);\n"
"}\n\n",
"scc_name", scc_name);
"$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::GenerateInitializationCode(io::Printer* printer) {
// Messages depend on the existence of a default instance, which has to
// initialized properly. The default instances are allocated in the data
// segment, but we can't quite allocate the type directly. The destructors
// cannot run at program exit as this could lead to segfaults in a threaded
// environment. Hence these instances must be inplace constructed at first
// use.
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.
@@ -1038,22 +1103,12 @@ void FileGenerator::GenerateInitializationCode(io::Printer* printer) {
"};\n"
"\n");
}
// -----------------------------------------------------------------
// All functionality that need private access.
// 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);
}
}
}
void FileGenerator::GenerateForwardDeclarations(io::Printer* printer) {
ForwardDeclarations decls;
FillForwardDeclarations(&decls);
decls.Print(printer, options_);
decls.PrintForwardDeclarations(printer, options_);
}
void FileGenerator::FillForwardDeclarations(ForwardDeclarations* decls) {
@@ -1078,8 +1133,8 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer,
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $filename$\n"
"\n"
"#ifndef PROTOBUF_$filename_identifier$__INCLUDED\n"
"#define PROTOBUF_$filename_identifier$__INCLUDED\n"
"#ifndef PROTOBUF_INCLUDED_$filename_identifier$\n"
"#define PROTOBUF_INCLUDED_$filename_identifier$\n"
"\n"
"#include <string>\n",
"filename", file_->name(), "filename_identifier", filename_identifier);
@@ -1089,7 +1144,7 @@ void FileGenerator::GenerateTopHeaderGuard(io::Printer* printer,
void FileGenerator::GenerateBottomHeaderGuard(
io::Printer* printer, const string& filename_identifier) {
printer->Print(
"#endif // PROTOBUF_$filename_identifier$__INCLUDED\n",
"#endif // PROTOBUF_INCLUDED_$filename_identifier$\n",
"filename_identifier", filename_identifier);
}
@@ -1126,7 +1181,9 @@ void FileGenerator::GenerateLibraryIncludes(io::Printer* printer) {
"#include <google/protobuf/arena.h>\n"
"#include <google/protobuf/arenastring.h>\n"
"#include <google/protobuf/generated_message_table_driven.h>\n"
"#include <google/protobuf/generated_message_util.h>\n");
"#include <google/protobuf/generated_message_util.h>\n"
"#include <google/protobuf/inlined_string_field.h>\n");
if (HasDescriptorMethods(file_, options_)) {
printer->Print(
@@ -1213,11 +1270,12 @@ void FileGenerator::GenerateDependencyIncludes(io::Printer* printer) {
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", StripProto(name),
"dependency", basename,
"iwyu", (public_import) ? " // IWYU pragma: export" : "",
"left", use_system_include ? "<" : "\"",
"right", use_system_include ? ">" : "\"");
@@ -1251,28 +1309,6 @@ void FileGenerator::GenerateGlobalStateFunctionDeclarations(
"void $dllexport_decl$AddDescriptors();\n", "dllexport_decl",
options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
}
for (int i = 0; i < message_generators_.size(); i++) {
if (!IsSCCRepresentative(message_generators_[i]->descriptor_)) continue;
string scc_name = ClassName(message_generators_[i]->descriptor_);
// TODO(gerbens) Remove the Impl from header. This is solely because
// it currently still needs to be a friend of the protos.
printer->Print(
"void $dllexport_decl$InitDefaults$scc_name$Impl();\n"
"void $dllexport_decl$InitDefaults$scc_name$();\n",
"scc_name", scc_name, "dllexport_decl",
options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
}
// TODO(gerbens) This is for proto1 interoperability. Remove when proto1
// is gone.
printer->Print(
"inline void $dllexport_decl$InitDefaults() {\n", "dllexport_decl",
options_.dllexport_decl.empty() ? "" : options_.dllexport_decl + " ");
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(" InitDefaults$scc_name$();\n", "scc_name", scc_name);
}
printer->Print("}\n");
printer->Print(
"} // namespace $file_namespace$\n",
"file_namespace", FileLevelNamespace(file_));
@@ -1349,8 +1385,6 @@ void FileGenerator::GenerateInlineFunctionDefinitions(io::Printer* printer) {
printer->Print(kThinSeparator);
printer->Print("\n");
}
// Methods of the dependent base class must always be inline in the header.
message_generators_[i]->GenerateDependentInlineMethods(printer);
}
}
@@ -37,9 +37,6 @@
#include <algorithm>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <set>
#include <string>
#include <vector>
@@ -97,7 +94,7 @@ class FileGenerator {
void GenerateSourceDefaultInstance(int idx, io::Printer* printer);
void GenerateInitForSCC(const SCC* scc, io::Printer* printer);
void GenerateInitializationCode(io::Printer* printer);
void GenerateTables(io::Printer* printer);
void GenerateReflectionInitializationCode(io::Printer* printer);
// For other imports, generates their forward-declarations.
@@ -176,10 +173,10 @@ class FileGenerator {
// These members are just for owning (and thus proper deleting).
// Nested (enum/extension)_generators are owned by child messages.
google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_owner_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<ServiceGenerator> >
std::unique_ptr<std::unique_ptr<EnumGenerator> []> enum_generators_owner_;
std::unique_ptr<std::unique_ptr<ServiceGenerator> []>
service_generators_owner_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> >
std::unique_ptr<std::unique_ptr<ExtensionGenerator> []>
extension_generators_owner_;
// E.g. if the package is foo.bar, package_parts_ is {"foo", "bar"}.
@@ -36,17 +36,15 @@
#include <vector>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <utility>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/compiler/cpp/cpp_file.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
@@ -66,12 +64,6 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// -----------------------------------------------------------------
// parse generator options
// TODO(kenton): If we ever have more options, we may want to create a
// class that encapsulates them which we can pass down to all the
// generator classes. Currently we pass dllexport_decl down to all of
// them via the constructors, but we don't want to have to add another
// constructor parameter for every option.
// 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
@@ -85,7 +77,6 @@ bool CppGenerator::Generate(const FileDescriptor* file,
// __declspec(dllimport) depending on what is being compiled.
//
Options file_options;
bool split_source = false;
for (int i = 0; i < options.size(); i++) {
if (options[i].first == "dllexport_decl") {
file_options.dllexport_decl = options[i].second;
@@ -101,28 +92,39 @@ bool CppGenerator::Generate(const FileDescriptor* file,
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 if (options[i].first == "split_source") {
split_source = 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) {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".proto.h"));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
@@ -134,14 +136,14 @@ bool CppGenerator::Generate(const FileDescriptor* file,
file_generator.GenerateProtoHeader(
&printer, file_options.annotate_headers ? info_path : "");
if (file_options.annotate_headers) {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
std::unique_ptr<io::ZeroCopyOutputStream> info_output(
generator_context->Open(info_path));
annotations.SerializeToZeroCopyStream(info_output.get());
}
}
{
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".pb.h"));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
@@ -153,30 +155,44 @@ bool CppGenerator::Generate(const FileDescriptor* file,
file_generator.GeneratePBHeader(
&printer, file_options.annotate_headers ? info_path : "");
if (file_options.annotate_headers) {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
std::unique_ptr<io::ZeroCopyOutputStream> info_output(
generator_context->Open(info_path));
annotations.SerializeToZeroCopyStream(info_output.get());
}
}
// Generate cc file.
if (split_source) {
// Generate cc file(s).
if (UsingImplicitWeakFields(file, file_options)) {
{
// This is the global .cc file, containing enum/services/tables/reflection
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".pb.cc"));
io::Printer printer(output.get(), '$');
file_generator.GenerateGlobalSource(&printer);
}
for (int i = 0; i < file_generator.NumMessages(); i++) {
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.
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + "." + SimpleItoa(i) + ".cc"));
io::Printer printer(output.get(), '$');
file_generator.GenerateSourceForMessage(i, &printer);
if (i < file_generator.NumMessages()) {
file_generator.GenerateSourceForMessage(i, &printer);
}
}
} else {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".pb.cc"));
io::Printer printer(output.get(), '$');
file_generator.GenerateSource(&printer);
@@ -42,6 +42,7 @@
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
@@ -73,7 +74,7 @@ const char* const kKeywordList[] = {
"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", "NULL",
"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",
@@ -219,24 +220,12 @@ string ReferenceFunctionName(const Descriptor* descriptor) {
return QualifiedClassName(descriptor) + "_ReferenceStrong";
}
string DependentBaseClassTemplateName(const Descriptor* descriptor) {
return ClassName(descriptor, false) + "_InternalBase";
}
string SuperClassName(const Descriptor* descriptor, const Options& options) {
return HasDescriptorMethods(descriptor->file(), options)
? "::google::protobuf::Message"
: "::google::protobuf::MessageLite";
}
string DependentBaseDownCast() {
return "reinterpret_cast<T*>(this)->";
}
string DependentBaseConstDownCast() {
return "reinterpret_cast<const T*>(this)->";
}
string FieldName(const FieldDescriptor* field) {
string result = field->name();
LowerString(&result);
@@ -294,60 +283,6 @@ string FieldConstantName(const FieldDescriptor *field) {
return result;
}
bool IsFieldDependent(const FieldDescriptor* field) {
if (field->containing_oneof() != NULL &&
field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
return true;
}
if (field->is_map()) {
const Descriptor* map_descriptor = field->message_type();
for (int i = 0; i < map_descriptor->field_count(); i++) {
if (IsFieldDependent(map_descriptor->field(i))) {
return true;
}
}
return false;
}
if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
return false;
}
if (field->containing_oneof() != NULL) {
// Oneof fields will always be dependent.
//
// This is a unique case for field codegen. Field generators are
// responsible for generating all the field-specific accessor
// functions, except for the clear_*() function; instead, field
// generators produce inline clearing code.
//
// For non-oneof fields, the Message class uses the inline clearing
// code to define the field's clear_*() function, as well as in the
// destructor. For oneof fields, the Message class generates a much
// more complicated clear_*() function, which clears only the oneof
// member that is set, in addition to clearing methods for each of the
// oneof members individually.
//
// Since oneofs do not have their own generator class, the Message code
// generation logic would be significantly complicated in order to
// split dependent and non-dependent manipulation logic based on
// whether the oneof truly needs to be dependent; so, for oneof fields,
// we just assume it (and its constituents) should be manipulated by a
// dependent base class function.
//
// This is less precise than how dependent message-typed fields are
// handled, but the cost is limited to only the generated code for the
// oneof field, which seems like an acceptable tradeoff.
return true;
}
if (field->file() == field->message_type()->file()) {
return false;
}
return true;
}
string DependentTypeName(const FieldDescriptor* field) {
return "InternalBase_" + field->name() + "_T";
}
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.
@@ -748,12 +683,17 @@ bool UsingImplicitWeakFields(const FileDescriptor* file,
GetOptimizeFor(file, options) == FileOptions::LITE_RUNTIME;
}
bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options) {
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_repeated() && !field->is_map() &&
field->containing_oneof() == NULL;
!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 {
@@ -920,6 +860,7 @@ void ListAllTypesForServices(const FileDescriptor* fd,
}
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
@@ -38,8 +38,9 @@
#include <map>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_options.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
@@ -53,6 +54,7 @@ namespace cpp {
extern const char kThickSeparator[];
extern const char kThinSeparator[];
// Name space of the proto file. This namespace is such that the string
// "<namespace>::some_name" is the correct fully qualified namespace.
// This means if the package is empty the namespace is "", and otherwise
@@ -102,19 +104,9 @@ string DefaultInstanceName(const Descriptor* descriptor);
// fields.
string ReferenceFunctionName(const Descriptor* descriptor);
// Name of the CRTP class template (for use with proto_h).
// This is a class name, like "ProtoName_InternalBase".
string DependentBaseClassTemplateName(const Descriptor* descriptor);
// Name of the base class: either the dependent base class (for use with
// proto_h) or google::protobuf::Message.
// Name of the base class: google::protobuf::Message or google::protobuf::MessageLite.
string SuperClassName(const Descriptor* descriptor, const Options& options);
// Returns a string that down-casts from the dependent base class to the
// derived class.
string DependentBaseDownCast();
string DependentBaseConstDownCast();
// 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
@@ -141,20 +133,6 @@ inline const Descriptor* FieldScope(const FieldDescriptor* field) {
field->extension_scope() : field->containing_type();
}
// Returns true if the given 'field_descriptor' has a message type that is
// a dependency of the file where the field is defined (i.e., the field
// type is defined in a different file than the message holding the field).
//
// This only applies to Message-typed fields. Enum-typed fields may refer
// to an enum in a dependency; however, enums are specified and
// forward-declared with an enum-base, so the definition is not required to
// manipulate the field value.
bool IsFieldDependent(const FieldDescriptor* field_descriptor);
// Returns the name that should be used for forcing dependent lookup from a
// dependent base class.
string DependentTypeName(const FieldDescriptor* field);
// Returns the fully-qualified type name field->message_type(). Usually this
// is just ClassName(field->message_type(), true);
string FieldMessageTypeName(const FieldDescriptor* field);
@@ -310,6 +288,15 @@ 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) {
return "_i_give_permission_to_break_this_code_default_" + FieldName(field) +
"_";
}
bool IsAnyMessage(const FileDescriptor* descriptor);
bool IsAnyMessage(const Descriptor* descriptor);
@@ -346,13 +333,6 @@ inline std::vector<const Descriptor*> FlattenMessagesInFile(
bool HasWeakFields(const Descriptor* desc);
bool HasWeakFields(const FileDescriptor* desc);
// Indicates whether we should use implicit weak fields for this file.
bool UsingImplicitWeakFields(const FileDescriptor* file,
const Options& options);
// Indicates whether to treat this field as implicitly weak.
bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options);
// Returns true if the "required" restriction check should be ignored for the
// given field.
inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field,
@@ -458,11 +438,21 @@ class LIBPROTOC_EXPORT SCCAnalyzer {
void AddChildren(SCC* scc);
};
void ListAllFields(const Descriptor* d,
std::vector<const FieldDescriptor*>* fields);
void ListAllFields(const FileDescriptor* d,
std::vector<const FieldDescriptor*>* fields);
void ListAllTypesForServices(const FileDescriptor* fd,
std::vector<const Descriptor*>* types);
// Indicates whether we should use implicit weak fields for this file.
bool UsingImplicitWeakFields(const FileDescriptor* file,
const Options& options);
// Indicates whether to treat this field as implicitly weak.
bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options,
SCCAnalyzer* scc_analyzer);
} // namespace cpp
} // namespace compiler
} // namespace protobuf
@@ -104,9 +104,7 @@ void SetMessageVariables(const FieldDescriptor* descriptor,
MapFieldGenerator::MapFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: FieldGenerator(options),
descriptor_(descriptor),
dependent_field_(options.proto_h && IsFieldDependent(descriptor)) {
: FieldGenerator(options), descriptor_(descriptor) {
SetMessageVariables(descriptor, &variables_, options);
}
@@ -202,7 +200,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
key = "entry->key()";
value = "entry->value()";
printer->Print(variables_,
"::google::protobuf::scoped_ptr<$map_classname$> entry($name$_.NewEntry());\n");
"::std::unique_ptr<$map_classname$> entry($name$_.NewEntry());\n");
printer->Print(variables_,
"{\n"
" ::std::string data;\n"
@@ -258,7 +256,7 @@ static void GenerateSerializationLoop(io::Printer* printer,
const string& ptr,
bool loop_via_iterators) {
printer->Print(variables,
StrCat("::google::protobuf::scoped_ptr<$map_classname$> entry;\n",
StrCat("::std::unique_ptr<$map_classname$> entry;\n",
loop_header, " {\n").c_str());
printer->Indent();
@@ -365,7 +363,7 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes(
"\n"
"if ($deterministic$ &&\n"
" this->$name$().size() > 1) {\n"
" ::google::protobuf::scoped_array<SortItem> items(\n"
" ::std::unique_ptr<SortItem[]> 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"
@@ -402,7 +400,7 @@ GenerateByteSize(io::Printer* printer) const {
"total_size += $tag_size$ *\n"
" ::google::protobuf::internal::FromIntSize(this->$name$_size());\n"
"{\n"
" ::google::protobuf::scoped_ptr<$map_classname$> entry;\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");
@@ -66,7 +66,6 @@ class MapFieldGenerator : public FieldGenerator {
io::Printer* printer, const std::map<string, string>& variables) const;
const FieldDescriptor* descriptor_;
const bool dependent_field_;
std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MapFieldGenerator);
File diff suppressed because it is too large. Load diff
@@ -36,9 +36,6 @@
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_H__
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <set>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_field.h>
@@ -87,9 +84,6 @@ class MessageGenerator {
// file).
void GenerateInlineMethods(io::Printer* printer);
// Dependent methods are always inline.
void GenerateDependentInlineMethods(io::Printer* printer);
// Source file stuff.
// Generate extra fields
@@ -106,12 +100,12 @@ class MessageGenerator {
// 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 GenerateDependentBaseClassDefinition(io::Printer* printer);
void GenerateDependentFieldAccessorDeclarations(io::Printer* printer);
void GenerateFieldAccessorDeclarations(io::Printer* printer);
void GenerateDependentFieldAccessorDefinitions(io::Printer* printer);
void GenerateFieldAccessorDefinitions(io::Printer* printer);
// Generate the table-driven parsing array. Returns the number of entries
@@ -219,15 +213,14 @@ class MessageGenerator {
std::vector<const FieldDescriptor *> optimized_order_;
std::vector<int> has_bit_indices_;
int max_has_bit_index_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > extension_generators_;
std::unique_ptr<std::unique_ptr<EnumGenerator> []> enum_generators_;
std::unique_ptr<std::unique_ptr<ExtensionGenerator> []> extension_generators_;
int num_required_fields_;
bool use_dependent_base_;
int num_weak_fields_;
// table_driven_ indicates the generated message uses table-driven parsing.
bool table_driven_;
google::protobuf::scoped_ptr<MessageLayoutHelper> message_layout_helper_;
std::unique_ptr<MessageLayoutHelper> message_layout_helper_;
SCCAnalyzer* scc_analyzer_;
string scc_name_;
File diff suppressed because it is too large. Load diff
@@ -38,25 +38,22 @@
#include <map>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options);
class MessageFieldGenerator : public FieldGenerator {
public:
MessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
const Options& options, SCCAnalyzer* scc_analyzer);
~MessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
@@ -73,7 +70,6 @@ class MessageFieldGenerator : public FieldGenerator {
protected:
const FieldDescriptor* descriptor_;
const bool dependent_field_;
const bool implicit_weak_field_;
std::map<string, string> variables_;
@@ -84,11 +80,10 @@ class MessageFieldGenerator : public FieldGenerator {
class MessageOneofFieldGenerator : public MessageFieldGenerator {
public:
MessageOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
const Options& options, SCCAnalyzer* scc_analyzer);
~MessageOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
@@ -101,24 +96,19 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
void GenerateConstructorCode(io::Printer* printer) const;
private:
void InternalGenerateInlineAccessorDefinitions(
const std::map<string, string>& variables, io::Printer* printer) const;
const bool dependent_base_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageOneofFieldGenerator);
};
class RepeatedMessageFieldGenerator : public FieldGenerator {
public:
RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor,
const Options& options);
const Options& options,
SCCAnalyzer* scc_analyzer);
~RepeatedMessageFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
@@ -131,12 +121,8 @@ class RepeatedMessageFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
private:
void InternalGenerateTypeDependentAccessorDeclarations(
io::Printer* printer) const;
const FieldDescriptor* descriptor_;
const bool dependent_field_;
const bool dependent_getter_;
const bool implicit_weak_field_;
std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator);
@@ -34,7 +34,7 @@
#include <gtest/gtest.h>
#if LANG_CXX11
#include <google/protobuf/stubs/type_traits.h>
#include <type_traits>
#endif
namespace google {
@@ -54,6 +54,8 @@ struct Options {
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;
@@ -65,6 +67,8 @@ struct Options {
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;
@@ -50,10 +50,10 @@ namespace cpp {
class PaddingOptimizer : public MessageLayoutHelper {
public:
PaddingOptimizer() {}
~PaddingOptimizer() {}
~PaddingOptimizer() override {}
void OptimizeLayout(std::vector<const FieldDescriptor*>* fields,
const Options& options);
const Options& options) override;
};
} // namespace cpp
@@ -35,9 +35,6 @@
// worth.
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
@@ -172,7 +169,7 @@ class TestGenerator : public CodeGenerator {
void TryInsert(const string& filename, const string& insertion_point,
GeneratorContext* context) const {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
context->OpenForInsert(filename, insertion_point));
io::Printer printer(output.get(), '$');
printer.Print("// inserted $name$\n", "name", insertion_point);
@@ -215,7 +215,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_;\n"
" return $field_member$;\n"
" }\n"
" return $default$;\n"
"}\n"
@@ -224,14 +224,14 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" }\n"
" $oneof_prefix$$name$_ = value;\n"
" $field_member$ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n");
}
void PrimitiveOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
printer->Print(variables_, "$oneof_prefix$$name$_ = $default$;\n");
printer->Print(variables_, "$field_member$ = $default$;\n");
}
void PrimitiveOneofFieldGenerator::
@@ -251,7 +251,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
"clear_$oneof_name$();\n"
"DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
" $type$, $wire_format_field_type$>(\n"
" input, &$oneof_prefix$$name$_)));\n"
" input, &$field_member$)));\n"
"set_has_$name$();\n");
}
@@ -34,8 +34,8 @@
#include <google/protobuf/compiler/cpp/cpp_string_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
@@ -53,7 +53,7 @@ void SetStringVariables(const FieldDescriptor* descriptor,
(*variables)["default"] = DefaultValue(descriptor);
(*variables)["default_length"] =
SimpleItoa(descriptor->default_value_string().length());
string default_variable_string = "_default_" + FieldName(descriptor) + "_";
string default_variable_string = MakeDefaultName(descriptor);
(*variables)["default_variable_name"] = default_variable_string;
(*variables)["default_variable"] =
descriptor->default_value_string().empty()
@@ -82,8 +82,24 @@ void SetStringVariables(const FieldDescriptor* descriptor,
StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: FieldGenerator(options), descriptor_(descriptor),
lite_(!HasDescriptorMethods(descriptor->file(), 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);
}
@@ -91,27 +107,36 @@ StringFieldGenerator::~StringFieldGenerator() {}
void StringFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
// 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");
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");
" $default_variable_name$;\n"
"private:\n");
}
}
@@ -246,9 +271,23 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n"
"}\n"
"inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_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$_.Release($default_variable$, GetArenaNoVirtual());\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"
@@ -322,9 +361,22 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" return $name$_.MutableNoArena($default_variable$);\n"
"}\n"
"inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_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$_.ReleaseNoArena($default_variable$);\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"
@@ -343,7 +395,7 @@ GenerateNonInlineAccessorDefinitions(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
// Initialized in GenerateDefaultInstanceAllocator.
printer->Print(variables_,
"::google::protobuf::internal::ExplicitlyConstructed< ::std::string> "
"::google::protobuf::internal::ExplicitlyConstructed<::std::string> "
"$classname$::$default_variable_name$;\n");
}
}
@@ -383,18 +435,34 @@ GenerateMessageClearingCode(io::Printer* printer) const {
// 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());
const bool must_be_present =
HasFieldPresence(descriptor_->file());
if (must_be_present) {
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()) {
printer->Print(variables_,
"$name$_.ClearToEmpty($default_variable$, GetArenaNoVirtual());\n");
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");
}
@@ -402,11 +470,11 @@ GenerateMessageClearingCode(io::Printer* printer) const {
// 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$_.UnsafeRawStringPointer())->clear();\n");
printer->Print(variables_, "$name$_.ClearNonDefaultToEmptyNoArena();\n");
} else {
printer->Print(variables_,
"(*$name$_.UnsafeRawStringPointer())->assign(*$default_variable$);\n");
printer->Print(
variables_,
"$name$_.UnsafeMutablePointer()->assign(*$default_variable$);\n");
}
} else {
if (descriptor_->default_value_string().empty()) {
@@ -433,13 +501,29 @@ GenerateMergingCode(io::Printer* printer) const {
void StringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.Swap(&other->$name$_);\n");
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");
"$name$_.UnsafeSetDefault($default_variable$);\n");
}
void StringFieldGenerator::
@@ -472,8 +556,23 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
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_,
"$name$_.DestroyNoArena($default_variable$);\n");
"_this->$name$_.DestroyNoArena($default_variable$);\n");
return true;
}
void StringFieldGenerator::
@@ -504,6 +603,11 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
}
}
bool StringFieldGenerator::
MergeFromCodedStreamNeedsArena() const {
return false;
}
void StringFieldGenerator::
GenerateSerializeWithCachedSizes(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
@@ -539,13 +643,17 @@ GenerateByteSize(io::Printer* printer) const {
" this->$name$());\n");
}
uint32 StringFieldGenerator::CalculateFieldTag() const {
return inlined_ ? 1 : 0;
}
// ===================================================================
StringOneofFieldGenerator::
StringOneofFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: StringFieldGenerator(descriptor, options),
dependent_field_(options.proto_h) {
StringOneofFieldGenerator::StringOneofFieldGenerator(
const FieldDescriptor* descriptor, const Options& options)
: StringFieldGenerator(descriptor, options) {
inlined_ = false;
SetCommonOneofFieldVariables(descriptor, &variables_);
}
@@ -559,7 +667,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_.Get();\n"
" return $field_member$.Get();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
@@ -567,9 +675,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.Set$lite$($default_variable$, value,\n"
" $field_member$.Set$lite$($default_variable$, value,\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
@@ -579,9 +687,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.Set$lite$(\n"
" $field_member$.Set$lite$(\n"
" $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
@@ -591,9 +699,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.Set$lite$($default_variable$,\n"
" $field_member$.Set$lite$($default_variable$,\n"
" $string_piece$(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
@@ -603,9 +711,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.Set$lite$(\n"
" $field_member$.Set$lite$(\n"
" $default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size),\n"
" GetArenaNoVirtual());\n"
@@ -615,9 +723,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" return $oneof_prefix$$name$_.Mutable($default_variable$,\n"
" return $field_member$.Mutable($default_variable$,\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
"}\n"
@@ -625,7 +733,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
" return $oneof_prefix$$name$_.Release($default_variable$,\n"
" return $field_member$.Release($default_variable$,\n"
" GetArenaNoVirtual());\n"
" } else {\n"
" return NULL;\n"
@@ -633,12 +741,12 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"}\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" clear_$oneof_name$();\n"
" if ($name$ != NULL) {\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.SetAllocated($default_variable$, $name$,\n"
" $field_member$.SetAllocated($default_variable$, $name$,\n"
" GetArenaNoVirtual());\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
@@ -649,7 +757,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
" return $oneof_prefix$$name$_.UnsafeArenaRelease(\n"
" return $field_member$.UnsafeArenaRelease(\n"
" $default_variable$, GetArenaNoVirtual());\n"
" } else {\n"
" return NULL;\n"
@@ -659,12 +767,12 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"::std::string* $name$) {\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (!has_$name$()) {\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" clear_$oneof_name$();\n"
" if ($name$) {\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeArenaSetAllocated($default_variable$, "
" $field_member$.UnsafeArenaSetAllocated($default_variable$, "
"$name$, GetArenaNoVirtual());\n"
" }\n"
" // @@protoc_insertion_point(field_unsafe_arena_set_allocated:"
@@ -677,7 +785,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
"inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_.GetNoArena();\n"
" return $field_member$.GetNoArena();\n"
" }\n"
" return *$default_variable$;\n"
"}\n"
@@ -686,9 +794,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.SetNoArena($default_variable$, value);\n"
" $field_member$.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
@@ -697,10 +805,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.SetNoArena(\n"
" $default_variable$, ::std::move(value));\n"
" $field_member$.SetNoArena($default_variable$, ::std::move(value));\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
@@ -709,9 +816,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.SetNoArena($default_variable$,\n"
" $field_member$.SetNoArena($default_variable$,\n"
" $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
@@ -721,10 +828,9 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.SetNoArena($default_variable$, "
"$string_piece$(\n"
" $field_member$.SetNoArena($default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
@@ -732,29 +838,28 @@ GenerateInlineAccessorDefinitions(io::Printer* printer) const {
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $oneof_prefix$$name$_.MutableNoArena($default_variable$);\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 $oneof_prefix$$name$_.ReleaseNoArena($default_variable$);\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"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" $field_member$.UnsafeSetDefault($default_variable$);\n"
" }\n"
" clear_$oneof_name$();\n"
" if ($name$ != NULL) {\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.SetAllocatedNoArena($default_variable$,\n"
" $name$);\n"
" $field_member$.SetAllocatedNoArena($default_variable$, $name$);\n"
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n");
@@ -765,12 +870,11 @@ void StringOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(variables_,
"$oneof_prefix$$name$_.Destroy($default_variable$,\n"
"$field_member$.Destroy($default_variable$,\n"
" GetArenaNoVirtual());\n");
} else {
printer->Print(variables_,
"$oneof_prefix$$name$_."
"DestroyNoArena($default_variable$);\n");
"$field_member$.DestroyNoArena($default_variable$);\n");
}
}
@@ -796,7 +900,7 @@ void StringOneofFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
printer->Print(variables_,
"if (has_$name$()) {\n"
" $oneof_prefix$$name$_.DestroyNoArena($default_variable$);\n"
" $field_member$.DestroyNoArena($default_variable$);\n"
"}\n");
}
@@ -912,11 +1016,21 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
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 const ::std::string& $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.$cppget$(index);\n"
"}\n"
"inline ::std::string* $classname$::mutable_$name$(int index) {\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
@@ -991,7 +1105,8 @@ GenerateMergingCode(io::Printer* printer) const {
void RepeatedStringFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "$name$_.InternalSwap(&other->$name$_);\n");
printer->Print(variables_,
"$name$_.InternalSwap(CastToBase(&other->$name$_));\n");
}
void RepeatedStringFieldGenerator::
@@ -63,16 +63,22 @@ class StringFieldGenerator : public FieldGenerator {
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<string, string> variables_;
const bool lite_;
bool inlined_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
@@ -97,7 +103,6 @@ class StringOneofFieldGenerator : public StringFieldGenerator {
void GenerateMergeFromCodedStream(io::Printer* printer) const;
private:
const bool dependent_field_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOneofFieldGenerator);
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -29,9 +29,6 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
@@ -72,9 +69,7 @@ class CppMetadataTest : public ::testing::Test {
TestTempDir();
const bool result =
atu::CaptureMetadata(filename, cpp_out,
/* meta_file_suffix */ "", &cli, file,
/* outputs */ NULL);
atu::RunProtoCompiler(filename, cpp_out, &cli, file);
if (!result) {
return result;
@@ -56,7 +56,7 @@ void WriteDocCommentBodyImpl(io::Printer* printer, SourceLocation location) {
// node of a summary element, not part of an attribute.
comments = StringReplace(comments, "&", "&amp;", true);
comments = StringReplace(comments, "<", "&lt;", true);
vector<string> lines = Split(comments, "\n", false /* skip_empty */);
std::vector<string> 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("/// <summary>\n");
@@ -43,8 +43,6 @@
#include <google/protobuf/compiler/csharp/csharp_helpers.h>
#include <google/protobuf/compiler/csharp/csharp_options.h>
using google::protobuf::internal::scoped_ptr;
namespace google {
namespace protobuf {
namespace compiler {
@@ -46,8 +46,6 @@
#include <google/protobuf/compiler/csharp/csharp_helpers.h>
#include <google/protobuf/compiler/csharp/csharp_names.h>
using google::protobuf::internal::scoped_ptr;
namespace google {
namespace protobuf {
namespace compiler {
@@ -44,8 +44,6 @@
#include <google/protobuf/compiler/csharp/csharp_options.h>
#include <google/protobuf/compiler/csharp/csharp_reflection_class.h>
using google::protobuf::internal::scoped_ptr;
namespace google {
namespace protobuf {
namespace compiler {
@@ -64,7 +62,7 @@ bool Generator::Generate(
GeneratorContext* generator_context,
string* error) const {
vector<pair<string, string> > options;
std::vector<std::pair<string, string> > options;
ParseGeneratorParameter(parameter, &options);
// We only support proto3 - but we make an exception for descriptor.proto.
@@ -100,7 +98,7 @@ bool Generator::Generate(
*error = filename_error;
return false;
}
scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(filename));
io::Printer printer(output.get(), '$');
@@ -63,9 +63,9 @@ void MapFieldGenerator::GenerateMembers(io::Printer* printer) {
descriptor_->message_type()->FindFieldByName("value");
variables_["key_type_name"] = type_name(key_descriptor);
variables_["value_type_name"] = type_name(value_descriptor);
scoped_ptr<FieldGeneratorBase> key_generator(
std::unique_ptr<FieldGeneratorBase> key_generator(
CreateFieldGenerator(key_descriptor, 1, this->options()));
scoped_ptr<FieldGeneratorBase> value_generator(
std::unique_ptr<FieldGeneratorBase> value_generator(
CreateFieldGenerator(value_descriptor, 2, this->options()));
printer->Print(
@@ -49,8 +49,6 @@
#include <google/protobuf/compiler/csharp/csharp_message.h>
#include <google/protobuf/compiler/csharp/csharp_names.h>
using google::protobuf::internal::scoped_ptr;
namespace google {
namespace protobuf {
namespace compiler {
@@ -111,7 +109,7 @@ void MessageGenerator::Generate(io::Printer* printer) {
WriteMessageDocComment(printer, descriptor_);
AddDeprecatedFlag(printer);
printer->Print(
vars,
"$access_level$ sealed partial class $class_name$ : pb::IMessage<$class_name$> {\n");
@@ -119,14 +117,17 @@ void MessageGenerator::Generate(io::Printer* printer) {
// 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");
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");
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()) {
@@ -139,14 +140,14 @@ void MessageGenerator::Generate(io::Printer* printer) {
WriteGeneratedCodeAttributes(printer);
printer->Print(
vars,
"public static pbr::MessageDescriptor Descriptor {\n"
" get { return $descriptor_accessor$; }\n"
"}\n"
"\n");
vars,
"public static pbr::MessageDescriptor Descriptor {\n"
" get { return $descriptor_accessor$; }\n"
"}\n"
"\n");
WriteGeneratedCodeAttributes(printer);
printer->Print(
vars,
vars,
"pbr::MessageDescriptor pb::IMessage.Descriptor {\n"
" get { return Descriptor; }\n"
"}\n"
@@ -181,7 +182,7 @@ void MessageGenerator::Generate(io::Printer* printer) {
"field_name", fieldDescriptor->name(),
"field_constant_name", GetFieldConstantName(fieldDescriptor),
"index", SimpleItoa(fieldDescriptor->number()));
scoped_ptr<FieldGeneratorBase> generator(
std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(fieldDescriptor));
generator->GenerateMembers(printer);
printer->Print("\n");
@@ -209,18 +210,18 @@ void MessageGenerator::Generate(io::Printer* printer) {
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,
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"
@@ -290,7 +291,7 @@ void MessageGenerator::GenerateCloningCode(io::Printer* printer) {
// Clone non-oneof fields first
for (int i = 0; i < descriptor_->field_count(); i++) {
if (!descriptor_->field(i)->containing_oneof()) {
scoped_ptr<FieldGeneratorBase> generator(
std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->GenerateCloningCode(printer);
}
@@ -304,7 +305,7 @@ void MessageGenerator::GenerateCloningCode(io::Printer* printer) {
printer->Indent();
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
scoped_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
vars["field_property_name"] = GetPropertyName(field);
printer->Print(
vars,
@@ -317,6 +318,9 @@ void MessageGenerator::GenerateCloningCode(io::Printer* printer) {
printer->Outdent();
printer->Print("}\n\n");
}
// Clone unknown fields
printer->Print(
"_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);\n");
printer->Outdent();
printer->Print("}\n\n");
@@ -337,15 +341,15 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) {
vars["class_name"] = class_name();
// Equality
WriteGeneratedCodeAttributes(printer);
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,
WriteGeneratedCodeAttributes(printer);
printer->Print(
vars,
"public bool Equals($class_name$ other) {\n"
" if (ReferenceEquals(other, null)) {\n"
" return false;\n"
@@ -355,7 +359,7 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) {
" }\n");
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
scoped_ptr<FieldGeneratorBase> generator(
std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->WriteEquals(printer);
}
@@ -365,18 +369,18 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) {
}
printer->Outdent();
printer->Print(
" return true;\n"
" 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(
WriteGeneratedCodeAttributes(printer);
printer->Print(
"public override int GetHashCode() {\n"
" int hash = 1;\n");
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
scoped_ptr<FieldGeneratorBase> generator(
std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->WriteHash(printer);
}
@@ -384,12 +388,16 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) {
printer->Print("hash ^= (int) $name$Case_;\n",
"name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false));
}
printer->Print("return hash;\n");
printer->Print(
"if (_unknownFields != null) {\n"
" hash ^= _unknownFields.GetHashCode();\n"
"}\n"
"return hash;\n");
printer->Outdent();
printer->Print("}\n\n");
WriteGeneratedCodeAttributes(printer);
printer->Print(
WriteGeneratedCodeAttributes(printer);
printer->Print(
"public override string ToString() {\n"
" return pb::JsonFormatter.ToDiagnosticString(this);\n"
"}\n\n");
@@ -403,26 +411,38 @@ void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer)
// Serialize all the fields
for (int i = 0; i < fields_by_number().size(); i++) {
scoped_ptr<FieldGeneratorBase> generator(
std::unique_ptr<FieldGeneratorBase> 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");
"}\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++) {
scoped_ptr<FieldGeneratorBase> generator(
std::unique_ptr<FieldGeneratorBase> 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");
@@ -447,7 +467,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
// Merge non-oneof fields
for (int i = 0; i < descriptor_->field_count(); i++) {
if (!descriptor_->field(i)->containing_oneof()) {
scoped_ptr<FieldGeneratorBase> generator(
std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(descriptor_->field(i)));
generator->GenerateMergingCode(printer);
}
@@ -465,7 +485,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
vars,
"case $property_name$OneofCase.$field_property_name$:\n");
printer->Indent();
scoped_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
generator->GenerateMergingCode(printer);
printer->Print("break;\n");
printer->Outdent();
@@ -473,8 +493,14 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
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();
@@ -486,14 +512,14 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
printer->Indent();
// Option messages need to store unknown fields so that options can be parsed later.
if (IsDescriptorOptionMessage(descriptor_)) {
printer->Print(
printer->Print(
"default:\n"
" CustomOptions = CustomOptions.ReadOrSkipUnknownField(input);\n"
" break;\n");
} else {
printer->Print(
"default:\n"
" input.SkipLastField();\n" // We're not storing the data, but we still need to consume it.
" _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);\n"
" break;\n");
}
for (int i = 0; i < fields_by_number().size(); i++) {
@@ -518,7 +544,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
printer->Print("case $tag$: {\n", "tag", SimpleItoa(tag));
printer->Indent();
scoped_ptr<FieldGeneratorBase> generator(
std::unique_ptr<FieldGeneratorBase> generator(
CreateFieldGeneratorInternal(field));
generator->GenerateParsingCode(printer);
printer->Print("break;\n");
@@ -133,7 +133,7 @@ void MessageFieldGenerator::WriteToString(io::Printer* printer) {
void MessageFieldGenerator::GenerateCloningCode(io::Printer* printer) {
printer->Print(variables_,
"$property_name$ = other.$has_property_check$ ? other.$property_name$.Clone() : null;\n");
"$name$_ = other.$has_property_check$ ? other.$name$_.Clone() : null;\n");
}
void MessageFieldGenerator::GenerateFreezingCode(io::Printer* printer) {
@@ -137,14 +137,22 @@ void PrimitiveFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) {
}
void PrimitiveFieldGenerator::WriteHash(io::Printer* printer) {
printer->Print(
variables_,
"if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n");
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) {
printer->Print(
variables_,
"if ($property_name$ != other.$property_name$) return false;\n");
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(
@@ -104,8 +104,10 @@ void ReflectionClassGenerator::Generate(io::Printer* printer) {
void ReflectionClassGenerator::WriteIntroduction(io::Printer* printer) {
printer->Print(
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $file_name$\n"
"// <auto-generated>\n"
"// Generated by the protocol buffer compiler. DO NOT EDIT!\n"
"// source: $file_name$\n"
"// </auto-generated>\n"
"#pragma warning disable 1591, 0612, 3021\n"
"#region Designer generated code\n"
"\n"
@@ -66,11 +66,11 @@ void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) {
// "create single field generator for this repeated field"
// function, but it doesn't seem worth it for just this.
if (IsWrapperType(descriptor_)) {
scoped_ptr<FieldGeneratorBase> single_generator(
std::unique_ptr<FieldGeneratorBase> single_generator(
new WrapperFieldGenerator(descriptor_, fieldOrdinal_, this->options()));
single_generator->GenerateCodecCode(printer);
} else {
scoped_ptr<FieldGeneratorBase> single_generator(
std::unique_ptr<FieldGeneratorBase> single_generator(
new MessageFieldGenerator(descriptor_, fieldOrdinal_, this->options()));
single_generator->GenerateCodecCode(printer);
}
@@ -120,15 +120,25 @@ void WrapperFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) {
}
void WrapperFieldGenerator::WriteHash(io::Printer* printer) {
printer->Print(
variables_,
"if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n");
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) {
printer->Print(
variables_,
"if ($property_name$ != other.$property_name$) return false;\n");
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) {
@@ -32,7 +32,6 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifdef _MSC_VER
#include <direct.h>
#else
@@ -45,9 +44,6 @@
#include <algorithm>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/compiler/importer.h>
@@ -55,6 +51,8 @@
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/io_win32.h>
#ifdef _WIN32
@@ -131,7 +129,7 @@ SourceTreeDescriptorDatabase::~SourceTreeDescriptorDatabase() {}
bool SourceTreeDescriptorDatabase::FindFileByName(
const string& filename, FileDescriptorProto* output) {
google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_->Open(filename));
std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_->Open(filename));
if (input == NULL) {
if (error_collector_ != NULL) {
error_collector_->AddError(filename, -1, 0,
@@ -420,7 +418,7 @@ DiskSourceTree::DiskFileToVirtualFile(
// 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.
google::protobuf::scoped_ptr<io::ZeroCopyInputStream> stream(OpenDiskFile(disk_file));
std::unique_ptr<io::ZeroCopyInputStream> stream(OpenDiskFile(disk_file));
if (stream == NULL) {
return CANNOT_OPEN;
}
@@ -430,7 +428,7 @@ DiskSourceTree::DiskFileToVirtualFile(
bool DiskSourceTree::VirtualFileToDiskFile(const string& virtual_file,
string* disk_file) {
google::protobuf::scoped_ptr<io::ZeroCopyInputStream> stream(
std::unique_ptr<io::ZeroCopyInputStream> stream(
OpenVirtualFile(virtual_file, disk_file));
return stream != NULL;
}
@@ -36,9 +36,6 @@
#include <google/protobuf/stubs/hash.h>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -268,7 +265,7 @@ class DiskSourceTreeTest : public testing::Test {
void ExpectFileContents(const string& filename,
const char* expected_contents) {
google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
ASSERT_FALSE(input == NULL);
@@ -285,7 +282,7 @@ class DiskSourceTreeTest : public testing::Test {
void ExpectCannotOpenFile(const string& filename,
const string& error_message) {
google::protobuf::scoped_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
std::unique_ptr<io::ZeroCopyInputStream> input(source_tree_.Open(filename));
EXPECT_TRUE(input == NULL);
EXPECT_EQ(error_message, source_tree_.GetLastErrorMessage());
}
@@ -69,14 +69,14 @@ bool IsConflicting(const FieldDescriptor* field1, const string& name1,
// field1 is repeated, and field2 is not.
if (name1 + "Count" == name2) {
*info = "both repeated field \"" + field1->name() + "\" and singular " +
"field \"" + field2->name() + "\" generates the method \"" +
"get" + name1 + "Count()\"";
"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() + "\" generates the method \"" +
"get" + name1 + "List()\"";
"field \"" + field2->name() + "\" generate the method \"" +
"get" + name1 + "List()\"";
return true;
}
// Well, there are obviously many more conflicting cases, but it probably
@@ -33,9 +33,6 @@
#include <map>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <vector>
#include <google/protobuf/stubs/common.h>
@@ -97,7 +94,7 @@ class Context {
void InitializeFieldGeneratorInfoForFields(
const std::vector<const FieldDescriptor*>& fields);
google::protobuf::scoped_ptr<ClassNameResolver> name_resolver_;
std::unique_ptr<ClassNameResolver> name_resolver_;
std::map<const FieldDescriptor*, FieldGeneratorInfo>
field_generator_info_map_;
std::map<const OneofDescriptor*, OneofGeneratorInfo>
@@ -36,12 +36,12 @@
#include <string>
#include <google/protobuf/compiler/java/java_context.h>
#include <google/protobuf/compiler/java/java_enum.h>
#include <google/protobuf/compiler/java/java_doc_comment.h>
#include <google/protobuf/compiler/java/java_enum.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -80,7 +80,7 @@ void SetEnumVariables(const FieldDescriptor* descriptor,
// 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.
// with v2.5.0/v2.6.1, and remove the @SuppressWarnings annotations.
(*variables)["for_number"] = "valueOf";
if (SupportFieldPresence(descriptor->file())) {
@@ -199,6 +199,7 @@ GenerateMembers(io::Printer* printer) const {
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");
@@ -237,6 +238,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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");
@@ -320,6 +322,7 @@ GenerateParsingCode(io::Printer* printer) const {
} 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"
@@ -412,6 +415,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -456,6 +460,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -517,6 +522,7 @@ GenerateParsingCode(io::Printer* printer) const {
} 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"
@@ -626,6 +632,7 @@ GenerateMembers(io::Printer* printer) const {
" 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"
@@ -667,8 +674,7 @@ GenerateMembers(io::Printer* printer) const {
printer->Annotate("{", "}", descriptor_);
}
if (descriptor_->is_packed() &&
context_->HasGeneratedMethods(descriptor_->containing_type())) {
if (descriptor_->is_packed()) {
printer->Print(variables_,
"private int $name$MemoizedSerializedSize;\n");
}
@@ -879,6 +885,7 @@ GenerateParsingCode(io::Printer* printer) const {
} 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"
@@ -165,6 +165,7 @@ GenerateMembers(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 $get_has_field_bit_message$;\n"
"}\n");
@@ -173,6 +174,7 @@ GenerateMembers(io::Printer* printer) const {
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");
@@ -180,6 +182,7 @@ GenerateMembers(io::Printer* printer) const {
}
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"
@@ -217,6 +220,7 @@ 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");
@@ -225,6 +229,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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");
@@ -241,6 +246,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -378,6 +384,7 @@ GenerateMembers(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 $has_oneof_case_message$;\n"
"}\n");
@@ -386,6 +393,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -396,6 +404,7 @@ GenerateMembers(io::Printer* printer) const {
}
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"
@@ -439,6 +448,7 @@ 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");
@@ -447,6 +457,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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");
@@ -463,6 +474,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -611,6 +623,7 @@ GenerateMembers(io::Printer* printer) const {
" 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"
@@ -619,6 +632,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -627,12 +641,14 @@ GenerateMembers(io::Printer* printer) const {
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");
@@ -640,6 +656,7 @@ GenerateMembers(io::Printer* printer) const {
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.Integer>\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return $name$_;\n"
@@ -647,6 +664,7 @@ GenerateMembers(io::Printer* printer) const {
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");
@@ -732,6 +750,7 @@ 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"
@@ -739,12 +758,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
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");
@@ -787,6 +808,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.Integer>\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
@@ -795,6 +817,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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");
@@ -36,12 +36,12 @@
#include <string>
#include <google/protobuf/compiler/java/java_context.h>
#include <google/protobuf/compiler/java/java_enum_lite.h>
#include <google/protobuf/compiler/java/java_doc_comment.h>
#include <google/protobuf/compiler/java/java_enum_lite.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
@@ -135,6 +135,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
printer->Print(
"\n"
"@java.lang.Override\n"
"public final int getNumber() {\n");
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
@@ -182,6 +183,7 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
"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"
@@ -141,6 +141,7 @@ void ImmutableExtensionGenerator::Generate(io::Printer* printer) {
" $singular_type$.class,\n"
" $prototype$);\n");
}
printer->Annotate("name", descriptor_);
}
int ImmutableExtensionGenerator::GenerateNonNestedInitializationCode(
@@ -96,6 +96,7 @@ void ImmutableExtensionLiteGenerator::Generate(io::Printer* printer) {
" com.google.protobuf.WireFormat.FieldType.$type_constant$,\n"
" $singular_type$.class);\n");
}
printer->Annotate("name", descriptor_);
}
int ImmutableExtensionLiteGenerator::GenerateNonNestedInitializationCode(
@@ -35,9 +35,6 @@
#include <google/protobuf/compiler/java/java_field.h>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
@@ -214,8 +211,7 @@ template <>
FieldGeneratorMap<ImmutableFieldGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context)
: descriptor_(descriptor),
field_generators_(new google::protobuf::scoped_ptr<
ImmutableFieldGenerator>[descriptor->field_count()]) {
field_generators_(descriptor->field_count()) {
// Construct all the FieldGenerators and assign them bit indices for their
// bit fields.
@@ -237,8 +233,7 @@ template <>
FieldGeneratorMap<ImmutableFieldLiteGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context)
: descriptor_(descriptor),
field_generators_(new google::protobuf::scoped_ptr<
ImmutableFieldLiteGenerator>[descriptor->field_count()]) {
field_generators_(descriptor->field_count()) {
// Construct all the FieldGenerators and assign them bit indices for their
// bit fields.
int messageBitIndex = 0;
@@ -37,9 +37,6 @@
#include <map>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <string>
#include <google/protobuf/stubs/common.h>
@@ -141,7 +138,7 @@ class FieldGeneratorMap {
const Descriptor* descriptor_;
Context* context_;
ClassNameResolver* name_resolver_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<FieldGeneratorType> > field_generators_;
std::vector<std::unique_ptr<FieldGeneratorType>> field_generators_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
@@ -163,6 +160,14 @@ template<>
FieldGeneratorMap<ImmutableFieldGenerator>::~FieldGeneratorMap();
template <>
FieldGeneratorMap<ImmutableFieldLiteGenerator>::FieldGeneratorMap(
const Descriptor* descriptor, Context* context);
template <>
FieldGeneratorMap<ImmutableFieldLiteGenerator>::~FieldGeneratorMap();
// Field information used in FieldGeneartors.
struct FieldGeneratorInfo {
string name;
@@ -35,9 +35,6 @@
#include <google/protobuf/compiler/java/java_file.h>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <set>
#include <google/protobuf/compiler/java/java_context.h>
@@ -51,9 +48,9 @@
#include <google/protobuf/compiler/java/java_service.h>
#include <google/protobuf/compiler/java/java_shared_code_generator.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/stubs/strutil.h>
@@ -136,7 +133,7 @@ void CollectExtensions(const FileDescriptorProto& file_proto,
"descriptor.proto is not in the transitive dependencies. "
"This normally should not happen. Please report a bug.";
DynamicMessageFactory factory;
google::protobuf::scoped_ptr<Message> dynamic_file_proto(
std::unique_ptr<Message> dynamic_file_proto(
factory.GetPrototype(file_proto_desc)->New());
GOOGLE_CHECK(dynamic_file_proto.get() != NULL);
GOOGLE_CHECK(dynamic_file_proto->ParseFromString(file_data));
@@ -189,10 +186,8 @@ FileGenerator::FileGenerator(const FileDescriptor* file, const Options& options,
bool immutable_api)
: file_(file),
java_package_(FileJavaPackage(file, immutable_api)),
message_generators_(
new google::protobuf::scoped_ptr<MessageGenerator>[file->message_type_count()]),
extension_generators_(
new google::protobuf::scoped_ptr<ExtensionGenerator>[file->extension_count()]),
message_generators_(file->message_type_count()),
extension_generators_(file->extension_count()),
context_(new Context(file, options)),
name_resolver_(context_->GetNameResolver()),
options_(options),
@@ -228,6 +223,16 @@ bool FileGenerator::Validate(string* error) {
"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;
}
@@ -309,7 +314,7 @@ void FileGenerator::Generate(io::Printer* printer) {
}
if (HasGenericServices(file_, context_->EnforceLite())) {
for (int i = 0; i < file_->service_count(); i++) {
google::protobuf::scoped_ptr<ServiceGenerator> generator(
std::unique_ptr<ServiceGenerator> generator(
generator_factory_->NewServiceGenerator(file_->service(i)));
generator->Generate(printer);
}
@@ -435,7 +440,7 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable(
" com.google.protobuf.ExtensionRegistry.newInstance();\n");
FieldDescriptorSet::iterator it;
for (it = extensions.begin(); it != extensions.end(); it++) {
google::protobuf::scoped_ptr<ExtensionGenerator> generator(
std::unique_ptr<ExtensionGenerator> generator(
generator_factory_->NewExtensionGenerator(*it));
bytecode_estimate += generator->GenerateRegistrationCode(printer);
MaybeRestartJavaMethod(
@@ -588,7 +593,7 @@ static void GenerateSibling(const string& package_dir,
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
io::Printer printer(output.get(), '$',
annotate_code ? &annotation_collector : NULL);
@@ -607,7 +612,7 @@ static void GenerateSibling(const string& package_dir,
(generator->*pfn)(&printer);
if (annotate_code) {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
std::unique_ptr<io::ZeroCopyOutputStream> info_output(
context->Open(info_full_path));
annotations.SerializeToZeroCopyStream(info_output.get());
annotation_list->push_back(info_full_path);
@@ -650,7 +655,7 @@ void FileGenerator::GenerateSiblings(const string& package_dir,
}
if (HasGenericServices(file_, context_->EnforceLite())) {
for (int i = 0; i < file_->service_count(); i++) {
google::protobuf::scoped_ptr<ServiceGenerator> generator(
std::unique_ptr<ServiceGenerator> generator(
generator_factory_->NewServiceGenerator(file_->service(i)));
GenerateSibling<ServiceGenerator>(
package_dir, java_package_, file_->service(i), context, file_list,
@@ -36,9 +36,6 @@
#define GOOGLE_PROTOBUF_COMPILER_JAVA_FILE_H__
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <string>
#include <vector>
#include <google/protobuf/stubs/common.h>
@@ -101,10 +98,10 @@ class FileGenerator {
string java_package_;
string classname_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<MessageGenerator> > message_generators_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > extension_generators_;
google::protobuf::scoped_ptr<GeneratorFactory> generator_factory_;
google::protobuf::scoped_ptr<Context> context_;
std::vector<std::unique_ptr<MessageGenerator>> message_generators_;
std::vector<std::unique_ptr<ExtensionGenerator>> extension_generators_;
std::unique_ptr<GeneratorFactory> generator_factory_;
std::unique_ptr<Context> context_;
ClassNameResolver* name_resolver_;
const Options options_;
bool immutable_api_;
@@ -35,9 +35,6 @@
#include <google/protobuf/compiler/java/java_generator.h>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/compiler/java/java_file.h>
#include <google/protobuf/compiler/java/java_generator_factory.h>
@@ -45,9 +42,9 @@
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/compiler/java/java_options.h>
#include <google/protobuf/compiler/java/java_shared_code_generator.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/stubs/strutil.h>
@@ -144,7 +141,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
}
// Generate main java file.
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
context->Open(java_filename));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
@@ -160,7 +157,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
&all_annotations);
if (file_options.annotate_code) {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
std::unique_ptr<io::ZeroCopyOutputStream> info_output(
context->Open(info_full_path));
annotations.SerializeToZeroCopyStream(info_output.get());
}
@@ -175,7 +172,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
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.
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> srclist_raw_output(
std::unique_ptr<io::ZeroCopyOutputStream> 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++) {
@@ -186,7 +183,7 @@ bool JavaGenerator::Generate(const FileDescriptor* file,
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.
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> annotation_list_raw_output(
std::unique_ptr<io::ZeroCopyOutputStream> 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++) {
@@ -75,6 +75,8 @@ const char* kForbiddenWordList[] = {
"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]) {
@@ -103,6 +105,20 @@ string FieldName(const FieldDescriptor* field) {
}
// 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<int64>(hi) - lo + 1); // words
int64 table_time_cost = 3; // comparisons
int64 lookup_space_cost = 3 + 2 * static_cast<int64>(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,
@@ -915,6 +931,23 @@ void EscapeUtf16ToString(uint16 code, string* output) {
output->append(StringPrintf("\\u%04x", code));
}
}
std::pair<int, int> 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
@@ -37,8 +37,8 @@
#include <string>
#include <google/protobuf/compiler/java/java_context.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.h>
namespace google {
@@ -414,6 +414,11 @@ void EscapeUtf16ToString(uint16 code, string* output);
// 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<int, int> GetTableDrivenNumberOfEntriesAndLookUpStartFieldNumber(
const FieldDescriptor** fields, int count);
} // namespace java
} // namespace compiler
} // namespace protobuf
@@ -301,6 +301,7 @@ GenerateMembers(io::Printer* printer) const {
"}\n");
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public int ${$get$capitalized_name$Count$}$() {\n"
" return internalGet$capitalized_name$().size();\n"
@@ -309,6 +310,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
@@ -339,6 +341,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -352,6 +355,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -367,6 +371,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -385,6 +390,7 @@ GenerateMembers(io::Printer* printer) const {
"/**\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"
@@ -394,6 +400,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -404,6 +411,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
@@ -417,6 +425,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -436,6 +445,7 @@ GenerateMembers(io::Printer* printer) const {
"/**\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"
@@ -445,6 +455,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$Map$}$() {\n"
@@ -455,6 +466,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
@@ -468,6 +480,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -519,6 +532,7 @@ 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"
@@ -527,6 +541,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
@@ -570,6 +585,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -580,6 +596,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -595,6 +612,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -636,6 +654,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
"/**\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"
@@ -645,6 +664,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -655,6 +675,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
@@ -668,6 +689,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -709,6 +731,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
"/**\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"
@@ -718,6 +741,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$Map$}$() {\n"
@@ -728,6 +752,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
@@ -741,6 +766,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"@java.lang.Override\n"
"$deprecation$\n"
"public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <vector>
#include <google/protobuf/compiler/java/java_context.h>
@@ -52,9 +49,9 @@
#include <google/protobuf/compiler/java/java_message_builder.h>
#include <google/protobuf/compiler/java/java_message_builder_lite.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
@@ -437,11 +434,11 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
printer->Print(
"$field_name$($field_number$),\n",
"field_name",
ToUpper(field->name()),
"field_number",
SimpleItoa(field->number()));
"$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",
@@ -555,6 +552,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
GenerateParser(printer);
printer->Print(
"@java.lang.Override\n"
"public $classname$ getDefaultInstanceForType() {\n"
" return DEFAULT_INSTANCE;\n"
"}\n"
@@ -578,7 +576,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
void ImmutableMessageGenerator::
GenerateMessageSerializationMethods(io::Printer* printer) {
google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields(
std::unique_ptr<const FieldDescriptor * []> sorted_fields(
SortFieldsByNumber(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
@@ -588,6 +586,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
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();
@@ -648,6 +647,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
printer->Print(
"}\n"
"\n"
"@java.lang.Override\n"
"public int getSerializedSize() {\n"
" int size = memoizedSize;\n"
" if (size != -1) return size;\n"
@@ -789,6 +789,7 @@ void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange(
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(
@@ -798,6 +799,7 @@ void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) {
"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"
@@ -841,6 +843,7 @@ GenerateDescriptorMethods(io::Printer* printer) {
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");
@@ -866,6 +869,7 @@ GenerateDescriptorMethods(io::Printer* printer) {
"}\n");
}
printer->Print(
"@java.lang.Override\n"
"protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n"
" internalGetFieldAccessorTable() {\n"
" return $fileclass$.internal_$identifier$_fieldAccessorTable\n"
@@ -889,6 +893,7 @@ void ImmutableMessageGenerator::GenerateIsInitialized(
printer->Print(
"private byte memoizedIsInitialized = -1;\n");
printer->Print(
"@java.lang.Override\n"
"public final boolean isInitialized() {\n");
printer->Indent();
@@ -1209,7 +1214,7 @@ GenerateExtensionRegistrationCode(io::Printer* printer) {
// ===================================================================
void ImmutableMessageGenerator::
GenerateParsingConstructor(io::Printer* printer) {
google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields(
std::unique_ptr<const FieldDescriptor * []> sorted_fields(
SortFieldsByNumber(descriptor_));
printer->Print(
@@ -1259,19 +1264,9 @@ GenerateParsingConstructor(io::Printer* printer) {
printer->Indent();
printer->Print(
"case 0:\n" // zero signals EOF / limit reached
" done = true;\n"
" break;\n"
"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"
: "");
"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];
@@ -1309,6 +1304,18 @@ GenerateParsingConstructor(io::Printer* printer) {
}
}
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(
@@ -1356,6 +1363,7 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) {
"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"
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <vector>
#include <google/protobuf/compiler/java/java_context.h>
@@ -50,9 +47,9 @@
#include <google/protobuf/compiler/java/java_generator_factory.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
@@ -180,11 +177,13 @@ Generate(io::Printer* printer) {
// 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"
@@ -277,6 +276,7 @@ GenerateDescriptorMethods(io::Printer* printer) {
"}\n");
}
printer->Print(
"@java.lang.Override\n"
"protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n"
" internalGetFieldAccessorTable() {\n"
" return $fileclass$.internal_$identifier$_fieldAccessorTable\n"
@@ -333,6 +333,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"}\n");
printer->Print(
"@java.lang.Override\n"
"public Builder clear() {\n"
" super.clear();\n");
@@ -361,6 +362,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"\n");
printer->Print(
"@java.lang.Override\n"
"public com.google.protobuf.Descriptors.Descriptor\n"
" getDescriptorForType() {\n"
" return $fileclass$.internal_$identifier$_descriptor;\n"
@@ -371,6 +373,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
// LITE runtime implements this in GeneratedMessageLite.
printer->Print(
"@java.lang.Override\n"
"public $classname$ getDefaultInstanceForType() {\n"
" return $classname$.getDefaultInstance();\n"
"}\n"
@@ -378,6 +381,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Print(
"@java.lang.Override\n"
"public $classname$ build() {\n"
" $classname$ result = buildPartial();\n"
" if (!result.isInitialized()) {\n"
@@ -389,6 +393,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"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_));
@@ -457,27 +462,33 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
// 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"
@@ -486,24 +497,28 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"@java.lang.Override\n"
"public <Type> 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 <Type> Builder setExtension(\n"
" com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
" $classname$, java.util.List<Type>> extension,\n"
" int index, Type value) {\n"
" return (Builder) super.setExtension(extension, index, value);\n"
"}\n"
"@java.lang.Override\n"
"public <Type> Builder addExtension(\n"
" com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
" $classname$, java.util.List<Type>> extension,\n"
" Type value) {\n"
" return (Builder) super.addExtension(extension, value);\n"
"}\n"
"@java.lang.Override\n"
"public <Type> Builder clearExtension(\n"
" com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
" $classname$, ?> extension) {\n"
@@ -516,6 +531,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
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"
@@ -602,6 +618,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
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"
@@ -627,6 +644,7 @@ GenerateBuilderParsingMethods(io::Printer* printer) {
void MessageBuilderGenerator::GenerateIsInitialized(
io::Printer* printer) {
printer->Print(
"@java.lang.Override\n"
"public final boolean isInitialized() {\n");
printer->Indent();
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <vector>
#include <google/protobuf/compiler/java/java_context.h>
@@ -50,12 +47,12 @@
#include <google/protobuf/compiler/java/java_generator_factory.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
@@ -109,6 +106,7 @@ Generate(io::Printer* printer) {
// 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"
@@ -147,12 +147,14 @@ GenerateMembers(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 $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");
@@ -160,12 +162,14 @@ GenerateMembers(io::Printer* printer) const {
} 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");
@@ -195,7 +199,11 @@ GenerateMembers(io::Printer* printer) const {
// 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"
@@ -223,6 +231,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// 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");
@@ -231,6 +240,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// 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");
@@ -396,12 +406,14 @@ 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"
@@ -434,6 +446,9 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -464,6 +479,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// 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");
@@ -472,6 +488,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// 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");
@@ -624,6 +641,7 @@ GenerateMembers(io::Printer* printer) const {
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
@@ -638,12 +656,14 @@ GenerateMembers(io::Printer* printer) const {
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");
@@ -761,6 +781,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// List<Field> 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"
@@ -771,6 +792,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// 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"
"}");
@@ -779,6 +801,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// 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");
@@ -38,9 +38,6 @@
#include <google/protobuf/stubs/hash.h>
#include <map>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <vector>
#include <google/protobuf/compiler/java/java_context.h>
@@ -52,9 +49,9 @@
#include <google/protobuf/compiler/java/java_message_builder.h>
#include <google/protobuf/compiler/java/java_message_builder_lite.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/strutil.h>
@@ -310,6 +307,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
" default: return null;\n"
" }\n"
"}\n"
"@java.lang.Override\n"
"public int getNumber() {\n"
" return this.value;\n"
"}\n",
@@ -318,6 +316,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
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"
@@ -356,6 +355,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
}
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"
@@ -369,22 +369,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Indent();
printer->Indent();
printer->Print("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 NEW_BUILDER: {\n");
printer->Indent();
@@ -392,6 +377,22 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* 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");
@@ -399,15 +400,16 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Indent();
GenerateDynamicMethodVisit(printer);
printer->Outdent();
printer->Print(
"}\n"
"case MERGE_FROM_STREAM: {\n");
printer->Indent();
GenerateDynamicMethodMergeFromStream(printer);
printer->Outdent();
}
printer->Print(
"}\n"
"case MERGE_FROM_STREAM: {\n");
printer->Indent();
GenerateDynamicMethodMergeFromStream(printer);
printer->Outdent();
printer->Print(
"}\n"
@@ -420,14 +422,20 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
// 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.
" if (PARSER == null) {"
//
// 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"
" if (PARSER == null) {\n"
" PARSER = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n"
" parser = PARSER;\n"
" if (parser == null) {\n"
" parser = new DefaultInstanceBasedParser(DEFAULT_INSTANCE);\n"
" PARSER = parser;\n"
" }\n"
" }\n"
" }\n"
" return PARSER;\n",
" return parser;\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Outdent();
@@ -475,8 +483,9 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Print(
"static {\n"
" // New instances are implicitly immutable so no need to make\n"
" // immutable.\n"
" DEFAULT_INSTANCE = new $classname$();\n"
" DEFAULT_INSTANCE.makeImmutable();\n"
"}\n"
"\n",
"classname", descriptor_->name());
@@ -491,6 +500,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
"}\n",
"classname", descriptor_->name());
}
printer->Print(
"public static $classname$ getDefaultInstance() {\n"
" return DEFAULT_INSTANCE;\n"
@@ -519,6 +529,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
.Generate(printer);
}
printer->Outdent();
printer->Print("}\n\n");
}
@@ -528,7 +539,11 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
void ImmutableMessageLiteGenerator::
GenerateMessageSerializationMethods(io::Printer* printer) {
google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields(
if (EnableExperimentalRuntimeForLite()) {
return;
}
std::unique_ptr<const FieldDescriptor * []> sorted_fields(
SortFieldsByNumber(descriptor_));
std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
@@ -539,6 +554,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
ExtensionRangeOrdering());
printer->Print(
"@java.lang.Override\n"
"public void writeTo(com.google.protobuf.CodedOutputStream output)\n"
" throws java.io.IOException {\n");
printer->Indent();
@@ -594,6 +610,7 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
printer->Print(
"}\n"
"\n"
"@java.lang.Override\n"
"public int getSerializedSize() {\n"
" int size = memoizedSerializedSize;\n"
" if (size != -1) return size;\n"
@@ -1005,38 +1022,7 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
" done = true;\n"
" break;\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");
}
google::protobuf::scoped_array<const FieldDescriptor* > sorted_fields(
std::unique_ptr<const FieldDescriptor* []> sorted_fields(
SortFieldsByNumber(descriptor_));
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = sorted_fields[i];
@@ -1073,6 +1059,37 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
}
}
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(
@@ -35,9 +35,6 @@
// worth.
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/compiler/java/java_generator.h>
#include <google/protobuf/compiler/command_line_interface.h>
@@ -76,7 +73,7 @@ class TestGenerator : public CodeGenerator {
void TryInsert(const string& filename, const string& insertion_point,
GeneratorContext* context) const {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
std::unique_ptr<io::ZeroCopyOutputStream> output(
context->OpenForInsert(filename, insertion_point));
io::Printer printer(output.get(), '$');
printer.Print("// inserted $name$\n", "name", insertion_point);
@@ -633,8 +633,7 @@ GenerateMembers(io::Printer* printer) const {
"}\n");
printer->Annotate("{", "}", descriptor_);
if (descriptor_->is_packed() &&
context_->HasGeneratedMethods(descriptor_->containing_type())) {
if (descriptor_->is_packed()) {
printer->Print(variables_,
"private int $name$MemoizedSerializedSize = -1;\n");
}
@@ -222,6 +222,7 @@ GenerateMembers(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 $get_has_field_bit_message$;\n"
"}\n");
@@ -230,6 +231,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
@@ -266,6 +268,7 @@ 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");
@@ -274,6 +277,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -488,6 +492,7 @@ GenerateMembers(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 $has_oneof_case_message$;\n"
"}\n");
@@ -496,6 +501,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -528,6 +534,7 @@ 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");
@@ -536,6 +543,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
@@ -645,6 +653,7 @@ GenerateMembers(io::Printer* printer) const {
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
@@ -652,12 +661,14 @@ GenerateMembers(io::Printer* printer) const {
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");
@@ -711,6 +722,7 @@ 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"
@@ -719,12 +731,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
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");
@@ -33,16 +33,13 @@
#include <google/protobuf/compiler/java/java_shared_code_generator.h>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
@@ -69,11 +66,11 @@ void SharedCodeGenerator::Generate(GeneratorContext* context,
string classname = name_resolver_->GetDescriptorClassName(file_);
string filename = package_dir + classname + ".java";
file_list->push_back(filename);
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
std::unique_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
google::protobuf::scoped_ptr<io::Printer> printer(
std::unique_ptr<io::Printer> printer(
new io::Printer(output.get(), '$',
options_.annotate_code ? &annotation_collector : NULL));
string info_relative_path = classname + ".java.pb.meta";
@@ -108,7 +105,7 @@ void SharedCodeGenerator::Generate(GeneratorContext* context,
"}\n");
if (options_.annotate_code) {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
std::unique_ptr<io::ZeroCopyOutputStream> info_output(
context->Open(info_full_path));
annotations.SerializeToZeroCopyStream(info_output.get());
annotation_file_list->push_back(info_full_path);
@@ -36,9 +36,6 @@
#define GOOGLE_PROTOBUF_COMPILER_JAVA_SHARED_CODE_GENERATOR_H__
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <string>
#include <vector>
@@ -77,7 +74,7 @@ class SharedCodeGenerator {
void GenerateDescriptors(io::Printer* printer);
private:
google::protobuf::scoped_ptr<ClassNameResolver> name_resolver_;
std::unique_ptr<ClassNameResolver> name_resolver_;
const FileDescriptor* file_;
const Options options_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SharedCodeGenerator);
@@ -192,6 +192,7 @@ GenerateMembers(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 $get_has_field_bit_message$;\n"
"}\n");
@@ -200,12 +201,14 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -249,6 +252,7 @@ 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");
@@ -257,6 +261,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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");
@@ -264,6 +269,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -419,6 +425,7 @@ GenerateMembers(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 $has_oneof_case_message$;\n"
"}\n");
@@ -427,6 +434,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -438,6 +446,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -489,6 +498,7 @@ 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");
@@ -497,6 +507,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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");
@@ -504,6 +515,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -641,6 +653,7 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.String> "
"${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
@@ -648,12 +661,14 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -661,6 +676,7 @@ GenerateMembers(io::Printer* printer) const {
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"
@@ -725,6 +741,7 @@ void RepeatedImmutableStringFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"@java.lang.Override\n"
"$deprecation$public java.util.List<java.lang.String>\n"
" ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
@@ -733,12 +750,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -746,6 +765,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
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"
@@ -1,143 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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 <map>
#include <string>
#include <google/protobuf/compiler/javanano/javanano_params.h>
#include <google/protobuf/compiler/javanano/javanano_enum.h>
#include <google/protobuf/compiler/javanano/javanano_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace javanano {
EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, const Params& params)
: params_(params), descriptor_(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) {
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) {
printer->Print(
"\n"
"// enum $classname$\n",
"classname", descriptor_->name());
const string classname = RenameJavaKeywords(descriptor_->name());
// Start of container interface
// If generating intdefs, we use the container interface as the intdef if
// present. Otherwise, we just make an empty @interface parallel to the
// constants.
bool use_intdef = params_.generate_intdefs();
bool use_shell_class = params_.java_enum_style();
if (use_intdef) {
// @IntDef annotation so tools can enforce correctness
// Annotations will be discarded by the compiler
printer->Print("@java.lang.annotation.Retention("
"java.lang.annotation.RetentionPolicy.SOURCE)\n"
"@android.support.annotation.IntDef({\n");
printer->Indent();
for (int i = 0; i < canonical_values_.size(); i++) {
const string constant_name =
RenameJavaKeywords(canonical_values_[i]->name());
if (use_shell_class) {
printer->Print("$classname$.$name$,\n",
"classname", classname,
"name", constant_name);
} else {
printer->Print("$name$,\n", "name", constant_name);
}
}
printer->Outdent();
printer->Print("})\n");
}
if (use_shell_class || use_intdef) {
printer->Print(
"public $at_for_intdef$interface $classname$ {\n",
"classname", classname,
"at_for_intdef", use_intdef ? "@" : "");
if (use_shell_class) {
printer->Indent();
} else {
printer->Print("}\n\n");
}
}
// Canonical values
for (int i = 0; i < canonical_values_.size(); i++) {
printer->Print(
"public static final int $name$ = $canonical_value$;\n",
"name", RenameJavaKeywords(canonical_values_[i]->name()),
"canonical_value", SimpleItoa(canonical_values_[i]->number()));
}
// Aliases
for (int i = 0; i < aliases_.size(); i++) {
printer->Print(
"public static final int $name$ = $canonical_name$;\n",
"name", RenameJavaKeywords(aliases_[i].value->name()),
"canonical_name", RenameJavaKeywords(aliases_[i].canonical_value->name()));
}
// End of container interface
if (use_shell_class) {
printer->Outdent();
printer->Print("}\n");
}
}
} // namespace javanano
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -1,87 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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_JAVANANO_ENUM_H__
#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_H__
#include <string>
#include <vector>
#include <google/protobuf/compiler/javanano/javanano_params.h>
#include <google/protobuf/descriptor.h>
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace javanano {
class EnumGenerator {
public:
explicit EnumGenerator(const EnumDescriptor* descriptor, const Params& params);
~EnumGenerator();
void Generate(io::Printer* printer);
private:
const Params& params_;
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.
vector<const EnumValueDescriptor*> canonical_values_;
struct Alias {
const EnumValueDescriptor* value;
const EnumValueDescriptor* canonical_value;
};
vector<Alias> aliases_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
};
} // namespace javanano
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_H__
@@ -1,544 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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 <map>
#include <string>
#include <google/protobuf/compiler/javanano/javanano_enum_field.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/javanano/javanano_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace javanano {
namespace {
// TODO(kenton): Factor out a "SetCommonFieldVariables()" to get rid of
// repeat code between this and the other field types.
void SetEnumVariables(const Params& params,
const FieldDescriptor* descriptor, std::map<string, string>* variables) {
(*variables)["name"] =
RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
(*variables)["capitalized_name"] =
RenameJavaKeywords(UnderscoresToCapitalizedCamelCase(descriptor));
(*variables)["number"] = SimpleItoa(descriptor->number());
if (params.use_reference_types_for_primitives()
&& !params.reftypes_primitive_enums()
&& !descriptor->is_repeated()) {
(*variables)["type"] = "java.lang.Integer";
(*variables)["default"] = "null";
} else {
(*variables)["type"] = "int";
(*variables)["default"] = DefaultValue(params, descriptor);
}
(*variables)["repeated_default"] =
"com.google.protobuf.nano.WireFormatNano.EMPTY_INT_ARRAY";
(*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor));
(*variables)["tag_size"] = SimpleItoa(
internal::WireFormat::TagSize(descriptor->number(), descriptor->type()));
(*variables)["non_packed_tag"] = SimpleItoa(
internal::WireFormatLite::MakeTag(descriptor->number(),
internal::WireFormat::WireTypeForFieldType(descriptor->type())));
(*variables)["message_name"] = descriptor->containing_type()->name();
const EnumDescriptor* enum_type = descriptor->enum_type();
(*variables)["message_type_intdef"] = "@"
+ ToJavaName(params, enum_type->name(), true,
enum_type->containing_type(), enum_type->file());
}
void LoadEnumValues(const Params& params,
const EnumDescriptor* enum_descriptor, vector<string>* canonical_values) {
string enum_class_name = ClassName(params, enum_descriptor);
for (int i = 0; i < enum_descriptor->value_count(); i++) {
const EnumValueDescriptor* value = enum_descriptor->value(i);
const EnumValueDescriptor* canonical_value =
enum_descriptor->FindValueByNumber(value->number());
if (value == canonical_value) {
canonical_values->push_back(
enum_class_name + "." + RenameJavaKeywords(value->name()));
}
}
}
void PrintCaseLabels(
io::Printer* printer, const vector<string>& canonical_values) {
for (int i = 0; i < canonical_values.size(); i++) {
printer->Print(
" case $value$:\n",
"value", canonical_values[i]);
}
}
} // namespace
// ===================================================================
EnumFieldGenerator::
EnumFieldGenerator(const FieldDescriptor* descriptor, const Params& params)
: FieldGenerator(params), descriptor_(descriptor) {
SetEnumVariables(params, descriptor, &variables_);
LoadEnumValues(params, descriptor->enum_type(), &canonical_values_);
}
EnumFieldGenerator::~EnumFieldGenerator() {}
void EnumFieldGenerator::
GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
if (params_.generate_intdefs()) {
printer->Print(variables_, "$message_type_intdef$\n");
}
printer->Print(variables_, "public $type$ $name$;\n");
if (params_.generate_has()) {
printer->Print(variables_,
"public boolean has$capitalized_name$;\n");
}
}
void EnumFieldGenerator::
GenerateClearCode(io::Printer* printer) const {
printer->Print(variables_,
"$name$ = $default$;\n");
if (params_.generate_has()) {
printer->Print(variables_,
"has$capitalized_name$ = false;\n");
}
}
void EnumFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_,
"int value = input.readInt32();\n"
"switch (value) {\n");
PrintCaseLabels(printer, canonical_values_);
printer->Print(variables_,
" this.$name$ = value;\n");
if (params_.generate_has()) {
printer->Print(variables_,
" has$capitalized_name$ = true;\n");
}
printer->Print(
" break;\n"
"}\n");
// No default case: in case of invalid value from the wire, preserve old
// field value. Also we are not storing the invalid value into the unknown
// fields, because there is no way to get the value out.
}
void EnumFieldGenerator::
GenerateSerializationCode(io::Printer* printer) const {
if (descriptor_->is_required() && !params_.generate_has()) {
// Always serialize a required field if we don't have the 'has' signal.
printer->Print(variables_,
"output.writeInt32($number$, this.$name$);\n");
} else {
if (params_.generate_has()) {
printer->Print(variables_,
"if (this.$name$ != $default$ || has$capitalized_name$) {\n");
} else {
printer->Print(variables_,
"if (this.$name$ != $default$) {\n");
}
printer->Print(variables_,
" output.writeInt32($number$, this.$name$);\n"
"}\n");
}
}
void EnumFieldGenerator::
GenerateSerializedSizeCode(io::Printer* printer) const {
if (descriptor_->is_required() && !params_.generate_has()) {
printer->Print(variables_,
"size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
" .computeInt32Size($number$, this.$name$);\n");
} else {
if (params_.generate_has()) {
printer->Print(variables_,
"if (this.$name$ != $default$ || has$capitalized_name$) {\n");
} else {
printer->Print(variables_,
"if (this.$name$ != $default$) {\n");
}
printer->Print(variables_,
" size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
" .computeInt32Size($number$, this.$name$);\n"
"}\n");
}
}
void EnumFieldGenerator::GenerateEqualsCode(io::Printer* printer) const {
if (params_.use_reference_types_for_primitives()
&& !params_.reftypes_primitive_enums()) {
printer->Print(variables_,
"if (this.$name$ == null) {\n"
" if (other.$name$ != null) {\n"
" return false;\n"
" }\n"
"} else if (!this.$name$.equals(other.$name$)) {\n"
" return false;"
"}\n");
} else {
// We define equality as serialized form equality. If generate_has(),
// then if the field value equals the default value in both messages,
// but one's 'has' field is set and the other's is not, the serialized
// forms are different and we should return false.
printer->Print(variables_,
"if (this.$name$ != other.$name$");
if (params_.generate_has()) {
printer->Print(variables_,
"\n"
" || (this.$name$ == $default$\n"
" && this.has$capitalized_name$ != other.has$capitalized_name$)");
}
printer->Print(") {\n"
" return false;\n"
"}\n");
}
}
void EnumFieldGenerator::GenerateHashCodeCode(io::Printer* printer) const {
printer->Print(
"result = 31 * result + ");
if (params_.use_reference_types_for_primitives()
&& !params_.reftypes_primitive_enums()) {
printer->Print(variables_,
"(this.$name$ == null ? 0 : this.$name$)");
} else {
printer->Print(variables_,
"this.$name$");
}
printer->Print(";\n");
}
// ===================================================================
AccessorEnumFieldGenerator::
AccessorEnumFieldGenerator(const FieldDescriptor* descriptor,
const Params& params, int has_bit_index)
: FieldGenerator(params), descriptor_(descriptor) {
SetEnumVariables(params, descriptor, &variables_);
LoadEnumValues(params, descriptor->enum_type(), &canonical_values_);
SetBitOperationVariables("has", has_bit_index, &variables_);
}
AccessorEnumFieldGenerator::~AccessorEnumFieldGenerator() {}
void AccessorEnumFieldGenerator::
GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
printer->Print(variables_, "private int $name$_;\n");
if (params_.generate_intdefs()) {
printer->Print(variables_, "$message_type_intdef$\n");
}
printer->Print(variables_,
"public int get$capitalized_name$() {\n"
" return $name$_;\n"
"}\n"
"public $message_name$ set$capitalized_name$(");
if (params_.generate_intdefs()) {
printer->Print(variables_,
"\n"
" $message_type_intdef$ ");
}
printer->Print(variables_,
"int value) {\n"
" $name$_ = value;\n"
" $set_has$;\n"
" return this;\n"
"}\n"
"public boolean has$capitalized_name$() {\n"
" return $get_has$;\n"
"}\n"
"public $message_name$ clear$capitalized_name$() {\n"
" $name$_ = $default$;\n"
" $clear_has$;\n"
" return this;\n"
"}\n");
}
void AccessorEnumFieldGenerator::
GenerateClearCode(io::Printer* printer) const {
printer->Print(variables_,
"$name$_ = $default$;\n");
}
void AccessorEnumFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
printer->Print(variables_,
"int value = input.readInt32();\n"
"switch (value) {\n");
PrintCaseLabels(printer, canonical_values_);
printer->Print(variables_,
" $name$_ = value;\n"
" $set_has$;\n"
" break;\n"
"}\n");
// No default case: in case of invalid value from the wire, preserve old
// field value. Also we are not storing the invalid value into the unknown
// fields, because there is no way to get the value out.
}
void AccessorEnumFieldGenerator::
GenerateSerializationCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($get_has$) {\n"
" output.writeInt32($number$, $name$_);\n"
"}\n");
}
void AccessorEnumFieldGenerator::
GenerateSerializedSizeCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($get_has$) {\n"
" size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
" .computeInt32Size($number$, $name$_);\n"
"}\n");
}
void AccessorEnumFieldGenerator::
GenerateEqualsCode(io::Printer* printer) const {
printer->Print(variables_,
"if ($different_has$\n"
" || $name$_ != other.$name$_) {\n"
" return false;\n"
"}\n");
}
void AccessorEnumFieldGenerator::
GenerateHashCodeCode(io::Printer* printer) const {
printer->Print(variables_,
"result = 31 * result + $name$_;\n");
}
// ===================================================================
RepeatedEnumFieldGenerator::
RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, const Params& params)
: FieldGenerator(params), descriptor_(descriptor) {
SetEnumVariables(params, descriptor, &variables_);
LoadEnumValues(params, descriptor->enum_type(), &canonical_values_);
}
RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() {}
void RepeatedEnumFieldGenerator::
GenerateMembers(io::Printer* printer, bool /* unused lazy_init */) const {
printer->Print(variables_,
"public $type$[] $name$;\n");
}
void RepeatedEnumFieldGenerator::
GenerateClearCode(io::Printer* printer) const {
printer->Print(variables_,
"$name$ = $repeated_default$;\n");
}
void RepeatedEnumFieldGenerator::
GenerateMergingCode(io::Printer* printer) const {
// First, figure out the maximum length of the array, then parse,
// and finally copy the valid values to the field.
printer->Print(variables_,
"int length = com.google.protobuf.nano.WireFormatNano\n"
" .getRepeatedFieldArrayLength(input, $non_packed_tag$);\n"
"int[] validValues = new int[length];\n"
"int validCount = 0;\n"
"for (int i = 0; i < length; i++) {\n"
" if (i != 0) { // tag for first value already consumed.\n"
" input.readTag();\n"
" }\n"
" int value = input.readInt32();\n"
" switch (value) {\n");
printer->Indent();
PrintCaseLabels(printer, canonical_values_);
printer->Outdent();
printer->Print(variables_,
" validValues[validCount++] = value;\n"
" break;\n"
" }\n"
"}\n"
"if (validCount != 0) {\n"
" int i = this.$name$ == null ? 0 : this.$name$.length;\n"
" if (i == 0 && validCount == validValues.length) {\n"
" this.$name$ = validValues;\n"
" } else {\n"
" int[] newArray = new int[i + validCount];\n"
" if (i != 0) {\n"
" java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
" }\n"
" java.lang.System.arraycopy(validValues, 0, newArray, i, validCount);\n"
" this.$name$ = newArray;\n"
" }\n"
"}\n");
}
void RepeatedEnumFieldGenerator::
GenerateMergingCodeFromPacked(io::Printer* printer) const {
printer->Print(variables_,
"int bytes = input.readRawVarint32();\n"
"int limit = input.pushLimit(bytes);\n"
"// First pass to compute array length.\n"
"int arrayLength = 0;\n"
"int startPos = input.getPosition();\n"
"while (input.getBytesUntilLimit() > 0) {\n"
" switch (input.readInt32()) {\n");
printer->Indent();
PrintCaseLabels(printer, canonical_values_);
printer->Outdent();
printer->Print(variables_,
" arrayLength++;\n"
" break;\n"
" }\n"
"}\n"
"if (arrayLength != 0) {\n"
" input.rewindToPosition(startPos);\n"
" int i = this.$name$ == null ? 0 : this.$name$.length;\n"
" int[] newArray = new int[i + arrayLength];\n"
" if (i != 0) {\n"
" java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
" }\n"
" while (input.getBytesUntilLimit() > 0) {\n"
" int value = input.readInt32();\n"
" switch (value) {\n");
printer->Indent();
printer->Indent();
PrintCaseLabels(printer, canonical_values_);
printer->Outdent();
printer->Outdent();
printer->Print(variables_,
" newArray[i++] = value;\n"
" break;\n"
" }\n"
" }\n"
" this.$name$ = newArray;\n"
"}\n"
"input.popLimit(limit);\n");
}
void RepeatedEnumFieldGenerator::
GenerateRepeatedDataSizeCode(io::Printer* printer) const {
// Creates a variable dataSize and puts the serialized size in there.
printer->Print(variables_,
"int dataSize = 0;\n"
"for (int i = 0; i < this.$name$.length; i++) {\n"
" int element = this.$name$[i];\n"
" dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
" .computeInt32SizeNoTag(element);\n"
"}\n");
}
void RepeatedEnumFieldGenerator::
GenerateSerializationCode(io::Printer* printer) const {
printer->Print(variables_,
"if (this.$name$ != null && this.$name$.length > 0) {\n");
printer->Indent();
if (descriptor_->options().packed()) {
GenerateRepeatedDataSizeCode(printer);
printer->Print(variables_,
"output.writeRawVarint32($tag$);\n"
"output.writeRawVarint32(dataSize);\n"
"for (int i = 0; i < this.$name$.length; i++) {\n"
" output.writeRawVarint32(this.$name$[i]);\n"
"}\n");
} else {
printer->Print(variables_,
"for (int i = 0; i < this.$name$.length; i++) {\n"
" output.writeInt32($number$, this.$name$[i]);\n"
"}\n");
}
printer->Outdent();
printer->Print(variables_,
"}\n");
}
void RepeatedEnumFieldGenerator::
GenerateSerializedSizeCode(io::Printer* printer) const {
printer->Print(variables_,
"if (this.$name$ != null && this.$name$.length > 0) {\n");
printer->Indent();
GenerateRepeatedDataSizeCode(printer);
printer->Print(
"size += dataSize;\n");
if (descriptor_->options().packed()) {
printer->Print(variables_,
"size += $tag_size$;\n"
"size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
" .computeRawVarint32Size(dataSize);\n");
} else {
printer->Print(variables_,
"size += $tag_size$ * this.$name$.length;\n");
}
printer->Outdent();
printer->Print(
"}\n");
}
void RepeatedEnumFieldGenerator::
GenerateFixClonedCode(io::Printer* printer) const {
printer->Print(variables_,
"if (this.$name$ != null && this.$name$.length > 0) {\n"
" cloned.$name$ = this.$name$.clone();\n"
"}\n");
}
void RepeatedEnumFieldGenerator::
GenerateEqualsCode(io::Printer* printer) const {
printer->Print(variables_,
"if (!com.google.protobuf.nano.InternalNano.equals(\n"
" this.$name$, other.$name$)) {\n"
" return false;\n"
"}\n");
}
void RepeatedEnumFieldGenerator::
GenerateHashCodeCode(io::Printer* printer) const {
printer->Print(variables_,
"result = 31 * result\n"
" + com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n");
}
} // namespace javanano
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -1,126 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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_JAVANANO_ENUM_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__
#include <map>
#include <string>
#include <vector>
#include <google/protobuf/compiler/javanano/javanano_field.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace javanano {
class EnumFieldGenerator : public FieldGenerator {
public:
explicit EnumFieldGenerator(
const FieldDescriptor* descriptor, const Params& params);
~EnumFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateMembers(io::Printer* printer, bool lazy_init) const;
void GenerateClearCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCodeCode(io::Printer* printer) const;
private:
const FieldDescriptor* descriptor_;
std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
};
class AccessorEnumFieldGenerator : public FieldGenerator {
public:
explicit AccessorEnumFieldGenerator(const FieldDescriptor* descriptor,
const Params& params, int has_bit_index);
~AccessorEnumFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateMembers(io::Printer* printer, bool lazy_init) const;
void GenerateClearCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCodeCode(io::Printer* printer) const;
private:
const FieldDescriptor* descriptor_;
std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorEnumFieldGenerator);
};
class RepeatedEnumFieldGenerator : public FieldGenerator {
public:
explicit RepeatedEnumFieldGenerator(
const FieldDescriptor* descriptor, const Params& params);
~RepeatedEnumFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateMembers(io::Printer* printer, bool lazy_init) const;
void GenerateClearCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateMergingCodeFromPacked(io::Printer* printer) const;
void GenerateSerializationCode(io::Printer* printer) const;
void GenerateSerializedSizeCode(io::Printer* printer) const;
void GenerateEqualsCode(io::Printer* printer) const;
void GenerateHashCodeCode(io::Printer* printer) const;
void GenerateFixClonedCode(io::Printer* printer) const;
private:
void GenerateRepeatedDataSizeCode(io::Printer* printer) const;
const FieldDescriptor* descriptor_;
std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
};
} // namespace javanano
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__
@@ -1,150 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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: bduff@google.com (Brian Duff)
#include <google/protobuf/compiler/javanano/javanano_extension.h>
#include <google/protobuf/compiler/javanano/javanano_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/wire_format.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace javanano {
using internal::WireFormat;
using internal::WireFormatLite;
namespace {
const char* GetTypeConstantName(const FieldDescriptor::Type type) {
switch (type) {
case FieldDescriptor::TYPE_INT32 : return "TYPE_INT32" ;
case FieldDescriptor::TYPE_UINT32 : return "TYPE_UINT32" ;
case FieldDescriptor::TYPE_SINT32 : return "TYPE_SINT32" ;
case FieldDescriptor::TYPE_FIXED32 : return "TYPE_FIXED32" ;
case FieldDescriptor::TYPE_SFIXED32: return "TYPE_SFIXED32";
case FieldDescriptor::TYPE_INT64 : return "TYPE_INT64" ;
case FieldDescriptor::TYPE_UINT64 : return "TYPE_UINT64" ;
case FieldDescriptor::TYPE_SINT64 : return "TYPE_SINT64" ;
case FieldDescriptor::TYPE_FIXED64 : return "TYPE_FIXED64" ;
case FieldDescriptor::TYPE_SFIXED64: return "TYPE_SFIXED64";
case FieldDescriptor::TYPE_FLOAT : return "TYPE_FLOAT" ;
case FieldDescriptor::TYPE_DOUBLE : return "TYPE_DOUBLE" ;
case FieldDescriptor::TYPE_BOOL : return "TYPE_BOOL" ;
case FieldDescriptor::TYPE_STRING : return "TYPE_STRING" ;
case FieldDescriptor::TYPE_BYTES : return "TYPE_BYTES" ;
case FieldDescriptor::TYPE_ENUM : return "TYPE_ENUM" ;
case FieldDescriptor::TYPE_GROUP : return "TYPE_GROUP" ;
case FieldDescriptor::TYPE_MESSAGE : return "TYPE_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;
}
} // namespace
void SetVariables(const FieldDescriptor* descriptor, const Params params,
std::map<string, string>* variables) {
(*variables)["extends"] = ClassName(params, descriptor->containing_type());
(*variables)["name"] = RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
bool repeated = descriptor->is_repeated();
(*variables)["repeated"] = repeated ? "Repeated" : "";
(*variables)["type"] = GetTypeConstantName(descriptor->type());
JavaType java_type = GetJavaType(descriptor->type());
string tag = SimpleItoa(WireFormat::MakeTag(descriptor));
if (java_type == JAVATYPE_MESSAGE) {
(*variables)["ext_type"] = "MessageTyped";
string message_type = ClassName(params, descriptor->message_type());
if (repeated) {
message_type += "[]";
}
(*variables)["class"] = message_type;
// For message typed extensions, tags_params contains a single tag
// for both singular and repeated cases.
(*variables)["tag_params"] = tag;
} else {
(*variables)["ext_type"] = "PrimitiveTyped";
if (!repeated) {
(*variables)["class"] = BoxedPrimitiveTypeName(java_type);
(*variables)["tag_params"] = tag;
} else {
(*variables)["class"] = PrimitiveTypeName(java_type) + "[]";
if (!descriptor->is_packable()) {
// Non-packable: nonPackedTag == tag, packedTag == 0
(*variables)["tag_params"] = tag + ", " + tag + ", 0";
} else if (descriptor->options().packed()) {
// Packable and packed: tag == packedTag
string non_packed_tag = SimpleItoa(WireFormatLite::MakeTag(
descriptor->number(),
WireFormat::WireTypeForFieldType(descriptor->type())));
(*variables)["tag_params"] = tag + ", " + non_packed_tag + ", " + tag;
} else {
// Packable and not packed: tag == nonPackedTag
string packed_tag = SimpleItoa(WireFormatLite::MakeTag(
descriptor->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED));
(*variables)["tag_params"] = tag + ", " + tag + ", " + packed_tag;
}
}
}
}
ExtensionGenerator::
ExtensionGenerator(const FieldDescriptor* descriptor, const Params& params)
: params_(params), descriptor_(descriptor) {
SetVariables(descriptor, params, &variables_);
}
ExtensionGenerator::~ExtensionGenerator() {}
void ExtensionGenerator::Generate(io::Printer* printer) const {
printer->Print("\n");
PrintFieldComment(printer, descriptor_);
printer->Print(variables_,
"public static final com.google.protobuf.nano.Extension<\n"
" $extends$,\n"
" $class$> $name$ =\n"
" com.google.protobuf.nano.Extension.create$repeated$$ext_type$(\n"
" com.google.protobuf.nano.Extension.$type$,\n"
" $class$.class,\n"
" $tag_params$L);\n");
}
} // namespace javanano
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -1,209 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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 <google/protobuf/compiler/javanano/javanano_field.h>
#include <google/protobuf/compiler/javanano/javanano_helpers.h>
#include <google/protobuf/compiler/javanano/javanano_primitive_field.h>
#include <google/protobuf/compiler/javanano/javanano_enum_field.h>
#include <google/protobuf/compiler/javanano/javanano_map_field.h>
#include <google/protobuf/compiler/javanano/javanano_message_field.h>
#include <google/protobuf/stubs/common.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace javanano {
FieldGenerator::~FieldGenerator() {}
bool FieldGenerator::SavedDefaultNeeded() const {
// No saved default for this field by default.
// Subclasses whose instances may need saved defaults will override this
// and return the appropriate value.
return false;
}
void FieldGenerator::GenerateInitSavedDefaultCode(io::Printer* printer) const {
// No saved default for this field by default.
// Subclasses whose instances may need saved defaults will override this
// and generate the appropriate init code to the printer.
}
void FieldGenerator::GenerateMergingCodeFromPacked(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) << "GenerateParsingCodeFromPacked() "
<< "called on field generator that does not support packing.";
}
// =============================================
FieldGeneratorMap::FieldGeneratorMap(
const Descriptor* descriptor, const Params &params)
: descriptor_(descriptor),
field_generators_(
new scoped_ptr<FieldGenerator>[descriptor->field_count()]) {
int next_has_bit_index = 0;
bool saved_defaults_needed = false;
// Construct all the FieldGenerators.
for (int i = 0; i < descriptor->field_count(); i++) {
FieldGenerator* field_generator = MakeGenerator(
descriptor->field(i), params, &next_has_bit_index);
saved_defaults_needed = saved_defaults_needed
|| field_generator->SavedDefaultNeeded();
field_generators_[i].reset(field_generator);
}
total_bits_ = next_has_bit_index;
saved_defaults_needed_ = saved_defaults_needed;
}
FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field,
const Params &params, int* next_has_bit_index) {
JavaType java_type = GetJavaType(field);
if (field->is_repeated()) {
switch (java_type) {
case JAVATYPE_MESSAGE:
if (IsMapEntry(field->message_type())) {
return new MapFieldGenerator(field, params);
} else {
return new RepeatedMessageFieldGenerator(field, params);
}
case JAVATYPE_ENUM:
return new RepeatedEnumFieldGenerator(field, params);
default:
return new RepeatedPrimitiveFieldGenerator(field, params);
}
} else if (field->containing_oneof()) {
switch (java_type) {
case JAVATYPE_MESSAGE:
return new MessageOneofFieldGenerator(field, params);
case JAVATYPE_ENUM:
default:
return new PrimitiveOneofFieldGenerator(field, params);
}
} else if (params.optional_field_accessors() && field->is_optional()
&& java_type != JAVATYPE_MESSAGE) {
// We need a has-bit for each primitive/enum field because their default
// values could be same as explicitly set values. But we don't need it
// for a message field because they have no defaults and Nano uses 'null'
// for unset messages, which cannot be set explicitly.
switch (java_type) {
case JAVATYPE_ENUM:
return new AccessorEnumFieldGenerator(
field, params, (*next_has_bit_index)++);
default:
return new AccessorPrimitiveFieldGenerator(
field, params, (*next_has_bit_index)++);
}
} else {
switch (java_type) {
case JAVATYPE_MESSAGE:
return new MessageFieldGenerator(field, params);
case JAVATYPE_ENUM:
return new EnumFieldGenerator(field, params);
default:
return new PrimitiveFieldGenerator(field, params);
}
}
}
FieldGeneratorMap::~FieldGeneratorMap() {}
const FieldGenerator& FieldGeneratorMap::get(
const FieldDescriptor* field) const {
GOOGLE_CHECK_EQ(field->containing_type(), descriptor_);
return *field_generators_[field->index()];
}
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables) {
(*variables)["oneof_name"] =
UnderscoresToCamelCase(descriptor->containing_oneof());
(*variables)["oneof_capitalized_name"] =
UnderscoresToCapitalizedCamelCase(descriptor->containing_oneof());
(*variables)["oneof_index"] =
SimpleItoa(descriptor->containing_oneof()->index());
(*variables)["set_oneof_case"] =
"this." + (*variables)["oneof_name"] +
"Case_ = " + SimpleItoa(descriptor->number());
(*variables)["clear_oneof_case"] =
"this." + (*variables)["oneof_name"] + "Case_ = 0";
(*variables)["has_oneof_case"] =
"this." + (*variables)["oneof_name"] + "Case_ == " +
SimpleItoa(descriptor->number());
}
void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
const std::map<string, string>& variables,
io::Printer* printer) {
if (GetJavaType(descriptor) == JAVATYPE_BYTES) {
printer->Print(variables,
"if (this.has$capitalized_name$()) {\n"
" if (!java.util.Arrays.equals((byte[]) this.$oneof_name$_,\n"
" (byte[]) other.$oneof_name$_)) {\n"
" return false;\n"
" }\n"
"}\n");
} else {
printer->Print(variables,
"if (this.has$capitalized_name$()) {\n"
" if (!this.$oneof_name$_.equals(other.$oneof_name$_)) {\n"
" return false;\n"
" }\n"
"}\n");
}
}
void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor,
const std::map<string, string>& variables,
io::Printer* printer) {
if (GetJavaType(descriptor) == JAVATYPE_BYTES) {
printer->Print(variables,
"result = 31 * result + ($has_oneof_case$\n"
" ? java.util.Arrays.hashCode((byte[]) this.$oneof_name$_) : 0);\n");
} else {
printer->Print(variables,
"result = 31 * result +\n"
" ($has_oneof_case$ ? this.$oneof_name$_.hashCode() : 0);\n");
}
}
} // namespace javanano
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -1,130 +0,0 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// 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_JAVANANO_FIELD_H__
#define GOOGLE_PROTOBUF_COMPILER_JAVANANO_FIELD_H__
#include <map>
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/compiler/javanano/javanano_params.h>
namespace google {
namespace protobuf {
namespace io {
class Printer; // printer.h
}
}
namespace protobuf {
namespace compiler {
namespace javanano {
class FieldGenerator {
public:
FieldGenerator(const Params& params) : params_(params) {}
virtual ~FieldGenerator();
virtual bool SavedDefaultNeeded() const;
virtual void GenerateInitSavedDefaultCode(io::Printer* printer) const;
// Generates code for Java fields and methods supporting this field.
// If this field needs a saved default (SavedDefaultNeeded() is true),
// then @lazy_init controls how the static field for that default value
// and its initialization code should be generated. If @lazy_init is
// true, the static field is not declared final and the initialization
// code is generated only when GenerateInitSavedDefaultCode is called;
// otherwise, the static field is declared final and initialized inline.
// GenerateInitSavedDefaultCode will not be called in the latter case.
virtual void GenerateMembers(
io::Printer* printer, bool lazy_init) const = 0;
virtual void GenerateClearCode(io::Printer* printer) const = 0;
virtual void GenerateMergingCode(io::Printer* printer) const = 0;
// Generates code to merge from packed serialized form. The default
// implementation will fail; subclasses which can handle packed serialized
// forms will override this and print appropriate code to the printer.
virtual void GenerateMergingCodeFromPacked(io::Printer* printer) const;
virtual void GenerateSerializationCode(io::Printer* printer) const = 0;
virtual void GenerateSerializedSizeCode(io::Printer* printer) const = 0;
virtual void GenerateEqualsCode(io::Printer* printer) const = 0;
virtual void GenerateHashCodeCode(io::Printer* printer) const = 0;
virtual void GenerateFixClonedCode(io::Printer* printer) const {}
protected:
const Params& params_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);
};
// Convenience class which constructs FieldGenerators for a Descriptor.
class FieldGeneratorMap {
public:
explicit FieldGeneratorMap(const Descriptor* descriptor, const Params &params);
~FieldGeneratorMap();
const FieldGenerator& get(const FieldDescriptor* field) const;
int total_bits() const { return total_bits_; }
bool saved_defaults_needed() const { return saved_defaults_needed_; }
private:
const Descriptor* descriptor_;
scoped_array<scoped_ptr<FieldGenerator> > field_generators_;
int total_bits_;
bool saved_defaults_needed_;
static FieldGenerator* MakeGenerator(const FieldDescriptor* field,
const Params &params, int* next_has_bit_index);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables);
void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
const std::map<string, string>& variables,
io::Printer* printer);
void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor,
const std::map<string, string>& variables,
io::Printer* printer);
} // namespace javanano
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_FIELD_H__
Loaded 100 of 421 files, more files were not shown because too many files have changed in this diff. Show more