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 // Author: jonp@google.com (Jon Perlow)
33 //  Based on original Protocol Buffers design by
34 //  Sanjay Ghemawat, Jeff Dean, and others.
35 
36 #include <map>
37 #include <string>
38 
39 #include <google/protobuf/stubs/logging.h>
40 #include <google/protobuf/stubs/common.h>
41 #include <google/protobuf/compiler/java/java_context.h>
42 #include <google/protobuf/compiler/java/java_doc_comment.h>
43 #include <google/protobuf/compiler/java/java_helpers.h>
44 #include <google/protobuf/compiler/java/java_name_resolver.h>
45 #include <google/protobuf/compiler/java/java_string_field.h>
46 #include <google/protobuf/io/printer.h>
47 #include <google/protobuf/wire_format.h>
48 #include <google/protobuf/stubs/strutil.h>
49 
50 namespace google {
51 namespace protobuf {
52 namespace compiler {
53 namespace java {
54 
55 using internal::WireFormat;
56 using internal::WireFormatLite;
57 
58 namespace {
59 
SetPrimitiveVariables(const FieldDescriptor * descriptor,int messageBitIndex,int builderBitIndex,const FieldGeneratorInfo * info,ClassNameResolver * name_resolver,map<string,string> * variables)60 void SetPrimitiveVariables(const FieldDescriptor* descriptor,
61                            int messageBitIndex,
62                            int builderBitIndex,
63                            const FieldGeneratorInfo* info,
64                            ClassNameResolver* name_resolver,
65                            map<string, string>* variables) {
66   SetCommonFieldVariables(descriptor, info, variables);
67 
68   (*variables)["empty_list"] = "com.google.protobuf.LazyStringArrayList.EMPTY";
69 
70   (*variables)["default"] = ImmutableDefaultValue(descriptor, name_resolver);
71   (*variables)["default_init"] =
72       "= " + ImmutableDefaultValue(descriptor, name_resolver);
73   (*variables)["capitalized_type"] = "String";
74   (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor));
75   (*variables)["tag_size"] = SimpleItoa(
76       WireFormat::TagSize(descriptor->number(), GetType(descriptor)));
77   (*variables)["null_check"] =
78       "  if (value == null) {\n"
79       "    throw new NullPointerException();\n"
80       "  }\n";
81   (*variables)["writeString"] =
82       "com.google.protobuf.GeneratedMessage" + GeneratedCodeVersionSuffix() +
83       ".writeString";
84   (*variables)["computeStringSize"] =
85       "com.google.protobuf.GeneratedMessage" + GeneratedCodeVersionSuffix() +
86       ".computeStringSize";
87 
88   // TODO(birdo): Add @deprecated javadoc when generating javadoc is supported
89   // by the proto compiler
90   (*variables)["deprecation"] = descriptor->options().deprecated()
91       ? "@java.lang.Deprecated " : "";
92   (*variables)["on_changed"] = "onChanged();";
93 
94   if (SupportFieldPresence(descriptor->file())) {
95     // For singular messages and builders, one bit is used for the hasField bit.
96     (*variables)["get_has_field_bit_message"] = GenerateGetBit(messageBitIndex);
97     (*variables)["get_has_field_bit_builder"] = GenerateGetBit(builderBitIndex);
98 
99     // Note that these have a trailing ";".
100     (*variables)["set_has_field_bit_message"] =
101         GenerateSetBit(messageBitIndex) + ";";
102     (*variables)["set_has_field_bit_builder"] =
103         GenerateSetBit(builderBitIndex) + ";";
104     (*variables)["clear_has_field_bit_builder"] =
105         GenerateClearBit(builderBitIndex) + ";";
106 
107     (*variables)["is_field_present_message"] = GenerateGetBit(messageBitIndex);
108   } else {
109     (*variables)["set_has_field_bit_message"] = "";
110     (*variables)["set_has_field_bit_builder"] = "";
111     (*variables)["clear_has_field_bit_builder"] = "";
112 
113     (*variables)["is_field_present_message"] =
114         "!get" + (*variables)["capitalized_name"] + "Bytes().isEmpty()";
115   }
116 
117   // For repeated builders, one bit is used for whether the array is immutable.
118   (*variables)["get_mutable_bit_builder"] = GenerateGetBit(builderBitIndex);
119   (*variables)["set_mutable_bit_builder"] = GenerateSetBit(builderBitIndex);
120   (*variables)["clear_mutable_bit_builder"] = GenerateClearBit(builderBitIndex);
121 
122   // For repeated fields, one bit is used for whether the array is immutable
123   // in the parsing constructor.
124   (*variables)["get_mutable_bit_parser"] =
125       GenerateGetBitMutableLocal(builderBitIndex);
126   (*variables)["set_mutable_bit_parser"] =
127       GenerateSetBitMutableLocal(builderBitIndex);
128 
129   (*variables)["get_has_field_bit_from_local"] =
130       GenerateGetBitFromLocal(builderBitIndex);
131   (*variables)["set_has_field_bit_to_local"] =
132       GenerateSetBitToLocal(messageBitIndex);
133 }
134 
135 }  // namespace
136 
137 // ===================================================================
138 
139 ImmutableStringFieldGenerator::
ImmutableStringFieldGenerator(const FieldDescriptor * descriptor,int messageBitIndex,int builderBitIndex,Context * context)140 ImmutableStringFieldGenerator(const FieldDescriptor* descriptor,
141                               int messageBitIndex,
142                               int builderBitIndex,
143                               Context* context)
144   : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
145     builderBitIndex_(builderBitIndex), context_(context),
146     name_resolver_(context->GetNameResolver()) {
147   SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex,
148                         context->GetFieldGeneratorInfo(descriptor),
149                         name_resolver_, &variables_);
150 }
151 
~ImmutableStringFieldGenerator()152 ImmutableStringFieldGenerator::~ImmutableStringFieldGenerator() {}
153 
GetNumBitsForMessage() const154 int ImmutableStringFieldGenerator::GetNumBitsForMessage() const {
155   return 1;
156 }
157 
GetNumBitsForBuilder() const158 int ImmutableStringFieldGenerator::GetNumBitsForBuilder() const {
159   return 1;
160 }
161 
162 // A note about how strings are handled. This code used to just store a String
163 // in the Message. This had two issues:
164 //
165 //  1. It wouldn't roundtrip byte arrays that were not vaid UTF-8 encoded
166 //     strings, but rather fields that were raw bytes incorrectly marked
167 //     as strings in the proto file. This is common because in the proto1
168 //     syntax, string was the way to indicate bytes and C++ engineers can
169 //     easily make this mistake without affecting the C++ API. By converting to
170 //     strings immediately, some java code might corrupt these byte arrays as
171 //     it passes through a java server even if the field was never accessed by
172 //     application code.
173 //
174 //  2. There's a performance hit to converting between bytes and strings and
175 //     it many cases, the field is never even read by the application code. This
176 //     avoids unnecessary conversions in the common use cases.
177 //
178 // So now, the field for String is maintained as an Object reference which can
179 // either store a String or a ByteString. The code uses an instanceof check
180 // to see which one it has and converts to the other one if needed. It remembers
181 // the last value requested (in a thread safe manner) as this is most likely
182 // the one needed next. The thread safety is such that if two threads both
183 // convert the field because the changes made by each thread were not visible to
184 // the other, they may cause a conversion to happen more times than would
185 // otherwise be necessary. This was deemed better than adding synchronization
186 // overhead. It will not cause any corruption issues or affect the behavior of
187 // the API. The instanceof check is also highly optimized in the JVM and we
188 // decided it was better to reduce the memory overhead by not having two
189 // separate fields but rather use dynamic type checking.
190 //
191 // For single fields, the logic for this is done inside the generated code. For
192 // repeated fields, the logic is done in LazyStringArrayList and
193 // UnmodifiableLazyStringList.
194 void ImmutableStringFieldGenerator::
GenerateInterfaceMembers(io::Printer * printer) const195 GenerateInterfaceMembers(io::Printer* printer) const {
196   if (SupportFieldPresence(descriptor_->file())) {
197     WriteFieldDocComment(printer, descriptor_);
198     printer->Print(variables_,
199       "$deprecation$boolean has$capitalized_name$();\n");
200   }
201   WriteFieldDocComment(printer, descriptor_);
202   printer->Print(variables_,
203     "$deprecation$java.lang.String get$capitalized_name$();\n");
204   WriteFieldDocComment(printer, descriptor_);
205   printer->Print(variables_,
206     "$deprecation$com.google.protobuf.ByteString\n"
207     "    get$capitalized_name$Bytes();\n");
208 }
209 
210 void ImmutableStringFieldGenerator::
GenerateMembers(io::Printer * printer) const211 GenerateMembers(io::Printer* printer) const {
212   printer->Print(variables_,
213     "private volatile java.lang.Object $name$_;\n");
214   PrintExtraFieldInfo(variables_, printer);
215 
216   if (SupportFieldPresence(descriptor_->file())) {
217     WriteFieldDocComment(printer, descriptor_);
218     printer->Print(variables_,
219       "$deprecation$public boolean has$capitalized_name$() {\n"
220       "  return $get_has_field_bit_message$;\n"
221       "}\n");
222   }
223 
224   WriteFieldDocComment(printer, descriptor_);
225   printer->Print(variables_,
226     "$deprecation$public java.lang.String get$capitalized_name$() {\n"
227     "  java.lang.Object ref = $name$_;\n"
228     "  if (ref instanceof java.lang.String) {\n"
229     "    return (java.lang.String) ref;\n"
230     "  } else {\n"
231     "    com.google.protobuf.ByteString bs = \n"
232     "        (com.google.protobuf.ByteString) ref;\n"
233       "    java.lang.String s = bs.toStringUtf8();\n");
234   if (CheckUtf8(descriptor_)) {
235     printer->Print(variables_,
236       "    $name$_ = s;\n");
237   } else {
238     printer->Print(variables_,
239       "    if (bs.isValidUtf8()) {\n"
240       "      $name$_ = s;\n"
241       "    }\n");
242   }
243   printer->Print(variables_,
244     "    return s;\n"
245     "  }\n"
246     "}\n");
247   WriteFieldDocComment(printer, descriptor_);
248   printer->Print(variables_,
249     "$deprecation$public com.google.protobuf.ByteString\n"
250     "    get$capitalized_name$Bytes() {\n"
251     "  java.lang.Object ref = $name$_;\n"
252     "  if (ref instanceof java.lang.String) {\n"
253     "    com.google.protobuf.ByteString b = \n"
254     "        com.google.protobuf.ByteString.copyFromUtf8(\n"
255     "            (java.lang.String) ref);\n"
256     "    $name$_ = b;\n"
257     "    return b;\n"
258     "  } else {\n"
259     "    return (com.google.protobuf.ByteString) ref;\n"
260     "  }\n"
261     "}\n");
262 }
263 
264 void ImmutableStringFieldGenerator::
GenerateBuilderMembers(io::Printer * printer) const265 GenerateBuilderMembers(io::Printer* printer) const {
266   printer->Print(variables_,
267     "private java.lang.Object $name$_ $default_init$;\n");
268   if (SupportFieldPresence(descriptor_->file())) {
269     WriteFieldDocComment(printer, descriptor_);
270     printer->Print(variables_,
271       "$deprecation$public boolean has$capitalized_name$() {\n"
272       "  return $get_has_field_bit_builder$;\n"
273       "}\n");
274   }
275 
276   WriteFieldDocComment(printer, descriptor_);
277   printer->Print(variables_,
278     "$deprecation$public java.lang.String get$capitalized_name$() {\n"
279     "  java.lang.Object ref = $name$_;\n"
280     "  if (!(ref instanceof java.lang.String)) {\n"
281     "    com.google.protobuf.ByteString bs =\n"
282     "        (com.google.protobuf.ByteString) ref;\n"
283     "    java.lang.String s = bs.toStringUtf8();\n");
284   if (CheckUtf8(descriptor_)) {
285     printer->Print(variables_,
286       "    $name$_ = s;\n");
287   } else {
288     printer->Print(variables_,
289       "    if (bs.isValidUtf8()) {\n"
290       "      $name$_ = s;\n"
291       "    }\n");
292   }
293   printer->Print(variables_,
294     "    return s;\n"
295     "  } else {\n"
296     "    return (java.lang.String) ref;\n"
297     "  }\n"
298     "}\n");
299 
300   WriteFieldDocComment(printer, descriptor_);
301   printer->Print(variables_,
302     "$deprecation$public com.google.protobuf.ByteString\n"
303     "    get$capitalized_name$Bytes() {\n"
304     "  java.lang.Object ref = $name$_;\n"
305     "  if (ref instanceof String) {\n"
306     "    com.google.protobuf.ByteString b = \n"
307     "        com.google.protobuf.ByteString.copyFromUtf8(\n"
308     "            (java.lang.String) ref);\n"
309     "    $name$_ = b;\n"
310     "    return b;\n"
311     "  } else {\n"
312     "    return (com.google.protobuf.ByteString) ref;\n"
313     "  }\n"
314     "}\n");
315 
316   WriteFieldDocComment(printer, descriptor_);
317   printer->Print(variables_,
318     "$deprecation$public Builder set$capitalized_name$(\n"
319     "    java.lang.String value) {\n"
320     "$null_check$"
321     "  $set_has_field_bit_builder$\n"
322     "  $name$_ = value;\n"
323     "  $on_changed$\n"
324     "  return this;\n"
325     "}\n");
326   WriteFieldDocComment(printer, descriptor_);
327   printer->Print(variables_,
328     "$deprecation$public Builder clear$capitalized_name$() {\n"
329     "  $clear_has_field_bit_builder$\n");
330   // The default value is not a simple literal so we want to avoid executing
331   // it multiple times.  Instead, get the default out of the default instance.
332   printer->Print(variables_,
333     "  $name$_ = getDefaultInstance().get$capitalized_name$();\n");
334   printer->Print(variables_,
335     "  $on_changed$\n"
336     "  return this;\n"
337     "}\n");
338 
339   WriteFieldDocComment(printer, descriptor_);
340   printer->Print(variables_,
341     "$deprecation$public Builder set$capitalized_name$Bytes(\n"
342     "    com.google.protobuf.ByteString value) {\n"
343     "$null_check$");
344   if (CheckUtf8(descriptor_)) {
345     printer->Print(variables_,
346       "  checkByteStringIsUtf8(value);\n");
347   }
348   printer->Print(variables_,
349     "  $set_has_field_bit_builder$\n"
350     "  $name$_ = value;\n"
351     "  $on_changed$\n"
352     "  return this;\n"
353     "}\n");
354 }
355 
356 void ImmutableStringFieldGenerator::
GenerateFieldBuilderInitializationCode(io::Printer * printer) const357 GenerateFieldBuilderInitializationCode(io::Printer* printer)  const {
358   // noop for primitives
359 }
360 
361 void ImmutableStringFieldGenerator::
GenerateInitializationCode(io::Printer * printer) const362 GenerateInitializationCode(io::Printer* printer) const {
363   printer->Print(variables_, "$name$_ = $default$;\n");
364 }
365 
366 void ImmutableStringFieldGenerator::
GenerateBuilderClearCode(io::Printer * printer) const367 GenerateBuilderClearCode(io::Printer* printer) const {
368   printer->Print(variables_,
369     "$name$_ = $default$;\n"
370     "$clear_has_field_bit_builder$\n");
371 }
372 
373 void ImmutableStringFieldGenerator::
GenerateMergingCode(io::Printer * printer) const374 GenerateMergingCode(io::Printer* printer) const {
375   if (SupportFieldPresence(descriptor_->file())) {
376     // Allow a slight breach of abstraction here in order to avoid forcing
377     // all string fields to Strings when copying fields from a Message.
378     printer->Print(variables_,
379       "if (other.has$capitalized_name$()) {\n"
380       "  $set_has_field_bit_builder$\n"
381       "  $name$_ = other.$name$_;\n"
382       "  $on_changed$\n"
383       "}\n");
384   } else {
385     printer->Print(variables_,
386       "if (!other.get$capitalized_name$().isEmpty()) {\n"
387       "  $name$_ = other.$name$_;\n"
388       "  $on_changed$\n"
389       "}\n");
390   }
391 }
392 
393 void ImmutableStringFieldGenerator::
GenerateBuildingCode(io::Printer * printer) const394 GenerateBuildingCode(io::Printer* printer) const {
395   if (SupportFieldPresence(descriptor_->file())) {
396     printer->Print(variables_,
397       "if ($get_has_field_bit_from_local$) {\n"
398       "  $set_has_field_bit_to_local$;\n"
399       "}\n");
400   }
401   printer->Print(variables_,
402     "result.$name$_ = $name$_;\n");
403 }
404 
405 void ImmutableStringFieldGenerator::
GenerateParsingCode(io::Printer * printer) const406 GenerateParsingCode(io::Printer* printer) const {
407   if (CheckUtf8(descriptor_)) {
408     printer->Print(variables_,
409       "java.lang.String s = input.readStringRequireUtf8();\n"
410       "$set_has_field_bit_message$\n"
411       "$name$_ = s;\n");
412   } else {
413     printer->Print(variables_,
414       "com.google.protobuf.ByteString bs = input.readBytes();\n"
415       "$set_has_field_bit_message$\n"
416       "$name$_ = bs;\n");
417   }
418 }
419 
420 void ImmutableStringFieldGenerator::
GenerateParsingDoneCode(io::Printer * printer) const421 GenerateParsingDoneCode(io::Printer* printer) const {
422   // noop for strings.
423 }
424 
425 void ImmutableStringFieldGenerator::
GenerateSerializationCode(io::Printer * printer) const426 GenerateSerializationCode(io::Printer* printer) const {
427   printer->Print(variables_,
428     "if ($is_field_present_message$) {\n"
429     "  $writeString$(output, $number$, $name$_);\n"
430     "}\n");
431 }
432 
433 void ImmutableStringFieldGenerator::
GenerateSerializedSizeCode(io::Printer * printer) const434 GenerateSerializedSizeCode(io::Printer* printer) const {
435   printer->Print(variables_,
436     "if ($is_field_present_message$) {\n"
437     "  size += $computeStringSize$($number$, $name$_);\n"
438     "}\n");
439 }
440 
441 void ImmutableStringFieldGenerator::
GenerateEqualsCode(io::Printer * printer) const442 GenerateEqualsCode(io::Printer* printer) const {
443   printer->Print(variables_,
444     "result = result && get$capitalized_name$()\n"
445     "    .equals(other.get$capitalized_name$());\n");
446 }
447 
448 void ImmutableStringFieldGenerator::
GenerateHashCode(io::Printer * printer) const449 GenerateHashCode(io::Printer* printer) const {
450   printer->Print(variables_,
451     "hash = (37 * hash) + $constant_name$;\n");
452   printer->Print(variables_,
453     "hash = (53 * hash) + get$capitalized_name$().hashCode();\n");
454 }
455 
GetBoxedType() const456 string ImmutableStringFieldGenerator::GetBoxedType() const {
457   return "java.lang.String";
458 }
459 
460 // ===================================================================
461 
462 ImmutableStringOneofFieldGenerator::
ImmutableStringOneofFieldGenerator(const FieldDescriptor * descriptor,int messageBitIndex,int builderBitIndex,Context * context)463 ImmutableStringOneofFieldGenerator(const FieldDescriptor* descriptor,
464                                    int messageBitIndex,
465                                    int builderBitIndex,
466                                    Context* context)
467     : ImmutableStringFieldGenerator(
468           descriptor, messageBitIndex, builderBitIndex, context) {
469   const OneofGeneratorInfo* info =
470       context->GetOneofGeneratorInfo(descriptor->containing_oneof());
471   SetCommonOneofVariables(descriptor, info, &variables_);
472 }
473 
474 ImmutableStringOneofFieldGenerator::
~ImmutableStringOneofFieldGenerator()475 ~ImmutableStringOneofFieldGenerator() {}
476 
477 void ImmutableStringOneofFieldGenerator::
GenerateMembers(io::Printer * printer) const478 GenerateMembers(io::Printer* printer) const {
479   PrintExtraFieldInfo(variables_, printer);
480 
481   if (SupportFieldPresence(descriptor_->file())) {
482   WriteFieldDocComment(printer, descriptor_);
483   printer->Print(variables_,
484     "$deprecation$public boolean has$capitalized_name$() {\n"
485     "  return $has_oneof_case_message$;\n"
486     "}\n");
487   }
488 
489   WriteFieldDocComment(printer, descriptor_);
490   printer->Print(variables_,
491     "$deprecation$public java.lang.String get$capitalized_name$() {\n"
492     "  java.lang.Object ref $default_init$;\n"
493     "  if ($has_oneof_case_message$) {\n"
494     "    ref = $oneof_name$_;\n"
495     "  }\n"
496     "  if (ref instanceof java.lang.String) {\n"
497     "    return (java.lang.String) ref;\n"
498     "  } else {\n"
499     "    com.google.protobuf.ByteString bs = \n"
500     "        (com.google.protobuf.ByteString) ref;\n"
501     "    java.lang.String s = bs.toStringUtf8();\n");
502   if (CheckUtf8(descriptor_)) {
503     printer->Print(variables_,
504     "    if ($has_oneof_case_message$) {\n"
505     "      $oneof_name$_ = s;\n"
506     "    }\n");
507   } else {
508     printer->Print(variables_,
509     "    if (bs.isValidUtf8() && ($has_oneof_case_message$)) {\n"
510     "      $oneof_name$_ = s;\n"
511     "    }\n");
512   }
513   printer->Print(variables_,
514     "    return s;\n"
515     "  }\n"
516     "}\n");
517   WriteFieldDocComment(printer, descriptor_);
518 
519   printer->Print(variables_,
520     "$deprecation$public com.google.protobuf.ByteString\n"
521     "    get$capitalized_name$Bytes() {\n"
522     "  java.lang.Object ref $default_init$;\n"
523     "  if ($has_oneof_case_message$) {\n"
524     "    ref = $oneof_name$_;\n"
525     "  }\n"
526     "  if (ref instanceof java.lang.String) {\n"
527     "    com.google.protobuf.ByteString b = \n"
528     "        com.google.protobuf.ByteString.copyFromUtf8(\n"
529     "            (java.lang.String) ref);\n"
530     "    if ($has_oneof_case_message$) {\n"
531     "      $oneof_name$_ = b;\n"
532     "    }\n"
533     "    return b;\n"
534     "  } else {\n"
535     "    return (com.google.protobuf.ByteString) ref;\n"
536     "  }\n"
537     "}\n");
538 }
539 
540 void ImmutableStringOneofFieldGenerator::
GenerateBuilderMembers(io::Printer * printer) const541 GenerateBuilderMembers(io::Printer* printer) const {
542   if (SupportFieldPresence(descriptor_->file())) {
543     WriteFieldDocComment(printer, descriptor_);
544     printer->Print(variables_,
545       "$deprecation$public boolean has$capitalized_name$() {\n"
546       "  return $has_oneof_case_message$;\n"
547       "}\n");
548   }
549 
550   WriteFieldDocComment(printer, descriptor_);
551   printer->Print(variables_,
552     "$deprecation$public java.lang.String get$capitalized_name$() {\n"
553     "  java.lang.Object ref $default_init$;\n"
554     "  if ($has_oneof_case_message$) {\n"
555     "    ref = $oneof_name$_;\n"
556     "  }\n"
557     "  if (!(ref instanceof java.lang.String)) {\n"
558     "    com.google.protobuf.ByteString bs =\n"
559     "        (com.google.protobuf.ByteString) ref;\n"
560     "    java.lang.String s = bs.toStringUtf8();\n"
561     "    if ($has_oneof_case_message$) {\n");
562   if (CheckUtf8(descriptor_)) {
563     printer->Print(variables_,
564       "      $oneof_name$_ = s;\n");
565   } else {
566     printer->Print(variables_,
567       "      if (bs.isValidUtf8()) {\n"
568       "        $oneof_name$_ = s;\n"
569       "      }\n");
570   }
571   printer->Print(variables_,
572     "    }\n"
573     "    return s;\n"
574     "  } else {\n"
575     "    return (java.lang.String) ref;\n"
576     "  }\n"
577     "}\n");
578 
579   WriteFieldDocComment(printer, descriptor_);
580   printer->Print(variables_,
581     "$deprecation$public com.google.protobuf.ByteString\n"
582     "    get$capitalized_name$Bytes() {\n"
583     "  java.lang.Object ref $default_init$;\n"
584     "  if ($has_oneof_case_message$) {\n"
585     "    ref = $oneof_name$_;\n"
586     "  }\n"
587     "  if (ref instanceof String) {\n"
588     "    com.google.protobuf.ByteString b = \n"
589     "        com.google.protobuf.ByteString.copyFromUtf8(\n"
590     "            (java.lang.String) ref);\n"
591     "    if ($has_oneof_case_message$) {\n"
592     "      $oneof_name$_ = b;\n"
593     "    }\n"
594     "    return b;\n"
595     "  } else {\n"
596     "    return (com.google.protobuf.ByteString) ref;\n"
597     "  }\n"
598     "}\n");
599 
600   WriteFieldDocComment(printer, descriptor_);
601   printer->Print(variables_,
602     "$deprecation$public Builder set$capitalized_name$(\n"
603     "    java.lang.String value) {\n"
604     "$null_check$"
605     "  $set_oneof_case_message$;\n"
606     "  $oneof_name$_ = value;\n"
607     "  $on_changed$\n"
608     "  return this;\n"
609     "}\n");
610   WriteFieldDocComment(printer, descriptor_);
611   printer->Print(variables_,
612     "$deprecation$public Builder clear$capitalized_name$() {\n"
613     "  if ($has_oneof_case_message$) {\n"
614     "    $clear_oneof_case_message$;\n"
615     "    $oneof_name$_ = null;\n"
616     "    $on_changed$\n"
617     "  }\n"
618     "  return this;\n"
619     "}\n");
620 
621   WriteFieldDocComment(printer, descriptor_);
622   printer->Print(variables_,
623     "$deprecation$public Builder set$capitalized_name$Bytes(\n"
624     "    com.google.protobuf.ByteString value) {\n"
625     "$null_check$");
626   if (CheckUtf8(descriptor_)) {
627     printer->Print(variables_,
628       "  checkByteStringIsUtf8(value);\n");
629   }
630   printer->Print(variables_,
631     "  $set_oneof_case_message$;\n"
632     "  $oneof_name$_ = value;\n"
633     "  $on_changed$\n"
634     "  return this;\n"
635     "}\n");
636 }
637 
638 void ImmutableStringOneofFieldGenerator::
GenerateMergingCode(io::Printer * printer) const639 GenerateMergingCode(io::Printer* printer) const {
640   // Allow a slight breach of abstraction here in order to avoid forcing
641   // all string fields to Strings when copying fields from a Message.
642   printer->Print(variables_,
643     "$set_oneof_case_message$;\n"
644     "$oneof_name$_ = other.$oneof_name$_;\n"
645     "$on_changed$\n");
646 }
647 
648 void ImmutableStringOneofFieldGenerator::
GenerateBuildingCode(io::Printer * printer) const649 GenerateBuildingCode(io::Printer* printer) const {
650   printer->Print(variables_,
651     "if ($has_oneof_case_message$) {\n"
652     "  result.$oneof_name$_ = $oneof_name$_;\n"
653     "}\n");
654 }
655 
656 void ImmutableStringOneofFieldGenerator::
GenerateParsingCode(io::Printer * printer) const657 GenerateParsingCode(io::Printer* printer) const {
658   if (CheckUtf8(descriptor_)) {
659     printer->Print(variables_,
660       "java.lang.String s = input.readStringRequireUtf8();\n"
661       "$set_oneof_case_message$;\n"
662       "$oneof_name$_ = s;\n");
663   } else {
664     printer->Print(variables_,
665       "com.google.protobuf.ByteString bs = input.readBytes();\n"
666       "$set_oneof_case_message$;\n"
667       "$oneof_name$_ = bs;\n");
668   }
669 }
670 
671 void ImmutableStringOneofFieldGenerator::
GenerateSerializationCode(io::Printer * printer) const672 GenerateSerializationCode(io::Printer* printer) const {
673   printer->Print(variables_,
674     "if ($has_oneof_case_message$) {\n"
675     "  $writeString$(output, $number$, $oneof_name$_);\n"
676     "}\n");
677 }
678 
679 void ImmutableStringOneofFieldGenerator::
GenerateSerializedSizeCode(io::Printer * printer) const680 GenerateSerializedSizeCode(io::Printer* printer) const {
681   printer->Print(variables_,
682     "if ($has_oneof_case_message$) {\n"
683     "  size += $computeStringSize$($number$, $oneof_name$_);\n"
684     "}\n");
685 }
686 
687 // ===================================================================
688 
689 RepeatedImmutableStringFieldGenerator::
RepeatedImmutableStringFieldGenerator(const FieldDescriptor * descriptor,int messageBitIndex,int builderBitIndex,Context * context)690 RepeatedImmutableStringFieldGenerator(const FieldDescriptor* descriptor,
691                                       int messageBitIndex,
692                                       int builderBitIndex,
693                                       Context* context)
694   : descriptor_(descriptor), messageBitIndex_(messageBitIndex),
695     builderBitIndex_(builderBitIndex), context_(context),
696     name_resolver_(context->GetNameResolver()) {
697   SetPrimitiveVariables(descriptor, messageBitIndex, builderBitIndex,
698                         context->GetFieldGeneratorInfo(descriptor),
699                         name_resolver_, &variables_);
700 }
701 
702 RepeatedImmutableStringFieldGenerator::
~RepeatedImmutableStringFieldGenerator()703 ~RepeatedImmutableStringFieldGenerator() {}
704 
GetNumBitsForMessage() const705 int RepeatedImmutableStringFieldGenerator::GetNumBitsForMessage() const {
706   return 0;
707 }
708 
GetNumBitsForBuilder() const709 int RepeatedImmutableStringFieldGenerator::GetNumBitsForBuilder() const {
710   return 1;
711 }
712 
713 void RepeatedImmutableStringFieldGenerator::
GenerateInterfaceMembers(io::Printer * printer) const714 GenerateInterfaceMembers(io::Printer* printer) const {
715   WriteFieldDocComment(printer, descriptor_);
716   printer->Print(variables_,
717     // NOTE: the same method in the implementation class actually returns
718     // com.google.protobuf.ProtocolStringList (a subclass of List). It's
719     // changed between protobuf 2.5.0 release and protobuf 2.6.1 release.
720     // To retain binary compatibility with both 2.5.0 and 2.6.1 generated
721     // code, we make this interface method return List so both methods
722     // with different return types exist in the compiled byte code.
723     "$deprecation$java.util.List<java.lang.String>\n"
724     "    get$capitalized_name$List();\n");
725   WriteFieldDocComment(printer, descriptor_);
726   printer->Print(variables_,
727     "$deprecation$int get$capitalized_name$Count();\n");
728   WriteFieldDocComment(printer, descriptor_);
729   printer->Print(variables_,
730     "$deprecation$java.lang.String get$capitalized_name$(int index);\n");
731   WriteFieldDocComment(printer, descriptor_);
732   printer->Print(variables_,
733     "$deprecation$com.google.protobuf.ByteString\n"
734     "    get$capitalized_name$Bytes(int index);\n");
735 }
736 
737 
738 void RepeatedImmutableStringFieldGenerator::
GenerateMembers(io::Printer * printer) const739 GenerateMembers(io::Printer* printer) const {
740   printer->Print(variables_,
741     "private com.google.protobuf.LazyStringList $name$_;\n");
742   PrintExtraFieldInfo(variables_, printer);
743   WriteFieldDocComment(printer, descriptor_);
744   printer->Print(variables_,
745     "$deprecation$public com.google.protobuf.ProtocolStringList\n"
746     "    get$capitalized_name$List() {\n"
747     "  return $name$_;\n"   // note:  unmodifiable list
748     "}\n");
749   WriteFieldDocComment(printer, descriptor_);
750   printer->Print(variables_,
751     "$deprecation$public int get$capitalized_name$Count() {\n"
752     "  return $name$_.size();\n"
753     "}\n");
754   WriteFieldDocComment(printer, descriptor_);
755   printer->Print(variables_,
756     "$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
757     "  return $name$_.get(index);\n"
758     "}\n");
759   WriteFieldDocComment(printer, descriptor_);
760   printer->Print(variables_,
761     "$deprecation$public com.google.protobuf.ByteString\n"
762     "    get$capitalized_name$Bytes(int index) {\n"
763     "  return $name$_.getByteString(index);\n"
764     "}\n");
765 }
766 
767 void RepeatedImmutableStringFieldGenerator::
GenerateBuilderMembers(io::Printer * printer) const768 GenerateBuilderMembers(io::Printer* printer) const {
769   // One field is the list and the bit field keeps track of whether the
770   // list is immutable. If it's immutable, the invariant is that it must
771   // either an instance of Collections.emptyList() or it's an ArrayList
772   // wrapped in a Collections.unmodifiableList() wrapper and nobody else has
773   // a refererence to the underlying ArrayList. This invariant allows us to
774   // share instances of lists between protocol buffers avoiding expensive
775   // memory allocations. Note, immutable is a strong guarantee here -- not
776   // just that the list cannot be modified via the reference but that the
777   // list can never be modified.
778   printer->Print(variables_,
779     "private com.google.protobuf.LazyStringList $name$_ = $empty_list$;\n");
780 
781   printer->Print(variables_,
782     "private void ensure$capitalized_name$IsMutable() {\n"
783     "  if (!$get_mutable_bit_builder$) {\n"
784     "    $name$_ = new com.google.protobuf.LazyStringArrayList($name$_);\n"
785     "    $set_mutable_bit_builder$;\n"
786     "   }\n"
787     "}\n");
788 
789     // Note:  We return an unmodifiable list because otherwise the caller
790     //   could hold on to the returned list and modify it after the message
791     //   has been built, thus mutating the message which is supposed to be
792     //   immutable.
793   WriteFieldDocComment(printer, descriptor_);
794   printer->Print(variables_,
795     "$deprecation$public com.google.protobuf.ProtocolStringList\n"
796     "    get$capitalized_name$List() {\n"
797     "  return $name$_.getUnmodifiableView();\n"
798     "}\n");
799   WriteFieldDocComment(printer, descriptor_);
800   printer->Print(variables_,
801     "$deprecation$public int get$capitalized_name$Count() {\n"
802     "  return $name$_.size();\n"
803     "}\n");
804   WriteFieldDocComment(printer, descriptor_);
805   printer->Print(variables_,
806     "$deprecation$public java.lang.String get$capitalized_name$(int index) {\n"
807     "  return $name$_.get(index);\n"
808     "}\n");
809   WriteFieldDocComment(printer, descriptor_);
810   printer->Print(variables_,
811     "$deprecation$public com.google.protobuf.ByteString\n"
812     "    get$capitalized_name$Bytes(int index) {\n"
813     "  return $name$_.getByteString(index);\n"
814     "}\n");
815   WriteFieldDocComment(printer, descriptor_);
816   printer->Print(variables_,
817     "$deprecation$public Builder set$capitalized_name$(\n"
818     "    int index, java.lang.String value) {\n"
819     "$null_check$"
820     "  ensure$capitalized_name$IsMutable();\n"
821     "  $name$_.set(index, value);\n"
822     "  $on_changed$\n"
823     "  return this;\n"
824     "}\n");
825   WriteFieldDocComment(printer, descriptor_);
826   printer->Print(variables_,
827     "$deprecation$public Builder add$capitalized_name$(\n"
828     "    java.lang.String value) {\n"
829     "$null_check$"
830     "  ensure$capitalized_name$IsMutable();\n"
831     "  $name$_.add(value);\n"
832     "  $on_changed$\n"
833     "  return this;\n"
834     "}\n");
835   WriteFieldDocComment(printer, descriptor_);
836   printer->Print(variables_,
837     "$deprecation$public Builder addAll$capitalized_name$(\n"
838     "    java.lang.Iterable<java.lang.String> values) {\n"
839     "  ensure$capitalized_name$IsMutable();\n"
840     "  com.google.protobuf.AbstractMessageLite.Builder.addAll(\n"
841     "      values, $name$_);\n"
842     "  $on_changed$\n"
843     "  return this;\n"
844     "}\n");
845   WriteFieldDocComment(printer, descriptor_);
846   printer->Print(variables_,
847     "$deprecation$public Builder clear$capitalized_name$() {\n"
848     "  $name$_ = $empty_list$;\n"
849     "  $clear_mutable_bit_builder$;\n"
850     "  $on_changed$\n"
851     "  return this;\n"
852     "}\n");
853 
854   WriteFieldDocComment(printer, descriptor_);
855   printer->Print(variables_,
856     "$deprecation$public Builder add$capitalized_name$Bytes(\n"
857     "    com.google.protobuf.ByteString value) {\n"
858     "$null_check$");
859   if (CheckUtf8(descriptor_)) {
860     printer->Print(variables_,
861       "  checkByteStringIsUtf8(value);\n");
862   }
863   printer->Print(variables_,
864     "  ensure$capitalized_name$IsMutable();\n"
865     "  $name$_.add(value);\n"
866     "  $on_changed$\n"
867     "  return this;\n"
868     "}\n");
869 }
870 
871 void RepeatedImmutableStringFieldGenerator::
GenerateFieldBuilderInitializationCode(io::Printer * printer) const872 GenerateFieldBuilderInitializationCode(io::Printer* printer)  const {
873   // noop for primitives
874 }
875 
876 void RepeatedImmutableStringFieldGenerator::
GenerateInitializationCode(io::Printer * printer) const877 GenerateInitializationCode(io::Printer* printer) const {
878   printer->Print(variables_, "$name$_ = $empty_list$;\n");
879 }
880 
881 void RepeatedImmutableStringFieldGenerator::
GenerateBuilderClearCode(io::Printer * printer) const882 GenerateBuilderClearCode(io::Printer* printer) const {
883   printer->Print(variables_,
884     "$name$_ = $empty_list$;\n"
885     "$clear_mutable_bit_builder$;\n");
886 }
887 
888 void RepeatedImmutableStringFieldGenerator::
GenerateMergingCode(io::Printer * printer) const889 GenerateMergingCode(io::Printer* printer) const {
890   // The code below does two optimizations:
891   //   1. If the other list is empty, there's nothing to do. This ensures we
892   //      don't allocate a new array if we already have an immutable one.
893   //   2. If the other list is non-empty and our current list is empty, we can
894   //      reuse the other list which is guaranteed to be immutable.
895   printer->Print(variables_,
896     "if (!other.$name$_.isEmpty()) {\n"
897     "  if ($name$_.isEmpty()) {\n"
898     "    $name$_ = other.$name$_;\n"
899     "    $clear_mutable_bit_builder$;\n"
900     "  } else {\n"
901     "    ensure$capitalized_name$IsMutable();\n"
902     "    $name$_.addAll(other.$name$_);\n"
903     "  }\n"
904     "  $on_changed$\n"
905     "}\n");
906 }
907 
908 void RepeatedImmutableStringFieldGenerator::
GenerateBuildingCode(io::Printer * printer) const909 GenerateBuildingCode(io::Printer* printer) const {
910   // The code below ensures that the result has an immutable list. If our
911   // list is immutable, we can just reuse it. If not, we make it immutable.
912 
913   printer->Print(variables_,
914     "if ($get_mutable_bit_builder$) {\n"
915     "  $name$_ = $name$_.getUnmodifiableView();\n"
916     "  $clear_mutable_bit_builder$;\n"
917     "}\n"
918     "result.$name$_ = $name$_;\n");
919 }
920 
921 void RepeatedImmutableStringFieldGenerator::
GenerateParsingCode(io::Printer * printer) const922 GenerateParsingCode(io::Printer* printer) const {
923   if (CheckUtf8(descriptor_)) {
924     printer->Print(variables_,
925     "java.lang.String s = input.readStringRequireUtf8();\n");
926   } else {
927     printer->Print(variables_,
928     "com.google.protobuf.ByteString bs = input.readBytes();\n");
929   }
930   printer->Print(variables_,
931     "if (!$get_mutable_bit_parser$) {\n"
932     "  $name$_ = new com.google.protobuf.LazyStringArrayList();\n"
933     "  $set_mutable_bit_parser$;\n"
934     "}\n");
935   if (CheckUtf8(descriptor_)) {
936     printer->Print(variables_,
937       "$name$_.add(s);\n");
938   } else {
939     printer->Print(variables_,
940       "$name$_.add(bs);\n");
941   }
942 }
943 
944 void RepeatedImmutableStringFieldGenerator::
GenerateParsingDoneCode(io::Printer * printer) const945 GenerateParsingDoneCode(io::Printer* printer) const {
946   printer->Print(variables_,
947     "if ($get_mutable_bit_parser$) {\n"
948     "  $name$_ = $name$_.getUnmodifiableView();\n"
949     "}\n");
950 }
951 
952 void RepeatedImmutableStringFieldGenerator::
GenerateSerializationCode(io::Printer * printer) const953 GenerateSerializationCode(io::Printer* printer) const {
954   printer->Print(variables_,
955     "for (int i = 0; i < $name$_.size(); i++) {\n"
956     "  $writeString$(output, $number$, $name$_.getRaw(i));\n"
957     "}\n");
958 }
959 
960 void RepeatedImmutableStringFieldGenerator::
GenerateSerializedSizeCode(io::Printer * printer) const961 GenerateSerializedSizeCode(io::Printer* printer) const {
962   printer->Print(variables_,
963     "{\n"
964     "  int dataSize = 0;\n");
965   printer->Indent();
966 
967   printer->Print(variables_,
968     "for (int i = 0; i < $name$_.size(); i++) {\n"
969     "  dataSize += computeStringSizeNoTag($name$_.getRaw(i));\n"
970     "}\n");
971 
972   printer->Print(
973       "size += dataSize;\n");
974 
975   printer->Print(variables_,
976     "size += $tag_size$ * get$capitalized_name$List().size();\n");
977 
978   printer->Outdent();
979   printer->Print("}\n");
980 }
981 
982 void RepeatedImmutableStringFieldGenerator::
GenerateEqualsCode(io::Printer * printer) const983 GenerateEqualsCode(io::Printer* printer) const {
984   printer->Print(variables_,
985     "result = result && get$capitalized_name$List()\n"
986     "    .equals(other.get$capitalized_name$List());\n");
987 }
988 
989 void RepeatedImmutableStringFieldGenerator::
GenerateHashCode(io::Printer * printer) const990 GenerateHashCode(io::Printer* printer) const {
991   printer->Print(variables_,
992     "if (get$capitalized_name$Count() > 0) {\n"
993     "  hash = (37 * hash) + $constant_name$;\n"
994     "  hash = (53 * hash) + get$capitalized_name$List().hashCode();\n"
995     "}\n");
996 }
997 
GetBoxedType() const998 string RepeatedImmutableStringFieldGenerator::GetBoxedType() const {
999   return "String";
1000 }
1001 
1002 }  // namespace java
1003 }  // namespace compiler
1004 }  // namespace protobuf
1005 }  // namespace google
1006