diff options
Diffstat (limited to 'src/google/protobuf/compiler/java/java_message.cc')
-rw-r--r-- | src/google/protobuf/compiler/java/java_message.cc | 586 |
1 files changed, 359 insertions, 227 deletions
diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/java_message.cc index 22a70c32..209c0b2a 100644 --- a/src/google/protobuf/compiler/java/java_message.cc +++ b/src/google/protobuf/compiler/java/java_message.cc @@ -38,9 +38,6 @@ #include <google/protobuf/stubs/hash.h> #include <map> #include <memory> -#ifndef _SHARED_PTR_H -#include <google/protobuf/stubs/shared_ptr.h> -#endif #include <vector> #include <google/protobuf/compiler/java/java_context.h> @@ -52,12 +49,13 @@ #include <google/protobuf/compiler/java/java_message_builder.h> #include <google/protobuf/compiler/java/java_message_builder_lite.h> #include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/wire_format.h> -#include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/stubs/strutil.h> + namespace google { namespace protobuf { @@ -89,19 +87,20 @@ MessageGenerator::MessageGenerator(const Descriptor* descriptor) MessageGenerator::~MessageGenerator() {} // =================================================================== -// TODO(api): Move this class to a separate immutable_message.cc file. ImmutableMessageGenerator::ImmutableMessageGenerator( const Descriptor* descriptor, Context* context) : MessageGenerator(descriptor), context_(context), name_resolver_(context->GetNameResolver()), field_generators_(descriptor, context_) { - GOOGLE_CHECK_NE( - FileOptions::LITE_RUNTIME, descriptor->file()->options().optimize_for()); + GOOGLE_CHECK(HasDescriptorMethods(descriptor->file(), context->EnforceLite())) + << "Generator factory error: A non-lite message generator is used to " + "generate lite messages."; } ImmutableMessageGenerator::~ImmutableMessageGenerator() {} -void ImmutableMessageGenerator::GenerateStaticVariables(io::Printer* printer) { +void ImmutableMessageGenerator::GenerateStaticVariables( + io::Printer* printer, int* bytecode_estimate) { // Because descriptor.proto (com.google.protobuf.DescriptorProtos) is // used in the construction of descriptors, we have a tricky bootstrapping // problem. To help control static initialization order, we make sure all @@ -109,7 +108,7 @@ void ImmutableMessageGenerator::GenerateStaticVariables(io::Printer* printer) { // the outermost class in the file. This way, they will be initialized in // a deterministic order. - map<string, string> vars; + std::map<string, string> vars; vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); vars["index"] = SimpleItoa(descriptor_->index()); vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_); @@ -124,30 +123,36 @@ void ImmutableMessageGenerator::GenerateStaticVariables(io::Printer* printer) { } else { vars["private"] = "private "; } + if (*bytecode_estimate <= kMaxStaticSize) { + vars["final"] = "final "; + } else { + vars["final"] = ""; + } // The descriptor for this type. printer->Print(vars, // TODO(teboring): final needs to be added back. The way to fix it is to // generate methods that can construct the types, and then still declare the // types, and then init them in clinit with the new method calls. - "$private$static com.google.protobuf.Descriptors.Descriptor\n" + "$private$static $final$com.google.protobuf.Descriptors.Descriptor\n" " internal_$identifier$_descriptor;\n"); + *bytecode_estimate += 30; // And the FieldAccessorTable. - GenerateFieldAccessorTable(printer); + GenerateFieldAccessorTable(printer, bytecode_estimate); // Generate static members for all nested types. for (int i = 0; i < descriptor_->nested_type_count(); i++) { // TODO(kenton): Reuse MessageGenerator objects? ImmutableMessageGenerator(descriptor_->nested_type(i), context_) - .GenerateStaticVariables(printer); + .GenerateStaticVariables(printer, bytecode_estimate); } } int ImmutableMessageGenerator::GenerateStaticVariableInitializers( io::Printer* printer) { int bytecode_estimate = 0; - map<string, string> vars; + std::map<string, string> vars; vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); vars["index"] = SimpleItoa(descriptor_->index()); vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_); @@ -183,8 +188,8 @@ int ImmutableMessageGenerator::GenerateStaticVariableInitializers( } void ImmutableMessageGenerator:: -GenerateFieldAccessorTable(io::Printer* printer) { - map<string, string> vars; +GenerateFieldAccessorTable(io::Printer* printer, int* bytecode_estimate) { + std::map<string, string> vars; vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); if (MultipleJavaFiles(descriptor_->file(), /* immutable = */ true)) { // We can only make these package-private since the classes that use them @@ -193,10 +198,20 @@ GenerateFieldAccessorTable(io::Printer* printer) { } else { vars["private"] = "private "; } + if (*bytecode_estimate <= kMaxStaticSize) { + vars["final"] = "final "; + } else { + vars["final"] = ""; + } + vars["ver"] = GeneratedCodeVersionSuffix(); printer->Print(vars, - "$private$static\n" - " com.google.protobuf.GeneratedMessage.FieldAccessorTable\n" + "$private$static $final$\n" + " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" " internal_$identifier$_fieldAccessorTable;\n"); + + // 6 bytes per field and oneof + *bytecode_estimate += 10 + 6 * descriptor_->field_count() + + 6 * descriptor_->oneof_decl_count(); } int ImmutableMessageGenerator:: @@ -204,11 +219,11 @@ GenerateFieldAccessorTableInitializer(io::Printer* printer) { int bytecode_estimate = 10; printer->Print( "internal_$identifier$_fieldAccessorTable = new\n" - " com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n" + " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable(\n" " internal_$identifier$_descriptor,\n" " new java.lang.String[] { ", - "identifier", - UniqueFileScopeIdentifier(descriptor_)); + "identifier", UniqueFileScopeIdentifier(descriptor_), + "ver", GeneratedCodeVersionSuffix()); for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = descriptor_->field(i); const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); @@ -232,22 +247,31 @@ GenerateFieldAccessorTableInitializer(io::Printer* printer) { // =================================================================== void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) { + MaybePrintGeneratedAnnotation(context_, printer, descriptor_, + /* immutable = */ true, "OrBuilder"); if (descriptor_->extension_range_count() > 0) { printer->Print( - "public interface $classname$OrBuilder extends\n" - " $extra_interfaces$\n" - " com.google.protobuf.GeneratedMessage.\n" - " ExtendableMessageOrBuilder<$classname$> {\n", - "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name()); + "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n" + " $extra_interfaces$\n" + " com.google.protobuf.GeneratedMessage$ver$.\n" + " ExtendableMessageOrBuilder<$classname$> {\n", + "deprecation", descriptor_->options().deprecated() ? + "@java.lang.Deprecated " : "", + "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), + "classname", descriptor_->name(), + "{", "", "}", "", "ver", GeneratedCodeVersionSuffix()); } else { printer->Print( - "public interface $classname$OrBuilder extends\n" - " $extra_interfaces$\n" - " com.google.protobuf.MessageOrBuilder {\n", - "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), - "classname", descriptor_->name()); + "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n" + " $extra_interfaces$\n" + " com.google.protobuf.MessageOrBuilder {\n", + "deprecation", descriptor_->options().deprecated() ? + "@java.lang.Deprecated " : "", + "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_), + "classname", descriptor_->name(), + "{", "", "}", ""); } + printer->Annotate("{", "}", descriptor_); printer->Indent(); for (int i = 0; i < descriptor_->field_count(); i++) { @@ -275,37 +299,53 @@ void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) { // =================================================================== void ImmutableMessageGenerator::Generate(io::Printer* printer) { - bool is_own_file = - descriptor_->containing_type() == NULL && - MultipleJavaFiles(descriptor_->file(), /* immutable = */ true); + bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true); - map<string, string> variables; + std::map<string, string> variables; variables["static"] = is_own_file ? " " : " static "; variables["classname"] = descriptor_->name(); variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_); + variables["ver"] = GeneratedCodeVersionSuffix(); + variables["deprecation"] = descriptor_->options().deprecated() + ? "@java.lang.Deprecated " : ""; WriteMessageDocComment(printer, descriptor_); + MaybePrintGeneratedAnnotation(context_, printer, descriptor_, + /* immutable = */ true); // The builder_type stores the super type name of the nested Builder class. string builder_type; if (descriptor_->extension_range_count() > 0) { - printer->Print(variables, - "public $static$final class $classname$ extends\n" - " com.google.protobuf.GeneratedMessage.ExtendableMessage<\n" - " $classname$> implements\n" - " $extra_interfaces$\n" - " $classname$OrBuilder {\n"); + printer->Print( + variables, + "$deprecation$public $static$final class $classname$ extends\n"); + printer->Annotate("classname", descriptor_); + printer->Print( + variables, + " com.google.protobuf.GeneratedMessage$ver$.ExtendableMessage<\n" + " $classname$> implements\n" + " $extra_interfaces$\n" + " $classname$OrBuilder {\n"); builder_type = strings::Substitute( - "com.google.protobuf.GeneratedMessage.ExtendableBuilder<$0, ?>", - name_resolver_->GetImmutableClassName(descriptor_)); + "com.google.protobuf.GeneratedMessage$1.ExtendableBuilder<$0, ?>", + name_resolver_->GetImmutableClassName(descriptor_), + GeneratedCodeVersionSuffix()); } else { + printer->Print( + variables, + "$deprecation$public $static$final class $classname$ extends\n"); + printer->Annotate("classname", descriptor_); printer->Print(variables, - "public $static$final class $classname$ extends\n" - " com.google.protobuf.GeneratedMessage implements\n" + " com.google.protobuf.GeneratedMessage$ver$ implements\n" " $extra_interfaces$\n" " $classname$OrBuilder {\n"); - builder_type = "com.google.protobuf.GeneratedMessage.Builder<?>"; + builder_type = strings::Substitute( + "com.google.protobuf.GeneratedMessage$0.Builder<?>", + GeneratedCodeVersionSuffix()); } + printer->Print( + "private static final long serialVersionUID = 0L;\n"); + printer->Indent(); // Using builder_type, instead of Builder, prevents the Builder class from // being loaded into PermGen space when the default instance is created. @@ -328,22 +368,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 (HasGeneratedMethods(descriptor_)) { - GenerateParsingConstructor(printer); + if (context_->HasGeneratedMethods(descriptor_)) { + if (!EnableExperimentalRuntime(context_) || + IsDescriptorProto(descriptor_)) { + GenerateParsingConstructor(printer); + } } GenerateDescriptorMethods(printer); @@ -378,7 +415,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { } // oneof - map<string, string> vars; + std::map<string, string> vars; for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { vars["oneof_name"] = context_->GetOneofGeneratorInfo( descriptor_->oneof_decl(i))->name; @@ -397,23 +434,31 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); printer->Print( - "$field_name$($field_number$),\n", - "field_name", - ToUpper(field->name()), - "field_number", - SimpleItoa(field->number())); + "$deprecation$$field_name$($field_number$),\n", + "deprecation", + field->options().deprecated() ? "@java.lang.Deprecated " : "", + "field_name", ToUpper(field->name()), + "field_number", SimpleItoa(field->number())); } printer->Print( "$cap_oneof_name$_NOT_SET(0);\n", "cap_oneof_name", ToUpper(vars["oneof_name"])); printer->Print(vars, - "private int value = 0;\n" + "private final int value;\n" "private $oneof_capitalized_name$Case(int value) {\n" " this.value = value;\n" "}\n"); printer->Print(vars, + "/**\n" + " * @deprecated Use {@link #forNumber(int)} instead.\n" + " */\n" + "@java.lang.Deprecated\n" "public static $oneof_capitalized_name$Case valueOf(int value) {\n" + " return forNumber(value);\n" + "}\n" + "\n" + "public static $oneof_capitalized_name$Case forNumber(int value) {\n" " switch (value) {\n"); for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); @@ -426,8 +471,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { } printer->Print( " case 0: return $cap_oneof_name$_NOT_SET;\n" - " default: throw new java.lang.IllegalArgumentException(\n" - " \"Value is undefined for this oneof enum.\");\n" + " default: return null;\n" " }\n" "}\n" "public int getNumber() {\n" @@ -440,7 +484,7 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { printer->Print(vars, "public $oneof_capitalized_name$Case\n" "get$oneof_capitalized_name$Case() {\n" - " return $oneof_capitalized_name$Case.valueOf(\n" + " return $oneof_capitalized_name$Case.forNumber(\n" " $oneof_name$Case_);\n" "}\n" "\n"); @@ -459,12 +503,9 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { printer->Print("\n"); } - if (HasGeneratedMethods(descriptor_)) { + if (context_->HasGeneratedMethods(descriptor_)) { GenerateIsInitialized(printer); GenerateMessageSerializationMethods(printer); - } - - if (HasEqualsAndHashCode(descriptor_)) { GenerateEqualsAndHashCode(printer); } @@ -497,9 +538,21 @@ 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( + "@java.lang.Override\n" "public $classname$ getDefaultInstanceForType() {\n" " return DEFAULT_INSTANCE;\n" "}\n" @@ -523,116 +576,120 @@ void ImmutableMessageGenerator::Generate(io::Printer* printer) { void ImmutableMessageGenerator:: GenerateMessageSerializationMethods(io::Printer* printer) { - google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields( + std::unique_ptr<const FieldDescriptor * []> sorted_fields( SortFieldsByNumber(descriptor_)); - vector<const Descriptor::ExtensionRange*> sorted_extensions; + std::vector<const Descriptor::ExtensionRange*> sorted_extensions; for (int i = 0; i < descriptor_->extension_range_count(); ++i) { sorted_extensions.push_back(descriptor_->extension_range(i)); } std::sort(sorted_extensions.begin(), sorted_extensions.end(), ExtensionRangeOrdering()); - printer->Print( + "@java.lang.Override\n" "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" " throws java.io.IOException {\n"); printer->Indent(); - if (HasPackedFields(descriptor_)) { - // writeTo(CodedOutputStream output) might be invoked without - // getSerializedSize() ever being called, but we need the memoized - // sizes in case this message has packed fields. Rather than emit checks for - // each packed field, just call getSerializedSize() up front. - // In most cases, getSerializedSize() will have already been called anyway - // by one of the wrapper writeTo() methods, making this call cheap. - printer->Print( - "getSerializedSize();\n"); - } - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "com.google.protobuf.GeneratedMessage\n" - " .ExtendableMessage<$classname$>.ExtensionWriter\n" - " extensionWriter = newMessageSetExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); - } else { - printer->Print( - "com.google.protobuf.GeneratedMessage\n" - " .ExtendableMessage<$classname$>.ExtensionWriter\n" - " extensionWriter = newExtensionWriter();\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + 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" + "@java.lang.Override\n" + "public int getSerializedSize() {\n" + " int size = memoizedSize;\n" + " if (size != -1) return size;\n" + "\n"); printer->Indent(); + if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) { + printer->Print( + "memoizedSize = getSerializedSizeInternal();\n" + "return memoizedSize;\n"); + } else { - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer); - } + printer->Print("size = 0;\n"); - if (descriptor_->extension_range_count() > 0) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "size += extensionsSerializedSizeAsMessageSet();\n"); - } else { - printer->Print( - "size += extensionsSerializedSize();\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 (PreserveUnknownFields(descriptor_)) { if (descriptor_->options().message_set_wire_format()) { printer->Print( - "size += unknownFields.getSerializedSizeAsMessageSet();\n"); + "size += unknownFields.getSerializedSizeAsMessageSet();\n"); } else { - printer->Print( - "size += unknownFields.getSerializedSize();\n"); + 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:: @@ -642,6 +699,17 @@ GenerateParseFromMethods(io::Printer* printer) { // for code size. printer->Print( "public static $classname$ parseFrom(\n" + " java.nio.ByteBuffer data)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return PARSER.parseFrom(data);\n" + "}\n" + "public static $classname$ parseFrom(\n" + " java.nio.ByteBuffer data,\n" + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n" + " return PARSER.parseFrom(data, extensionRegistry);\n" + "}\n" + "public static $classname$ parseFrom(\n" " com.google.protobuf.ByteString data)\n" " throws com.google.protobuf.InvalidProtocolBufferException {\n" " return PARSER.parseFrom(data);\n" @@ -664,37 +732,44 @@ GenerateParseFromMethods(io::Printer* printer) { "}\n" "public static $classname$ parseFrom(java.io.InputStream input)\n" " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input);" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseWithIOException(PARSER, input);\n" "}\n" "public static $classname$ parseFrom(\n" " java.io.InputStream input,\n" " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry);" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseWithIOException(PARSER, input, extensionRegistry);\n" "}\n" "public static $classname$ parseDelimitedFrom(java.io.InputStream input)\n" " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input);" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseDelimitedWithIOException(PARSER, input);\n" "}\n" "public static $classname$ parseDelimitedFrom(\n" " java.io.InputStream input,\n" " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage.parseDelimitedWithIOException(PARSER, input, extensionRegistry);" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseDelimitedWithIOException(PARSER, input, extensionRegistry);\n" "}\n" "public static $classname$ parseFrom(\n" " com.google.protobuf.CodedInputStream input)\n" " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input);" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseWithIOException(PARSER, input);\n" "}\n" "public static $classname$ parseFrom(\n" " com.google.protobuf.CodedInputStream input,\n" " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" " throws java.io.IOException {\n" - " return com.google.protobuf.GeneratedMessage.parseWithIOException(PARSER, input, extensionRegistry);" + " return com.google.protobuf.GeneratedMessage$ver$\n" + " .parseWithIOException(PARSER, input, extensionRegistry);\n" "}\n" "\n", - "classname", name_resolver_->GetImmutableClassName(descriptor_)); + "classname", name_resolver_->GetImmutableClassName(descriptor_), + "ver", GeneratedCodeVersionSuffix()); } void ImmutableMessageGenerator::GenerateSerializeOneField( @@ -714,6 +789,7 @@ void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange( void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) { // LITE_RUNTIME implements this at the GeneratedMessageLite level. printer->Print( + "@java.lang.Override\n" "public Builder newBuilderForType() { return newBuilder(); }\n"); printer->Print( @@ -723,6 +799,7 @@ void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) { "public static Builder newBuilder($classname$ prototype) {\n" " return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n" "}\n" + "@java.lang.Override\n" "public Builder toBuilder() {\n" " return this == DEFAULT_INSTANCE\n" " ? new Builder() : new Builder().mergeFrom(this);\n" @@ -733,10 +810,11 @@ void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) { printer->Print( "@java.lang.Override\n" "protected Builder newBuilderForType(\n" - " com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n" + " com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n" " Builder builder = new Builder(parent);\n" " return builder;\n" - "}\n"); + "}\n", + "ver", GeneratedCodeVersionSuffix()); MessageBuilderGenerator builderGenerator(descriptor_, context_); builderGenerator.Generate(printer); @@ -754,7 +832,7 @@ GenerateDescriptorMethods(io::Printer* printer) { "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), "identifier", UniqueFileScopeIdentifier(descriptor_)); } - vector<const FieldDescriptor*> map_fields; + std::vector<const FieldDescriptor*> map_fields; for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = descriptor_->field(i); if (GetJavaType(field) == JAVATYPE_MESSAGE && @@ -765,6 +843,7 @@ GenerateDescriptorMethods(io::Printer* printer) { if (!map_fields.empty()) { printer->Print( "@SuppressWarnings({\"rawtypes\"})\n" + "@java.lang.Override\n" "protected com.google.protobuf.MapField internalGetMapField(\n" " int number) {\n" " switch (number) {\n"); @@ -790,7 +869,8 @@ GenerateDescriptorMethods(io::Printer* printer) { "}\n"); } printer->Print( - "protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n" + "@java.lang.Override\n" + "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n" " internalGetFieldAccessorTable() {\n" " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" " .ensureFieldAccessorsInitialized(\n" @@ -799,7 +879,8 @@ GenerateDescriptorMethods(io::Printer* printer) { "\n", "classname", name_resolver_->GetImmutableClassName(descriptor_), "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()), - "identifier", UniqueFileScopeIdentifier(descriptor_)); + "identifier", UniqueFileScopeIdentifier(descriptor_), + "ver", GeneratedCodeVersionSuffix()); } // =================================================================== @@ -812,6 +893,7 @@ void ImmutableMessageGenerator::GenerateIsInitialized( printer->Print( "private byte memoizedIsInitialized = -1;\n"); printer->Print( + "@java.lang.Override\n" "public final boolean isInitialized() {\n"); printer->Indent(); @@ -882,7 +964,7 @@ void ImmutableMessageGenerator::GenerateIsInitialized( case FieldDescriptor::LABEL_REPEATED: if (IsMapEntry(field->message_type())) { printer->Print( - "for ($type$ item : get$name$().values()) {\n" + "for ($type$ item : get$name$Map().values()) {\n" " if (!item.isInitialized()) {\n" " memoizedIsInitialized = 0;\n" " return false;\n" @@ -1014,13 +1096,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" @@ -1047,24 +1127,59 @@ GenerateEqualsAndHashCode(io::Printer* printer) { "}\n" "int hash = 41;\n"); - printer->Print("hash = (19 * hash) + getDescriptorForType().hashCode();\n"); + // If we output a getDescriptor() method, use that as it is more efficient. + if (descriptor_->options().no_standard_descriptor_accessor()) { + printer->Print("hash = (19 * hash) + getDescriptorForType().hashCode();\n"); + } else { + printer->Print("hash = (19 * hash) + getDescriptor().hashCode();\n"); + } + // hashCode non-oneofs. for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = descriptor_->field(i); - const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); - bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field); - if (check_has_bits) { + if (field->containing_oneof() == NULL) { + const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field); + bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field); + if (check_has_bits) { + printer->Print( + "if (has$name$()) {\n", + "name", info->capitalized_name); + printer->Indent(); + } + field_generators_.get(field).GenerateHashCode(printer); + if (check_has_bits) { + printer->Outdent(); + printer->Print("}\n"); + } + } + } + + // hashCode oneofs. + for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { + printer->Print( + "switch ($oneof_name$Case_) {\n", + "oneof_name", + context_->GetOneofGeneratorInfo( + descriptor_->oneof_decl(i))->name); + printer->Indent(); + for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { + const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); printer->Print( - "if (has$name$()) {\n", - "name", info->capitalized_name); + "case $field_number$:\n", + "field_number", + SimpleItoa(field->number())); printer->Indent(); - } - field_generators_.get(field).GenerateHashCode(printer); - if (check_has_bits) { + field_generators_.get(field).GenerateHashCode(printer); + printer->Print("break;\n"); printer->Outdent(); - printer->Print("}\n"); } + printer->Print( + "case 0:\n" + "default:\n"); + printer->Outdent(); + printer->Print("}\n"); } + if (descriptor_->extension_range_count() > 0) { printer->Print( "hash = hashFields(hash, getExtensionFields());\n"); @@ -1099,19 +1214,23 @@ GenerateExtensionRegistrationCode(io::Printer* printer) { // =================================================================== void ImmutableMessageGenerator:: GenerateParsingConstructor(io::Printer* printer) { - google::protobuf::scoped_array<const FieldDescriptor * > sorted_fields( + std::unique_ptr<const FieldDescriptor * []> sorted_fields( SortFieldsByNumber(descriptor_)); printer->Print( "private $classname$(\n" " com.google.protobuf.CodedInputStream input,\n" - " com.google.protobuf.ExtensionRegistryLite extensionRegistry) {\n", + " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" + " throws com.google.protobuf.InvalidProtocolBufferException {\n", "classname", descriptor_->name()); printer->Indent(); // Initialize all fields to default. printer->Print( - "this();\n"); + "this();\n" + "if (extensionRegistry == null) {\n" + " throw new java.lang.NullPointerException();\n" + "}\n"); // Use builder bits to track mutable repeated fields. int totalBuilderBits = 0; @@ -1126,11 +1245,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"); @@ -1147,28 +1264,9 @@ GenerateParsingConstructor(io::Printer* printer) { printer->Indent(); printer->Print( - "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"); - } + "case 0:\n" // zero signals EOF / limit reached + " done = true;\n" + " break;\n"); for (int i = 0; i < descriptor_->field_count(); i++) { const FieldDescriptor* field = sorted_fields[i]; @@ -1177,7 +1275,7 @@ GenerateParsingConstructor(io::Printer* printer) { printer->Print( "case $tag$: {\n", - "tag", SimpleItoa(tag)); + "tag", SimpleItoa(static_cast<int32>(tag))); printer->Indent(); field_generators_.get(field).GenerateParsingCode(printer); @@ -1194,7 +1292,7 @@ GenerateParsingConstructor(io::Printer* printer) { WireFormatLite::WIRETYPE_LENGTH_DELIMITED); printer->Print( "case $tag$: {\n", - "tag", SimpleItoa(packed_tag)); + "tag", SimpleItoa(static_cast<int32>(packed_tag))); printer->Indent(); field_generators_.get(field).GenerateParsingCodeFromPacked(printer); @@ -1206,6 +1304,18 @@ GenerateParsingConstructor(io::Printer* printer) { } } + printer->Print( + "default: {\n" + " if (!parseUnknownField$suffix$(\n" + " input, unknownFields, extensionRegistry, tag)) {\n" + " done = true;\n" // it's an endgroup tag + " }\n" + " break;\n" + "}\n", + "suffix", + descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? "Proto3" + : ""); + printer->Outdent(); printer->Outdent(); printer->Print( @@ -1215,10 +1325,10 @@ GenerateParsingConstructor(io::Printer* printer) { printer->Outdent(); printer->Print( "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" - " throw new RuntimeException(e.setUnfinishedMessage(this));\n" + " throw e.setUnfinishedMessage(this);\n" "} catch (java.io.IOException e) {\n" - " throw new RuntimeException(new com.google.protobuf.InvalidProtocolBufferException(e)\n" - " .setUnfinishedMessage(this));\n" + " throw new com.google.protobuf.InvalidProtocolBufferException(\n" + " e).setUnfinishedMessage(this);\n" "} finally {\n"); printer->Indent(); @@ -1228,10 +1338,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( @@ -1255,26 +1363,24 @@ void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) { "classname", descriptor_->name()); printer->Indent(); printer->Print( + "@java.lang.Override\n" "public $classname$ parsePartialFrom(\n" " com.google.protobuf.CodedInputStream input,\n" " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" " throws com.google.protobuf.InvalidProtocolBufferException {\n", "classname", descriptor_->name()); - if (HasGeneratedMethods(descriptor_)) { - // The parsing constructor throws an InvalidProtocolBufferException via a - // RuntimeException to aid in method pruning. We unwrap it here. + if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) { + printer->Indent(); printer->Print( - " try {\n" - " return new $classname$(input, extensionRegistry);\n" - " } catch (RuntimeException e) {\n" - " if (e.getCause() instanceof\n" - " com.google.protobuf.InvalidProtocolBufferException) {\n" - " throw (com.google.protobuf.InvalidProtocolBufferException)\n" - " e.getCause();\n" - " }\n" - " throw e;\n" - " }\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() @@ -1328,14 +1434,39 @@ void ImmutableMessageGenerator::GenerateInitializers(io::Printer* printer) { void ImmutableMessageGenerator::GenerateAnyMethods(io::Printer* printer) { printer->Print( "private static String getTypeUrl(\n" + " java.lang.String typeUrlPrefix,\n" " com.google.protobuf.Descriptors.Descriptor descriptor) {\n" - " return \"type.googleapis.com/\" + descriptor.getFullName();\n" + " return typeUrlPrefix.endsWith(\"/\")\n" + " ? typeUrlPrefix + descriptor.getFullName()\n" + " : typeUrlPrefix + \"/\" + descriptor.getFullName();\n" + "}\n" + "\n" + "private static String getTypeNameFromTypeUrl(\n" + " java.lang.String typeUrl) {\n" + " int pos = typeUrl.lastIndexOf('/');\n" + " return pos == -1 ? \"\" : typeUrl.substring(pos + 1);\n" "}\n" "\n" "public static <T extends com.google.protobuf.Message> Any pack(\n" " T message) {\n" " return Any.newBuilder()\n" - " .setTypeUrl(getTypeUrl(message.getDescriptorForType()))\n" + " .setTypeUrl(getTypeUrl(\"type.googleapis.com\",\n" + " message.getDescriptorForType()))\n" + " .setValue(message.toByteString())\n" + " .build();\n" + "}\n" + "\n" + "/**\n" + " * Packs a message using the given type URL prefix. The type URL will\n" + " * be constructed by concatenating the message type's full name to the\n" + " * prefix with an optional \"/\" separator if the prefix doesn't end\n" + " * with \"/\" already.\n" + " */\n" + "public static <T extends com.google.protobuf.Message> Any pack(\n" + " T message, java.lang.String typeUrlPrefix) {\n" + " return Any.newBuilder()\n" + " .setTypeUrl(getTypeUrl(typeUrlPrefix,\n" + " message.getDescriptorForType()))\n" " .setValue(message.toByteString())\n" " .build();\n" "}\n" @@ -1344,12 +1475,13 @@ void ImmutableMessageGenerator::GenerateAnyMethods(io::Printer* printer) { " java.lang.Class<T> clazz) {\n" " T defaultInstance =\n" " com.google.protobuf.Internal.getDefaultInstance(clazz);\n" - " return getTypeUrl().equals(\n" - " getTypeUrl(defaultInstance.getDescriptorForType()));\n" + " return getTypeNameFromTypeUrl(getTypeUrl()).equals(\n" + " defaultInstance.getDescriptorForType().getFullName());\n" "}\n" "\n" "private volatile com.google.protobuf.Message cachedUnpackValue;\n" "\n" + "@java.lang.SuppressWarnings(\"unchecked\")\n" "public <T extends com.google.protobuf.Message> T unpack(\n" " java.lang.Class<T> clazz)\n" " throws com.google.protobuf.InvalidProtocolBufferException {\n" |