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