1 // Protocol Buffers - Google's data interchange format 2 // Copyright 2008 Google Inc. All rights reserved. 3 // http://code.google.com/p/protobuf/ 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 (at) google.com (Kenton Varda) 32 // Based on original Protocol Buffers design by 33 // Sanjay Ghemawat, Jeff Dean, and others. 34 35 #include <google/protobuf/compiler/java/java_message.h> 36 37 #include <algorithm> 38 #include <google/protobuf/stubs/hash.h> 39 #include <map> 40 #include <vector> 41 42 #include <google/protobuf/compiler/java/java_doc_comment.h> 43 #include <google/protobuf/compiler/java/java_enum.h> 44 #include <google/protobuf/compiler/java/java_extension.h> 45 #include <google/protobuf/compiler/java/java_helpers.h> 46 #include <google/protobuf/io/coded_stream.h> 47 #include <google/protobuf/io/printer.h> 48 #include <google/protobuf/descriptor.pb.h> 49 #include <google/protobuf/wire_format.h> 50 #include <google/protobuf/stubs/strutil.h> 51 #include <google/protobuf/stubs/substitute.h> 52 53 namespace google { 54 namespace protobuf { 55 namespace compiler { 56 namespace java { 57 58 using internal::WireFormat; 59 using internal::WireFormatLite; 60 61 namespace { 62 63 void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field) { 64 // Print the field's proto-syntax definition as a comment. We don't want to 65 // print group bodies so we cut off after the first line. 66 string def = field->DebugString(); 67 printer->Print("// $def$\n", 68 "def", def.substr(0, def.find_first_of('\n'))); 69 } 70 71 struct FieldOrderingByNumber { 72 inline bool operator()(const FieldDescriptor* a, 73 const FieldDescriptor* b) const { 74 return a->number() < b->number(); 75 } 76 }; 77 78 struct ExtensionRangeOrdering { 79 bool operator()(const Descriptor::ExtensionRange* a, 80 const Descriptor::ExtensionRange* b) const { 81 return a->start < b->start; 82 } 83 }; 84 85 // Sort the fields of the given Descriptor by number into a new[]'d array 86 // and return it. 87 const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { 88 const FieldDescriptor** fields = 89 new const FieldDescriptor*[descriptor->field_count()]; 90 for (int i = 0; i < descriptor->field_count(); i++) { 91 fields[i] = descriptor->field(i); 92 } 93 sort(fields, fields + descriptor->field_count(), 94 FieldOrderingByNumber()); 95 return fields; 96 } 97 98 // Get an identifier that uniquely identifies this type within the file. 99 // This is used to declare static variables related to this type at the 100 // outermost file scope. 101 string UniqueFileScopeIdentifier(const Descriptor* descriptor) { 102 return "static_" + StringReplace(descriptor->full_name(), ".", "_", true); 103 } 104 105 // Returns true if the message type has any required fields. If it doesn't, 106 // we can optimize out calls to its isInitialized() method. 107 // 108 // already_seen is used to avoid checking the same type multiple times 109 // (and also to protect against recursion). 110 static bool HasRequiredFields( 111 const Descriptor* type, 112 hash_set<const Descriptor*>* already_seen) { 113 if (already_seen->count(type) > 0) { 114 // The type is already in cache. This means that either: 115 // a. The type has no required fields. 116 // b. We are in the midst of checking if the type has required fields, 117 // somewhere up the stack. In this case, we know that if the type 118 // has any required fields, they'll be found when we return to it, 119 // and the whole call to HasRequiredFields() will return true. 120 // Therefore, we don't have to check if this type has required fields 121 // here. 122 return false; 123 } 124 already_seen->insert(type); 125 126 // If the type has extensions, an extension with message type could contain 127 // required fields, so we have to be conservative and assume such an 128 // extension exists. 129 if (type->extension_range_count() > 0) return true; 130 131 for (int i = 0; i < type->field_count(); i++) { 132 const FieldDescriptor* field = type->field(i); 133 if (field->is_required()) { 134 return true; 135 } 136 if (GetJavaType(field) == JAVATYPE_MESSAGE) { 137 if (HasRequiredFields(field->message_type(), already_seen)) { 138 return true; 139 } 140 } 141 } 142 143 return false; 144 } 145 146 static bool HasRequiredFields(const Descriptor* type) { 147 hash_set<const Descriptor*> already_seen; 148 return HasRequiredFields(type, &already_seen); 149 } 150 151 } // namespace 152 153 // =================================================================== 154 155 MessageGenerator::MessageGenerator(const Descriptor* descriptor) 156 : descriptor_(descriptor), 157 field_generators_(descriptor) { 158 } 159 160 MessageGenerator::~MessageGenerator() {} 161 162 void MessageGenerator::GenerateStaticVariables(io::Printer* printer) { 163 if (HasDescriptorMethods(descriptor_)) { 164 // Because descriptor.proto (com.google.protobuf.DescriptorProtos) is 165 // used in the construction of descriptors, we have a tricky bootstrapping 166 // problem. To help control static initialization order, we make sure all 167 // descriptors and other static data that depends on them are members of 168 // the outermost class in the file. This way, they will be initialized in 169 // a deterministic order. 170 171 map<string, string> vars; 172 vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); 173 vars["index"] = SimpleItoa(descriptor_->index()); 174 vars["classname"] = ClassName(descriptor_); 175 if (descriptor_->containing_type() != NULL) { 176 vars["parent"] = UniqueFileScopeIdentifier( 177 descriptor_->containing_type()); 178 } 179 if (descriptor_->file()->options().java_multiple_files()) { 180 // We can only make these package-private since the classes that use them 181 // are in separate files. 182 vars["private"] = ""; 183 } else { 184 vars["private"] = "private "; 185 } 186 187 // The descriptor for this type. 188 printer->Print(vars, 189 "$private$static com.google.protobuf.Descriptors.Descriptor\n" 190 " internal_$identifier$_descriptor;\n"); 191 192 // And the FieldAccessorTable. 193 printer->Print(vars, 194 "$private$static\n" 195 " com.google.protobuf.GeneratedMessage.FieldAccessorTable\n" 196 " internal_$identifier$_fieldAccessorTable;\n"); 197 } 198 199 // Generate static members for all nested types. 200 for (int i = 0; i < descriptor_->nested_type_count(); i++) { 201 // TODO(kenton): Reuse MessageGenerator objects? 202 MessageGenerator(descriptor_->nested_type(i)) 203 .GenerateStaticVariables(printer); 204 } 205 } 206 207 void MessageGenerator::GenerateStaticVariableInitializers( 208 io::Printer* printer) { 209 if (HasDescriptorMethods(descriptor_)) { 210 map<string, string> vars; 211 vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); 212 vars["index"] = SimpleItoa(descriptor_->index()); 213 vars["classname"] = ClassName(descriptor_); 214 if (descriptor_->containing_type() != NULL) { 215 vars["parent"] = UniqueFileScopeIdentifier( 216 descriptor_->containing_type()); 217 } 218 219 // The descriptor for this type. 220 if (descriptor_->containing_type() == NULL) { 221 printer->Print(vars, 222 "internal_$identifier$_descriptor =\n" 223 " getDescriptor().getMessageTypes().get($index$);\n"); 224 } else { 225 printer->Print(vars, 226 "internal_$identifier$_descriptor =\n" 227 " internal_$parent$_descriptor.getNestedTypes().get($index$);\n"); 228 } 229 230 // And the FieldAccessorTable. 231 printer->Print(vars, 232 "internal_$identifier$_fieldAccessorTable = new\n" 233 " com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n" 234 " internal_$identifier$_descriptor,\n" 235 " new java.lang.String[] { "); 236 for (int i = 0; i < descriptor_->field_count(); i++) { 237 printer->Print( 238 "\"$field_name$\", ", 239 "field_name", 240 UnderscoresToCapitalizedCamelCase(descriptor_->field(i))); 241 } 242 printer->Print( 243 "});\n"); 244 } 245 246 // Generate static member initializers for all nested types. 247 for (int i = 0; i < descriptor_->nested_type_count(); i++) { 248 // TODO(kenton): Reuse MessageGenerator objects? 249 MessageGenerator(descriptor_->nested_type(i)) 250 .GenerateStaticVariableInitializers(printer); 251 } 252 } 253 254 // =================================================================== 255 256 void MessageGenerator::GenerateInterface(io::Printer* printer) { 257 if (descriptor_->extension_range_count() > 0) { 258 if (HasDescriptorMethods(descriptor_)) { 259 printer->Print( 260 "public interface $classname$OrBuilder extends\n" 261 " com.google.protobuf.GeneratedMessage.\n" 262 " ExtendableMessageOrBuilder<$classname$> {\n", 263 "classname", descriptor_->name()); 264 } else { 265 printer->Print( 266 "public interface $classname$OrBuilder extends \n" 267 " com.google.protobuf.GeneratedMessageLite.\n" 268 " ExtendableMessageOrBuilder<$classname$> {\n", 269 "classname", descriptor_->name()); 270 } 271 } else { 272 if (HasDescriptorMethods(descriptor_)) { 273 printer->Print( 274 "public interface $classname$OrBuilder\n" 275 " extends com.google.protobuf.MessageOrBuilder {\n", 276 "classname", descriptor_->name()); 277 } else { 278 printer->Print( 279 "public interface $classname$OrBuilder\n" 280 " extends com.google.protobuf.MessageLiteOrBuilder {\n", 281 "classname", descriptor_->name()); 282 } 283 } 284 285 printer->Indent(); 286 for (int i = 0; i < descriptor_->field_count(); i++) { 287 printer->Print("\n"); 288 PrintFieldComment(printer, descriptor_->field(i)); 289 field_generators_.get(descriptor_->field(i)) 290 .GenerateInterfaceMembers(printer); 291 } 292 printer->Outdent(); 293 294 printer->Print("}\n"); 295 } 296 297 // =================================================================== 298 299 void MessageGenerator::Generate(io::Printer* printer) { 300 bool is_own_file = 301 descriptor_->containing_type() == NULL && 302 descriptor_->file()->options().java_multiple_files(); 303 304 WriteMessageDocComment(printer, descriptor_); 305 306 // The builder_type stores the super type name of the nested Builder class. 307 string builder_type; 308 if (descriptor_->extension_range_count() > 0) { 309 if (HasDescriptorMethods(descriptor_)) { 310 printer->Print( 311 "public $static$ final class $classname$ extends\n" 312 " com.google.protobuf.GeneratedMessage.ExtendableMessage<\n" 313 " $classname$> implements $classname$OrBuilder {\n", 314 "static", is_own_file ? "" : "static", 315 "classname", descriptor_->name()); 316 builder_type = strings::Substitute( 317 "com.google.protobuf.GeneratedMessage.ExtendableBuilder<$0, ?>", 318 ClassName(descriptor_)); 319 } else { 320 printer->Print( 321 "public $static$ final class $classname$ extends\n" 322 " com.google.protobuf.GeneratedMessageLite.ExtendableMessage<\n" 323 " $classname$> implements $classname$OrBuilder {\n", 324 "static", is_own_file ? "" : "static", 325 "classname", descriptor_->name()); 326 builder_type = strings::Substitute( 327 "com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<$0, ?>", 328 ClassName(descriptor_)); 329 } 330 } else { 331 if (HasDescriptorMethods(descriptor_)) { 332 printer->Print( 333 "public $static$ final class $classname$ extends\n" 334 " com.google.protobuf.GeneratedMessage\n" 335 " implements $classname$OrBuilder {\n", 336 "static", is_own_file ? "" : "static", 337 "classname", descriptor_->name()); 338 builder_type = "com.google.protobuf.GeneratedMessage.Builder<?>"; 339 } else { 340 printer->Print( 341 "public $static$ final class $classname$ extends\n" 342 " com.google.protobuf.GeneratedMessageLite\n" 343 " implements $classname$OrBuilder {\n", 344 "static", is_own_file ? "" : "static", 345 "classname", descriptor_->name()); 346 builder_type = "com.google.protobuf.GeneratedMessageLite.Builder"; 347 } 348 } 349 printer->Indent(); 350 // Using builder_type, instead of Builder, prevents the Builder class from 351 // being loaded into PermGen space when the default instance is created. 352 // This optimizes the PermGen space usage for clients that do not modify 353 // messages. 354 printer->Print( 355 "// Use $classname$.newBuilder() to construct.\n" 356 "private $classname$($buildertype$ builder) {\n" 357 " super(builder);\n" 358 "$set_unknown_fields$\n" 359 "}\n", 360 "classname", descriptor_->name(), 361 "buildertype", builder_type, 362 "set_unknown_fields", HasUnknownFields(descriptor_) 363 ? " this.unknownFields = builder.getUnknownFields();" : ""); 364 printer->Print( 365 // Used when constructing the default instance, which cannot be initialized 366 // immediately because it may cyclically refer to other default instances. 367 "private $classname$(boolean noInit) {$set_default_unknown_fields$}\n" 368 "\n" 369 "private static final $classname$ defaultInstance;\n" 370 "public static $classname$ getDefaultInstance() {\n" 371 " return defaultInstance;\n" 372 "}\n" 373 "\n" 374 "public $classname$ getDefaultInstanceForType() {\n" 375 " return defaultInstance;\n" 376 "}\n" 377 "\n", 378 "classname", descriptor_->name(), 379 "set_default_unknown_fields", HasUnknownFields(descriptor_) 380 ? " this.unknownFields =" 381 " com.google.protobuf.UnknownFieldSet.getDefaultInstance(); " : ""); 382 383 if (HasUnknownFields(descriptor_)) { 384 printer->Print( 385 "private final com.google.protobuf.UnknownFieldSet unknownFields;\n" 386 "" 387 "@java.lang.Override\n" 388 "public final com.google.protobuf.UnknownFieldSet\n" 389 " getUnknownFields() {\n" 390 " return this.unknownFields;\n" 391 "}\n"); 392 } 393 394 if (HasGeneratedMethods(descriptor_)) { 395 GenerateParsingConstructor(printer); 396 } 397 398 GenerateDescriptorMethods(printer); 399 GenerateParser(printer); 400 401 // Nested types 402 for (int i = 0; i < descriptor_->enum_type_count(); i++) { 403 EnumGenerator(descriptor_->enum_type(i)).Generate(printer); 404 } 405 406 for (int i = 0; i < descriptor_->nested_type_count(); i++) { 407 MessageGenerator messageGenerator(descriptor_->nested_type(i)); 408 messageGenerator.GenerateInterface(printer); 409 messageGenerator.Generate(printer); 410 } 411 412 // Integers for bit fields. 413 int totalBits = 0; 414 for (int i = 0; i < descriptor_->field_count(); i++) { 415 totalBits += field_generators_.get(descriptor_->field(i)) 416 .GetNumBitsForMessage(); 417 } 418 int totalInts = (totalBits + 31) / 32; 419 for (int i = 0; i < totalInts; i++) { 420 printer->Print("private int $bit_field_name$;\n", 421 "bit_field_name", GetBitFieldName(i)); 422 } 423 424 // Fields 425 for (int i = 0; i < descriptor_->field_count(); i++) { 426 PrintFieldComment(printer, descriptor_->field(i)); 427 printer->Print("public static final int $constant_name$ = $number$;\n", 428 "constant_name", FieldConstantName(descriptor_->field(i)), 429 "number", SimpleItoa(descriptor_->field(i)->number())); 430 field_generators_.get(descriptor_->field(i)).GenerateMembers(printer); 431 printer->Print("\n"); 432 } 433 434 // Called by the constructor, except in the case of the default instance, 435 // in which case this is called by static init code later on. 436 printer->Print("private void initFields() {\n"); 437 printer->Indent(); 438 for (int i = 0; i < descriptor_->field_count(); i++) { 439 field_generators_.get(descriptor_->field(i)) 440 .GenerateInitializationCode(printer); 441 } 442 printer->Outdent(); 443 printer->Print("}\n"); 444 445 if (HasGeneratedMethods(descriptor_)) { 446 GenerateIsInitialized(printer, MEMOIZE); 447 GenerateMessageSerializationMethods(printer); 448 } 449 450 if (HasEqualsAndHashCode(descriptor_)) { 451 GenerateEqualsAndHashCode(printer); 452 } 453 454 GenerateParseFromMethods(printer); 455 GenerateBuilder(printer); 456 457 // Carefully initialize the default instance in such a way that it doesn't 458 // conflict with other initialization. 459 printer->Print( 460 "\n" 461 "static {\n" 462 " defaultInstance = new $classname$(true);\n" 463 " defaultInstance.initFields();\n" 464 "}\n" 465 "\n" 466 "// @@protoc_insertion_point(class_scope:$full_name$)\n", 467 "classname", descriptor_->name(), 468 "full_name", descriptor_->full_name()); 469 470 // Extensions must be declared after the defaultInstance is initialized 471 // because the defaultInstance is used by the extension to lazily retrieve 472 // the outer class's FileDescriptor. 473 for (int i = 0; i < descriptor_->extension_count(); i++) { 474 ExtensionGenerator(descriptor_->extension(i)).Generate(printer); 475 } 476 477 printer->Outdent(); 478 printer->Print("}\n\n"); 479 } 480 481 482 // =================================================================== 483 484 void MessageGenerator:: 485 GenerateMessageSerializationMethods(io::Printer* printer) { 486 scoped_array<const FieldDescriptor*> sorted_fields( 487 SortFieldsByNumber(descriptor_)); 488 489 vector<const Descriptor::ExtensionRange*> sorted_extensions; 490 for (int i = 0; i < descriptor_->extension_range_count(); ++i) { 491 sorted_extensions.push_back(descriptor_->extension_range(i)); 492 } 493 sort(sorted_extensions.begin(), sorted_extensions.end(), 494 ExtensionRangeOrdering()); 495 496 printer->Print( 497 "public void writeTo(com.google.protobuf.CodedOutputStream output)\n" 498 " throws java.io.IOException {\n"); 499 printer->Indent(); 500 // writeTo(CodedOutputStream output) might be invoked without 501 // getSerializedSize() ever being called, but we need the memoized 502 // sizes in case this message has packed fields. Rather than emit checks for 503 // each packed field, just call getSerializedSize() up front for all messages. 504 // In most cases, getSerializedSize() will have already been called anyway by 505 // one of the wrapper writeTo() methods, making this call cheap. 506 printer->Print( 507 "getSerializedSize();\n"); 508 509 if (descriptor_->extension_range_count() > 0) { 510 if (descriptor_->options().message_set_wire_format()) { 511 printer->Print( 512 "com.google.protobuf.GeneratedMessage$lite$\n" 513 " .ExtendableMessage<$classname$>.ExtensionWriter extensionWriter =\n" 514 " newMessageSetExtensionWriter();\n", 515 "lite", HasDescriptorMethods(descriptor_) ? "" : "Lite", 516 "classname", ClassName(descriptor_)); 517 } else { 518 printer->Print( 519 "com.google.protobuf.GeneratedMessage$lite$\n" 520 " .ExtendableMessage<$classname$>.ExtensionWriter extensionWriter =\n" 521 " newExtensionWriter();\n", 522 "lite", HasDescriptorMethods(descriptor_) ? "" : "Lite", 523 "classname", ClassName(descriptor_)); 524 } 525 } 526 527 // Merge the fields and the extension ranges, both sorted by field number. 528 for (int i = 0, j = 0; 529 i < descriptor_->field_count() || j < sorted_extensions.size(); 530 ) { 531 if (i == descriptor_->field_count()) { 532 GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); 533 } else if (j == sorted_extensions.size()) { 534 GenerateSerializeOneField(printer, sorted_fields[i++]); 535 } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { 536 GenerateSerializeOneField(printer, sorted_fields[i++]); 537 } else { 538 GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]); 539 } 540 } 541 542 if (HasUnknownFields(descriptor_)) { 543 if (descriptor_->options().message_set_wire_format()) { 544 printer->Print( 545 "getUnknownFields().writeAsMessageSetTo(output);\n"); 546 } else { 547 printer->Print( 548 "getUnknownFields().writeTo(output);\n"); 549 } 550 } 551 552 printer->Outdent(); 553 printer->Print( 554 "}\n" 555 "\n" 556 "private int memoizedSerializedSize = -1;\n" 557 "public int getSerializedSize() {\n" 558 " int size = memoizedSerializedSize;\n" 559 " if (size != -1) return size;\n" 560 "\n" 561 " size = 0;\n"); 562 printer->Indent(); 563 564 for (int i = 0; i < descriptor_->field_count(); i++) { 565 field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCode(printer); 566 } 567 568 if (descriptor_->extension_range_count() > 0) { 569 if (descriptor_->options().message_set_wire_format()) { 570 printer->Print( 571 "size += extensionsSerializedSizeAsMessageSet();\n"); 572 } else { 573 printer->Print( 574 "size += extensionsSerializedSize();\n"); 575 } 576 } 577 578 if (HasUnknownFields(descriptor_)) { 579 if (descriptor_->options().message_set_wire_format()) { 580 printer->Print( 581 "size += getUnknownFields().getSerializedSizeAsMessageSet();\n"); 582 } else { 583 printer->Print( 584 "size += getUnknownFields().getSerializedSize();\n"); 585 } 586 } 587 588 printer->Outdent(); 589 printer->Print( 590 " memoizedSerializedSize = size;\n" 591 " return size;\n" 592 "}\n" 593 "\n"); 594 595 printer->Print( 596 "private static final long serialVersionUID = 0L;\n" 597 "@java.lang.Override\n" 598 "protected java.lang.Object writeReplace()\n" 599 " throws java.io.ObjectStreamException {\n" 600 " return super.writeReplace();\n" 601 "}\n" 602 "\n"); 603 } 604 605 void MessageGenerator:: 606 GenerateParseFromMethods(io::Printer* printer) { 607 // Note: These are separate from GenerateMessageSerializationMethods() 608 // because they need to be generated even for messages that are optimized 609 // for code size. 610 printer->Print( 611 "public static $classname$ parseFrom(\n" 612 " com.google.protobuf.ByteString data)\n" 613 " throws com.google.protobuf.InvalidProtocolBufferException {\n" 614 " return PARSER.parseFrom(data);\n" 615 "}\n" 616 "public static $classname$ parseFrom(\n" 617 " com.google.protobuf.ByteString data,\n" 618 " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" 619 " throws com.google.protobuf.InvalidProtocolBufferException {\n" 620 " return PARSER.parseFrom(data, extensionRegistry);\n" 621 "}\n" 622 "public static $classname$ parseFrom(byte[] data)\n" 623 " throws com.google.protobuf.InvalidProtocolBufferException {\n" 624 " return PARSER.parseFrom(data);\n" 625 "}\n" 626 "public static $classname$ parseFrom(\n" 627 " byte[] data,\n" 628 " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" 629 " throws com.google.protobuf.InvalidProtocolBufferException {\n" 630 " return PARSER.parseFrom(data, extensionRegistry);\n" 631 "}\n" 632 "public static $classname$ parseFrom(java.io.InputStream input)\n" 633 " throws java.io.IOException {\n" 634 " return PARSER.parseFrom(input);\n" 635 "}\n" 636 "public static $classname$ parseFrom(\n" 637 " java.io.InputStream input,\n" 638 " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" 639 " throws java.io.IOException {\n" 640 " return PARSER.parseFrom(input, extensionRegistry);\n" 641 "}\n" 642 "public static $classname$ parseDelimitedFrom(java.io.InputStream input)\n" 643 " throws java.io.IOException {\n" 644 " return PARSER.parseDelimitedFrom(input);\n" 645 "}\n" 646 "public static $classname$ parseDelimitedFrom(\n" 647 " java.io.InputStream input,\n" 648 " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" 649 " throws java.io.IOException {\n" 650 " return PARSER.parseDelimitedFrom(input, extensionRegistry);\n" 651 "}\n" 652 "public static $classname$ parseFrom(\n" 653 " com.google.protobuf.CodedInputStream input)\n" 654 " throws java.io.IOException {\n" 655 " return PARSER.parseFrom(input);\n" 656 "}\n" 657 "public static $classname$ parseFrom(\n" 658 " com.google.protobuf.CodedInputStream input,\n" 659 " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" 660 " throws java.io.IOException {\n" 661 " return PARSER.parseFrom(input, extensionRegistry);\n" 662 "}\n" 663 "\n", 664 "classname", ClassName(descriptor_)); 665 } 666 667 void MessageGenerator::GenerateSerializeOneField( 668 io::Printer* printer, const FieldDescriptor* field) { 669 field_generators_.get(field).GenerateSerializationCode(printer); 670 } 671 672 void MessageGenerator::GenerateSerializeOneExtensionRange( 673 io::Printer* printer, const Descriptor::ExtensionRange* range) { 674 printer->Print( 675 "extensionWriter.writeUntil($end$, output);\n", 676 "end", SimpleItoa(range->end)); 677 } 678 679 // =================================================================== 680 681 void MessageGenerator::GenerateBuilder(io::Printer* printer) { 682 printer->Print( 683 "public static Builder newBuilder() { return Builder.create(); }\n" 684 "public Builder newBuilderForType() { return newBuilder(); }\n" 685 "public static Builder newBuilder($classname$ prototype) {\n" 686 " return newBuilder().mergeFrom(prototype);\n" 687 "}\n" 688 "public Builder toBuilder() { return newBuilder(this); }\n" 689 "\n", 690 "classname", ClassName(descriptor_)); 691 692 if (HasNestedBuilders(descriptor_)) { 693 printer->Print( 694 "@java.lang.Override\n" 695 "protected Builder newBuilderForType(\n" 696 " com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n" 697 " Builder builder = new Builder(parent);\n" 698 " return builder;\n" 699 "}\n"); 700 } 701 702 WriteMessageDocComment(printer, descriptor_); 703 704 if (descriptor_->extension_range_count() > 0) { 705 if (HasDescriptorMethods(descriptor_)) { 706 printer->Print( 707 "public static final class Builder extends\n" 708 " com.google.protobuf.GeneratedMessage.ExtendableBuilder<\n" 709 " $classname$, Builder> implements $classname$OrBuilder {\n", 710 "classname", ClassName(descriptor_)); 711 } else { 712 printer->Print( 713 "public static final class Builder extends\n" 714 " com.google.protobuf.GeneratedMessageLite.ExtendableBuilder<\n" 715 " $classname$, Builder> implements $classname$OrBuilder {\n", 716 "classname", ClassName(descriptor_)); 717 } 718 } else { 719 if (HasDescriptorMethods(descriptor_)) { 720 printer->Print( 721 "public static final class Builder extends\n" 722 " com.google.protobuf.GeneratedMessage.Builder<Builder>\n" 723 " implements $classname$OrBuilder {\n", 724 "classname", ClassName(descriptor_)); 725 } else { 726 printer->Print( 727 "public static final class Builder extends\n" 728 " com.google.protobuf.GeneratedMessageLite.Builder<\n" 729 " $classname$, Builder>\n" 730 " implements $classname$OrBuilder {\n", 731 "classname", ClassName(descriptor_)); 732 } 733 } 734 printer->Indent(); 735 736 GenerateDescriptorMethods(printer); 737 GenerateCommonBuilderMethods(printer); 738 739 if (HasGeneratedMethods(descriptor_)) { 740 GenerateIsInitialized(printer, DONT_MEMOIZE); 741 GenerateBuilderParsingMethods(printer); 742 } 743 744 // Integers for bit fields. 745 int totalBits = 0; 746 for (int i = 0; i < descriptor_->field_count(); i++) { 747 totalBits += field_generators_.get(descriptor_->field(i)) 748 .GetNumBitsForBuilder(); 749 } 750 int totalInts = (totalBits + 31) / 32; 751 for (int i = 0; i < totalInts; i++) { 752 printer->Print("private int $bit_field_name$;\n", 753 "bit_field_name", GetBitFieldName(i)); 754 } 755 756 for (int i = 0; i < descriptor_->field_count(); i++) { 757 printer->Print("\n"); 758 PrintFieldComment(printer, descriptor_->field(i)); 759 field_generators_.get(descriptor_->field(i)) 760 .GenerateBuilderMembers(printer); 761 } 762 763 printer->Print( 764 "\n" 765 "// @@protoc_insertion_point(builder_scope:$full_name$)\n", 766 "full_name", descriptor_->full_name()); 767 768 printer->Outdent(); 769 printer->Print("}\n"); 770 } 771 772 void MessageGenerator::GenerateDescriptorMethods(io::Printer* printer) { 773 if (HasDescriptorMethods(descriptor_)) { 774 if (!descriptor_->options().no_standard_descriptor_accessor()) { 775 printer->Print( 776 "public static final com.google.protobuf.Descriptors.Descriptor\n" 777 " getDescriptor() {\n" 778 " return $fileclass$.internal_$identifier$_descriptor;\n" 779 "}\n" 780 "\n", 781 "fileclass", ClassName(descriptor_->file()), 782 "identifier", UniqueFileScopeIdentifier(descriptor_)); 783 } 784 printer->Print( 785 "protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n" 786 " internalGetFieldAccessorTable() {\n" 787 " return $fileclass$.internal_$identifier$_fieldAccessorTable\n" 788 " .ensureFieldAccessorsInitialized(\n" 789 " $classname$.class, $classname$.Builder.class);\n" 790 "}\n" 791 "\n", 792 "classname", ClassName(descriptor_), 793 "fileclass", ClassName(descriptor_->file()), 794 "identifier", UniqueFileScopeIdentifier(descriptor_)); 795 } 796 } 797 798 // =================================================================== 799 800 void MessageGenerator::GenerateCommonBuilderMethods(io::Printer* printer) { 801 printer->Print( 802 "// Construct using $classname$.newBuilder()\n" 803 "private Builder() {\n" 804 " maybeForceBuilderInitialization();\n" 805 "}\n" 806 "\n", 807 "classname", ClassName(descriptor_)); 808 809 if (HasDescriptorMethods(descriptor_)) { 810 printer->Print( 811 "private Builder(\n" 812 " com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n" 813 " super(parent);\n" 814 " maybeForceBuilderInitialization();\n" 815 "}\n", 816 "classname", ClassName(descriptor_)); 817 } 818 819 820 if (HasNestedBuilders(descriptor_)) { 821 printer->Print( 822 "private void maybeForceBuilderInitialization() {\n" 823 " if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n"); 824 825 printer->Indent(); 826 printer->Indent(); 827 for (int i = 0; i < descriptor_->field_count(); i++) { 828 field_generators_.get(descriptor_->field(i)) 829 .GenerateFieldBuilderInitializationCode(printer); 830 } 831 printer->Outdent(); 832 printer->Outdent(); 833 834 printer->Print( 835 " }\n" 836 "}\n"); 837 } else { 838 printer->Print( 839 "private void maybeForceBuilderInitialization() {\n" 840 "}\n"); 841 } 842 843 printer->Print( 844 "private static Builder create() {\n" 845 " return new Builder();\n" 846 "}\n" 847 "\n" 848 "public Builder clear() {\n" 849 " super.clear();\n", 850 "classname", ClassName(descriptor_)); 851 852 printer->Indent(); 853 854 for (int i = 0; i < descriptor_->field_count(); i++) { 855 field_generators_.get(descriptor_->field(i)) 856 .GenerateBuilderClearCode(printer); 857 } 858 859 printer->Outdent(); 860 861 printer->Print( 862 " return this;\n" 863 "}\n" 864 "\n" 865 "public Builder clone() {\n" 866 " return create().mergeFrom(buildPartial());\n" 867 "}\n" 868 "\n", 869 "classname", ClassName(descriptor_)); 870 if (HasDescriptorMethods(descriptor_)) { 871 printer->Print( 872 "public com.google.protobuf.Descriptors.Descriptor\n" 873 " getDescriptorForType() {\n" 874 " return $fileclass$.internal_$identifier$_descriptor;\n" 875 "}\n" 876 "\n", 877 "fileclass", ClassName(descriptor_->file()), 878 "identifier", UniqueFileScopeIdentifier(descriptor_)); 879 } 880 printer->Print( 881 "public $classname$ getDefaultInstanceForType() {\n" 882 " return $classname$.getDefaultInstance();\n" 883 "}\n" 884 "\n", 885 "classname", ClassName(descriptor_)); 886 887 // ----------------------------------------------------------------- 888 889 printer->Print( 890 "public $classname$ build() {\n" 891 " $classname$ result = buildPartial();\n" 892 " if (!result.isInitialized()) {\n" 893 " throw newUninitializedMessageException(result);\n" 894 " }\n" 895 " return result;\n" 896 "}\n" 897 "\n" 898 "public $classname$ buildPartial() {\n" 899 " $classname$ result = new $classname$(this);\n", 900 "classname", ClassName(descriptor_)); 901 902 printer->Indent(); 903 904 // Local vars for from and to bit fields to avoid accessing the builder and 905 // message over and over for these fields. Seems to provide a slight 906 // perforamance improvement in micro benchmark and this is also what proto1 907 // code does. 908 int totalBuilderBits = 0; 909 int totalMessageBits = 0; 910 for (int i = 0; i < descriptor_->field_count(); i++) { 911 const FieldGenerator& field = field_generators_.get(descriptor_->field(i)); 912 totalBuilderBits += field.GetNumBitsForBuilder(); 913 totalMessageBits += field.GetNumBitsForMessage(); 914 } 915 int totalBuilderInts = (totalBuilderBits + 31) / 32; 916 int totalMessageInts = (totalMessageBits + 31) / 32; 917 for (int i = 0; i < totalBuilderInts; i++) { 918 printer->Print("int from_$bit_field_name$ = $bit_field_name$;\n", 919 "bit_field_name", GetBitFieldName(i)); 920 } 921 for (int i = 0; i < totalMessageInts; i++) { 922 printer->Print("int to_$bit_field_name$ = 0;\n", 923 "bit_field_name", GetBitFieldName(i)); 924 } 925 926 // Output generation code for each field. 927 for (int i = 0; i < descriptor_->field_count(); i++) { 928 field_generators_.get(descriptor_->field(i)).GenerateBuildingCode(printer); 929 } 930 931 // Copy the bit field results to the generated message 932 for (int i = 0; i < totalMessageInts; i++) { 933 printer->Print("result.$bit_field_name$ = to_$bit_field_name$;\n", 934 "bit_field_name", GetBitFieldName(i)); 935 } 936 937 printer->Outdent(); 938 939 if (HasDescriptorMethods(descriptor_)) { 940 printer->Print( 941 " onBuilt();\n"); 942 } 943 944 printer->Print( 945 " return result;\n" 946 "}\n" 947 "\n", 948 "classname", ClassName(descriptor_)); 949 950 // ----------------------------------------------------------------- 951 952 if (HasGeneratedMethods(descriptor_)) { 953 // MergeFrom(Message other) requires the ability to distinguish the other 954 // messages type by its descriptor. 955 if (HasDescriptorMethods(descriptor_)) { 956 printer->Print( 957 "public Builder mergeFrom(com.google.protobuf.Message other) {\n" 958 " if (other instanceof $classname$) {\n" 959 " return mergeFrom(($classname$)other);\n" 960 " } else {\n" 961 " super.mergeFrom(other);\n" 962 " return this;\n" 963 " }\n" 964 "}\n" 965 "\n", 966 "classname", ClassName(descriptor_)); 967 } 968 969 printer->Print( 970 "public Builder mergeFrom($classname$ other) {\n" 971 // Optimization: If other is the default instance, we know none of its 972 // fields are set so we can skip the merge. 973 " if (other == $classname$.getDefaultInstance()) return this;\n", 974 "classname", ClassName(descriptor_)); 975 printer->Indent(); 976 977 for (int i = 0; i < descriptor_->field_count(); i++) { 978 field_generators_.get(descriptor_->field(i)).GenerateMergingCode(printer); 979 } 980 981 printer->Outdent(); 982 983 // if message type has extensions 984 if (descriptor_->extension_range_count() > 0) { 985 printer->Print( 986 " this.mergeExtensionFields(other);\n"); 987 } 988 989 if (HasUnknownFields(descriptor_)) { 990 printer->Print( 991 " this.mergeUnknownFields(other.getUnknownFields());\n"); 992 } 993 994 printer->Print( 995 " return this;\n" 996 "}\n" 997 "\n"); 998 } 999 } 1000 1001 // =================================================================== 1002 1003 void MessageGenerator::GenerateBuilderParsingMethods(io::Printer* printer) { 1004 printer->Print( 1005 "public Builder mergeFrom(\n" 1006 " com.google.protobuf.CodedInputStream input,\n" 1007 " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" 1008 " throws java.io.IOException {\n" 1009 " $classname$ parsedMessage = null;\n" 1010 " try {\n" 1011 " parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n" 1012 " } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" 1013 " parsedMessage = ($classname$) e.getUnfinishedMessage();\n" 1014 " throw e;\n" 1015 " } finally {\n" 1016 " if (parsedMessage != null) {\n" 1017 " mergeFrom(parsedMessage);\n" 1018 " }\n" 1019 " }\n" 1020 " return this;\n" 1021 "}\n", 1022 "classname", ClassName(descriptor_)); 1023 } 1024 1025 // =================================================================== 1026 1027 void MessageGenerator::GenerateIsInitialized( 1028 io::Printer* printer, UseMemoization useMemoization) { 1029 bool memoization = useMemoization == MEMOIZE; 1030 if (memoization) { 1031 // Memoizes whether the protocol buffer is fully initialized (has all 1032 // required fields). -1 means not yet computed. 0 means false and 1 means 1033 // true. 1034 printer->Print( 1035 "private byte memoizedIsInitialized = -1;\n"); 1036 } 1037 printer->Print( 1038 "public final boolean isInitialized() {\n"); 1039 printer->Indent(); 1040 1041 if (memoization) { 1042 printer->Print( 1043 "byte isInitialized = memoizedIsInitialized;\n" 1044 "if (isInitialized != -1) return isInitialized == 1;\n" 1045 "\n"); 1046 } 1047 1048 // Check that all required fields in this message are set. 1049 // TODO(kenton): We can optimize this when we switch to putting all the 1050 // "has" fields into a single bitfield. 1051 for (int i = 0; i < descriptor_->field_count(); i++) { 1052 const FieldDescriptor* field = descriptor_->field(i); 1053 1054 if (field->is_required()) { 1055 printer->Print( 1056 "if (!has$name$()) {\n" 1057 " $memoize$\n" 1058 " return false;\n" 1059 "}\n", 1060 "name", UnderscoresToCapitalizedCamelCase(field), 1061 "memoize", memoization ? "memoizedIsInitialized = 0;" : ""); 1062 } 1063 } 1064 1065 // Now check that all embedded messages are initialized. 1066 for (int i = 0; i < descriptor_->field_count(); i++) { 1067 const FieldDescriptor* field = descriptor_->field(i); 1068 if (GetJavaType(field) == JAVATYPE_MESSAGE && 1069 HasRequiredFields(field->message_type())) { 1070 switch (field->label()) { 1071 case FieldDescriptor::LABEL_REQUIRED: 1072 printer->Print( 1073 "if (!get$name$().isInitialized()) {\n" 1074 " $memoize$\n" 1075 " return false;\n" 1076 "}\n", 1077 "type", ClassName(field->message_type()), 1078 "name", UnderscoresToCapitalizedCamelCase(field), 1079 "memoize", memoization ? "memoizedIsInitialized = 0;" : ""); 1080 break; 1081 case FieldDescriptor::LABEL_OPTIONAL: 1082 printer->Print( 1083 "if (has$name$()) {\n" 1084 " if (!get$name$().isInitialized()) {\n" 1085 " $memoize$\n" 1086 " return false;\n" 1087 " }\n" 1088 "}\n", 1089 "type", ClassName(field->message_type()), 1090 "name", UnderscoresToCapitalizedCamelCase(field), 1091 "memoize", memoization ? "memoizedIsInitialized = 0;" : ""); 1092 break; 1093 case FieldDescriptor::LABEL_REPEATED: 1094 printer->Print( 1095 "for (int i = 0; i < get$name$Count(); i++) {\n" 1096 " if (!get$name$(i).isInitialized()) {\n" 1097 " $memoize$\n" 1098 " return false;\n" 1099 " }\n" 1100 "}\n", 1101 "type", ClassName(field->message_type()), 1102 "name", UnderscoresToCapitalizedCamelCase(field), 1103 "memoize", memoization ? "memoizedIsInitialized = 0;" : ""); 1104 break; 1105 } 1106 } 1107 } 1108 1109 if (descriptor_->extension_range_count() > 0) { 1110 printer->Print( 1111 "if (!extensionsAreInitialized()) {\n" 1112 " $memoize$\n" 1113 " return false;\n" 1114 "}\n", 1115 "memoize", memoization ? "memoizedIsInitialized = 0;" : ""); 1116 } 1117 1118 printer->Outdent(); 1119 1120 if (memoization) { 1121 printer->Print( 1122 " memoizedIsInitialized = 1;\n"); 1123 } 1124 1125 printer->Print( 1126 " return true;\n" 1127 "}\n" 1128 "\n"); 1129 } 1130 1131 // =================================================================== 1132 1133 void MessageGenerator::GenerateEqualsAndHashCode(io::Printer* printer) { 1134 printer->Print( 1135 "@java.lang.Override\n" 1136 "public boolean equals(final java.lang.Object obj) {\n"); 1137 printer->Indent(); 1138 printer->Print( 1139 "if (obj == this) {\n" 1140 " return true;\n" 1141 "}\n" 1142 "if (!(obj instanceof $classname$)) {\n" 1143 " return super.equals(obj);\n" 1144 "}\n" 1145 "$classname$ other = ($classname$) obj;\n" 1146 "\n", 1147 "classname", ClassName(descriptor_)); 1148 1149 printer->Print("boolean result = true;\n"); 1150 for (int i = 0; i < descriptor_->field_count(); i++) { 1151 const FieldDescriptor* field = descriptor_->field(i); 1152 if (!field->is_repeated()) { 1153 printer->Print( 1154 "result = result && (has$name$() == other.has$name$());\n" 1155 "if (has$name$()) {\n", 1156 "name", UnderscoresToCapitalizedCamelCase(field)); 1157 printer->Indent(); 1158 } 1159 field_generators_.get(field).GenerateEqualsCode(printer); 1160 if (!field->is_repeated()) { 1161 printer->Outdent(); 1162 printer->Print( 1163 "}\n"); 1164 } 1165 } 1166 if (HasDescriptorMethods(descriptor_)) { 1167 printer->Print( 1168 "result = result &&\n" 1169 " getUnknownFields().equals(other.getUnknownFields());\n"); 1170 if (descriptor_->extension_range_count() > 0) { 1171 printer->Print( 1172 "result = result &&\n" 1173 " getExtensionFields().equals(other.getExtensionFields());\n"); 1174 } 1175 } 1176 printer->Print( 1177 "return result;\n"); 1178 printer->Outdent(); 1179 printer->Print( 1180 "}\n" 1181 "\n"); 1182 1183 printer->Print( 1184 "private int memoizedHashCode = 0;\n"); 1185 printer->Print( 1186 "@java.lang.Override\n" 1187 "public int hashCode() {\n"); 1188 printer->Indent(); 1189 printer->Print( 1190 "if (memoizedHashCode != 0) {\n"); 1191 printer->Indent(); 1192 printer->Print( 1193 "return memoizedHashCode;\n"); 1194 printer->Outdent(); 1195 printer->Print( 1196 "}\n" 1197 "int hash = 41;\n" 1198 "hash = (19 * hash) + getDescriptorForType().hashCode();\n"); 1199 for (int i = 0; i < descriptor_->field_count(); i++) { 1200 const FieldDescriptor* field = descriptor_->field(i); 1201 if (!field->is_repeated()) { 1202 printer->Print( 1203 "if (has$name$()) {\n", 1204 "name", UnderscoresToCapitalizedCamelCase(field)); 1205 printer->Indent(); 1206 } 1207 field_generators_.get(field).GenerateHashCode(printer); 1208 if (!field->is_repeated()) { 1209 printer->Outdent(); 1210 printer->Print("}\n"); 1211 } 1212 } 1213 if (HasDescriptorMethods(descriptor_)) { 1214 if (descriptor_->extension_range_count() > 0) { 1215 printer->Print( 1216 "hash = hashFields(hash, getExtensionFields());\n"); 1217 } 1218 } 1219 printer->Print( 1220 "hash = (29 * hash) + getUnknownFields().hashCode();\n" 1221 "memoizedHashCode = hash;\n" 1222 "return hash;\n"); 1223 printer->Outdent(); 1224 printer->Print( 1225 "}\n" 1226 "\n"); 1227 } 1228 1229 // =================================================================== 1230 1231 void MessageGenerator::GenerateExtensionRegistrationCode(io::Printer* printer) { 1232 for (int i = 0; i < descriptor_->extension_count(); i++) { 1233 ExtensionGenerator(descriptor_->extension(i)) 1234 .GenerateRegistrationCode(printer); 1235 } 1236 1237 for (int i = 0; i < descriptor_->nested_type_count(); i++) { 1238 MessageGenerator(descriptor_->nested_type(i)) 1239 .GenerateExtensionRegistrationCode(printer); 1240 } 1241 } 1242 1243 // =================================================================== 1244 void MessageGenerator::GenerateParsingConstructor(io::Printer* printer) { 1245 scoped_array<const FieldDescriptor*> sorted_fields( 1246 SortFieldsByNumber(descriptor_)); 1247 1248 printer->Print( 1249 "private $classname$(\n" 1250 " com.google.protobuf.CodedInputStream input,\n" 1251 " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" 1252 " throws com.google.protobuf.InvalidProtocolBufferException {\n", 1253 "classname", descriptor_->name()); 1254 printer->Indent(); 1255 1256 // Initialize all fields to default. 1257 printer->Print( 1258 "initFields();\n"); 1259 1260 // Use builder bits to track mutable repeated fields. 1261 int totalBuilderBits = 0; 1262 for (int i = 0; i < descriptor_->field_count(); i++) { 1263 const FieldGenerator& field = field_generators_.get(descriptor_->field(i)); 1264 totalBuilderBits += field.GetNumBitsForBuilder(); 1265 } 1266 int totalBuilderInts = (totalBuilderBits + 31) / 32; 1267 for (int i = 0; i < totalBuilderInts; i++) { 1268 printer->Print("int mutable_$bit_field_name$ = 0;\n", 1269 "bit_field_name", GetBitFieldName(i)); 1270 } 1271 1272 if (HasUnknownFields(descriptor_)) { 1273 printer->Print( 1274 "com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n" 1275 " com.google.protobuf.UnknownFieldSet.newBuilder();\n"); 1276 } 1277 1278 printer->Print( 1279 "try {\n"); 1280 printer->Indent(); 1281 1282 printer->Print( 1283 "boolean done = false;\n" 1284 "while (!done) {\n"); 1285 printer->Indent(); 1286 1287 printer->Print( 1288 "int tag = input.readTag();\n" 1289 "switch (tag) {\n"); 1290 printer->Indent(); 1291 1292 printer->Print( 1293 "case 0:\n" // zero signals EOF / limit reached 1294 " done = true;\n" 1295 " break;\n" 1296 "default: {\n" 1297 " if (!parseUnknownField(input,$unknown_fields$\n" 1298 " extensionRegistry, tag)) {\n" 1299 " done = true;\n" // it's an endgroup tag 1300 " }\n" 1301 " break;\n" 1302 "}\n", 1303 "unknown_fields", HasUnknownFields(descriptor_) 1304 ? " unknownFields," : ""); 1305 1306 for (int i = 0; i < descriptor_->field_count(); i++) { 1307 const FieldDescriptor* field = sorted_fields[i]; 1308 uint32 tag = WireFormatLite::MakeTag(field->number(), 1309 WireFormat::WireTypeForFieldType(field->type())); 1310 1311 printer->Print( 1312 "case $tag$: {\n", 1313 "tag", SimpleItoa(tag)); 1314 printer->Indent(); 1315 1316 field_generators_.get(field).GenerateParsingCode(printer); 1317 1318 printer->Outdent(); 1319 printer->Print( 1320 " break;\n" 1321 "}\n"); 1322 1323 if (field->is_packable()) { 1324 // To make packed = true wire compatible, we generate parsing code from a 1325 // packed version of this field regardless of field->options().packed(). 1326 uint32 packed_tag = WireFormatLite::MakeTag(field->number(), 1327 WireFormatLite::WIRETYPE_LENGTH_DELIMITED); 1328 printer->Print( 1329 "case $tag$: {\n", 1330 "tag", SimpleItoa(packed_tag)); 1331 printer->Indent(); 1332 1333 field_generators_.get(field).GenerateParsingCodeFromPacked(printer); 1334 1335 printer->Outdent(); 1336 printer->Print( 1337 " break;\n" 1338 "}\n"); 1339 } 1340 } 1341 1342 printer->Outdent(); 1343 printer->Outdent(); 1344 printer->Print( 1345 " }\n" // switch (tag) 1346 "}\n"); // while (!done) 1347 1348 printer->Outdent(); 1349 printer->Print( 1350 "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" 1351 " throw e.setUnfinishedMessage(this);\n" 1352 "} catch (java.io.IOException e) {\n" 1353 " throw new com.google.protobuf.InvalidProtocolBufferException(\n" 1354 " e.getMessage()).setUnfinishedMessage(this);\n" 1355 "} finally {\n"); 1356 printer->Indent(); 1357 1358 // Make repeated field list immutable. 1359 for (int i = 0; i < descriptor_->field_count(); i++) { 1360 const FieldDescriptor* field = sorted_fields[i]; 1361 field_generators_.get(field).GenerateParsingDoneCode(printer); 1362 } 1363 1364 // Make unknown fields immutable. 1365 if (HasUnknownFields(descriptor_)) { 1366 printer->Print( 1367 "this.unknownFields = unknownFields.build();\n"); 1368 } 1369 1370 // Make extensions immutable. 1371 printer->Print( 1372 "makeExtensionsImmutable();\n"); 1373 1374 printer->Outdent(); 1375 printer->Outdent(); 1376 printer->Print( 1377 " }\n" // finally 1378 "}\n"); 1379 } 1380 1381 // =================================================================== 1382 void MessageGenerator::GenerateParser(io::Printer* printer) { 1383 printer->Print( 1384 "public static com.google.protobuf.Parser<$classname$> PARSER =\n" 1385 " new com.google.protobuf.AbstractParser<$classname$>() {\n", 1386 "classname", descriptor_->name()); 1387 printer->Indent(); 1388 printer->Print( 1389 "public $classname$ parsePartialFrom(\n" 1390 " com.google.protobuf.CodedInputStream input,\n" 1391 " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n" 1392 " throws com.google.protobuf.InvalidProtocolBufferException {\n", 1393 "classname", descriptor_->name()); 1394 if (HasGeneratedMethods(descriptor_)) { 1395 printer->Print( 1396 " return new $classname$(input, extensionRegistry);\n", 1397 "classname", descriptor_->name()); 1398 } else { 1399 // When parsing constructor isn't generated, use builder to parse messages. 1400 // Note, will fallback to use reflection based mergeFieldFrom() in 1401 // AbstractMessage.Builder. 1402 printer->Indent(); 1403 printer->Print( 1404 "Builder builder = newBuilder();\n" 1405 "try {\n" 1406 " builder.mergeFrom(input, extensionRegistry);\n" 1407 "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n" 1408 " throw e.setUnfinishedMessage(builder.buildPartial());\n" 1409 "} catch (java.io.IOException e) {\n" 1410 " throw new com.google.protobuf.InvalidProtocolBufferException(\n" 1411 " e.getMessage()).setUnfinishedMessage(builder.buildPartial());\n" 1412 "}\n" 1413 "return builder.buildPartial();\n"); 1414 printer->Outdent(); 1415 } 1416 printer->Print( 1417 "}\n"); 1418 printer->Outdent(); 1419 printer->Print( 1420 "};\n" 1421 "\n"); 1422 1423 printer->Print( 1424 "@java.lang.Override\n" 1425 "public com.google.protobuf.Parser<$classname$> getParserForType() {\n" 1426 " return PARSER;\n" 1427 "}\n" 1428 "\n", 1429 "classname", descriptor_->name()); 1430 } 1431 1432 } // namespace java 1433 } // namespace compiler 1434 } // namespace protobuf 1435 } // namespace google 1436