PageRenderTime 72ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/src/google/protobuf/compiler/java/java_message.cc

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