windows pbuf 3.5

This commit is contained in:
Kevin Darby committed 2018-12-28 12:56:19 -05:00
1 parent cc3510c6c2
commit 9caeae1761
370 files changed
+35788 -24867

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
$protobuf = "protobuf-3.3.0"
$protobuf = "protobuf-3.5.0"
$root = Resolve-Path "../.."
$work = Join-Path $root "work"
$src = Join-Path $root src
+18
View File
@@ -0,0 +1,18 @@
run this: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\VC\Auxiliary\Build\vcvars64.bat
then from
\spark\externals\src\protobuf> powershell -executionpolicy remotesigned -File build_protobuf.ps1
you will probably want to put
#pragma warning( push )
#pragma warning( disable : 4146)
at wire_formate_lite.h line 862
and then
#pragma warning( pop )
at 881
Binary file not shown.
+77 -181
View File
@@ -1,7 +1,6 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/any.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/any.pb.h>
#include <algorithm>
@@ -15,56 +14,61 @@
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// This is a temporary google only hack
#ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS
#include "third_party/protobuf/version.h"
#endif
// @@protoc_insertion_point(includes)
namespace google {
namespace protobuf {
class AnyDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Any> {
class AnyDefaultTypeInternal {
public:
::google::protobuf::internal::ExplicitlyConstructed<Any>
_instance;
} _Any_default_instance_;
} // namespace protobuf
} // namespace google
namespace protobuf_google_2fprotobuf_2fany_2eproto {
void InitDefaultsAnyImpl() {
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();
::google::protobuf::internal::OnShutdownDestroyMessage(ptr);
}
::google::protobuf::Any::InitAsDefaultInstance();
}
namespace {
void InitDefaultsAny() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &InitDefaultsAnyImpl);
}
::google::protobuf::Metadata file_level_metadata[1];
} // namespace
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField
const TableStruct::entries[] = {
{0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0},
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField
const TableStruct::aux[] = {
::google::protobuf::internal::AuxillaryParseTableField(),
};
PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const
TableStruct::schema[] = {
{ NULL, NULL, 0, -1, -1, false },
};
const ::google::protobuf::uint32 TableStruct::offsets[] = {
const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
~0u, // no _has_bits_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, _internal_metadata_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, _internal_metadata_),
~0u, // no _extensions_
~0u, // no _oneof_case_
~0u, // no _weak_field_map_
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, type_url_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Any, value_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, type_url_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::google::protobuf::Any, value_),
};
static const ::google::protobuf::internal::MigrationSchema schemas[] = {
{ 0, -1, sizeof(Any)},
static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
{ 0, -1, sizeof(::google::protobuf::Any)},
};
static ::google::protobuf::Message const * const file_default_instances[] = {
reinterpret_cast<const ::google::protobuf::Message*>(&_Any_default_instance_),
reinterpret_cast<const ::google::protobuf::Message*>(&::google::protobuf::_Any_default_instance_),
};
namespace {
void protobuf_AssignDescriptors() {
AddDescriptors();
::google::protobuf::MessageFactory* factory = NULL;
@@ -78,33 +82,15 @@ void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 1);
}
} // namespace
void TableStruct::Shutdown() {
_Any_default_instance_.Shutdown();
delete file_level_metadata[0].reflection;
}
void TableStruct::InitDefaultsImpl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::internal::InitProtobufDefaults();
_Any_default_instance_.DefaultConstruct();
}
void InitDefaults() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl);
}
void AddDescriptorsImpl() {
InitDefaults();
static const char descriptor[] = {
static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = {
"\n\031google/protobuf/any.proto\022\017google.prot"
"obuf\"&\n\003Any\022\020\n\010type_url\030\001 \001(\t\022\r\n\005value\030\002"
" \001(\014Bo\n\023com.google.protobufB\010AnyProtoP\001Z"
@@ -116,25 +102,26 @@ void AddDescriptorsImpl() {
descriptor, 205);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/any.proto", &protobuf_RegisterTypes);
::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown);
}
void AddDescriptors() {
static GOOGLE_PROTOBUF_DECLARE_ONCE(once);
::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl);
}
// Force AddDescriptors() to be called at static initialization time.
// Force AddDescriptors() to be called at dynamic initialization time.
struct StaticDescriptorInitializer {
StaticDescriptorInitializer() {
AddDescriptors();
}
} static_descriptor_initializer;
} // namespace protobuf_google_2fprotobuf_2fany_2eproto
namespace google {
namespace protobuf {
// ===================================================================
void Any::InitAsDefaultInstance() {
}
void Any::PackFrom(const ::google::protobuf::Message& message) {
_any_metadata_.PackFrom(message);
}
@@ -156,7 +143,7 @@ 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::InitDefaults();
::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
}
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.Any)
@@ -200,12 +187,12 @@ void Any::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Any::descriptor() {
protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
::protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages].descriptor;
}
const Any& Any::default_instance() {
protobuf_google_2fprotobuf_2fany_2eproto::InitDefaults();
::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAny();
return *internal_default_instance();
}
@@ -219,8 +206,13 @@ Any* Any::New(::google::protobuf::Arena* arena) const {
void Any::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.Any)
::google::protobuf::uint32 cached_has_bits = 0;
// Prevent compiler warnings about cached_has_bits being unused
(void) cached_has_bits;
type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
_internal_metadata_.Clear();
}
bool Any::MergePartialFromCodedStream(
@@ -236,11 +228,11 @@ bool Any::MergePartialFromCodedStream(
// string type_url = 1;
case 1: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(10u)) {
static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_type_url()));
DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->type_url().data(), this->type_url().length(),
this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::PARSE,
"google.protobuf.Any.type_url"));
} else {
@@ -252,7 +244,7 @@ bool Any::MergePartialFromCodedStream(
// bytes value = 2;
case 2: {
if (static_cast< ::google::protobuf::uint8>(tag) ==
static_cast< ::google::protobuf::uint8>(18u)) {
static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) {
DO_(::google::protobuf::internal::WireFormatLite::ReadBytes(
input, this->mutable_value()));
} else {
@@ -263,12 +255,11 @@ bool Any::MergePartialFromCodedStream(
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
if (tag == 0) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, _internal_metadata_.mutable_unknown_fields()));
break;
}
}
@@ -291,7 +282,7 @@ void Any::SerializeWithCachedSizes(
// string type_url = 1;
if (this->type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->type_url().data(), this->type_url().length(),
this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Any.type_url");
::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
@@ -304,11 +295,16 @@ void Any::SerializeWithCachedSizes(
2, this->value(), output);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.Any)
}
::google::protobuf::uint8* Any::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.Any)
::google::protobuf::uint32 cached_has_bits = 0;
(void) cached_has_bits;
@@ -316,7 +312,7 @@ void Any::SerializeWithCachedSizes(
// string type_url = 1;
if (this->type_url().size() > 0) {
::google::protobuf::internal::WireFormatLite::VerifyUtf8String(
this->type_url().data(), this->type_url().length(),
this->type_url().data(), static_cast<int>(this->type_url().length()),
::google::protobuf::internal::WireFormatLite::SERIALIZE,
"google.protobuf.Any.type_url");
target =
@@ -331,6 +327,10 @@ void Any::SerializeWithCachedSizes(
2, this->value(), target);
}
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.Any)
return target;
}
@@ -339,6 +339,11 @@ size_t Any::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.Any)
size_t total_size = 0;
if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
(::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()));
}
// string type_url = 1;
if (this->type_url().size() > 0) {
total_size += 1 +
@@ -415,129 +420,20 @@ void Any::Swap(Any* other) {
InternalSwap(other);
}
void Any::InternalSwap(Any* other) {
using std::swap;
type_url_.Swap(&other->type_url_);
value_.Swap(&other->value_);
std::swap(_cached_size_, other->_cached_size_);
_internal_metadata_.Swap(&other->_internal_metadata_);
swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Any::GetMetadata() const {
protobuf_google_2fprotobuf_2fany_2eproto::protobuf_AssignDescriptorsOnce();
return protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages];
return ::protobuf_google_2fprotobuf_2fany_2eproto::file_level_metadata[kIndexInFileMessages];
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Any
// string type_url = 1;
void Any::clear_type_url() {
type_url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& Any::type_url() const {
// @@protoc_insertion_point(field_get:google.protobuf.Any.type_url)
return type_url_.GetNoArena();
}
void Any::set_type_url(const ::std::string& value) {
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Any.type_url)
}
#if LANG_CXX11
void Any::set_type_url(::std::string&& value) {
type_url_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.type_url)
}
#endif
void Any::set_type_url(const char* value) {
GOOGLE_DCHECK(value != NULL);
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.type_url)
}
void Any::set_type_url(const char* value, size_t size) {
type_url_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.type_url)
}
::std::string* Any::mutable_type_url() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Any.type_url)
return type_url_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* Any::release_type_url() {
// @@protoc_insertion_point(field_release:google.protobuf.Any.type_url)
return type_url_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void Any::set_allocated_type_url(::std::string* type_url) {
if (type_url != NULL) {
} else {
}
type_url_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type_url);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.type_url)
}
// bytes value = 2;
void Any::clear_value() {
value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
const ::std::string& Any::value() const {
// @@protoc_insertion_point(field_get:google.protobuf.Any.value)
return value_.GetNoArena();
}
void Any::set_value(const ::std::string& value) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:google.protobuf.Any.value)
}
#if LANG_CXX11
void Any::set_value(::std::string&& value) {
value_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:google.protobuf.Any.value)
}
#endif
void Any::set_value(const char* value) {
GOOGLE_DCHECK(value != NULL);
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:google.protobuf.Any.value)
}
void Any::set_value(const void* value, size_t size) {
value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:google.protobuf.Any.value)
}
::std::string* Any::mutable_value() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Any.value)
return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
::std::string* Any::release_value() {
// @@protoc_insertion_point(field_release:google.protobuf.Any.value)
return value_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
void Any::set_allocated_value(::std::string* value) {
if (value != NULL) {
} else {
}
value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+47 -21
View File
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3003000
#if GOOGLE_PROTOBUF_VERSION < 3005000
#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 3003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#if 3005000 < 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.
@@ -31,6 +31,24 @@
#include <google/protobuf/unknown_field_set.h>
#include <google/protobuf/any.h>
// @@protoc_insertion_point(includes)
namespace protobuf_google_2fprotobuf_2fany_2eproto {
// Internal implementation detail -- do not use these members.
struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[1];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
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 {
class Any;
@@ -38,24 +56,9 @@ class AnyDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern AnyDefaultTypeInternal _Any_default_instance_;
} // namespace protobuf
} // namespace google
namespace google {
namespace protobuf {
namespace protobuf_google_2fprotobuf_2fany_2eproto {
// Internal implementation detail -- do not call these.
struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[];
static const ::google::protobuf::uint32 offsets[];
static void InitDefaultsImpl();
static void Shutdown();
};
void LIBPROTOBUF_EXPORT AddDescriptors();
void LIBPROTOBUF_EXPORT InitDefaults();
} // namespace protobuf_google_2fprotobuf_2fany_2eproto
// ===================================================================
class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Any) */ {
@@ -69,10 +72,25 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Any(Any&& from) noexcept
: Any() {
*this = ::std::move(from);
}
inline Any& operator=(Any&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor();
static const Any& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Any* internal_default_instance() {
return reinterpret_cast<const Any*>(
&_Any_default_instance_);
@@ -91,6 +109,9 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
}
void Swap(Any* other);
friend void swap(Any& a, Any& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
@@ -168,14 +189,18 @@ class LIBPROTOBUF_EXPORT Any : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::internal::ArenaStringPtr value_;
mutable int _cached_size_;
::google::protobuf::internal::AnyMetadata _any_metadata_;
friend struct protobuf_google_2fprotobuf_2fany_2eproto::TableStruct;
friend struct ::protobuf_google_2fprotobuf_2fany_2eproto::TableStruct;
friend void ::protobuf_google_2fprotobuf_2fany_2eproto::InitDefaultsAnyImpl();
};
// ===================================================================
// ===================================================================
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// Any
// string type_url = 1;
@@ -284,11 +309,12 @@ inline void Any::set_allocated_value(::std::string* value) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+10
View File
@@ -74,6 +74,16 @@ option objc_class_prefix = "GPB";
// any.Unpack(foo)
// ...
//
// Example 4: Pack and unpack a message in Go
//
// foo := &pb.Foo{...}
// any, err := ptypes.MarshalAny(foo)
// ...
// foo := &pb.Foo{}
// if err := ptypes.UnmarshalAny(any, foo); err != nil {
// ...
// }
//
// The pack methods provided by protobuf library will by default use
// 'type.googleapis.com/full.type.name' as the type URL and the unpack
// methods only use the fully qualified type name after the last '/'
File diff suppressed because it is too large. Load diff
+114 -63
View File
@@ -8,12 +8,12 @@
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3003000
#if GOOGLE_PROTOBUF_VERSION < 3005000
#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 3003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#if 3005000 < 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.
@@ -32,55 +32,46 @@
#include <google/protobuf/source_context.pb.h>
#include <google/protobuf/type.pb.h>
// @@protoc_insertion_point(includes)
namespace protobuf_google_2fprotobuf_2fapi_2eproto {
// Internal implementation detail -- do not use these members.
struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[3];
static const ::google::protobuf::internal::FieldMetadata field_metadata[];
static const ::google::protobuf::internal::SerializationTable serialization_table[];
static const ::google::protobuf::uint32 offsets[];
};
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 {
class Api;
class ApiDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern ApiDefaultTypeInternal _Api_default_instance_;
class Enum;
class EnumDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern EnumDefaultTypeInternal _Enum_default_instance_;
class EnumValue;
class EnumValueDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern EnumValueDefaultTypeInternal _EnumValue_default_instance_;
class Field;
class FieldDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern FieldDefaultTypeInternal _Field_default_instance_;
class Method;
class MethodDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern MethodDefaultTypeInternal _Method_default_instance_;
class Mixin;
class MixinDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern MixinDefaultTypeInternal _Mixin_default_instance_;
class Option;
class OptionDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern OptionDefaultTypeInternal _Option_default_instance_;
class SourceContext;
class SourceContextDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern SourceContextDefaultTypeInternal _SourceContext_default_instance_;
class Type;
class TypeDefaultTypeInternal;
LIBPROTOBUF_EXPORT extern TypeDefaultTypeInternal _Type_default_instance_;
} // namespace protobuf
} // namespace google
namespace google {
namespace protobuf {
namespace protobuf_google_2fprotobuf_2fapi_2eproto {
// Internal implementation detail -- do not call these.
struct LIBPROTOBUF_EXPORT TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[];
static const ::google::protobuf::uint32 offsets[];
static void InitDefaultsImpl();
static void Shutdown();
};
void LIBPROTOBUF_EXPORT AddDescriptors();
void LIBPROTOBUF_EXPORT InitDefaults();
} // namespace protobuf_google_2fprotobuf_2fapi_2eproto
// ===================================================================
class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.Api) */ {
@@ -94,10 +85,25 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Api(Api&& from) noexcept
: Api() {
*this = ::std::move(from);
}
inline Api& operator=(Api&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor();
static const Api& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Api* internal_default_instance() {
return reinterpret_cast<const Api*>(
&_Api_default_instance_);
@@ -106,6 +112,9 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
0;
void Swap(Api* other);
friend void swap(Api& a, Api& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
@@ -216,8 +225,8 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
void clear_source_context();
static const int kSourceContextFieldNumber = 5;
const ::google::protobuf::SourceContext& source_context() const;
::google::protobuf::SourceContext* mutable_source_context();
::google::protobuf::SourceContext* release_source_context();
::google::protobuf::SourceContext* mutable_source_context();
void set_allocated_source_context(::google::protobuf::SourceContext* source_context);
// .google.protobuf.Syntax syntax = 7;
@@ -238,7 +247,8 @@ class LIBPROTOBUF_EXPORT Api : public ::google::protobuf::Message /* @@protoc_in
::google::protobuf::SourceContext* source_context_;
int syntax_;
mutable int _cached_size_;
friend struct protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsApiImpl();
};
// -------------------------------------------------------------------
@@ -253,10 +263,25 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Method(Method&& from) noexcept
: Method() {
*this = ::std::move(from);
}
inline Method& operator=(Method&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor();
static const Method& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Method* internal_default_instance() {
return reinterpret_cast<const Method*>(
&_Method_default_instance_);
@@ -265,6 +290,9 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
1;
void Swap(Method* other);
friend void swap(Method& a, Method& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
@@ -390,7 +418,8 @@ class LIBPROTOBUF_EXPORT Method : public ::google::protobuf::Message /* @@protoc
bool response_streaming_;
int syntax_;
mutable int _cached_size_;
friend struct protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMethodImpl();
};
// -------------------------------------------------------------------
@@ -405,10 +434,25 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
CopyFrom(from);
return *this;
}
#if LANG_CXX11
Mixin(Mixin&& from) noexcept
: Mixin() {
*this = ::std::move(from);
}
inline Mixin& operator=(Mixin&& from) noexcept {
if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
if (this != &from) InternalSwap(&from);
} else {
CopyFrom(from);
}
return *this;
}
#endif
static const ::google::protobuf::Descriptor* descriptor();
static const Mixin& default_instance();
static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY
static inline const Mixin* internal_default_instance() {
return reinterpret_cast<const Mixin*>(
&_Mixin_default_instance_);
@@ -417,6 +461,9 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
2;
void Swap(Mixin* other);
friend void swap(Mixin& a, Mixin& b) {
a.Swap(&b);
}
// implements Message ----------------------------------------------
@@ -493,14 +540,18 @@ class LIBPROTOBUF_EXPORT Mixin : public ::google::protobuf::Message /* @@protoc_
::google::protobuf::internal::ArenaStringPtr name_;
::google::protobuf::internal::ArenaStringPtr root_;
mutable int _cached_size_;
friend struct protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend struct ::protobuf_google_2fprotobuf_2fapi_2eproto::TableStruct;
friend void ::protobuf_google_2fprotobuf_2fapi_2eproto::InitDefaultsMixinImpl();
};
// ===================================================================
// ===================================================================
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
// Api
// string name = 1;
@@ -590,9 +641,6 @@ Api::methods() const {
inline int Api::options_size() const {
return options_.size();
}
inline void Api::clear_options() {
options_.Clear();
}
inline const ::google::protobuf::Option& Api::options(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Api.options)
return options_.Get(index);
@@ -673,14 +721,18 @@ 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 void Api::clear_source_context() {
if (GetArenaNoVirtual() == NULL && source_context_ != NULL) delete source_context_;
source_context_ = NULL;
}
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)
return source_context_ != NULL ? *source_context_
: *::google::protobuf::SourceContext::internal_default_instance();
return p != NULL ? *p : *reinterpret_cast<const ::google::protobuf::SourceContext*>(
&::google::protobuf::_SourceContext_default_instance_);
}
inline ::google::protobuf::SourceContext* Api::release_source_context() {
// @@protoc_insertion_point(field_release:google.protobuf.Api.source_context)
::google::protobuf::SourceContext* temp = source_context_;
source_context_ = NULL;
return temp;
}
inline ::google::protobuf::SourceContext* Api::mutable_source_context() {
@@ -690,21 +742,22 @@ inline ::google::protobuf::SourceContext* Api::mutable_source_context() {
// @@protoc_insertion_point(field_mutable:google.protobuf.Api.source_context)
return source_context_;
}
inline ::google::protobuf::SourceContext* Api::release_source_context() {
// @@protoc_insertion_point(field_release:google.protobuf.Api.source_context)
::google::protobuf::SourceContext* temp = source_context_;
source_context_ = NULL;
return temp;
}
inline void Api::set_allocated_source_context(::google::protobuf::SourceContext* source_context) {
delete source_context_;
source_context_ = source_context;
::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
if (message_arena == NULL) {
delete reinterpret_cast< ::google::protobuf::MessageLite*>(source_context_);
}
if (source_context) {
::google::protobuf::Arena* submessage_arena = NULL;
if (message_arena != submessage_arena) {
source_context = ::google::protobuf::internal::GetOwnedMessage(
message_arena, source_context, submessage_arena);
}
} else {
}
source_context_ = source_context;
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.source_context)
}
@@ -947,9 +1000,6 @@ inline void Method::set_response_streaming(bool value) {
inline int Method::options_size() const {
return options_.size();
}
inline void Method::clear_options() {
options_.Clear();
}
inline const ::google::protobuf::Option& Method::options(int index) const {
// @@protoc_insertion_point(field_get:google.protobuf.Method.options)
return options_.Get(index);
@@ -1097,7 +1147,9 @@ inline void Mixin::set_allocated_root(::std::string* root) {
// @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root)
}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif // __GNUC__
// -------------------------------------------------------------------
// -------------------------------------------------------------------
@@ -1105,7 +1157,6 @@ inline void Mixin::set_allocated_root(::std::string* root) {
// @@protoc_insertion_point(namespace_scope)
} // namespace protobuf
} // namespace google
+29 -21
View File
@@ -42,26 +42,33 @@ option java_multiple_files = true;
option objc_class_prefix = "GPB";
option go_package = "google.golang.org/genproto/protobuf/api;api";
// Api is a light-weight descriptor for a protocol buffer service.
// Api is a light-weight descriptor for an API Interface.
//
// Interfaces are also described as "protocol buffer services" in some contexts,
// such as by the "service" keyword in a .proto file, but they are different
// from API Services, which represent a concrete implementation of an interface
// as opposed to simply a description of methods and bindings. They are also
// sometimes simply referred to as "APIs" in other contexts, such as the name of
// this message itself. See https://cloud.google.com/apis/design/glossary for
// detailed terminology.
message Api {
// The fully qualified name of this api, including package name
// followed by the api's simple name.
// The fully qualified name of this interface, including package name
// followed by the interface's simple name.
string name = 1;
// The methods of this api, in unspecified order.
// The methods of this interface, in unspecified order.
repeated Method methods = 2;
// Any metadata attached to the API.
// Any metadata attached to the interface.
repeated Option options = 3;
// A version string for this api. If specified, must have the form
// `major-version.minor-version`, as in `1.10`. If the minor version
// is omitted, it defaults to zero. If the entire version field is
// empty, the major version is derived from the package name, as
// outlined below. If the field is not empty, the version in the
// package name will be verified to be consistent with what is
// provided here.
// A version string for this interface. If specified, must have the form
// `major-version.minor-version`, as in `1.10`. If the minor version is
// omitted, it defaults to zero. If the entire version field is empty, the
// major version is derived from the package name, as outlined below. If the
// field is not empty, the version in the package name will be verified to be
// consistent with what is provided here.
//
// The versioning schema uses [semantic
// versioning](http://semver.org) where the major version number
@@ -71,10 +78,10 @@ message Api {
// chosen based on the product plan.
//
// The major version is also reflected in the package name of the
// API, which must end in `v<major-version>`, as in
// interface, which must end in `v<major-version>`, as in
// `google.feature.v1`. For major versions 0 and 1, the suffix can
// be omitted. Zero major versions must only be used for
// experimental, none-GA apis.
// experimental, non-GA interfaces.
//
//
string version = 4;
@@ -83,14 +90,14 @@ message Api {
// message.
SourceContext source_context = 5;
// Included APIs. See [Mixin][].
// Included interfaces. See [Mixin][].
repeated Mixin mixins = 6;
// The source syntax of the service.
Syntax syntax = 7;
}
// Method represents a method of an api.
// Method represents a method of an API interface.
message Method {
// The simple name of this method.
@@ -115,9 +122,9 @@ message Method {
Syntax syntax = 7;
}
// Declares an API to be included in this API. The including API must
// redeclare all the methods from the included API, but documentation
// and options are inherited as follows:
// Declares an API Interface to be included in this interface. The including
// interface must redeclare all the methods from the included interface, but
// documentation and options are inherited as follows:
//
// - If after comment and whitespace stripping, the documentation
// string of the redeclared method is empty, it will be inherited
@@ -129,7 +136,8 @@ message Method {
//
// - If an http annotation is inherited, the path pattern will be
// modified as follows. Any version prefix will be replaced by the
// version of the including API plus the [root][] path if specified.
// version of the including interface plus the [root][] path if
// specified.
//
// Example of a simple mixin:
//
@@ -193,7 +201,7 @@ message Method {
// ...
// }
message Mixin {
// The fully qualified name of the API which is included.
// The fully qualified name of the interface which is included.
string name = 1;
// If non-empty specifies a path under which inherited HTTP paths
+237 -167
View File
@@ -38,171 +38,187 @@
#include <sanitizer/asan_interface.h>
#endif // ADDRESS_SANITIZER
#include <google/protobuf/stubs/port.h>
namespace google {
static const size_t kMinCleanupListElements = 8;
static const size_t kMaxCleanupListElements = 64; // 1kB on 64-bit.
namespace protobuf {
namespace internal {
google::protobuf::internal::SequenceNumber Arena::lifecycle_id_generator_;
google::protobuf::internal::SequenceNumber ArenaImpl::lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
Arena::ThreadCache& Arena::thread_cache() {
ArenaImpl::ThreadCache& ArenaImpl::thread_cache() {
static internal::ThreadLocalStorage<ThreadCache>* thread_cache_ =
new internal::ThreadLocalStorage<ThreadCache>();
return *thread_cache_->Get();
}
#elif defined(PROTOBUF_USE_DLLS)
Arena::ThreadCache& Arena::thread_cache() {
ArenaImpl::ThreadCache& ArenaImpl::thread_cache() {
static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_ = { -1, NULL };
return thread_cache_;
}
#else
GOOGLE_THREAD_LOCAL Arena::ThreadCache Arena::thread_cache_ = { -1, NULL };
GOOGLE_THREAD_LOCAL ArenaImpl::ThreadCache ArenaImpl::thread_cache_ = {-1, NULL};
#endif
void Arena::Init() {
void ArenaImpl::Init() {
lifecycle_id_ = lifecycle_id_generator_.GetNext();
blocks_ = 0;
hint_ = 0;
space_allocated_ = 0;
owns_first_block_ = true;
cleanup_list_ = 0;
google::protobuf::internal::NoBarrier_Store(&hint_, 0);
google::protobuf::internal::NoBarrier_Store(&threads_, 0);
if (options_.initial_block != NULL && options_.initial_block_size > 0) {
GOOGLE_CHECK_GE(options_.initial_block_size, sizeof(Block))
<< ": Initial block size too small for header.";
// Add first unowned block to list.
Block* first_block = reinterpret_cast<Block*>(options_.initial_block);
first_block->size = options_.initial_block_size;
first_block->pos = kHeaderSize;
first_block->next = NULL;
if (initial_block_) {
// Thread which calls Init() owns the first block. This allows the
// single-threaded case to allocate on the first block without taking any
// locks.
first_block->owner = &thread_cache();
SetThreadCacheBlock(first_block);
AddBlockInternal(first_block);
owns_first_block_ = false;
}
// Call the initialization hook
if (options_.on_arena_init != NULL) {
hooks_cookie_ = options_.on_arena_init(this);
// 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_);
} else {
hooks_cookie_ = NULL;
google::protobuf::internal::NoBarrier_Store(&space_allocated_, 0);
}
}
Arena::~Arena() {
uint64 space_allocated = ResetInternal();
// Call the destruction hook
if (options_.on_arena_destruction != NULL) {
options_.on_arena_destruction(this, hooks_cookie_, space_allocated);
}
ArenaImpl::~ArenaImpl() {
// Have to do this in a first pass, because some of the destructors might
// refer to memory in other blocks.
CleanupList();
FreeBlocks();
}
uint64 Arena::Reset() {
// Invalidate any ThreadCaches pointing to any blocks we just destroyed.
lifecycle_id_ = lifecycle_id_generator_.GetNext();
return ResetInternal();
}
uint64 Arena::ResetInternal() {
uint64 ArenaImpl::Reset() {
// Have to do this in a first pass, because some of the destructors might
// refer to memory in other blocks.
CleanupList();
uint64 space_allocated = FreeBlocks();
// Call the reset hook
if (options_.on_arena_reset != NULL) {
options_.on_arena_reset(this, hooks_cookie_, space_allocated);
}
Init();
return space_allocated;
}
Arena::Block* Arena::NewBlock(void* me, Block* my_last_block, size_t n,
size_t start_block_size, size_t max_block_size) {
ArenaImpl::Block* ArenaImpl::NewBlock(void* me, Block* my_last_block,
size_t min_bytes) {
size_t size;
if (my_last_block != NULL) {
// Double the current block size, up to a limit.
size = 2 * (my_last_block->size);
if (size > max_block_size) size = max_block_size;
size = std::min(2 * my_last_block->size, options_.max_block_size);
} else {
size = start_block_size;
size = options_.start_block_size;
}
// Verify that n + kHeaderSize won't overflow.
GOOGLE_CHECK_LE(n, std::numeric_limits<size_t>::max() - kHeaderSize);
size = std::max(size, kHeaderSize + n);
// 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);
Block* b = reinterpret_cast<Block*>(options_.block_alloc(size));
b->pos = kHeaderSize + n;
InitBlock(b, me, size);
google::protobuf::internal::NoBarrier_AtomicIncrement(&space_allocated_, size);
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
return b;
}
void Arena::AddBlock(Block* b) {
MutexLock l(&blocks_lock_);
AddBlockInternal(b);
}
void Arena::AddBlockInternal(Block* b) {
b->next = reinterpret_cast<Block*>(google::protobuf::internal::NoBarrier_Load(&blocks_));
google::protobuf::internal::Release_Store(&blocks_, reinterpret_cast<google::protobuf::internal::AtomicWord>(b));
if (b->avail() != 0) {
// Direct future allocations to this block.
google::protobuf::internal::Release_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(b));
ArenaImpl::CleanupChunk* ArenaImpl::ExpandCleanupList(CleanupChunk* cleanup,
Block* b) {
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);
}
space_allocated_ += b->size;
CleanupChunk* list =
reinterpret_cast<CleanupChunk*>(AllocFromBlock(b, bytes));
list->next = b->thread_info->cleanup;
list->size = size;
list->len = 0;
b->thread_info->cleanup = list;
return list;
}
void Arena::AddListNode(void* elem, void (*cleanup)(void*)) {
Node* node = reinterpret_cast<Node*>(AllocateAligned(sizeof(Node)));
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);
}
CleanupNode* node = &cleanup->nodes[cleanup->len++];
node->elem = elem;
node->cleanup = cleanup;
node->next = reinterpret_cast<Node*>(
google::protobuf::internal::NoBarrier_AtomicExchange(&cleanup_list_,
reinterpret_cast<google::protobuf::internal::AtomicWord>(node)));
node->cleanup = func;
}
void* Arena::AllocateAligned(const std::type_info* allocated, size_t n) {
// Align n to next multiple of 8 (from Hacker's Delight, Chapter 3.)
n = (n + 7) & -8;
void ArenaImpl::AddCleanup(void* elem, void (*cleanup)(void*)) {
return AddCleanupInBlock(GetBlock(0), elem, cleanup);
}
// Monitor allocation if needed.
if (GOOGLE_PREDICT_FALSE(hooks_cookie_ != NULL) &&
options_.on_arena_allocation != NULL) {
options_.on_arena_allocation(allocated, n, hooks_cookie_);
}
void* ArenaImpl::AllocateAligned(size_t n) {
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
return AllocFromBlock(GetBlock(n), n);
}
void* ArenaImpl::AllocateAlignedAndAddCleanup(size_t n,
void (*cleanup)(void*)) {
GOOGLE_DCHECK_EQ(internal::AlignUpTo8(n), n); // Must be already aligned.
Block* b = GetBlock(n);
void* mem = AllocFromBlock(b, n);
AddCleanupInBlock(b, mem, cleanup);
return mem;
}
inline GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
ArenaImpl::Block* ArenaImpl::GetBlock(size_t n) {
Block* my_block = NULL;
// 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.
if (thread_cache().last_lifecycle_id_seen == lifecycle_id_ &&
thread_cache().last_block_used_ != NULL) {
if (thread_cache().last_block_used_->avail() < n) {
return SlowAlloc(n);
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;
}
return AllocFromBlock(thread_cache().last_block_used_, n);
}
// Check whether we own the last accessed block on this arena.
// This fast path optimizes the case where a single thread uses multiple
// arenas.
void* me = &thread_cache();
Block* b = reinterpret_cast<Block*>(google::protobuf::internal::Acquire_Load(&hint_));
if (!b || b->owner != me || b->avail() < n) {
return SlowAlloc(n);
if (b != NULL && b->owner == tc) {
my_block = b;
if (my_block->avail() >= n) {
return my_block;
}
}
return AllocFromBlock(b, n);
return GetBlockSlow(tc, my_block, n);
}
void* Arena::AllocFromBlock(Block* b, size_t n) {
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;
#ifdef ADDRESS_SANITIZER
@@ -211,104 +227,158 @@ void* Arena::AllocFromBlock(Block* b, size_t n) {
return reinterpret_cast<char*>(b) + p;
}
void* Arena::SlowAlloc(size_t n) {
void* me = &thread_cache();
Block* b = FindBlock(me); // Find block owned by me.
// See if allocation fits in my latest block.
if (b != NULL && b->avail() >= n) {
SetThreadCacheBlock(b);
google::protobuf::internal::NoBarrier_Store(&hint_, reinterpret_cast<google::protobuf::internal::AtomicWord>(b));
return AllocFromBlock(b, n);
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;
}
b = NewBlock(me, b, n, options_.start_block_size, options_.max_block_size);
AddBlock(b);
SetThreadCacheBlock(b);
return reinterpret_cast<char*>(b) + kHeaderSize;
CacheBlock(b);
return b;
}
uint64 Arena::SpaceAllocated() const {
MutexLock l(&blocks_lock_);
return space_allocated_;
uint64 ArenaImpl::SpaceAllocated() const {
return google::protobuf::internal::NoBarrier_Load(&space_allocated_);
}
uint64 Arena::SpaceUsed() const {
uint64 ArenaImpl::SpaceUsed() const {
ThreadInfo* info =
reinterpret_cast<ThreadInfo*>(google::protobuf::internal::Acquire_Load(&threads_));
uint64 space_used = 0;
Block* b = reinterpret_cast<Block*>(google::protobuf::internal::NoBarrier_Load(&blocks_));
while (b != NULL) {
space_used += (b->pos - kHeaderSize);
b = b->next;
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);
}
}
return space_used;
}
std::pair<uint64, uint64> Arena::SpaceAllocatedAndUsed() const {
return std::make_pair(SpaceAllocated(), SpaceUsed());
}
uint64 Arena::FreeBlocks() {
uint64 ArenaImpl::FreeBlocks() {
uint64 space_allocated = 0;
Block* b = reinterpret_cast<Block*>(google::protobuf::internal::NoBarrier_Load(&blocks_));
Block* first_block = NULL;
while (b != NULL) {
space_allocated += (b->size);
Block* next = b->next;
if (next != NULL) {
// 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_));
while (info) {
// 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);
#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);
#endif // ADDRESS_SANITIZER
options_.block_dealloc(b, b->size);
} else {
if (owns_first_block_) {
#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);
#endif // ADDRESS_SANITIZER
if (b != initial_block_) {
options_.block_dealloc(b, b->size);
} else {
// User passed in the first block, skip free'ing the memory.
first_block = b;
}
b = next_block;
}
b = next;
}
blocks_ = 0;
hint_ = 0;
space_allocated_ = 0;
if (!owns_first_block_) {
// Make the first block that was passed in through ArenaOptions
// available for reuse.
first_block->pos = kHeaderSize;
// Thread which calls Reset() owns the first block. This allows the
// single-threaded case to allocate on the first block without taking any
// locks.
first_block->owner = &thread_cache();
SetThreadCacheBlock(first_block);
AddBlockInternal(first_block);
info = next_info;
}
return space_allocated;
}
void Arena::CleanupList() {
Node* head =
reinterpret_cast<Node*>(google::protobuf::internal::NoBarrier_Load(&cleanup_list_));
while (head != NULL) {
head->cleanup(head->elem);
head = head->next;
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_));
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;
}
}
cleanup_list_ = 0;
}
Arena::Block* Arena::FindBlock(void* me) {
// TODO(sanjay): We might want to keep a separate list with one
// entry per thread.
Block* b = reinterpret_cast<Block*>(google::protobuf::internal::Acquire_Load(&blocks_));
while (b != NULL && b->owner != me) {
b = b->next;
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;
}
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;
}
}
return NULL;
}
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;
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);
}
return info;
}
} // namespace internal
void Arena::CallDestructorHooks() {
uint64 space_allocated = impl_.SpaceAllocated();
// Call the reset hook
if (on_arena_reset_ != NULL) {
on_arena_reset_(this, hooks_cookie_, space_allocated);
}
// Call the destruction hook
if (on_arena_destruction_ != NULL) {
on_arena_destruction_(this, hooks_cookie_, space_allocated);
}
}
void Arena::OnArenaAllocation(const std::type_info* allocated_type,
size_t n) const {
if (on_arena_allocation_ != NULL) {
on_arena_allocation_(allocated_type, n, hooks_cookie_);
}
return b;
}
} // namespace protobuf
+329 -350
View File
@@ -37,7 +37,7 @@
#ifdef max
#undef max // Visual Studio defines this macro
#endif
#if __cplusplus >= 201103L
#if LANG_CXX11
#include <google/protobuf/stubs/type_traits.h>
#endif
#if defined(_MSC_VER) && !_HAS_EXCEPTIONS
@@ -51,13 +51,8 @@ using type_info = ::type_info;
#include <typeinfo>
#endif
#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/arena_impl.h>
#include <google/protobuf/stubs/port.h>
namespace google {
namespace protobuf {
@@ -66,7 +61,7 @@ class Arena; // defined below
class Message; // message.h
namespace internal {
class ArenaString; // arenastring.h
struct ArenaStringPtr; // arenastring.h
class LazyField; // lazy_field.h
template<typename Type>
@@ -122,7 +117,6 @@ struct ArenaOptions {
// from the arena. By default, it contains a ptr to a wrapper function that
// calls free.
void (*block_dealloc)(void*, size_t);
// 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.
@@ -225,21 +219,39 @@ class LIBPROTOBUF_EXPORT Arena {
public:
// Arena constructor taking custom options. See ArenaOptions below for
// descriptions of the options available.
explicit Arena(const ArenaOptions& options) : options_(options) {
Init();
explicit Arena(const ArenaOptions& options) : impl_(options) {
Init(options);
}
// Block overhead. Use this as a guide for how much to over-allocate the
// initial block if you want an allocation of size N to fit inside it.
//
// 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;
// Default constructor with sensible default options, tuned for average
// use-cases.
Arena() {
Init();
Arena() : impl_(ArenaOptions()) { Init(ArenaOptions()); }
~Arena() {
if (on_arena_reset_ != NULL || on_arena_destruction_ != NULL) {
CallDestructorHooks();
}
}
// Destructor deletes all owned heap allocated objects, and destructs objects
// that have non-trivial destructors, except for proto2 message objects whose
// destructors can be skipped. Also, frees all blocks except the initial block
// if it was passed in.
~Arena();
void Init(const ArenaOptions& options) {
on_arena_allocation_ = options.on_arena_allocation;
on_arena_reset_ = options.on_arena_reset;
on_arena_destruction_ = options.on_arena_destruction;
// Call the initialization hook
if (options.on_arena_init != NULL) {
hooks_cookie_ = options.on_arena_init(this);
} else {
hooks_cookie_ = NULL;
}
}
// API to create proto2 message objects on the arena. If the arena passed in
// is NULL, then a heap allocated object is returned. Type T must be a message
@@ -251,40 +263,68 @@ class LIBPROTOBUF_EXPORT Arena {
//
// This function also accepts any type T that satisfies the arena message
// allocation protocol, documented above.
template <typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
#if LANG_CXX11
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE static T* CreateMessage(
::google::protobuf::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>(static_cast<T*>(0));
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_ATTRIBUTE_ALWAYS_INLINE
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>(static_cast<T*>(0),
arg);
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_ATTRIBUTE_ALWAYS_INLINE
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>(static_cast<T*>(0),
arg1, arg2);
return arena->CreateMessageInternal<T>(arg1, arg2);
}
}
@@ -304,7 +344,8 @@ class LIBPROTOBUF_EXPORT Arena {
// 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_ATTRIBUTE_ALWAYS_INLINE
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)...);
@@ -314,7 +355,7 @@ class LIBPROTOBUF_EXPORT Arena {
}
}
#endif
template <typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* Create(::google::protobuf::Arena* arena) {
if (arena == NULL) {
return new T();
@@ -324,7 +365,7 @@ class LIBPROTOBUF_EXPORT Arena {
}
// Version of the above with one constructor argument for the created object.
template <typename T, typename Arg> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
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);
@@ -335,7 +376,8 @@ class LIBPROTOBUF_EXPORT Arena {
}
// Version of the above with two constructor arguments for the created object.
template <typename T, typename Arg1, typename Arg2> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
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);
@@ -348,9 +390,11 @@ class LIBPROTOBUF_EXPORT Arena {
// Version of the above with three constructor arguments for the created
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3>
GOOGLE_ATTRIBUTE_ALWAYS_INLINE static T* Create(::google::protobuf::Arena* arena,
const Arg1& arg1, const Arg2& arg2,
const Arg3& 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 {
@@ -363,9 +407,10 @@ class LIBPROTOBUF_EXPORT Arena {
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4>
GOOGLE_ATTRIBUTE_ALWAYS_INLINE static T* Create(::google::protobuf::Arena* arena,
const Arg1& arg1, const Arg2& arg2,
const Arg3& arg3, const Arg4& 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 {
@@ -378,10 +423,11 @@ class LIBPROTOBUF_EXPORT Arena {
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5>
GOOGLE_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) {
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 {
@@ -394,10 +440,11 @@ class LIBPROTOBUF_EXPORT Arena {
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6>
GOOGLE_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) {
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 {
@@ -410,11 +457,12 @@ class LIBPROTOBUF_EXPORT Arena {
// object.
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7>
GOOGLE_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) {
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 {
@@ -428,11 +476,12 @@ class LIBPROTOBUF_EXPORT Arena {
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7,
typename Arg8>
GOOGLE_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) {
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 {
@@ -448,7 +497,7 @@ 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_ATTRIBUTE_ALWAYS_INLINE
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))
@@ -463,28 +512,36 @@ class LIBPROTOBUF_EXPORT Arena {
// Returns the total space allocated by the arena, which is the sum of the
// sizes of the underlying blocks. This method is relatively fast; a counter
// is kept as blocks are allocated.
uint64 SpaceAllocated() const;
uint64 SpaceAllocated() const { return impl_.SpaceAllocated(); }
// Returns the total space used by the arena. Similar to SpaceAllocated but
// does not include free space and block overhead. The total space returned
// may not include space used by other threads executing concurrently with
// the call to this method.
GOOGLE_ATTRIBUTE_NOINLINE uint64 SpaceUsed() const;
uint64 SpaceUsed() const { return impl_.SpaceUsed(); }
// DEPRECATED. Please use SpaceAllocated() and SpaceUsed().
//
// Combines SpaceAllocated and SpaceUsed. Returns a pair of
// <space_allocated, space_used>.
GOOGLE_ATTRIBUTE_NOINLINE std::pair<uint64, uint64> SpaceAllocatedAndUsed() const;
std::pair<uint64, uint64> SpaceAllocatedAndUsed() const {
return std::make_pair(SpaceAllocated(), SpaceUsed());
}
// Frees all storage allocated by this arena after calling destructors
// registered with OwnDestructor() and freeing objects registered with Own().
// Any objects allocated on this arena are unusable after this call. It also
// returns the total space used by the arena which is the sums of the sizes
// of the allocated blocks. This method is not thread-safe.
GOOGLE_ATTRIBUTE_NOINLINE uint64 Reset();
GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE uint64 Reset() {
// Call the reset hook
if (on_arena_reset_ != NULL) {
on_arena_reset_(this, hooks_cookie_, impl_.SpaceAllocated());
}
return impl_.Reset();
}
// 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_ATTRIBUTE_NOINLINE
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void Own(T* object) {
OwnInternal(object, google::protobuf::internal::is_convertible<T*, ::google::protobuf::Message*>());
}
@@ -494,10 +551,10 @@ 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_ATTRIBUTE_NOINLINE
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void OwnDestructor(T* object) {
if (object != NULL) {
AddListNode(object, &internal::arena_destruct_object<T>);
impl_.AddCleanup(object, &internal::arena_destruct_object<T>);
}
}
@@ -505,30 +562,70 @@ class LIBPROTOBUF_EXPORT Arena {
// will be manually called when the arena is destroyed or reset. This differs
// from OwnDestructor() in that any member function may be specified, not only
// the class destructor.
GOOGLE_ATTRIBUTE_NOINLINE void OwnCustomDestructor(void* object,
void (*destruct)(void*)) {
AddListNode(object, destruct);
GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE void OwnCustomDestructor(
void* object, void (*destruct)(void*)) {
impl_.AddCleanup(object, destruct);
}
// Retrieves the arena associated with |value| if |value| is an arena-capable
// message, or NULL otherwise. This differs from value->GetArena() in that the
// latter is a virtual call, while this method is a templated call that
// resolves at compile-time.
template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArena(const T* value) {
return GetArenaInternal(value, static_cast<T*>(0));
return GetArenaInternal(value, is_arena_constructable<T>());
}
private:
struct InternalIsArenaConstructableHelper {
template <typename T>
class InternalHelper {
template <typename U>
static char DestructorSkippable(const typename U::DestructorSkippable_*);
template <typename U>
static double DestructorSkippable(...);
typedef google::protobuf::internal::integral_constant<
bool, sizeof(DestructorSkippable<T>(static_cast<const T*>(0))) ==
sizeof(char) ||
google::protobuf::internal::has_trivial_destructor<T>::value>
is_destructor_skippable;
template<typename U>
static char ArenaConstructable(
const typename U::InternalArenaConstructable_*);
template<typename U>
static double ArenaConstructable(...);
typedef google::protobuf::internal::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;
};
public:
// Helper typetrait 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
@@ -537,278 +634,202 @@ class LIBPROTOBUF_EXPORT Arena {
// 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
: public google::protobuf::internal::integral_constant<
bool, sizeof(InternalIsArenaConstructableHelper::ArenaConstructable<
const T>(static_cast<const T*>(0))) == sizeof(char)> {
};
struct is_arena_constructable : InternalHelper<T>::is_arena_constructable {};
private:
// 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, or
// &this->owner if not yet owned by a thread.
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_ATTRIBUTE_ALWAYS_INLINE size_t avail() const { return size - pos; }
// data follows
};
template<typename Type> friend class ::google::protobuf::internal::GenericTypeHandler;
friend class MockArena; // For unit-testing.
friend class internal::ArenaString; // For AllocateAligned.
friend class internal::LazyField; // For CreateMaybeMessage.
struct ThreadCache {
// 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_;
};
static const size_t kHeaderSize = sizeof(Block);
static google::protobuf::internal::SequenceNumber lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
// Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread
// local storage class we implemented.
// iOS also does not support the GOOGLE_THREAD_LOCAL keyword.
static ThreadCache& thread_cache();
#elif defined(PROTOBUF_USE_DLLS)
// Thread local variables cannot be exposed through DLL interface but we can
// wrap them in static functions.
static ThreadCache& thread_cache();
#else
static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_;
static ThreadCache& thread_cache() { return thread_cache_; }
#endif
// SFINAE for skipping addition to delete list for a message type when created
// with CreateMessage. This is mainly to skip proto2/proto1 message objects
// with cc_enable_arenas=true from being part of the delete list. Also, note,
// compiler will optimize out the branch in CreateInternal<T>.
template<typename T>
static inline bool SkipDeleteList(typename T::DestructorSkippable_*) {
return true;
void CallDestructorHooks();
void OnArenaAllocation(const std::type_info* allocated_type, size_t n) const;
inline void AllocHook(const std::type_info* allocated_type, size_t n) const {
if (GOOGLE_PREDICT_FALSE(hooks_cookie_ != NULL)) {
OnArenaAllocation(allocated_type, n);
}
}
// For message objects that don't have the DestructorSkippable_ trait, we
// always add to the delete list.
template<typename T>
static inline bool SkipDeleteList(...) {
return google::protobuf::internal::has_trivial_destructor<T>::value;
// 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) {
const size_t n = internal::AlignUpTo8(sizeof(T));
AllocHook(RTTI_TYPE_ID(T), n);
// Monitor allocation if needed.
if (skip_explicit_ownership) {
return impl_.AllocateAligned(n);
} else {
return impl_.AllocateAlignedAndAddCleanup(
n, &internal::arena_destruct_object<T>);
}
}
private:
struct InternalIsDestructorSkippableHelper {
template<typename U>
static char DestructorSkippable(
const typename U::DestructorSkippable_*);
template<typename U>
static double DestructorSkippable(...);
};
public:
// Helper typetrait that indicates whether the desctructor of type T should be
// called when arena is destroyed at compile time. This is only to allow
// construction of higher-level templated utilities.
// is_destructor_skippable<T>::value is true if the destructor of the message
// type T should not be called when arena is destroyed or 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_destructor_skippable
: public google::protobuf::internal::integral_constant<
bool,
sizeof(InternalIsDestructorSkippableHelper::DestructorSkippable<
const T>(static_cast<const T*>(0))) == sizeof(char) ||
google::protobuf::internal::has_trivial_destructor<T>::value> {};
private:
// CreateMessage<T> requires that T supports arenas, but this private method
// works whether or not T supports arenas. These are not exposed to user code
// 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_ATTRIBUTE_ALWAYS_INLINE
static Msg* CreateMaybeMessage(
Arena* arena, typename Msg::InternalArenaConstructable_*) {
template <typename Msg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static Msg* CreateMaybeMessage(Arena* arena, google::protobuf::internal::true_type) {
return CreateMessage<Msg>(arena);
}
template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMaybeMessage(Arena* arena, ...) {
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> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static T* CreateMaybeMessage(Arena* arena) {
return CreateMaybeMessage<T>(arena, is_arena_constructable<T>());
}
// Just allocate the required size for the given type assuming the
// type has a trivial constructor.
template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
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.";
return static_cast<T*>(
AllocateAligned(RTTI_TYPE_ID(T), sizeof(T) * num_elements));
const size_t n = internal::AlignUpTo8(sizeof(T) * num_elements);
// Monitor allocation if needed.
AllocHook(RTTI_TYPE_ID(T), n);
return static_cast<T*>(impl_.AllocateAligned(n));
}
#if LANG_CXX11
template <typename T, typename... Args> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership, Args&&... args) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
return new (AllocateInternal<T>(skip_explicit_ownership))
T(std::forward<Args>(args)...);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
}
#endif
template <typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
#else
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T))) T();
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
return new (AllocateInternal<T>(skip_explicit_ownership)) T();
}
template <typename T, typename Arg> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
template <typename T, typename Arg> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(bool skip_explicit_ownership, const Arg& arg) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T))) T(arg);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
return new (AllocateInternal<T>(skip_explicit_ownership)) T(arg);
}
template <typename T, typename Arg1, typename Arg2> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
T* CreateInternal(
bool skip_explicit_ownership, const Arg1& arg1, const Arg2& arg2) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T))) T(arg1, arg2);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
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_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
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);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4>
GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3,
const Arg4& arg4) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
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);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5>
GOOGLE_ATTRIBUTE_ALWAYS_INLINE T* CreateInternal(bool skip_explicit_ownership,
const Arg1& arg1,
const Arg2& arg2,
const Arg3& arg3,
const Arg4& arg4,
const Arg5& arg5) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
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);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6>
GOOGLE_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) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
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);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7>
GOOGLE_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) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
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);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
}
template <typename T, typename Arg1, typename Arg2, typename Arg3,
typename Arg4, typename Arg5, typename Arg6, typename Arg7,
typename Arg8>
GOOGLE_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) {
T* t = new (AllocateAligned(RTTI_TYPE_ID(T), sizeof(T)))
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);
if (!skip_explicit_ownership) {
AddListNode(t, &internal::arena_destruct_object<T>);
}
return t;
}
#endif
#if LANG_CXX11
template <typename T, typename... Args>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE T* CreateMessageInternal(
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> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
T* CreateMessageInternal(typename T::InternalArenaConstructable_*) {
return CreateInternal<T>(SkipDeleteList<T>(static_cast<T*>(0)), 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 Arg> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
T* CreateMessageInternal(typename T::InternalArenaConstructable_*,
const Arg& arg) {
return CreateInternal<T>(SkipDeleteList<T>(static_cast<T*>(0)), this, arg);
}
template <typename T, typename Arg1, typename Arg2> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
T* CreateMessageInternal(typename T::InternalArenaConstructable_*,
const Arg1& arg1, const Arg2& arg2) {
return CreateInternal<T>(SkipDeleteList<T>(static_cast<T*>(0)), this, arg1,
arg2);
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,
@@ -818,24 +839,25 @@ class LIBPROTOBUF_EXPORT Arena {
static void CreateInArenaStorage(T* ptr, Arena* arena) {
CreateInArenaStorageInternal(ptr, arena,
typename is_arena_constructable<T>::type());
RegisterDestructorInternal(ptr, arena,
typename is_destructor_skippable<T>::type());
RegisterDestructorInternal(
ptr, arena,
typename InternalHelper<T>::is_destructor_skippable::type());
}
template <typename T>
static void CreateInArenaStorageInternal(
T* ptr, Arena* arena, google::protobuf::internal::true_type) {
new (ptr) T(arena);
InternalHelper<T>::Construct(ptr, arena);
}
template <typename T>
static void CreateInArenaStorageInternal(
T* ptr, Arena* arena, google::protobuf::internal::false_type) {
T* ptr, Arena* /* arena */, google::protobuf::internal::false_type) {
new (ptr) T();
}
template <typename T>
static void RegisterDestructorInternal(
T* ptr, Arena* arena, google::protobuf::internal::true_type) {}
T* /* ptr */, Arena* /* arena */, google::protobuf::internal::true_type) {}
template <typename T>
static void RegisterDestructorInternal(
T* ptr, Arena* arena, google::protobuf::internal::false_type) {
@@ -847,103 +869,60 @@ 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_ATTRIBUTE_ALWAYS_INLINE
template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void OwnInternal(T* object, google::protobuf::internal::true_type) {
if (object != NULL) {
AddListNode(object, &internal::arena_delete_object< ::google::protobuf::Message >);
impl_.AddCleanup(object,
&internal::arena_delete_object< ::google::protobuf::Message>);
}
}
template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
template<typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
void OwnInternal(T* object, google::protobuf::internal::false_type) {
if (object != NULL) {
AddListNode(object, &internal::arena_delete_object<T>);
impl_.AddCleanup(object, &internal::arena_delete_object<T>);
}
}
// 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_ATTRIBUTE_ALWAYS_INLINE
template <typename T> GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArenaInternal(
const T* value, typename T::InternalArenaConstructable_*) {
return value->GetArenaNoVirtual();
const T* value, google::protobuf::internal::true_type) {
return InternalHelper<T>::GetArena(value);
}
template<typename T> GOOGLE_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArenaInternal(const T* value, ...) {
template <typename T>
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE
static ::google::protobuf::Arena* GetArenaInternal(
const T* /* value */, google::protobuf::internal::false_type) {
return NULL;
}
// 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.
void* AllocateAligned(const std::type_info* allocated, size_t n);
// Allocate an internal allocation, avoiding optional typed monitoring.
GOOGLE_ATTRIBUTE_ALWAYS_INLINE void* AllocateAligned(size_t n) {
return AllocateAligned(NULL, n);
// For friends of arena.
void* AllocateAligned(size_t n) {
AllocHook(NULL, n);
return impl_.AllocateAligned(internal::AlignUpTo8(n));
}
void Init();
internal::ArenaImpl impl_;
// Free all blocks and return the total space used which is the sums of sizes
// of the all the allocated blocks.
uint64 FreeBlocks();
// Add object pointer and cleanup function pointer to the list.
// TODO(rohananil, cfallin): We could pass in a sub-arena into this method
// to avoid polluting blocks of this arena with list nodes. This would help in
// mixed mode (where many protobufs have cc_enable_arenas=false), and is an
// alternative to a chunked linked-list, but with extra overhead of *next.
void AddListNode(void* elem, void (*cleanup)(void*));
// Delete or Destruct all objects owned by the arena.
void CleanupList();
uint64 ResetInternal();
inline void SetThreadCacheBlock(Block* block) {
thread_cache().last_block_used_ = block;
thread_cache().last_lifecycle_id_seen = lifecycle_id_;
}
int64 lifecycle_id_; // Unique for each arena. Changes on Reset().
google::protobuf::internal::AtomicWord blocks_; // Head of linked list of all allocated blocks
google::protobuf::internal::AtomicWord hint_; // Fast thread-local block access
uint64 space_allocated_; // Sum of sizes of all allocated blocks.
// Node contains the ptr of the object to be cleaned up and the associated
// cleanup function ptr.
struct Node {
void* elem; // Pointer to the object to be cleaned up.
void (*cleanup)(void*); // Function pointer to the destructor or deleter.
Node* next; // Next node in the list.
};
google::protobuf::internal::AtomicWord cleanup_list_; // Head of a linked list of nodes containing object
// ptrs and cleanup methods.
bool owns_first_block_; // Indicates that arena owns the first block
mutable Mutex blocks_lock_;
void AddBlock(Block* b);
// Access must be synchronized, either by blocks_lock_ or by being called from
// Init()/Reset().
void AddBlockInternal(Block* b);
void* SlowAlloc(size_t n);
Block* FindBlock(void* me);
Block* NewBlock(void* me, Block* my_last_block, size_t n,
size_t start_block_size, size_t max_block_size);
static void* AllocFromBlock(Block* b, size_t n);
template <typename Key, typename T>
friend class Map;
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);
void (*on_arena_destruction_)(Arena* arena, void* cookie, uint64 space_used);
// The arena may save a cookie it receives from the external on_init hook
// and then use it when calling the on_reset and on_destruction hooks.
void* hooks_cookie_;
ArenaOptions options_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Arena);
template <typename Type>
friend class ::google::protobuf::internal::GenericTypeHandler;
friend struct internal::ArenaStringPtr; // For AllocateAligned.
friend class internal::LazyField; // For CreateMaybeMessage.
template <typename Key, typename T>
friend class Map;
};
// Defined above for supporting environments without RTTI.
@@ -0,0 +1,242 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This file defines an Arena allocator for better allocation performance.
#ifndef GOOGLE_PROTOBUF_ARENA_IMPL_H__
#define GOOGLE_PROTOBUF_ARENA_IMPL_H__
#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>
namespace google {
namespace protobuf {
namespace internal {
inline size_t AlignUpTo8(size_t n) {
// Align n to next multiple of 8 (from Hacker's Delight, Chapter 3.)
return (n + 7) & -8;
}
// This class provides the core Arena memory allocation library. Different
// implementations only need to implement the public interface below.
// Arena is not a template type as that would only be useful if all protos
// in turn would be templates, which will/cannot happen. However separating
// the memory allocation part from the cruft of the API users expect we can
// use #ifdef the select the best implementation based on hardware / OS.
class LIBPROTOBUF_EXPORT ArenaImpl {
public:
struct Options {
size_t start_block_size;
size_t max_block_size;
char* initial_block;
size_t initial_block_size;
void* (*block_alloc)(size_t);
void (*block_dealloc)(void*, size_t);
template <typename O>
explicit Options(const O& options)
: start_block_size(options.start_block_size),
max_block_size(options.max_block_size),
initial_block(options.initial_block),
initial_block_size(options.initial_block_size),
block_alloc(options.block_alloc),
block_dealloc(options.block_dealloc) {}
};
template <typename O>
explicit ArenaImpl(const O& options) : options_(options) {
if (options_.initial_block != NULL && options_.initial_block_size > 0) {
GOOGLE_CHECK_GE(options_.initial_block_size, sizeof(Block))
<< ": Initial block size too small for header.";
initial_block_ = reinterpret_cast<Block*>(options_.initial_block);
} else {
initial_block_ = NULL;
}
Init();
}
// Destructor deletes all owned heap allocated objects, and destructs objects
// that have non-trivial destructors, except for proto2 message objects whose
// destructors can be skipped. Also, frees all blocks except the initial block
// if it was passed in.
~ArenaImpl();
uint64 Reset();
uint64 SpaceAllocated() const;
uint64 SpaceUsed() const;
void* AllocateAligned(size_t n);
void* AllocateAlignedAndAddCleanup(size_t n, void (*cleanup)(void*));
// Add object pointer and cleanup function pointer to the list.
void AddCleanup(void* elem, void (*cleanup)(void*));
private:
// Node contains the ptr of the object to be cleaned up and the associated
// cleanup function ptr.
struct CleanupNode {
void* elem; // Pointer to the object to be cleaned up.
void (*cleanup)(void*); // Function pointer to the destructor or deleter.
};
// Cleanup uses a chunked linked list, to reduce pointer chasing.
struct CleanupChunk {
static size_t SizeOf(size_t i) {
return sizeof(CleanupChunk) + (sizeof(CleanupNode) * (i - 1));
}
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;
// 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.
};
// 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; }
// data follows
};
struct ThreadCache {
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
// If we are using the ThreadLocalStorage class to store the ThreadCache,
// then the ThreadCache's default constructor has to be responsible for
// initializing it.
ThreadCache() : last_lifecycle_id_seen(-1), last_block_used_(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_;
};
static google::protobuf::internal::SequenceNumber lifecycle_id_generator_;
#if defined(GOOGLE_PROTOBUF_NO_THREADLOCAL)
// Android ndk does not support GOOGLE_THREAD_LOCAL keyword so we use a custom thread
// local storage class we implemented.
// iOS also does not support the GOOGLE_THREAD_LOCAL keyword.
static ThreadCache& thread_cache();
#elif defined(PROTOBUF_USE_DLLS)
// Thread local variables cannot be exposed through DLL interface but we can
// wrap them in static functions.
static ThreadCache& thread_cache();
#else
static GOOGLE_THREAD_LOCAL ThreadCache thread_cache_;
static ThreadCache& thread_cache() { return thread_cache_; }
#endif
void Init();
// Free all blocks and return the total space used which is the sums of sizes
// of the all the allocated blocks.
uint64 FreeBlocks();
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;
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));
}
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.
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);
int64 lifecycle_id_; // Unique for each arena. Changes on Reset().
Options options_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArenaImpl);
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
};
} // namespace internal
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_ARENA_IMPL_H__
@@ -270,7 +270,7 @@ 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(64);
std::vector<char> arena_block(72);
ArenaOptions options;
options.initial_block = &arena_block[0];
options.initial_block_size = arena_block.size();
@@ -1299,12 +1299,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, 190);
::google::protobuf::Arena::CreateArray<char>(&arena_3, 182);
EXPECT_EQ(256, arena_3.SpaceAllocated());
EXPECT_EQ(Align8(190), arena_3.SpaceUsed());
EXPECT_EQ(Align8(182), arena_3.SpaceUsed());
::google::protobuf::Arena::CreateArray<char>(&arena_3, 70);
EXPECT_EQ(256 + 512, arena_3.SpaceAllocated());
EXPECT_EQ(Align8(190) + Align8(70), arena_3.SpaceUsed());
EXPECT_EQ(Align8(182) + Align8(70), arena_3.SpaceUsed());
EXPECT_EQ(256 + 512, arena_3.Reset());
}
+18 -10
View File
@@ -33,12 +33,11 @@
#include <string>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/fastmem.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/port.h>
// This is the implementation of arena string fields written for the open-source
// release. The ArenaStringPtr struct below is an internal implementation class
@@ -62,6 +61,12 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
}
}
inline void SetLite(const ::std::string* default_value,
const ::std::string& value,
::google::protobuf::Arena* arena) {
Set(default_value, value, arena);
}
// Basic accessors.
inline const ::std::string& Get() const { return *ptr_; }
@@ -84,8 +89,9 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
}
::std::string* released = NULL;
if (arena != NULL) {
// ptr_ is owned by the arena -- we need to return a copy.
released = new ::std::string(*ptr_);
// ptr_ is owned by the arena.
released = new ::std::string;
released->swap(*ptr_);
} else {
released = ptr_;
}
@@ -143,7 +149,7 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
// Swaps internal pointers. Arena-safety semantics: this is guarded by the
// logic in Swap()/UnsafeArenaSwap() at the message level, so this method is
// 'unsafe' if called directly.
GOOGLE_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) {
GOOGLE_PROTOBUF_ATTRIBUTE_ALWAYS_INLINE void Swap(ArenaStringPtr* other) {
std::swap(ptr_, other->ptr_);
}
@@ -291,15 +297,17 @@ struct LIBPROTOBUF_EXPORT ArenaStringPtr {
private:
::std::string* ptr_;
GOOGLE_ATTRIBUTE_NOINLINE void CreateInstance(::google::protobuf::Arena* arena,
const ::std::string* initial_value) {
GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
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_);
}
}
GOOGLE_ATTRIBUTE_NOINLINE void CreateInstanceNoArena(const ::std::string* initial_value) {
GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE
void CreateInstanceNoArena(const ::std::string* initial_value) {
GOOGLE_DCHECK(initial_value != NULL);
ptr_ = new ::std::string(*initial_value);
}
@@ -32,19 +32,23 @@
#include <google/protobuf/arenastring.h>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <cstdlib>
#include <string>
#include <vector>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <gtest/gtest.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
namespace google {
using google::protobuf::internal::ArenaString;
using google::protobuf::internal::ArenaStringPtr;
namespace protobuf {
@@ -87,7 +91,8 @@ TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) {
EXPECT_EQ(string("default"), field.Get());
field.Set(&default_value, WrapString("Test short"), &arena);
EXPECT_EQ(string("Test short"), field.Get());
field.Set(&default_value, WrapString("Test long long long long value"), &arena);
field.Set(&default_value, WrapString("Test long long long long value"),
&arena);
EXPECT_EQ(string("Test long long long long value"), field.Get());
field.Set(&default_value, string(""), &arena);
field.Destroy(&default_value, &arena);
@@ -104,5 +109,33 @@ TEST(ArenaStringPtrTest, ArenaStringPtrOnArena) {
field2.Destroy(&default_value, &arena);
}
TEST(ArenaStringPtrTest, ArenaStringPtrOnArenaNoSSO) {
google::protobuf::Arena arena;
ArenaStringPtr field;
::std::string default_value = "default";
field.UnsafeSetDefault(&default_value);
EXPECT_EQ(string("default"), field.Get());
// Avoid triggering the SSO optimization by setting the string to something
// larger than the internal buffer.
field.Set(&default_value, WrapString("Test long long long long value"),
&arena);
EXPECT_EQ(string("Test long long long long value"), field.Get());
field.Set(&default_value, string(""), &arena);
field.Destroy(&default_value, &arena);
ArenaStringPtr field2;
field2.UnsafeSetDefault(&default_value);
::std::string* mut = field2.Mutable(&default_value, &arena);
EXPECT_EQ(mut, field2.Mutable(&default_value, &arena));
EXPECT_EQ(mut, &field2.Get());
EXPECT_NE(&default_value, mut);
EXPECT_EQ(string("default"), *mut);
*mut = "Test long long long long value"; // ensure string allocates storage
EXPECT_EQ(string("Test long long long long value"), field2.Get());
field2.Destroy(&default_value, &arena);
}
} // namespace protobuf
} // namespace google
@@ -0,0 +1,187 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <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>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/file.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace annotation_test_util {
namespace {
// A CodeGenerator that captures the FileDescriptor it's passed as a
// FileDescriptorProto.
class DescriptorCapturingGenerator : public CodeGenerator {
public:
// Does not own file; file must outlive the Generator.
explicit DescriptorCapturingGenerator(FileDescriptorProto* file)
: file_(file) {}
virtual bool Generate(const FileDescriptor* file, const string& parameter,
GeneratorContext* context, string* error) const {
file->CopyTo(file_);
return true;
}
private:
FileDescriptorProto* file_;
};
} // namespace
void AddFile(const string& filename, const string& data) {
GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/" + filename, data,
true));
}
bool CaptureMetadata(const string& filename, const string& plugin_specific_args,
const string& meta_file_suffix, CommandLineInterface* cli,
FileDescriptorProto* file,
std::vector<ExpectedOutput>* outputs) {
cli->SetInputsAreProtoPathRelative(true);
DescriptorCapturingGenerator capturing_generator(file);
cli->RegisterGenerator("--capture_out", &capturing_generator, "");
string proto_path = "-I" + TestTempDir();
string capture_out = "--capture_out=" + TestTempDir();
const char* argv[] = {"protoc", proto_path.c_str(),
plugin_specific_args.c_str(), capture_out.c_str(),
filename.c_str()};
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;
}
bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) {
string data;
GOOGLE_CHECK_OK(File::GetContents(path, &data, true));
io::ArrayInputStream input(data.data(), data.size());
return info->ParseFromZeroCopyStream(&input);
}
void FindAnnotationsOnPath(
const GeneratedCodeInfo& info, const string& source_file,
const std::vector<int>& path,
std::vector<const GeneratedCodeInfo::Annotation*>* annotations) {
for (int i = 0; i < info.annotation_size(); ++i) {
const GeneratedCodeInfo::Annotation* annotation = &info.annotation(i);
if (annotation->source_file() != source_file ||
annotation->path_size() != path.size()) {
continue;
}
int node = 0;
for (; node < path.size(); ++node) {
if (annotation->path(node) != path[node]) {
break;
}
}
if (node == path.size()) {
annotations->push_back(annotation);
}
}
}
const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
const GeneratedCodeInfo& info, const string& source_file,
const std::vector<int>& path) {
std::vector<const GeneratedCodeInfo::Annotation*> annotations;
FindAnnotationsOnPath(info, source_file, path, &annotations);
if (annotations.empty()) {
return NULL;
}
return annotations[0];
}
bool AtLeastOneAnnotationMatchesSubstring(
const string& file_content,
const std::vector<const GeneratedCodeInfo::Annotation*>& annotations,
const string& expected_text) {
for (std::vector<const GeneratedCodeInfo::Annotation*>::const_iterator
i = annotations.begin(),
e = annotations.end();
i != e; ++i) {
const GeneratedCodeInfo::Annotation* annotation = *i;
uint32 begin = annotation->begin();
uint32 end = annotation->end();
if (end < begin || end > file_content.size()) {
return false;
}
if (file_content.substr(begin, end - begin) == expected_text) {
return true;
}
}
return false;
}
bool AnnotationMatchesSubstring(const string& file_content,
const GeneratedCodeInfo::Annotation* annotation,
const string& expected_text) {
std::vector<const GeneratedCodeInfo::Annotation*> annotations;
annotations.push_back(annotation);
return AtLeastOneAnnotationMatchesSubstring(file_content, annotations,
expected_text);
}
} // namespace annotation_test_util
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,119 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__
#define GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
// Utilities that assist in writing tests for generator annotations.
// See java/internal/annotation_unittest.cc for an example.
namespace google {
namespace protobuf {
namespace compiler {
namespace annotation_test_util {
// Struct that contains the file generated from a .proto file and its
// GeneratedCodeInfo. For example, the Java generator will fill this struct
// (for some 'foo.proto') with:
// file_path = "Foo.java"
// file_content = content of Foo.java
// file_info = parsed content of Foo.java.pb.meta
struct ExpectedOutput {
string file_path;
string file_content;
GeneratedCodeInfo file_info;
explicit ExpectedOutput(const string& file_path) : file_path(file_path) {}
};
// Creates a file with name `filename` and content `data` in temp test
// directory.
void AddFile(const string& filename, const string& data);
// Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output
// code from the previously added file with name `filename`.
//
// 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 DecodeMetadata(const string& path, GeneratedCodeInfo* info);
// Finds all of the Annotations for a given source file and path.
// See Location.path in http://google/protobuf/descriptor.proto for
// explanation of what path vector is.
void FindAnnotationsOnPath(
const GeneratedCodeInfo& info, const string& source_file,
const std::vector<int>& path,
std::vector<const GeneratedCodeInfo::Annotation*>* annotations);
// Finds the Annotation for a given source file and path (or returns null if it
// couldn't). If there are several annotations for given path, returns the first
// one. See Location.path in
// http://google/protobuf/descriptor.proto for explanation of what path
// vector is.
const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
const GeneratedCodeInfo& info, const string& source_file,
const std::vector<int>& path);
// Returns true if at least one of the provided annotations covers a given
// substring in file_content.
bool AtLeastOneAnnotationMatchesSubstring(
const string& file_content,
const std::vector<const GeneratedCodeInfo::Annotation*>& annotations,
const string& expected_text);
// Returns true if the provided annotation covers a given substring in
// file_content.
bool AnnotationMatchesSubstring(const string& file_content,
const GeneratedCodeInfo::Annotation* annotation,
const string& expected_text);
} // namespace annotation_test_util
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_ANNOTATION_TEST_UTIL_H__
@@ -50,6 +50,8 @@ namespace io { class ZeroCopyOutputStream; }
class FileDescriptor;
namespace compiler {
class AccessInfoMap;
class Version;
// Defined in this file.
@@ -112,7 +114,8 @@ class LIBPROTOC_EXPORT CodeGenerator {
// runs.
class LIBPROTOC_EXPORT GeneratorContext {
public:
inline GeneratorContext() {}
inline GeneratorContext() {
}
virtual ~GeneratorContext();
// Opens the given file, truncating it if it exists, and returns a
@@ -148,6 +151,7 @@ class LIBPROTOC_EXPORT GeneratorContext {
// this GeneratorContext.
virtual void GetCompilerVersion(Version* version) const;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GeneratorContext);
};
@@ -162,8 +166,8 @@ typedef GeneratorContext OutputDirectory;
// "foo=bar,baz,qux=corge"
// parses to the pairs:
// ("foo", "bar"), ("baz", ""), ("qux", "corge")
extern void ParseGeneratorParameter(const string&,
std::vector<std::pair<string, string> >*);
void ParseGeneratorParameter(
const string&, std::vector<std::pair<string, string> >*);
} // namespace compiler
} // namespace protobuf
@@ -33,6 +33,8 @@
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/stubs/platform_macros.h>
#include <stdio.h>
@@ -45,10 +47,7 @@
#endif
#include <sys/stat.h>
#include <fcntl.h>
#ifdef _MSC_VER
#include <io.h>
#include <direct.h>
#else
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <errno.h>
@@ -68,45 +67,30 @@
#endif
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/stringprintf.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/compiler/subprocess.h>
#include <google/protobuf/compiler/zip_writer.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/compiler/plugin.pb.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/map_util.h>
#include <google/protobuf/stubs/stl_util.h>
#include <google/protobuf/stubs/io_win32.h>
namespace google {
namespace protobuf {
namespace compiler {
#if defined(_WIN32)
#define mkdir(name, mode) mkdir(name)
#ifndef W_OK
#define W_OK 02 // not defined by MSVC for whatever reason
#endif
#ifndef F_OK
#define F_OK 00 // not defined by MSVC for whatever reason
#endif
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#endif
#ifndef O_BINARY
#ifdef _O_BINARY
#define O_BINARY _O_BINARY
@@ -116,10 +100,15 @@ namespace compiler {
#endif
namespace {
#if defined(_WIN32) && !defined(__CYGWIN__)
static const char* kPathSeparator = ";";
#else
static const char* kPathSeparator = ":";
#if defined(_WIN32)
// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
// them like we do below.
using google::protobuf::internal::win32::access;
using google::protobuf::internal::win32::close;
using google::protobuf::internal::win32::mkdir;
using google::protobuf::internal::win32::open;
using google::protobuf::internal::win32::setmode;
using google::protobuf::internal::win32::write;
#endif
static const char* kDefaultDirectDependenciesViolationMsg =
@@ -141,9 +130,9 @@ static bool IsWindowsAbsolutePath(const string& text) {
void SetFdToTextMode(int fd) {
#ifdef _WIN32
if (_setmode(fd, _O_TEXT) == -1) {
if (setmode(fd, _O_TEXT) == -1) {
// This should never happen, I think.
GOOGLE_LOG(WARNING) << "_setmode(" << fd << ", _O_TEXT): " << strerror(errno);
GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_TEXT): " << strerror(errno);
}
#endif
// (Text and binary are the same on non-Windows platforms.)
@@ -151,9 +140,9 @@ void SetFdToTextMode(int fd) {
void SetFdToBinaryMode(int fd) {
#ifdef _WIN32
if (_setmode(fd, _O_BINARY) == -1) {
if (setmode(fd, _O_BINARY) == -1) {
// This should never happen, I think.
GOOGLE_LOG(WARNING) << "_setmode(" << fd << ", _O_BINARY): " << strerror(errno);
GOOGLE_LOG(WARNING) << "setmode(" << fd << ", _O_BINARY): " << strerror(errno);
}
#endif
// (Text and binary are the same on non-Windows platforms.)
@@ -235,7 +224,7 @@ bool IsInstalledProtoPath(const string& path) {
return access(file_path.c_str(), F_OK) != -1;
}
// Add the paths where google/protobuf/descritor.proto and other well-known
// Add the paths where google/protobuf/descriptor.proto and other well-known
// type protos are installed.
void AddDefaultProtoPaths(vector<pair<string, string> >* paths) {
// TODO(xiaofeng): The code currently only checks relative paths of where
@@ -278,11 +267,14 @@ string PluginName(const string& plugin_prefix, const string& directive) {
// strip the "--" and "_out/_opt" and add the plugin prefix.
return plugin_prefix + "gen-" + directive.substr(2, directive.size() - 6);
}
} // namespace
// A MultiFileErrorCollector that prints errors to stderr.
class CommandLineInterface::ErrorPrinter : public MultiFileErrorCollector,
public io::ErrorCollector {
class CommandLineInterface::ErrorPrinter
: public MultiFileErrorCollector,
public io::ErrorCollector,
public DescriptorPool::ErrorCollector {
public:
ErrorPrinter(ErrorFormat format, DiskSourceTree *tree = NULL)
: format_(format), tree_(tree), found_errors_(false) {}
@@ -309,6 +301,25 @@ class CommandLineInterface::ErrorPrinter : public MultiFileErrorCollector,
AddErrorOrWarning("input", line, column, message, "warning", std::clog);
}
// implements DescriptorPool::ErrorCollector-------------------------
void AddError(
const string& filename,
const string& element_name,
const Message* descriptor,
ErrorLocation location,
const string& message) {
AddErrorOrWarning(filename, -1, -1, message, "error", std::cerr);
}
void AddWarning(
const string& filename,
const string& element_name,
const Message* descriptor,
ErrorLocation location,
const string& message) {
AddErrorOrWarning(filename, -1, -1, message, "warning", std::clog);
}
bool FoundErrors() const { return found_errors_; }
private:
@@ -410,6 +421,13 @@ class CommandLineInterface::MemoryOutputStream
virtual int64 ByteCount() const { return inner_->ByteCount(); }
private:
// Checks to see if "filename_.meta" exists in directory_; if so, fixes the
// offsets in that GeneratedCodeInfo record to reflect bytes inserted in
// filename_ at original offset insertion_offset with length insertion_length.
// We assume that insertions will not occur within any given annotated span
// of text.
void UpdateMetadata(size_t insertion_offset, size_t insertion_length);
// Where to insert the string when it's done.
GeneratorContextImpl* directory_;
string filename_;
@@ -430,8 +448,7 @@ class CommandLineInterface::MemoryOutputStream
CommandLineInterface::GeneratorContextImpl::GeneratorContextImpl(
const std::vector<const FileDescriptor*>& parsed_files)
: parsed_files_(parsed_files),
had_error_(false) {
}
had_error_(false) {}
CommandLineInterface::GeneratorContextImpl::~GeneratorContextImpl() {
STLDeleteValues(&files_);
@@ -607,6 +624,44 @@ CommandLineInterface::MemoryOutputStream::MemoryOutputStream(
inner_(new io::StringOutputStream(&data_)) {
}
void CommandLineInterface::MemoryOutputStream::UpdateMetadata(
size_t insertion_offset, size_t insertion_length) {
std::map<string, string*>::iterator meta_file =
directory_->files_.find(filename_ + ".meta");
if (meta_file == directory_->files_.end() || !meta_file->second) {
// No metadata was recorded for this file.
return;
}
string* encoded_data = meta_file->second;
GeneratedCodeInfo metadata;
bool is_text_format = false;
if (!metadata.ParseFromString(*encoded_data)) {
if (!TextFormat::ParseFromString(*encoded_data, &metadata)) {
// The metadata is invalid.
std::cerr << filename_
<< ".meta: Could not parse metadata as wire or text format."
<< std::endl;
return;
}
// Generators that use the public plugin interface emit text-format
// metadata (because in the public plugin protocol, file content must be
// UTF8-encoded strings).
is_text_format = true;
}
for (int i = 0; i < metadata.annotation_size(); ++i) {
GeneratedCodeInfo::Annotation* annotation = metadata.mutable_annotation(i);
if (annotation->begin() >= insertion_offset) {
annotation->set_begin(annotation->begin() + insertion_length);
annotation->set_end(annotation->end() + insertion_length);
}
}
if (is_text_format) {
TextFormat::PrintToString(metadata, encoded_data);
} else {
metadata.SerializeToString(encoded_data);
}
}
CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// Make sure all data has been written.
inner_.reset();
@@ -684,6 +739,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
if (indent_.empty()) {
// No indent. This makes things easier.
target->insert(pos, data_);
UpdateMetadata(pos, data_.size());
} else {
// Calculate how much space we need.
int indent_size = 0;
@@ -693,6 +749,7 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// Make a hole for it.
target->insert(pos, data_.size() + indent_size, '\0');
UpdateMetadata(pos, data_.size() + indent_size);
// Now copy in the data.
string::size_type data_pos = 0;
@@ -720,6 +777,12 @@ CommandLineInterface::MemoryOutputStream::~MemoryOutputStream() {
// ===================================================================
#if defined(_WIN32) && !defined(__CYGWIN__)
const char* const CommandLineInterface::kPathSeparator = ";";
#else
const char* const CommandLineInterface::kPathSeparator = ":";
#endif
CommandLineInterface::CommandLineInterface()
: mode_(MODE_COMPILE),
print_mode_(PRINT_NONE),
@@ -729,9 +792,7 @@ CommandLineInterface::CommandLineInterface()
kDefaultDirectDependenciesViolationMsg),
imports_in_descriptor_set_(false),
source_info_in_descriptor_set_(false),
disallow_services_(false),
inputs_are_proto_path_relative_(false) {
}
disallow_services_(false) {}
CommandLineInterface::~CommandLineInterface() {}
void CommandLineInterface::RegisterGenerator(const string& flag_name,
@@ -772,62 +833,41 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
break;
}
AddDefaultProtoPaths(&proto_path_);
// Set up the source tree.
DiskSourceTree source_tree;
for (int i = 0; i < proto_path_.size(); i++) {
source_tree.MapPath(proto_path_[i].first, proto_path_[i].second);
}
// Map input files to virtual paths if necessary.
if (!inputs_are_proto_path_relative_) {
if (!MakeInputsBeProtoPathRelative(&source_tree)) {
return 1;
}
}
// Allocate the Importer.
ErrorPrinter error_collector(error_format_, &source_tree);
Importer importer(&source_tree, &error_collector);
std::vector<const FileDescriptor*> parsed_files;
// Parse each file.
for (int i = 0; i < input_files_.size(); i++) {
// Import the file.
importer.AddUnusedImportTrackFile(input_files_[i]);
const FileDescriptor* parsed_file = importer.Import(input_files_[i]);
importer.ClearUnusedImportTrackFiles();
if (parsed_file == NULL) return 1;
parsed_files.push_back(parsed_file);
// Enforce --disallow_services.
if (disallow_services_ && parsed_file->service_count() > 0) {
cerr << parsed_file->name() << ": This file contains services, but "
"--disallow_services was used." << endl;
// 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;
if (descriptor_set_in_names_.empty()) {
disk_source_tree.reset(new DiskSourceTree());
if (!InitializeDiskSourceTree(disk_source_tree.get())) {
return 1;
}
error_collector.reset(
new ErrorPrinter(error_format_, disk_source_tree.get()));
// Enforce --direct_dependencies
if (direct_dependencies_explicitly_set_) {
bool indirect_imports = false;
for (int i = 0; i < parsed_file->dependency_count(); i++) {
if (direct_dependencies_.find(parsed_file->dependency(i)->name()) ==
direct_dependencies_.end()) {
indirect_imports = true;
std::cerr << parsed_file->name() << ": "
<< StringReplace(direct_dependencies_violation_msg_, "%s",
parsed_file->dependency(i)->name(),
true /* replace_all */)
<< std::endl;
}
}
if (indirect_imports) {
return 1;
}
SourceTreeDescriptorDatabase* database =
new SourceTreeDescriptorDatabase(disk_source_tree.get());
database->RecordErrorsTo(error_collector.get());
descriptor_database.reset(database);
descriptor_pool.reset(new DescriptorPool(
descriptor_database.get(), database->GetValidationErrorCollector()));
} else {
error_collector.reset(new ErrorPrinter(error_format_));
SimpleDescriptorDatabase* database = new SimpleDescriptorDatabase();
descriptor_database.reset(database);
if (!PopulateSimpleDescriptorDatabase(database)) {
return 1;
}
descriptor_pool.reset(new DescriptorPool(database, error_collector.get()));
}
descriptor_pool->EnforceWeakDependencies(true);
if (!ParseInputFiles(descriptor_pool.get(), &parsed_files)) {
return 1;
}
// We construct a separate GeneratorContext for each output location. Note
// that two code generators may output to the same location, in which case
@@ -879,15 +919,16 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
}
if (!dependency_out_name_.empty()) {
GOOGLE_DCHECK(disk_source_tree.get());
if (!GenerateDependencyManifestFile(parsed_files, output_directories,
&source_tree)) {
disk_source_tree.get())) {
return 1;
}
}
STLDeleteValues(&output_directories);
if (!descriptor_set_name_.empty()) {
if (!descriptor_set_out_name_.empty()) {
if (!WriteDescriptorSet(parsed_files)) {
return 1;
}
@@ -906,13 +947,13 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
return 1;
}
} else {
if (!EncodeOrDecode(importer.pool())) {
if (!EncodeOrDecode(descriptor_pool.get())) {
return 1;
}
}
}
if (error_collector.FoundErrors()) {
if (error_collector->FoundErrors()) {
return 1;
}
@@ -928,7 +969,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
break;
case PRINT_NONE:
GOOGLE_LOG(ERROR) << "If the code reaches here, it usually means a bug of "
"flag parsing in the CommonadLineInterface.";
"flag parsing in the CommandLineInterface.";
return 1;
// Do not add a default case.
@@ -938,6 +979,113 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) {
return 0;
}
bool CommandLineInterface::InitializeDiskSourceTree(
DiskSourceTree* source_tree) {
AddDefaultProtoPaths(&proto_path_);
// Set up the source tree.
for (int i = 0; i < proto_path_.size(); i++) {
source_tree->MapPath(proto_path_[i].first, proto_path_[i].second);
}
// Map input files to virtual paths if possible.
if (!MakeInputsBeProtoPathRelative(source_tree)) {
return false;
}
return true;
}
bool CommandLineInterface::PopulateSimpleDescriptorDatabase(
SimpleDescriptorDatabase* database) {
for (int i = 0; i < descriptor_set_in_names_.size(); i++) {
int fd;
do {
fd = open(descriptor_set_in_names_[i].c_str(), O_RDONLY | O_BINARY);
} while (fd < 0 && errno == EINTR);
if (fd < 0) {
std::cerr << descriptor_set_in_names_[i] << ": "
<< strerror(ENOENT) << std::endl;
return false;
}
FileDescriptorSet file_descriptor_set;
bool parsed = file_descriptor_set.ParseFromFileDescriptor(fd);
if (close(fd) != 0) {
std::cerr << descriptor_set_in_names_[i] << ": close: "
<< strerror(errno)
<< std::endl;
return false;
}
if (!parsed) {
std::cerr << descriptor_set_in_names_[i] << ": Unable to parse."
<< std::endl;
return false;
}
for (int j = 0; j < file_descriptor_set.file_size(); j++) {
FileDescriptorProto previously_added_file_descriptor_proto;
if (database->FindFileByName(file_descriptor_set.file(j).name(),
&previously_added_file_descriptor_proto)) {
// already present - skip
continue;
}
if (!database->Add(file_descriptor_set.file(j))) {
return false;
}
}
}
return true;
}
bool CommandLineInterface::ParseInputFiles(
DescriptorPool* descriptor_pool,
std::vector<const FileDescriptor*>* parsed_files) {
// Parse each file.
for (int i = 0; i < input_files_.size(); i++) {
// Import the file.
descriptor_pool->AddUnusedImportTrackFile(input_files_[i]);
const FileDescriptor* parsed_file =
descriptor_pool->FindFileByName(input_files_[i]);
descriptor_pool->ClearUnusedImportTrackFiles();
if (parsed_file == NULL) {
if (!descriptor_set_in_names_.empty()) {
std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl;
}
return false;
}
parsed_files->push_back(parsed_file);
// Enforce --disallow_services.
if (disallow_services_ && parsed_file->service_count() > 0) {
std::cerr << parsed_file->name() << ": This file contains services, but "
"--disallow_services was used." << std::endl;
return false;
}
// Enforce --direct_dependencies
if (direct_dependencies_explicitly_set_) {
bool indirect_imports = false;
for (int i = 0; i < parsed_file->dependency_count(); i++) {
if (direct_dependencies_.find(parsed_file->dependency(i)->name()) ==
direct_dependencies_.end()) {
indirect_imports = true;
std::cerr << parsed_file->name() << ": "
<< StringReplace(direct_dependencies_violation_msg_, "%s",
parsed_file->dependency(i)->name(),
true /* replace_all */)
<< std::endl;
}
}
if (indirect_imports) {
return false;
}
}
}
return true;
}
void CommandLineInterface::Clear() {
// Clear all members that are set by Run(). Note that we must not clear
// members which are set by other methods before Run() is called.
@@ -948,7 +1096,8 @@ void CommandLineInterface::Clear() {
direct_dependencies_violation_msg_ = kDefaultDirectDependenciesViolationMsg;
output_directives_.clear();
codec_type_.clear();
descriptor_set_name_.clear();
descriptor_set_in_names_.clear();
descriptor_set_out_name_.clear();
dependency_out_name_.clear();
mode_ = MODE_COMPILE;
@@ -962,6 +1111,17 @@ void CommandLineInterface::Clear() {
bool CommandLineInterface::MakeInputsBeProtoPathRelative(
DiskSourceTree* source_tree) {
for (int i = 0; i < input_files_.size(); i++) {
// If the input file path is not a physical file path, it must be a virtual
// path.
if (access(input_files_[i].c_str(), F_OK) < 0) {
string disk_file;
if (source_tree->VirtualFileToDiskFile(input_files_[i], &disk_file)) {
return true;
} else {
std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl;
return false;
}
}
string virtual_file, shadowing_disk_file;
switch (source_tree->DiskFileToVirtualFile(
input_files_[i], &virtual_file, &shadowing_disk_file)) {
@@ -979,12 +1139,14 @@ bool CommandLineInterface::MakeInputsBeProtoPathRelative(
case DiskSourceTree::CANNOT_OPEN:
std::cerr << input_files_[i] << ": " << strerror(errno) << std::endl;
return false;
case DiskSourceTree::NO_MAPPING:
// First check if the file exists at all.
if (access(input_files_[i].c_str(), F_OK) < 0) {
// File does not even exist.
std::cerr << input_files_[i] << ": " << strerror(ENOENT) << std::endl;
case DiskSourceTree::NO_MAPPING: {
// Try to interpret the path as a virtual path.
string disk_file;
if (source_tree->VirtualFileToDiskFile(input_files_[i], &disk_file)) {
return true;
} else {
// The input file path can't be mapped to any --proto_path and it also
// can't be interpreted as a virtual path.
std::cerr
<< input_files_[i]
<< ": File does not reside within any path "
@@ -993,15 +1155,32 @@ bool CommandLineInterface::MakeInputsBeProtoPathRelative(
"proto_path must be an exact prefix of the .proto file "
"names -- protoc is too dumb to figure out when two paths "
"(e.g. absolute and relative) are equivalent (it's harder "
"than you think)." << std::endl;
"than you think)."
<< std::endl;
return false;
}
return false;
}
}
}
return true;
}
bool CommandLineInterface::ExpandArgumentFile(const string& file,
std::vector<string>* arguments) {
// The argument file is searched in the working directory only. We don't
// use the proto import path here.
std::ifstream file_stream(file.c_str());
if (!file_stream.is_open()) {
return false;
}
string argument;
// We don't support any kind of shell expansion right now.
while (std::getline(file_stream, argument)) {
arguments->push_back(argument);
}
return true;
}
CommandLineInterface::ParseArgumentStatus
CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
@@ -1009,9 +1188,23 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
std::vector<string> arguments;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == '@') {
if (!ExpandArgumentFile(argv[i] + 1, &arguments)) {
std::cerr << "Failed to open argument file: " << (argv[i] + 1)
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
continue;
}
arguments.push_back(argv[i]);
}
// if no arguments are given, show help
if (arguments.empty()) {
PrintHelpText();
return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler.
}
// Iterate through all arguments and parse them.
for (int i = 0; i < arguments.size(); ++i) {
string name, value;
@@ -1085,7 +1278,7 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
return PARSE_ARGUMENT_FAIL;
}
if (mode_ == MODE_COMPILE && output_directives_.empty() &&
descriptor_set_name_.empty()) {
descriptor_set_out_name_.empty()) {
std::cerr << "Missing output directives." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
@@ -1100,11 +1293,11 @@ CommandLineInterface::ParseArguments(int argc, const char* const argv[]) {
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
if (imports_in_descriptor_set_ && descriptor_set_name_.empty()) {
if (imports_in_descriptor_set_ && descriptor_set_out_name_.empty()) {
std::cerr << "--include_imports only makes sense when combined with "
"--descriptor_set_out." << std::endl;
}
if (source_info_in_descriptor_set_ && descriptor_set_name_.empty()) {
if (source_info_in_descriptor_set_ && descriptor_set_out_name_.empty()) {
std::cerr << "--include_source_info only makes sense when combined with "
"--descriptor_set_out." << std::endl;
}
@@ -1191,11 +1384,20 @@ CommandLineInterface::InterpretArgument(const string& name,
input_files_.push_back(value);
} else if (name == "-I" || name == "--proto_path") {
if (!descriptor_set_in_names_.empty()) {
std::cerr << "Only one of " << name
<< " and --descriptor_set_in can be specified."
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
// Java's -classpath (and some other languages) delimits path components
// with colons. Let's accept that syntax too just to make things more
// intuitive.
std::vector<string> parts = Split(
value, kPathSeparator, true);
value,
CommandLineInterface::kPathSeparator,
true);
for (int i = 0; i < parts.size(); i++) {
string virtual_path;
@@ -1253,8 +1455,38 @@ CommandLineInterface::InterpretArgument(const string& name,
} else if (name == "--direct_dependencies_violation_msg") {
direct_dependencies_violation_msg_ = value;
} else if (name == "--descriptor_set_in") {
if (!descriptor_set_in_names_.empty()) {
std::cerr << name << " may only be passed once. To specify multiple "
"descriptor sets, pass them all as a single "
"parameter separated by '"
<< CommandLineInterface::kPathSeparator << "'."
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
if (value.empty()) {
std::cerr << name << " requires a non-empty value." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
if (!proto_path_.empty()) {
std::cerr << "Only one of " << name
<< " and --proto_path can be specified."
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
if (!dependency_out_name_.empty()) {
std::cerr << name << " cannot be used with --dependency_out."
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
descriptor_set_in_names_ = Split(
value,
CommandLineInterface::kPathSeparator,
true);
} else if (name == "-o" || name == "--descriptor_set_out") {
if (!descriptor_set_name_.empty()) {
if (!descriptor_set_out_name_.empty()) {
std::cerr << name << " may only be passed once." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
@@ -1268,7 +1500,7 @@ CommandLineInterface::InterpretArgument(const string& name,
"same time." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
descriptor_set_name_ = value;
descriptor_set_out_name_ = value;
} else if (name == "--dependency_out") {
if (!dependency_out_name_.empty()) {
@@ -1279,6 +1511,11 @@ CommandLineInterface::InterpretArgument(const string& name,
std::cerr << name << " requires a non-empty value." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
if (!descriptor_set_in_names_.empty()) {
std::cerr << name << " cannot be used with --descriptor_set_in."
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
dependency_out_name_ = value;
} else if (name == "--include_imports") {
@@ -1303,9 +1540,9 @@ CommandLineInterface::InterpretArgument(const string& name,
if (!version_info_.empty()) {
std::cout << version_info_ << std::endl;
}
cout << "libprotoc "
std::cout << "libprotoc "
<< protobuf::internal::VersionString(GOOGLE_PROTOBUF_VERSION)
<< endl;
<< std::endl;
return PARSE_ARGUMENT_DONE_AND_EXIT; // Exit without running compiler.
} else if (name == "--disallow_services") {
@@ -1318,7 +1555,7 @@ CommandLineInterface::InterpretArgument(const string& name,
<< std::endl;
return PARSE_ARGUMENT_FAIL;
}
if (!output_directives_.empty() || !descriptor_set_name_.empty()) {
if (!output_directives_.empty() || !descriptor_set_out_name_.empty()) {
std::cerr << "Cannot use " << name
<< " and generate code or descriptors at the same time."
<< std::endl;
@@ -1384,7 +1621,7 @@ CommandLineInterface::InterpretArgument(const string& name,
<< "other info at the same time." << std::endl;
return PARSE_ARGUMENT_FAIL;
}
if (!output_directives_.empty() || !descriptor_set_name_.empty()) {
if (!output_directives_.empty() || !descriptor_set_out_name_.empty()) {
std::cerr << "Cannot use " << name
<< " and generate code or descriptors at the same time."
<< std::endl;
@@ -1476,6 +1713,14 @@ void CommandLineInterface::PrintHelpText() {
" pairs in text format to standard output. No\n"
" PROTO_FILES should be given when using this\n"
" flag.\n"
" --descriptor_set_in=FILES Specifies a delimited list of FILES\n"
" each containing a FileDescriptorSet (a\n"
" protocol buffer defined in descriptor.proto).\n"
" The FileDescriptor for each of the PROTO_FILES\n"
" provided will be loaded from these\n"
" FileDescriptorSets. If a FileDescriptor\n"
" appears multiple times, the first occurrence\n"
" will be used.\n"
" -oFILE, Writes a FileDescriptorSet (a protocol buffer,\n"
" --descriptor_set_out=FILE defined in descriptor.proto) containing all of\n"
" the input files to FILE.\n"
@@ -1521,6 +1766,20 @@ void CommandLineInterface::PrintHelpText() {
<< string(19 - iter->first.size(), ' ') // Spaces for alignment.
<< iter->second.help_text << std::endl;
}
std::cerr <<
" @<filename> Read options and filenames from file. If a\n"
" relative file path is specified, the file\n"
" will be searched in the working directory.\n"
" The --proto_path option will not affect how\n"
" this argument file is searched. Content of\n"
" the file will be expanded in the position of\n"
" @<filename> as in the argument list. Note\n"
" that shell expansion is not applied to the\n"
" content of the file (i.e., you cannot use\n"
" quotes, wildcards, escapes, commands, etc.).\n"
" Each line corresponds to a single argument,\n"
" even if it contains spaces."
<< std::endl;
}
bool CommandLineInterface::GenerateOutput(
@@ -1655,6 +1914,7 @@ bool CommandLineInterface::GeneratePluginOutput(
request.set_parameter(parameter);
}
std::set<const FileDescriptor*> already_seen;
for (int i = 0; i < parsed_files.size(); i++) {
request.add_file_to_generate(parsed_files[i]->name());
@@ -1823,24 +2083,24 @@ bool CommandLineInterface::WriteDescriptorSet(
int fd;
do {
fd = open(descriptor_set_name_.c_str(),
fd = open(descriptor_set_out_name_.c_str(),
O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
} while (fd < 0 && errno == EINTR);
if (fd < 0) {
perror(descriptor_set_name_.c_str());
perror(descriptor_set_out_name_.c_str());
return false;
}
io::FileOutputStream out(fd);
if (!file_set.SerializeToZeroCopyStream(&out)) {
std::cerr << descriptor_set_name_ << ": " << strerror(out.GetErrno())
std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno())
<< std::endl;
out.Close();
return false;
}
if (!out.Close()) {
std::cerr << descriptor_set_name_ << ": " << strerror(out.GetErrno())
std::cerr << descriptor_set_out_name_ << ": " << strerror(out.GetErrno())
<< std::endl;
return false;
}
@@ -52,17 +52,16 @@ namespace protobuf {
class Descriptor; // descriptor.h
class DescriptorPool; // descriptor.h
class FileDescriptor; // descriptor.h
class FileDescriptorSet; // descriptor.h
class FileDescriptorProto; // descriptor.pb.h
template<typename T> class RepeatedPtrField; // repeated_field.h
class SimpleDescriptorDatabase; // descriptor_database.h
} // namespace protobuf
namespace protobuf {
namespace compiler {
class CodeGenerator; // code_generator.h
class GeneratorContext; // code_generator.h
class DiskSourceTree; // importer.h
class CodeGenerator; // code_generator.h
class GeneratorContext; // code_generator.h
class DiskSourceTree; // importer.h
// This class implements the command-line interface to the protocol compiler.
// It is designed to make it very easy to create a custom protocol compiler
@@ -91,9 +90,21 @@ class DiskSourceTree; // importer.h
// The compiler is invoked with syntax like:
// protoc --cpp_out=outdir --foo_out=outdir --proto_path=src src/foo.proto
//
// The .proto file to compile can be specified on the command line using either
// its physical file path, or a virtual path relative to a diretory specified
// in --proto_path. For example, for src/foo.proto, the following two protoc
// invocations work the same way:
// 1. protoc --proto_path=src src/foo.proto (physical file path)
// 2. protoc --proto_path=src foo.proto (virtual path relative to src)
//
// If a file path can be interpreted both as a physical file path and as a
// relative virtual path, the physical file path takes precendence.
//
// For a full description of the command-line syntax, invoke it with --help.
class LIBPROTOC_EXPORT CommandLineInterface {
public:
static const char* const kPathSeparator;
CommandLineInterface();
~CommandLineInterface();
@@ -175,17 +186,11 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// it calls strerror(). I'm not sure why you'd want to do this anyway.
int Run(int argc, const char* const argv[]);
// Call SetInputsAreCwdRelative(true) if the input files given on the command
// line should be interpreted relative to the proto import path specified
// using --proto_path or -I flags. Otherwise, input file names will be
// interpreted relative to the current working directory (or as absolute
// paths if they start with '/'), though they must still reside inside
// a directory given by --proto_path or the compiler will fail. The latter
// mode is generally more intuitive and easier to use, especially e.g. when
// defining implicit rules in Makefiles.
void SetInputsAreProtoPathRelative(bool enable) {
inputs_are_proto_path_relative_ = enable;
}
// DEPRECATED. Calling this method has no effect. Protocol compiler now
// always try to find the .proto file relative to the current directory
// first and if the file is not found, it will then treat the input path
// as a virutal path.
void SetInputsAreProtoPathRelative(bool /* enable */) {}
// Provides some text which will be printed when the --version flag is
// used. The version of libprotoc will also be printed on the next line
@@ -222,6 +227,9 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// Parse all command-line arguments.
ParseArgumentStatus ParseArguments(int argc, const char* const argv[]);
// Read an argument file and append the file's content to the list of
// arguments. Return false if the file cannot be read.
bool ExpandArgumentFile(const string& file, std::vector<string>* arguments);
// Parses a command-line argument into a name/value pair. Returns
// true if the next argument in the argv should be used as the value,
@@ -243,6 +251,16 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// Print the --help text to stderr.
void PrintHelpText();
// Loads proto_path_ into the provided source_tree.
bool InitializeDiskSourceTree(DiskSourceTree* source_tree);
// Loads descriptor_set_in into the provided database
bool PopulateSimpleDescriptorDatabase(SimpleDescriptorDatabase* database);
// Parses input_files_ into parsed_files
bool ParseInputFiles(DescriptorPool* descriptor_pool,
std::vector<const FileDescriptor*>* parsed_files);
// Generate the given output file from the given input.
struct OutputDirective; // see below
bool GenerateOutput(const std::vector<const FileDescriptor*>& parsed_files,
@@ -383,9 +401,13 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// decoding. (Empty string indicates --decode_raw.)
string codec_type_;
// If --descriptor_set_in was given, these are filenames containing
// parsed FileDescriptorSets to be used for loading protos. Otherwise, empty.
std::vector<string> descriptor_set_in_names_;
// If --descriptor_set_out was given, this is the filename to which the
// FileDescriptorSet should be written. Otherwise, empty.
string descriptor_set_name_;
string descriptor_set_out_name_;
// If --dependency_out was given, this is the path to the file where the
// dependency file will be written. Otherwise, empty.
@@ -408,9 +430,6 @@ class LIBPROTOC_EXPORT CommandLineInterface {
// Was the --disallow_services flag used?
bool disallow_services_;
// See SetInputsAreProtoPathRelative().
bool inputs_are_proto_path_relative_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CommandLineInterface);
};
@@ -35,9 +35,8 @@
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef _MSC_VER
#include <io.h>
#else
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <memory>
@@ -65,26 +64,27 @@
#include <gtest/gtest.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/io_win32.h>
namespace google {
namespace protobuf {
namespace compiler {
#if defined(_WIN32)
// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
// them like we do below.
using google::protobuf::internal::win32::access;
using google::protobuf::internal::win32::dup;
using google::protobuf::internal::win32::dup2;
using google::protobuf::internal::win32::close;
using google::protobuf::internal::win32::open;
using google::protobuf::internal::win32::write;
#endif
// Disable the whole test when we use tcmalloc for "draconian" heap checks, in
// which case tcmalloc will print warnings that fail the plugin tests.
#if !GOOGLE_PROTOBUF_HEAP_CHECK_DRACONIAN
#if defined(_WIN32)
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef F_OK
#define F_OK 00 // not defined by MSVC for whatever reason
#endif
#endif
namespace {
@@ -129,10 +129,6 @@ class CommandLineInterfaceTest : public testing::Test {
// google3.
#endif // !PROTOBUF_OPENSOURCE
void SetInputsAreProtoPathRelative(bool enable) {
cli_.SetInputsAreProtoPathRelative(enable);
}
// -----------------------------------------------------------------
// Methods to check the test results (called after Run()).
@@ -192,12 +188,17 @@ class CommandLineInterfaceTest : public testing::Test {
const string& insertions,
const string& proto_name,
const string& message_name);
void CheckGeneratedAnnotations(const string& name, const string& file);
void ExpectNullCodeGeneratorCalled(const string& parameter);
void ReadDescriptorSet(const string& filename,
FileDescriptorSet* descriptor_set);
void WriteDescriptorSet(const string& filename,
const FileDescriptorSet* descriptor_set);
void ExpectFileContent(const string& filename,
const string& content);
@@ -251,11 +252,6 @@ class CommandLineInterfaceTest::NullCodeGenerator : public CodeGenerator {
// ===================================================================
void CommandLineInterfaceTest::SetUp() {
// Most of these tests were written before this option was added, so we
// run with the option on (which used to be the only way) except in certain
// tests where we turn it off.
cli_.SetInputsAreProtoPathRelative(true);
temp_directory_ = TestTempDir() + "/proto2_cli_test_temp";
// If the temp directory already exists, it must be left over from a
@@ -281,6 +277,7 @@ void CommandLineInterfaceTest::SetUp() {
mock_generators_to_delete_.push_back(generator);
cli_.RegisterGenerator("--null_out", generator, "Null output.");
disallow_plugins_ = false;
}
@@ -471,12 +468,18 @@ void CommandLineInterfaceTest::ExpectGeneratedWithInsertions(
proto_name, temp_directory_);
}
void CommandLineInterfaceTest::CheckGeneratedAnnotations(const string& name,
const string& file) {
MockCodeGenerator::CheckGeneratedAnnotations(name, file, temp_directory_);
}
void CommandLineInterfaceTest::ExpectNullCodeGeneratorCalled(
const string& parameter) {
EXPECT_TRUE(null_generator_->called_);
EXPECT_EQ(parameter, null_generator_->parameter_);
}
void CommandLineInterfaceTest::ReadDescriptorSet(
const string& filename, FileDescriptorSet* descriptor_set) {
string path = temp_directory_ + "/" + filename;
@@ -488,6 +491,13 @@ void CommandLineInterfaceTest::ReadDescriptorSet(
}
}
void CommandLineInterfaceTest::WriteDescriptorSet(
const string& filename, const FileDescriptorSet* descriptor_set) {
string binary_proto;
GOOGLE_CHECK(descriptor_set->SerializeToString(&binary_proto));
CreateTempFile(filename, binary_proto);
}
void CommandLineInterfaceTest::ExpectCapturedStdout(
const string& expected_text) {
EXPECT_EQ(expected_text, captured_stdout_);
@@ -496,7 +506,8 @@ void CommandLineInterfaceTest::ExpectCapturedStdout(
void CommandLineInterfaceTest::ExpectCapturedStdoutSubstringWithZeroReturnCode(
const string& expected_substring) {
EXPECT_EQ(0, return_code_);
EXPECT_PRED_FORMAT2(testing::IsSubstring, expected_substring, captured_stdout_);
EXPECT_PRED_FORMAT2(
testing::IsSubstring, expected_substring, captured_stdout_);
}
void CommandLineInterfaceTest::ExpectFileContent(
@@ -525,6 +536,22 @@ TEST_F(CommandLineInterfaceTest, BasicOutput) {
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
}
TEST_F(CommandLineInterfaceTest, BasicOutput_DescriptorSetIn) {
// Test that the common case works.
FileDescriptorSet file_descriptor_set;
FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("foo.proto");
file_descriptor_proto->add_message_type()->set_name("Foo");
WriteDescriptorSet("foo.bin", &file_descriptor_set);
Run("protocol_compiler --test_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo.bin foo.proto");
ExpectNoErrors();
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
}
TEST_F(CommandLineInterfaceTest, BasicPlugin) {
// Test that basic plugins work.
@@ -539,6 +566,23 @@ TEST_F(CommandLineInterfaceTest, BasicPlugin) {
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
}
TEST_F(CommandLineInterfaceTest, BasicPlugin_DescriptorSetIn) {
// Test that basic plugins work.
FileDescriptorSet file_descriptor_set;
FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("foo.proto");
file_descriptor_proto->add_message_type()->set_name("Foo");
WriteDescriptorSet("foo.bin", &file_descriptor_set);
Run("protocol_compiler --plug_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo.bin foo.proto");
ExpectNoErrors();
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
}
TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin) {
// Invoke a generator and a plugin at the same time.
@@ -554,6 +598,24 @@ TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin) {
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
}
TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin_DescriptorSetIn) {
// Invoke a generator and a plugin at the same time.
FileDescriptorSet file_descriptor_set;
FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("foo.proto");
file_descriptor_proto->add_message_type()->set_name("Foo");
WriteDescriptorSet("foo.bin", &file_descriptor_set);
Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo.bin foo.proto");
ExpectNoErrors();
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
}
TEST_F(CommandLineInterfaceTest, MultipleInputs) {
// Test parsing multiple input files.
@@ -578,6 +640,34 @@ TEST_F(CommandLineInterfaceTest, MultipleInputs) {
"bar.proto", "Bar");
}
TEST_F(CommandLineInterfaceTest, MultipleInputs_DescriptorSetIn) {
// Test parsing multiple input files.
FileDescriptorSet file_descriptor_set;
FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("foo.proto");
file_descriptor_proto->add_message_type()->set_name("Foo");
file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("bar.proto");
file_descriptor_proto->add_message_type()->set_name("Bar");
WriteDescriptorSet("foo.bin", &file_descriptor_set);
Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo.bin foo.proto bar.proto");
ExpectNoErrors();
ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
"foo.proto", "Foo");
ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
"bar.proto", "Bar");
ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
"foo.proto", "Foo");
ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
"bar.proto", "Bar");
}
TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport) {
// Test parsing multiple input files with an import of a separate file.
@@ -608,6 +698,165 @@ TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport) {
"bar.proto", "Bar");
}
TEST_F(CommandLineInterfaceTest, MultipleInputsWithImport_DescriptorSetIn) {
// Test parsing multiple input files with an import of a separate file.
FileDescriptorSet file_descriptor_set;
FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("foo.proto");
file_descriptor_proto->add_message_type()->set_name("Foo");
file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("bar.proto");
file_descriptor_proto->add_dependency("baz.proto");
DescriptorProto* message = file_descriptor_proto->add_message_type();
message->set_name("Bar");
FieldDescriptorProto* field = message->add_field();
field->set_type_name("Baz");
field->set_name("a");
field->set_number(1);
WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set);
file_descriptor_set.clear_file();
file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("baz.proto");
file_descriptor_proto->add_message_type()->set_name("Baz");
file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("bat.proto");
file_descriptor_proto->add_dependency("baz.proto");
message = file_descriptor_proto->add_message_type();
message->set_name("Bat");
field = message->add_field();
field->set_type_name("Baz");
field->set_name("a");
field->set_number(1);
WriteDescriptorSet("baz_and_bat.bin", &file_descriptor_set);
Run(strings::Substitute(
"protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
"--descriptor_set_in=$0 foo.proto bar.proto",
string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator +
"$tmpdir/baz_and_bat.bin"));
ExpectNoErrors();
ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
"foo.proto", "Foo");
ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
"bar.proto", "Bar");
ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
"foo.proto", "Foo");
ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
"bar.proto", "Bar");
Run(strings::Substitute(
"protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
"--descriptor_set_in=$0 baz.proto bat.proto",
string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator +
"$tmpdir/baz_and_bat.bin"));
ExpectNoErrors();
ExpectGeneratedWithMultipleInputs("test_generator", "baz.proto,bat.proto",
"baz.proto", "Baz");
ExpectGeneratedWithMultipleInputs("test_generator", "baz.proto,bat.proto",
"bat.proto", "Bat");
ExpectGeneratedWithMultipleInputs("test_plugin", "baz.proto,bat.proto",
"baz.proto", "Baz");
ExpectGeneratedWithMultipleInputs("test_plugin", "baz.proto,bat.proto",
"bat.proto", "Bat");
}
TEST_F(CommandLineInterfaceTest,
MultipleInputsWithImport_DescriptorSetIn_DuplicateFileDescriptor) {
// Test parsing multiple input files with an import of a separate file.
FileDescriptorSet file_descriptor_set;
FileDescriptorProto foo_file_descriptor_proto;
foo_file_descriptor_proto.set_name("foo.proto");
foo_file_descriptor_proto.add_message_type()->set_name("Foo");
file_descriptor_set.add_file()->CopyFrom(foo_file_descriptor_proto);
FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("bar.proto");
file_descriptor_proto->add_dependency("baz.proto");
file_descriptor_proto->add_dependency("foo.proto");
DescriptorProto* message = file_descriptor_proto->add_message_type();
message->set_name("Bar");
FieldDescriptorProto* field = message->add_field();
field->set_type_name("Baz");
field->set_name("a");
field->set_number(1);
field = message->add_field();
field->set_type_name("Foo");
field->set_name("f");
field->set_number(2);
WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set);
file_descriptor_set.clear_file();
file_descriptor_set.add_file()->CopyFrom(foo_file_descriptor_proto);
file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("baz.proto");
file_descriptor_proto->add_dependency("foo.proto");
message = file_descriptor_proto->add_message_type();
message->set_name("Baz");
field = message->add_field();
field->set_type_name("Foo");
field->set_name("f");
field->set_number(1);
WriteDescriptorSet("foo_and_baz.bin", &file_descriptor_set);
Run(strings::Substitute(
"protocol_compiler --test_out=$$tmpdir --plug_out=$$tmpdir "
"--descriptor_set_in=$0 bar.proto",
string("$tmpdir/foo_and_bar.bin") +
CommandLineInterface::kPathSeparator +
"$tmpdir/foo_and_baz.bin"));
ExpectNoErrors();
ExpectGenerated("test_generator", "", "bar.proto", "Bar");
ExpectGenerated("test_plugin", "", "bar.proto", "Bar");
}
TEST_F(CommandLineInterfaceTest,
MultipleInputsWithImport_DescriptorSetIn_MissingImport) {
// Test parsing multiple input files with an import of a separate file.
FileDescriptorSet file_descriptor_set;
FileDescriptorProto* file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("foo.proto");
file_descriptor_proto->add_message_type()->set_name("Foo");
file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("bar.proto");
file_descriptor_proto->add_dependency("baz.proto");
DescriptorProto* message = file_descriptor_proto->add_message_type();
message->set_name("Bar");
FieldDescriptorProto* field = message->add_field();
field->set_type_name("Baz");
field->set_name("a");
field->set_number(1);
WriteDescriptorSet("foo_and_bar.bin", &file_descriptor_set);
file_descriptor_set.clear_file();
file_descriptor_proto = file_descriptor_set.add_file();
file_descriptor_proto->set_name("baz.proto");
file_descriptor_proto->add_message_type()->set_name("Baz");
WriteDescriptorSet("baz.bin", &file_descriptor_set);
Run("protocol_compiler --test_out=$tmpdir --plug_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo_and_bar.bin "
"foo.proto bar.proto");
ExpectErrorSubstring(
"bar.proto: Import \"baz.proto\" was not found or had errors.");
ExpectErrorSubstring("bar.proto: \"Baz\" is not defined.");
}
TEST_F(CommandLineInterfaceTest, CreateDirectory) {
// Test that when we output to a sub-directory, it is created.
@@ -754,6 +1003,25 @@ TEST_F(CommandLineInterfaceTest, Insert) {
"foo.proto", "Foo");
}
TEST_F(CommandLineInterfaceTest, InsertWithAnnotationFixup) {
// Check that annotation spans are updated after insertions.
CreateTempFile("foo.proto",
"syntax = \"proto2\";\n"
"message MockCodeGenerator_Annotate {}\n");
Run("protocol_compiler "
"--test_out=TestParameter:$tmpdir "
"--plug_out=TestPluginParameter:$tmpdir "
"--test_out=insert=test_generator,test_plugin:$tmpdir "
"--plug_out=insert=test_generator,test_plugin:$tmpdir "
"--proto_path=$tmpdir foo.proto");
ExpectNoErrors();
CheckGeneratedAnnotations("test_generator", "foo.proto");
CheckGeneratedAnnotations("test_plugin", "foo.proto");
}
#if defined(_WIN32)
TEST_F(CommandLineInterfaceTest, WindowsOutputPath) {
@@ -839,17 +1107,11 @@ TEST_F(CommandLineInterfaceTest, ColonDelimitedPath) {
"}\n");
CreateTempFile("b/foo.proto", "this should not be parsed\n");
#undef PATH_SEPARATOR
#if defined(_WIN32)
#define PATH_SEPARATOR ";"
#else
#define PATH_SEPARATOR ":"
#endif
Run("protocol_compiler --test_out=$tmpdir "
"--proto_path=$tmpdir/a" PATH_SEPARATOR "$tmpdir/b foo.proto");
#undef PATH_SEPARATOR
Run(strings::Substitute(
"protocol_compiler --test_out=$$tmpdir --proto_path=$0 foo.proto",
string("$tmpdir/a") +
CommandLineInterface::kPathSeparator +
"$tmpdir/b"));
ExpectNoErrors();
ExpectGenerated("test_generator", "", "foo.proto", "Foo");
@@ -1059,8 +1321,6 @@ TEST_F(CommandLineInterfaceTest, DirectDependencies_CustomErrorMessage) {
TEST_F(CommandLineInterfaceTest, CwdRelativeInputs) {
// Test that we can accept working-directory-relative input files.
SetInputsAreProtoPathRelative(false);
CreateTempFile("foo.proto",
"syntax = \"proto2\";\n"
"message Foo {}\n");
@@ -1301,6 +1561,36 @@ TEST_F(CommandLineInterfaceTest, WriteDependencyManifestFileForAbsolutePath) {
}
#endif // !_WIN32
TEST_F(CommandLineInterfaceTest, TestArgumentFile) {
// Test parsing multiple input files using an argument file.
CreateTempFile("foo.proto",
"syntax = \"proto2\";\n"
"message Foo {}\n");
CreateTempFile("bar.proto",
"syntax = \"proto2\";\n"
"message Bar {}\n");
CreateTempFile("arguments.txt",
"--test_out=$tmpdir\n"
"--plug_out=$tmpdir\n"
"--proto_path=$tmpdir\n"
"--direct_dependencies_violation_msg=%s is not imported\n"
"foo.proto\n"
"bar.proto");
Run("protocol_compiler @$tmpdir/arguments.txt");
ExpectNoErrors();
ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
"foo.proto", "Foo");
ExpectGeneratedWithMultipleInputs("test_generator", "foo.proto,bar.proto",
"bar.proto", "Bar");
ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
"foo.proto", "Foo");
ExpectGeneratedWithMultipleInputs("test_plugin", "foo.proto,bar.proto",
"bar.proto", "Bar");
}
// -------------------------------------------------------------------
@@ -1318,6 +1608,17 @@ TEST_F(CommandLineInterfaceTest, ParseErrors) {
"foo.proto:2:1: Expected top-level statement (e.g. \"message\").\n");
}
TEST_F(CommandLineInterfaceTest, ParseErrors_DescriptorSetIn) {
// Test that parse errors are reported.
CreateTempFile("foo.bin", "not a FileDescriptorSet");
Run("protocol_compiler --test_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo.bin foo.proto");
ExpectErrorText(
"$tmpdir/foo.bin: Unable to parse.\n");
}
TEST_F(CommandLineInterfaceTest, ParseErrorsMultipleFiles) {
// Test that parse errors are reported from multiple files.
@@ -1364,16 +1665,23 @@ TEST_F(CommandLineInterfaceTest, InputNotFoundError) {
Run("protocol_compiler --test_out=$tmpdir "
"--proto_path=$tmpdir foo.proto");
ExpectErrorText("foo.proto: No such file or directory\n");
}
TEST_F(CommandLineInterfaceTest, InputNotFoundError_DescriptorSetIn) {
// Test what happens if the input file is not found.
Run("protocol_compiler --test_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo.bin foo.proto");
ExpectErrorText(
"foo.proto: File not found.\n");
"$tmpdir/foo.bin: No such file or directory\n");
}
TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundError) {
// Test what happens when a working-directory-relative input file is not
// found.
SetInputsAreProtoPathRelative(false);
Run("protocol_compiler --test_out=$tmpdir "
"--proto_path=$tmpdir $tmpdir/foo.proto");
@@ -1385,8 +1693,6 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotMappedError) {
// Test what happens when a working-directory-relative input file is not
// mapped to a virtual path.
SetInputsAreProtoPathRelative(false);
CreateTempFile("foo.proto",
"syntax = \"proto2\";\n"
"message Foo {}\n");
@@ -1411,8 +1717,6 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputNotFoundAndNotMappedError) {
// Check what happens if the input file is not found *and* is not mapped
// in the proto_path.
SetInputsAreProtoPathRelative(false);
// Create a directory called "bar" so that we can point --proto_path at it.
CreateTempFile("bar/dummy", "");
@@ -1427,8 +1731,6 @@ TEST_F(CommandLineInterfaceTest, CwdRelativeInputShadowedError) {
// Test what happens when a working-directory-relative input file is shadowed
// by another file in the virtual path.
SetInputsAreProtoPathRelative(false);
CreateTempFile("foo/foo.proto",
"syntax = \"proto2\";\n"
"message Foo {}\n");
@@ -1454,8 +1756,34 @@ TEST_F(CommandLineInterfaceTest, ProtoPathNotFoundError) {
"--proto_path=$tmpdir/foo foo.proto");
ExpectErrorText(
"$tmpdir/foo: warning: directory does not exist.\n"
"foo.proto: File not found.\n");
"$tmpdir/foo: warning: directory does not exist.\n"
"foo.proto: No such file or directory\n");
}
TEST_F(CommandLineInterfaceTest, ProtoPathAndDescriptorSetIn) {
Run("protocol_compiler --test_out=$tmpdir "
"--proto_path=$tmpdir --descriptor_set_in=$tmpdir/foo.bin foo.proto");
ExpectErrorText(
"Only one of --descriptor_set_in and --proto_path can be specified.\n");
Run("protocol_compiler --test_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo.bin --proto_path=$tmpdir foo.proto");
ExpectErrorText(
"Only one of --proto_path and --descriptor_set_in can be specified.\n");
}
TEST_F(CommandLineInterfaceTest, ProtoPathAndDependencyOut) {
Run("protocol_compiler --test_out=$tmpdir "
"--dependency_out=$tmpdir/manifest "
"--descriptor_set_in=$tmpdir/foo.bin foo.proto");
ExpectErrorText(
"--descriptor_set_in cannot be used with --dependency_out.\n");
Run("protocol_compiler --test_out=$tmpdir "
"--descriptor_set_in=$tmpdir/foo.bin "
"--dependency_out=$tmpdir/manifest foo.proto");
ExpectErrorText(
"--dependency_out cannot be used with --descriptor_set_in.\n");
}
TEST_F(CommandLineInterfaceTest, MissingInputError) {
@@ -1905,9 +2233,16 @@ TEST_F(CommandLineInterfaceTest, PrintFreeFieldNumbers) {
// test as a shell script, but we'd like to be able to run the test on
// platforms that don't have a Bourne-compatible shell available (especially
// Windows/MSVC).
class EncodeDecodeTest : public testing::Test {
enum EncodeDecodeTestMode {
PROTO_PATH,
DESCRIPTOR_SET_IN
};
class EncodeDecodeTest : public testing::TestWithParam<EncodeDecodeTestMode> {
protected:
virtual void SetUp() {
WriteUnittestProtoDescriptorSet();
duped_stdin_ = dup(STDIN_FILENO);
}
@@ -1950,7 +2285,18 @@ class EncodeDecodeTest : public testing::Test {
std::vector<string> args;
args.push_back("protoc");
SplitStringUsing(command, " ", &args);
args.push_back("--proto_path=" + TestSourceDir());
switch (GetParam()) {
case PROTO_PATH:
args.push_back("--proto_path=" + TestSourceDir());
break;
case DESCRIPTOR_SET_IN:
args.push_back(StrCat(
"--descriptor_set_in=",
unittest_proto_descriptor_set_filename_));
break;
default:
ADD_FAILURE() << "unexpected EncodeDecodeTestMode: " << GetParam();
}
google::protobuf::scoped_array<const char * > argv(new const char* [args.size()]);
for (int i = 0; i < args.size(); i++) {
@@ -1958,7 +2304,6 @@ class EncodeDecodeTest : public testing::Test {
}
CommandLineInterface cli;
cli.SetInputsAreProtoPathRelative(true);
CaptureTestStdout();
CaptureTestStderr();
@@ -1996,12 +2341,37 @@ class EncodeDecodeTest : public testing::Test {
}
private:
void WriteUnittestProtoDescriptorSet() {
unittest_proto_descriptor_set_filename_ =
TestTempDir() + "/unittest_proto_descriptor_set.bin";
FileDescriptorSet file_descriptor_set;
protobuf_unittest::TestAllTypes test_all_types;
test_all_types.descriptor()->file()->CopyTo(file_descriptor_set.add_file());
protobuf_unittest_import::ImportMessage import_message;
import_message.descriptor()->file()->CopyTo(file_descriptor_set.add_file());
protobuf_unittest_import::PublicImportMessage public_import_message;
public_import_message.descriptor()->file()->CopyTo(
file_descriptor_set.add_file());
GOOGLE_DCHECK(file_descriptor_set.IsInitialized());
string binary_proto;
GOOGLE_CHECK(file_descriptor_set.SerializeToString(&binary_proto));
GOOGLE_CHECK_OK(File::SetContents(
unittest_proto_descriptor_set_filename_,
binary_proto,
true));
}
int duped_stdin_;
string captured_stdout_;
string captured_stderr_;
string unittest_proto_descriptor_set_filename_;
};
TEST_F(EncodeDecodeTest, Encode) {
TEST_P(EncodeDecodeTest, Encode) {
RedirectStdinFromFile(TestSourceDir() + "/google/protobuf/"
"testdata/text_format_unittest_data_oneof_implemented.txt");
EXPECT_TRUE(Run("google/protobuf/unittest.proto "
@@ -2011,7 +2381,7 @@ TEST_F(EncodeDecodeTest, Encode) {
ExpectStderrMatchesText("");
}
TEST_F(EncodeDecodeTest, Decode) {
TEST_P(EncodeDecodeTest, Decode) {
RedirectStdinFromFile(TestSourceDir() +
"/google/protobuf/testdata/golden_message_oneof_implemented");
EXPECT_TRUE(Run("google/protobuf/unittest.proto "
@@ -2022,7 +2392,7 @@ TEST_F(EncodeDecodeTest, Decode) {
ExpectStderrMatchesText("");
}
TEST_F(EncodeDecodeTest, Partial) {
TEST_P(EncodeDecodeTest, Partial) {
RedirectStdinFromText("");
EXPECT_TRUE(Run("google/protobuf/unittest.proto "
"--encode=protobuf_unittest.TestRequired"));
@@ -2031,7 +2401,7 @@ TEST_F(EncodeDecodeTest, Partial) {
"warning: Input message is missing required fields: a, b, c\n");
}
TEST_F(EncodeDecodeTest, DecodeRaw) {
TEST_P(EncodeDecodeTest, DecodeRaw) {
protobuf_unittest::TestAllTypes message;
message.set_optional_int32(123);
message.set_optional_string("foo");
@@ -2045,21 +2415,24 @@ TEST_F(EncodeDecodeTest, DecodeRaw) {
ExpectStderrMatchesText("");
}
TEST_F(EncodeDecodeTest, UnknownType) {
TEST_P(EncodeDecodeTest, UnknownType) {
EXPECT_FALSE(Run("google/protobuf/unittest.proto "
"--encode=NoSuchType"));
ExpectStdoutMatchesText("");
ExpectStderrMatchesText("Type not defined: NoSuchType\n");
}
TEST_F(EncodeDecodeTest, ProtoParseError) {
TEST_P(EncodeDecodeTest, ProtoParseError) {
EXPECT_FALSE(Run("google/protobuf/no_such_file.proto "
"--encode=NoSuchType"));
ExpectStdoutMatchesText("");
ExpectStderrMatchesText(
"google/protobuf/no_such_file.proto: File not found.\n");
"google/protobuf/no_such_file.proto: No such file or directory\n");
}
INSTANTIATE_TEST_CASE_P(FileDescriptorSetSource,
EncodeDecodeTest,
testing::Values(PROTO_PATH, DESCRIPTOR_SET_IN));
} // anonymous namespace
#endif // !GOOGLE_PROTOBUF_HEAP_CHECK_DRACONIAN
@@ -125,12 +125,9 @@ TEST(BootstrapTest, GeneratedDescriptorMatches) {
importer.Import("google/protobuf/descriptor.proto");
const FileDescriptor* plugin_proto_file =
importer.Import("google/protobuf/compiler/plugin.proto");
const FileDescriptor* profile_proto_file =
importer.Import("google/protobuf/compiler/profile.proto");
EXPECT_EQ("", error_collector.text_);
ASSERT_TRUE(proto_file != NULL);
ASSERT_TRUE(plugin_proto_file != NULL);
ASSERT_TRUE(profile_proto_file != NULL);
CppGenerator generator;
MockGeneratorContext context;
@@ -141,8 +138,6 @@ TEST(BootstrapTest, GeneratedDescriptorMatches) {
parameter = "dllexport_decl=LIBPROTOC_EXPORT";
ASSERT_TRUE(generator.Generate(plugin_proto_file, parameter,
&context, &error));
ASSERT_TRUE(generator.Generate(profile_proto_file, parameter,
&context, &error));
context.ExpectFileMatches("google/protobuf/descriptor.pb.h",
"google/protobuf/descriptor.pb.h");
@@ -152,10 +147,6 @@ TEST(BootstrapTest, GeneratedDescriptorMatches) {
"google/protobuf/compiler/plugin.pb.h");
context.ExpectFileMatches("google/protobuf/compiler/plugin.pb.cc",
"google/protobuf/compiler/plugin.pb.cc");
context.ExpectFileMatches("google/protobuf/compiler/profile.pb.h",
"google/protobuf/compiler/profile.pb.h");
context.ExpectFileMatches("google/protobuf/compiler/profile.pb.cc",
"google/protobuf/compiler/profile.pb.cc");
}
} // namespace
@@ -81,10 +81,16 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
std::map<string, string> vars;
vars["classname"] = classname_;
vars["short_name"] = descriptor_->name();
vars["enumbase"] = classname_ + (options_.proto_h ? " : int" : "");
vars["enumbase"] = options_.proto_h ? " : int" : "";
// These variables are placeholders to pick out the beginning and ends of
// identifiers for annotations (when doing so with existing variables would
// be ambiguous or impossible). They should never be set to anything but the
// empty string.
vars["{"] = "";
vars["}"] = "";
printer->Print(vars, "enum $enumbase$ {\n");
printer->Annotate("enumbase", descriptor_);
printer->Print(vars, "enum $classname$$enumbase$ {\n");
printer->Annotate("classname", descriptor_);
printer->Indent();
const EnumValueDescriptor* min_value = descriptor_->value(0);
@@ -102,7 +108,8 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
" PROTOBUF_DEPRECATED" : "";
if (i > 0) printer->Print(",\n");
printer->Print(vars, "$prefix$$name$$deprecation$ = $number$");
printer->Print(vars, "${$$prefix$$name$$}$$deprecation$ = $number$");
printer->Annotate("{", "}", descriptor_->value(i));
if (descriptor_->value(i)->number() < min_value->number()) {
min_value = descriptor_->value(i);
@@ -134,14 +141,20 @@ void EnumGenerator::GenerateDefinition(io::Printer* printer) {
}
printer->Print(vars,
"$dllexport$bool $classname$_IsValid(int value);\n"
"const $classname$ $prefix$$short_name$_MIN = $prefix$$min_name$;\n"
"const $classname$ $prefix$$short_name$_MAX = $prefix$$max_name$;\n");
"$dllexport$bool $classname$_IsValid(int value);\n"
"const $classname$ ${$$prefix$$short_name$_MIN$}$ = "
"$prefix$$min_name$;\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(vars,
"const $classname$ ${$$prefix$$short_name$_MAX$}$ = "
"$prefix$$max_name$;\n");
printer->Annotate("{", "}", descriptor_);
if (generate_array_size_) {
printer->Print(vars,
"const int $prefix$$short_name$_ARRAYSIZE = "
"$prefix$$short_name$_MAX + 1;\n\n");
"const int ${$$prefix$$short_name$_ARRAYSIZE$}$ = "
"$prefix$$short_name$_MAX + 1;\n\n");
printer->Annotate("{", "}", descriptor_);
}
if (HasDescriptorMethods(descriptor_->file(), options_)) {
@@ -184,6 +197,8 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) {
vars["nested_name"] = descriptor_->name();
vars["classname"] = classname_;
vars["constexpr"] = options_.proto_h ? "constexpr " : "";
vars["{"] = "";
vars["}"] = "";
printer->Print(vars, "typedef $classname$ $nested_name$;\n");
for (int j = 0; j < descriptor_->value_count(); j++) {
@@ -191,22 +206,27 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) {
vars["deprecated_attr"] = descriptor_->value(j)->options().deprecated() ?
"GOOGLE_PROTOBUF_DEPRECATED_ATTR " : "";
printer->Print(vars,
"$deprecated_attr$static $constexpr$const $nested_name$ $tag$ =\n"
"$deprecated_attr$static $constexpr$const $nested_name$ ${$$tag$$}$ =\n"
" $classname$_$tag$;\n");
printer->Annotate("{", "}", descriptor_->value(j));
}
printer->Print(vars,
"static inline bool $nested_name$_IsValid(int value) {\n"
" return $classname$_IsValid(value);\n"
"}\n"
"static const $nested_name$ $nested_name$_MIN =\n"
" $classname$_$nested_name$_MIN;\n"
"static const $nested_name$ $nested_name$_MAX =\n"
"static const $nested_name$ ${$$nested_name$_MIN$}$ =\n"
" $classname$_$nested_name$_MIN;\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(vars,
"static const $nested_name$ ${$$nested_name$_MAX$}$ =\n"
" $classname$_$nested_name$_MAX;\n");
printer->Annotate("{", "}", descriptor_);
if (generate_array_size_) {
printer->Print(vars,
"static const int $nested_name$_ARRAYSIZE =\n"
"static const int ${$$nested_name$_ARRAYSIZE$}$ =\n"
" $classname$_$nested_name$_ARRAYSIZE;\n");
printer->Annotate("{", "}", descriptor_);
}
if (HasDescriptorMethods(descriptor_->file(), options_)) {
@@ -229,27 +249,10 @@ void EnumGenerator::GenerateSymbolImports(io::Printer* printer) {
}
}
void EnumGenerator::GenerateDescriptorInitializer(io::Printer* printer) {
std::map<string, string> vars;
vars["index"] = SimpleItoa(descriptor_->index());
vars["index_in_metadata"] = SimpleItoa(index_in_metadata_);
if (descriptor_->containing_type() == NULL) {
printer->Print(vars,
"file_level_enum_descriptors[$index_in_metadata$] = "
"file->enum_type($index$);\n");
} else {
vars["parent"] = ClassName(descriptor_->containing_type(), false);
printer->Print(vars,
"file_level_enum_descriptors[$index_in_metadata$] = "
"$parent$_descriptor->enum_type($index$);\n");
}
}
void EnumGenerator::GenerateMethods(io::Printer* printer) {
void EnumGenerator::GenerateMethods(int idx, io::Printer* printer) {
std::map<string, string> vars;
vars["classname"] = classname_;
vars["index_in_metadata"] = SimpleItoa(index_in_metadata_);
vars["index_in_metadata"] = SimpleItoa(idx);
vars["constexpr"] = options_.proto_h ? "constexpr " : "";
vars["file_namespace"] = FileLevelNamespace(descriptor_->file()->name());
@@ -86,13 +86,10 @@ class EnumGenerator {
// Source file stuff.
// Generate code that initializes the global variable storing the enum's
// descriptor.
void GenerateDescriptorInitializer(io::Printer* printer);
// Generate non-inline methods related to the enum, such as IsValidValue().
// Goes in the .cc file.
void GenerateMethods(io::Printer* printer);
// Goes in the .cc file. EnumDescriptors are stored in an array, idx is
// the index in this array that corresponds with this enum.
void GenerateMethods(int idx, io::Printer* printer);
private:
const EnumDescriptor* descriptor_;
@@ -101,8 +98,6 @@ class EnumGenerator {
// whether to generate the *_ARRAYSIZE constant.
const bool generate_array_size_;
int index_in_metadata_;
friend class FileGenerator;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
};
@@ -74,27 +74,26 @@ GeneratePrivateMembers(io::Printer* printer) const {
void EnumFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_, "$deprecated_attr$$type$ $name$() const;\n");
printer->Annotate("name", descriptor_);
printer->Print(variables_,
"$deprecated_attr$$type$ $name$() const;\n"
"$deprecated_attr$void set_$name$($type$ value);\n");
"$deprecated_attr$void ${$set_$name$$}$($type$ value);\n");
printer->Annotate("{", "}", descriptor_);
}
void EnumFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
"$inline$$type$ $classname$::$name$() const {\n"
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return static_cast< $type$ >($name$_);\n"
"}\n"
"$inline$void $classname$::set_$name$($type$ value) {\n");
"inline void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
printer->Print(variables,
printer->Print(variables_,
" assert($type$_IsValid(value));\n");
}
printer->Print(variables,
printer->Print(variables_,
" $set_hasbit$\n"
" $name$_ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
@@ -113,7 +112,7 @@ GenerateMergingCode(io::Printer* printer) const {
void EnumFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
printer->Print(variables_, "swap($name$_, other->$name$_);\n");
}
void EnumFieldGenerator::
@@ -143,12 +142,14 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(variables_,
"} else {\n"
" mutable_unknown_fields()->AddVarint($number$, value);\n");
" mutable_unknown_fields()->AddVarint(\n"
" $number$, static_cast< ::google::protobuf::uint64>(value));\n");
} else {
printer->Print(
"} else {\n"
" unknown_fields_stream.WriteVarint32($tag$u);\n"
" unknown_fields_stream.WriteVarint32(value);\n",
" unknown_fields_stream.WriteVarint32(\n"
" static_cast< ::google::protobuf::uint32>(value));\n",
"tag", SimpleItoa(internal::WireFormat::MakeTag(descriptor_)));
}
printer->Print(variables_,
@@ -189,24 +190,21 @@ EnumOneofFieldGenerator(const FieldDescriptor* descriptor,
EnumOneofFieldGenerator::~EnumOneofFieldGenerator() {}
void EnumOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
"$inline$$type$ $classname$::$name$() const {\n"
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return static_cast< $type$ >($oneof_prefix$$name$_);\n"
" }\n"
" return static_cast< $type$ >($default$);\n"
"}\n"
"$inline$void $classname$::set_$name$($type$ value) {\n");
"inline void $classname$::set_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
printer->Print(variables,
printer->Print(variables_,
" assert($type$_IsValid(value));\n");
}
printer->Print(variables,
printer->Print(variables_,
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -228,9 +226,8 @@ GenerateSwappingCode(io::Printer* printer) const {
void EnumOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(
variables_,
"_$classname$_default_instance_.$name$_ = $default$;\n");
printer->Print(variables_,
"$ns$::_$classname$_default_instance_.$name$_ = $default$;\n");
}
// ===================================================================
@@ -257,49 +254,56 @@ GeneratePrivateMembers(io::Printer* printer) const {
void RepeatedEnumFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"$deprecated_attr$$type$ $name$(int index) const;\n"
"$deprecated_attr$void set_$name$(int index, $type$ value);\n"
"$deprecated_attr$void add_$name$($type$ value);\n");
"$deprecated_attr$$type$ $name$(int index) const;\n");
printer->Annotate("name", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$void ${$set_$name$$}$(int index, $type$ value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$const ::google::protobuf::RepeatedField<int>& $name$() const;\n"
"$deprecated_attr$::google::protobuf::RepeatedField<int>* mutable_$name$();\n");
"$deprecated_attr$void ${$add_$name$$}$($type$ value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$const ::google::protobuf::RepeatedField<int>& $name$() const;\n");
printer->Annotate("name", descriptor_);
printer->Print(variables_,
"$deprecated_attr$::google::protobuf::RepeatedField<int>* "
"${$mutable_$name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
}
void RepeatedEnumFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
"$inline$$type$ $classname$::$name$(int index) const {\n"
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return static_cast< $type$ >($name$_.Get(index));\n"
"}\n"
"$inline$void $classname$::set_$name$(int index, $type$ value) {\n");
"inline void $classname$::set_$name$(int index, $type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
printer->Print(variables,
printer->Print(variables_,
" assert($type$_IsValid(value));\n");
}
printer->Print(variables,
printer->Print(variables_,
" $name$_.Set(index, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"$inline$void $classname$::add_$name$($type$ value) {\n");
"inline void $classname$::add_$name$($type$ value) {\n");
if (!HasPreservingUnknownEnumSemantics(descriptor_->file())) {
printer->Print(variables,
printer->Print(variables_,
" assert($type$_IsValid(value));\n");
}
printer->Print(variables,
printer->Print(variables_,
" $name$_.Add(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n");
printer->Print(variables,
"$inline$const ::google::protobuf::RepeatedField<int>&\n"
"}\n"
"inline const ::google::protobuf::RepeatedField<int>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
"$inline$::google::protobuf::RepeatedField<int>*\n"
"inline ::google::protobuf::RepeatedField<int>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -344,12 +348,14 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(variables_,
"} else {\n"
" mutable_unknown_fields()->AddVarint($number$, value);\n");
" mutable_unknown_fields()->AddVarint(\n"
" $number$, static_cast< ::google::protobuf::uint64>(value));\n");
} else {
printer->Print(
"} else {\n"
" unknown_fields_stream.WriteVarint32(tag);\n"
" unknown_fields_stream.WriteVarint32(value);\n");
" unknown_fields_stream.WriteVarint32(\n"
" static_cast< ::google::protobuf::uint32>(value));\n");
}
printer->Print("}\n");
}
@@ -391,7 +397,7 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
"::google::protobuf::uint32 length;\n"
"DO_(input->ReadVarint32(&length));\n"
"::google::protobuf::io::CodedInputStream::Limit limit = "
"input->PushLimit(length);\n"
"input->PushLimit(static_cast<int>(length));\n"
"while (input->BytesUntilLimit() > 0) {\n"
" int value;\n"
" DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<\n"
@@ -407,11 +413,13 @@ GenerateMergeFromCodedStreamWithPacking(io::Printer* printer) const {
" } else {\n");
if (UseUnknownFieldSet(descriptor_->file(), options_)) {
printer->Print(variables_,
" mutable_unknown_fields()->AddVarint($number$, value);\n");
" mutable_unknown_fields()->AddVarint(\n"
" $number$, static_cast< ::google::protobuf::uint64>(value));\n");
} else {
printer->Print(variables_,
" unknown_fields_stream.WriteVarint32(tag);\n"
" unknown_fields_stream.WriteVarint32(value);\n");
" unknown_fields_stream.WriteVarint32(\n"
" static_cast< ::google::protobuf::uint32>(value));\n");
}
printer->Print(
" }\n");
@@ -432,7 +440,8 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
" $number$,\n"
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" output);\n"
" output->WriteVarint32(_$name$_cached_byte_size_);\n"
" output->WriteVarint32(\n"
" static_cast< ::google::protobuf::uint32>(_$name$_cached_byte_size_));\n"
"}\n");
}
printer->Print(variables_,
@@ -460,7 +469,8 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" target);\n"
" target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray("
" _$name$_cached_byte_size_, target);\n"
" static_cast< ::google::protobuf::uint32>(\n"
" _$name$_cached_byte_size_), target);\n"
" target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray(\n"
" this->$name$_, target);\n"
"}\n");
@@ -476,19 +486,20 @@ GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"{\n"
" size_t data_size = 0;\n"
" unsigned int count = this->$name$_size();");
" unsigned int count = static_cast<unsigned int>(this->$name$_size());");
printer->Indent();
printer->Print(variables_,
"for (unsigned int i = 0; i < count; i++) {\n"
" data_size += ::google::protobuf::internal::WireFormatLite::EnumSize(\n"
" this->$name$(i));\n"
" this->$name$(static_cast<int>(i)));\n"
"}\n");
if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (data_size > 0) {\n"
" total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
" ::google::protobuf::internal::WireFormatLite::Int32Size(\n"
" static_cast< ::google::protobuf::int32>(data_size));\n"
"}\n"
"int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
@@ -52,8 +52,7 @@ class EnumFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
@@ -79,8 +78,7 @@ class EnumOneofFieldGenerator : public EnumFieldGenerator {
~EnumOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
@@ -98,8 +96,7 @@ class RepeatedEnumFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
@@ -35,9 +35,10 @@
#include <google/protobuf/compiler/cpp/cpp_extension.h>
#include <map>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
@@ -166,46 +167,6 @@ void ExtensionGenerator::GenerateDefinition(io::Printer* printer) {
" $name$($constant_name$, $default$);\n");
}
void ExtensionGenerator::GenerateRegistration(io::Printer* printer) {
std::map<string, string> vars;
vars["extendee" ] = ExtendeeClassName(descriptor_);
vars["number" ] = SimpleItoa(descriptor_->number());
vars["field_type" ] = SimpleItoa(static_cast<int>(descriptor_->type()));
vars["is_repeated"] = descriptor_->is_repeated() ? "true" : "false";
vars["is_packed" ] = (descriptor_->is_repeated() &&
descriptor_->options().packed())
? "true" : "false";
switch (descriptor_->cpp_type()) {
case FieldDescriptor::CPPTYPE_ENUM:
printer->Print(
vars,
"::google::protobuf::internal::ExtensionSet::RegisterEnumExtension(\n"
" $extendee$::internal_default_instance(),\n"
" $number$, $field_type$, $is_repeated$, $is_packed$,\n");
printer->Print(
" &$type$_IsValid);\n",
"type", ClassName(descriptor_->enum_type(), true));
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
printer->Print(
vars,
"::google::protobuf::internal::ExtensionSet::RegisterMessageExtension(\n"
" $extendee$::internal_default_instance(),\n"
" $number$, $field_type$, $is_repeated$, $is_packed$,\n");
printer->Print(" $type$::internal_default_instance());\n", "type",
ClassName(descriptor_->message_type(), true));
break;
default:
printer->Print(
vars,
"::google::protobuf::internal::ExtensionSet::RegisterExtension(\n"
" $extendee$::internal_default_instance(),\n"
" $number$, $field_type$, $is_repeated$, $is_packed$);\n");
break;
}
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
@@ -67,9 +67,6 @@ class ExtensionGenerator {
// Source file stuff.
void GenerateDefinition(io::Printer* printer);
// Generate code to register the extension.
void GenerateRegistration(io::Printer* printer);
private:
const FieldDescriptor* descriptor_;
string type_traits_;
@@ -61,6 +61,7 @@ using internal::WireFormat;
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables,
const Options& options) {
(*variables)["ns"] = Namespace(descriptor);
(*variables)["name"] = FieldName(descriptor);
(*variables)["index"] = SimpleItoa(descriptor->index());
(*variables)["number"] = SimpleItoa(descriptor->number());
@@ -95,6 +96,13 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
// 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
// empty string.
(*variables)["{"] = "";
(*variables)["}"] = "";
}
void SetCommonOneofFieldVariables(const FieldDescriptor* descriptor,
@@ -194,7 +202,6 @@ const FieldGenerator& FieldGeneratorMap::get(
return *field_generators_[field->index()];
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
@@ -109,19 +109,19 @@ class FieldGenerator {
// 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 {}
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, bool is_inline) const = 0;
io::Printer* printer) const = 0;
// Generate definitions of accessors that aren't inlined. These are
// placed somewhere in the .cc file.
// Most field types don't need this, so the default implementation is empty.
virtual void GenerateNonInlineAccessorDefinitions(
io::Printer* /*printer*/) const {}
io::Printer* /*printer*/) const {}
// Generate lines of code (statements, not declarations) which clear the
// field. This is used to define the clear_$name$() method
@@ -180,10 +180,6 @@ class FieldGenerator {
virtual void GenerateDefaultInstanceAllocator(io::Printer* /*printer*/)
const {}
// Generate code that should be run when ShutdownProtobufLibrary() is called,
// to delete all dynamically-allocated objects.
virtual void GenerateShutdownCode(io::Printer* /*printer*/) const {}
// Generate lines to decode this field, which will be placed inside the
// message's MergeFromCodedStream() method.
virtual void GenerateMergeFromCodedStream(io::Printer* printer) const = 0;
@@ -233,7 +229,6 @@ class FieldGeneratorMap {
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
File diff suppressed because it is too large. Load diff
@@ -35,10 +35,12 @@
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_FILE_H__
#include <algorithm>
#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif
#include <set>
#include <string>
#include <vector>
#include <google/protobuf/stubs/common.h>
@@ -82,16 +84,21 @@ class FileGenerator {
const string& info_path);
void GenerateSource(io::Printer* printer);
int NumMessages() const { return message_generators_.size(); }
// Similar to GenerateSource but generates only one message
void GenerateSourceForMessage(int idx, io::Printer* printer);
void GenerateGlobalSource(io::Printer* printer);
private:
// Internal type used by GenerateForwardDeclarations (defined in file.cc).
class ForwardDeclarations;
// Generate the BuildDescriptors() procedure, which builds all descriptors
// for types defined in the file.
void GenerateBuildDescriptors(io::Printer* printer);
void GenerateSourceIncludes(io::Printer* printer);
void GenerateSourceDefaultInstance(int idx, io::Printer* printer);
void GenerateNamespaceOpeners(io::Printer* printer);
void GenerateNamespaceClosers(io::Printer* printer);
void GenerateInitForSCC(const SCC* scc, io::Printer* printer);
void GenerateInitializationCode(io::Printer* printer);
void GenerateReflectionInitializationCode(io::Printer* printer);
// For other imports, generates their forward-declarations.
void GenerateForwardDeclarations(io::Printer* printer);
@@ -143,11 +150,23 @@ class FileGenerator {
// a breaking change so we prefer the #undef approach.
void GenerateMacroUndefs(io::Printer* printer);
bool IsSCCRepresentative(const Descriptor* d) {
return GetSCCRepresentative(d) == d;
}
const Descriptor* GetSCCRepresentative(const Descriptor* d) {
return GetSCC(d)->GetRepresentative();
}
const SCC* GetSCC(const Descriptor* d) {
return scc_analyzer_.GetSCC(d);
}
const FileDescriptor* file_;
const Options options_;
SCCAnalyzer scc_analyzer_;
// Contains the post-order walk of all the messages (and child messages) in
// this file. If you need a pre-order walk just reverse iterate.
std::vector<MessageGenerator*> message_generators_;
@@ -155,10 +174,8 @@ class FileGenerator {
std::vector<ServiceGenerator*> service_generators_;
std::vector<ExtensionGenerator*> extension_generators_;
// These members are just for owning (and thus proper deleting). Some of the
// message_ and enum_generators above are owned by child messages.
google::protobuf::scoped_array<google::protobuf::scoped_ptr<MessageGenerator> >
message_generators_owner_;
// 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> >
service_generators_owner_;
@@ -46,6 +46,7 @@
#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 {
@@ -84,7 +85,7 @@ 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;
@@ -98,8 +99,14 @@ bool CppGenerator::Generate(const FileDescriptor* file,
file_options.annotation_guard_name = options[i].second;
} else if (options[i].first == "lite") {
file_options.enforce_lite = true;
} else if (options[i].first == "lite_implicit_weak_fields") {
file_options.lite_implicit_weak_fields = true;
} 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;
@@ -133,14 +140,13 @@ bool CppGenerator::Generate(const FileDescriptor* file,
}
}
basename.append(".pb");
{
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".h"));
generator_context->Open(basename + ".pb.h"));
GeneratedCodeInfo annotations;
io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
&annotations);
string info_path = basename + ".h.meta";
string info_path = basename + ".pb.h.meta";
io::Printer printer(output.get(), '$', file_options.annotate_headers
? &annotation_collector
: NULL);
@@ -154,9 +160,24 @@ bool CppGenerator::Generate(const FileDescriptor* file,
}
// Generate cc file.
{
if (split_source) {
{
// This is the global .cc file, containing enum/services/tables/reflection
google::protobuf::scoped_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++) {
// TODO(gerbens) Agree on naming scheme.
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + "." + SimpleItoa(i) + ".cc"));
io::Printer printer(output.get(), '$');
file_generator.GenerateSourceForMessage(i, &printer);
}
} else {
google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(
generator_context->Open(basename + ".cc"));
generator_context->Open(basename + ".pb.cc"));
io::Printer printer(output.get(), '$');
file_generator.GenerateSource(&printer);
}
@@ -32,19 +32,22 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#include <google/protobuf/stubs/hash.h>
#include <limits>
#include <map>
#include <queue>
#include <vector>
#include <google/protobuf/stubs/hash.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
namespace google {
namespace protobuf {
namespace compiler {
@@ -103,6 +106,30 @@ bool HasExtension(const Descriptor* descriptor) {
return false;
}
// Encode [0..63] as 'A'-'Z', 'a'-'z', '0'-'9', '_'
char Base63Char(int value) {
GOOGLE_CHECK_GE(value, 0);
if (value < 26) return 'A' + value;
value -= 26;
if (value < 26) return 'a' + value;
value -= 26;
if (value < 10) return '0' + value;
GOOGLE_CHECK_EQ(value, 10);
return '_';
}
// Given a c identifier has 63 legal characters we can't implement base64
// encoding. So we return the k least significant "digits" in base 63.
template <typename I>
string Base63(I n, int k) {
string res;
while (k-- > 0) {
res += Base63Char(static_cast<int>(n % 63));
n /= 63;
}
return res;
}
} // namespace
string UnderscoresToCamelCase(const string& input, bool cap_next_letter) {
@@ -135,38 +162,62 @@ const char kThickSeparator[] =
const char kThinSeparator[] =
"// -------------------------------------------------------------------\n";
string ClassName(const Descriptor* descriptor, bool qualified) {
// Find "outer", the descriptor of the top-level message in which
// "descriptor" is embedded.
const Descriptor* outer = descriptor;
while (outer->containing_type() != NULL) outer = outer->containing_type();
const string& outer_name = outer->full_name();
string inner_name = descriptor->full_name().substr(outer_name.size());
if (qualified) {
return "::" + DotsToColons(outer_name) + DotsToUnderscores(inner_name);
} else {
return outer->name() + DotsToUnderscores(inner_name);
bool CanInitializeByZeroing(const FieldDescriptor* field) {
if (field->is_repeated() || field->is_extension()) return false;
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_ENUM:
return field->default_value_enum()->number() == 0;
case FieldDescriptor::CPPTYPE_INT32:
return field->default_value_int32() == 0;
case FieldDescriptor::CPPTYPE_INT64:
return field->default_value_int64() == 0;
case FieldDescriptor::CPPTYPE_UINT32:
return field->default_value_uint32() == 0;
case FieldDescriptor::CPPTYPE_UINT64:
return field->default_value_uint64() == 0;
case FieldDescriptor::CPPTYPE_FLOAT:
return field->default_value_float() == 0;
case FieldDescriptor::CPPTYPE_DOUBLE:
return field->default_value_double() == 0;
case FieldDescriptor::CPPTYPE_BOOL:
return field->default_value_bool() == false;
default:
return false;
}
}
string ClassName(const EnumDescriptor* enum_descriptor, bool qualified) {
string ClassName(const Descriptor* descriptor) {
const Descriptor* parent = descriptor->containing_type();
string res;
if (parent) res += ClassName(parent) + "_";
res += descriptor->name();
if (IsMapEntryMessage(descriptor)) res += "_DoNotUse";
return res;
}
string ClassName(const EnumDescriptor* enum_descriptor) {
if (enum_descriptor->containing_type() == NULL) {
if (qualified) {
return "::" + DotsToColons(enum_descriptor->full_name());
} else {
return enum_descriptor->name();
}
return enum_descriptor->name();
} else {
string result = ClassName(enum_descriptor->containing_type(), qualified);
result += '_';
result += enum_descriptor->name();
return result;
return ClassName(enum_descriptor->containing_type()) + "_" +
enum_descriptor->name();
}
}
string Namespace(const string& package) {
if (package.empty()) return "";
return "::" + DotsToColons(package);
}
string DefaultInstanceName(const Descriptor* descriptor) {
string prefix = descriptor->file()->package().empty() ? "" : "::";
return prefix + DotsToColons(descriptor->file()->package()) + "::_" +
ClassName(descriptor, false) + "_default_instance_";
}
string ReferenceFunctionName(const Descriptor* descriptor) {
return QualifiedClassName(descriptor) + "_ReferenceStrong";
}
string DependentBaseClassTemplateName(const Descriptor* descriptor) {
return ClassName(descriptor, false) + "_InternalBase";
@@ -203,6 +254,30 @@ string EnumValueName(const EnumValueDescriptor* enum_value) {
return result;
}
int EstimateAlignmentSize(const FieldDescriptor* field) {
if (field == NULL) return 0;
if (field->is_repeated()) return 8;
switch (field->cpp_type()) {
case FieldDescriptor::CPPTYPE_BOOL:
return 1;
case FieldDescriptor::CPPTYPE_INT32:
case FieldDescriptor::CPPTYPE_UINT32:
case FieldDescriptor::CPPTYPE_ENUM:
case FieldDescriptor::CPPTYPE_FLOAT:
return 4;
case FieldDescriptor::CPPTYPE_INT64:
case FieldDescriptor::CPPTYPE_UINT64:
case FieldDescriptor::CPPTYPE_DOUBLE:
case FieldDescriptor::CPPTYPE_STRING:
case FieldDescriptor::CPPTYPE_MESSAGE:
return 8;
}
GOOGLE_LOG(FATAL) << "Can't get here.";
return -1; // Make compiler happy.
}
string FieldConstantName(const FieldDescriptor *field) {
string field_name = UnderscoresToCamelCase(field->name(), true);
string result = "k" + field_name + "FieldNumber";
@@ -477,19 +552,6 @@ string SafeFunctionName(const Descriptor* descriptor,
return function_name;
}
bool StaticInitializersForced(const FileDescriptor* file,
const Options& options) {
if (HasDescriptorMethods(file, options) || file->extension_count() > 0) {
return true;
}
for (int i = 0; i < file->message_type_count(); ++i) {
if (HasExtension(file->message_type(i))) {
return true;
}
}
return false;
}
static bool HasMapFields(const Descriptor* descriptor) {
for (int i = 0; i < descriptor->field_count(); ++i) {
@@ -654,6 +716,24 @@ void GenerateUtf8CheckCodeForCord(const FieldDescriptor* field,
"VerifyUtf8Cord", "VerifyUTF8CordNamedField", printer);
}
namespace {
void Flatten(const Descriptor* descriptor,
std::vector<const Descriptor*>* flatten) {
for (int i = 0; i < descriptor->nested_type_count(); i++)
Flatten(descriptor->nested_type(i), flatten);
flatten->push_back(descriptor);
}
} // namespace
void FlattenMessagesInFile(const FileDescriptor* file,
std::vector<const Descriptor*>* result) {
for (int i = 0; i < file->message_type_count(); i++) {
Flatten(file->message_type(i), result);
}
}
bool HasWeakFields(const Descriptor* descriptor) {
return false;
}
@@ -662,6 +742,26 @@ bool HasWeakFields(const FileDescriptor* file) {
return false;
}
bool UsingImplicitWeakFields(const FileDescriptor* file,
const Options& options) {
return options.lite_implicit_weak_fields &&
GetOptimizeFor(file, options) == FileOptions::LITE_RUNTIME;
}
bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options) {
return UsingImplicitWeakFields(field->file(), options) &&
field->type() == FieldDescriptor::TYPE_MESSAGE &&
!field->is_required() && !field->is_repeated() && !field->is_map() &&
field->containing_oneof() == NULL;
}
struct CompareDescriptors {
bool operator()(const Descriptor* a, const Descriptor* b) {
return a->full_name() < b->full_name();
}
};
SCCAnalyzer::NodeData SCCAnalyzer::DFS(const Descriptor* descriptor) {
// Must not have visited already.
GOOGLE_DCHECK_EQ(cache_.count(descriptor), 0);
@@ -701,10 +801,33 @@ SCCAnalyzer::NodeData SCCAnalyzer::DFS(const Descriptor* descriptor) {
if (scc_desc == descriptor) break;
}
// The order of descriptors is random and depends how this SCC was
// discovered. In-order to ensure maximum stability we sort it by name.
std::sort(scc->descriptors.begin(), scc->descriptors.end(),
CompareDescriptors());
AddChildren(scc);
}
return result;
}
void SCCAnalyzer::AddChildren(SCC* scc) {
std::set<const SCC*> seen;
for (int i = 0; i < scc->descriptors.size(); i++) {
const Descriptor* descriptor = scc->descriptors[i];
for (int j = 0; j < descriptor->field_count(); j++) {
const Descriptor* child_msg = descriptor->field(j)->message_type();
if (child_msg) {
const SCC* child = GetSCC(child_msg);
if (child == scc) continue;
if (seen.insert(child).second) {
scc->children.push_back(child);
}
}
}
}
}
MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) {
if (analysis_cache_.count(scc)) return analysis_cache_[scc];
MessageAnalysis result = MessageAnalysis();
@@ -757,6 +880,46 @@ MessageAnalysis SCCAnalyzer::GetSCCAnalysis(const SCC* scc) {
return analysis_cache_[scc] = result;
}
void ListAllFields(const Descriptor* d,
std::vector<const FieldDescriptor*>* fields) {
// Collect sub messages
for (int i = 0; i < d->nested_type_count(); i++) {
ListAllFields(d->nested_type(i), fields);
}
// Collect message level extensions.
for (int i = 0; i < d->extension_count(); i++) {
fields->push_back(d->extension(i));
}
// Add types of fields necessary
for (int i = 0; i < d->field_count(); i++) {
fields->push_back(d->field(i));
}
}
void ListAllFields(const FileDescriptor* d,
std::vector<const FieldDescriptor*>* fields) {
// Collect file level message.
for (int i = 0; i < d->message_type_count(); i++) {
ListAllFields(d->message_type(i), fields);
}
// Collect message level extensions.
for (int i = 0; i < d->extension_count(); i++) {
fields->push_back(d->extension(i));
}
}
void ListAllTypesForServices(const FileDescriptor* fd,
std::vector<const Descriptor*>* types) {
for (int i = 0; i < fd->service_count(); i++) {
const ServiceDescriptor* sd = fd->service(i);
for (int j = 0; j < sd->method_count(); j++) {
const MethodDescriptor* method = sd->method(j);
types->push_back(method->input_type());
types->push_back(method->output_type());
}
}
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
@@ -38,16 +38,13 @@
#include <map>
#include <string>
#include <google/protobuf/compiler/cpp/cpp_options.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
namespace io {
class Printer;
}
namespace compiler {
namespace cpp {
@@ -56,6 +53,31 @@ 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
// the namespace is "::foo::bar::...::baz" without trailing semi-colons.
string Namespace(const string& package);
inline string Namespace(const FileDescriptor* d) {
return Namespace(d->package());
}
template <typename Desc>
string Namespace(const Desc* d) {
return Namespace(d->file());
}
// Returns true if it's safe to reset "field" to zero.
bool CanInitializeByZeroing(const FieldDescriptor* field);
string ClassName(const Descriptor* descriptor);
string ClassName(const EnumDescriptor* enum_descriptor);
template <typename Desc>
string QualifiedClassName(const Desc* d) {
return Namespace(d) + "::" + ClassName(d);
}
// DEPRECATED just use ClassName or QualifiedClassName, a boolean is very
// unreadable at the callsite.
// Returns the non-nested type name for the given type. If "qualified" is
// true, prefix the type with the full namespace. For example, if you had:
// package foo.bar;
@@ -64,8 +86,21 @@ extern const char kThinSeparator[];
// ::foo::bar::Baz_Qux
// While the non-qualified version would be:
// Baz_Qux
string ClassName(const Descriptor* descriptor, bool qualified);
string ClassName(const EnumDescriptor* enum_descriptor, bool qualified);
inline string ClassName(const Descriptor* descriptor, bool qualified) {
return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor);
}
inline string ClassName(const EnumDescriptor* descriptor, bool qualified) {
return qualified ? QualifiedClassName(descriptor) : ClassName(descriptor);
}
// Fully qualified name of the default_instance of this message.
string DefaultInstanceName(const Descriptor* descriptor);
// Returns the name of a no-op function that we can call to introduce a linker
// dependency on the given message type. This is used to implement implicit weak
// fields.
string ReferenceFunctionName(const Descriptor* descriptor);
// Name of the CRTP class template (for use with proto_h).
// This is a class name, like "ProtoName_InternalBase".
@@ -89,6 +124,12 @@ string FieldName(const FieldDescriptor* field);
// Get the sanitized name that should be used for the given enum in C++ code.
string EnumValueName(const EnumValueDescriptor* enum_value);
// Returns an estimate of the compiler's alignment for the field. This
// can't guarantee to be correct because the generated code could be compiled on
// different systems with different alignment rules. The estimates below assume
// 64-bit pointers.
int EstimateAlignmentSize(const FieldDescriptor* field);
// Get the unqualified name that should be used for a field's field
// number constant.
string FieldConstantName(const FieldDescriptor *field);
@@ -147,6 +188,12 @@ string FilenameIdentifier(const string& filename);
// For each .proto file generates a unique namespace. In this namespace global
// definitions are put to prevent collisions.
string FileLevelNamespace(const string& filename);
inline string FileLevelNamespace(const FileDescriptor* file) {
return FileLevelNamespace(file->name());
}
inline string FileLevelNamespace(const Descriptor* d) {
return FileLevelNamespace(d->file());
}
// Return the qualified C++ name for a file level symbol.
string QualifiedFileLevelSymbol(const string& package, const string& name);
@@ -159,8 +206,18 @@ string SafeFunctionName(const Descriptor* descriptor,
const FieldDescriptor* field,
const string& prefix);
// Returns true if unknown fields are preseved after parsing.
inline bool PreserveUnknownFields(const Descriptor* message) {
// Returns true if unknown fields are always preserved after parsing.
inline bool AlwaysPreserveUnknownFields(const FileDescriptor* file) {
return file->syntax() != FileDescriptor::SYNTAX_PROTO3;
}
// Returns true if unknown fields are preserved after parsing.
inline bool AlwaysPreserveUnknownFields(const Descriptor* message) {
return AlwaysPreserveUnknownFields(message->file());
}
// Returns true if generated messages have public unknown fields accessors
inline bool PublicUnknownFieldsAccessors(const Descriptor* message) {
return message->file()->syntax() != FileDescriptor::SYNTAX_PROTO3;
}
@@ -168,10 +225,8 @@ inline bool PreserveUnknownFields(const Descriptor* message) {
::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor(
const FileDescriptor* file, const Options& options);
// If PreserveUnknownFields() is true, determines whether unknown
// fields will be stored in an UnknownFieldSet or a string.
// If PreserveUnknownFields() is false, this method will not be
// used.
// Determines whether unknown fields will be stored in an UnknownFieldSet or
// a string.
inline bool UseUnknownFieldSet(const FileDescriptor* file,
const Options& options) {
return GetOptimizeFor(file, options) != FileOptions::LITE_RUNTIME;
@@ -214,10 +269,6 @@ inline bool HasFastArraySerialization(const FileDescriptor* file,
return GetOptimizeFor(file, options) == FileOptions::SPEED;
}
// Returns whether we have to generate code with static initializers.
bool StaticInitializersForced(const FileDescriptor* file,
const Options& options);
inline bool IsMapEntryMessage(const Descriptor* descriptor) {
return descriptor->options().map_entry();
@@ -254,6 +305,11 @@ inline bool SupportsArenas(const FieldDescriptor* field) {
return SupportsArenas(field->file());
}
inline bool IsCrossFileMessage(const FieldDescriptor* field) {
return field->type() == FieldDescriptor::TYPE_MESSAGE &&
field->message_type()->file() != field->file();
}
bool IsAnyMessage(const FileDescriptor* descriptor);
bool IsAnyMessage(const Descriptor* descriptor);
@@ -277,9 +333,26 @@ inline ::google::protobuf::FileOptions_OptimizeMode GetOptimizeFor(
: file->options().optimize_for();
}
// This orders the messages in a .pb.cc as it's outputted by file.cc
void FlattenMessagesInFile(const FileDescriptor* file,
std::vector<const Descriptor*>* result);
inline std::vector<const Descriptor*> FlattenMessagesInFile(
const FileDescriptor* file) {
std::vector<const Descriptor*> result;
FlattenMessagesInFile(file, &result);
return result;
}
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,
@@ -287,8 +360,46 @@ inline static bool ShouldIgnoreRequiredFieldCheck(const FieldDescriptor* field,
return false;
}
class LIBPROTOC_EXPORT NamespaceOpener {
public:
explicit NamespaceOpener(io::Printer* printer) : printer_(printer) {}
NamespaceOpener(const string& name, io::Printer* printer)
: printer_(printer) {
ChangeTo(name);
}
~NamespaceOpener() { ChangeTo(""); }
void ChangeTo(const string& name) {
std::vector<string> new_stack_ =
Split(name, "::", true);
int len = std::min(name_stack_.size(), new_stack_.size());
int common_idx = 0;
while (common_idx < len) {
if (name_stack_[common_idx] != new_stack_[common_idx]) break;
common_idx++;
}
for (int i = name_stack_.size() - 1; i >= common_idx; i--) {
printer_->Print("} // namespace $ns$\n", "ns", name_stack_[i]);
}
name_stack_.swap(new_stack_);
for (int i = common_idx; i < name_stack_.size(); i++) {
printer_->Print("namespace $ns$ {\n", "ns", name_stack_[i]);
}
}
private:
io::Printer* printer_;
std::vector<string> name_stack_;
};
// Description of each strongly connected component. Note that the order
// of both the descriptors in this SCC and the order of children is
// deterministic.
struct SCC {
std::vector<const Descriptor*> descriptors;
std::vector<const SCC*> children;
const Descriptor* GetRepresentative() const { return descriptors[0]; }
};
struct MessageAnalysis {
@@ -342,8 +453,16 @@ class LIBPROTOC_EXPORT SCCAnalyzer {
// Tarjan's Strongly Connected Components algo
NodeData DFS(const Descriptor* descriptor);
// Add the SCC's that are children of this SCC to its children.
void AddChildren(SCC* scc);
};
void ListAllFields(const FileDescriptor* d,
std::vector<const FieldDescriptor*>* fields);
void ListAllTypesForServices(const FileDescriptor* fd,
std::vector<const Descriptor*>* types);
} // namespace cpp
} // namespace compiler
} // namespace protobuf
@@ -114,72 +114,37 @@ MapFieldGenerator::~MapFieldGenerator() {}
void MapFieldGenerator::
GeneratePrivateMembers(io::Printer* printer) const {
if (HasDescriptorMethods(descriptor_->file(), options_)) {
printer->Print(
variables_,
"public:\n"
"class $map_classname$ : public "
"::google::protobuf::internal::MapEntry<$map_classname$, \n"
" $key_cpp$, $val_cpp$,\n"
" $key_wire_type$,\n"
" $val_wire_type$,\n"
" $default_enum_value$ > {\n"
"public:\n"
" typedef ::google::protobuf::internal::MapEntry<$map_classname$, \n"
" $key_cpp$, $val_cpp$,\n"
" $key_wire_type$,\n"
" $val_wire_type$,\n"
" $default_enum_value$ > SuperType;\n"
" $map_classname$();\n"
" $map_classname$(::google::protobuf::Arena* arena);\n"
" void MergeFrom(const ::google::protobuf::Message& other) PROTOBUF_FINAL;\n"
" void MergeFrom(const $map_classname$& other);\n"
" static const Message* internal_default_instance() { return "
"reinterpret_cast<const "
"Message*>(&_$map_classname$_default_instance_); }\n"
" ::google::protobuf::Metadata GetMetadata() const;\n"
"};\n");
} else {
printer->Print(variables_,
"public:\n"
"typedef ::google::protobuf::internal::MapEntryLite<\n"
" $key_cpp$, $val_cpp$,\n"
" $key_wire_type$,\n"
" $val_wire_type$,\n"
" $default_enum_value$ >\n"
" $map_classname$;\n");
}
printer->Print(variables_,
"::google::protobuf::internal::MapField$lite$<\n"
" $map_classname$,\n"
" $key_cpp$, $val_cpp$,\n"
" $key_wire_type$,\n"
" $val_wire_type$,\n"
" $default_enum_value$ > $name$_;\n"
"private:\n");
" $default_enum_value$ > $name$_;\n");
}
void MapFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
printer->Print(
variables_,
"$deprecated_attr$const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n"
" $name$() const;\n"
"$deprecated_attr$::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n"
" mutable_$name$();\n");
" $name$() const;\n");
printer->Annotate("name", descriptor_);
printer->Print(variables_,
"$deprecated_attr$::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n"
" ${$mutable_$name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
}
void MapFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline" : "";
printer->Print(variables,
"$inline$ const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n"
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline const ::google::protobuf::Map< $key_cpp$, $val_cpp$ >&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_map:$full_name$)\n"
" return $name$_.GetMap();\n"
"}\n"
"$inline$ ::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n"
"inline ::google::protobuf::Map< $key_cpp$, $val_cpp$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_map:$full_name$)\n"
" return $name$_.MutableMap();\n"
@@ -188,9 +153,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
void MapFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
std::map<string, string> variables(variables_);
variables["this_message"] = dependent_field_ ? DependentBaseDownCast() : "";
printer->Print(variables, "$this_message$$name$_.Clear();\n");
printer->Print(variables_, "$name$_.Clear();\n");
}
void MapFieldGenerator::
@@ -256,7 +219,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
} else {
printer->Print(variables_,
" unknown_fields_stream.WriteVarint32($tag$u);\n"
" unknown_fields_stream.WriteVarint32(data.size());\n"
" unknown_fields_stream.WriteVarint32(\n"
" static_cast< ::google::protobuf::uint32>(data.size()));\n"
" unknown_fields_stream.WriteString(data);\n");
}
@@ -267,12 +231,16 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (key_field->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
key_field, options_, true, variables_,
StrCat(key, ".data(), ", key, ".length(),\n").data(), printer);
key_field, options_, true, variables_,
StrCat(key, ".data(), static_cast<int>(", key, ".length()),\n").data(),
printer);
}
if (value_field->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(value_field, options_, true, variables_,
StrCat(value, ".data(), ", value, ".length(),\n").data(), printer);
GenerateUtf8CheckCodeForString(
value_field, options_, true, variables_,
StrCat(value, ".data(), static_cast<int>(", value, ".length()),\n")
.data(),
printer);
}
// If entry is allocated by arena, its desctructor should be avoided.
@@ -376,14 +344,14 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes(
printer->Indent();
printer->Indent();
if (string_key) {
GenerateUtf8CheckCodeForString(key_field, options_, false, variables,
"p->first.data(), p->first.length(),\n",
printer);
GenerateUtf8CheckCodeForString(
key_field, options_, false, variables,
"p->first.data(), static_cast<int>(p->first.length()),\n", printer);
}
if (string_value) {
GenerateUtf8CheckCodeForString(value_field, options_, false, variables,
"p->second.data(), p->second.length(),\n",
printer);
GenerateUtf8CheckCodeForString(
value_field, options_, false, variables,
"p->second.data(), static_cast<int>(p->second.length()),\n", printer);
}
printer->Outdent();
printer->Outdent();
@@ -404,13 +372,14 @@ void MapFieldGenerator::GenerateSerializeWithCachedSizes(
" for (::google::protobuf::Map< $key_cpp$, $val_cpp$ >::const_iterator\n"
" it = this->$name$().begin();\n"
" it != this->$name$().end(); ++it, ++n) {\n"
" items[n] = SortItem(&*it);\n"
" items[static_cast<ptrdiff_t>(n)] = SortItem(&*it);\n"
" }\n"
" ::std::sort(&items[0], &items[n], Less());\n");
" ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less());\n");
printer->Indent();
GenerateSerializationLoop(printer, variables, SupportsArenas(descriptor_),
utf8_check, "for (size_type i = 0; i < n; i++)",
string_key ? "items[i]" : "items[i].second", false);
utf8_check, "for (size_type i = 0; i < n; i++)",
string_key ? "items[static_cast<ptrdiff_t>(i)]" :
"items[static_cast<ptrdiff_t>(i)].second", false);
printer->Outdent();
printer->Print(
"} else {\n");
@@ -49,8 +49,7 @@ class MapFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
File diff suppressed because it is too large. Load diff
@@ -43,6 +43,7 @@
#include <string>
#include <google/protobuf/compiler/cpp/cpp_field.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_message_layout_helper.h>
#include <google/protobuf/compiler/cpp/cpp_options.h>
namespace google {
@@ -62,12 +63,10 @@ class ExtensionGenerator; // extension.h
class MessageGenerator {
public:
// See generator.cc for the meaning of dllexport_decl.
MessageGenerator(const Descriptor* descriptor, const Options& options,
SCCAnalyzer* scc_analyzer);
MessageGenerator(const Descriptor* descriptor, int index_in_file_messages,
const Options& options, SCCAnalyzer* scc_analyzer);
~MessageGenerator();
// Appends the pre-order walk of the nested generators to list.
void Flatten(std::vector<MessageGenerator*>* list);
// Append the two types of nested generators to the corresponding vector.
void AddGenerators(std::vector<EnumGenerator*>* enum_generators,
std::vector<ExtensionGenerator*>* extension_generators);
@@ -86,7 +85,7 @@ class MessageGenerator {
// Generate definitions of inline methods (placed at the end of the header
// file).
void GenerateInlineMethods(io::Printer* printer, bool is_inline);
void GenerateInlineMethods(io::Printer* printer);
// Dependent methods are always inline.
void GenerateDependentInlineMethods(io::Printer* printer);
@@ -96,18 +95,14 @@ class MessageGenerator {
// Generate extra fields
void GenerateExtraDefaultFields(io::Printer* printer);
// Generates code that allocates the message's default instance.
void GenerateDefaultInstanceAllocator(io::Printer* printer);
// Generates code that creates default instances for fields.
void GenerateFieldDefaultInstances(io::Printer* printer);
// Generates code that initializes the message's default instance. This
// is separate from allocating because all default instances must be
// allocated before any can be initialized.
void GenerateDefaultInstanceInitializer(io::Printer* printer);
// Generates code that should be run when ShutdownProtobufLibrary() is called,
// to delete all dynamically-allocated objects.
void GenerateShutdownCode(io::Printer* printer);
// Generate all non-inline methods for this class.
void GenerateClassMethods(io::Printer* printer);
@@ -117,7 +112,7 @@ class MessageGenerator {
void GenerateDependentFieldAccessorDeclarations(io::Printer* printer);
void GenerateFieldAccessorDeclarations(io::Printer* printer);
void GenerateDependentFieldAccessorDefinitions(io::Printer* printer);
void GenerateFieldAccessorDefinitions(io::Printer* printer, bool is_inline);
void GenerateFieldAccessorDefinitions(io::Printer* printer);
// Generate the table-driven parsing array. Returns the number of entries
// generated.
@@ -132,6 +127,9 @@ class MessageGenerator {
// of entries generated and the index of the first has_bit entry.
std::pair<size_t, size_t> GenerateOffsets(io::Printer* printer);
void GenerateSchema(io::Printer* printer, int offset, int has_offset);
// For each field generates a table entry describing the field for the
// table driven serializer.
int GenerateFieldMetadata(io::Printer* printer);
// Generate constructors and destructor.
void GenerateStructors(io::Printer* printer);
@@ -147,6 +145,13 @@ class MessageGenerator {
// Generate the arena-specific destructor code.
void GenerateArenaDestructorCode(io::Printer* printer);
// Helper for GenerateClear and others. Optionally emits a condition that
// assumes the existence of the cached_has_bits variable, and returns true if
// the condition was printed.
bool MaybeGenerateOptionalFieldCondition(io::Printer* printer,
const FieldDescriptor* field,
int expected_has_bits_index);
// Generate standard Message methods.
void GenerateClear(io::Printer* printer);
void GenerateOneofClear(io::Printer* printer);
@@ -179,13 +184,12 @@ class MessageGenerator {
io::Printer* printer, const Descriptor::ExtensionRange* range,
bool unbounded);
// Generates has_foo() functions and variables for singular field has-bits.
void GenerateSingularFieldHasBits(const FieldDescriptor* field,
std::map<string, string> vars,
io::Printer* printer);
// Generates has_foo() functions and variables for oneof field has-bits.
void GenerateOneofHasBits(io::Printer* printer, bool is_inline);
void GenerateOneofHasBits(io::Printer* printer);
// Generates has_foo_bar() functions for oneof members.
void GenerateOneofMemberHasBits(const FieldDescriptor* field,
const std::map<string, string>& vars,
@@ -193,6 +197,7 @@ class MessageGenerator {
// Generates the clear_foo() method for a field.
void GenerateFieldClear(const FieldDescriptor* field,
const std::map<string, string>& vars,
bool is_inline,
io::Printer* printer);
void GenerateConstructorBody(io::Printer* printer,
@@ -203,6 +208,7 @@ class MessageGenerator {
std::vector<uint32> RequiredFieldsBitMask() const;
const Descriptor* descriptor_;
int index_in_file_messages_;
string classname_;
Options options_;
FieldGeneratorMap field_generators_;
@@ -213,7 +219,6 @@ 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<MessageGenerator> > nested_generators_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<EnumGenerator> > enum_generators_;
google::protobuf::scoped_array<google::protobuf::scoped_ptr<ExtensionGenerator> > extension_generators_;
int num_required_fields_;
@@ -222,9 +227,10 @@ class MessageGenerator {
// table_driven_ indicates the generated message uses table-driven parsing.
bool table_driven_;
int index_in_file_messages_;
google::protobuf::scoped_ptr<MessageLayoutHelper> message_layout_helper_;
SCCAnalyzer* scc_analyzer_;
string scc_name_;
friend class FileGenerator;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator);
File diff suppressed because it is too large. Load diff
@@ -44,6 +44,8 @@ namespace protobuf {
namespace compiler {
namespace cpp {
bool IsImplicitWeakField(const FieldDescriptor* field, const Options& options);
class MessageFieldGenerator : public FieldGenerator {
public:
MessageFieldGenerator(const FieldDescriptor* descriptor,
@@ -55,8 +57,7 @@ class MessageFieldGenerator : public FieldGenerator {
void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMessageClearingCode(io::Printer* printer) const;
@@ -71,13 +72,9 @@ class MessageFieldGenerator : public FieldGenerator {
void GenerateByteSize(io::Printer* printer) const;
protected:
void GenerateArenaManipulationCode(const std::map<string, string>& variables,
io::Printer* printer) const;
virtual void GenerateGetterDeclaration(io::Printer* printer) const;
const FieldDescriptor* descriptor_;
const bool dependent_field_;
const bool implicit_weak_field_;
std::map<string, string> variables_;
private:
@@ -91,11 +88,9 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
~MessageOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const { }
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
// MessageFieldGenerator, from which we inherit, overrides this so we need to
@@ -105,9 +100,6 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
void GenerateDestructorCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
protected:
void GenerateGetterDeclaration(io::Printer* printer) const;
private:
void InternalGenerateInlineAccessorDefinitions(
const std::map<string, string>& variables, io::Printer* printer) const;
@@ -127,8 +119,7 @@ class RepeatedMessageFieldGenerator : public FieldGenerator {
void GenerateDependentAccessorDeclarations(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateDependentInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
@@ -29,40 +29,33 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: seongkim@google.com (Seong Beom Kim)
//
// protoc (Protocol Compiler) can generate more efficient code
// if it knows how a workload accesses fields of a message;
// e.g. some much more frequently than others.
//
// Protos defined here describe the access information per message
// and per field. Note that one can use any methods to collect
// the access patterns like CPU profiling, instrumented build, etc.
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
syntax = "proto2";
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__
package google.protobuf.compiler;
#include <google/protobuf/compiler/cpp/cpp_options.h>
#include <google/protobuf/descriptor.h>
// To convey the access pattern of a field, it classifies
// the type of the accessor methods into getters, setters and
// configs. Getters and setters read and write the field
// respectively and other operations like checking if the field
// exists are considered as configs.
message FieldAccessInfo {
optional string name = 1;
optional uint64 getters_count = 2;
optional uint64 setters_count = 3;
optional uint64 configs_count = 4;
}
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
// "count" correlates with how many samples an access info has
// for a message. High "count" means more confident optimization
// based on the info.
message MessageAccessInfo {
optional string name = 1;
optional uint64 count = 2;
repeated FieldAccessInfo field = 3;
}
// Provides an abstract interface to optimize message layout
// by rearranging the fields of a message.
class MessageLayoutHelper {
public:
virtual ~MessageLayoutHelper() {}
message AccessInfo {
repeated MessageAccessInfo message = 1;
}
virtual void OptimizeLayout(std::vector<const FieldDescriptor*>* fields,
const Options& options) = 0;
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__
@@ -0,0 +1,169 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/test_util.h>
#include <google/protobuf/unittest.pb.h>
#include <gtest/gtest.h>
#if LANG_CXX11
#include <google/protobuf/stubs/type_traits.h>
#endif
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
// Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
namespace cpp_unittest {
// Moves are enabled only when compiling with a C++11 compiler or newer.
#if LANG_CXX11
TEST(MovableMessageTest, MoveConstructor) {
protobuf_unittest::TestAllTypes message1;
TestUtil::SetAllFields(&message1);
const auto* nested = &message1.optional_nested_message();
protobuf_unittest::TestAllTypes message2(std::move(message1));
TestUtil::ExpectAllFieldsSet(message2);
// Check if the optional_nested_message was actually moved (and not just
// copied).
EXPECT_EQ(nested, &message2.optional_nested_message());
EXPECT_NE(nested, &message1.optional_nested_message());
}
TEST(MovableMessageTest, MoveAssignmentOperator) {
protobuf_unittest::TestAllTypes message1;
TestUtil::SetAllFields(&message1);
const auto* nested = &message1.optional_nested_message();
protobuf_unittest::TestAllTypes message2;
message2 = std::move(message1);
TestUtil::ExpectAllFieldsSet(message2);
// Check if the optional_nested_message was actually moved (and not just
// copied).
EXPECT_EQ(nested, &message2.optional_nested_message());
EXPECT_NE(nested, &message1.optional_nested_message());
}
TEST(MovableMessageTest, SelfMoveAssignment) {
// The `self` reference is necessary to defeat -Wself-move.
protobuf_unittest::TestAllTypes message, &self = message;
TestUtil::SetAllFields(&message);
message = std::move(self);
TestUtil::ExpectAllFieldsSet(message);
}
TEST(MovableMessageTest, MoveSameArena) {
Arena arena;
auto* message1_on_arena =
Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena);
TestUtil::SetAllFields(message1_on_arena);
const auto* nested = &message1_on_arena->optional_nested_message();
auto* message2_on_arena =
Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena);
// Moving messages on the same arena should lead to swapped pointers.
*message2_on_arena = std::move(*message1_on_arena);
EXPECT_EQ(nested, &message2_on_arena->optional_nested_message());
}
TEST(MovableMessageTest, MoveDifferentArenas) {
Arena arena1, arena2;
auto* message1_on_arena =
Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena1);
TestUtil::SetAllFields(message1_on_arena);
const auto* nested = &message1_on_arena->optional_nested_message();
auto* message2_on_arena =
Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena2);
// Moving messages on two different arenas should lead to a copy.
*message2_on_arena = std::move(*message1_on_arena);
EXPECT_NE(nested, &message2_on_arena->optional_nested_message());
TestUtil::ExpectAllFieldsSet(*message1_on_arena);
TestUtil::ExpectAllFieldsSet(*message2_on_arena);
}
TEST(MovableMessageTest, MoveFromArena) {
Arena arena;
auto* message1_on_arena =
Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena);
TestUtil::SetAllFields(message1_on_arena);
const auto* nested = &message1_on_arena->optional_nested_message();
protobuf_unittest::TestAllTypes message2;
// Moving from a message on the arena should lead to a copy.
message2 = std::move(*message1_on_arena);
EXPECT_NE(nested, &message2.optional_nested_message());
TestUtil::ExpectAllFieldsSet(*message1_on_arena);
TestUtil::ExpectAllFieldsSet(message2);
}
TEST(MovableMessageTest, MoveToArena) {
Arena arena;
protobuf_unittest::TestAllTypes message1;
TestUtil::SetAllFields(&message1);
const auto* nested = &message1.optional_nested_message();
auto* message2_on_arena =
Arena::CreateMessage<protobuf_unittest::TestAllTypes>(&arena);
// Moving to a message on the arena should lead to a copy.
*message2_on_arena = std::move(message1);
EXPECT_NE(nested, &message2_on_arena->optional_nested_message());
TestUtil::ExpectAllFieldsSet(message1);
TestUtil::ExpectAllFieldsSet(*message2_on_arena);
}
TEST(MovableMessageTest, Noexcept) {
EXPECT_TRUE(
std::is_nothrow_move_constructible<protobuf_unittest::TestAllTypes>());
EXPECT_TRUE(std::is_nothrow_move_assignable<protobuf_unittest::TestAllTypes>());
}
#endif // LANG_CXX11
} // namespace cpp_unittest
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -39,6 +39,8 @@
namespace google {
namespace protobuf {
namespace compiler {
class AccessInfoMap;
namespace cpp {
// Generator options (see generator.cc for a description of each):
@@ -49,7 +51,10 @@ struct Options {
transitive_pb_h(true),
annotate_headers(false),
enforce_lite(false),
table_driven_parsing(false) {}
table_driven_parsing(false),
table_driven_serialization(false),
lite_implicit_weak_fields(false),
access_info_map(NULL) {}
string dllexport_decl;
bool safe_boundary_check;
@@ -58,8 +63,11 @@ struct Options {
bool annotate_headers;
bool enforce_lite;
bool table_driven_parsing;
bool table_driven_serialization;
bool lite_implicit_weak_fields;
string annotation_pragma_name;
string annotation_guard_name;
const AccessInfoMap* access_info_map;
};
} // namespace cpp
@@ -0,0 +1,220 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h>
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
// FieldGroup is just a helper for PaddingOptimizer below. It holds a vector of
// fields that are grouped together because they have compatible alignment, and
// a preferred location in the final field ordering.
class FieldGroup {
public:
FieldGroup() : preferred_location_(0) {}
// A group with a single field.
FieldGroup(float preferred_location, const FieldDescriptor* field)
: preferred_location_(preferred_location), fields_(1, field) {}
// Append the fields in 'other' to this group.
void Append(const FieldGroup& other) {
if (other.fields_.empty()) {
return;
}
// Preferred location is the average among all the fields, so we weight by
// the number of fields on each FieldGroup object.
preferred_location_ = (preferred_location_ * fields_.size() +
(other.preferred_location_ * other.fields_.size())) /
(fields_.size() + other.fields_.size());
fields_.insert(fields_.end(), other.fields_.begin(), other.fields_.end());
}
void SetPreferredLocation(float location) { preferred_location_ = location; }
const std::vector<const FieldDescriptor*>& fields() const { return fields_; }
// FieldGroup objects sort by their preferred location.
bool operator<(const FieldGroup& other) const {
return preferred_location_ < other.preferred_location_;
}
private:
// "preferred_location_" is an estimate of where this group should go in the
// final list of fields. We compute this by taking the average index of each
// field in this group in the original ordering of fields. This is very
// approximate, but should put this group close to where its member fields
// originally went.
float preferred_location_;
std::vector<const FieldDescriptor*> fields_;
// We rely on the default copy constructor and operator= so this type can be
// used in a vector.
};
} // namespace
// Reorder 'fields' so that if the fields are output into a c++ class in the new
// order, fields of similar family (see below) are together and within each
// family, alignment padding is minimized.
//
// We try to do this while keeping each field as close as possible to its field
// number order so that we don't reduce cache locality much for function that
// access each field in order. Originally, OptimizePadding used declaration
// order for its decisions, but generated code minus the serializer/parsers uses
// the output of OptimizePadding as well (stored in
// MessageGenerator::optimized_order_). Since the serializers use field number
// order, we use that as a tie-breaker.
//
// We classify each field into a particular "family" of fields, that we perform
// the same operation on in our generated functions.
//
// REPEATED is placed first, as the C++ compiler automatically initializes
// these fields in layout order.
//
// STRING is grouped next, as our Clear/SharedCtor/SharedDtor walks it and
// calls ArenaStringPtr::Destroy on each.
//
//
// MESSAGE is grouped next, as our Clear/SharedDtor code walks it and calls
// delete on each. We initialize these fields with a NULL pointer (see
// MessageFieldGenerator::GenerateConstructorCode), which allows them to be
// memset.
//
// ZERO_INITIALIZABLE is memset in Clear/SharedCtor
//
// OTHER these fields are initialized one-by-one.
void PaddingOptimizer::OptimizeLayout(
std::vector<const FieldDescriptor*>* fields, const Options& options) {
// The sorted numeric order of Family determines the declaration order in the
// memory layout.
enum Family {
REPEATED = 0,
STRING = 1,
MESSAGE = 3,
ZERO_INITIALIZABLE = 4,
OTHER = 5,
kMaxFamily
};
// First divide fields into those that align to 1 byte, 4 bytes or 8 bytes.
std::vector<FieldGroup> aligned_to_1[kMaxFamily];
std::vector<FieldGroup> aligned_to_4[kMaxFamily];
std::vector<FieldGroup> aligned_to_8[kMaxFamily];
for (int i = 0; i < fields->size(); ++i) {
const FieldDescriptor* field = (*fields)[i];
Family f = OTHER;
if (field->is_repeated()) {
f = REPEATED;
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
f = STRING;
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
f = MESSAGE;
} else if (CanInitializeByZeroing(field)) {
f = ZERO_INITIALIZABLE;
}
const int j = field->number();
switch (EstimateAlignmentSize(field)) {
case 1:
aligned_to_1[f].push_back(FieldGroup(j, field));
break;
case 4:
aligned_to_4[f].push_back(FieldGroup(j, field));
break;
case 8:
aligned_to_8[f].push_back(FieldGroup(j, field));
break;
default:
GOOGLE_LOG(FATAL) << "Unknown alignment size " << EstimateAlignmentSize(field)
<< "for a field " << field->full_name() << ".";
}
}
// For each family, group fields to optimize padding.
for (int f = 0; f < kMaxFamily; f++) {
// Now group fields aligned to 1 byte into sets of 4, and treat those like a
// single field aligned to 4 bytes.
for (int i = 0; i < aligned_to_1[f].size(); i += 4) {
FieldGroup field_group;
for (int j = i; j < aligned_to_1[f].size() && j < i + 4; ++j) {
field_group.Append(aligned_to_1[f][j]);
}
aligned_to_4[f].push_back(field_group);
}
// Sort by preferred location to keep fields as close to their field number
// order as possible. Using stable_sort ensures that the output is
// consistent across runs.
std::stable_sort(aligned_to_4[f].begin(), aligned_to_4[f].end());
// Now group fields aligned to 4 bytes (or the 4-field groups created above)
// into pairs, and treat those like a single field aligned to 8 bytes.
for (int i = 0; i < aligned_to_4[f].size(); i += 2) {
FieldGroup field_group;
for (int j = i; j < aligned_to_4[f].size() && j < i + 2; ++j) {
field_group.Append(aligned_to_4[f][j]);
}
if (i == aligned_to_4[f].size() - 1) {
if (f == OTHER) {
// Move incomplete 4-byte block to the beginning. This is done to
// pair with the (possible) leftover blocks from the
// ZERO_INITIALIZABLE family.
field_group.SetPreferredLocation(-1);
} else {
// Move incomplete 4-byte block to the end.
field_group.SetPreferredLocation(fields->size() + 1);
}
}
aligned_to_8[f].push_back(field_group);
}
// Sort by preferred location.
std::stable_sort(aligned_to_8[f].begin(), aligned_to_8[f].end());
}
// Now pull out all the FieldDescriptors in order.
fields->clear();
for (int f = 0; f < kMaxFamily; ++f) {
for (int i = 0; i < aligned_to_8[f].size(); ++i) {
fields->insert(fields->end(), aligned_to_8[f][i].fields().begin(),
aligned_to_8[f][i].fields().end());
}
}
}
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
@@ -0,0 +1,64 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: seongkim@google.com (Seong Beom Kim)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__
#define GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__
#include <google/protobuf/compiler/cpp/cpp_message_layout_helper.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace cpp {
// Rearranges the fields of a message to minimize padding.
// Fields are grouped by the type and the size.
// For example, grouping four boolean fields and one int32
// field results in zero padding overhead. See OptimizeLayout's
// comment for details.
class PaddingOptimizer : public MessageLayoutHelper {
public:
PaddingOptimizer() {}
~PaddingOptimizer() {}
void OptimizeLayout(std::vector<const FieldDescriptor*>* fields,
const Options& options);
};
} // namespace cpp
} // namespace compiler
} // namespace protobuf
} // namespace google
#endif // GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__
@@ -132,7 +132,7 @@ class TestGenerator : public CodeGenerator {
// Check field accessors for a message inside oneof{}:
TryInsert("test.pb.h", "field_get:foo.Bar.oneOfMessage", context);
TryInsert("test.pb.h", "field_mutable:foo.Bar.oneOfMessage", context);
TryInsert("test.pb.h", "field_set_allocated:foo.Bar.oneOfMessage", context);
TryInsert("test.pb.cc", "field_set_allocated:foo.Bar.oneOfMessage", context);
// Check field accessors for an optional enum:
TryInsert("test.pb.h", "field_get:foo.Bar.optEnum", context);
@@ -115,21 +115,21 @@ GeneratePrivateMembers(io::Printer* printer) const {
void PrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_, "$deprecated_attr$$type$ $name$() const;\n");
printer->Annotate("name", descriptor_);
printer->Print(variables_,
"$deprecated_attr$$type$ $name$() const;\n"
"$deprecated_attr$void set_$name$($type$ value);\n");
"$deprecated_attr$void ${$set_$name$$}$($type$ value);\n");
printer->Annotate("{", "}", descriptor_);
}
void PrimitiveFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
"$inline$$type$ $classname$::$name$() const {\n"
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_;\n"
"}\n"
"$inline$void $classname$::set_$name$($type$ value) {\n"
"inline void $classname$::set_$name$($type$ value) {\n"
" $set_hasbit$\n"
" $name$_ = value;\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
@@ -148,7 +148,7 @@ GenerateMergingCode(io::Printer* printer) const {
void PrimitiveFieldGenerator::
GenerateSwappingCode(io::Printer* printer) const {
printer->Print(variables_, "std::swap($name$_, other->$name$_);\n");
printer->Print(variables_, "swap($name$_, other->$name$_);\n");
}
void PrimitiveFieldGenerator::
@@ -210,18 +210,16 @@ PrimitiveOneofFieldGenerator(const FieldDescriptor* descriptor,
PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {}
void PrimitiveOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
"$inline$$type$ $classname$::$name$() const {\n"
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" if (has_$name$()) {\n"
" return $oneof_prefix$$name$_;\n"
" }\n"
" return $default$;\n"
"}\n"
"$inline$void $classname$::set_$name$($type$ value) {\n"
"inline void $classname$::set_$name$($type$ value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -243,9 +241,8 @@ GenerateSwappingCode(io::Printer* printer) const {
void PrimitiveOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(
variables_,
"_$classname$_default_instance_.$name$_ = $default$;\n");
printer->Print(variables_,
"$ns$::_$classname$_default_instance_.$name$_ = $default$;\n");
}
void PrimitiveOneofFieldGenerator::
@@ -290,40 +287,46 @@ GeneratePrivateMembers(io::Printer* printer) const {
void RepeatedPrimitiveFieldGenerator::
GenerateAccessorDeclarations(io::Printer* printer) const {
printer->Print(variables_,
"$deprecated_attr$$type$ $name$(int index) const;\n"
"$deprecated_attr$void set_$name$(int index, $type$ value);\n"
"$deprecated_attr$void add_$name$($type$ value);\n");
"$deprecated_attr$$type$ $name$(int index) const;\n");
printer->Annotate("name", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$void ${$set_$name$$}$(int index, $type$ value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$const ::google::protobuf::RepeatedField< $type$ >&\n"
" $name$() const;\n"
"$deprecated_attr$::google::protobuf::RepeatedField< $type$ >*\n"
" mutable_$name$();\n");
"$deprecated_attr$void ${$add_$name$$}$($type$ value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$const ::google::protobuf::RepeatedField< $type$ >&\n"
" $name$() const;\n");
printer->Annotate("name", descriptor_);
printer->Print(variables_,
"$deprecated_attr$::google::protobuf::RepeatedField< $type$ >*\n"
" ${$mutable_$name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
}
void RepeatedPrimitiveFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer, bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
"$inline$$type$ $classname$::$name$(int index) const {\n"
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
printer->Print(variables_,
"inline $type$ $classname$::$name$(int index) const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get(index);\n"
"}\n"
"$inline$void $classname$::set_$name$(int index, $type$ value) {\n"
"inline void $classname$::set_$name$(int index, $type$ value) {\n"
" $name$_.Set(index, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"$inline$void $classname$::add_$name$($type$ value) {\n"
"inline void $classname$::add_$name$($type$ value) {\n"
" $name$_.Add(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n");
printer->Print(variables,
"$inline$const ::google::protobuf::RepeatedField< $type$ >&\n"
"}\n"
"inline const ::google::protobuf::RepeatedField< $type$ >&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
"$inline$::google::protobuf::RepeatedField< $type$ >*\n"
"inline ::google::protobuf::RepeatedField< $type$ >*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -382,7 +385,8 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
"$number$, "
"::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, "
"output);\n"
" output->WriteVarint32(_$name$_cached_byte_size_);\n");
" output->WriteVarint32(static_cast< ::google::protobuf::uint32>(\n"
" _$name$_cached_byte_size_));\n");
if (FixedSize(descriptor_->type()) > 0) {
// TODO(ckennelly): Use RepeatedField<T>::unsafe_data() via
@@ -422,7 +426,8 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
" ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,\n"
" target);\n"
" target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(\n"
" _$name$_cached_byte_size_, target);\n"
" static_cast< ::google::protobuf::int32>(\n"
" _$name$_cached_byte_size_), target);\n"
" target = ::google::protobuf::internal::WireFormatLite::\n"
" Write$declared_type$NoTagToArray(this->$name$_, target);\n"
"}\n");
@@ -444,7 +449,7 @@ GenerateByteSize(io::Printer* printer) const {
" $declared_type$Size(this->$name$_);\n");
} else {
printer->Print(variables_,
"unsigned int count = this->$name$_size();\n"
"unsigned int count = static_cast<unsigned int>(this->$name$_size());\n"
"size_t data_size = $fixed_size$UL * count;\n");
}
@@ -452,7 +457,8 @@ GenerateByteSize(io::Printer* printer) const {
printer->Print(variables_,
"if (data_size > 0) {\n"
" total_size += $tag_size$ +\n"
" ::google::protobuf::internal::WireFormatLite::Int32Size(data_size);\n"
" ::google::protobuf::internal::WireFormatLite::Int32Size(\n"
" static_cast< ::google::protobuf::int32>(data_size));\n"
"}\n"
"int cached_size = ::google::protobuf::internal::ToCachedSize(data_size);\n"
"GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
@@ -53,8 +53,7 @@ class PrimitiveFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
@@ -80,8 +79,7 @@ class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator {
~PrimitiveOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
void GenerateConstructorCode(io::Printer* printer) const;
@@ -100,8 +98,7 @@ class RepeatedPrimitiveFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
@@ -58,8 +58,8 @@ void SetStringVariables(const FieldDescriptor* descriptor,
(*variables)["default_variable"] =
descriptor->default_value_string().empty()
? "&::google::protobuf::internal::GetEmptyStringAlreadyInited()"
: "&" + (*variables)["classname"] + "::" + default_variable_string +
".get()";
: "&" + Namespace(descriptor) + "::" + (*variables)["classname"] +
"::" + default_variable_string + ".get()";
(*variables)["pointer_type"] =
descriptor->type() == FieldDescriptor::TYPE_BYTES ? "void" : "char";
(*variables)["null_check"] = "GOOGLE_DCHECK(value != NULL);\n";
@@ -71,6 +71,9 @@ void SetStringVariables(const FieldDescriptor* descriptor,
(*variables)["full_name"] = descriptor->full_name();
(*variables)["string_piece"] = "::std::string";
(*variables)["lite"] =
HasDescriptorMethods(descriptor->file(), options) ? "" : "Lite";
}
} // namespace
@@ -79,7 +82,8 @@ void SetStringVariables(const FieldDescriptor* descriptor,
StringFieldGenerator::StringFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: FieldGenerator(options), descriptor_(descriptor) {
: FieldGenerator(options), descriptor_(descriptor),
lite_(!HasDescriptorMethods(descriptor->file(), options)) {
SetStringVariables(descriptor, &variables_, options);
}
@@ -142,30 +146,54 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
printer->Print(variables_,
"$deprecated_attr$const ::std::string& $name$() const;\n"
"$deprecated_attr$void set_$name$(const ::std::string& value);\n");
if (!SupportsArenas(descriptor_)) {
printer->Print(variables_,
"#if LANG_CXX11\n"
"$deprecated_attr$void set_$name$(::std::string&& value);\n"
"#endif\n");
}
"$deprecated_attr$const ::std::string& $name$() const;\n");
printer->Annotate("name", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$void ${$set_$name$$}$(const ::std::string& value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$void set_$name$(const char* value);\n"
"$deprecated_attr$void set_$name$(const $pointer_type$* value, size_t size)"
";\n"
"$deprecated_attr$::std::string* mutable_$name$();\n"
"$deprecated_attr$::std::string* $release_name$();\n"
"$deprecated_attr$void set_allocated_$name$(::std::string* $name$);\n");
if (SupportsArenas(descriptor_)) {
printer->Print(variables_,
"$deprecated_attr$::std::string* unsafe_arena_release_$name$();\n"
"$deprecated_attr$void unsafe_arena_set_allocated_$name$(\n"
" ::std::string* $name$);\n");
}
"#if LANG_CXX11\n"
"$deprecated_attr$void ${$set_$name$$}$(::std::string&& value);\n"
"#endif\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$void ${$set_$name$$}$(const char* value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$void ${$set_$name$$}$(const $pointer_type$* "
"value, size_t size)"
";\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$::std::string* ${$mutable_$name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_, "$deprecated_attr$::std::string* $release_name$();\n");
printer->Annotate("release_name", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$void ${$set_allocated_$name$$}$(::std::string* $name$);\n");
printer->Annotate("{", "}", descriptor_);
if (SupportsArenas(descriptor_)) {
printer->Print(
variables_,
"PROTOBUF_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors for\"\n"
"\" string fields are deprecated and will be removed in a\"\n"
"\" future release.\")\n"
"::std::string* ${$unsafe_arena_release_$name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"PROTOBUF_RUNTIME_DEPRECATED(\"The unsafe_arena_ accessors for\"\n"
"\" string fields are deprecated and will be removed in a\"\n"
"\" future release.\")\n"
"void ${$unsafe_arena_set_allocated_$name$$}$(\n"
" ::std::string* $name$);\n");
printer->Annotate("{", "}", descriptor_);
}
if (unknown_ctype) {
printer->Outdent();
@@ -175,57 +203,54 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
void StringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(
variables,
"$inline$const ::std::string& $classname$::$name$() const {\n"
variables_,
"inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.Get();\n"
"}\n"
"$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.Set($default_variable$, value, GetArenaNoVirtual());\n"
" $name$_.Set$lite$($default_variable$, value, GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"$inline$void $classname$::set_$name$(const char* value) {\n"
"#if LANG_CXX11\n"
"inline void $classname$::set_$name$(::std::string&& value) {\n"
" $set_hasbit$\n"
" $name$_.Set$lite$(\n"
" $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" $null_check$"
" $set_hasbit$\n"
" $name$_.Set($default_variable$, $string_piece$(value),\n"
" $name$_.Set$lite$($default_variable$, $string_piece$(value),\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
"$inline$"
"inline "
"void $classname$::set_$name$(const $pointer_type$* value,\n"
" size_t size) {\n"
" $set_hasbit$\n"
" $name$_.Set($default_variable$, $string_piece$(\n"
" $name$_.Set$lite$($default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size), "
"GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"$inline$::std::string* $classname$::mutable_$name$() {\n"
"inline ::std::string* $classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable($default_variable$, GetArenaNoVirtual());\n"
"}\n"
"$inline$::std::string* $classname$::$release_name$() {\n"
"inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" $clear_hasbit$\n"
" return $name$_.Release($default_variable$, GetArenaNoVirtual());\n"
"}\n"
"$inline$::std::string* $classname$::unsafe_arena_release_$name$() {\n"
" // "
"@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" $clear_hasbit$\n"
" return $name$_.UnsafeArenaRelease($default_variable$,\n"
" GetArenaNoVirtual());\n"
"}\n"
"$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$ != NULL) {\n"
" $set_hasbit$\n"
" } else {\n"
@@ -235,7 +260,15 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n"
"$inline$void $classname$::unsafe_arena_set_allocated_$name$(\n"
"inline ::std::string* $classname$::unsafe_arena_release_$name$() {\n"
" // "
"@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" $clear_hasbit$\n"
" return $name$_.UnsafeArenaRelease($default_variable$,\n"
" GetArenaNoVirtual());\n"
"}\n"
"inline void $classname$::unsafe_arena_set_allocated_$name$(\n"
" ::std::string* $name$) {\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if ($name$ != NULL) {\n"
@@ -251,31 +284,31 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
} else {
// No-arena case.
printer->Print(
variables,
"$inline$const ::std::string& $classname$::$name$() const {\n"
variables_,
"inline const ::std::string& $classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_get:$full_name$)\n"
" return $name$_.GetNoArena();\n"
"}\n"
"$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, value);\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
"$inline$void $classname$::set_$name$(::std::string&& value) {\n"
"inline void $classname$::set_$name$(::std::string&& value) {\n"
" $set_hasbit$\n"
" $name$_.SetNoArena(\n"
" $default_variable$, ::std::move(value));\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
"$inline$void $classname$::set_$name$(const char* value) {\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" $null_check$"
" $set_hasbit$\n"
" $name$_.SetNoArena($default_variable$, $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
"$inline$"
"inline "
"void $classname$::set_$name$(const $pointer_type$* value, "
"size_t size) {\n"
" $set_hasbit$\n"
@@ -283,17 +316,17 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $string_piece$(reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"$inline$::std::string* $classname$::mutable_$name$() {\n"
"inline ::std::string* $classname$::mutable_$name$() {\n"
" $set_hasbit$\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.MutableNoArena($default_variable$);\n"
"}\n"
"$inline$::std::string* $classname$::$release_name$() {\n"
"inline ::std::string* $classname$::$release_name$() {\n"
" // @@protoc_insertion_point(field_release:$full_name$)\n"
" $clear_hasbit$\n"
" return $name$_.ReleaseNoArena($default_variable$);\n"
"}\n"
"$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if ($name$ != NULL) {\n"
" $set_hasbit$\n"
" } else {\n"
@@ -426,7 +459,7 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
if (SupportsArenas(descriptor_) || descriptor_->containing_oneof() != NULL) {
// TODO(gpike): improve this
printer->Print(variables_,
"$name$_.Set($default_variable$, from.$name$(),\n"
"$name$_.Set$lite$($default_variable$, from.$name$(),\n"
" GetArenaNoVirtual());\n");
} else {
printer->Print(variables_,
@@ -439,32 +472,21 @@ GenerateCopyConstructorCode(io::Printer* printer) const {
void StringFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
// The variable |arena| is defined by the enclosing code.
// See MessageGenerator::GenerateSharedDestructorCode.
printer->Print(variables_,
"$name$_.Destroy($default_variable$, arena);\n");
} else {
printer->Print(variables_,
"$name$_.DestroyNoArena($default_variable$);\n");
}
printer->Print(variables_,
"$name$_.DestroyNoArena($default_variable$);\n");
}
void StringFieldGenerator::
GenerateDefaultInstanceAllocator(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
printer->Print(variables_,
"$classname$::$default_variable_name$.DefaultConstruct();\n"
"*$classname$::$default_variable_name$.get_mutable() = "
"::std::string($default$, $default_length$);\n");
}
}
void StringFieldGenerator::
GenerateShutdownCode(io::Printer* printer) const {
if (!descriptor_->default_value_string().empty()) {
printer->Print(variables_,
"$classname$::$default_variable_name$.Shutdown();\n");
printer->Print(
variables_,
"$ns$::$classname$::$default_variable_name$.DefaultConstruct();\n"
"*$ns$::$classname$::$default_variable_name$.get_mutable() = "
"::std::string($default$, $default_length$);\n"
"::google::protobuf::internal::OnShutdownDestroyString(\n"
" $ns$::$classname$::$default_variable_name$.get_mutable());\n"
);
}
}
@@ -477,7 +499,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, true, variables_,
"this->$name$().data(), this->$name$().length(),\n", printer);
"this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
printer);
}
}
@@ -486,7 +509,8 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, false, variables_,
"this->$name$().data(), this->$name$().length(),\n", printer);
"this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
printer);
}
printer->Print(variables_,
"::google::protobuf::internal::WireFormatLite::Write$declared_type$MaybeAliased(\n"
@@ -498,7 +522,8 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, false, variables_,
"this->$name$().data(), this->$name$().length(),\n", printer);
"this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
printer);
}
printer->Print(variables_,
"target =\n"
@@ -527,42 +552,52 @@ StringOneofFieldGenerator(const FieldDescriptor* descriptor,
StringOneofFieldGenerator::~StringOneofFieldGenerator() {}
void StringOneofFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(
variables,
"$inline$const ::std::string& $classname$::$name$() const {\n"
variables_,
"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"
" }\n"
" return *$default_variable$;\n"
"}\n"
"$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.Set($default_variable$, value,\n"
" $oneof_prefix$$name$_.Set$lite$($default_variable$, value,\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"$inline$void $classname$::set_$name$(const char* value) {\n"
"#if LANG_CXX11\n"
"inline void $classname$::set_$name$(::std::string&& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.Set$lite$(\n"
" $default_variable$, ::std::move(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" $null_check$"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.Set($default_variable$,\n"
" $oneof_prefix$$name$_.Set$lite$($default_variable$,\n"
" $string_piece$(value), GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
"$inline$"
"inline "
"void $classname$::set_$name$(const $pointer_type$* value,\n"
" size_t size) {\n"
" if (!has_$name$()) {\n"
@@ -570,12 +605,13 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" set_has_$name$();\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
" $oneof_prefix$$name$_.Set($default_variable$, $string_piece$(\n"
" $oneof_prefix$$name$_.Set$lite$(\n"
" $default_variable$, $string_piece$(\n"
" reinterpret_cast<const char*>(value), size),\n"
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"$inline$::std::string* $classname$::mutable_$name$() {\n"
"inline ::std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -585,7 +621,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" GetArenaNoVirtual());\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
"}\n"
"$inline$::std::string* $classname$::$release_name$() {\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"
@@ -595,19 +631,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" return NULL;\n"
" }\n"
"}\n"
"$inline$::std::string* $classname$::unsafe_arena_release_$name$() {\n"
" // "
"@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
" return $oneof_prefix$$name$_.UnsafeArenaRelease(\n"
" $default_variable$, GetArenaNoVirtual());\n"
" } else {\n"
" return NULL;\n"
" }\n"
"}\n"
"$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
@@ -619,7 +643,19 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" }\n"
" // @@protoc_insertion_point(field_set_allocated:$full_name$)\n"
"}\n"
"$inline$void $classname$::unsafe_arena_set_allocated_$name$("
"inline ::std::string* $classname$::unsafe_arena_release_$name$() {\n"
" // "
"@@protoc_insertion_point(field_unsafe_arena_release:$full_name$)\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (has_$name$()) {\n"
" clear_has_$oneof_name$();\n"
" return $oneof_prefix$$name$_.UnsafeArenaRelease(\n"
" $default_variable$, GetArenaNoVirtual());\n"
" } else {\n"
" return NULL;\n"
" }\n"
"}\n"
"inline void $classname$::unsafe_arena_set_allocated_$name$("
"::std::string* $name$) {\n"
" GOOGLE_DCHECK(GetArenaNoVirtual() != NULL);\n"
" if (!has_$name$()) {\n"
@@ -637,15 +673,15 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
} else {
// No-arena case.
printer->Print(
variables,
"$inline$const ::std::string& $classname$::$name$() const {\n"
variables_,
"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"
" }\n"
" return *$default_variable$;\n"
"}\n"
"$inline$void $classname$::set_$name$(const ::std::string& value) {\n"
"inline void $classname$::set_$name$(const ::std::string& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -656,7 +692,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" // @@protoc_insertion_point(field_set:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
"$inline$void $classname$::set_$name$(::std::string&& value) {\n"
"inline void $classname$::set_$name$(::std::string&& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -668,7 +704,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" // @@protoc_insertion_point(field_set_rvalue:$full_name$)\n"
"}\n"
"#endif\n"
"$inline$void $classname$::set_$name$(const char* value) {\n"
"inline void $classname$::set_$name$(const char* value) {\n"
" $null_check$"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
@@ -679,7 +715,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" $string_piece$(value));\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
"$inline$"
"inline "
"void $classname$::set_$name$(const $pointer_type$* value, size_t "
"size) {\n"
" if (!has_$name$()) {\n"
@@ -692,7 +728,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" reinterpret_cast<const char*>(value), size));\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"$inline$::std::string* $classname$::mutable_$name$() {\n"
"inline ::std::string* $classname$::mutable_$name$() {\n"
" if (!has_$name$()) {\n"
" clear_$oneof_name$();\n"
" set_has_$name$();\n"
@@ -701,7 +737,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $oneof_prefix$$name$_.MutableNoArena($default_variable$);\n"
"}\n"
"$inline$::std::string* $classname$::$release_name$() {\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"
@@ -710,7 +746,7 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
" return NULL;\n"
" }\n"
"}\n"
"$inline$void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
"inline void $classname$::set_allocated_$name$(::std::string* $name$) {\n"
" if (!has_$name$()) {\n"
" $oneof_prefix$$name$_.UnsafeSetDefault($default_variable$);\n"
" }\n"
@@ -727,29 +763,13 @@ GenerateInlineAccessorDefinitions(io::Printer* printer,
void StringOneofFieldGenerator::
GenerateClearingCode(io::Printer* printer) const {
std::map<string, string> variables(variables_);
if (dependent_field_) {
variables["this_message"] = DependentBaseDownCast();
// This clearing code may be in the dependent base class. If the default
// value is an empty string, then the $default_variable$ is a global
// singleton. If the default is not empty, we need to down-cast to get the
// default value's global singleton instance. See SetStringVariables() for
// possible values of default_variable.
if (!descriptor_->default_value_string().empty()) {
variables["default_variable"] = "&" + DependentBaseDownCast() +
variables["default_variable_name"] +
".get()";
}
} else {
variables["this_message"] = "";
}
if (SupportsArenas(descriptor_)) {
printer->Print(variables,
"$this_message$$oneof_prefix$$name$_.Destroy($default_variable$,\n"
" $this_message$GetArenaNoVirtual());\n");
printer->Print(variables_,
"$oneof_prefix$$name$_.Destroy($default_variable$,\n"
" GetArenaNoVirtual());\n");
} else {
printer->Print(variables,
"$this_message$$oneof_prefix$$name$_."
printer->Print(variables_,
"$oneof_prefix$$name$_."
"DestroyNoArena($default_variable$);\n");
}
}
@@ -768,24 +788,16 @@ void StringOneofFieldGenerator::
GenerateConstructorCode(io::Printer* printer) const {
printer->Print(
variables_,
"_$classname$_default_instance_.$name$_.UnsafeSetDefault(\n"
"$ns$::_$classname$_default_instance_.$name$_.UnsafeSetDefault(\n"
" $default_variable$);\n");
}
void StringOneofFieldGenerator::
GenerateDestructorCode(io::Printer* printer) const {
if (SupportsArenas(descriptor_)) {
printer->Print(variables_,
"if (has_$name$()) {\n"
" $oneof_prefix$$name$_.Destroy($default_variable$,\n"
" GetArenaNoVirtual());\n"
"}\n");
} else {
printer->Print(variables_,
"if (has_$name$()) {\n"
" $oneof_prefix$$name$_.DestroyNoArena($default_variable$);\n"
"}\n");
}
printer->Print(variables_,
"if (has_$name$()) {\n"
" $oneof_prefix$$name$_.DestroyNoArena($default_variable$);\n"
"}\n");
}
void StringOneofFieldGenerator::
@@ -797,7 +809,8 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, true, variables_,
"this->$name$().data(), this->$name$().length(),\n", printer);
"this->$name$().data(), static_cast<int>(this->$name$().length()),\n",
printer);
}
}
@@ -833,28 +846,62 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
printer->Print(variables_,
"$deprecated_attr$const ::std::string& $name$(int index) const;\n"
"$deprecated_attr$::std::string* mutable_$name$(int index);\n"
"$deprecated_attr$void set_$name$(int index, const ::std::string& value);\n"
"#if LANG_CXX11\n"
"$deprecated_attr$void set_$name$(int index, ::std::string&& value);\n"
"#endif\n"
"$deprecated_attr$void set_$name$(int index, const char* value);\n"
""
"$deprecated_attr$void set_$name$("
"int index, const $pointer_type$* value, size_t size);\n"
"$deprecated_attr$::std::string* add_$name$();\n"
"$deprecated_attr$void add_$name$(const ::std::string& value);\n"
"#if LANG_CXX11\n"
"$deprecated_attr$void add_$name$(::std::string&& value);\n"
"#endif\n"
"$deprecated_attr$void add_$name$(const char* value);\n"
"$deprecated_attr$void add_$name$(const $pointer_type$* value, size_t size)"
";\n"
"$deprecated_attr$const ::google::protobuf::RepeatedPtrField< ::std::string>& $name$() "
"const;\n"
"$deprecated_attr$::google::protobuf::RepeatedPtrField< ::std::string>* mutable_$name$()"
"$deprecated_attr$const ::std::string& $name$(int index) const;\n");
printer->Annotate("name", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$::std::string* ${$mutable_$name$$}$(int index);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$void ${$set_$name$$}$(int index, const "
"::std::string& value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"#if LANG_CXX11\n"
"$deprecated_attr$void ${$set_$name$$}$(int index, ::std::string&& value);\n"
"#endif\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$void ${$set_$name$$}$(int index, const "
"char* value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
""
"$deprecated_attr$void ${$set_$name$$}$("
"int index, const $pointer_type$* value, size_t size);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$::std::string* ${$add_$name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$void ${$add_$name$$}$(const ::std::string& value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"#if LANG_CXX11\n"
"$deprecated_attr$void ${$add_$name$$}$(::std::string&& value);\n"
"#endif\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$void ${$add_$name$$}$(const char* value);\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"$deprecated_attr$void ${$add_$name$$}$(const $pointer_type$* "
"value, size_t size)"
";\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"$deprecated_attr$const ::google::protobuf::RepeatedPtrField< ::std::string>& $name$() "
"const;\n");
printer->Annotate("name", descriptor_);
printer->Print(variables_,
"$deprecated_attr$::google::protobuf::RepeatedPtrField< ::std::string>* "
"${$mutable_$name$$}$()"
";\n");
printer->Annotate("{", "}", descriptor_);
if (unknown_ctype) {
printer->Outdent();
@@ -864,71 +911,68 @@ GenerateAccessorDeclarations(io::Printer* printer) const {
}
void RepeatedStringFieldGenerator::
GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const {
std::map<string, string> variables(variables_);
variables["inline"] = is_inline ? "inline " : "";
printer->Print(variables,
"$inline$const ::std::string& $classname$::$name$(int index) const {\n"
GenerateInlineAccessorDefinitions(io::Printer* printer) const {
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"
"inline ::std::string* $classname$::mutable_$name$(int index) {\n"
" // @@protoc_insertion_point(field_mutable:$full_name$)\n"
" return $name$_.Mutable(index);\n"
"}\n"
"$inline$void $classname$::set_$name$(int index, const ::std::string& value) {\n"
"inline void $classname$::set_$name$(int index, const ::std::string& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" $name$_.Mutable(index)->assign(value);\n"
"}\n"
"#if LANG_CXX11\n"
"$inline$void $classname$::set_$name$(int index, ::std::string&& value) {\n"
"inline void $classname$::set_$name$(int index, ::std::string&& value) {\n"
" // @@protoc_insertion_point(field_set:$full_name$)\n"
" $name$_.Mutable(index)->assign(std::move(value));\n"
"}\n"
"#endif\n"
"$inline$void $classname$::set_$name$(int index, const char* value) {\n"
"inline void $classname$::set_$name$(int index, const char* value) {\n"
" $null_check$"
" $name$_.Mutable(index)->assign(value);\n"
" // @@protoc_insertion_point(field_set_char:$full_name$)\n"
"}\n"
"$inline$void "
"inline void "
"$classname$::set_$name$"
"(int index, const $pointer_type$* value, size_t size) {\n"
" $name$_.Mutable(index)->assign(\n"
" reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_set_pointer:$full_name$)\n"
"}\n"
"$inline$::std::string* $classname$::add_$name$() {\n"
"inline ::std::string* $classname$::add_$name$() {\n"
" // @@protoc_insertion_point(field_add_mutable:$full_name$)\n"
" return $name$_.Add();\n"
"}\n"
"$inline$void $classname$::add_$name$(const ::std::string& value) {\n"
"inline void $classname$::add_$name$(const ::std::string& value) {\n"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n"
"#if LANG_CXX11\n"
"$inline$void $classname$::add_$name$(::std::string&& value) {\n"
"inline void $classname$::add_$name$(::std::string&& value) {\n"
" $name$_.Add(std::move(value));\n"
" // @@protoc_insertion_point(field_add:$full_name$)\n"
"}\n"
"#endif\n"
"$inline$void $classname$::add_$name$(const char* value) {\n"
"inline void $classname$::add_$name$(const char* value) {\n"
" $null_check$"
" $name$_.Add()->assign(value);\n"
" // @@protoc_insertion_point(field_add_char:$full_name$)\n"
"}\n"
"$inline$void "
"inline void "
"$classname$::add_$name$(const $pointer_type$* value, size_t size) {\n"
" $name$_.Add()->assign(reinterpret_cast<const char*>(value), size);\n"
" // @@protoc_insertion_point(field_add_pointer:$full_name$)\n"
"}\n"
"$inline$const ::google::protobuf::RepeatedPtrField< ::std::string>&\n"
"inline const ::google::protobuf::RepeatedPtrField< ::std::string>&\n"
"$classname$::$name$() const {\n"
" // @@protoc_insertion_point(field_list:$full_name$)\n"
" return $name$_;\n"
"}\n"
"$inline$::google::protobuf::RepeatedPtrField< ::std::string>*\n"
"inline ::google::protobuf::RepeatedPtrField< ::std::string>*\n"
"$classname$::mutable_$name$() {\n"
" // @@protoc_insertion_point(field_mutable_list:$full_name$)\n"
" return &$name$_;\n"
@@ -969,7 +1013,7 @@ GenerateMergeFromCodedStream(io::Printer* printer) const {
GenerateUtf8CheckCodeForString(
descriptor_, options_, true, variables_,
"this->$name$(this->$name$_size() - 1).data(),\n"
"this->$name$(this->$name$_size() - 1).length(),\n",
"static_cast<int>(this->$name$(this->$name$_size() - 1).length()),\n",
printer);
}
}
@@ -982,7 +1026,8 @@ GenerateSerializeWithCachedSizes(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, false, variables_,
"this->$name$(i).data(), this->$name$(i).length(),\n", printer);
"this->$name$(i).data(), static_cast<int>(this->$name$(i).length()),\n",
printer);
}
printer->Outdent();
printer->Print(variables_,
@@ -999,7 +1044,8 @@ GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const {
if (descriptor_->type() == FieldDescriptor::TYPE_STRING) {
GenerateUtf8CheckCodeForString(
descriptor_, options_, false, variables_,
"this->$name$(i).data(), this->$name$(i).length(),\n", printer);
"this->$name$(i).data(), static_cast<int>(this->$name$(i).length()),\n",
printer);
}
printer->Outdent();
printer->Print(variables_,
@@ -54,8 +54,7 @@ class StringFieldGenerator : public FieldGenerator {
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateStaticMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateNonInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMessageClearingCode(io::Printer* printer) const;
@@ -65,7 +64,6 @@ class StringFieldGenerator : public FieldGenerator {
void GenerateCopyConstructorCode(io::Printer* printer) const;
void GenerateDestructorCode(io::Printer* printer) const;
void GenerateDefaultInstanceAllocator(io::Printer* printer) const;
void GenerateShutdownCode(io::Printer* printer) const;
void GenerateMergeFromCodedStream(io::Printer* printer) const;
void GenerateSerializeWithCachedSizes(io::Printer* printer) const;
void GenerateSerializeWithCachedSizesToArray(io::Printer* printer) const;
@@ -74,6 +72,7 @@ class StringFieldGenerator : public FieldGenerator {
protected:
const FieldDescriptor* descriptor_;
std::map<string, string> variables_;
const bool lite_;
private:
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringFieldGenerator);
@@ -86,8 +85,7 @@ class StringOneofFieldGenerator : public StringFieldGenerator {
~StringOneofFieldGenerator();
// implements FieldGenerator ---------------------------------------
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
// StringFieldGenerator, from which we inherit, overrides this so we need to
@@ -112,8 +110,7 @@ class RepeatedStringFieldGenerator : public FieldGenerator {
// implements FieldGenerator ---------------------------------------
void GeneratePrivateMembers(io::Printer* printer) const;
void GenerateAccessorDeclarations(io::Printer* printer) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer,
bool is_inline) const;
void GenerateInlineAccessorDefinitions(io::Printer* printer) const;
void GenerateClearingCode(io::Printer* printer) const;
void GenerateMergingCode(io::Printer* printer) const;
void GenerateSwappingCode(io::Printer* printer) const;
@@ -151,6 +151,10 @@ enum ConflictingEnum { // NO_PROTO3
message DummyMessage {}
// Message names that could conflict.
message Shutdown {}
message TableStruct {}
service TestConflictingMethodNames {
rpc Closure(DummyMessage) returns (DummyMessage);
}
@@ -576,12 +576,73 @@ TEST(GeneratedMessageTest, SwapWithOther) {
EXPECT_EQ(unittest::TestAllTypes::BAR, message2.repeated_nested_enum(1));
}
TEST(GeneratedMessageTest, CopyConstructor) {
unittest::TestAllTypes message1;
TEST(GeneratedMessageTest, ADLSwap) {
unittest::TestAllTypes message1, message2;
TestUtil::SetAllFields(&message1);
unittest::TestAllTypes message2(message1);
// Note the address of one of the repeated fields, to verify it was swapped
// rather than copied.
const int32* addr = &message1.repeated_int32().Get(0);
using std::swap;
swap(message1, message2);
TestUtil::ExpectAllFieldsSet(message2);
TestUtil::ExpectClear(message1);
EXPECT_EQ(addr, &message2.repeated_int32().Get(0));
}
TEST(GeneratedMessageTest, CopyConstructor) {
// All set.
{
unittest::TestAllTypes message1;
TestUtil::SetAllFields(&message1);
unittest::TestAllTypes message2(message1);
TestUtil::ExpectAllFieldsSet(message2);
}
// None set.
{
unittest::TestAllTypes message1;
unittest::TestAllTypes message2(message1);
EXPECT_FALSE(message1.has_optional_string());
EXPECT_FALSE(message2.has_optional_string());
EXPECT_EQ(&message1.optional_string(),
&message2.optional_string());
EXPECT_FALSE(message1.has_optional_bytes());
EXPECT_FALSE(message2.has_optional_bytes());
EXPECT_EQ(&message1.optional_bytes(),
&message2.optional_bytes());
EXPECT_FALSE(message1.has_optional_nested_message());
EXPECT_FALSE(message2.has_optional_nested_message());
EXPECT_EQ(&message1.optional_nested_message(),
&message2.optional_nested_message());
EXPECT_FALSE(message1.has_optional_foreign_message());
EXPECT_FALSE(message2.has_optional_foreign_message());
EXPECT_EQ(&message1.optional_foreign_message(),
&message2.optional_foreign_message());
EXPECT_FALSE(message1.has_optional_import_message());
EXPECT_FALSE(message2.has_optional_import_message());
EXPECT_EQ(&message1.optional_import_message(),
&message2.optional_import_message());
EXPECT_FALSE(message1.has_optional_public_import_message());
EXPECT_FALSE(message2.has_optional_public_import_message());
EXPECT_EQ(&message1.optional_public_import_message(),
&message2.optional_public_import_message());
EXPECT_FALSE(message1.has_optional_lazy_message());
EXPECT_FALSE(message2.has_optional_lazy_message());
EXPECT_EQ(&message1.optional_lazy_message(),
&message2.optional_lazy_message());
}
}
TEST(GeneratedMessageTest, CopyConstructorWithArenas) {
@@ -683,21 +744,6 @@ TEST(GeneratedMessageTest, NonEmptyMergeFrom) {
TestUtil::ExpectAllFieldsSet(message1);
}
#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || \
!defined(GOOGLE_PROTOBUF_NO_RTTI)
#ifdef PROTOBUF_HAS_DEATH_TEST
#ifndef NDEBUG
TEST(GeneratedMessageTest, MergeFromSelf) {
unittest::TestAllTypes message;
EXPECT_DEATH(message.MergeFrom(message), "pb[.]cc.*Check failed:");
EXPECT_DEATH(message.MergeFrom(implicit_cast<const Message&>(message)),
"pb[.]cc.*Check failed:");
}
#endif // NDEBUG
#endif // PROTOBUF_HAS_DEATH_TEST
#endif // !PROTOBUF_TEST_NO_DESCRIPTORS || !GOOGLE_PROTOBUF_NO_RTTI
// Test the generated SerializeWithCachedSizesToArray(),
TEST(GeneratedMessageTest, SerializationToArray) {
@@ -1340,7 +1386,7 @@ class GeneratedServiceTest : public testing::Test {
foo_(descriptor_->FindMethodByName("Foo")),
bar_(descriptor_->FindMethodByName("Bar")),
stub_(&mock_channel_),
done_(NewPermanentCallback(&DoNothing)) {}
done_(::google::protobuf::NewPermanentCallback(&DoNothing)) {}
virtual void SetUp() {
ASSERT_TRUE(foo_ != NULL);
@@ -35,10 +35,8 @@
#include <google/protobuf/compiler/cpp/cpp_helpers.h>
#include <google/protobuf/compiler/cpp/cpp_generator.h>
#include <google/protobuf/compiler/annotation_test_util.h>
#include <google/protobuf/compiler/command_line_interface.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/testing/file.h>
@@ -47,37 +45,15 @@
#include <gtest/gtest.h>
namespace google {
namespace atu = ::google::protobuf::compiler::annotation_test_util;
namespace protobuf {
namespace compiler {
namespace cpp {
namespace {
// A CodeGenerator that captures the FileDescriptor it's passed as a
// FileDescriptorProto.
class DescriptorCapturingGenerator : public CodeGenerator {
public:
// Does not own file; file must outlive the Generator.
explicit DescriptorCapturingGenerator(FileDescriptorProto* file)
: file_(file) {}
virtual bool Generate(const FileDescriptor* file, const string& parameter,
GeneratorContext* context, string* error) const {
file->CopyTo(file_);
return true;
}
private:
FileDescriptorProto* file_;
};
class CppMetadataTest : public ::testing::Test {
public:
// Adds a file with name `filename` and content `data`.
void AddFile(const string& filename, const string& data) {
GOOGLE_CHECK_OK(File::SetContents(TestTempDir() + "/" + filename, data,
true));
}
// Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output
// code from the previously added file with name `filename`. Returns true on
// success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to
@@ -87,26 +63,21 @@ class CppMetadataTest : public ::testing::Test {
string* proto_h, GeneratedCodeInfo* proto_h_info,
string* pb_cc) {
google::protobuf::compiler::CommandLineInterface cli;
cli.SetInputsAreProtoPathRelative(true);
CppGenerator cpp_generator;
DescriptorCapturingGenerator capturing_generator(file);
cli.RegisterGenerator("--cpp_out", &cpp_generator, "");
cli.RegisterGenerator("--capture_out", &capturing_generator, "");
string proto_path = "-I" + TestTempDir();
string cpp_out =
"--cpp_out=annotate_headers=true,"
"annotation_pragma_name=pragma_name,"
"annotation_guard_name=guard_name:" +
TestTempDir();
string capture_out = "--capture_out=" + TestTempDir();
const char* argv[] = {"protoc", proto_path.c_str(), cpp_out.c_str(),
capture_out.c_str(), filename.c_str()};
const bool result =
atu::CaptureMetadata(filename, cpp_out,
/* meta_file_suffix */ "", &cli, file,
/* outputs */ NULL);
if (cli.Run(5, argv) != 0) {
return false;
if (!result) {
return result;
}
string output_base = TestTempDir() + "/" + StripProto(filename);
@@ -119,7 +90,7 @@ class CppMetadataTest : public ::testing::Test {
if (pb_h != NULL && pb_h_info != NULL) {
GOOGLE_CHECK_OK(
File::GetContents(output_base + ".pb.h", pb_h, true));
if (!DecodeMetadata(output_base + ".pb.h.meta", pb_h_info)) {
if (!atu::DecodeMetadata(output_base + ".pb.h.meta", pb_h_info)) {
return false;
}
}
@@ -127,23 +98,13 @@ class CppMetadataTest : public ::testing::Test {
if (proto_h != NULL && proto_h_info != NULL) {
GOOGLE_CHECK_OK(File::GetContents(output_base + ".proto.h", proto_h,
true));
if (!DecodeMetadata(output_base + ".proto.h.meta", proto_h_info)) {
if (!atu::DecodeMetadata(output_base + ".proto.h.meta", proto_h_info)) {
return false;
}
}
return true;
}
private:
// Decodes GeneratedCodeInfo stored in path and copies it to info.
// Returns true on success.
bool DecodeMetadata(const string& path, GeneratedCodeInfo* info) {
string data;
GOOGLE_CHECK_OK(File::GetContents(path, &data, true));
io::ArrayInputStream input(data.data(), data.size());
return info->ParseFromZeroCopyStream(&input);
}
};
const char kSmallTestFile[] =
@@ -152,48 +113,11 @@ const char kSmallTestFile[] =
"enum Enum { VALUE = 0; }\n"
"message Message { }\n";
// Finds the Annotation for a given source file and path (or returns null if it
// couldn't).
const GeneratedCodeInfo::Annotation* FindAnnotationOnPath(
const GeneratedCodeInfo& info, const string& source_file,
const std::vector<int>& path) {
for (int i = 0; i < info.annotation_size(); ++i) {
const GeneratedCodeInfo::Annotation* annotation = &info.annotation(i);
if (annotation->source_file() != source_file ||
annotation->path_size() != path.size()) {
continue;
}
int node = 0;
for (; node < path.size(); ++node) {
if (annotation->path(node) != path[node]) {
break;
}
}
if (node == path.size()) {
return annotation;
}
}
return NULL;
}
// Returns true if the provided annotation covers a given substring in
// file_content.
bool AnnotationMatchesSubstring(const string& file_content,
const GeneratedCodeInfo::Annotation* annotation,
const string& expected_text) {
uint32 begin = annotation->begin();
uint32 end = annotation->end();
if (end < begin || end > file_content.size()) {
return false;
}
return file_content.substr(begin, end - begin) == expected_text;
}
TEST_F(CppMetadataTest, CapturesEnumNames) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
AddFile("test.proto", kSmallTestFile);
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_EQ("Enum", file.enum_type(0).name());
@@ -201,16 +125,16 @@ TEST_F(CppMetadataTest, CapturesEnumNames) {
enum_path.push_back(FileDescriptorProto::kEnumTypeFieldNumber);
enum_path.push_back(0);
const GeneratedCodeInfo::Annotation* enum_annotation =
FindAnnotationOnPath(info, "test.proto", enum_path);
atu::FindAnnotationOnPath(info, "test.proto", enum_path);
EXPECT_TRUE(NULL != enum_annotation);
EXPECT_TRUE(AnnotationMatchesSubstring(pb_h, enum_annotation, "Enum"));
EXPECT_TRUE(atu::AnnotationMatchesSubstring(pb_h, enum_annotation, "Enum"));
}
TEST_F(CppMetadataTest, AddsPragma) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
AddFile("test.proto", kSmallTestFile);
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_TRUE(pb_h.find("#ifdef guard_name") != string::npos);
@@ -222,7 +146,7 @@ TEST_F(CppMetadataTest, CapturesMessageNames) {
FileDescriptorProto file;
GeneratedCodeInfo info;
string pb_h;
AddFile("test.proto", kSmallTestFile);
atu::AddFile("test.proto", kSmallTestFile);
EXPECT_TRUE(
CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL));
EXPECT_EQ("Message", file.message_type(0).name());
@@ -230,9 +154,10 @@ TEST_F(CppMetadataTest, CapturesMessageNames) {
message_path.push_back(FileDescriptorProto::kMessageTypeFieldNumber);
message_path.push_back(0);
const GeneratedCodeInfo::Annotation* message_annotation =
FindAnnotationOnPath(info, "test.proto", message_path);
atu::FindAnnotationOnPath(info, "test.proto", message_path);
EXPECT_TRUE(NULL != message_annotation);
EXPECT_TRUE(AnnotationMatchesSubstring(pb_h, message_annotation, "Message"));
EXPECT_TRUE(
atu::AnnotationMatchesSubstring(pb_h, message_annotation, "Message"));
}
} // namespace
@@ -134,6 +134,14 @@ class GenerateAndTest {
};
TEST(CsharpBootstrapTest, GeneratedCsharpDescriptorMatches) {
// Skip this whole test if the csharp directory doesn't exist (i.e., a C++11
// only distribution).
string descriptor_file_name =
"../csharp/src/Google.Protobuf/Reflection/Descriptor.cs";
if (!File::Exists(TestSourceDir() + "/" + descriptor_file_name)) {
return;
}
MockErrorCollector error_collector;
DiskSourceTree source_tree;
Importer importer(&source_tree, &error_collector);
@@ -176,11 +184,6 @@ TEST(CsharpBootstrapTest, GeneratedCsharpDescriptorMatches) {
"../csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs");
generate_test.SetParameter("");
source_tree.MapPath("", TestSourceDir() + "/../examples");
generate_test.Run(importer.Import("addressbook.proto"),
"Addressbook.cs",
"../csharp/src/AddressBook/Addressbook.cs");
source_tree.MapPath("", TestSourceDir() + "/../conformance");
generate_test.Run(importer.Import("conformance.proto"),
"Conformance.cs",
@@ -89,6 +89,10 @@ EnumOneofFieldGenerator::EnumOneofFieldGenerator(
EnumOneofFieldGenerator::~EnumOneofFieldGenerator() {
}
void EnumOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
printer->Print(variables_, "$property_name$ = other.$property_name$;\n");
}
void EnumOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) {
// TODO(jonskeet): What about if we read the default value?
printer->Print(
@@ -64,6 +64,7 @@ class EnumOneofFieldGenerator : public PrimitiveOneofFieldGenerator {
const Options *options);
~EnumOneofFieldGenerator();
virtual void GenerateMergingCode(io::Printer* printer);
virtual void GenerateParsingCode(io::Printer* printer);
virtual void GenerateSerializationCode(io::Printer* printer);
virtual void GenerateSerializedSizeCode(io::Printer* printer);
@@ -54,7 +54,7 @@ namespace compiler {
namespace csharp {
void FieldGeneratorBase::SetCommonFieldVariables(
map<string, string>* variables) {
std::map<string, string>* variables) {
// Note: this will be valid even though the tag emitted for packed and unpacked versions of
// repeated fields varies by wire format. The wire format is encoded in the bottom 3 bits, which
// never effects the tag size.
@@ -92,7 +92,7 @@ void FieldGeneratorBase::SetCommonFieldVariables(
}
void FieldGeneratorBase::SetCommonOneofFieldVariables(
map<string, string>* variables) {
std::map<string, string>* variables) {
(*variables)["oneof_name"] = oneof_name();
(*variables)["has_property_check"] =
oneof_name() + "Case_ == " + oneof_property_name() +
@@ -322,9 +322,9 @@ std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor)
}
case FieldDescriptor::TYPE_DOUBLE: {
double value = descriptor->default_value_double();
if (value == numeric_limits<double>::infinity()) {
if (value == std::numeric_limits<double>::infinity()) {
return "double.PositiveInfinity";
} else if (value == -numeric_limits<double>::infinity()) {
} else if (value == -std::numeric_limits<double>::infinity()) {
return "double.NegativeInfinity";
} else if (MathLimits<double>::IsNaN(value)) {
return "double.NaN";
@@ -333,9 +333,9 @@ std::string FieldGeneratorBase::default_value(const FieldDescriptor* descriptor)
}
case FieldDescriptor::TYPE_FLOAT: {
float value = descriptor->default_value_float();
if (value == numeric_limits<float>::infinity()) {
if (value == std::numeric_limits<float>::infinity()) {
return "float.PositiveInfinity";
} else if (value == -numeric_limits<float>::infinity()) {
} else if (value == -std::numeric_limits<float>::infinity()) {
return "float.NegativeInfinity";
} else if (MathLimits<float>::IsNaN(value)) {
return "float.NaN";
@@ -66,14 +66,14 @@ class FieldGeneratorBase : public SourceGeneratorBase {
protected:
const FieldDescriptor* descriptor_;
const int fieldOrdinal_;
map<string, string> variables_;
std::map<string, string> variables_;
void AddDeprecatedFlag(io::Printer* printer);
void AddNullCheck(io::Printer* printer);
void AddNullCheck(io::Printer* printer, const std::string& name);
void AddPublicMemberAttributes(io::Printer* printer);
void SetCommonOneofFieldVariables(map<string, string>* variables);
void SetCommonOneofFieldVariables(std::map<string, string>* variables);
std::string oneof_property_name();
std::string oneof_name();
@@ -89,7 +89,7 @@ class FieldGeneratorBase : public SourceGeneratorBase {
std::string capitalized_type_name();
private:
void SetCommonFieldVariables(map<string, string>* variables);
void SetCommonFieldVariables(std::map<string, string>* variables);
std::string GetStringDefaultValueInternal();
std::string GetBytesDefaultValueInternal();
@@ -105,7 +105,7 @@ void MessageGenerator::AddDeprecatedFlag(io::Printer* printer) {
}
void MessageGenerator::Generate(io::Printer* printer) {
map<string, string> vars;
std::map<string, string> vars;
vars["class_name"] = class_name();
vars["access_level"] = class_access_level();
@@ -280,7 +280,7 @@ bool MessageGenerator::HasNestedGeneratedTypes()
}
void MessageGenerator::GenerateCloningCode(io::Printer* printer) {
map<string, string> vars;
std::map<string, string> vars;
WriteGeneratedCodeAttributes(printer);
vars["class_name"] = class_name();
printer->Print(
@@ -333,7 +333,7 @@ void MessageGenerator::GenerateFreezingCode(io::Printer* printer) {
}
void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) {
map<string, string> vars;
std::map<string, string> vars;
vars["class_name"] = class_name();
// Equality
@@ -432,7 +432,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
// Note: These are separate from GenerateMessageSerializationMethods()
// because they need to be generated even for messages that are optimized
// for code size.
map<string, string> vars;
std::map<string, string> vars;
vars["class_name"] = class_name();
WriteGeneratedCodeAttributes(printer);
@@ -463,9 +463,12 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) {
vars["field_property_name"] = GetPropertyName(field);
printer->Print(
vars,
"case $property_name$OneofCase.$field_property_name$:\n"
" $field_property_name$ = other.$field_property_name$;\n"
" break;\n");
"case $property_name$OneofCase.$field_property_name$:\n");
printer->Indent();
scoped_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field));
generator->GenerateMergingCode(printer);
printer->Print("break;\n");
printer->Outdent();
}
printer->Outdent();
printer->Print("}\n\n");
@@ -171,6 +171,14 @@ void MessageOneofFieldGenerator::GenerateMembers(io::Printer* printer) {
"}\n");
}
void MessageOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
printer->Print(variables_,
"if ($property_name$ == null) {\n"
" $property_name$ = new $type_name$();\n"
"}\n"
"$property_name$.MergeFrom(other.$property_name$);\n");
}
void MessageOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) {
// TODO(jonskeet): We may be able to do better than this
printer->Print(
@@ -74,6 +74,7 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator {
virtual void GenerateCloningCode(io::Printer* printer);
virtual void GenerateMembers(io::Printer* printer);
virtual void GenerateMergingCode(io::Printer* printer);
virtual void WriteToString(io::Printer* printer);
virtual void GenerateParsingCode(io::Printer* printer);
@@ -196,6 +196,10 @@ void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) {
"}\n");
}
void PrimitiveOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
printer->Print(variables_, "$property_name$ = other.$property_name$;\n");
}
void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) {
printer->Print(variables_,
"PrintField(\"$descriptor_name$\", $has_property_check$, $oneof_name$_, writer);\n");
@@ -78,6 +78,7 @@ class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator {
virtual void GenerateCloningCode(io::Printer* printer);
virtual void GenerateMembers(io::Printer* printer);
virtual void GenerateMergingCode(io::Printer* printer);
virtual void WriteToString(io::Printer* printer);
virtual void GenerateParsingCode(io::Printer* printer);
@@ -181,6 +181,10 @@ void WrapperOneofFieldGenerator::GenerateMembers(io::Printer* printer) {
"}\n");
}
void WrapperOneofFieldGenerator::GenerateMergingCode(io::Printer* printer) {
printer->Print(variables_, "$property_name$ = other.$property_name$;\n");
}
void WrapperOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) {
printer->Print(
variables_,
@@ -75,6 +75,7 @@ class WrapperOneofFieldGenerator : public WrapperFieldGenerator {
~WrapperOneofFieldGenerator();
virtual void GenerateMembers(io::Printer* printer);
virtual void GenerateMergingCode(io::Printer* printer);
virtual void GenerateParsingCode(io::Printer* printer);
virtual void GenerateSerializationCode(io::Printer* printer);
virtual void GenerateSerializedSizeCode(io::Printer* printer);
@@ -32,8 +32,9 @@
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
#ifdef _MSC_VER
#include <io.h>
#include <direct.h>
#else
#include <unistd.h>
#endif
@@ -54,16 +55,21 @@
#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
#include <ctype.h>
#endif
namespace google {
namespace protobuf {
namespace compiler {
#ifdef _WIN32
#ifndef F_OK
#define F_OK 00 // not defined by MSVC for whatever reason
#endif
#include <ctype.h>
// DO NOT include <io.h>, instead create functions in io_win32.{h,cc} and import
// them like we do below.
using google::protobuf::internal::win32::access;
using google::protobuf::internal::win32::open;
#endif
// Returns true if the text looks like a Windows-style absolute path, starting
@@ -295,10 +301,8 @@ static string CanonicalizePath(string path) {
}
static inline bool ContainsParentReference(const string& path) {
return path == ".." ||
HasPrefixString(path, "../") ||
HasSuffixString(path, "/..") ||
path.find("/../") != string::npos;
return path == ".." || HasPrefixString(path, "../") ||
HasSuffixString(path, "/..") || path.find("/../") != string::npos;
}
// Maps a file from an old location to a new one. Typically, old_prefix is
@@ -328,8 +332,7 @@ static bool ApplyMapping(const string& filename,
// We do not allow the file name to use "..".
return false;
}
if (HasPrefixString(filename, "/") ||
IsWindowsAbsolutePath(filename)) {
if (HasPrefixString(filename, "/") || IsWindowsAbsolutePath(filename)) {
// This is an absolute path, so it isn't matched by the empty string.
return false;
}
@@ -50,7 +50,7 @@ Context::Context(const FileDescriptor* file, const Options& options)
Context::~Context() {
}
ClassNameResolver* Context::GetNameResolver() {
ClassNameResolver* Context::GetNameResolver() const {
return name_resolver_.get();
}
@@ -154,7 +154,7 @@ void Context::InitializeFieldGeneratorInfoForFields(
for (int i = 0; i < fields.size(); ++i) {
const FieldDescriptor* field = fields[i];
FieldGeneratorInfo info;
info.name = UnderscoresToCamelCase(field);
info.name = CamelCaseFieldName(field);
info.capitalized_name = UnderscoresToCapitalizedCamelCase(field);
// For fields conflicting with some other fields, we append the field
// number to their field names in generated code to avoid conflicts.
@@ -70,7 +70,7 @@ class Context {
// Get the name resolver associated with this context. The resolver
// can be used to map descriptors to Java class names.
ClassNameResolver* GetNameResolver();
ClassNameResolver* GetNameResolver() const;
// Get the FieldGeneratorInfo for a given field.
const FieldGeneratorInfo* GetFieldGeneratorInfo(
@@ -109,14 +109,16 @@ void EnumGenerator::Generate(io::Printer* printer) {
printer->Print(vars,
"$name$($index$, $number$),\n");
}
printer->Annotate("name", canonical_values_[i]);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
if (ordinal_is_index) {
printer->Print("UNRECOGNIZED(-1),\n");
printer->Print("${$UNRECOGNIZED$}$(-1),\n", "{", "", "}", "");
} else {
printer->Print("UNRECOGNIZED(-1, -1),\n");
printer->Print("${$UNRECOGNIZED$}$(-1, -1),\n", "{", "", "}", "");
}
printer->Annotate("{", "}", descriptor_);
}
printer->Print(
@@ -133,15 +135,19 @@ void EnumGenerator::Generate(io::Printer* printer) {
WriteEnumValueDocComment(printer, aliases_[i].value);
printer->Print(vars,
"public static final $classname$ $name$ = $canonical_name$;\n");
printer->Annotate("name", aliases_[i].value);
}
for (int i = 0; i < descriptor_->value_count(); i++) {
std::map<string, string> vars;
vars["name"] = descriptor_->value(i)->name();
vars["number"] = SimpleItoa(descriptor_->value(i)->number());
vars["{"] = "";
vars["}"] = "";
WriteEnumValueDocComment(printer, descriptor_->value(i));
printer->Print(vars,
"public static final int $name$_VALUE = $number$;\n");
"public static final int ${$$name$_VALUE$}$ = $number$;\n");
printer->Annotate("{", "}", descriptor_->value(i));
}
printer->Print("\n");
@@ -183,23 +183,26 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value() {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" $type$ result = $type$.$for_number$($name$_);\n"
" return result == null ? $unknown$ : result;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumFieldGenerator::
@@ -209,33 +212,38 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value() {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Value(int value) {\n"
"$deprecation$public Builder "
"${$set$capitalized_name$Value$}$(int value) {\n"
" $name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" $type$ result = $type$.$for_number$($name$_);\n"
" return result == null ? $unknown$ : result;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" if (value == null) {\n"
" throw new NullPointerException();\n"
" }\n"
@@ -244,14 +252,16 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $clear_has_field_bit_builder$\n"
" $name$_ = $default_number$;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumFieldGenerator::
@@ -311,12 +321,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
"if (value == null) {\n");
if (PreserveUnknownFields(descriptor_->containing_type())) {
printer->Print(variables_,
" unknownFields.mergeVarintField($number$, rawValue);\n");
}
printer->Print(variables_,
"if (value == null) {\n"
" unknownFields.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" $set_has_field_bit_message$\n"
" $name$_ = rawValue;\n"
@@ -386,23 +392,25 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value() {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return (java.lang.Integer) $oneof_name$_;\n"
" }\n"
" return $default_number$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $type$ result = $type$.$for_number$(\n"
" (java.lang.Integer) $oneof_name$_);\n"
@@ -410,6 +418,7 @@ GenerateMembers(io::Printer* printer) const {
" }\n"
" return $default$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumOneofFieldGenerator::
@@ -417,31 +426,35 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value() {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ((java.lang.Integer) $oneof_name$_).intValue();\n"
" }\n"
" return $default_number$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Value(int value) {\n"
"$deprecation$public Builder "
"${$set$capitalized_name$Value$}$(int value) {\n"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $type$ result = $type$.$for_number$(\n"
" (java.lang.Integer) $oneof_name$_);\n"
@@ -449,9 +462,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return $default$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" if (value == null) {\n"
" throw new NullPointerException();\n"
" }\n"
@@ -460,9 +474,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
" $oneof_name$_ = null;\n"
@@ -470,6 +485,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumOneofFieldGenerator::
@@ -502,12 +518,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
"if (value == null) {\n");
if (PreserveUnknownFields(descriptor_->containing_type())) {
printer->Print(variables_,
" unknownFields.mergeVarintField($number$, rawValue);\n");
}
printer->Print(variables_,
"if (value == null) {\n"
" unknownFields.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = rawValue;\n"
@@ -621,32 +633,38 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return new com.google.protobuf.Internal.ListAdapter<\n"
" java.lang.Integer, $type$>($name$_, $name$_converter_);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_converter_.convert($name$_.get(index));\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<java.lang.Integer>\n"
"get$capitalized_name$ValueList() {\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value(int index) {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (descriptor_->is_packed() &&
@@ -684,23 +702,27 @@ GenerateBuilderMembers(io::Printer* printer) const {
// could hold on to the returned list and modify it after the message
// has been built, thus mutating the message which is supposed to be
// immutable.
"$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return new com.google.protobuf.Internal.ListAdapter<\n"
" java.lang.Integer, $type$>($name$_, $name$_converter_);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_converter_.convert($name$_.get(index));\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -710,9 +732,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
" if (value == null) {\n"
" throw new NullPointerException();\n"
" }\n"
@@ -721,9 +744,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $type$> values) {\n"
" ensure$capitalized_name$IsMutable();\n"
" for ($type$ value : values) {\n"
@@ -732,47 +756,54 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $name$_ = java.util.Collections.emptyList();\n"
" $clear_mutable_bit_builder$;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<java.lang.Integer>\n"
"get$capitalized_name$ValueList() {\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return java.util.Collections.unmodifiableList($name$_);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value(int index) {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Value(\n"
"$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n"
" int index, int value) {\n"
" ensure$capitalized_name$IsMutable();\n"
" $name$_.set(index, value);\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$Value(int value) {\n"
"$deprecation$public Builder "
"${$add$capitalized_name$Value$}$(int value) {\n"
" ensure$capitalized_name$IsMutable();\n"
" $name$_.add(value);\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$Value(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n"
" java.lang.Iterable<java.lang.Integer> values) {\n"
" ensure$capitalized_name$IsMutable();\n"
" for (int value : values) {\n"
@@ -781,6 +812,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
}
@@ -848,12 +880,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.$for_number$(rawValue);\n"
"if (value == null) {\n");
if (PreserveUnknownFields(descriptor_->containing_type())) {
printer->Print(variables_,
" unknownFields.mergeVarintField($number$, rawValue);\n");
}
printer->Print(variables_,
"if (value == null) {\n"
" unknownFields.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" if (!$get_mutable_bit_parser$) {\n"
" $name$_ = new java.util.ArrayList<java.lang.Integer>();\n"
@@ -165,23 +165,26 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value() {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" $type$ result = $type$.forNumber($name$_);\n"
" return result == null ? $unknown$ : result;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Generate private setters for the builder to proxy into.
if (SupportUnknownEnumValue(descriptor_->file())) {
@@ -214,43 +217,50 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value() {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return instance.get$capitalized_name$Value();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Value(int value) {\n"
"$deprecation$public Builder "
"${$set$capitalized_name$Value$}$(int value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Value(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumFieldLiteGenerator::
@@ -296,12 +306,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.forNumber(rawValue);\n"
"if (value == null) {\n");
if (PreserveUnknownFields(descriptor_->containing_type())) {
printer->Print(variables_,
" super.mergeVarintField($number$, rawValue);\n");
}
printer->Print(variables_,
"if (value == null) {\n"
" super.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" $set_has_field_bit_message$\n"
" $name$_ = rawValue;\n"
@@ -372,29 +378,32 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value() {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return (java.lang.Integer) $oneof_name$_;\n"
" }\n"
" return $default_number$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $type$ result = $type$.forNumber((java.lang.Integer) $oneof_name$_);\n"
" return result == null ? $unknown$ : result;\n"
" }\n"
" return $default$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Generate private setters for the builder to proxy into.
if (SupportUnknownEnumValue(descriptor_->file())) {
@@ -430,43 +439,50 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value() {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$() {\n"
" return instance.get$capitalized_name$Value();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Value(int value) {\n"
"$deprecation$public Builder "
"${$set$capitalized_name$Value$}$(int value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Value(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableEnumOneofFieldLiteGenerator::
@@ -487,12 +503,8 @@ GenerateParsingCode(io::Printer* printer) const {
printer->Print(variables_,
"int rawValue = input.readEnum();\n"
"$type$ value = $type$.forNumber(rawValue);\n"
"if (value == null) {\n");
if (PreserveUnknownFields(descriptor_->containing_type())) {
printer->Print(variables_,
" super.mergeVarintField($number$, rawValue);\n");
}
printer->Print(variables_,
"if (value == null) {\n"
" super.mergeVarintField($number$, rawValue);\n"
"} else {\n"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = rawValue;\n"
@@ -607,35 +619,41 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return new com.google.protobuf.Internal.ListAdapter<\n"
" java.lang.Integer, $type$>($name$_, $name$_converter_);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_converter_.convert($name$_.getInt(index));\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<java.lang.Integer>\n"
"get$capitalized_name$ValueList() {\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value(int index) {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return $name$_.getInt(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
if (descriptor_->options().packed() &&
if (descriptor_->is_packed() &&
context_->HasGeneratedMethods(descriptor_->containing_type())) {
printer->Print(variables_,
"private int $name$MemoizedSerializedSize;\n");
@@ -714,85 +732,99 @@ void RepeatedImmutableEnumFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return instance.get$capitalized_name$List();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\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_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $type$> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$(values);"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<java.lang.Integer>\n"
"get$capitalized_name$ValueList() {\n"
"${$get$capitalized_name$ValueList$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
" instance.get$capitalized_name$ValueList());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Value(int index) {\n"
"$deprecation$public int ${$get$capitalized_name$Value$}$(int index) {\n"
" return instance.get$capitalized_name$Value(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Value(\n"
"$deprecation$public Builder ${$set$capitalized_name$Value$}$(\n"
" int index, int value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Value(index, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$Value(int value) {\n"
"$deprecation$public Builder "
"${$add$capitalized_name$Value$}$(int value) {\n"
" instance.add$capitalized_name$Value(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$Value(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$Value$}$(\n"
" java.lang.Iterable<java.lang.Integer> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$Value(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
}
@@ -889,7 +921,7 @@ GenerateParsingDoneCode(io::Printer* printer) const {
void RepeatedImmutableEnumFieldLiteGenerator::
GenerateSerializationCode(io::Printer* printer) const {
if (descriptor_->options().packed()) {
if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (get$capitalized_name$List().size() > 0) {\n"
" output.writeUInt32NoTag($tag$);\n"
@@ -920,7 +952,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
"}\n");
printer->Print(
"size += dataSize;\n");
if (descriptor_->options().packed()) {
if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (!get$capitalized_name$List().isEmpty()) {"
" size += $tag_size$;\n"
@@ -933,7 +965,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
}
// cache the data size for packed fields.
if (descriptor_->options().packed()) {
if (descriptor_->is_packed()) {
printer->Print(variables_,
"$name$MemoizedSerializedSize = dataSize;\n");
}
@@ -93,10 +93,12 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
}
printer->Print(vars,
"$name$($number$),\n");
printer->Annotate("name", canonical_values_[i]);
}
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print("UNRECOGNIZED(-1),\n");
printer->Print("${$UNRECOGNIZED$}$(-1),\n", "{", "", "}", "");
printer->Annotate("{", "}", descriptor_);
}
printer->Print(
@@ -113,15 +115,19 @@ void EnumLiteGenerator::Generate(io::Printer* printer) {
WriteEnumValueDocComment(printer, aliases_[i].value);
printer->Print(vars,
"public static final $classname$ $name$ = $canonical_name$;\n");
printer->Annotate("name", aliases_[i].value);
}
for (int i = 0; i < descriptor_->value_count(); i++) {
std::map<string, string> vars;
vars["name"] = descriptor_->value(i)->name();
vars["number"] = SimpleItoa(descriptor_->value(i)->number());
vars["{"] = "";
vars["}"] = "";
WriteEnumValueDocComment(printer, descriptor_->value(i));
printer->Print(vars,
"public static final int $name$_VALUE = $number$;\n");
"public static final int ${$$name$_VALUE$}$ = $number$;\n");
printer->Annotate("{", "}", descriptor_->value(i));
}
printer->Print("\n");
@@ -75,7 +75,7 @@ void ExtensionGenerator::InitTemplateVars(
vars["default"] = descriptor->is_repeated() ?
"" : DefaultValue(descriptor, immutable, name_resolver);
vars["type_constant"] = FieldTypeName(GetType(descriptor));
vars["packed"] = descriptor->options().packed() ? "true" : "false";
vars["packed"] = descriptor->is_packed() ? "true" : "false";
vars["enum_map"] = "null";
vars["prototype"] = "null";
@@ -45,8 +45,6 @@
#include <google/protobuf/compiler/java/java_enum_field.h>
#include <google/protobuf/compiler/java/java_enum_field_lite.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_lazy_message_field.h>
#include <google/protobuf/compiler/java/java_lazy_message_field_lite.h>
#include <google/protobuf/compiler/java/java_map_field.h>
#include <google/protobuf/compiler/java/java_map_field_lite.h>
#include <google/protobuf/compiler/java/java_message_field.h>
@@ -77,13 +75,8 @@ ImmutableFieldGenerator* MakeImmutableGenerator(
return new ImmutableMapFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
if (IsLazy(field, context->EnforceLite())) {
return new RepeatedImmutableLazyMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new RepeatedImmutableMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
return new RepeatedImmutableMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
case JAVATYPE_ENUM:
return new RepeatedImmutableEnumFieldGenerator(
@@ -99,13 +92,8 @@ ImmutableFieldGenerator* MakeImmutableGenerator(
if (field->containing_oneof()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsLazy(field, context->EnforceLite())) {
return new ImmutableLazyMessageOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new ImmutableMessageOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
return new ImmutableMessageOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumOneofFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
@@ -119,13 +107,8 @@ ImmutableFieldGenerator* MakeImmutableGenerator(
} else {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsLazy(field, context->EnforceLite())) {
return new ImmutableLazyMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new ImmutableMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
}
return new ImmutableMessageFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumFieldGenerator(
field, messageBitIndex, builderBitIndex, context);
@@ -150,13 +133,8 @@ ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator(
return new ImmutableMapFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
if (IsLazy(field, context->EnforceLite())) {
return new RepeatedImmutableLazyMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new RepeatedImmutableMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
return new RepeatedImmutableMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
case JAVATYPE_ENUM:
return new RepeatedImmutableEnumFieldLiteGenerator(
@@ -172,13 +150,8 @@ ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator(
if (field->containing_oneof()) {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsLazy(field, context->EnforceLite())) {
return new ImmutableLazyMessageOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new ImmutableMessageOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
return new ImmutableMessageOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumOneofFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
@@ -192,13 +165,8 @@ ImmutableFieldLiteGenerator* MakeImmutableLiteGenerator(
} else {
switch (GetJavaType(field)) {
case JAVATYPE_MESSAGE:
if (IsLazy(field, context->EnforceLite())) {
return new ImmutableLazyMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
} else {
return new ImmutableMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
}
return new ImmutableMessageFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
case JAVATYPE_ENUM:
return new ImmutableEnumFieldLiteGenerator(
field, messageBitIndex, builderBitIndex, context);
@@ -293,10 +261,17 @@ void SetCommonFieldVariables(const FieldDescriptor* descriptor,
std::map<string, string>* variables) {
(*variables)["field_name"] = descriptor->name();
(*variables)["name"] = info->name;
(*variables)["classname"] = descriptor->containing_type()->name();
(*variables)["capitalized_name"] = info->capitalized_name;
(*variables)["disambiguated_reason"] = info->disambiguated_reason;
(*variables)["constant_name"] = FieldConstantName(descriptor);
(*variables)["number"] = SimpleItoa(descriptor->number());
// These variables are placeholders to pick out the beginning and ends of
// identifiers for annotations (when doing so with existing variables would
// be ambiguous or impossible). They should never be set to anything but the
// empty string.
(*variables)["{"] = "";
(*variables)["}"] = "";
}
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
@@ -248,9 +248,12 @@ void FileGenerator::Generate(io::Printer* printer) {
PrintGeneratedAnnotation(
printer, '$', options_.annotate_code ? classname_ + ".java.pb.meta" : "");
printer->Print(
"public final class $classname$ {\n"
"$deprecation$public final class $classname$ {\n"
" private $ctor$() {}\n",
"classname", classname_, "ctor", classname_);
"deprecation", file_->options().deprecated() ?
"@java.lang.Deprecated " : "",
"classname", classname_,
"ctor", classname_);
printer->Annotate("classname", file_->name());
printer->Indent();
@@ -499,19 +502,57 @@ void FileGenerator::GenerateDescriptorInitializationCodeForMutable(io::Printer*
// Try to load immutable messages' outer class. Its initialization code
// will take care of interpreting custom options.
printer->Print(
"try {\n"
// Note that we have to load the immutable class dynamically here as
// we want the mutable code to be independent from the immutable code
// at compile time. It is required to implement dual-compile for
// mutable and immutable API in blaze.
" java.lang.Class immutableClass = java.lang.Class.forName(\n"
" \"$immutable_classname$\");\n"
"} catch (java.lang.ClassNotFoundException e) {\n"
// The immutable class can not be found. Custom options are left
// as unknown fields.
// TODO(xiaofeng): inform the user with a warning?
"}\n",
"immutable_classname", name_resolver_->GetImmutableClassName(file_));
"try {\n"
// Note that we have to load the immutable class dynamically here as
// we want the mutable code to be independent from the immutable code
// at compile time. It is required to implement dual-compile for
// mutable and immutable API in blaze.
" java.lang.Class immutableClass = java.lang.Class.forName(\n"
" \"$immutable_classname$\");\n"
"} catch (java.lang.ClassNotFoundException e) {\n",
"immutable_classname", name_resolver_->GetImmutableClassName(file_));
printer->Indent();
// The immutable class can not be found. We try our best to collect all
// custom option extensions to interpret the custom options.
printer->Print(
"com.google.protobuf.ExtensionRegistry registry =\n"
" com.google.protobuf.ExtensionRegistry.newInstance();\n"
"com.google.protobuf.MessageLite defaultExtensionInstance = null;\n");
FieldDescriptorSet::iterator it;
for (it = extensions.begin(); it != extensions.end(); it++) {
const FieldDescriptor* field = *it;
string scope;
if (field->extension_scope() != NULL) {
scope = name_resolver_->GetMutableClassName(field->extension_scope()) +
".getDescriptor()";
} else {
scope = FileJavaPackage(field->file(), true) + "." +
name_resolver_->GetDescriptorClassName(field->file()) +
".descriptor";
}
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
printer->Print(
"defaultExtensionInstance = com.google.protobuf.Internal\n"
" .getDefaultInstance(\"$class$\");\n"
"if (defaultExtensionInstance != null) {\n"
" registry.add(\n"
" $scope$.getExtensions().get($index$),\n"
" (com.google.protobuf.Message) defaultExtensionInstance);\n"
"}\n",
"scope", scope, "index", SimpleItoa(field->index()), "class",
name_resolver_->GetImmutableClassName(field->message_type()));
} else {
printer->Print("registry.add($scope$.getExtensions().get($index$));\n",
"scope", scope, "index", SimpleItoa(field->index()));
}
}
printer->Print(
"com.google.protobuf.Descriptors.FileDescriptor\n"
" .internalUpdateFileDescriptor(descriptor, registry);\n");
printer->Outdent();
printer->Print("}\n");
}
// Force descriptor initialization of all dependencies.
@@ -42,6 +42,7 @@
#include <google/protobuf/compiler/java/java_file.h>
#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/compiler/java/java_options.h>
#include <google/protobuf/compiler/java/java_shared_code_generator.h>
#include <google/protobuf/io/printer.h>
@@ -37,12 +37,15 @@
#include <limits>
#include <vector>
#include <google/protobuf/stubs/stringprintf.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/wire_format.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/stubs/substitute.h>
#include <google/protobuf/stubs/hash.h> // for hash<T *>
namespace google {
@@ -167,6 +170,14 @@ string UniqueFileScopeIdentifier(const Descriptor* descriptor) {
return "static_" + StringReplace(descriptor->full_name(), ".", "_", true);
}
string CamelCaseFieldName(const FieldDescriptor* field) {
string fieldName = UnderscoresToCamelCase(field);
if ('0' <= fieldName[0] && fieldName[0] <= '9') {
return '_' + fieldName;
}
return fieldName;
}
string StripProto(const string& filename) {
if (HasSuffixString(filename, ".protodevel")) {
return StripSuffixString(filename, ".protodevel");
@@ -773,6 +784,137 @@ bool HasRepeatedFields(const Descriptor* descriptor) {
return false;
}
// Encode an unsigned 32-bit value into a sequence of UTF-16 characters.
//
// If the value is in [0x0000, 0xD7FF], we encode it with a single character
// with the same numeric value.
//
// If the value is larger than 0xD7FF, we encode its lowest 13 bits into a
// character in the range [0xE000, 0xFFFF] by combining these 13 bits with
// 0xE000 using logic-or. Then we shift the value to the right by 13 bits, and
// encode the remaining value by repeating this same process until we get to
// a value in [0x0000, 0xD7FF] where we will encode it using a character with
// the same numeric value.
//
// Note that we only use code points in [0x0000, 0xD7FF] and [0xE000, 0xFFFF].
// There will be no surrogate pairs in the encoded character sequence.
void WriteUInt32ToUtf16CharSequence(uint32 number,
std::vector<uint16>* output) {
// For values in [0x0000, 0xD7FF], only use one char to encode it.
if (number < 0xD800) {
output->push_back(static_cast<uint16>(number));
return;
}
// Encode into multiple chars. All except the last char will be in the range
// [0xE000, 0xFFFF], and the last char will be in the range [0x0000, 0xD7FF].
// Note that we don't use any value in range [0xD800, 0xDFFF] because they
// have to come in pairs and the encoding is just more space-efficient w/o
// them.
while (number >= 0xD800) {
// [0xE000, 0xFFFF] can represent 13 bits of info.
output->push_back(static_cast<uint16>(0xE000 | (number & 0x1FFF)));
number >>= 13;
}
output->push_back(static_cast<uint16>(number));
}
int GetExperimentalJavaFieldTypeForSingular(const FieldDescriptor* field) {
// j/c/g/protobuf/FieldType.java lists field types in a slightly different
// order from FieldDescriptor::Type so we can't do a simple cast.
//
// TODO(xiaofeng): Make j/c/g/protobuf/FieldType.java follow the same order.
int result = field->type();
if (result == FieldDescriptor::TYPE_GROUP) {
return 17;
} else if (result < FieldDescriptor::TYPE_GROUP) {
return result - 1;
} else {
return result - 2;
}
}
int GetExperimentalJavaFieldTypeForRepeated(const FieldDescriptor* field) {
if (field->type() == FieldDescriptor::TYPE_GROUP) {
return 49;
} else {
return GetExperimentalJavaFieldTypeForSingular(field) + 18;
}
}
int GetExperimentalJavaFieldTypeForPacked(const FieldDescriptor* field) {
int result = field->type();
if (result < FieldDescriptor::TYPE_STRING) {
return result + 34;
} else if (result > FieldDescriptor::TYPE_BYTES) {
return result + 30;
} else {
GOOGLE_LOG(FATAL) << field->full_name() << " can't be packed.";
return 0;
}
}
int GetExperimentalJavaFieldType(const FieldDescriptor* field) {
static const int kMapFieldType = 50;
static const int kOneofFieldTypeOffset = 51;
static const int kRequiredBit = 0x100;
static const int kUtf8CheckBit = 0x200;
static const int kCheckInitialized = 0x400;
static const int kMapWithProto2EnumValue = 0x800;
int extra_bits = field->is_required() ? kRequiredBit : 0;
if (field->type() == FieldDescriptor::TYPE_STRING && CheckUtf8(field)) {
extra_bits |= kUtf8CheckBit;
}
if (field->is_required() || (GetJavaType(field) == JAVATYPE_MESSAGE &&
HasRequiredFields(field->message_type()))) {
extra_bits |= kCheckInitialized;
}
if (field->is_map()) {
if (SupportFieldPresence(field->file())) {
const FieldDescriptor* value =
field->message_type()->FindFieldByName("value");
if (GetJavaType(value) == JAVATYPE_ENUM) {
extra_bits |= kMapWithProto2EnumValue;
}
}
return kMapFieldType | extra_bits;
} else if (field->is_packed()) {
return GetExperimentalJavaFieldTypeForPacked(field);
} else if (field->is_repeated()) {
return GetExperimentalJavaFieldTypeForRepeated(field) | extra_bits;
} else if (field->containing_oneof() != NULL) {
return (GetExperimentalJavaFieldTypeForSingular(field) +
kOneofFieldTypeOffset) |
extra_bits;
} else {
return GetExperimentalJavaFieldTypeForSingular(field) | extra_bits;
}
}
// Escape a UTF-16 character to be embedded in a Java string.
void EscapeUtf16ToString(uint16 code, string* output) {
if (code == '\t') {
output->append("\\t");
} else if (code == '\b') {
output->append("\\b");
} else if (code == '\n') {
output->append("\\n");
} else if (code == '\r') {
output->append("\\r");
} else if (code == '\f') {
output->append("\\f");
} else if (code == '\'') {
output->append("\\'");
} else if (code == '\"') {
output->append("\\\"");
} else if (code == '\\') {
output->append("\\\\");
} else if (code >= 0x20 && code <= 0x7f) {
output->push_back(static_cast<char>(code));
} else {
output->append(StringPrintf("\\u%04x", code));
}
}
} // namespace java
} // namespace compiler
} // namespace protobuf
@@ -74,6 +74,10 @@ string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field);
// of lower-casing the first letter of the name.)
string UnderscoresToCamelCase(const MethodDescriptor* method);
// Similar to UnderscoresToCamelCase, but guarentees that the result is a
// complete Java identifier by adding a _ if needed.
string CamelCaseFieldName(const FieldDescriptor* field);
// Get an identifier that uniquely identifies this type within the file.
// This is used to declare static variables related to this type at the
// outermost file scope.
@@ -132,6 +136,13 @@ inline string ShortMutableJavaClassName(const Descriptor* descriptor) {
return descriptor->name();
}
// Whether the given descriptor is for one of the core descriptor protos. We
// cannot currently use the new runtime with core protos since there is a
// bootstrapping problem with obtaining their descriptors.
inline bool IsDescriptorProto(const Descriptor* descriptor) {
return descriptor->file()->name() == "google/protobuf/descriptor.proto";
}
// Whether we should generate multiple java files for messages.
inline bool MultipleJavaFiles(
@@ -242,15 +253,6 @@ inline bool HasGenericServices(const FileDescriptor *file, bool enforce_lite) {
file->options().java_generic_services();
}
inline bool IsLazy(const FieldDescriptor* descriptor, bool enforce_lite) {
// Currently, the proto-lite version supports lazy field.
// TODO(niwasaki): Support lazy fields also for other proto runtimes.
if (HasDescriptorMethods(descriptor->file(), enforce_lite)) {
return false;
}
return descriptor->options().lazy();
}
// Methods for shared bitfields.
// Gets the name of the shared bitfield for the given index.
@@ -372,14 +374,14 @@ inline bool IsMapField(const FieldDescriptor* descriptor) {
return descriptor->is_map();
}
inline bool PreserveUnknownFields(const Descriptor* descriptor) {
return descriptor->file()->syntax() != FileDescriptor::SYNTAX_PROTO3;
}
inline bool IsAnyMessage(const Descriptor* descriptor) {
return descriptor->full_name() == "google.protobuf.Any";
}
inline bool IsWrappersProtoFile(const FileDescriptor* descriptor) {
return descriptor->name() == "google/protobuf/wrappers.proto";
}
inline bool CheckUtf8(const FieldDescriptor* descriptor) {
return descriptor->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ||
descriptor->file()->options().java_string_check_utf8();
@@ -388,6 +390,30 @@ inline bool CheckUtf8(const FieldDescriptor* descriptor) {
inline string GeneratedCodeVersionSuffix() {
return "V3";
}
inline bool EnableExperimentalRuntime(Context* context) {
return false;
}
void WriteUInt32ToUtf16CharSequence(uint32 number, std::vector<uint16>* output);
inline void WriteIntToUtf16CharSequence(int value,
std::vector<uint16>* output) {
WriteUInt32ToUtf16CharSequence(static_cast<uint32>(value), output);
}
// Escape a UTF-16 character so it can be embedded in a Java string literal.
void EscapeUtf16ToString(uint16 code, string* output);
// Only the lowest two bytes of the return value are used. The lowest byte
// is the integer value of a j/c/g/protobuf/FieldType enum. For the other
// byte:
// bit 0: whether the field is required.
// bit 1: whether the field requires UTF-8 validation.
// bit 2: whether the field needs isInitialized check.
// bit 3: whether the field is a map field with proto2 enum value.
// bits 4-7: unused
int GetExperimentalJavaFieldType(const FieldDescriptor* field);
} // namespace java
} // namespace compiler
} // namespace protobuf
@@ -183,12 +183,14 @@ GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$int get$capitalized_name$Count();\n");
"$deprecation$int ${$get$capitalized_name$Count$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$boolean contains$capitalized_name$(\n"
"$deprecation$boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key);\n");
printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -197,23 +199,27 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$();\n");
"${$get$capitalized_name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$Map();\n");
"${$get$capitalized_name$Map$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$$value_enum_type$ get$capitalized_name$OrDefault(\n"
"$deprecation$$value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue);\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$$value_enum_type$ get$capitalized_name$OrThrow(\n"
"$deprecation$$value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key);\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -222,25 +228,29 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$type_parameters$>\n"
"get$capitalized_name$Value();\n");
"${$get$capitalized_name$Value$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$type_parameters$>\n"
"get$capitalized_name$ValueMap();\n");
"${$get$capitalized_name$ValueMap$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"$value_type$ get$capitalized_name$ValueOrDefault(\n"
"$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue);\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"$value_type$ get$capitalized_name$ValueOrThrow(\n"
"$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key);\n");
printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -250,25 +260,29 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$type_parameters$>\n"
"get$capitalized_name$();\n");
"${$get$capitalized_name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$type_parameters$>\n"
"get$capitalized_name$Map();\n");
"${$get$capitalized_name$Map$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"$value_type$ get$capitalized_name$OrDefault(\n"
"$value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue);\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"$value_type$ get$capitalized_name$OrThrow(\n"
"$value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key);\n");
printer->Annotate("{", "}", descriptor_);
}
}
@@ -349,23 +363,27 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return $name$_;\n"
"}\n");
GenerateMapGetters(printer);
printer->Print(variables_,
"$deprecation$\n"
"public Builder clear$capitalized_name$() {\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .clear();\n"
" return this;\n"
"}\n");
printer->Print(
variables_,
"$deprecation$\n"
"public Builder ${$clear$capitalized_name$$}$() {\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .clear();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$\n"
"public Builder remove$capitalized_name$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .remove(key);\n"
" return this;\n"
"}\n");
printer->Print(
variables_,
"$deprecation$\n"
"public Builder ${$remove$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .remove(key);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -374,13 +392,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"getMutable$capitalized_name$() {\n"
"${$getMutable$capitalized_name$$}$() {\n"
" return internalGetAdapted$capitalized_name$Map(\n"
" internalGetMutable$capitalized_name$().getMutableMap());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder put$capitalized_name$(\n"
"$deprecation$public Builder ${$put$capitalized_name$$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ value) {\n"
" $key_null_check$\n"
@@ -389,16 +408,18 @@ GenerateBuilderMembers(io::Printer* printer) const {
" .put(key, $name$ValueConverter.doBackward(value));\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$public Builder putAll$capitalized_name$(\n"
"$deprecation$public Builder ${$putAll$capitalized_name$$}$(\n"
" java.util.Map<$boxed_key_type$, $value_enum_type$> values) {\n"
" internalGetAdapted$capitalized_name$Map(\n"
" internalGetMutable$capitalized_name$().getMutableMap())\n"
" .putAll(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -407,32 +428,32 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"getMutable$capitalized_name$Value() {\n"
"${$getMutable$capitalized_name$Value$}$() {\n"
" return internalGetMutable$capitalized_name$().getMutableMap();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$public Builder put$capitalized_name$Value(\n"
"$deprecation$public Builder ${$put$capitalized_name$Value$}$(\n"
" $key_type$ key,\n"
" $value_type$ value) {\n"
" $key_null_check$\n"
" if ($value_enum_type$.forNumber(value) == null) {\n"
" throw new java.lang.IllegalArgumentException();\n"
" }\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .put(key, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$public Builder putAll$capitalized_name$Value(\n"
"$deprecation$public Builder ${$putAll$capitalized_name$Value$}$(\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> values) {\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .putAll(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -442,30 +463,35 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$type_parameters$>\n"
"getMutable$capitalized_name$() {\n"
"${$getMutable$capitalized_name$$}$() {\n"
" return internalGetMutable$capitalized_name$().getMutableMap();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$"
"public Builder put$capitalized_name$(\n"
" $key_type$ key,\n"
" $value_type$ value) {\n"
" $key_null_check$\n"
" $value_null_check$\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .put(key, value);\n"
" return this;\n"
"}\n");
printer->Print(
variables_,
"$deprecation$"
"public Builder ${$put$capitalized_name$$}$(\n"
" $key_type$ key,\n"
" $value_type$ value) {\n"
" $key_null_check$\n"
" $value_null_check$\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .put(key, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$\n"
"public Builder putAll$capitalized_name$(\n"
" java.util.Map<$type_parameters$> values) {\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .putAll(values);\n"
" return this;\n"
"}\n");
printer->Print(
variables_,
"$deprecation$\n"
"public Builder ${$putAll$capitalized_name$$}$(\n"
" java.util.Map<$type_parameters$> values) {\n"
" internalGetMutable$capitalized_name$().getMutableMap()\n"
" .putAll(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
}
@@ -474,18 +500,20 @@ GenerateMapGetters(io::Printer* printer) const {
printer->Print(
variables_,
"$deprecation$\n"
"public int get$capitalized_name$Count() {\n"
"public int ${$get$capitalized_name$Count$}$() {\n"
" return internalGet$capitalized_name$().getMap().size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public boolean contains$capitalized_name$(\n"
"public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" return internalGet$capitalized_name$().getMap().containsKey(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -494,22 +522,25 @@ GenerateMapGetters(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$() {\n"
"${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$Map() {\n"
" return internalGetAdapted$capitalized_name$Map(\n"
" internalGet$capitalized_name$().getMap());"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_enum_type$ get$capitalized_name$OrDefault(\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"${$get$capitalized_name$Map$}$() {\n"
" return internalGetAdapted$capitalized_name$Map(\n"
" internalGet$capitalized_name$().getMap());"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -519,11 +550,12 @@ GenerateMapGetters(io::Printer* printer) const {
" ? $name$ValueConverter.doForward(map.get(key))\n"
" : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_enum_type$ get$capitalized_name$OrThrow(\n"
"public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -533,6 +565,7 @@ GenerateMapGetters(io::Printer* printer) const {
" }\n"
" return $name$ValueConverter.doForward(map.get(key));\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -541,22 +574,24 @@ GenerateMapGetters(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"get$capitalized_name$Value() {\n"
"${$get$capitalized_name$Value$}$() {\n"
" return get$capitalized_name$ValueMap();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"get$capitalized_name$ValueMap() {\n"
"${$get$capitalized_name$ValueMap$}$() {\n"
" return internalGet$capitalized_name$().getMap();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$ValueOrDefault(\n"
"public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -564,11 +599,12 @@ GenerateMapGetters(io::Printer* printer) const {
" internalGet$capitalized_name$().getMap();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$ValueOrThrow(\n"
"public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -578,6 +614,7 @@ GenerateMapGetters(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -586,21 +623,25 @@ GenerateMapGetters(io::Printer* printer) const {
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$type_parameters$> get$capitalized_name$() {\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$type_parameters$> get$capitalized_name$Map() {\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$Map$}$() {\n"
" return internalGet$capitalized_name$().getMap();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$OrDefault(\n"
"public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -608,11 +649,12 @@ GenerateMapGetters(io::Printer* printer) const {
" internalGet$capitalized_name$().getMap();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$OrThrow(\n"
"public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$type_parameters$> map =\n"
@@ -622,6 +664,7 @@ GenerateMapGetters(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
}
@@ -166,12 +166,14 @@ GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$int get$capitalized_name$Count();\n");
"$deprecation$int ${$get$capitalized_name$Count$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$boolean contains$capitalized_name$(\n"
"$deprecation$boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key);\n");
printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -180,23 +182,27 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$();\n");
"${$get$capitalized_name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$Map();\n");
"${$get$capitalized_name$Map$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$$value_enum_type$ get$capitalized_name$OrDefault(\n"
"$deprecation$$value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue);\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$$value_enum_type$ get$capitalized_name$OrThrow(\n"
"$deprecation$$value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key);\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -205,25 +211,29 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$type_parameters$>\n"
"get$capitalized_name$Value();\n");
"${$get$capitalized_name$Value$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$type_parameters$>\n"
"get$capitalized_name$ValueMap();\n");
"${$get$capitalized_name$ValueMap$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"$value_type$ get$capitalized_name$ValueOrDefault(\n"
"$value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue);\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"$value_type$ get$capitalized_name$ValueOrThrow(\n"
"$value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key);\n");
printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -233,25 +243,29 @@ GenerateInterfaceMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"java.util.Map<$type_parameters$>\n"
"get$capitalized_name$();\n");
"${$get$capitalized_name$$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$java.util.Map<$type_parameters$>\n"
"get$capitalized_name$Map();\n");
"${$get$capitalized_name$Map$}$();\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"$value_type$ get$capitalized_name$OrDefault(\n"
"$value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue);\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"$value_type$ get$capitalized_name$OrThrow(\n"
"$value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key);\n");
printer->Annotate("{", "}", descriptor_);
}
}
@@ -288,18 +302,20 @@ GenerateMembers(io::Printer* printer) const {
printer->Print(
variables_,
"$deprecation$\n"
"public int get$capitalized_name$Count() {\n"
"public int ${$get$capitalized_name$Count$}$() {\n"
" return internalGet$capitalized_name$().size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public boolean contains$capitalized_name$(\n"
"public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" return internalGet$capitalized_name$().containsKey(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -316,26 +332,28 @@ GenerateMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$() {\n"
"${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$Map() {\n"
"${$get$capitalized_name$Map$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" new com.google.protobuf.Internal.MapAdapter<\n"
" $boxed_key_type$, $value_enum_type$, java.lang.Integer>(\n"
" internalGet$capitalized_name$(),\n"
" $name$ValueConverter));\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_enum_type$ get$capitalized_name$OrDefault(\n"
"public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -345,11 +363,12 @@ GenerateMembers(io::Printer* printer) const {
" ? $name$ValueConverter.doForward(map.get(key))\n"
" : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_enum_type$ get$capitalized_name$OrThrow(\n"
"public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -359,6 +378,7 @@ GenerateMembers(io::Printer* printer) const {
" }\n"
" return $name$ValueConverter.doForward(map.get(key));\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -367,23 +387,25 @@ GenerateMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"get$capitalized_name$Value() {\n"
"${$get$capitalized_name$Value$}$() {\n"
" return get$capitalized_name$ValueMap();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"get$capitalized_name$ValueMap() {\n"
"${$get$capitalized_name$ValueMap$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" internalGet$capitalized_name$());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$ValueOrDefault(\n"
"public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -391,11 +413,12 @@ GenerateMembers(io::Printer* printer) const {
" internalGet$capitalized_name$();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$ValueOrThrow(\n"
"public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -405,6 +428,7 @@ GenerateMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -413,22 +437,26 @@ GenerateMembers(io::Printer* printer) const {
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$type_parameters$> get$capitalized_name$() {\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$type_parameters$> get$capitalized_name$Map() {\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$Map$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" internalGet$capitalized_name$());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$OrDefault(\n"
"public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -436,11 +464,12 @@ GenerateMembers(io::Printer* printer) const {
" internalGet$capitalized_name$();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$OrThrow(\n"
"public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$type_parameters$> map =\n"
@@ -450,6 +479,7 @@ GenerateMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
// Generate private setters for the builder to proxy into.
@@ -490,37 +520,41 @@ GenerateBuilderMembers(io::Printer* printer) const {
printer->Print(
variables_,
"$deprecation$\n"
"public int get$capitalized_name$Count() {\n"
"public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Map().size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public boolean contains$capitalized_name$(\n"
"public boolean ${$contains$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" return instance.get$capitalized_name$Map().containsKey(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public Builder clear$capitalized_name$() {\n"
"public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$Map().clear();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public Builder remove$capitalized_name$(\n"
"public Builder ${$remove$capitalized_name$$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$Map().remove(key);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (GetJavaType(ValueField(descriptor_)) == JAVATYPE_ENUM) {
printer->Print(
variables_,
@@ -529,23 +563,25 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$() {\n"
"${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $value_enum_type$>\n"
"get$capitalized_name$Map() {\n"
"${$get$capitalized_name$Map$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" instance.get$capitalized_name$Map());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_enum_type$ get$capitalized_name$OrDefault(\n"
"public $value_enum_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -555,11 +591,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" ? map.get(key)\n"
" : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_enum_type$ get$capitalized_name$OrThrow(\n"
"public $value_enum_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $value_enum_type$> map =\n"
@@ -569,10 +606,11 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$public Builder put$capitalized_name$(\n"
"$deprecation$public Builder ${$put$capitalized_name$$}$(\n"
" $key_type$ key,\n"
" $value_enum_type$ value) {\n"
" $key_null_check$\n"
@@ -581,15 +619,17 @@ GenerateBuilderMembers(io::Printer* printer) const {
" instance.getMutable$capitalized_name$Map().put(key, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$public Builder putAll$capitalized_name$(\n"
"$deprecation$public Builder ${$putAll$capitalized_name$$}$(\n"
" java.util.Map<$boxed_key_type$, $value_enum_type$> values) {\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$Map().putAll(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (SupportUnknownEnumValue(descriptor_->file())) {
printer->Print(
variables_,
@@ -598,23 +638,25 @@ GenerateBuilderMembers(io::Printer* printer) const {
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"get$capitalized_name$Value() {\n"
"${$get$capitalized_name$Value$}$() {\n"
" return get$capitalized_name$ValueMap();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public java.util.Map<$boxed_key_type$, $boxed_value_type$>\n"
"get$capitalized_name$ValueMap() {\n"
"${$get$capitalized_name$ValueMap$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" instance.get$capitalized_name$ValueMap());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$ValueOrDefault(\n"
"public $value_type$ ${$get$capitalized_name$ValueOrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -622,11 +664,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" instance.get$capitalized_name$ValueMap();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$ValueOrThrow(\n"
"public $value_type$ ${$get$capitalized_name$ValueOrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> map =\n"
@@ -636,29 +679,29 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$public Builder put$capitalized_name$Value(\n"
"$deprecation$public Builder ${$put$capitalized_name$Value$}$(\n"
" $key_type$ key,\n"
" $value_type$ value) {\n"
" $key_null_check$\n"
" if ($value_enum_type$.forNumber(value) == null) {\n"
" throw new java.lang.IllegalArgumentException();\n"
" }\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$ValueMap().put(key, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$public Builder putAll$capitalized_name$Value(\n"
"$deprecation$public Builder ${$putAll$capitalized_name$Value$}$(\n"
" java.util.Map<$boxed_key_type$, $boxed_value_type$> values) {\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$ValueMap().putAll(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
} else {
printer->Print(
@@ -667,22 +710,26 @@ GenerateBuilderMembers(io::Printer* printer) const {
" * Use {@link #get$capitalized_name$Map()} instead.\n"
" */\n"
"@java.lang.Deprecated\n"
"public java.util.Map<$type_parameters$> get$capitalized_name$() {\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$$}$() {\n"
" return get$capitalized_name$Map();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$"
"public java.util.Map<$type_parameters$> get$capitalized_name$Map() {\n"
"public java.util.Map<$type_parameters$> "
"${$get$capitalized_name$Map$}$() {\n"
" return java.util.Collections.unmodifiableMap(\n"
" instance.get$capitalized_name$Map());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$OrDefault(\n"
"public $value_type$ ${$get$capitalized_name$OrDefault$}$(\n"
" $key_type$ key,\n"
" $value_type$ defaultValue) {\n"
" $key_null_check$\n"
@@ -690,11 +737,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" instance.get$capitalized_name$Map();\n"
" return map.containsKey(key) ? map.get(key) : defaultValue;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$\n"
"public $value_type$ get$capitalized_name$OrThrow(\n"
"public $value_type$ ${$get$capitalized_name$OrThrow$}$(\n"
" $key_type$ key) {\n"
" $key_null_check$\n"
" java.util.Map<$type_parameters$> map =\n"
@@ -704,11 +752,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return map.get(key);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$"
"public Builder put$capitalized_name$(\n"
"public Builder ${$put$capitalized_name$$}$(\n"
" $key_type$ key,\n"
" $value_type$ value) {\n"
" $key_null_check$\n"
@@ -717,16 +766,18 @@ GenerateBuilderMembers(io::Printer* printer) const {
" instance.getMutable$capitalized_name$Map().put(key, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(
variables_,
"$deprecation$"
"public Builder putAll$capitalized_name$(\n"
"public Builder ${$putAll$capitalized_name$$}$(\n"
" java.util.Map<$type_parameters$> values) {\n"
" copyOnWrite();\n"
" instance.getMutable$capitalized_name$Map().putAll(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
}
@@ -56,8 +56,9 @@
#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 {
@@ -253,7 +254,7 @@ void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) {
/* immutable = */ true, "OrBuilder");
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"$deprecation$public interface $classname$OrBuilder$idend$ extends\n"
"$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n"
" $extra_interfaces$\n"
" com.google.protobuf.GeneratedMessage$ver$.\n"
" ExtendableMessageOrBuilder<$classname$> {\n",
@@ -261,19 +262,19 @@ void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) {
"@java.lang.Deprecated " : "",
"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
"classname", descriptor_->name(),
"idend", "", "ver", GeneratedCodeVersionSuffix());
"{", "", "}", "", "ver", GeneratedCodeVersionSuffix());
} else {
printer->Print(
"$deprecation$public interface $classname$OrBuilder$idend$ extends\n"
"$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n"
" $extra_interfaces$\n"
" com.google.protobuf.MessageOrBuilder {\n",
"deprecation", descriptor_->options().deprecated() ?
"@java.lang.Deprecated " : "",
"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
"classname", descriptor_->name(),
"idend", "");
"{", "", "}", "");
}
printer->Annotate("classname", "idend", descriptor_);
printer->Annotate("{", "}", descriptor_);
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
@@ -345,6 +346,9 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
"com.google.protobuf.GeneratedMessage$0.Builder<?>",
GeneratedCodeVersionSuffix());
}
printer->Print(
"private static final long serialVersionUID = 0L;\n");
printer->Indent();
// Using builder_type, instead of Builder, prevents the Builder class from
// being loaded into PermGen space when the default instance is created.
@@ -367,22 +371,19 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
"}\n"
"\n");
printer->Print(
"@java.lang.Override\n"
"public final com.google.protobuf.UnknownFieldSet\n"
"getUnknownFields() {\n");
if (PreserveUnknownFields(descriptor_)) {
printer->Print(
" return this.unknownFields;\n");
} else {
printer->Print(
" return com.google.protobuf.UnknownFieldSet.getDefaultInstance();\n");
}
printer->Print(
"getUnknownFields() {\n"
" return this.unknownFields;\n"
"}\n");
if (context_->HasGeneratedMethods(descriptor_)) {
GenerateParsingConstructor(printer);
if (!EnableExperimentalRuntime(context_) ||
IsDescriptorProto(descriptor_)) {
GenerateParsingConstructor(printer);
}
}
GenerateDescriptorMethods(printer);
@@ -540,6 +541,17 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) {
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
// 'of' method for Wrappers
if (IsWrappersProtoFile(descriptor_->file())) {
printer->Print(
"public static $classname$ of($field_type$ value) {\n"
" return newBuilder().setValue(value).build();\n"
"}\n"
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_),
"field_type", PrimitiveTypeName(GetJavaType(descriptor_->field(0))));
}
GenerateParser(printer);
printer->Print(
@@ -579,104 +591,105 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
"public void writeTo(com.google.protobuf.CodedOutputStream output)\n"
" throws java.io.IOException {\n");
printer->Indent();
if (HasPackedFields(descriptor_)) {
// writeTo(CodedOutputStream output) might be invoked without
// getSerializedSize() ever being called, but we need the memoized
// sizes in case this message has packed fields. Rather than emit checks for
// each packed field, just call getSerializedSize() up front.
// In most cases, getSerializedSize() will have already been called anyway
// by one of the wrapper writeTo() methods, making this call cheap.
printer->Print(
"getSerializedSize();\n");
}
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"com.google.protobuf.GeneratedMessage$ver$\n"
" .ExtendableMessage<$classname$>.ExtensionWriter\n"
" extensionWriter = newMessageSetExtensionWriter();\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_),
"ver", GeneratedCodeVersionSuffix());
} else {
printer->Print(
"com.google.protobuf.GeneratedMessage$ver$\n"
" .ExtendableMessage<$classname$>.ExtensionWriter\n"
" extensionWriter = newExtensionWriter();\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_),
"ver", GeneratedCodeVersionSuffix());
if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
printer->Print("writeToInternal(output);\n");
} else {
if (HasPackedFields(descriptor_)) {
// writeTo(CodedOutputStream output) might be invoked without
// getSerializedSize() ever being called, but we need the memoized
// sizes in case this message has packed fields. Rather than emit checks
// for each packed field, just call getSerializedSize() up front. In most
// cases, getSerializedSize() will have already been called anyway by one
// of the wrapper writeTo() methods, making this call cheap.
printer->Print("getSerializedSize();\n");
}
}
// Merge the fields and the extension ranges, both sorted by field number.
for (int i = 0, j = 0;
i < descriptor_->field_count() || j < sorted_extensions.size();
) {
if (i == descriptor_->field_count()) {
GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
} else if (j == sorted_extensions.size()) {
GenerateSerializeOneField(printer, sorted_fields[i++]);
} else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
GenerateSerializeOneField(printer, sorted_fields[i++]);
} else {
GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"com.google.protobuf.GeneratedMessage$ver$\n"
" .ExtendableMessage<$classname$>.ExtensionWriter\n"
" extensionWriter = newMessageSetExtensionWriter();\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_),
"ver", GeneratedCodeVersionSuffix());
} else {
printer->Print(
"com.google.protobuf.GeneratedMessage$ver$\n"
" .ExtendableMessage<$classname$>.ExtensionWriter\n"
" extensionWriter = newExtensionWriter();\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_),
"ver", GeneratedCodeVersionSuffix());
}
}
// Merge the fields and the extension ranges, both sorted by field number.
for (int i = 0, j = 0;
i < descriptor_->field_count() || j < sorted_extensions.size();) {
if (i == descriptor_->field_count()) {
GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
} else if (j == sorted_extensions.size()) {
GenerateSerializeOneField(printer, sorted_fields[i++]);
} else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
GenerateSerializeOneField(printer, sorted_fields[i++]);
} else {
GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
}
}
}
if (PreserveUnknownFields(descriptor_)) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"unknownFields.writeAsMessageSetTo(output);\n");
printer->Print("unknownFields.writeAsMessageSetTo(output);\n");
} else {
printer->Print(
"unknownFields.writeTo(output);\n");
printer->Print("unknownFields.writeTo(output);\n");
}
}
printer->Outdent();
printer->Print(
"}\n"
"\n"
"public int getSerializedSize() {\n"
" int size = memoizedSize;\n"
" if (size != -1) return size;\n"
"\n"
" size = 0;\n");
"}\n"
"\n"
"public int getSerializedSize() {\n"
" int size = memoizedSize;\n"
" if (size != -1) return size;\n"
"\n");
printer->Indent();
if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
printer->Print(
"memoizedSize = getSerializedSizeInternal();\n"
"return memoizedSize;\n");
} else {
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer);
}
printer->Print("size = 0;\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(sorted_fields[i])
.GenerateSerializedSizeCode(printer);
}
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print("size += extensionsSerializedSizeAsMessageSet();\n");
} else {
printer->Print("size += extensionsSerializedSize();\n");
}
}
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"size += extensionsSerializedSizeAsMessageSet();\n");
"size += unknownFields.getSerializedSizeAsMessageSet();\n");
} else {
printer->Print(
"size += extensionsSerializedSize();\n");
printer->Print("size += unknownFields.getSerializedSize();\n");
}
}
if (PreserveUnknownFields(descriptor_)) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"size += unknownFields.getSerializedSizeAsMessageSet();\n");
} else {
printer->Print(
"size += unknownFields.getSerializedSize();\n");
}
printer->Print(
"memoizedSize = size;\n"
"return size;\n");
}
printer->Outdent();
printer->Print(
" memoizedSize = size;\n"
" return size;\n"
"}\n"
"\n");
printer->Print(
"private static final long serialVersionUID = 0L;\n");
}
void ImmutableMessageGenerator::
@@ -1078,13 +1091,11 @@ GenerateEqualsAndHashCode(io::Printer* printer) {
printer->Print("}\n");
}
if (PreserveUnknownFields(descriptor_)) {
// Always consider unknown fields for equality. This will sometimes return
// false for non-canonical ordering when running in LITE_RUNTIME but it's
// the best we can do.
printer->Print(
// Always consider unknown fields for equality. This will sometimes return
// false for non-canonical ordering when running in LITE_RUNTIME but it's
// the best we can do.
printer->Print(
"result = result && unknownFields.equals(other.unknownFields);\n");
}
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"result = result &&\n"
@@ -1211,7 +1222,10 @@ GenerateParsingConstructor(io::Printer* printer) {
// Initialize all fields to default.
printer->Print(
"this();\n");
"this();\n"
"if (extensionRegistry == null) {\n"
" throw new java.lang.NullPointerException();\n"
"}\n");
// Use builder bits to track mutable repeated fields.
int totalBuilderBits = 0;
@@ -1226,11 +1240,9 @@ GenerateParsingConstructor(io::Printer* printer) {
"bit_field_name", GetBitFieldName(i));
}
if (PreserveUnknownFields(descriptor_)) {
printer->Print(
printer->Print(
"com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n"
" com.google.protobuf.UnknownFieldSet.newBuilder();\n");
}
printer->Print(
"try {\n");
@@ -1247,28 +1259,19 @@ GenerateParsingConstructor(io::Printer* printer) {
printer->Indent();
printer->Print(
"case 0:\n" // zero signals EOF / limit reached
"case 0:\n" // zero signals EOF / limit reached
" done = true;\n"
" break;\n");
if (PreserveUnknownFields(descriptor_)) {
printer->Print(
"default: {\n"
" if (!parseUnknownField(input, unknownFields,\n"
" extensionRegistry, tag)) {\n"
" done = true;\n" // it's an endgroup tag
" }\n"
" break;\n"
"}\n");
} else {
printer->Print(
"default: {\n"
" if (!input.skipField(tag)) {\n"
" done = true;\n" // it's an endgroup tag
" }\n"
" break;\n"
"}\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"
: "");
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = sorted_fields[i];
@@ -1328,10 +1331,8 @@ GenerateParsingConstructor(io::Printer* printer) {
field_generators_.get(field).GenerateParsingDoneCode(printer);
}
if (PreserveUnknownFields(descriptor_)) {
// Make unknown fields immutable.
printer->Print("this.unknownFields = unknownFields.build();\n");
}
// Make unknown fields immutable.
printer->Print("this.unknownFields = unknownFields.build();\n");
// Make extensions immutable.
printer->Print(
@@ -1360,10 +1361,18 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) {
" com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
" throws com.google.protobuf.InvalidProtocolBufferException {\n",
"classname", descriptor_->name());
if (context_->HasGeneratedMethods(descriptor_)) {
if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
printer->Indent();
printer->Print(
" return new $classname$(input, extensionRegistry);\n",
"$classname$ msg = new $classname$();\n"
"msg.mergeFromInternal(input, extensionRegistry);\n"
"msg.makeImmutableInternal();\n"
"return msg;\n",
"classname", descriptor_->name());
printer->Outdent();
} else if (context_->HasGeneratedMethods(descriptor_)) {
printer->Print(" return new $classname$(input, extensionRegistry);\n",
"classname", descriptor_->name());
} else {
// When parsing constructor isn't generated, use builder to parse
// messages. Note, will fallback to use reflection based mergeFieldFrom()
@@ -54,8 +54,9 @@
#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 {
@@ -171,36 +172,25 @@ Generate(io::Printer* printer) {
.GenerateBuilderMembers(printer);
}
if (!PreserveUnknownFields(descriptor_)) {
printer->Print(
"public final Builder setUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return this;\n"
"}\n"
"\n"
"public final Builder mergeUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return this;\n"
"}\n"
"\n");
} else {
bool is_proto3 =
descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3;
// Override methods declared in GeneratedMessage to return the concrete
// generated type so callsites won't depend on GeneratedMessage. This
// is needed to keep binary compatibility when we change generated code
// to subclass a different GeneratedMessage class (e.g., in v3.0.0 release
// we changed all generated code to subclass GeneratedMessageV3).
printer->Print(
"public final Builder setUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return super.setUnknownFields(unknownFields);\n"
"}\n"
"\n"
"public final Builder mergeUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return super.mergeUnknownFields(unknownFields);\n"
"}\n"
"\n");
}
printer->Print(
"public final Builder setUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return super.setUnknownFields$suffix$(unknownFields);\n"
"}\n"
"\n"
"public final Builder mergeUnknownFields(\n"
" final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
" return super.mergeUnknownFields(unknownFields);\n"
"}\n"
"\n",
"suffix", is_proto3 ? "Proto3" : "");
printer->Print(
"\n"
@@ -472,7 +462,7 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"}\n"
"public Builder setField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
" Object value) {\n"
" java.lang.Object value) {\n"
" return (Builder) super.setField(field, value);\n"
"}\n"
"public Builder clearField(\n"
@@ -485,12 +475,12 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
"}\n"
"public Builder setRepeatedField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
" int index, Object value) {\n"
" int index, java.lang.Object value) {\n"
" return (Builder) super.setRepeatedField(field, index, value);\n"
"}\n"
"public Builder addRepeatedField(\n"
" com.google.protobuf.Descriptors.FieldDescriptor field,\n"
" Object value) {\n"
" java.lang.Object value) {\n"
" return (Builder) super.addRepeatedField(field, value);\n"
"}\n");
@@ -594,10 +584,8 @@ GenerateCommonBuilderMethods(io::Printer* printer) {
" this.mergeExtensionFields(other);\n");
}
if (PreserveUnknownFields(descriptor_)) {
printer->Print(
" this.mergeUnknownFields(other.unknownFields);\n");
}
printer->Print(
" this.mergeUnknownFields(other.unknownFields);\n");
printer->Print(
" onChanged();\n");
@@ -150,12 +150,9 @@ GenerateInterfaceMembers(io::Printer* printer) const {
// interface so that builders can choose dynamically to either return a
// message or a nested builder, so that asking for the interface doesn't
// cause a message to ever be built.
if (SupportFieldPresence(descriptor_->file()) ||
descriptor_->containing_oneof() == NULL) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$$type$ get$capitalized_name$();\n");
@@ -174,39 +171,45 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\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_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder "
"get$capitalized_name$OrBuilder() {\n"
"${$get$capitalized_name$OrBuilder$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
} else {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $name$_ != null;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder "
"get$capitalized_name$OrBuilder() {\n"
"${$get$capitalized_name$OrBuilder$}$() {\n"
" return get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
}
@@ -232,6 +235,7 @@ void ImmutableMessageFieldGenerator::PrintNestedBuilderFunction(
const char* nested_builder_case,
const char* trailing_code) const {
printer->Print(variables_, method_prototype);
printer->Annotate("{", "}", descriptor_);
printer->Print(" {\n");
printer->Indent();
PrintNestedBuilderCondition(printer, regular_case, nested_builder_case);
@@ -267,20 +271,22 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
if (support_field_presence) {
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
} else {
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $name$Builder_ != null || $name$_ != null;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
// Field getField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public $type$ get$capitalized_name$()",
"$deprecation$public $type$ ${$get$capitalized_name$$}$()",
"return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n",
"return $name$Builder_.getMessage();\n",
NULL);
@@ -288,7 +294,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder set$capitalized_name$($type$ value)",
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)",
"if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -304,7 +310,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder setField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" $type$.Builder builderForValue)",
"$name$_ = builderForValue.build();\n"
@@ -318,7 +324,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder merge$capitalized_name$($type$ value)",
"$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)",
support_field_presence
? "if ($get_has_field_bit_builder$ &&\n"
@@ -346,7 +352,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder clearField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder clear$capitalized_name$()",
"$deprecation$public Builder ${$clear$capitalized_name$$}$()",
"$name$_ = null;\n"
"$on_changed$\n",
@@ -361,14 +367,17 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n"
"$deprecation$public $type$.Builder "
"${$get$capitalized_name$Builder$}$() {\n"
" $set_has_field_bit_builder$\n"
" $on_changed$\n"
" return get$capitalized_name$FieldBuilder().getBuilder();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$() {\n"
" if ($name$Builder_ != null) {\n"
" return $name$Builder_.getMessageOrBuilder();\n"
" } else {\n"
@@ -376,6 +385,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $type$.getDefaultInstance() : $name$_;\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"private com.google.protobuf.SingleFieldBuilder$ver$<\n"
@@ -530,30 +540,32 @@ ImmutableMessageOneofFieldGenerator::
void ImmutableMessageOneofFieldGenerator::
GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
" }\n"
" return $type$.getDefaultInstance();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
" }\n"
" return $type$.getDefaultInstance();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableMessageOneofFieldGenerator::
@@ -571,19 +583,18 @@ GenerateBuilderMembers(io::Printer* printer) const {
// The comments above the methods below are based on a hypothetical
// field of type "Field" called "Field".
if (SupportFieldPresence(descriptor_->file())) {
// boolean hasField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
}
// boolean hasField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field getField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public $type$ get$capitalized_name$()",
"$deprecation$public $type$ ${$get$capitalized_name$$}$()",
"if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
@@ -600,7 +611,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder set$capitalized_name$($type$ value)",
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value)",
"if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -616,7 +627,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder setField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" $type$.Builder builderForValue)",
"$oneof_name$_ = builderForValue.build();\n"
@@ -630,7 +641,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder merge$capitalized_name$($type$ value)",
"$deprecation$public Builder ${$merge$capitalized_name$$}$($type$ value)",
"if ($has_oneof_case_message$ &&\n"
" $oneof_name$_ != $type$.getDefaultInstance()) {\n"
@@ -652,7 +663,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field.Builder clearField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder clear$capitalized_name$()",
"$deprecation$public Builder ${$clear$capitalized_name$$}$()",
"if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
@@ -670,12 +681,15 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n"
"$deprecation$public $type$.Builder "
"${$get$capitalized_name$Builder$}$() {\n"
" return get$capitalized_name$FieldBuilder().getBuilder();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$() {\n"
" if (($has_oneof_case_message$) && ($name$Builder_ != null)) {\n"
" return $name$Builder_.getMessageOrBuilder();\n"
" } else {\n"
@@ -685,11 +699,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return $type$.getDefaultInstance();\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"private com.google.protobuf.SingleFieldBuilder$ver$<\n"
" $type$, $type$.Builder, $type$OrBuilder> \n"
" get$capitalized_name$FieldBuilder() {\n"
" ${$get$capitalized_name$FieldBuilder$}$() {\n"
" if ($name$Builder_ == null) {\n"
" if (!($has_oneof_case_message$)) {\n"
" $oneof_name$_ = $type$.getDefaultInstance();\n"
@@ -705,6 +720,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$;\n"
" return $name$Builder_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableMessageOneofFieldGenerator::
@@ -833,31 +849,38 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
" get$capitalized_name$OrBuilderList() {\n"
" ${$get$capitalized_name$OrBuilderList$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$(\n"
" int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
@@ -883,6 +906,7 @@ void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderFunction(
const char* nested_builder_case,
const char* trailing_code) const {
printer->Print(variables_, method_prototype);
printer->Annotate("{", "}", descriptor_);
printer->Print(" {\n");
printer->Indent();
PrintNestedBuilderCondition(printer, regular_case, nested_builder_case);
@@ -934,7 +958,8 @@ GenerateBuilderMembers(io::Printer* printer) const {
// List<Field> getRepeatedFieldList()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public java.util.List<$type$> get$capitalized_name$List()",
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$()",
"return java.util.Collections.unmodifiableList($name$_);\n",
"return $name$Builder_.getMessageList();\n",
@@ -944,7 +969,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// int getRepeatedFieldCount()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public int get$capitalized_name$Count()",
"$deprecation$public int ${$get$capitalized_name$Count$}$()",
"return $name$_.size();\n",
"return $name$Builder_.getCount();\n",
@@ -954,7 +979,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Field getRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public $type$ get$capitalized_name$(int index)",
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index)",
"return $name$_.get(index);\n",
@@ -965,7 +990,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder setRepeatedField(int index, Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value)",
"if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -979,7 +1004,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder setRepeatedField(int index, Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$.Builder builderForValue)",
"ensure$capitalized_name$IsMutable();\n"
@@ -993,7 +1018,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addRepeatedField(Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder add$capitalized_name$($type$ value)",
"$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value)",
"if (value == null) {\n"
" throw new NullPointerException();\n"
@@ -1010,7 +1035,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addRepeatedField(int index, Field value)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder add$capitalized_name$(\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" int index, $type$ value)",
"if (value == null) {\n"
@@ -1027,7 +1052,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addRepeatedField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder add$capitalized_name$(\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" $type$.Builder builderForValue)",
"ensure$capitalized_name$IsMutable();\n"
@@ -1041,7 +1066,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addRepeatedField(int index, Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder add$capitalized_name$(\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" int index, $type$.Builder builderForValue)",
"ensure$capitalized_name$IsMutable();\n"
@@ -1055,7 +1080,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder addAllRepeatedField(Iterable<Field> values)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder addAll$capitalized_name$(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $type$> values)",
"ensure$capitalized_name$IsMutable();\n"
@@ -1070,7 +1095,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder clearAllRepeatedField()
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder clear$capitalized_name$()",
"$deprecation$public Builder ${$clear$capitalized_name$$}$()",
"$name$_ = java.util.Collections.emptyList();\n"
"$clear_mutable_bit_builder$;\n"
@@ -1083,7 +1108,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
// Builder removeRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
PrintNestedBuilderFunction(printer,
"$deprecation$public Builder remove$capitalized_name$(int index)",
"$deprecation$public Builder ${$remove$capitalized_name$$}$(int index)",
"ensure$capitalized_name$IsMutable();\n"
"$name$_.remove(index);\n"
@@ -1095,14 +1120,16 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$.Builder get$capitalized_name$Builder(\n"
"$deprecation$public $type$.Builder ${$get$capitalized_name$Builder$}$(\n"
" int index) {\n"
" return get$capitalized_name$FieldBuilder().getBuilder(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$(\n"
" int index) {\n"
" if ($name$Builder_ == null) {\n"
" return $name$_.get(index);"
@@ -1110,35 +1137,40 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return $name$Builder_.getMessageOrBuilder(index);\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
" get$capitalized_name$OrBuilderList() {\n"
" ${$get$capitalized_name$OrBuilderList$}$() {\n"
" if ($name$Builder_ != null) {\n"
" return $name$Builder_.getMessageOrBuilderList();\n"
" } else {\n"
" return java.util.Collections.unmodifiableList($name$_);\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$.Builder add$capitalized_name$Builder() {\n"
"$deprecation$public $type$.Builder "
"${$add$capitalized_name$Builder$}$() {\n"
" return get$capitalized_name$FieldBuilder().addBuilder(\n"
" $type$.getDefaultInstance());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$.Builder add$capitalized_name$Builder(\n"
"$deprecation$public $type$.Builder ${$add$capitalized_name$Builder$}$(\n"
" int index) {\n"
" return get$capitalized_name$FieldBuilder().addBuilder(\n"
" index, $type$.getDefaultInstance());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$type$.Builder> \n"
" get$capitalized_name$BuilderList() {\n"
" ${$get$capitalized_name$BuilderList$}$() {\n"
" return get$capitalized_name$FieldBuilder().getBuilderList();\n"
"}\n"
"private com.google.protobuf.RepeatedFieldBuilder$ver$<\n"
@@ -1155,6 +1187,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return $name$Builder_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutableMessageFieldGenerator::
@@ -129,16 +129,9 @@ int ImmutableMessageFieldLiteGenerator::GetNumBitsForBuilder() const {
void ImmutableMessageFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
// TODO(jonp): In the future, consider having a method specific to the
// interface so that builders can choose dynamically to either return a
// message or a nested builder, so that asking for the interface doesn't
// cause a message to ever be built.
if (SupportFieldPresence(descriptor_->file()) ||
descriptor_->containing_oneof() == NULL) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$boolean has$capitalized_name$();\n");
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$$type$ get$capitalized_name$();\n");
@@ -154,25 +147,29 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\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_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
} else {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $name$_ != null;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
// Field.Builder setField(Field value)
@@ -226,53 +223,60 @@ GenerateBuilderMembers(io::Printer* printer) const {
// boolean hasField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field getField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
" }\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(builderForValue);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder merge$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder "
"${$merge$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.merge$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder clearField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableMessageFieldLiteGenerator::
@@ -390,21 +394,21 @@ ImmutableMessageOneofFieldLiteGenerator::
void ImmutableMessageOneofFieldLiteGenerator::
GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($type$) $oneof_name$_;\n"
" }\n"
" return $type$.getDefaultInstance();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
@@ -457,58 +461,63 @@ GenerateBuilderMembers(io::Printer* printer) const {
// The comments above the methods below are based on a hypothetical
// field of type "Field" called "Field".
if (SupportFieldPresence(descriptor_->file())) {
// boolean hasField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
}
// boolean hasField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field getField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder setField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(builderForValue);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder mergeField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder merge$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder "
"${$merge$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.merge$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Field.Builder clearField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableMessageOneofFieldLiteGenerator::
@@ -615,31 +624,38 @@ GenerateMembers(io::Printer* printer) const {
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
" get$capitalized_name$OrBuilderList() {\n"
" ${$get$capitalized_name$OrBuilderList$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
"$deprecation$public $type$OrBuilder "
"${$get$capitalized_name$OrBuilder$}$(\n"
" int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
@@ -745,110 +761,123 @@ GenerateBuilderMembers(io::Printer* printer) const {
// List<Field> getRepeatedFieldList()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
"$deprecation$public java.util.List<$type$> "
"${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
" instance.get$capitalized_name$List());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// int getRepeatedFieldCount()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return instance.get$capitalized_name$Count();\n"
"}");
printer->Annotate("{", "}", descriptor_);
// Field getRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder setRepeatedField(int index, Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder setRepeatedField(int index, Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, builderForValue);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder addRepeatedField(Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder addRepeatedField(int index, Field value)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$(\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder addRepeatedField(Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$(\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(builderForValue);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder addRepeatedField(int index, Field.Builder builderForValue)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$(\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" int index, $type$.Builder builderForValue) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(index, builderForValue);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder addAllRepeatedField(Iterable<Field> values)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $type$> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder clearAllRepeatedField()
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
// Builder removeRepeatedField(int index)
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder remove$capitalized_name$(int index) {\n"
"$deprecation$public Builder ${$remove$capitalized_name$$}$(int index) {\n"
" copyOnWrite();\n"
" instance.remove$capitalized_name$(index);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutableMessageFieldLiteGenerator::
@@ -56,8 +56,9 @@
#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 {
@@ -68,6 +69,14 @@ using internal::WireFormat;
using internal::WireFormatLite;
namespace {
bool EnableExperimentalRuntimeForLite() {
#ifdef PROTOBUF_EXPERIMENT
return PROTOBUF_EXPERIMENT;
#else // PROTOBUF_EXPERIMENT
return false;
#endif // !PROTOBUF_EXPERIMENT
}
bool GenerateHasBits(const Descriptor* descriptor) {
return SupportFieldPresence(descriptor->file()) ||
HasRepeatedFields(descriptor);
@@ -124,7 +133,7 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) {
/* immutable = */ true, "OrBuilder");
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"$deprecation$public interface $classname$OrBuilder$idend$ extends \n"
"$deprecation$public interface ${$$classname$OrBuilder$}$ extends \n"
" $extra_interfaces$\n"
" com.google.protobuf.GeneratedMessageLite.\n"
" ExtendableMessageOrBuilder<\n"
@@ -133,19 +142,19 @@ void ImmutableMessageLiteGenerator::GenerateInterface(io::Printer* printer) {
"@java.lang.Deprecated " : "",
"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
"classname", descriptor_->name(),
"idend", "");
"{", "", "}", "");
} else {
printer->Print(
"$deprecation$public interface $classname$OrBuilder$idend$ extends\n"
"$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n"
" $extra_interfaces$\n"
" com.google.protobuf.MessageLiteOrBuilder {\n",
"deprecation", descriptor_->options().deprecated() ?
"@java.lang.Deprecated " : "",
"extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
"classname", descriptor_->name(),
"idend", "");
"{", "", "}", "");
}
printer->Annotate("classname", "idend", descriptor_);
printer->Annotate("{", "}", descriptor_);
printer->Indent();
for (int i = 0; i < descriptor_->field_count(); i++) {
@@ -331,41 +340,43 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Print("\n");
}
GenerateMessageSerializationMethods(printer);
if (!EnableExperimentalRuntime(context_)) {
GenerateMessageSerializationMethods(printer);
}
GenerateParseFromMethods(printer);
GenerateBuilder(printer);
if (HasRequiredFields(descriptor_)) {
// Memoizes whether the protocol buffer is fully initialized (has all
// required fields). -1 means not yet computed. 0 means false and 1 means
// true.
// required fields). 0 means false, 1 means true, and all other values
// mean not yet computed.
printer->Print(
"private byte memoizedIsInitialized = -1;\n");
"private byte memoizedIsInitialized = 2;\n");
}
printer->Print(
"@java.lang.SuppressWarnings({\"unchecked\", \"fallthrough\"})\n"
"protected final Object dynamicMethod(\n"
" com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,\n"
" Object arg0, Object arg1) {\n"
" switch (method) {\n"
" case NEW_MUTABLE_INSTANCE: {\n"
" return new $classname$();\n"
" }\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
"@java.lang.SuppressWarnings({\"unchecked\", \"fallthrough\"})\n"
"protected final java.lang.Object dynamicMethod(\n"
" com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,\n"
" java.lang.Object arg0, java.lang.Object arg1) {\n"
" switch (method) {\n"
" case NEW_MUTABLE_INSTANCE: {\n"
" return new $classname$();\n"
" }\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Indent();
printer->Indent();
printer->Print(
"case IS_INITIALIZED: {\n");
printer->Print("case IS_INITIALIZED: {\n");
printer->Indent();
GenerateDynamicMethodIsInitialized(printer);
printer->Outdent();
printer->Print("}\n");
printer->Print(
"}\n"
"case MAKE_IMMUTABLE: {\n");
printer->Indent();
@@ -380,13 +391,15 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
GenerateDynamicMethodNewBuilder(printer);
printer->Outdent();
printer->Print(
"}\n"
"case VISIT: {\n");
if (!EnableExperimentalRuntimeForLite()) {
printer->Print(
"}\n"
"case VISIT: {\n");
printer->Indent();
GenerateDynamicMethodVisit(printer);
printer->Outdent();
printer->Indent();
GenerateDynamicMethodVisit(printer);
printer->Outdent();
}
printer->Print(
"}\n"
@@ -414,13 +427,33 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
" }\n"
" }\n"
" }\n"
" return PARSER;\n"
"}\n",
" return PARSER;\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
printer->Outdent();
printer->Outdent();
if (HasRequiredFields(descriptor_)) {
printer->Print(
"}\n"
"case GET_MEMOIZED_IS_INITIALIZED: {\n"
" return memoizedIsInitialized;\n"
"}\n"
"case SET_MEMOIZED_IS_INITIALIZED: {\n"
" memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1);\n"
" return null;\n"
"}\n");
} else {
printer->Print(
"}\n"
"case GET_MEMOIZED_IS_INITIALIZED: {\n"
" return (byte) 1;\n"
"}\n"
"case SET_MEMOIZED_IS_INITIALIZED: {\n"
" return null;\n"
"}\n");
}
printer->Outdent();
printer->Print(
" }\n"
" throw new UnsupportedOperationException();\n"
@@ -447,6 +480,17 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
"}\n"
"\n",
"classname", descriptor_->name());
if (EnableExperimentalRuntimeForLite()) {
// Register the default instance in a map. This map will be used by
// experimental runtime to lookup default instance given a class instance
// without using Java reflection.
printer->Print(
"static {\n"
" com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(\n"
" $classname$.class, DEFAULT_INSTANCE);\n"
"}\n",
"classname", descriptor_->name());
}
printer->Print(
"public static $classname$ getDefaultInstance() {\n"
" return DEFAULT_INSTANCE;\n"
@@ -454,6 +498,17 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
// 'of' method for Wrappers
if (IsWrappersProtoFile(descriptor_->file())) {
printer->Print(
"public static $classname$ of($field_type$ value) {\n"
" return newBuilder().setValue(value).build();\n"
"}\n"
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_),
"field_type", PrimitiveTypeName(GetJavaType(descriptor_->field(0))));
}
GenerateParser(printer);
// Extensions must be declared after the DEFAULT_INSTANCE is initialized
@@ -468,6 +523,7 @@ void ImmutableMessageLiteGenerator::Generate(io::Printer* printer) {
printer->Print("}\n\n");
}
// ===================================================================
void ImmutableMessageLiteGenerator::
@@ -489,36 +545,34 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
if (HasPackedFields(descriptor_)) {
// writeTo(CodedOutputStream output) might be invoked without
// getSerializedSize() ever being called, but we need the memoized
// sizes in case this message has packed fields. Rather than emit checks for
// each packed field, just call getSerializedSize() up front.
// In most cases, getSerializedSize() will have already been called anyway
// by one of the wrapper writeTo() methods, making this call cheap.
printer->Print(
"getSerializedSize();\n");
// sizes in case this message has packed fields. Rather than emit checks
// for each packed field, just call getSerializedSize() up front. In most
// cases, getSerializedSize() will have already been called anyway by one
// of the wrapper writeTo() methods, making this call cheap.
printer->Print("getSerializedSize();\n");
}
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"com.google.protobuf.GeneratedMessageLite\n"
" .ExtendableMessage<$classname$, $classname$.Builder>\n"
" .ExtensionWriter extensionWriter =\n"
" newMessageSetExtensionWriter();\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
"com.google.protobuf.GeneratedMessageLite\n"
" .ExtendableMessage<$classname$, $classname$.Builder>\n"
" .ExtensionWriter extensionWriter =\n"
" newMessageSetExtensionWriter();\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
} else {
printer->Print(
"com.google.protobuf.GeneratedMessageLite\n"
" .ExtendableMessage<$classname$, $classname$.Builder>\n"
" .ExtensionWriter extensionWriter =\n"
" newExtensionWriter();\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
"com.google.protobuf.GeneratedMessageLite\n"
" .ExtendableMessage<$classname$, $classname$.Builder>\n"
" .ExtensionWriter extensionWriter =\n"
" newExtensionWriter();\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
}
}
// Merge the fields and the extension ranges, both sorted by field number.
for (int i = 0, j = 0;
i < descriptor_->field_count() || j < sorted_extensions.size();
) {
i < descriptor_->field_count() || j < sorted_extensions.size();) {
if (i == descriptor_->field_count()) {
GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
} else if (j == sorted_extensions.size()) {
@@ -530,26 +584,23 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
}
}
if (PreserveUnknownFields(descriptor_)) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"unknownFields.writeAsMessageSetTo(output);\n");
} else {
printer->Print(
"unknownFields.writeTo(output);\n");
}
if (descriptor_->options().message_set_wire_format()) {
printer->Print("unknownFields.writeAsMessageSetTo(output);\n");
} else {
printer->Print("unknownFields.writeTo(output);\n");
}
printer->Outdent();
printer->Print(
"}\n"
"\n"
"public int getSerializedSize() {\n"
" int size = memoizedSerializedSize;\n"
" if (size != -1) return size;\n"
"\n"
" size = 0;\n");
"}\n"
"\n"
"public int getSerializedSize() {\n"
" int size = memoizedSerializedSize;\n"
" if (size != -1) return size;\n"
"\n");
printer->Indent();
printer->Print(
"size = 0;\n");
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer);
@@ -557,28 +608,24 @@ GenerateMessageSerializationMethods(io::Printer* printer) {
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"size += extensionsSerializedSizeAsMessageSet();\n");
printer->Print("size += extensionsSerializedSizeAsMessageSet();\n");
} else {
printer->Print(
"size += extensionsSerializedSize();\n");
printer->Print("size += extensionsSerializedSize();\n");
}
}
if (PreserveUnknownFields(descriptor_)) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
"size += unknownFields.getSerializedSizeAsMessageSet();\n");
} else {
printer->Print(
"size += unknownFields.getSerializedSize();\n");
}
if (descriptor_->options().message_set_wire_format()) {
printer->Print("size += unknownFields.getSerializedSizeAsMessageSet();\n");
} else {
printer->Print("size += unknownFields.getSerializedSize();\n");
}
printer->Print(
"memoizedSerializedSize = size;\n"
"return size;\n");
printer->Outdent();
printer->Print(
" memoizedSerializedSize = size;\n"
" return size;\n"
"}\n"
"\n");
}
@@ -683,10 +730,10 @@ void ImmutableMessageLiteGenerator::GenerateSerializeOneExtensionRange(
void ImmutableMessageLiteGenerator::GenerateBuilder(io::Printer* printer) {
printer->Print(
"public static Builder newBuilder() {\n"
" return DEFAULT_INSTANCE.toBuilder();\n"
" return (Builder) DEFAULT_INSTANCE.createBuilder();\n"
"}\n"
"public static Builder newBuilder($classname$ prototype) {\n"
" return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n"
" return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);\n"
"}\n"
"\n",
"classname", name_resolver_->GetImmutableClassName(descriptor_));
@@ -705,7 +752,10 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
return;
}
// Don't directly compare to -1 to avoid an Android x86 JIT bug.
// TODO(xiaofeng): Remove this when b/64445758 is fixed. We don't need to
// check memoizedIsInitialized here because the caller does that already,
// but right now proguard proto shrinker asserts on the bytecode layout of
// this code so it can't be removed until proguard is updated.
printer->Print(
"byte isInitialized = memoizedIsInitialized;\n"
"if (isInitialized == 1) return DEFAULT_INSTANCE;\n"
@@ -723,9 +773,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
if (field->is_required()) {
printer->Print(
"if (!has$name$()) {\n"
" if (shouldMemoize) {\n"
" memoizedIsInitialized = 0;\n"
" }\n"
" return null;\n"
"}\n",
"name", info->capitalized_name);
@@ -742,9 +789,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
case FieldDescriptor::LABEL_REQUIRED:
printer->Print(
"if (!get$name$().isInitialized()) {\n"
" if (shouldMemoize) {\n"
" memoizedIsInitialized = 0;\n"
" }\n"
" return null;\n"
"}\n",
"type", name_resolver_->GetImmutableClassName(
@@ -768,9 +812,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
}
printer->Print(
" if (!get$name$().isInitialized()) {\n"
" if (shouldMemoize) {\n"
" memoizedIsInitialized = 0;\n"
" }\n"
" return null;\n"
" }\n"
"}\n",
@@ -781,9 +822,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
printer->Print(
"for ($type$ item : get$name$Map().values()) {\n"
" if (!item.isInitialized()) {\n"
" if (shouldMemoize) {\n"
" memoizedIsInitialized = 0;\n"
" }\n"
" return null;\n"
" }\n"
"}\n",
@@ -794,9 +832,6 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
printer->Print(
"for (int i = 0; i < get$name$Count(); i++) {\n"
" if (!get$name$(i).isInitialized()) {\n"
" if (shouldMemoize) {\n"
" memoizedIsInitialized = 0;\n"
" }\n"
" return null;\n"
" }\n"
"}\n",
@@ -812,16 +847,10 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodIsInitialized(
if (descriptor_->extension_range_count() > 0) {
printer->Print(
"if (!extensionsAreInitialized()) {\n"
" if (shouldMemoize) {\n"
" memoizedIsInitialized = 0;\n"
" }\n"
" return null;\n"
"}\n");
}
printer->Print(
"if (shouldMemoize) memoizedIsInitialized = 1;\n");
printer->Print(
"return DEFAULT_INSTANCE;\n"
"\n");
@@ -949,26 +978,33 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
"com.google.protobuf.CodedInputStream input =\n"
" (com.google.protobuf.CodedInputStream) arg0;\n"
"com.google.protobuf.ExtensionRegistryLite extensionRegistry =\n"
" (com.google.protobuf.ExtensionRegistryLite) arg1;\n");
" (com.google.protobuf.ExtensionRegistryLite) arg1;\n"
"if (extensionRegistry == null) {\n"
" throw new java.lang.NullPointerException();\n"
"}\n");
printer->Print(
"try {\n");
printer->Indent();
printer->Print(
"boolean done = false;\n"
"while (!done) {\n");
printer->Indent();
if (EnableExperimentalRuntime(context_)) {
printer->Print(
"mergeFromInternal(input, extensionRegistry);\n"
"return DEFAULT_INSTANCE;\n");
} else {
printer->Print(
"boolean done = false;\n"
"while (!done) {\n");
printer->Indent();
printer->Print(
"int tag = input.readTag();\n"
"switch (tag) {\n");
printer->Indent();
printer->Print(
"int tag = input.readTag();\n"
"switch (tag) {\n");
printer->Indent();
printer->Print(
"case 0:\n" // zero signals EOF / limit reached
" done = true;\n"
" break;\n");
printer->Print(
"case 0:\n" // zero signals EOF / limit reached
" done = true;\n"
" break;\n");
if (PreserveUnknownFields(descriptor_)) {
if (descriptor_->extension_range_count() > 0) {
if (descriptor_->options().message_set_wire_format()) {
printer->Print(
@@ -992,66 +1028,57 @@ void ImmutableMessageLiteGenerator::GenerateDynamicMethodMergeFromStream(
}
} else {
printer->Print(
"default: {\n"
" if (!parseUnknownField(tag, input)) {\n"
" done = true;\n" // it's an endgroup tag
" }\n"
" break;\n"
"}\n");
"default: {\n"
" if (!parseUnknownField(tag, input)) {\n"
" done = true;\n" // it's an endgroup tag
" }\n"
" break;\n"
"}\n");
}
} else {
printer->Print(
"default: {\n"
" if (!input.skipField(tag)) {\n"
" done = true;\n" // it's an endgroup tag
" }\n"
" break;\n"
"}\n");
}
google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields(
SortFieldsByNumber(descriptor_));
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = sorted_fields[i];
uint32 tag = WireFormatLite::MakeTag(field->number(),
WireFormat::WireTypeForFieldType(field->type()));
google::protobuf::scoped_array<const FieldDescriptor* > sorted_fields(
SortFieldsByNumber(descriptor_));
for (int i = 0; i < descriptor_->field_count(); i++) {
const FieldDescriptor* field = sorted_fields[i];
uint32 tag = WireFormatLite::MakeTag(
field->number(), WireFormat::WireTypeForFieldType(field->type()));
printer->Print(
"case $tag$: {\n",
"tag", SimpleItoa(static_cast<int32>(tag)));
printer->Indent();
field_generators_.get(field).GenerateParsingCode(printer);
printer->Outdent();
printer->Print(
" break;\n"
"}\n");
if (field->is_packable()) {
// To make packed = true wire compatible, we generate parsing code from a
// packed version of this field regardless of field->options().packed().
uint32 packed_tag = WireFormatLite::MakeTag(field->number(),
WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
printer->Print(
"case $tag$: {\n",
"tag", SimpleItoa(static_cast<int32>(packed_tag)));
printer->Print("case $tag$: {\n", "tag",
SimpleItoa(static_cast<int32>(tag)));
printer->Indent();
field_generators_.get(field).GenerateParsingCodeFromPacked(printer);
field_generators_.get(field).GenerateParsingCode(printer);
printer->Outdent();
printer->Print(
" break;\n"
"}\n");
}
}
printer->Outdent();
printer->Outdent();
printer->Print(
" }\n" // switch (tag)
"}\n"); // while (!done)
if (field->is_packable()) {
// To make packed = true wire compatible, we generate parsing code from
// a packed version of this field regardless of
// field->options().packed().
uint32 packed_tag = WireFormatLite::MakeTag(
field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
printer->Print("case $tag$: {\n", "tag",
SimpleItoa(static_cast<int32>(packed_tag)));
printer->Indent();
field_generators_.get(field).GenerateParsingCodeFromPacked(printer);
printer->Outdent();
printer->Print(
" break;\n"
"}\n");
}
}
printer->Outdent();
printer->Outdent();
printer->Print(
" }\n" // switch (tag)
"}\n"); // while (!done)
}
printer->Outdent();
printer->Print(
@@ -33,6 +33,7 @@
#include <map>
#include <string>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/stubs/substitute.h>
@@ -59,10 +59,10 @@ struct Options {
bool annotate_code;
// Name of a file where we will write a list of generated .meta file names,
// one per line.
string annotation_list_file;
std::string annotation_list_file;
// Name of a file where we will write a list of generated file names, one
// per line.
string output_list_file;
std::string output_list_file;
};
} // namespace java
@@ -190,16 +190,18 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\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_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutablePrimitiveFieldGenerator::
@@ -210,31 +212,35 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
"$null_check$"
" $set_has_field_bit_builder$\n"
" $name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $clear_has_field_bit_builder$\n");
printer->Annotate("{", "}", descriptor_);
JavaType type = GetJavaType(descriptor_);
if (type == JAVATYPE_STRING || type == JAVATYPE_BYTES) {
// The default value is not a simple literal so we want to avoid executing
@@ -441,19 +447,21 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($boxed_type$) $oneof_name$_;\n"
" }\n"
" return $default$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
@@ -462,33 +470,36 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($boxed_type$) $oneof_name$_;\n"
" }\n"
" return $default$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
"$null_check$"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = value;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
" $oneof_name$_ = null;\n"
@@ -496,6 +507,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutablePrimitiveOneofFieldGenerator::
@@ -604,19 +616,22 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
" get$capitalized_name$List() {\n"
" ${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (descriptor_->is_packed() &&
context_->HasGeneratedMethods(descriptor_->containing_type())) {
@@ -654,22 +669,25 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
" get$capitalized_name$List() {\n"
" ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList($name$_);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
@@ -677,18 +695,20 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
" $name$_.add(value);\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $boxed_type$> values) {\n"
" ensure$capitalized_name$IsMutable();\n"
" com.google.protobuf.AbstractMessageLite.Builder.addAll(\n"
@@ -696,14 +716,16 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $name$_ = $empty_list$;\n"
" $clear_mutable_bit_builder$;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutablePrimitiveFieldGenerator::
@@ -222,16 +222,18 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\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_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
@@ -264,32 +266,36 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutablePrimitiveFieldLiteGenerator::
@@ -482,19 +488,21 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" return ($boxed_type$) $oneof_name$_;\n"
" }\n"
" return $default$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
@@ -520,32 +528,36 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$() {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutablePrimitiveOneofFieldLiteGenerator::
@@ -634,21 +646,24 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
" get$capitalized_name$List() {\n"
" ${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return $repeated_get$(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
if (descriptor_->options().packed() &&
if (descriptor_->is_packed() &&
context_->HasGeneratedMethods(descriptor_->containing_type())) {
printer->Print(variables_,
"private int $name$MemoizedSerializedSize = -1;\n");
@@ -697,50 +712,57 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<$boxed_type$>\n"
" get$capitalized_name$List() {\n"
" ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
" instance.get$capitalized_name$List());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\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_,
"$deprecation$public $type$ get$capitalized_name$(int index) {\n"
"$deprecation$public $type$ ${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, $type$ value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$($type$ value) {\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$($type$ value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<? extends $boxed_type$> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutablePrimitiveFieldLiteGenerator::
@@ -829,7 +851,7 @@ GenerateParsingDoneCode(io::Printer* printer) const {
void RepeatedImmutablePrimitiveFieldLiteGenerator::
GenerateSerializationCode(io::Printer* printer) const {
if (descriptor_->options().packed()) {
if (descriptor_->is_packed()) {
// We invoke getSerializedSize in writeTo for messages that have packed
// fields in ImmutableMessageGenerator::GenerateMessageSerializationMethods.
// That makes it safe to rely on the memoized size here.
@@ -870,7 +892,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
printer->Print(
"size += dataSize;\n");
if (descriptor_->options().packed()) {
if (descriptor_->is_packed()) {
printer->Print(variables_,
"if (!get$capitalized_name$List().isEmpty()) {\n"
" size += $tag_size$;\n"
@@ -883,7 +905,7 @@ GenerateSerializedSizeCode(io::Printer* printer) const {
}
// cache the data size for packed fields.
if (descriptor_->options().packed()) {
if (descriptor_->is_packed()) {
printer->Print(variables_,
"$name$MemoizedSerializedSize = dataSize;\n");
}
@@ -140,13 +140,16 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
"java.lang.String[] descriptorData = {\n");
printer->Indent();
// Only write 40 bytes per line.
// Limit the number of bytes per line.
static const int kBytesPerLine = 40;
// Limit the number of lines per string part.
static const int kLinesPerPart = 400;
// Every block of bytes, start a new string literal, in order to avoid the
// 64k length limit. Note that this value needs to be <64k.
static const int kBytesPerPart = kBytesPerLine * kLinesPerPart;
for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
if (i > 0) {
// Every 400 lines, start a new string literal, in order to avoid the
// 64k length limit.
if (i % 400 == 0) {
if (i % kBytesPerPart == 0) {
printer->Print(",\n");
} else {
printer->Print(" +\n");
@@ -182,10 +185,16 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
std::vector<std::pair<string, string> > dependencies;
for (int i = 0; i < file_->dependency_count(); i++) {
string filename = file_->dependency(i)->name();
string classname = FileJavaPackage(file_->dependency(i)) + "." +
name_resolver_->GetDescriptorClassName(
file_->dependency(i));
dependencies.push_back(std::make_pair(filename, classname));
string package = FileJavaPackage(file_->dependency(i));
string classname = name_resolver_->GetDescriptorClassName(
file_->dependency(i));
string full_name;
if (package.empty()) {
full_name = classname;
} else {
full_name = package + "." + classname;
}
dependencies.push_back(std::make_pair(filename, full_name));
}
// -----------------------------------------------------------------
@@ -217,14 +217,15 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\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_,
"$deprecation$public java.lang.String get$capitalized_name$() {\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (ref instanceof java.lang.String) {\n"
" return (java.lang.String) ref;\n"
@@ -232,6 +233,7 @@ GenerateMembers(io::Printer* printer) const {
" com.google.protobuf.ByteString bs = \n"
" (com.google.protobuf.ByteString) ref;\n"
" java.lang.String s = bs.toStringUtf8();\n");
printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" $name$_ = s;\n");
@@ -248,7 +250,7 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes() {\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (ref instanceof java.lang.String) {\n"
" com.google.protobuf.ByteString b = \n"
@@ -260,6 +262,7 @@ GenerateMembers(io::Printer* printer) const {
" return (com.google.protobuf.ByteString) ref;\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableStringFieldGenerator::
@@ -269,19 +272,21 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $get_has_field_bit_builder$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$() {\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (!(ref instanceof java.lang.String)) {\n"
" com.google.protobuf.ByteString bs =\n"
" (com.google.protobuf.ByteString) ref;\n"
" java.lang.String s = bs.toStringUtf8();\n");
printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" $name$_ = s;\n");
@@ -301,7 +306,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes() {\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref = $name$_;\n"
" if (ref instanceof String) {\n"
" com.google.protobuf.ByteString b = \n"
@@ -313,10 +318,11 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return (com.google.protobuf.ByteString) ref;\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
"$null_check$"
" $set_has_field_bit_builder$\n"
@@ -324,10 +330,12 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $clear_has_field_bit_builder$\n");
printer->Annotate("{", "}", descriptor_);
// The default value is not a simple literal so we want to avoid executing
// it multiple times. Instead, get the default out of the default instance.
printer->Print(variables_,
@@ -339,9 +347,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Bytes(\n"
"$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
"$null_check$");
printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" checkByteStringIsUtf8(value);\n");
@@ -482,14 +491,15 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$() {\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = $oneof_name$_;\n"
@@ -500,6 +510,7 @@ GenerateMembers(io::Printer* printer) const {
" com.google.protobuf.ByteString bs = \n"
" (com.google.protobuf.ByteString) ref;\n"
" java.lang.String s = bs.toStringUtf8();\n");
printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" if ($has_oneof_case_message$) {\n"
@@ -519,7 +530,7 @@ GenerateMembers(io::Printer* printer) const {
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes() {\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = $oneof_name$_;\n"
@@ -536,6 +547,7 @@ GenerateMembers(io::Printer* printer) const {
" return (com.google.protobuf.ByteString) ref;\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableStringOneofFieldGenerator::
@@ -543,14 +555,15 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$() {\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = $oneof_name$_;\n"
@@ -560,6 +573,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
" (com.google.protobuf.ByteString) ref;\n"
" java.lang.String s = bs.toStringUtf8();\n"
" if ($has_oneof_case_message$) {\n");
printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" $oneof_name$_ = s;\n");
@@ -580,7 +594,7 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes() {\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.Object ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = $oneof_name$_;\n"
@@ -597,10 +611,11 @@ GenerateBuilderMembers(io::Printer* printer) const {
" return (com.google.protobuf.ByteString) ref;\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
"$null_check$"
" $set_oneof_case_message$;\n"
@@ -608,9 +623,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
" $oneof_name$_ = null;\n"
@@ -618,12 +634,14 @@ GenerateBuilderMembers(io::Printer* printer) const {
" }\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Bytes(\n"
"$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
"$null_check$");
printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" checkByteStringIsUtf8(value);\n");
@@ -744,25 +762,30 @@ GenerateMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ProtocolStringList\n"
" get$capitalized_name$List() {\n"
" ${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
"$deprecation$public java.lang.String "
"${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes(int index) {\n"
" ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return $name$_.getByteString(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutableStringFieldGenerator::
@@ -794,28 +817,33 @@ GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ProtocolStringList\n"
" get$capitalized_name$List() {\n"
" ${$get$capitalized_name$List$}$() {\n"
" return $name$_.getUnmodifiableView();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
"$deprecation$public java.lang.String "
"${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes(int index) {\n"
" ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return $name$_.getByteString(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, java.lang.String value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
@@ -823,9 +851,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$(\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
"$null_check$"
" ensure$capitalized_name$IsMutable();\n"
@@ -833,9 +862,10 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<java.lang.String> values) {\n"
" ensure$capitalized_name$IsMutable();\n"
" com.google.protobuf.AbstractMessageLite.Builder.addAll(\n"
@@ -843,20 +873,23 @@ GenerateBuilderMembers(io::Printer* printer) const {
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" $name$_ = $empty_list$;\n"
" $clear_mutable_bit_builder$;\n"
" $on_changed$\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$Bytes(\n"
"$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
"$null_check$");
printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" checkByteStringIsUtf8(value);\n");
@@ -71,7 +71,7 @@ void SetPrimitiveVariables(const FieldDescriptor* descriptor,
(*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver);
(*variables)["default_init"] =
"= " + ImmutableDefaultValue(descriptor, name_resolver);
(*variables)["capitalized_type"] = "String";
(*variables)["capitalized_type"] = "java.lang.String";
(*variables)["tag"] =
SimpleItoa(static_cast<int32>(WireFormat::MakeTag(descriptor)));
(*variables)["tag_size"] = SimpleItoa(
@@ -192,22 +192,25 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\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_,
"$deprecation$public java.lang.String get$capitalized_name$() {\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return $name$_;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes() {\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" return com.google.protobuf.ByteString.copyFromUtf8($name$_);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
@@ -246,48 +249,54 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$() {\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes() {\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" return instance.get$capitalized_name$Bytes();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Bytes(\n"
"$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Bytes(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableStringFieldLiteGenerator::
@@ -324,7 +333,7 @@ void ImmutableStringFieldLiteGenerator::
GenerateParsingCode(io::Printer* printer) const {
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
"String s = input.readStringRequireUtf8();\n"
"java.lang.String s = input.readStringRequireUtf8();\n"
"$set_has_field_bit_message$\n"
"$name$_ = s;\n");
} else {
@@ -333,7 +342,7 @@ GenerateParsingCode(io::Printer* printer) const {
// spurious intermediary ByteString allocations, cutting overall allocations
// in half.
printer->Print(variables_,
"String s = input.readString();\n"
"java.lang.String s = input.readString();\n"
"$set_has_field_bit_message$\n"
"$name$_ = s;\n");
}
@@ -410,54 +419,60 @@ GenerateMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return $has_oneof_case_message$;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$() {\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" java.lang.String ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = (java.lang.String) $oneof_name$_;\n"
" }\n"
" return ref;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes() {\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" java.lang.String ref $default_init$;\n"
" if ($has_oneof_case_message$) {\n"
" ref = (java.lang.String) $oneof_name$_;\n"
" }\n"
" return com.google.protobuf.ByteString.copyFromUtf8(ref);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"private void set$capitalized_name$(\n"
"private void ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
"$null_check$"
" $set_oneof_case_message$;\n"
" $oneof_name$_ = value;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"private void clear$capitalized_name$() {\n"
"private void ${$clear$capitalized_name$$}$() {\n"
" if ($has_oneof_case_message$) {\n"
" $clear_oneof_case_message$;\n"
" $oneof_name$_ = null;\n"
" }\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"private void set$capitalized_name$Bytes(\n"
"private void ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
"$null_check$");
printer->Annotate("{", "}", descriptor_);
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
" checkByteStringIsUtf8(value);\n");
@@ -474,48 +489,54 @@ GenerateBuilderMembers(io::Printer* printer) const {
if (SupportFieldPresence(descriptor_->file())) {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public boolean has$capitalized_name$() {\n"
"$deprecation$public boolean ${$has$capitalized_name$$}$() {\n"
" return instance.has$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$() {\n"
"$deprecation$public java.lang.String ${$get$capitalized_name$$}$() {\n"
" return instance.get$capitalized_name$();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes() {\n"
" ${$get$capitalized_name$Bytes$}$() {\n"
" return instance.get$capitalized_name$Bytes();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$Bytes(\n"
"$deprecation$public Builder ${$set$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$Bytes(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void ImmutableStringOneofFieldLiteGenerator::
@@ -529,7 +550,7 @@ void ImmutableStringOneofFieldLiteGenerator::
GenerateParsingCode(io::Printer* printer) const {
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
"String s = input.readStringRequireUtf8();\n"
"java.lang.String s = input.readStringRequireUtf8();\n"
"$set_oneof_case_message$;\n"
"$oneof_name$_ = s;\n");
} else {
@@ -538,7 +559,7 @@ GenerateParsingCode(io::Printer* printer) const {
// spurious intermediary ByteString allocations, cutting overall allocations
// in half.
printer->Print(variables_,
"String s = input.readString();\n"
"java.lang.String s = input.readString();\n"
"$set_oneof_case_message$;\n"
"$oneof_name$_ = s;\n");
}
@@ -597,7 +618,7 @@ void RepeatedImmutableStringFieldLiteGenerator::
GenerateInterfaceMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$java.util.List<String>\n"
"$deprecation$java.util.List<java.lang.String>\n"
" get$capitalized_name$List();\n");
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
@@ -615,30 +636,37 @@ GenerateInterfaceMembers(io::Printer* printer) const {
void RepeatedImmutableStringFieldLiteGenerator::
GenerateMembers(io::Printer* printer) const {
printer->Print(variables_,
"private com.google.protobuf.Internal.ProtobufList<String> $name$_;\n");
"private com.google.protobuf.Internal.ProtobufList<java.lang.String> "
"$name$_;\n");
PrintExtraFieldInfo(variables_, printer);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<String> get$capitalized_name$List() {\n"
" return $name$_;\n" // note: unmodifiable list
"$deprecation$public java.util.List<java.lang.String> "
"${$get$capitalized_name$List$}$() {\n"
" return $name$_;\n" // note: unmodifiable list
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\n"
"$deprecation$public int ${$get$capitalized_name$Count$}$() {\n"
" return $name$_.size();\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
"$deprecation$public java.lang.String "
"${$get$capitalized_name$$}$(int index) {\n"
" return $name$_.get(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes(int index) {\n"
" ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return com.google.protobuf.ByteString.copyFromUtf8(\n"
" $name$_.get(index));\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
printer->Print(variables_,
"private void ensure$capitalized_name$IsMutable() {\n"
@@ -697,67 +725,77 @@ void RepeatedImmutableStringFieldLiteGenerator::
GenerateBuilderMembers(io::Printer* printer) const {
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public java.util.List<String>\n"
" get$capitalized_name$List() {\n"
"$deprecation$public java.util.List<java.lang.String>\n"
" ${$get$capitalized_name$List$}$() {\n"
" return java.util.Collections.unmodifiableList(\n"
" instance.get$capitalized_name$List());\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public int get$capitalized_name$Count() {\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_,
"$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
"$deprecation$public java.lang.String "
"${$get$capitalized_name$$}$(int index) {\n"
" return instance.get$capitalized_name$(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public com.google.protobuf.ByteString\n"
" get$capitalized_name$Bytes(int index) {\n"
" ${$get$capitalized_name$Bytes$}$(int index) {\n"
" return instance.get$capitalized_name$Bytes(index);\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder set$capitalized_name$(\n"
"$deprecation$public Builder ${$set$capitalized_name$$}$(\n"
" int index, java.lang.String value) {\n"
" copyOnWrite();\n"
" instance.set$capitalized_name$(index, value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$(\n"
"$deprecation$public Builder ${$add$capitalized_name$$}$(\n"
" java.lang.String value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder addAll$capitalized_name$(\n"
"$deprecation$public Builder ${$addAll$capitalized_name$$}$(\n"
" java.lang.Iterable<java.lang.String> values) {\n"
" copyOnWrite();\n"
" instance.addAll$capitalized_name$(values);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder clear$capitalized_name$() {\n"
"$deprecation$public Builder ${$clear$capitalized_name$$}$() {\n"
" copyOnWrite();\n"
" instance.clear$capitalized_name$();\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
WriteFieldDocComment(printer, descriptor_);
printer->Print(variables_,
"$deprecation$public Builder add$capitalized_name$Bytes(\n"
"$deprecation$public Builder ${$add$capitalized_name$Bytes$}$(\n"
" com.google.protobuf.ByteString value) {\n"
" copyOnWrite();\n"
" instance.add$capitalized_name$Bytes(value);\n"
" return this;\n"
"}\n");
printer->Annotate("{", "}", descriptor_);
}
void RepeatedImmutableStringFieldLiteGenerator::
@@ -787,14 +825,14 @@ void RepeatedImmutableStringFieldLiteGenerator::
GenerateParsingCode(io::Printer* printer) const {
if (CheckUtf8(descriptor_)) {
printer->Print(variables_,
"String s = input.readStringRequireUtf8();\n");
"java.lang.String s = input.readStringRequireUtf8();\n");
} else {
// Lite runtime should attempt to reduce allocations by attempting to
// construct the string directly from the input stream buffer. This avoids
// spurious intermediary ByteString allocations, cutting overall allocations
// in half.
printer->Print(variables_,
"String s = input.readString();\n");
"java.lang.String s = input.readString();\n");
}
printer->Print(variables_,
"if (!$is_mutable$) {\n"
@@ -868,7 +906,7 @@ GenerateHashCode(io::Printer* printer) const {
}
string RepeatedImmutableStringFieldLiteGenerator::GetBoxedType() const {
return "String";
return "java.lang.String";
}
} // namespace java
@@ -52,7 +52,7 @@ 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, map<string, string>* variables) {
const FieldDescriptor* descriptor, std::map<string, string>* variables) {
(*variables)["name"] =
RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
(*variables)["capitalized_name"] =
@@ -62,7 +62,7 @@ class EnumFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator);
@@ -85,7 +85,7 @@ class AccessorEnumFieldGenerator : public FieldGenerator {
private:
const FieldDescriptor* descriptor_;
map<string, string> variables_;
std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorEnumFieldGenerator);
@@ -112,7 +112,7 @@ class RepeatedEnumFieldGenerator : public FieldGenerator {
void GenerateRepeatedDataSizeCode(io::Printer* printer) const;
const FieldDescriptor* descriptor_;
map<string, string> variables_;
std::map<string, string> variables_;
vector<string> canonical_values_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
@@ -78,7 +78,7 @@ const char* GetTypeConstantName(const FieldDescriptor::Type type) {
} // namespace
void SetVariables(const FieldDescriptor* descriptor, const Params params,
map<string, string>* variables) {
std::map<string, string>* variables) {
(*variables)["extends"] = ClassName(params, descriptor->containing_type());
(*variables)["name"] = RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
bool repeated = descriptor->is_repeated();
@@ -61,7 +61,7 @@ class ExtensionGenerator {
private:
const Params& params_;
const FieldDescriptor* descriptor_;
map<string, string> variables_;
std::map<string, string> variables_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator);
};
@@ -151,7 +151,7 @@ const FieldGenerator& FieldGeneratorMap::get(
}
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
map<string, string>* variables) {
std::map<string, string>* variables) {
(*variables)["oneof_name"] =
UnderscoresToCamelCase(descriptor->containing_oneof());
(*variables)["oneof_capitalized_name"] =
@@ -169,7 +169,7 @@ void SetCommonOneofVariables(const FieldDescriptor* descriptor,
}
void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
const map<string, string>& variables,
const std::map<string, string>& variables,
io::Printer* printer) {
if (GetJavaType(descriptor) == JAVATYPE_BYTES) {
printer->Print(variables,
@@ -190,7 +190,7 @@ void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
}
void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor,
const map<string, string>& variables,
const std::map<string, string>& variables,
io::Printer* printer) {
if (GetJavaType(descriptor) == JAVATYPE_BYTES) {
printer->Print(variables,
@@ -114,12 +114,12 @@ class FieldGeneratorMap {
};
void SetCommonOneofVariables(const FieldDescriptor* descriptor,
map<string, string>* variables);
std::map<string, string>* variables);
void GenerateOneofFieldEquals(const FieldDescriptor* descriptor,
const map<string, string>& variables,
const std::map<string, string>& variables,
io::Printer* printer);
void GenerateOneofFieldHashCode(const FieldDescriptor* descriptor,
const map<string, string>& variables,
const std::map<string, string>& variables,
io::Printer* printer);
} // namespace javanano
@@ -120,12 +120,12 @@ bool FileGenerator::Validate(string* error) {
if (!params_.has_java_outer_classname(file_->name())
&& file_->message_type_count() == 1
&& file_->enum_type_count() == 0 && file_->extension_count() == 0) {
cout << "INFO: " << file_->name() << ":" << endl;
cout << "Javanano generator has changed to align with java generator. "
std::cout << "INFO: " << file_->name() << ":" << std::endl;
std::cout << "Javanano generator has changed to align with java generator. "
"An outer class will be created for this file and the single message "
"in the file will become a nested class. Use java_multiple_files to "
"skip generating the outer class, or set an explicit "
"java_outer_classname to suppress this message." << endl;
"java_outer_classname to suppress this message." << std::endl;
}
// Check that no class name matches the file's class name. This is a common
Loaded 100 of 370 files, more files were not shown because too many files have changed in this diff. Show more