• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 // Author: dweis@google.com (Daniel Weis)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 
35 #include <google/protobuf/compiler/java/java_message_builder.h>
36 
37 #include <algorithm>
38 #include <map>
39 #include <memory>
40 #include <vector>
41 
42 #include <google/protobuf/compiler/java/java_context.h>
43 #include <google/protobuf/compiler/java/java_doc_comment.h>
44 #include <google/protobuf/compiler/java/java_enum.h>
45 #include <google/protobuf/compiler/java/java_extension.h>
46 #include <google/protobuf/compiler/java/java_generator_factory.h>
47 #include <google/protobuf/compiler/java/java_helpers.h>
48 #include <google/protobuf/compiler/java/java_name_resolver.h>
49 #include <google/protobuf/descriptor.pb.h>
50 #include <google/protobuf/io/coded_stream.h>
51 #include <google/protobuf/io/printer.h>
52 #include <google/protobuf/wire_format.h>
53 #include <google/protobuf/stubs/strutil.h>
54 #include <google/protobuf/stubs/substitute.h>
55 
56 
57 
58 namespace google {
59 namespace protobuf {
60 namespace compiler {
61 namespace java {
62 
63 namespace {
MapValueImmutableClassdName(const Descriptor * descriptor,ClassNameResolver * name_resolver)64 std::string MapValueImmutableClassdName(const Descriptor* descriptor,
65                                         ClassNameResolver* name_resolver) {
66   const FieldDescriptor* value_field = descriptor->FindFieldByName("value");
67   GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type());
68   return name_resolver->GetImmutableClassName(value_field->message_type());
69 }
70 }  // namespace
71 
MessageBuilderGenerator(const Descriptor * descriptor,Context * context)72 MessageBuilderGenerator::MessageBuilderGenerator(const Descriptor* descriptor,
73                                                  Context* context)
74     : descriptor_(descriptor),
75       context_(context),
76       name_resolver_(context->GetNameResolver()),
77       field_generators_(descriptor, context_) {
78   GOOGLE_CHECK(HasDescriptorMethods(descriptor->file(), context->EnforceLite()))
79       << "Generator factory error: A non-lite message generator is used to "
80          "generate lite messages.";
81 }
82 
~MessageBuilderGenerator()83 MessageBuilderGenerator::~MessageBuilderGenerator() {}
84 
Generate(io::Printer * printer)85 void MessageBuilderGenerator::Generate(io::Printer* printer) {
86   WriteMessageDocComment(printer, descriptor_);
87   if (descriptor_->extension_range_count() > 0) {
88     printer->Print(
89         "public static final class Builder extends\n"
90         "    com.google.protobuf.GeneratedMessage$ver$.ExtendableBuilder<\n"
91         "      $classname$, Builder> implements\n"
92         "    $extra_interfaces$\n"
93         "    $classname$OrBuilder {\n",
94         "classname", name_resolver_->GetImmutableClassName(descriptor_),
95         "extra_interfaces", ExtraBuilderInterfaces(descriptor_), "ver",
96         GeneratedCodeVersionSuffix());
97   } else {
98     printer->Print(
99         "public static final class Builder extends\n"
100         "    com.google.protobuf.GeneratedMessage$ver$.Builder<Builder> "
101         "implements\n"
102         "    $extra_interfaces$\n"
103         "    $classname$OrBuilder {\n",
104         "classname", name_resolver_->GetImmutableClassName(descriptor_),
105         "extra_interfaces", ExtraBuilderInterfaces(descriptor_), "ver",
106         GeneratedCodeVersionSuffix());
107   }
108   printer->Indent();
109 
110   GenerateDescriptorMethods(printer);
111   GenerateCommonBuilderMethods(printer);
112 
113   if (context_->HasGeneratedMethods(descriptor_)) {
114     GenerateIsInitialized(printer);
115     GenerateBuilderParsingMethods(printer);
116   }
117 
118   // oneof
119   std::map<std::string, std::string> vars;
120   for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
121     vars["oneof_name"] =
122         context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name;
123     vars["oneof_capitalized_name"] =
124         context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
125             ->capitalized_name;
126     vars["oneof_index"] = StrCat(descriptor_->oneof_decl(i)->index());
127     // oneofCase_ and oneof_
128     printer->Print(vars,
129                    "private int $oneof_name$Case_ = 0;\n"
130                    "private java.lang.Object $oneof_name$_;\n");
131     // oneofCase() and clearOneof()
132     printer->Print(vars,
133                    "public $oneof_capitalized_name$Case\n"
134                    "    get$oneof_capitalized_name$Case() {\n"
135                    "  return $oneof_capitalized_name$Case.forNumber(\n"
136                    "      $oneof_name$Case_);\n"
137                    "}\n"
138                    "\n"
139                    "public Builder clear$oneof_capitalized_name$() {\n"
140                    "  $oneof_name$Case_ = 0;\n"
141                    "  $oneof_name$_ = null;\n");
142     printer->Print("  onChanged();\n");
143     printer->Print(
144         "  return this;\n"
145         "}\n"
146         "\n");
147   }
148 
149   // Integers for bit fields.
150   int totalBits = 0;
151   for (int i = 0; i < descriptor_->field_count(); i++) {
152     totalBits +=
153         field_generators_.get(descriptor_->field(i)).GetNumBitsForBuilder();
154   }
155   int totalInts = (totalBits + 31) / 32;
156   for (int i = 0; i < totalInts; i++) {
157     printer->Print("private int $bit_field_name$;\n", "bit_field_name",
158                    GetBitFieldName(i));
159   }
160 
161   for (int i = 0; i < descriptor_->field_count(); i++) {
162     printer->Print("\n");
163     field_generators_.get(descriptor_->field(i))
164         .GenerateBuilderMembers(printer);
165   }
166 
167   // Override methods declared in GeneratedMessage to return the concrete
168   // generated type so callsites won't depend on GeneratedMessage. This
169   // is needed to keep binary compatibility when we change generated code
170   // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release
171   // we changed all generated code to subclass GeneratedMessageV3).
172   printer->Print(
173       "@java.lang.Override\n"
174       "public final Builder setUnknownFields(\n"
175       "    final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
176       "  return super.setUnknownFields(unknownFields);\n"
177       "}\n"
178       "\n"
179       "@java.lang.Override\n"
180       "public final Builder mergeUnknownFields(\n"
181       "    final com.google.protobuf.UnknownFieldSet unknownFields) {\n"
182       "  return super.mergeUnknownFields(unknownFields);\n"
183       "}\n"
184       "\n");
185 
186   printer->Print(
187       "\n"
188       "// @@protoc_insertion_point(builder_scope:$full_name$)\n",
189       "full_name", descriptor_->full_name());
190 
191   printer->Outdent();
192   printer->Print("}\n");
193 }
194 
195 // ===================================================================
196 
GenerateDescriptorMethods(io::Printer * printer)197 void MessageBuilderGenerator::GenerateDescriptorMethods(io::Printer* printer) {
198   if (!descriptor_->options().no_standard_descriptor_accessor()) {
199     printer->Print(
200         "public static final com.google.protobuf.Descriptors.Descriptor\n"
201         "    getDescriptor() {\n"
202         "  return $fileclass$.internal_$identifier$_descriptor;\n"
203         "}\n"
204         "\n",
205         "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()),
206         "identifier", UniqueFileScopeIdentifier(descriptor_));
207   }
208   std::vector<const FieldDescriptor*> map_fields;
209   for (int i = 0; i < descriptor_->field_count(); i++) {
210     const FieldDescriptor* field = descriptor_->field(i);
211     if (GetJavaType(field) == JAVATYPE_MESSAGE &&
212         IsMapEntry(field->message_type())) {
213       map_fields.push_back(field);
214     }
215   }
216   if (!map_fields.empty()) {
217     printer->Print(
218         "@SuppressWarnings({\"rawtypes\"})\n"
219         "protected com.google.protobuf.MapField internalGetMapField(\n"
220         "    int number) {\n"
221         "  switch (number) {\n");
222     printer->Indent();
223     printer->Indent();
224     for (int i = 0; i < map_fields.size(); ++i) {
225       const FieldDescriptor* field = map_fields[i];
226       const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
227       printer->Print(
228           "case $number$:\n"
229           "  return internalGet$capitalized_name$();\n",
230           "number", StrCat(field->number()), "capitalized_name",
231           info->capitalized_name);
232     }
233     printer->Print(
234         "default:\n"
235         "  throw new RuntimeException(\n"
236         "      \"Invalid map field number: \" + number);\n");
237     printer->Outdent();
238     printer->Outdent();
239     printer->Print(
240         "  }\n"
241         "}\n");
242     printer->Print(
243         "@SuppressWarnings({\"rawtypes\"})\n"
244         "protected com.google.protobuf.MapField internalGetMutableMapField(\n"
245         "    int number) {\n"
246         "  switch (number) {\n");
247     printer->Indent();
248     printer->Indent();
249     for (int i = 0; i < map_fields.size(); ++i) {
250       const FieldDescriptor* field = map_fields[i];
251       const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
252       printer->Print(
253           "case $number$:\n"
254           "  return internalGetMutable$capitalized_name$();\n",
255           "number", StrCat(field->number()), "capitalized_name",
256           info->capitalized_name);
257     }
258     printer->Print(
259         "default:\n"
260         "  throw new RuntimeException(\n"
261         "      \"Invalid map field number: \" + number);\n");
262     printer->Outdent();
263     printer->Outdent();
264     printer->Print(
265         "  }\n"
266         "}\n");
267   }
268   printer->Print(
269       "@java.lang.Override\n"
270       "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n"
271       "    internalGetFieldAccessorTable() {\n"
272       "  return $fileclass$.internal_$identifier$_fieldAccessorTable\n"
273       "      .ensureFieldAccessorsInitialized(\n"
274       "          $classname$.class, $classname$.Builder.class);\n"
275       "}\n"
276       "\n",
277       "classname", name_resolver_->GetImmutableClassName(descriptor_),
278       "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()),
279       "identifier", UniqueFileScopeIdentifier(descriptor_), "ver",
280       GeneratedCodeVersionSuffix());
281 }
282 
283 // ===================================================================
284 
GenerateCommonBuilderMethods(io::Printer * printer)285 void MessageBuilderGenerator::GenerateCommonBuilderMethods(
286     io::Printer* printer) {
287   printer->Print(
288       "// Construct using $classname$.newBuilder()\n"
289       "private Builder() {\n"
290       "  maybeForceBuilderInitialization();\n"
291       "}\n"
292       "\n",
293       "classname", name_resolver_->GetImmutableClassName(descriptor_));
294 
295   printer->Print(
296       "private Builder(\n"
297       "    com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n"
298       "  super(parent);\n"
299       "  maybeForceBuilderInitialization();\n"
300       "}\n",
301       "classname", name_resolver_->GetImmutableClassName(descriptor_), "ver",
302       GeneratedCodeVersionSuffix());
303 
304   printer->Print(
305       "private void maybeForceBuilderInitialization() {\n"
306       "  if (com.google.protobuf.GeneratedMessage$ver$\n"
307       "          .alwaysUseFieldBuilders) {\n",
308       "ver", GeneratedCodeVersionSuffix());
309 
310   printer->Indent();
311   printer->Indent();
312   for (int i = 0; i < descriptor_->field_count(); i++) {
313     if (!descriptor_->field(i)->containing_oneof()) {
314       field_generators_.get(descriptor_->field(i))
315           .GenerateFieldBuilderInitializationCode(printer);
316     }
317   }
318   printer->Outdent();
319   printer->Outdent();
320 
321   printer->Print(
322       "  }\n"
323       "}\n");
324 
325   printer->Print(
326       "@java.lang.Override\n"
327       "public Builder clear() {\n"
328       "  super.clear();\n");
329 
330   printer->Indent();
331 
332   for (int i = 0; i < descriptor_->field_count(); i++) {
333     if (!descriptor_->field(i)->containing_oneof()) {
334       field_generators_.get(descriptor_->field(i))
335           .GenerateBuilderClearCode(printer);
336     }
337   }
338 
339   for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
340     printer->Print(
341         "$oneof_name$Case_ = 0;\n"
342         "$oneof_name$_ = null;\n",
343         "oneof_name",
344         context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name);
345   }
346 
347   printer->Outdent();
348 
349   printer->Print(
350       "  return this;\n"
351       "}\n"
352       "\n");
353 
354   printer->Print(
355       "@java.lang.Override\n"
356       "public com.google.protobuf.Descriptors.Descriptor\n"
357       "    getDescriptorForType() {\n"
358       "  return $fileclass$.internal_$identifier$_descriptor;\n"
359       "}\n"
360       "\n",
361       "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()),
362       "identifier", UniqueFileScopeIdentifier(descriptor_));
363 
364   // LITE runtime implements this in GeneratedMessageLite.
365   printer->Print(
366       "@java.lang.Override\n"
367       "public $classname$ getDefaultInstanceForType() {\n"
368       "  return $classname$.getDefaultInstance();\n"
369       "}\n"
370       "\n",
371       "classname", name_resolver_->GetImmutableClassName(descriptor_));
372 
373   printer->Print(
374       "@java.lang.Override\n"
375       "public $classname$ build() {\n"
376       "  $classname$ result = buildPartial();\n"
377       "  if (!result.isInitialized()) {\n"
378       "    throw newUninitializedMessageException(result);\n"
379       "  }\n"
380       "  return result;\n"
381       "}\n"
382       "\n",
383       "classname", name_resolver_->GetImmutableClassName(descriptor_));
384 
385   printer->Print(
386       "@java.lang.Override\n"
387       "public $classname$ buildPartial() {\n"
388       "  $classname$ result = new $classname$(this);\n",
389       "classname", name_resolver_->GetImmutableClassName(descriptor_));
390 
391   printer->Indent();
392 
393   int totalBuilderBits = 0;
394   int totalMessageBits = 0;
395   for (int i = 0; i < descriptor_->field_count(); i++) {
396     const ImmutableFieldGenerator& field =
397         field_generators_.get(descriptor_->field(i));
398     totalBuilderBits += field.GetNumBitsForBuilder();
399     totalMessageBits += field.GetNumBitsForMessage();
400   }
401   int totalBuilderInts = (totalBuilderBits + 31) / 32;
402   int totalMessageInts = (totalMessageBits + 31) / 32;
403 
404   // Local vars for from and to bit fields to avoid accessing the builder and
405   // message over and over for these fields. Seems to provide a slight
406   // perforamance improvement in micro benchmark and this is also what proto1
407   // code does.
408   for (int i = 0; i < totalBuilderInts; i++) {
409     printer->Print("int from_$bit_field_name$ = $bit_field_name$;\n",
410                    "bit_field_name", GetBitFieldName(i));
411   }
412   for (int i = 0; i < totalMessageInts; i++) {
413     printer->Print("int to_$bit_field_name$ = 0;\n", "bit_field_name",
414                    GetBitFieldName(i));
415   }
416 
417   // Output generation code for each field.
418   for (int i = 0; i < descriptor_->field_count(); i++) {
419     field_generators_.get(descriptor_->field(i)).GenerateBuildingCode(printer);
420   }
421 
422   // Copy the bit field results to the generated message
423   for (int i = 0; i < totalMessageInts; i++) {
424     printer->Print("result.$bit_field_name$ = to_$bit_field_name$;\n",
425                    "bit_field_name", GetBitFieldName(i));
426   }
427 
428   for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
429     printer->Print(
430         "result.$oneof_name$Case_ = $oneof_name$Case_;\n", "oneof_name",
431         context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))->name);
432   }
433 
434   printer->Outdent();
435 
436   printer->Print("  onBuilt();\n");
437 
438   printer->Print(
439       "  return result;\n"
440       "}\n"
441       "\n",
442       "classname", name_resolver_->GetImmutableClassName(descriptor_));
443 
444   // Override methods declared in GeneratedMessage to return the concrete
445   // generated type so callsites won't depend on GeneratedMessage. This
446   // is needed to keep binary compatibility when we change generated code
447   // to subclass a different GeneratedMessage class (e.g., in v3.0.0 release
448   // we changed all generated code to subclass GeneratedMessageV3).
449   printer->Print(
450       "@java.lang.Override\n"
451       "public Builder clone() {\n"
452       "  return super.clone();\n"
453       "}\n"
454       "@java.lang.Override\n"
455       "public Builder setField(\n"
456       "    com.google.protobuf.Descriptors.FieldDescriptor field,\n"
457       "    java.lang.Object value) {\n"
458       "  return super.setField(field, value);\n"
459       "}\n"
460       "@java.lang.Override\n"
461       "public Builder clearField(\n"
462       "    com.google.protobuf.Descriptors.FieldDescriptor field) {\n"
463       "  return super.clearField(field);\n"
464       "}\n"
465       "@java.lang.Override\n"
466       "public Builder clearOneof(\n"
467       "    com.google.protobuf.Descriptors.OneofDescriptor oneof) {\n"
468       "  return super.clearOneof(oneof);\n"
469       "}\n"
470       "@java.lang.Override\n"
471       "public Builder setRepeatedField(\n"
472       "    com.google.protobuf.Descriptors.FieldDescriptor field,\n"
473       "    int index, java.lang.Object value) {\n"
474       "  return super.setRepeatedField(field, index, value);\n"
475       "}\n"
476       "@java.lang.Override\n"
477       "public Builder addRepeatedField(\n"
478       "    com.google.protobuf.Descriptors.FieldDescriptor field,\n"
479       "    java.lang.Object value) {\n"
480       "  return super.addRepeatedField(field, value);\n"
481       "}\n");
482 
483   if (descriptor_->extension_range_count() > 0) {
484     printer->Print(
485         "@java.lang.Override\n"
486         "public <Type> Builder setExtension(\n"
487         "    com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
488         "        $classname$, Type> extension,\n"
489         "    Type value) {\n"
490         "  return super.setExtension(extension, value);\n"
491         "}\n"
492         "@java.lang.Override\n"
493         "public <Type> Builder setExtension(\n"
494         "    com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
495         "        $classname$, java.util.List<Type>> extension,\n"
496         "    int index, Type value) {\n"
497         "  return super.setExtension(extension, index, value);\n"
498         "}\n"
499         "@java.lang.Override\n"
500         "public <Type> Builder addExtension(\n"
501         "    com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
502         "        $classname$, java.util.List<Type>> extension,\n"
503         "    Type value) {\n"
504         "  return super.addExtension(extension, value);\n"
505         "}\n"
506         "@java.lang.Override\n"
507         "public <Type> Builder clearExtension(\n"
508         "    com.google.protobuf.GeneratedMessage.GeneratedExtension<\n"
509         "        $classname$, ?> extension) {\n"
510         "  return super.clearExtension(extension);\n"
511         "}\n",
512         "classname", name_resolver_->GetImmutableClassName(descriptor_));
513   }
514 
515   // -----------------------------------------------------------------
516 
517   if (context_->HasGeneratedMethods(descriptor_)) {
518     printer->Print(
519         "@java.lang.Override\n"
520         "public Builder mergeFrom(com.google.protobuf.Message other) {\n"
521         "  if (other instanceof $classname$) {\n"
522         "    return mergeFrom(($classname$)other);\n"
523         "  } else {\n"
524         "    super.mergeFrom(other);\n"
525         "    return this;\n"
526         "  }\n"
527         "}\n"
528         "\n",
529         "classname", name_resolver_->GetImmutableClassName(descriptor_));
530 
531     printer->Print(
532         "public Builder mergeFrom($classname$ other) {\n"
533         // Optimization:  If other is the default instance, we know none of its
534         //   fields are set so we can skip the merge.
535         "  if (other == $classname$.getDefaultInstance()) return this;\n",
536         "classname", name_resolver_->GetImmutableClassName(descriptor_));
537     printer->Indent();
538 
539     for (int i = 0; i < descriptor_->field_count(); i++) {
540       if (!descriptor_->field(i)->containing_oneof()) {
541         field_generators_.get(descriptor_->field(i))
542             .GenerateMergingCode(printer);
543       }
544     }
545 
546     // Merge oneof fields.
547     for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
548       printer->Print("switch (other.get$oneof_capitalized_name$Case()) {\n",
549                      "oneof_capitalized_name",
550                      context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
551                          ->capitalized_name);
552       printer->Indent();
553       for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
554         const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
555         printer->Print("case $field_name$: {\n", "field_name",
556                        ToUpper(field->name()));
557         printer->Indent();
558         field_generators_.get(field).GenerateMergingCode(printer);
559         printer->Print("break;\n");
560         printer->Outdent();
561         printer->Print("}\n");
562       }
563       printer->Print(
564           "case $cap_oneof_name$_NOT_SET: {\n"
565           "  break;\n"
566           "}\n",
567           "cap_oneof_name",
568           ToUpper(
569               context_->GetOneofGeneratorInfo(descriptor_->oneof_decl(i))
570                   ->name));
571       printer->Outdent();
572       printer->Print("}\n");
573     }
574 
575     printer->Outdent();
576 
577     // if message type has extensions
578     if (descriptor_->extension_range_count() > 0) {
579       printer->Print("  this.mergeExtensionFields(other);\n");
580     }
581 
582     printer->Print("  this.mergeUnknownFields(other.unknownFields);\n");
583 
584     printer->Print("  onChanged();\n");
585 
586     printer->Print(
587         "  return this;\n"
588         "}\n"
589         "\n");
590   }
591 }
592 
593 // ===================================================================
594 
GenerateBuilderParsingMethods(io::Printer * printer)595 void MessageBuilderGenerator::GenerateBuilderParsingMethods(
596     io::Printer* printer) {
597   printer->Print(
598       "@java.lang.Override\n"
599       "public Builder mergeFrom(\n"
600       "    com.google.protobuf.CodedInputStream input,\n"
601       "    com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
602       "    throws java.io.IOException {\n"
603       "  $classname$ parsedMessage = null;\n"
604       "  try {\n"
605       "    parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n"
606       "  } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n"
607       "    parsedMessage = ($classname$) e.getUnfinishedMessage();\n"
608       "    throw e.unwrapIOException();\n"
609       "  } finally {\n"
610       "    if (parsedMessage != null) {\n"
611       "      mergeFrom(parsedMessage);\n"
612       "    }\n"
613       "  }\n"
614       "  return this;\n"
615       "}\n",
616       "classname", name_resolver_->GetImmutableClassName(descriptor_));
617 }
618 
619 // ===================================================================
620 
GenerateIsInitialized(io::Printer * printer)621 void MessageBuilderGenerator::GenerateIsInitialized(io::Printer* printer) {
622   printer->Print(
623       "@java.lang.Override\n"
624       "public final boolean isInitialized() {\n");
625   printer->Indent();
626 
627   // Check that all required fields in this message are set.
628   // TODO(kenton):  We can optimize this when we switch to putting all the
629   //   "has" fields into a single bitfield.
630   for (int i = 0; i < descriptor_->field_count(); i++) {
631     const FieldDescriptor* field = descriptor_->field(i);
632     const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
633 
634     if (field->is_required()) {
635       printer->Print(
636           "if (!has$name$()) {\n"
637           "  return false;\n"
638           "}\n",
639           "name", info->capitalized_name);
640     }
641   }
642 
643   // Now check that all embedded messages are initialized.
644   for (int i = 0; i < descriptor_->field_count(); i++) {
645     const FieldDescriptor* field = descriptor_->field(i);
646     const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
647     if (GetJavaType(field) == JAVATYPE_MESSAGE &&
648         HasRequiredFields(field->message_type())) {
649       switch (field->label()) {
650         case FieldDescriptor::LABEL_REQUIRED:
651           printer->Print(
652               "if (!get$name$().isInitialized()) {\n"
653               "  return false;\n"
654               "}\n",
655               "type",
656               name_resolver_->GetImmutableClassName(field->message_type()),
657               "name", info->capitalized_name);
658           break;
659         case FieldDescriptor::LABEL_OPTIONAL:
660           if (!SupportFieldPresence(descriptor_->file()) &&
661               field->containing_oneof() != NULL) {
662             const OneofDescriptor* oneof = field->containing_oneof();
663             const OneofGeneratorInfo* oneof_info =
664                 context_->GetOneofGeneratorInfo(oneof);
665             printer->Print("if ($oneof_name$Case_ == $field_number$) {\n",
666                            "oneof_name", oneof_info->name, "field_number",
667                            StrCat(field->number()));
668           } else {
669             printer->Print("if (has$name$()) {\n", "name",
670                            info->capitalized_name);
671           }
672           printer->Print(
673               "  if (!get$name$().isInitialized()) {\n"
674               "    return false;\n"
675               "  }\n"
676               "}\n",
677               "name", info->capitalized_name);
678           break;
679         case FieldDescriptor::LABEL_REPEATED:
680           if (IsMapEntry(field->message_type())) {
681             printer->Print(
682                 "for ($type$ item : get$name$Map().values()) {\n"
683                 "  if (!item.isInitialized()) {\n"
684                 "    return false;\n"
685                 "  }\n"
686                 "}\n",
687                 "type",
688                 MapValueImmutableClassdName(field->message_type(),
689                                             name_resolver_),
690                 "name", info->capitalized_name);
691           } else {
692             printer->Print(
693                 "for (int i = 0; i < get$name$Count(); i++) {\n"
694                 "  if (!get$name$(i).isInitialized()) {\n"
695                 "    return false;\n"
696                 "  }\n"
697                 "}\n",
698                 "type",
699                 name_resolver_->GetImmutableClassName(field->message_type()),
700                 "name", info->capitalized_name);
701           }
702           break;
703       }
704     }
705   }
706 
707   if (descriptor_->extension_range_count() > 0) {
708     printer->Print(
709         "if (!extensionsAreInitialized()) {\n"
710         "  return false;\n"
711         "}\n");
712   }
713 
714   printer->Outdent();
715 
716   printer->Print(
717       "  return true;\n"
718       "}\n"
719       "\n");
720 }
721 
722 // ===================================================================
723 
724 }  // namespace java
725 }  // namespace compiler
726 }  // namespace protobuf
727 }  // namespace google
728