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: kenton@google.com (Kenton Varda)
32 //  Based on original Protocol Buffers design by
33 //  Sanjay Ghemawat, Jeff Dean, and others.
34 
35 #include <map>
36 #include <string>
37 
38 #include <google/protobuf/compiler/java/java_context.h>
39 #include <google/protobuf/compiler/java/java_message_field.h>
40 #include <google/protobuf/compiler/java/java_doc_comment.h>
41 #include <google/protobuf/compiler/java/java_helpers.h>
42 #include <google/protobuf/compiler/java/java_name_resolver.h>
43 #include <google/protobuf/io/printer.h>
44 #include <google/protobuf/wire_format.h>
45 #include <google/protobuf/stubs/strutil.h>
46 
47 namespace google {
48 namespace protobuf {
49 namespace compiler {
50 namespace java {
51 
52 namespace {
53 
SetMessageVariables(const FieldDescriptor * descriptor,int messageBitIndex,int builderBitIndex,const FieldGeneratorInfo * info,ClassNameResolver * name_resolver,map<string,string> * variables)54 void SetMessageVariables(const FieldDescriptor* descriptor,
55                          int messageBitIndex,
56                          int builderBitIndex,
57                          const FieldGeneratorInfo* info,
58                          ClassNameResolver* name_resolver,
59                          map<string, string>* variables) {
60   SetCommonFieldVariables(descriptor, info, variables);
61 
62   (*variables)["type"] =
63       name_resolver->GetImmutableClassName(descriptor->message_type());
64   (*variables)["mutable_type"] =
65       name_resolver->GetMutableClassName(descriptor->message_type());
66   (*variables)["group_or_message"] =
67     (GetType(descriptor) == FieldDescriptor::TYPE_GROUP) ?
68     "Group" : "Message";
69   // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported
70   // by the proto compiler
71   (*variables)["deprecation"] = descriptor->options().deprecated()
72       ? "@java.lang.Deprecated " : "";
73   (*variables)["on_changed"] = "onChanged();";
74   (*variables)["ver"] = GeneratedCodeVersionSuffix();
75   (*variables)["get_parser"] =
76       ExposePublicParser(descriptor->message_type()->file())
77           ? "PARSER" : "parser()";
78 
79   if (SupportFieldPresence(descriptor->file())) {
80     // For singular messages and builders, one bit is used for the hasField bit.
81     (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
82     (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
83 
84     // Note that these have a trailing ";".
85     (*variables)["set_has_field_bit_message"] =
86         GenerateSetBit(messageBitIndex) + ";";
87     (*variables)["set_has_field_bit_builder"] =
88         GenerateSetBit(builderBitIndex) + ";";
89     (*variables)["clear_has_field_bit_builder"] =
90         GenerateClearBit(builderBitIndex) + ";";
91 
92     (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
93   } else {
94     (*variables)["set_has_field_bit_message"] = "";
95     (*variables)["set_has_field_bit_builder"] = "";
96     (*variables)["clear_has_field_bit_builder"] = "";
97 
98     (*variables)["is_field_present_message"] =
99         (*variables)["name"] + "_ != null";
100   }
101 
102   // For repated builders, one bit is used for whether the array is immutable.
103   (*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex);
104   (*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex);
105   (*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex);
106 
107   // For repeated fields, one bit is used for whether the array is immutable
108   // in the parsing constructor.
109   (*variables)["get_mutable_bit_parser"] =
110       GenerateGetBitMutableLocal(builderBitIndex);
111   (*variables)["set_mutable_bit_parser"] =
112       GenerateSetBitMutableLocal(builderBitIndex);
113 
114   (*variables)["get_has_field_bit_from_local"] =
115       GenerateGetBitFromLocal(builderBitIndex);
116   (*variables)["set_has_field_bit_to_local"] =
117       GenerateSetBitToLocal(messageBitIndex);
118 }
119 
120 }  // namespace
121 
122 // ===================================================================
123 
124 ImmutableMessageFieldGenerator::
ImmutableMessageFieldGenerator(const FieldDescriptor * descriptor,int messageBitIndex,int builderBitIndex,Context * context)125 ImmutableMessageFieldGenerator(const FieldDescriptor* descriptor,
126                       int messageBitIndex,
127                       int builderBitIndex,
128                       Context* context)
129   : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
130     builderBitIndex_(builderBitIndex), context_(context),
131     name_resolver_(context->GetNameResolver()) {
132     SetMessageVariables(descriptor, messageBitIndex, builderBitIndex,
133                         context->GetFieldGeneratorInfo(descriptor),
134                         name_resolver_, &variables_);
135 }
136 
~ImmutableMessageFieldGenerator()137 ImmutableMessageFieldGenerator::~ImmutableMessageFieldGenerator() {}
138 
GetNumBitsForMessage() const139 int ImmutableMessageFieldGenerator::GetNumBitsForMessage() const {
140   return 1;
141 }
142 
GetNumBitsForBuilder() const143 int ImmutableMessageFieldGenerator::GetNumBitsForBuilder() const {
144   return 1;
145 }
146 
147 void ImmutableMessageFieldGenerator::
GenerateInterfaceMembers(io::Printer * printer) const148 GenerateInterfaceMembers(io::Printer* printer) const {
149   // TODO(jonp): In the future, consider having a method specific to the
150   // interface so that builders can choose dynamically to either return a
151   // message or a nested builder, so that asking for the interface doesn't
152   // cause a message to ever be built.
153   if (SupportFieldPresence(descriptor_->file()) ||
154       descriptor_->containing_oneof() == NULL) {
155     WriteFieldDocComment(printer, descriptor_);
156     printer->Print(variables_,
157       "$deprecation$boolean has$capitalized_name$();\n");
158   }
159   WriteFieldDocComment(printer, descriptor_);
160   printer->Print(variables_,
161     "$deprecation$$type$ get$capitalized_name$();\n");
162 
163   WriteFieldDocComment(printer, descriptor_);
164   printer->Print(variables_,
165     "$deprecation$$type$OrBuilder get$capitalized_name$OrBuilder();\n");
166 }
167 
168 void ImmutableMessageFieldGenerator::
GenerateMembers(io::Printer * printer) const169 GenerateMembers(io::Printer* printer) const {
170   printer->Print(variables_,
171     "private $type$ $name$_;\n");
172   PrintExtraFieldInfo(variables_, printer);
173 
174   if (SupportFieldPresence(descriptor_->file())) {
175     WriteFieldDocComment(printer, descriptor_);
176     printer->Print(variables_,
177       "$deprecation$public boolean has$capitalized_name$() {\n"
178       "  return $get_has_field_bit_message$;\n"
179       "}\n");
180     WriteFieldDocComment(printer, descriptor_);
181     printer->Print(variables_,
182       "$deprecation$public $type$ get$capitalized_name$() {\n"
183       "  return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
184       "}\n");
185 
186     WriteFieldDocComment(printer, descriptor_);
187     printer->Print(variables_,
188       "$deprecation$public $type$OrBuilder "
189       "get$capitalized_name$OrBuilder() {\n"
190       "  return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
191       "}\n");
192   } else {
193     WriteFieldDocComment(printer, descriptor_);
194     printer->Print(variables_,
195       "$deprecation$public boolean has$capitalized_name$() {\n"
196       "  return $name$_ != null;\n"
197       "}\n");
198     WriteFieldDocComment(printer, descriptor_);
199     printer->Print(variables_,
200       "$deprecation$public $type$ get$capitalized_name$() {\n"
201       "  return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n"
202       "}\n");
203 
204     WriteFieldDocComment(printer, descriptor_);
205     printer->Print(variables_,
206       "$deprecation$public $type$OrBuilder "
207       "get$capitalized_name$OrBuilder() {\n"
208       "  return get$capitalized_name$();\n"
209       "}\n");
210   }
211 }
212 
PrintNestedBuilderCondition(io::Printer * printer,const char * regular_case,const char * nested_builder_case) const213 void ImmutableMessageFieldGenerator::PrintNestedBuilderCondition(
214     io::Printer* printer,
215     const char* regular_case,
216     const char* nested_builder_case) const {
217   printer->Print(variables_, "if ($name$Builder_ == null) {\n");
218   printer->Indent();
219   printer->Print(variables_, regular_case);
220   printer->Outdent();
221   printer->Print("} else {\n");
222   printer->Indent();
223   printer->Print(variables_, nested_builder_case);
224   printer->Outdent();
225   printer->Print("}\n");
226 }
227 
PrintNestedBuilderFunction(io::Printer * printer,const char * method_prototype,const char * regular_case,const char * nested_builder_case,const char * trailing_code) const228 void ImmutableMessageFieldGenerator::PrintNestedBuilderFunction(
229     io::Printer* printer,
230     const char* method_prototype,
231     const char* regular_case,
232     const char* nested_builder_case,
233     const char* trailing_code) const {
234   printer->Print(variables_, method_prototype);
235   printer->Print(" {\n");
236   printer->Indent();
237   PrintNestedBuilderCondition(printer, regular_case, nested_builder_case);
238   if (trailing_code != NULL) {
239     printer->Print(variables_, trailing_code);
240   }
241   printer->Outdent();
242   printer->Print("}\n");
243 }
244 
245 void ImmutableMessageFieldGenerator::
GenerateBuilderMembers(io::Printer * printer) const246 GenerateBuilderMembers(io::Printer* printer) const {
247   // When using nested-builders, the code initially works just like the
248   // non-nested builder case. It only creates a nested builder lazily on
249   // demand and then forever delegates to it after creation.
250 
251   bool support_field_presence = SupportFieldPresence(descriptor_->file());
252 
253   printer->Print(variables_,
254     "private $type$ $name$_ = null;\n");
255 
256   printer->Print(variables_,
257       // If this builder is non-null, it is used and the other fields are
258       // ignored.
259       "private com.google.protobuf.SingleFieldBuilder$ver$<\n"
260       "    $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;"
261       "\n");
262 
263   // The comments above the methods below are based on a hypothetical
264   // field of type "Field" called "Field".
265 
266   // boolean hasField()
267   WriteFieldDocComment(printer, descriptor_);
268   if (support_field_presence) {
269     printer->Print(variables_,
270       "$deprecation$public boolean has$capitalized_name$() {\n"
271       "  return $get_has_field_bit_builder$;\n"
272       "}\n");
273   } else {
274     printer->Print(variables_,
275       "$deprecation$public boolean has$capitalized_name$() {\n"
276       "  return $name$Builder_ != null || $name$_ != null;\n"
277       "}\n");
278   }
279 
280   // Field getField()
281   WriteFieldDocComment(printer, descriptor_);
282   PrintNestedBuilderFunction(printer,
283     "$deprecation$public $type$ get$capitalized_name$()",
284     "return $name$_ == null ? $type$.getDefaultInstance() : $name$_;\n",
285     "return $name$Builder_.getMessage();\n",
286     NULL);
287 
288   // Field.Builder setField(Field value)
289   WriteFieldDocComment(printer, descriptor_);
290   PrintNestedBuilderFunction(printer,
291     "$deprecation$public Builder set$capitalized_name$($type$ value)",
292 
293     "if (value == null) {\n"
294     "  throw new NullPointerException();\n"
295     "}\n"
296     "$name$_ = value;\n"
297     "$on_changed$\n",
298 
299     "$name$Builder_.setMessage(value);\n",
300 
301     "$set_has_field_bit_builder$\n"
302     "return this;\n");
303 
304   // Field.Builder setField(Field.Builder builderForValue)
305   WriteFieldDocComment(printer, descriptor_);
306   PrintNestedBuilderFunction(printer,
307     "$deprecation$public Builder set$capitalized_name$(\n"
308     "    $type$.Builder builderForValue)",
309 
310     "$name$_ = builderForValue.build();\n"
311     "$on_changed$\n",
312 
313     "$name$Builder_.setMessage(builderForValue.build());\n",
314 
315     "$set_has_field_bit_builder$\n"
316     "return this;\n");
317 
318   // Field.Builder mergeField(Field value)
319   WriteFieldDocComment(printer, descriptor_);
320   PrintNestedBuilderFunction(printer,
321     "$deprecation$public Builder merge$capitalized_name$($type$ value)",
322 
323     support_field_presence
324         ? "if ($get_has_field_bit_builder$ &&\n"
325           "    $name$_ != null &&\n"
326           "    $name$_ != $type$.getDefaultInstance()) {\n"
327           "  $name$_ =\n"
328           "    $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n"
329           "} else {\n"
330           "  $name$_ = value;\n"
331           "}\n"
332           "$on_changed$\n"
333         : "if ($name$_ != null) {\n"
334           "  $name$_ =\n"
335           "    $type$.newBuilder($name$_).mergeFrom(value).buildPartial();\n"
336           "} else {\n"
337           "  $name$_ = value;\n"
338           "}\n"
339           "$on_changed$\n",
340 
341     "$name$Builder_.mergeFrom(value);\n",
342 
343     "$set_has_field_bit_builder$\n"
344     "return this;\n");
345 
346   // Field.Builder clearField()
347   WriteFieldDocComment(printer, descriptor_);
348   PrintNestedBuilderFunction(printer,
349     "$deprecation$public Builder clear$capitalized_name$()",
350 
351     "$name$_ = null;\n"
352     "$on_changed$\n",
353 
354     support_field_presence
355         ? "$name$Builder_.clear();\n"
356         : "$name$_ = null;\n"
357           "$name$Builder_ = null;\n",
358 
359     "$clear_has_field_bit_builder$\n"
360     "return this;\n");
361 
362   WriteFieldDocComment(printer, descriptor_);
363   printer->Print(variables_,
364     "$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n"
365     "  $set_has_field_bit_builder$\n"
366     "  $on_changed$\n"
367     "  return get$capitalized_name$FieldBuilder().getBuilder();\n"
368     "}\n");
369   WriteFieldDocComment(printer, descriptor_);
370   printer->Print(variables_,
371     "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
372     "  if ($name$Builder_ != null) {\n"
373     "    return $name$Builder_.getMessageOrBuilder();\n"
374     "  } else {\n"
375     "    return $name$_ == null ?\n"
376     "        $type$.getDefaultInstance() : $name$_;\n"
377     "  }\n"
378     "}\n");
379   WriteFieldDocComment(printer, descriptor_);
380   printer->Print(variables_,
381     "private com.google.protobuf.SingleFieldBuilder$ver$<\n"
382     "    $type$, $type$.Builder, $type$OrBuilder> \n"
383     "    get$capitalized_name$FieldBuilder() {\n"
384     "  if ($name$Builder_ == null) {\n"
385     "    $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n"
386     "        $type$, $type$.Builder, $type$OrBuilder>(\n"
387     "            get$capitalized_name$(),\n"
388     "            getParentForChildren(),\n"
389     "            isClean());\n"
390     "    $name$_ = null;\n"
391     "  }\n"
392     "  return $name$Builder_;\n"
393     "}\n");
394 }
395 
396 void ImmutableMessageFieldGenerator::
GenerateFieldBuilderInitializationCode(io::Printer * printer) const397 GenerateFieldBuilderInitializationCode(io::Printer* printer)  const {
398   if (SupportFieldPresence(descriptor_->file())) {
399     printer->Print(variables_,
400       "get$capitalized_name$FieldBuilder();\n");
401   }
402 }
403 
404 
405 void ImmutableMessageFieldGenerator::
GenerateInitializationCode(io::Printer * printer) const406 GenerateInitializationCode(io::Printer* printer) const {}
407 
408 void ImmutableMessageFieldGenerator::
GenerateBuilderClearCode(io::Printer * printer) const409 GenerateBuilderClearCode(io::Printer* printer) const {
410   if (SupportFieldPresence(descriptor_->file())) {
411     PrintNestedBuilderCondition(printer,
412       "$name$_ = null;\n",
413 
414       "$name$Builder_.clear();\n");
415     printer->Print(variables_, "$clear_has_field_bit_builder$\n");
416   } else {
417     PrintNestedBuilderCondition(printer,
418       "$name$_ = null;\n",
419 
420       "$name$_ = null;\n"
421       "$name$Builder_ = null;\n");
422   }
423 }
424 
425 void ImmutableMessageFieldGenerator::
GenerateMergingCode(io::Printer * printer) const426 GenerateMergingCode(io::Printer* printer) const {
427   printer->Print(variables_,
428     "if (other.has$capitalized_name$()) {\n"
429     "  merge$capitalized_name$(other.get$capitalized_name$());\n"
430     "}\n");
431 }
432 
433 void ImmutableMessageFieldGenerator::
GenerateBuildingCode(io::Printer * printer) const434 GenerateBuildingCode(io::Printer* printer) const {
435   if (SupportFieldPresence(descriptor_->file())) {
436     printer->Print(variables_,
437         "if ($get_has_field_bit_from_local$) {\n"
438         "  $set_has_field_bit_to_local$;\n"
439         "}\n");
440   }
441 
442   PrintNestedBuilderCondition(printer,
443     "result.$name$_ = $name$_;\n",
444 
445     "result.$name$_ = $name$Builder_.build();\n");
446 }
447 
448 void ImmutableMessageFieldGenerator::
GenerateParsingCode(io::Printer * printer) const449 GenerateParsingCode(io::Printer* printer) const {
450   printer->Print(variables_,
451     "$type$.Builder subBuilder = null;\n"
452     "if ($is_field_present_message$) {\n"
453     "  subBuilder = $name$_.toBuilder();\n"
454     "}\n");
455 
456   if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) {
457     printer->Print(variables_,
458       "$name$_ = input.readGroup($number$, $type$.$get_parser$,\n"
459       "    extensionRegistry);\n");
460   } else {
461     printer->Print(variables_,
462       "$name$_ = input.readMessage($type$.$get_parser$, extensionRegistry);\n");
463   }
464 
465   printer->Print(variables_,
466     "if (subBuilder != null) {\n"
467     "  subBuilder.mergeFrom($name$_);\n"
468     "  $name$_ = subBuilder.buildPartial();\n"
469     "}\n"
470     "$set_has_field_bit_message$\n");
471 }
472 
473 void ImmutableMessageFieldGenerator::
GenerateParsingDoneCode(io::Printer * printer) const474 GenerateParsingDoneCode(io::Printer* printer) const {
475   // noop for messages.
476 }
477 
478 void ImmutableMessageFieldGenerator::
GenerateSerializationCode(io::Printer * printer) const479 GenerateSerializationCode(io::Printer* printer) const {
480   printer->Print(variables_,
481     "if ($is_field_present_message$) {\n"
482     "  output.write$group_or_message$($number$, get$capitalized_name$());\n"
483     "}\n");
484 }
485 
486 void ImmutableMessageFieldGenerator::
GenerateSerializedSizeCode(io::Printer * printer) const487 GenerateSerializedSizeCode(io::Printer* printer) const {
488   printer->Print(variables_,
489     "if ($is_field_present_message$) {\n"
490     "  size += com.google.protobuf.CodedOutputStream\n"
491     "    .compute$group_or_message$Size($number$, get$capitalized_name$());\n"
492     "}\n");
493 }
494 
495 void ImmutableMessageFieldGenerator::
GenerateEqualsCode(io::Printer * printer) const496 GenerateEqualsCode(io::Printer* printer) const {
497   printer->Print(variables_,
498     "result = result && get$capitalized_name$()\n"
499     "    .equals(other.get$capitalized_name$());\n");
500 }
501 
502 void ImmutableMessageFieldGenerator::
GenerateHashCode(io::Printer * printer) const503 GenerateHashCode(io::Printer* printer) const {
504   printer->Print(variables_,
505     "hash = (37 * hash) + $constant_name$;\n"
506     "hash = (53 * hash) + get$capitalized_name$().hashCode();\n");
507 }
508 
GetBoxedType() const509 string ImmutableMessageFieldGenerator::GetBoxedType() const {
510   return name_resolver_->GetImmutableClassName(descriptor_->message_type());
511 }
512 
513 // ===================================================================
514 
515 ImmutableMessageOneofFieldGenerator::
ImmutableMessageOneofFieldGenerator(const FieldDescriptor * descriptor,int messageBitIndex,int builderBitIndex,Context * context)516 ImmutableMessageOneofFieldGenerator(const FieldDescriptor* descriptor,
517                                  int messageBitIndex,
518                                  int builderBitIndex,
519                                  Context* context)
520     : ImmutableMessageFieldGenerator(
521           descriptor, messageBitIndex, builderBitIndex, context) {
522   const OneofGeneratorInfo* info =
523       context->GetOneofGeneratorInfo(descriptor->containing_oneof());
524   SetCommonOneofVariables(descriptor, info, &variables_);
525 }
526 
527 ImmutableMessageOneofFieldGenerator::
~ImmutableMessageOneofFieldGenerator()528 ~ImmutableMessageOneofFieldGenerator() {}
529 
530 void ImmutableMessageOneofFieldGenerator::
GenerateMembers(io::Printer * printer) const531 GenerateMembers(io::Printer* printer) const {
532   PrintExtraFieldInfo(variables_, printer);
533   if (SupportFieldPresence(descriptor_->file())) {
534     WriteFieldDocComment(printer, descriptor_);
535     printer->Print(variables_,
536       "$deprecation$public boolean has$capitalized_name$() {\n"
537       "  return $has_oneof_case_message$;\n"
538       "}\n");
539   }
540   WriteFieldDocComment(printer, descriptor_);
541   printer->Print(variables_,
542     "$deprecation$public $type$ get$capitalized_name$() {\n"
543     "  if ($has_oneof_case_message$) {\n"
544     "     return ($type$) $oneof_name$_;\n"
545     "  }\n"
546     "  return $type$.getDefaultInstance();\n"
547     "}\n");
548 
549   WriteFieldDocComment(printer, descriptor_);
550   printer->Print(variables_,
551     "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
552     "  if ($has_oneof_case_message$) {\n"
553     "     return ($type$) $oneof_name$_;\n"
554     "  }\n"
555     "  return $type$.getDefaultInstance();\n"
556     "}\n");
557 }
558 
559 void ImmutableMessageOneofFieldGenerator::
GenerateBuilderMembers(io::Printer * printer) const560 GenerateBuilderMembers(io::Printer* printer) const {
561   // When using nested-builders, the code initially works just like the
562   // non-nested builder case. It only creates a nested builder lazily on
563   // demand and then forever delegates to it after creation.
564   printer->Print(variables_,
565     // If this builder is non-null, it is used and the other fields are
566     // ignored.
567     "private com.google.protobuf.SingleFieldBuilder$ver$<\n"
568     "    $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;"
569     "\n");
570 
571   // The comments above the methods below are based on a hypothetical
572   // field of type "Field" called "Field".
573 
574   if (SupportFieldPresence(descriptor_->file())) {
575     // boolean hasField()
576     WriteFieldDocComment(printer, descriptor_);
577     printer->Print(variables_,
578       "$deprecation$public boolean has$capitalized_name$() {\n"
579       "  return $has_oneof_case_message$;\n"
580       "}\n");
581   }
582 
583   // Field getField()
584   WriteFieldDocComment(printer, descriptor_);
585   PrintNestedBuilderFunction(printer,
586     "$deprecation$public $type$ get$capitalized_name$()",
587 
588     "if ($has_oneof_case_message$) {\n"
589     "  return ($type$) $oneof_name$_;\n"
590     "}\n"
591     "return $type$.getDefaultInstance();\n",
592 
593     "if ($has_oneof_case_message$) {\n"
594     "  return $name$Builder_.getMessage();\n"
595     "}\n"
596     "return $type$.getDefaultInstance();\n",
597 
598     NULL);
599 
600   // Field.Builder setField(Field value)
601   WriteFieldDocComment(printer, descriptor_);
602   PrintNestedBuilderFunction(printer,
603     "$deprecation$public Builder set$capitalized_name$($type$ value)",
604 
605     "if (value == null) {\n"
606     "  throw new NullPointerException();\n"
607     "}\n"
608     "$oneof_name$_ = value;\n"
609     "$on_changed$\n",
610 
611     "$name$Builder_.setMessage(value);\n",
612 
613     "$set_oneof_case_message$;\n"
614     "return this;\n");
615 
616   // Field.Builder setField(Field.Builder builderForValue)
617   WriteFieldDocComment(printer, descriptor_);
618   PrintNestedBuilderFunction(printer,
619     "$deprecation$public Builder set$capitalized_name$(\n"
620     "    $type$.Builder builderForValue)",
621 
622     "$oneof_name$_ = builderForValue.build();\n"
623     "$on_changed$\n",
624 
625     "$name$Builder_.setMessage(builderForValue.build());\n",
626 
627     "$set_oneof_case_message$;\n"
628     "return this;\n");
629 
630   // Field.Builder mergeField(Field value)
631   WriteFieldDocComment(printer, descriptor_);
632   PrintNestedBuilderFunction(printer,
633     "$deprecation$public Builder merge$capitalized_name$($type$ value)",
634 
635     "if ($has_oneof_case_message$ &&\n"
636     "    $oneof_name$_ != $type$.getDefaultInstance()) {\n"
637     "  $oneof_name$_ = $type$.newBuilder(($type$) $oneof_name$_)\n"
638     "      .mergeFrom(value).buildPartial();\n"
639     "} else {\n"
640     "  $oneof_name$_ = value;\n"
641     "}\n"
642     "$on_changed$\n",
643 
644     "if ($has_oneof_case_message$) {\n"
645     "  $name$Builder_.mergeFrom(value);\n"
646     "}\n"
647     "$name$Builder_.setMessage(value);\n",
648 
649     "$set_oneof_case_message$;\n"
650     "return this;\n");
651 
652   // Field.Builder clearField()
653   WriteFieldDocComment(printer, descriptor_);
654   PrintNestedBuilderFunction(printer,
655     "$deprecation$public Builder clear$capitalized_name$()",
656 
657     "if ($has_oneof_case_message$) {\n"
658     "  $clear_oneof_case_message$;\n"
659     "  $oneof_name$_ = null;\n"
660     "  $on_changed$\n"
661     "}\n",
662 
663     "if ($has_oneof_case_message$) {\n"
664     "  $clear_oneof_case_message$;\n"
665     "  $oneof_name$_ = null;\n"
666     "}\n"
667     "$name$Builder_.clear();\n",
668 
669     "return this;\n");
670 
671   WriteFieldDocComment(printer, descriptor_);
672   printer->Print(variables_,
673     "$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n"
674     "  return get$capitalized_name$FieldBuilder().getBuilder();\n"
675     "}\n");
676   WriteFieldDocComment(printer, descriptor_);
677   printer->Print(variables_,
678     "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n"
679     "  if (($has_oneof_case_message$) && ($name$Builder_ != null)) {\n"
680     "    return $name$Builder_.getMessageOrBuilder();\n"
681     "  } else {\n"
682     "    if ($has_oneof_case_message$) {\n"
683     "      return ($type$) $oneof_name$_;\n"
684     "    }\n"
685     "    return $type$.getDefaultInstance();\n"
686     "  }\n"
687     "}\n");
688   WriteFieldDocComment(printer, descriptor_);
689   printer->Print(variables_,
690     "private com.google.protobuf.SingleFieldBuilder$ver$<\n"
691     "    $type$, $type$.Builder, $type$OrBuilder> \n"
692     "    get$capitalized_name$FieldBuilder() {\n"
693     "  if ($name$Builder_ == null) {\n"
694     "    if (!($has_oneof_case_message$)) {\n"
695     "      $oneof_name$_ = $type$.getDefaultInstance();\n"
696     "    }\n"
697     "    $name$Builder_ = new com.google.protobuf.SingleFieldBuilder$ver$<\n"
698     "        $type$, $type$.Builder, $type$OrBuilder>(\n"
699     "            ($type$) $oneof_name$_,\n"
700     "            getParentForChildren(),\n"
701     "            isClean());\n"
702     "    $oneof_name$_ = null;\n"
703     "  }\n"
704     "  $set_oneof_case_message$;\n"
705     "  $on_changed$;\n"
706     "  return $name$Builder_;\n"
707     "}\n");
708 }
709 
710 void ImmutableMessageOneofFieldGenerator::
GenerateBuildingCode(io::Printer * printer) const711 GenerateBuildingCode(io::Printer* printer) const {
712 
713   printer->Print(variables_,
714                  "if ($has_oneof_case_message$) {\n");
715   printer->Indent();
716 
717   PrintNestedBuilderCondition(printer,
718     "result.$oneof_name$_ = $oneof_name$_;\n",
719 
720     "result.$oneof_name$_ = $name$Builder_.build();\n");
721 
722   printer->Outdent();
723   printer->Print("}\n");
724 }
725 
726 void ImmutableMessageOneofFieldGenerator::
GenerateMergingCode(io::Printer * printer) const727 GenerateMergingCode(io::Printer* printer) const {
728   printer->Print(variables_,
729     "merge$capitalized_name$(other.get$capitalized_name$());\n");
730 }
731 
732 void ImmutableMessageOneofFieldGenerator::
GenerateParsingCode(io::Printer * printer) const733 GenerateParsingCode(io::Printer* printer) const {
734   printer->Print(variables_,
735     "$type$.Builder subBuilder = null;\n"
736     "if ($has_oneof_case_message$) {\n"
737     "  subBuilder = (($type$) $oneof_name$_).toBuilder();\n"
738     "}\n");
739 
740   if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) {
741     printer->Print(variables_,
742       "$oneof_name$_ = input.readGroup($number$, $type$.$get_parser$,\n"
743       "    extensionRegistry);\n");
744   } else {
745     printer->Print(variables_,
746       "$oneof_name$_ =\n"
747       "    input.readMessage($type$.$get_parser$, extensionRegistry);\n");
748   }
749 
750   printer->Print(variables_,
751     "if (subBuilder != null) {\n"
752     "  subBuilder.mergeFrom(($type$) $oneof_name$_);\n"
753     "  $oneof_name$_ = subBuilder.buildPartial();\n"
754     "}\n");
755   printer->Print(variables_,
756     "$set_oneof_case_message$;\n");
757 }
758 
759 void ImmutableMessageOneofFieldGenerator::
GenerateSerializationCode(io::Printer * printer) const760 GenerateSerializationCode(io::Printer* printer) const {
761   printer->Print(variables_,
762     "if ($has_oneof_case_message$) {\n"
763     "  output.write$group_or_message$($number$, ($type$) $oneof_name$_);\n"
764     "}\n");
765 }
766 
767 void ImmutableMessageOneofFieldGenerator::
GenerateSerializedSizeCode(io::Printer * printer) const768 GenerateSerializedSizeCode(io::Printer* printer) const {
769   printer->Print(variables_,
770     "if ($has_oneof_case_message$) {\n"
771     "  size += com.google.protobuf.CodedOutputStream\n"
772     "    .compute$group_or_message$Size($number$, ($type$) $oneof_name$_);\n"
773     "}\n");
774 }
775 
776 // ===================================================================
777 
778 RepeatedImmutableMessageFieldGenerator::
RepeatedImmutableMessageFieldGenerator(const FieldDescriptor * descriptor,int messageBitIndex,int builderBitIndex,Context * context)779 RepeatedImmutableMessageFieldGenerator(const FieldDescriptor* descriptor,
780                                        int messageBitIndex,
781                                        int builderBitIndex,
782                                        Context* context)
783   : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
784     builderBitIndex_(builderBitIndex), context_(context),
785     name_resolver_(context->GetNameResolver())  {
786   SetMessageVariables(descriptor, messageBitIndex, builderBitIndex,
787                       context->GetFieldGeneratorInfo(descriptor),
788                       name_resolver_, &variables_);
789 }
790 
791 RepeatedImmutableMessageFieldGenerator::
~RepeatedImmutableMessageFieldGenerator()792 ~RepeatedImmutableMessageFieldGenerator() {}
793 
GetNumBitsForMessage() const794 int RepeatedImmutableMessageFieldGenerator::GetNumBitsForMessage() const {
795   return 0;
796 }
797 
GetNumBitsForBuilder() const798 int RepeatedImmutableMessageFieldGenerator::GetNumBitsForBuilder() const {
799   return 1;
800 }
801 
802 void RepeatedImmutableMessageFieldGenerator::
GenerateInterfaceMembers(io::Printer * printer) const803 GenerateInterfaceMembers(io::Printer* printer) const {
804   // TODO(jonp): In the future, consider having methods specific to the
805   // interface so that builders can choose dynamically to either return a
806   // message or a nested builder, so that asking for the interface doesn't
807   // cause a message to ever be built.
808   WriteFieldDocComment(printer, descriptor_);
809   printer->Print(variables_,
810     "$deprecation$java.util.List<$type$> \n"
811     "    get$capitalized_name$List();\n");
812   WriteFieldDocComment(printer, descriptor_);
813   printer->Print(variables_,
814     "$deprecation$$type$ get$capitalized_name$(int index);\n");
815   WriteFieldDocComment(printer, descriptor_);
816   printer->Print(variables_,
817     "$deprecation$int get$capitalized_name$Count();\n");
818 
819   WriteFieldDocComment(printer, descriptor_);
820   printer->Print(variables_,
821     "$deprecation$java.util.List<? extends $type$OrBuilder> \n"
822     "    get$capitalized_name$OrBuilderList();\n");
823   WriteFieldDocComment(printer, descriptor_);
824   printer->Print(variables_,
825     "$deprecation$$type$OrBuilder get$capitalized_name$OrBuilder(\n"
826     "    int index);\n");
827 }
828 
829 void RepeatedImmutableMessageFieldGenerator::
GenerateMembers(io::Printer * printer) const830 GenerateMembers(io::Printer* printer) const {
831   printer->Print(variables_,
832     "private java.util.List<$type$> $name$_;\n");
833   PrintExtraFieldInfo(variables_, printer);
834   WriteFieldDocComment(printer, descriptor_);
835   printer->Print(variables_,
836     "$deprecation$public java.util.List<$type$> get$capitalized_name$List() {\n"
837     "  return $name$_;\n"   // note:  unmodifiable list
838     "}\n");
839   WriteFieldDocComment(printer, descriptor_);
840   printer->Print(variables_,
841     "$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
842     "    get$capitalized_name$OrBuilderList() {\n"
843     "  return $name$_;\n"
844     "}\n");
845   WriteFieldDocComment(printer, descriptor_);
846   printer->Print(variables_,
847     "$deprecation$public int get$capitalized_name$Count() {\n"
848     "  return $name$_.size();\n"
849     "}\n");
850   WriteFieldDocComment(printer, descriptor_);
851   printer->Print(variables_,
852     "$deprecation$public $type$ get$capitalized_name$(int index) {\n"
853     "  return $name$_.get(index);\n"
854     "}\n");
855   WriteFieldDocComment(printer, descriptor_);
856   printer->Print(variables_,
857     "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
858     "    int index) {\n"
859     "  return $name$_.get(index);\n"
860     "}\n");
861 
862 }
863 
PrintNestedBuilderCondition(io::Printer * printer,const char * regular_case,const char * nested_builder_case) const864 void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderCondition(
865     io::Printer* printer,
866     const char* regular_case,
867     const char* nested_builder_case) const {
868   printer->Print(variables_, "if ($name$Builder_ == null) {\n");
869   printer->Indent();
870   printer->Print(variables_, regular_case);
871   printer->Outdent();
872   printer->Print("} else {\n");
873   printer->Indent();
874   printer->Print(variables_, nested_builder_case);
875   printer->Outdent();
876   printer->Print("}\n");
877 }
878 
PrintNestedBuilderFunction(io::Printer * printer,const char * method_prototype,const char * regular_case,const char * nested_builder_case,const char * trailing_code) const879 void RepeatedImmutableMessageFieldGenerator::PrintNestedBuilderFunction(
880     io::Printer* printer,
881     const char* method_prototype,
882     const char* regular_case,
883     const char* nested_builder_case,
884     const char* trailing_code) const {
885   printer->Print(variables_, method_prototype);
886   printer->Print(" {\n");
887   printer->Indent();
888   PrintNestedBuilderCondition(printer, regular_case, nested_builder_case);
889   if (trailing_code != NULL) {
890     printer->Print(variables_, trailing_code);
891   }
892   printer->Outdent();
893   printer->Print("}\n");
894 }
895 
896 void RepeatedImmutableMessageFieldGenerator::
GenerateBuilderMembers(io::Printer * printer) const897 GenerateBuilderMembers(io::Printer* printer) const {
898   // When using nested-builders, the code initially works just like the
899   // non-nested builder case. It only creates a nested builder lazily on
900   // demand and then forever delegates to it after creation.
901 
902   printer->Print(variables_,
903     // Used when the builder is null.
904     // One field is the list and the other field keeps track of whether the
905     // list is immutable. If it's immutable, the invariant is that it must
906     // either an instance of Collections.emptyList() or it's an ArrayList
907     // wrapped in a Collections.unmodifiableList() wrapper and nobody else has
908     // a refererence to the underlying ArrayList. This invariant allows us to
909     // share instances of lists between protocol buffers avoiding expensive
910     // memory allocations. Note, immutable is a strong guarantee here -- not
911     // just that the list cannot be modified via the reference but that the
912     // list can never be modified.
913     "private java.util.List<$type$> $name$_ =\n"
914     "  java.util.Collections.emptyList();\n"
915 
916     "private void ensure$capitalized_name$IsMutable() {\n"
917     "  if (!$get_mutable_bit_builder$) {\n"
918     "    $name$_ = new java.util.ArrayList<$type$>($name$_);\n"
919     "    $set_mutable_bit_builder$;\n"
920     "   }\n"
921     "}\n"
922     "\n");
923 
924   printer->Print(variables_,
925     // If this builder is non-null, it is used and the other fields are
926     // ignored.
927     "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n"
928     "    $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;\n"
929     "\n");
930 
931   // The comments above the methods below are based on a hypothetical
932   // repeated field of type "Field" called "RepeatedField".
933 
934   // List<Field> getRepeatedFieldList()
935   WriteFieldDocComment(printer, descriptor_);
936   PrintNestedBuilderFunction(printer,
937     "$deprecation$public java.util.List<$type$> get$capitalized_name$List()",
938 
939     "return java.util.Collections.unmodifiableList($name$_);\n",
940     "return $name$Builder_.getMessageList();\n",
941 
942     NULL);
943 
944   // int getRepeatedFieldCount()
945   WriteFieldDocComment(printer, descriptor_);
946   PrintNestedBuilderFunction(printer,
947     "$deprecation$public int get$capitalized_name$Count()",
948 
949     "return $name$_.size();\n",
950     "return $name$Builder_.getCount();\n",
951 
952     NULL);
953 
954   // Field getRepeatedField(int index)
955   WriteFieldDocComment(printer, descriptor_);
956   PrintNestedBuilderFunction(printer,
957     "$deprecation$public $type$ get$capitalized_name$(int index)",
958 
959     "return $name$_.get(index);\n",
960 
961     "return $name$Builder_.getMessage(index);\n",
962 
963     NULL);
964 
965   // Builder setRepeatedField(int index, Field value)
966   WriteFieldDocComment(printer, descriptor_);
967   PrintNestedBuilderFunction(printer,
968     "$deprecation$public Builder set$capitalized_name$(\n"
969     "    int index, $type$ value)",
970     "if (value == null) {\n"
971     "  throw new NullPointerException();\n"
972     "}\n"
973     "ensure$capitalized_name$IsMutable();\n"
974     "$name$_.set(index, value);\n"
975     "$on_changed$\n",
976     "$name$Builder_.setMessage(index, value);\n",
977     "return this;\n");
978 
979   // Builder setRepeatedField(int index, Field.Builder builderForValue)
980   WriteFieldDocComment(printer, descriptor_);
981   PrintNestedBuilderFunction(printer,
982     "$deprecation$public Builder set$capitalized_name$(\n"
983     "    int index, $type$.Builder builderForValue)",
984 
985     "ensure$capitalized_name$IsMutable();\n"
986     "$name$_.set(index, builderForValue.build());\n"
987     "$on_changed$\n",
988 
989     "$name$Builder_.setMessage(index, builderForValue.build());\n",
990 
991     "return this;\n");
992 
993   // Builder addRepeatedField(Field value)
994   WriteFieldDocComment(printer, descriptor_);
995   PrintNestedBuilderFunction(printer,
996     "$deprecation$public Builder add$capitalized_name$($type$ value)",
997 
998     "if (value == null) {\n"
999     "  throw new NullPointerException();\n"
1000     "}\n"
1001     "ensure$capitalized_name$IsMutable();\n"
1002     "$name$_.add(value);\n"
1003 
1004     "$on_changed$\n",
1005 
1006     "$name$Builder_.addMessage(value);\n",
1007 
1008     "return this;\n");
1009 
1010   // Builder addRepeatedField(int index, Field value)
1011   WriteFieldDocComment(printer, descriptor_);
1012   PrintNestedBuilderFunction(printer,
1013     "$deprecation$public Builder add$capitalized_name$(\n"
1014     "    int index, $type$ value)",
1015 
1016     "if (value == null) {\n"
1017     "  throw new NullPointerException();\n"
1018     "}\n"
1019     "ensure$capitalized_name$IsMutable();\n"
1020     "$name$_.add(index, value);\n"
1021     "$on_changed$\n",
1022 
1023     "$name$Builder_.addMessage(index, value);\n",
1024 
1025     "return this;\n");
1026 
1027   // Builder addRepeatedField(Field.Builder builderForValue)
1028   WriteFieldDocComment(printer, descriptor_);
1029   PrintNestedBuilderFunction(printer,
1030     "$deprecation$public Builder add$capitalized_name$(\n"
1031     "    $type$.Builder builderForValue)",
1032 
1033     "ensure$capitalized_name$IsMutable();\n"
1034     "$name$_.add(builderForValue.build());\n"
1035     "$on_changed$\n",
1036 
1037     "$name$Builder_.addMessage(builderForValue.build());\n",
1038 
1039     "return this;\n");
1040 
1041   // Builder addRepeatedField(int index, Field.Builder builderForValue)
1042   WriteFieldDocComment(printer, descriptor_);
1043   PrintNestedBuilderFunction(printer,
1044     "$deprecation$public Builder add$capitalized_name$(\n"
1045     "    int index, $type$.Builder builderForValue)",
1046 
1047     "ensure$capitalized_name$IsMutable();\n"
1048     "$name$_.add(index, builderForValue.build());\n"
1049     "$on_changed$\n",
1050 
1051     "$name$Builder_.addMessage(index, builderForValue.build());\n",
1052 
1053     "return this;\n");
1054 
1055   // Builder addAllRepeatedField(Iterable<Field> values)
1056   WriteFieldDocComment(printer, descriptor_);
1057   PrintNestedBuilderFunction(printer,
1058     "$deprecation$public Builder addAll$capitalized_name$(\n"
1059     "    java.lang.Iterable<? extends $type$> values)",
1060 
1061     "ensure$capitalized_name$IsMutable();\n"
1062     "com.google.protobuf.AbstractMessageLite.Builder.addAll(\n"
1063     "    values, $name$_);\n"
1064     "$on_changed$\n",
1065 
1066     "$name$Builder_.addAllMessages(values);\n",
1067 
1068     "return this;\n");
1069 
1070   // Builder clearAllRepeatedField()
1071   WriteFieldDocComment(printer, descriptor_);
1072   PrintNestedBuilderFunction(printer,
1073     "$deprecation$public Builder clear$capitalized_name$()",
1074 
1075     "$name$_ = java.util.Collections.emptyList();\n"
1076     "$clear_mutable_bit_builder$;\n"
1077     "$on_changed$\n",
1078 
1079     "$name$Builder_.clear();\n",
1080 
1081     "return this;\n");
1082 
1083   // Builder removeRepeatedField(int index)
1084   WriteFieldDocComment(printer, descriptor_);
1085   PrintNestedBuilderFunction(printer,
1086     "$deprecation$public Builder remove$capitalized_name$(int index)",
1087 
1088     "ensure$capitalized_name$IsMutable();\n"
1089     "$name$_.remove(index);\n"
1090     "$on_changed$\n",
1091 
1092     "$name$Builder_.remove(index);\n",
1093 
1094     "return this;\n");
1095 
1096   WriteFieldDocComment(printer, descriptor_);
1097   printer->Print(variables_,
1098     "$deprecation$public $type$.Builder get$capitalized_name$Builder(\n"
1099     "    int index) {\n"
1100     "  return get$capitalized_name$FieldBuilder().getBuilder(index);\n"
1101     "}\n");
1102 
1103   WriteFieldDocComment(printer, descriptor_);
1104       printer->Print(variables_,
1105     "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n"
1106     "    int index) {\n"
1107     "  if ($name$Builder_ == null) {\n"
1108     "    return $name$_.get(index);"
1109     "  } else {\n"
1110     "    return $name$Builder_.getMessageOrBuilder(index);\n"
1111     "  }\n"
1112     "}\n");
1113 
1114   WriteFieldDocComment(printer, descriptor_);
1115       printer->Print(variables_,
1116     "$deprecation$public java.util.List<? extends $type$OrBuilder> \n"
1117     "     get$capitalized_name$OrBuilderList() {\n"
1118     "  if ($name$Builder_ != null) {\n"
1119     "    return $name$Builder_.getMessageOrBuilderList();\n"
1120     "  } else {\n"
1121     "    return java.util.Collections.unmodifiableList($name$_);\n"
1122     "  }\n"
1123     "}\n");
1124 
1125   WriteFieldDocComment(printer, descriptor_);
1126       printer->Print(variables_,
1127     "$deprecation$public $type$.Builder add$capitalized_name$Builder() {\n"
1128     "  return get$capitalized_name$FieldBuilder().addBuilder(\n"
1129     "      $type$.getDefaultInstance());\n"
1130     "}\n");
1131   WriteFieldDocComment(printer, descriptor_);
1132       printer->Print(variables_,
1133     "$deprecation$public $type$.Builder add$capitalized_name$Builder(\n"
1134     "    int index) {\n"
1135     "  return get$capitalized_name$FieldBuilder().addBuilder(\n"
1136     "      index, $type$.getDefaultInstance());\n"
1137     "}\n");
1138   WriteFieldDocComment(printer, descriptor_);
1139       printer->Print(variables_,
1140     "$deprecation$public java.util.List<$type$.Builder> \n"
1141     "     get$capitalized_name$BuilderList() {\n"
1142     "  return get$capitalized_name$FieldBuilder().getBuilderList();\n"
1143     "}\n"
1144     "private com.google.protobuf.RepeatedFieldBuilder$ver$<\n"
1145     "    $type$, $type$.Builder, $type$OrBuilder> \n"
1146     "    get$capitalized_name$FieldBuilder() {\n"
1147     "  if ($name$Builder_ == null) {\n"
1148     "    $name$Builder_ = new com.google.protobuf.RepeatedFieldBuilder$ver$<\n"
1149     "        $type$, $type$.Builder, $type$OrBuilder>(\n"
1150     "            $name$_,\n"
1151     "            $get_mutable_bit_builder$,\n"
1152     "            getParentForChildren(),\n"
1153     "            isClean());\n"
1154     "    $name$_ = null;\n"
1155     "  }\n"
1156     "  return $name$Builder_;\n"
1157     "}\n");
1158 }
1159 
1160 void RepeatedImmutableMessageFieldGenerator::
GenerateFieldBuilderInitializationCode(io::Printer * printer) const1161 GenerateFieldBuilderInitializationCode(io::Printer* printer)  const {
1162   printer->Print(variables_,
1163     "get$capitalized_name$FieldBuilder();\n");
1164 }
1165 
1166 void RepeatedImmutableMessageFieldGenerator::
GenerateInitializationCode(io::Printer * printer) const1167 GenerateInitializationCode(io::Printer* printer) const {
1168   printer->Print(variables_, "$name$_ = java.util.Collections.emptyList();\n");
1169 }
1170 
1171 void RepeatedImmutableMessageFieldGenerator::
GenerateBuilderClearCode(io::Printer * printer) const1172 GenerateBuilderClearCode(io::Printer* printer) const {
1173   PrintNestedBuilderCondition(printer,
1174     "$name$_ = java.util.Collections.emptyList();\n"
1175     "$clear_mutable_bit_builder$;\n",
1176 
1177     "$name$Builder_.clear();\n");
1178 }
1179 
1180 void RepeatedImmutableMessageFieldGenerator::
GenerateMergingCode(io::Printer * printer) const1181 GenerateMergingCode(io::Printer* printer) const {
1182   // The code below does two optimizations (non-nested builder case):
1183   //   1. If the other list is empty, there's nothing to do. This ensures we
1184   //      don't allocate a new array if we already have an immutable one.
1185   //   2. If the other list is non-empty and our current list is empty, we can
1186   //      reuse the other list which is guaranteed to be immutable.
1187   PrintNestedBuilderCondition(printer,
1188     "if (!other.$name$_.isEmpty()) {\n"
1189     "  if ($name$_.isEmpty()) {\n"
1190     "    $name$_ = other.$name$_;\n"
1191     "    $clear_mutable_bit_builder$;\n"
1192     "  } else {\n"
1193     "    ensure$capitalized_name$IsMutable();\n"
1194     "    $name$_.addAll(other.$name$_);\n"
1195     "  }\n"
1196     "  $on_changed$\n"
1197     "}\n",
1198 
1199     "if (!other.$name$_.isEmpty()) {\n"
1200     "  if ($name$Builder_.isEmpty()) {\n"
1201     "    $name$Builder_.dispose();\n"
1202     "    $name$Builder_ = null;\n"
1203     "    $name$_ = other.$name$_;\n"
1204     "    $clear_mutable_bit_builder$;\n"
1205     "    $name$Builder_ = \n"
1206     "      com.google.protobuf.GeneratedMessage$ver$.alwaysUseFieldBuilders ?\n"
1207     "         get$capitalized_name$FieldBuilder() : null;\n"
1208     "  } else {\n"
1209     "    $name$Builder_.addAllMessages(other.$name$_);\n"
1210     "  }\n"
1211     "}\n");
1212 }
1213 
1214 void RepeatedImmutableMessageFieldGenerator::
GenerateBuildingCode(io::Printer * printer) const1215 GenerateBuildingCode(io::Printer* printer) const {
1216   // The code below (non-nested builder case) ensures that the result has an
1217   // immutable list. If our list is immutable, we can just reuse it. If not,
1218   // we make it immutable.
1219   PrintNestedBuilderCondition(printer,
1220     "if ($get_mutable_bit_builder$) {\n"
1221     "  $name$_ = java.util.Collections.unmodifiableList($name$_);\n"
1222     "  $clear_mutable_bit_builder$;\n"
1223     "}\n"
1224     "result.$name$_ = $name$_;\n",
1225 
1226     "result.$name$_ = $name$Builder_.build();\n");
1227 }
1228 
1229 void RepeatedImmutableMessageFieldGenerator::
GenerateParsingCode(io::Printer * printer) const1230 GenerateParsingCode(io::Printer* printer) const {
1231   printer->Print(variables_,
1232     "if (!$get_mutable_bit_parser$) {\n"
1233     "  $name$_ = new java.util.ArrayList<$type$>();\n"
1234     "  $set_mutable_bit_parser$;\n"
1235     "}\n");
1236 
1237   if (GetType(descriptor_) == FieldDescriptor::TYPE_GROUP) {
1238     printer->Print(variables_,
1239       "$name$_.add(input.readGroup($number$, $type$.$get_parser$,\n"
1240       "    extensionRegistry));\n");
1241   } else {
1242     printer->Print(variables_,
1243       "$name$_.add(\n"
1244       "    input.readMessage($type$.$get_parser$, extensionRegistry));\n");
1245   }
1246 }
1247 
1248 void RepeatedImmutableMessageFieldGenerator::
GenerateParsingDoneCode(io::Printer * printer) const1249 GenerateParsingDoneCode(io::Printer* printer) const {
1250   printer->Print(variables_,
1251     "if ($get_mutable_bit_parser$) {\n"
1252     "  $name$_ = java.util.Collections.unmodifiableList($name$_);\n"
1253     "}\n");
1254 }
1255 
1256 void RepeatedImmutableMessageFieldGenerator::
GenerateSerializationCode(io::Printer * printer) const1257 GenerateSerializationCode(io::Printer* printer) const {
1258   printer->Print(variables_,
1259     "for (int i = 0; i < $name$_.size(); i++) {\n"
1260     "  output.write$group_or_message$($number$, $name$_.get(i));\n"
1261     "}\n");
1262 }
1263 
1264 void RepeatedImmutableMessageFieldGenerator::
GenerateSerializedSizeCode(io::Printer * printer) const1265 GenerateSerializedSizeCode(io::Printer* printer) const {
1266   printer->Print(variables_,
1267     "for (int i = 0; i < $name$_.size(); i++) {\n"
1268     "  size += com.google.protobuf.CodedOutputStream\n"
1269     "    .compute$group_or_message$Size($number$, $name$_.get(i));\n"
1270     "}\n");
1271 }
1272 
1273 void RepeatedImmutableMessageFieldGenerator::
GenerateEqualsCode(io::Printer * printer) const1274 GenerateEqualsCode(io::Printer* printer) const {
1275   printer->Print(variables_,
1276     "result = result && get$capitalized_name$List()\n"
1277     "    .equals(other.get$capitalized_name$List());\n");
1278 }
1279 
1280 void RepeatedImmutableMessageFieldGenerator::
GenerateHashCode(io::Printer * printer) const1281 GenerateHashCode(io::Printer* printer) const {
1282   printer->Print(variables_,
1283     "if (get$capitalized_name$Count() > 0) {\n"
1284     "  hash = (37 * hash) + $constant_name$;\n"
1285     "  hash = (53 * hash) + get$capitalized_name$List().hashCode();\n"
1286     "}\n");
1287 }
1288 
GetBoxedType() const1289 string RepeatedImmutableMessageFieldGenerator::GetBoxedType() const {
1290   return name_resolver_->GetImmutableClassName(descriptor_->message_type());
1291 }
1292 
1293 }  // namespace java
1294 }  // namespace compiler
1295 }  // namespace protobuf
1296 }  // namespace google
1297