java_message.cc 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // 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 <memory>
  38. #include <vector>
  39. #include <google/protobuf/compiler/java/java_context.h>
  40. #include <google/protobuf/compiler/java/java_doc_comment.h>
  41. #include <google/protobuf/compiler/java/java_enum.h>
  42. #include <google/protobuf/compiler/java/java_extension.h>
  43. #include <google/protobuf/compiler/java/java_generator_factory.h>
  44. #include <google/protobuf/compiler/java/java_helpers.h>
  45. #include <google/protobuf/compiler/java/java_message_builder.h>
  46. #include <google/protobuf/compiler/java/java_message_builder_lite.h>
  47. #include <google/protobuf/compiler/java/java_name_resolver.h>
  48. #include <google/protobuf/descriptor.pb.h>
  49. #include <google/protobuf/io/coded_stream.h>
  50. #include <google/protobuf/io/printer.h>
  51. #include <google/protobuf/wire_format.h>
  52. #include <google/protobuf/stubs/substitute.h>
  53. #include <google/protobuf/stubs/strutil.h>
  54. namespace google {
  55. namespace protobuf {
  56. namespace compiler {
  57. namespace java {
  58. using internal::WireFormat;
  59. using internal::WireFormatLite;
  60. namespace {
  61. bool GenerateHasBits(const Descriptor* descriptor) {
  62. return SupportFieldPresence(descriptor->file()) ||
  63. HasRepeatedFields(descriptor);
  64. }
  65. string MapValueImmutableClassdName(const Descriptor* descriptor,
  66. ClassNameResolver* name_resolver) {
  67. const FieldDescriptor* value_field = descriptor->FindFieldByName("value");
  68. GOOGLE_CHECK_EQ(FieldDescriptor::TYPE_MESSAGE, value_field->type());
  69. return name_resolver->GetImmutableClassName(value_field->message_type());
  70. }
  71. } // namespace
  72. // ===================================================================
  73. MessageGenerator::MessageGenerator(const Descriptor* descriptor)
  74. : descriptor_(descriptor) {}
  75. MessageGenerator::~MessageGenerator() {}
  76. // ===================================================================
  77. ImmutableMessageGenerator::ImmutableMessageGenerator(
  78. const Descriptor* descriptor, Context* context)
  79. : MessageGenerator(descriptor), context_(context),
  80. name_resolver_(context->GetNameResolver()),
  81. field_generators_(descriptor, context_) {
  82. GOOGLE_CHECK(HasDescriptorMethods(descriptor->file(), context->EnforceLite()))
  83. << "Generator factory error: A non-lite message generator is used to "
  84. "generate lite messages.";
  85. }
  86. ImmutableMessageGenerator::~ImmutableMessageGenerator() {}
  87. void ImmutableMessageGenerator::GenerateStaticVariables(
  88. io::Printer* printer, int* bytecode_estimate) {
  89. // Because descriptor.proto (com.google.protobuf.DescriptorProtos) is
  90. // used in the construction of descriptors, we have a tricky bootstrapping
  91. // problem. To help control static initialization order, we make sure all
  92. // descriptors and other static data that depends on them are members of
  93. // the outermost class in the file. This way, they will be initialized in
  94. // a deterministic order.
  95. std::map<string, string> vars;
  96. vars["identifier"] = UniqueFileScopeIdentifier(descriptor_);
  97. vars["index"] = SimpleItoa(descriptor_->index());
  98. vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_);
  99. if (descriptor_->containing_type() != NULL) {
  100. vars["parent"] = UniqueFileScopeIdentifier(
  101. descriptor_->containing_type());
  102. }
  103. if (MultipleJavaFiles(descriptor_->file(), /* immutable = */ true)) {
  104. // We can only make these package-private since the classes that use them
  105. // are in separate files.
  106. vars["private"] = "";
  107. } else {
  108. vars["private"] = "private ";
  109. }
  110. if (*bytecode_estimate <= kMaxStaticSize) {
  111. vars["final"] = "final ";
  112. } else {
  113. vars["final"] = "";
  114. }
  115. // The descriptor for this type.
  116. printer->Print(vars,
  117. // TODO(teboring): final needs to be added back. The way to fix it is to
  118. // generate methods that can construct the types, and then still declare the
  119. // types, and then init them in clinit with the new method calls.
  120. "$private$static $final$com.google.protobuf.Descriptors.Descriptor\n"
  121. " internal_$identifier$_descriptor;\n");
  122. *bytecode_estimate += 30;
  123. // And the FieldAccessorTable.
  124. GenerateFieldAccessorTable(printer, bytecode_estimate);
  125. // Generate static members for all nested types.
  126. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  127. // TODO(kenton): Reuse MessageGenerator objects?
  128. ImmutableMessageGenerator(descriptor_->nested_type(i), context_)
  129. .GenerateStaticVariables(printer, bytecode_estimate);
  130. }
  131. }
  132. int ImmutableMessageGenerator::GenerateStaticVariableInitializers(
  133. io::Printer* printer) {
  134. int bytecode_estimate = 0;
  135. std::map<string, string> vars;
  136. vars["identifier"] = UniqueFileScopeIdentifier(descriptor_);
  137. vars["index"] = SimpleItoa(descriptor_->index());
  138. vars["classname"] = name_resolver_->GetImmutableClassName(descriptor_);
  139. if (descriptor_->containing_type() != NULL) {
  140. vars["parent"] = UniqueFileScopeIdentifier(
  141. descriptor_->containing_type());
  142. }
  143. // The descriptor for this type.
  144. if (descriptor_->containing_type() == NULL) {
  145. printer->Print(vars,
  146. "internal_$identifier$_descriptor =\n"
  147. " getDescriptor().getMessageTypes().get($index$);\n");
  148. bytecode_estimate += 30;
  149. } else {
  150. printer->Print(vars,
  151. "internal_$identifier$_descriptor =\n"
  152. " internal_$parent$_descriptor.getNestedTypes().get($index$);\n");
  153. bytecode_estimate += 30;
  154. }
  155. // And the FieldAccessorTable.
  156. bytecode_estimate += GenerateFieldAccessorTableInitializer(printer);
  157. // Generate static member initializers for all nested types.
  158. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  159. // TODO(kenton): Reuse MessageGenerator objects?
  160. bytecode_estimate +=
  161. ImmutableMessageGenerator(descriptor_->nested_type(i), context_)
  162. .GenerateStaticVariableInitializers(printer);
  163. }
  164. return bytecode_estimate;
  165. }
  166. void ImmutableMessageGenerator::
  167. GenerateFieldAccessorTable(io::Printer* printer, int* bytecode_estimate) {
  168. std::map<string, string> vars;
  169. vars["identifier"] = UniqueFileScopeIdentifier(descriptor_);
  170. if (MultipleJavaFiles(descriptor_->file(), /* immutable = */ true)) {
  171. // We can only make these package-private since the classes that use them
  172. // are in separate files.
  173. vars["private"] = "";
  174. } else {
  175. vars["private"] = "private ";
  176. }
  177. if (*bytecode_estimate <= kMaxStaticSize) {
  178. vars["final"] = "final ";
  179. } else {
  180. vars["final"] = "";
  181. }
  182. vars["ver"] = GeneratedCodeVersionSuffix();
  183. printer->Print(vars,
  184. "$private$static $final$\n"
  185. " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n"
  186. " internal_$identifier$_fieldAccessorTable;\n");
  187. // 6 bytes per field and oneof
  188. *bytecode_estimate += 10 + 6 * descriptor_->field_count()
  189. + 6 * descriptor_->oneof_decl_count();
  190. }
  191. int ImmutableMessageGenerator::
  192. GenerateFieldAccessorTableInitializer(io::Printer* printer) {
  193. int bytecode_estimate = 10;
  194. printer->Print(
  195. "internal_$identifier$_fieldAccessorTable = new\n"
  196. " com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable(\n"
  197. " internal_$identifier$_descriptor,\n"
  198. " new java.lang.String[] { ",
  199. "identifier", UniqueFileScopeIdentifier(descriptor_),
  200. "ver", GeneratedCodeVersionSuffix());
  201. for (int i = 0; i < descriptor_->field_count(); i++) {
  202. const FieldDescriptor* field = descriptor_->field(i);
  203. const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
  204. bytecode_estimate += 6;
  205. printer->Print(
  206. "\"$field_name$\", ",
  207. "field_name", info->capitalized_name);
  208. }
  209. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  210. const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
  211. const OneofGeneratorInfo* info = context_->GetOneofGeneratorInfo(oneof);
  212. bytecode_estimate += 6;
  213. printer->Print(
  214. "\"$oneof_name$\", ",
  215. "oneof_name", info->capitalized_name);
  216. }
  217. printer->Print("});\n");
  218. return bytecode_estimate;
  219. }
  220. // ===================================================================
  221. void ImmutableMessageGenerator::GenerateInterface(io::Printer* printer) {
  222. MaybePrintGeneratedAnnotation(context_, printer, descriptor_,
  223. /* immutable = */ true, "OrBuilder");
  224. if (descriptor_->extension_range_count() > 0) {
  225. printer->Print(
  226. "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n"
  227. " $extra_interfaces$\n"
  228. " com.google.protobuf.GeneratedMessage$ver$.\n"
  229. " ExtendableMessageOrBuilder<$classname$> {\n",
  230. "deprecation", descriptor_->options().deprecated() ?
  231. "@java.lang.Deprecated " : "",
  232. "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
  233. "classname", descriptor_->name(),
  234. "{", "", "}", "", "ver", GeneratedCodeVersionSuffix());
  235. } else {
  236. printer->Print(
  237. "$deprecation$public interface ${$$classname$OrBuilder$}$ extends\n"
  238. " $extra_interfaces$\n"
  239. " com.google.protobuf.MessageOrBuilder {\n",
  240. "deprecation", descriptor_->options().deprecated() ?
  241. "@java.lang.Deprecated " : "",
  242. "extra_interfaces", ExtraMessageOrBuilderInterfaces(descriptor_),
  243. "classname", descriptor_->name(),
  244. "{", "", "}", "");
  245. }
  246. printer->Annotate("{", "}", descriptor_);
  247. printer->Indent();
  248. for (int i = 0; i < descriptor_->field_count(); i++) {
  249. printer->Print("\n");
  250. field_generators_.get(descriptor_->field(i))
  251. .GenerateInterfaceMembers(printer);
  252. }
  253. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  254. printer->Print(
  255. "\n"
  256. "public $classname$.$oneof_capitalized_name$Case "
  257. "get$oneof_capitalized_name$Case();\n",
  258. "oneof_capitalized_name",
  259. context_->GetOneofGeneratorInfo(
  260. descriptor_->oneof_decl(i))->capitalized_name,
  261. "classname",
  262. context_->GetNameResolver()->GetImmutableClassName(
  263. descriptor_));
  264. }
  265. printer->Outdent();
  266. printer->Print("}\n");
  267. }
  268. // ===================================================================
  269. void ImmutableMessageGenerator::Generate(io::Printer* printer) {
  270. bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true);
  271. std::map<string, string> variables;
  272. variables["static"] = is_own_file ? " " : " static ";
  273. variables["classname"] = descriptor_->name();
  274. variables["extra_interfaces"] = ExtraMessageInterfaces(descriptor_);
  275. variables["ver"] = GeneratedCodeVersionSuffix();
  276. variables["deprecation"] = descriptor_->options().deprecated()
  277. ? "@java.lang.Deprecated " : "";
  278. WriteMessageDocComment(printer, descriptor_);
  279. MaybePrintGeneratedAnnotation(context_, printer, descriptor_,
  280. /* immutable = */ true);
  281. // The builder_type stores the super type name of the nested Builder class.
  282. string builder_type;
  283. if (descriptor_->extension_range_count() > 0) {
  284. printer->Print(
  285. variables,
  286. "$deprecation$public $static$final class $classname$ extends\n");
  287. printer->Annotate("classname", descriptor_);
  288. printer->Print(
  289. variables,
  290. " com.google.protobuf.GeneratedMessage$ver$.ExtendableMessage<\n"
  291. " $classname$> implements\n"
  292. " $extra_interfaces$\n"
  293. " $classname$OrBuilder {\n");
  294. builder_type = strings::Substitute(
  295. "com.google.protobuf.GeneratedMessage$1.ExtendableBuilder<$0, ?>",
  296. name_resolver_->GetImmutableClassName(descriptor_),
  297. GeneratedCodeVersionSuffix());
  298. } else {
  299. printer->Print(
  300. variables,
  301. "$deprecation$public $static$final class $classname$ extends\n");
  302. printer->Annotate("classname", descriptor_);
  303. printer->Print(variables,
  304. " com.google.protobuf.GeneratedMessage$ver$ implements\n"
  305. " $extra_interfaces$\n"
  306. " $classname$OrBuilder {\n");
  307. builder_type = strings::Substitute(
  308. "com.google.protobuf.GeneratedMessage$0.Builder<?>",
  309. GeneratedCodeVersionSuffix());
  310. }
  311. printer->Print(
  312. "private static final long serialVersionUID = 0L;\n");
  313. printer->Indent();
  314. // Using builder_type, instead of Builder, prevents the Builder class from
  315. // being loaded into PermGen space when the default instance is created.
  316. // This optimizes the PermGen space usage for clients that do not modify
  317. // messages.
  318. printer->Print(
  319. "// Use $classname$.newBuilder() to construct.\n"
  320. "private $classname$($buildertype$ builder) {\n"
  321. " super(builder);\n"
  322. "}\n",
  323. "classname", descriptor_->name(),
  324. "buildertype", builder_type);
  325. printer->Print(
  326. "private $classname$() {\n",
  327. "classname", descriptor_->name());
  328. printer->Indent();
  329. GenerateInitializers(printer);
  330. printer->Outdent();
  331. printer->Print(
  332. "}\n"
  333. "\n");
  334. printer->Print(
  335. "@java.lang.Override\n"
  336. "public final com.google.protobuf.UnknownFieldSet\n"
  337. "getUnknownFields() {\n"
  338. " return this.unknownFields;\n"
  339. "}\n");
  340. if (context_->HasGeneratedMethods(descriptor_)) {
  341. if (!EnableExperimentalRuntime(context_) ||
  342. IsDescriptorProto(descriptor_)) {
  343. GenerateParsingConstructor(printer);
  344. }
  345. }
  346. GenerateDescriptorMethods(printer);
  347. // Nested types
  348. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  349. EnumGenerator(descriptor_->enum_type(i), true, context_)
  350. .Generate(printer);
  351. }
  352. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  353. // Don't generate Java classes for map entry messages.
  354. if (IsMapEntry(descriptor_->nested_type(i))) continue;
  355. ImmutableMessageGenerator messageGenerator(
  356. descriptor_->nested_type(i), context_);
  357. messageGenerator.GenerateInterface(printer);
  358. messageGenerator.Generate(printer);
  359. }
  360. if (GenerateHasBits(descriptor_)) {
  361. // Integers for bit fields.
  362. int totalBits = 0;
  363. for (int i = 0; i < descriptor_->field_count(); i++) {
  364. totalBits += field_generators_.get(descriptor_->field(i))
  365. .GetNumBitsForMessage();
  366. }
  367. int totalInts = (totalBits + 31) / 32;
  368. for (int i = 0; i < totalInts; i++) {
  369. printer->Print("private int $bit_field_name$;\n",
  370. "bit_field_name", GetBitFieldName(i));
  371. }
  372. }
  373. // oneof
  374. std::map<string, string> vars;
  375. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  376. vars["oneof_name"] = context_->GetOneofGeneratorInfo(
  377. descriptor_->oneof_decl(i))->name;
  378. vars["oneof_capitalized_name"] = context_->GetOneofGeneratorInfo(
  379. descriptor_->oneof_decl(i))->capitalized_name;
  380. vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
  381. // oneofCase_ and oneof_
  382. printer->Print(vars,
  383. "private int $oneof_name$Case_ = 0;\n"
  384. "private java.lang.Object $oneof_name$_;\n");
  385. // OneofCase enum
  386. printer->Print(vars,
  387. "public enum $oneof_capitalized_name$Case\n"
  388. " implements com.google.protobuf.Internal.EnumLite {\n");
  389. printer->Indent();
  390. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  391. const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
  392. printer->Print(
  393. "$deprecation$$field_name$($field_number$),\n",
  394. "deprecation",
  395. field->options().deprecated() ? "@java.lang.Deprecated " : "",
  396. "field_name", ToUpper(field->name()),
  397. "field_number", SimpleItoa(field->number()));
  398. }
  399. printer->Print(
  400. "$cap_oneof_name$_NOT_SET(0);\n",
  401. "cap_oneof_name",
  402. ToUpper(vars["oneof_name"]));
  403. printer->Print(vars,
  404. "private final int value;\n"
  405. "private $oneof_capitalized_name$Case(int value) {\n"
  406. " this.value = value;\n"
  407. "}\n");
  408. printer->Print(vars,
  409. "/**\n"
  410. " * @deprecated Use {@link #forNumber(int)} instead.\n"
  411. " */\n"
  412. "@java.lang.Deprecated\n"
  413. "public static $oneof_capitalized_name$Case valueOf(int value) {\n"
  414. " return forNumber(value);\n"
  415. "}\n"
  416. "\n"
  417. "public static $oneof_capitalized_name$Case forNumber(int value) {\n"
  418. " switch (value) {\n");
  419. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  420. const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
  421. printer->Print(
  422. " case $field_number$: return $field_name$;\n",
  423. "field_number",
  424. SimpleItoa(field->number()),
  425. "field_name",
  426. ToUpper(field->name()));
  427. }
  428. printer->Print(
  429. " case 0: return $cap_oneof_name$_NOT_SET;\n"
  430. " default: return null;\n"
  431. " }\n"
  432. "}\n"
  433. "public int getNumber() {\n"
  434. " return this.value;\n"
  435. "}\n",
  436. "cap_oneof_name", ToUpper(vars["oneof_name"]));
  437. printer->Outdent();
  438. printer->Print("};\n\n");
  439. // oneofCase()
  440. printer->Print(vars,
  441. "public $oneof_capitalized_name$Case\n"
  442. "get$oneof_capitalized_name$Case() {\n"
  443. " return $oneof_capitalized_name$Case.forNumber(\n"
  444. " $oneof_name$Case_);\n"
  445. "}\n"
  446. "\n");
  447. }
  448. if (IsAnyMessage(descriptor_)) {
  449. GenerateAnyMethods(printer);
  450. }
  451. // Fields
  452. for (int i = 0; i < descriptor_->field_count(); i++) {
  453. printer->Print("public static final int $constant_name$ = $number$;\n",
  454. "constant_name", FieldConstantName(descriptor_->field(i)),
  455. "number", SimpleItoa(descriptor_->field(i)->number()));
  456. field_generators_.get(descriptor_->field(i)).GenerateMembers(printer);
  457. printer->Print("\n");
  458. }
  459. if (context_->HasGeneratedMethods(descriptor_)) {
  460. GenerateIsInitialized(printer);
  461. GenerateMessageSerializationMethods(printer);
  462. GenerateEqualsAndHashCode(printer);
  463. }
  464. GenerateParseFromMethods(printer);
  465. GenerateBuilder(printer);
  466. printer->Print(
  467. "\n"
  468. "// @@protoc_insertion_point(class_scope:$full_name$)\n",
  469. "full_name", descriptor_->full_name());
  470. // Carefully initialize the default instance in such a way that it doesn't
  471. // conflict with other initialization.
  472. printer->Print(
  473. "private static final $classname$ DEFAULT_INSTANCE;\n",
  474. "classname", name_resolver_->GetImmutableClassName(descriptor_));
  475. printer->Print(
  476. "static {\n"
  477. " DEFAULT_INSTANCE = new $classname$();\n"
  478. "}\n"
  479. "\n",
  480. "classname", name_resolver_->GetImmutableClassName(descriptor_));
  481. printer->Print(
  482. "public static $classname$ getDefaultInstance() {\n"
  483. " return DEFAULT_INSTANCE;\n"
  484. "}\n"
  485. "\n",
  486. "classname", name_resolver_->GetImmutableClassName(descriptor_));
  487. // 'of' method for Wrappers
  488. if (IsWrappersProtoFile(descriptor_->file())) {
  489. printer->Print(
  490. "public static $classname$ of($field_type$ value) {\n"
  491. " return newBuilder().setValue(value).build();\n"
  492. "}\n"
  493. "\n",
  494. "classname", name_resolver_->GetImmutableClassName(descriptor_),
  495. "field_type", PrimitiveTypeName(GetJavaType(descriptor_->field(0))));
  496. }
  497. GenerateParser(printer);
  498. printer->Print(
  499. "@java.lang.Override\n"
  500. "public $classname$ getDefaultInstanceForType() {\n"
  501. " return DEFAULT_INSTANCE;\n"
  502. "}\n"
  503. "\n",
  504. "classname", name_resolver_->GetImmutableClassName(descriptor_));
  505. // Extensions must be declared after the DEFAULT_INSTANCE is initialized
  506. // because the DEFAULT_INSTANCE is used by the extension to lazily retrieve
  507. // the outer class's FileDescriptor.
  508. for (int i = 0; i < descriptor_->extension_count(); i++) {
  509. ImmutableExtensionGenerator(descriptor_->extension(i), context_)
  510. .Generate(printer);
  511. }
  512. printer->Outdent();
  513. printer->Print("}\n\n");
  514. }
  515. // ===================================================================
  516. void ImmutableMessageGenerator::
  517. GenerateMessageSerializationMethods(io::Printer* printer) {
  518. std::unique_ptr<const FieldDescriptor * []> sorted_fields(
  519. SortFieldsByNumber(descriptor_));
  520. std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
  521. for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
  522. sorted_extensions.push_back(descriptor_->extension_range(i));
  523. }
  524. std::sort(sorted_extensions.begin(), sorted_extensions.end(),
  525. ExtensionRangeOrdering());
  526. printer->Print(
  527. "@java.lang.Override\n"
  528. "public void writeTo(com.google.protobuf.CodedOutputStream output)\n"
  529. " throws java.io.IOException {\n");
  530. printer->Indent();
  531. if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
  532. printer->Print("writeToInternal(output);\n");
  533. } else {
  534. if (HasPackedFields(descriptor_)) {
  535. // writeTo(CodedOutputStream output) might be invoked without
  536. // getSerializedSize() ever being called, but we need the memoized
  537. // sizes in case this message has packed fields. Rather than emit checks
  538. // for each packed field, just call getSerializedSize() up front. In most
  539. // cases, getSerializedSize() will have already been called anyway by one
  540. // of the wrapper writeTo() methods, making this call cheap.
  541. printer->Print("getSerializedSize();\n");
  542. }
  543. if (descriptor_->extension_range_count() > 0) {
  544. if (descriptor_->options().message_set_wire_format()) {
  545. printer->Print(
  546. "com.google.protobuf.GeneratedMessage$ver$\n"
  547. " .ExtendableMessage<$classname$>.ExtensionWriter\n"
  548. " extensionWriter = newMessageSetExtensionWriter();\n",
  549. "classname", name_resolver_->GetImmutableClassName(descriptor_),
  550. "ver", GeneratedCodeVersionSuffix());
  551. } else {
  552. printer->Print(
  553. "com.google.protobuf.GeneratedMessage$ver$\n"
  554. " .ExtendableMessage<$classname$>.ExtensionWriter\n"
  555. " extensionWriter = newExtensionWriter();\n",
  556. "classname", name_resolver_->GetImmutableClassName(descriptor_),
  557. "ver", GeneratedCodeVersionSuffix());
  558. }
  559. }
  560. // Merge the fields and the extension ranges, both sorted by field number.
  561. for (int i = 0, j = 0;
  562. i < descriptor_->field_count() || j < sorted_extensions.size();) {
  563. if (i == descriptor_->field_count()) {
  564. GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
  565. } else if (j == sorted_extensions.size()) {
  566. GenerateSerializeOneField(printer, sorted_fields[i++]);
  567. } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) {
  568. GenerateSerializeOneField(printer, sorted_fields[i++]);
  569. } else {
  570. GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++]);
  571. }
  572. }
  573. if (descriptor_->options().message_set_wire_format()) {
  574. printer->Print("unknownFields.writeAsMessageSetTo(output);\n");
  575. } else {
  576. printer->Print("unknownFields.writeTo(output);\n");
  577. }
  578. }
  579. printer->Outdent();
  580. printer->Print(
  581. "}\n"
  582. "\n"
  583. "@java.lang.Override\n"
  584. "public int getSerializedSize() {\n"
  585. " int size = memoizedSize;\n"
  586. " if (size != -1) return size;\n"
  587. "\n");
  588. printer->Indent();
  589. if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
  590. printer->Print(
  591. "memoizedSize = getSerializedSizeInternal();\n"
  592. "return memoizedSize;\n");
  593. } else {
  594. printer->Print("size = 0;\n");
  595. for (int i = 0; i < descriptor_->field_count(); i++) {
  596. field_generators_.get(sorted_fields[i])
  597. .GenerateSerializedSizeCode(printer);
  598. }
  599. if (descriptor_->extension_range_count() > 0) {
  600. if (descriptor_->options().message_set_wire_format()) {
  601. printer->Print("size += extensionsSerializedSizeAsMessageSet();\n");
  602. } else {
  603. printer->Print("size += extensionsSerializedSize();\n");
  604. }
  605. }
  606. if (descriptor_->options().message_set_wire_format()) {
  607. printer->Print(
  608. "size += unknownFields.getSerializedSizeAsMessageSet();\n");
  609. } else {
  610. printer->Print("size += unknownFields.getSerializedSize();\n");
  611. }
  612. printer->Print(
  613. "memoizedSize = size;\n"
  614. "return size;\n");
  615. }
  616. printer->Outdent();
  617. printer->Print(
  618. "}\n"
  619. "\n");
  620. }
  621. void ImmutableMessageGenerator::
  622. GenerateParseFromMethods(io::Printer* printer) {
  623. // Note: These are separate from GenerateMessageSerializationMethods()
  624. // because they need to be generated even for messages that are optimized
  625. // for code size.
  626. printer->Print(
  627. "public static $classname$ parseFrom(\n"
  628. " java.nio.ByteBuffer data)\n"
  629. " throws com.google.protobuf.InvalidProtocolBufferException {\n"
  630. " return PARSER.parseFrom(data);\n"
  631. "}\n"
  632. "public static $classname$ parseFrom(\n"
  633. " java.nio.ByteBuffer data,\n"
  634. " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
  635. " throws com.google.protobuf.InvalidProtocolBufferException {\n"
  636. " return PARSER.parseFrom(data, extensionRegistry);\n"
  637. "}\n"
  638. "public static $classname$ parseFrom(\n"
  639. " com.google.protobuf.ByteString data)\n"
  640. " throws com.google.protobuf.InvalidProtocolBufferException {\n"
  641. " return PARSER.parseFrom(data);\n"
  642. "}\n"
  643. "public static $classname$ parseFrom(\n"
  644. " com.google.protobuf.ByteString data,\n"
  645. " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
  646. " throws com.google.protobuf.InvalidProtocolBufferException {\n"
  647. " return PARSER.parseFrom(data, extensionRegistry);\n"
  648. "}\n"
  649. "public static $classname$ parseFrom(byte[] data)\n"
  650. " throws com.google.protobuf.InvalidProtocolBufferException {\n"
  651. " return PARSER.parseFrom(data);\n"
  652. "}\n"
  653. "public static $classname$ parseFrom(\n"
  654. " byte[] data,\n"
  655. " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
  656. " throws com.google.protobuf.InvalidProtocolBufferException {\n"
  657. " return PARSER.parseFrom(data, extensionRegistry);\n"
  658. "}\n"
  659. "public static $classname$ parseFrom(java.io.InputStream input)\n"
  660. " throws java.io.IOException {\n"
  661. " return com.google.protobuf.GeneratedMessage$ver$\n"
  662. " .parseWithIOException(PARSER, input);\n"
  663. "}\n"
  664. "public static $classname$ parseFrom(\n"
  665. " java.io.InputStream input,\n"
  666. " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
  667. " throws java.io.IOException {\n"
  668. " return com.google.protobuf.GeneratedMessage$ver$\n"
  669. " .parseWithIOException(PARSER, input, extensionRegistry);\n"
  670. "}\n"
  671. "public static $classname$ parseDelimitedFrom(java.io.InputStream input)\n"
  672. " throws java.io.IOException {\n"
  673. " return com.google.protobuf.GeneratedMessage$ver$\n"
  674. " .parseDelimitedWithIOException(PARSER, input);\n"
  675. "}\n"
  676. "public static $classname$ parseDelimitedFrom(\n"
  677. " java.io.InputStream input,\n"
  678. " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
  679. " throws java.io.IOException {\n"
  680. " return com.google.protobuf.GeneratedMessage$ver$\n"
  681. " .parseDelimitedWithIOException(PARSER, input, extensionRegistry);\n"
  682. "}\n"
  683. "public static $classname$ parseFrom(\n"
  684. " com.google.protobuf.CodedInputStream input)\n"
  685. " throws java.io.IOException {\n"
  686. " return com.google.protobuf.GeneratedMessage$ver$\n"
  687. " .parseWithIOException(PARSER, input);\n"
  688. "}\n"
  689. "public static $classname$ parseFrom(\n"
  690. " com.google.protobuf.CodedInputStream input,\n"
  691. " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
  692. " throws java.io.IOException {\n"
  693. " return com.google.protobuf.GeneratedMessage$ver$\n"
  694. " .parseWithIOException(PARSER, input, extensionRegistry);\n"
  695. "}\n"
  696. "\n",
  697. "classname", name_resolver_->GetImmutableClassName(descriptor_),
  698. "ver", GeneratedCodeVersionSuffix());
  699. }
  700. void ImmutableMessageGenerator::GenerateSerializeOneField(
  701. io::Printer* printer, const FieldDescriptor* field) {
  702. field_generators_.get(field).GenerateSerializationCode(printer);
  703. }
  704. void ImmutableMessageGenerator::GenerateSerializeOneExtensionRange(
  705. io::Printer* printer, const Descriptor::ExtensionRange* range) {
  706. printer->Print(
  707. "extensionWriter.writeUntil($end$, output);\n",
  708. "end", SimpleItoa(range->end));
  709. }
  710. // ===================================================================
  711. void ImmutableMessageGenerator::GenerateBuilder(io::Printer* printer) {
  712. // LITE_RUNTIME implements this at the GeneratedMessageLite level.
  713. printer->Print(
  714. "@java.lang.Override\n"
  715. "public Builder newBuilderForType() { return newBuilder(); }\n");
  716. printer->Print(
  717. "public static Builder newBuilder() {\n"
  718. " return DEFAULT_INSTANCE.toBuilder();\n"
  719. "}\n"
  720. "public static Builder newBuilder($classname$ prototype) {\n"
  721. " return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);\n"
  722. "}\n"
  723. "@java.lang.Override\n"
  724. "public Builder toBuilder() {\n"
  725. " return this == DEFAULT_INSTANCE\n"
  726. " ? new Builder() : new Builder().mergeFrom(this);\n"
  727. "}\n"
  728. "\n",
  729. "classname", name_resolver_->GetImmutableClassName(descriptor_));
  730. printer->Print(
  731. "@java.lang.Override\n"
  732. "protected Builder newBuilderForType(\n"
  733. " com.google.protobuf.GeneratedMessage$ver$.BuilderParent parent) {\n"
  734. " Builder builder = new Builder(parent);\n"
  735. " return builder;\n"
  736. "}\n",
  737. "ver", GeneratedCodeVersionSuffix());
  738. MessageBuilderGenerator builderGenerator(descriptor_, context_);
  739. builderGenerator.Generate(printer);
  740. }
  741. void ImmutableMessageGenerator::
  742. GenerateDescriptorMethods(io::Printer* printer) {
  743. if (!descriptor_->options().no_standard_descriptor_accessor()) {
  744. printer->Print(
  745. "public static final com.google.protobuf.Descriptors.Descriptor\n"
  746. " getDescriptor() {\n"
  747. " return $fileclass$.internal_$identifier$_descriptor;\n"
  748. "}\n"
  749. "\n",
  750. "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()),
  751. "identifier", UniqueFileScopeIdentifier(descriptor_));
  752. }
  753. std::vector<const FieldDescriptor*> map_fields;
  754. for (int i = 0; i < descriptor_->field_count(); i++) {
  755. const FieldDescriptor* field = descriptor_->field(i);
  756. if (GetJavaType(field) == JAVATYPE_MESSAGE &&
  757. IsMapEntry(field->message_type())) {
  758. map_fields.push_back(field);
  759. }
  760. }
  761. if (!map_fields.empty()) {
  762. printer->Print(
  763. "@SuppressWarnings({\"rawtypes\"})\n"
  764. "@java.lang.Override\n"
  765. "protected com.google.protobuf.MapField internalGetMapField(\n"
  766. " int number) {\n"
  767. " switch (number) {\n");
  768. printer->Indent();
  769. printer->Indent();
  770. for (int i = 0; i < map_fields.size(); ++i) {
  771. const FieldDescriptor* field = map_fields[i];
  772. const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
  773. printer->Print(
  774. "case $number$:\n"
  775. " return internalGet$capitalized_name$();\n",
  776. "number", SimpleItoa(field->number()),
  777. "capitalized_name", info->capitalized_name);
  778. }
  779. printer->Print(
  780. "default:\n"
  781. " throw new RuntimeException(\n"
  782. " \"Invalid map field number: \" + number);\n");
  783. printer->Outdent();
  784. printer->Outdent();
  785. printer->Print(
  786. " }\n"
  787. "}\n");
  788. }
  789. printer->Print(
  790. "@java.lang.Override\n"
  791. "protected com.google.protobuf.GeneratedMessage$ver$.FieldAccessorTable\n"
  792. " internalGetFieldAccessorTable() {\n"
  793. " return $fileclass$.internal_$identifier$_fieldAccessorTable\n"
  794. " .ensureFieldAccessorsInitialized(\n"
  795. " $classname$.class, $classname$.Builder.class);\n"
  796. "}\n"
  797. "\n",
  798. "classname", name_resolver_->GetImmutableClassName(descriptor_),
  799. "fileclass", name_resolver_->GetImmutableClassName(descriptor_->file()),
  800. "identifier", UniqueFileScopeIdentifier(descriptor_),
  801. "ver", GeneratedCodeVersionSuffix());
  802. }
  803. // ===================================================================
  804. void ImmutableMessageGenerator::GenerateIsInitialized(
  805. io::Printer* printer) {
  806. // Memoizes whether the protocol buffer is fully initialized (has all
  807. // required fields). -1 means not yet computed. 0 means false and 1 means
  808. // true.
  809. printer->Print(
  810. "private byte memoizedIsInitialized = -1;\n");
  811. printer->Print(
  812. "@java.lang.Override\n"
  813. "public final boolean isInitialized() {\n");
  814. printer->Indent();
  815. // Don't directly compare to -1 to avoid an Android x86 JIT bug.
  816. printer->Print(
  817. "byte isInitialized = memoizedIsInitialized;\n"
  818. "if (isInitialized == 1) return true;\n"
  819. "if (isInitialized == 0) return false;\n"
  820. "\n");
  821. // Check that all required fields in this message are set.
  822. // TODO(kenton): We can optimize this when we switch to putting all the
  823. // "has" fields into a single bitfield.
  824. for (int i = 0; i < descriptor_->field_count(); i++) {
  825. const FieldDescriptor* field = descriptor_->field(i);
  826. const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
  827. if (field->is_required()) {
  828. printer->Print(
  829. "if (!has$name$()) {\n"
  830. " memoizedIsInitialized = 0;\n"
  831. " return false;\n"
  832. "}\n",
  833. "name", info->capitalized_name);
  834. }
  835. }
  836. // Now check that all embedded messages are initialized.
  837. for (int i = 0; i < descriptor_->field_count(); i++) {
  838. const FieldDescriptor* field = descriptor_->field(i);
  839. const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
  840. if (GetJavaType(field) == JAVATYPE_MESSAGE &&
  841. HasRequiredFields(field->message_type())) {
  842. switch (field->label()) {
  843. case FieldDescriptor::LABEL_REQUIRED:
  844. printer->Print(
  845. "if (!get$name$().isInitialized()) {\n"
  846. " memoizedIsInitialized = 0;\n"
  847. " return false;\n"
  848. "}\n",
  849. "type", name_resolver_->GetImmutableClassName(
  850. field->message_type()),
  851. "name", info->capitalized_name);
  852. break;
  853. case FieldDescriptor::LABEL_OPTIONAL:
  854. if (!SupportFieldPresence(descriptor_->file()) &&
  855. field->containing_oneof() != NULL) {
  856. const OneofDescriptor* oneof = field->containing_oneof();
  857. const OneofGeneratorInfo* oneof_info =
  858. context_->GetOneofGeneratorInfo(oneof);
  859. printer->Print(
  860. "if ($oneof_name$Case_ == $field_number$) {\n",
  861. "oneof_name", oneof_info->name,
  862. "field_number", SimpleItoa(field->number()));
  863. } else {
  864. printer->Print(
  865. "if (has$name$()) {\n",
  866. "name", info->capitalized_name);
  867. }
  868. printer->Print(
  869. " if (!get$name$().isInitialized()) {\n"
  870. " memoizedIsInitialized = 0;\n"
  871. " return false;\n"
  872. " }\n"
  873. "}\n",
  874. "name", info->capitalized_name);
  875. break;
  876. case FieldDescriptor::LABEL_REPEATED:
  877. if (IsMapEntry(field->message_type())) {
  878. printer->Print(
  879. "for ($type$ item : get$name$Map().values()) {\n"
  880. " if (!item.isInitialized()) {\n"
  881. " memoizedIsInitialized = 0;\n"
  882. " return false;\n"
  883. " }\n"
  884. "}\n",
  885. "type", MapValueImmutableClassdName(field->message_type(),
  886. name_resolver_),
  887. "name", info->capitalized_name);
  888. } else {
  889. printer->Print(
  890. "for (int i = 0; i < get$name$Count(); i++) {\n"
  891. " if (!get$name$(i).isInitialized()) {\n"
  892. " memoizedIsInitialized = 0;\n"
  893. " return false;\n"
  894. " }\n"
  895. "}\n",
  896. "type", name_resolver_->GetImmutableClassName(
  897. field->message_type()),
  898. "name", info->capitalized_name);
  899. }
  900. break;
  901. }
  902. }
  903. }
  904. if (descriptor_->extension_range_count() > 0) {
  905. printer->Print(
  906. "if (!extensionsAreInitialized()) {\n"
  907. " memoizedIsInitialized = 0;\n"
  908. " return false;\n"
  909. "}\n");
  910. }
  911. printer->Outdent();
  912. printer->Print(
  913. " memoizedIsInitialized = 1;\n");
  914. printer->Print(
  915. " return true;\n"
  916. "}\n"
  917. "\n");
  918. }
  919. // ===================================================================
  920. namespace {
  921. bool CheckHasBitsForEqualsAndHashCode(const FieldDescriptor* field) {
  922. if (field->is_repeated()) {
  923. return false;
  924. }
  925. if (SupportFieldPresence(field->file())) {
  926. return true;
  927. }
  928. return GetJavaType(field) == JAVATYPE_MESSAGE &&
  929. field->containing_oneof() == NULL;
  930. }
  931. } // namespace
  932. void ImmutableMessageGenerator::
  933. GenerateEqualsAndHashCode(io::Printer* printer) {
  934. printer->Print(
  935. "@java.lang.Override\n"
  936. "public boolean equals(final java.lang.Object obj) {\n");
  937. printer->Indent();
  938. printer->Print(
  939. "if (obj == this) {\n"
  940. " return true;\n"
  941. "}\n"
  942. "if (!(obj instanceof $classname$)) {\n"
  943. " return super.equals(obj);\n"
  944. "}\n"
  945. "$classname$ other = ($classname$) obj;\n"
  946. "\n",
  947. "classname", name_resolver_->GetImmutableClassName(descriptor_));
  948. printer->Print("boolean result = true;\n");
  949. for (int i = 0; i < descriptor_->field_count(); i++) {
  950. const FieldDescriptor* field = descriptor_->field(i);
  951. if (field->containing_oneof() == NULL) {
  952. const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
  953. bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field);
  954. if (check_has_bits) {
  955. printer->Print(
  956. "result = result && (has$name$() == other.has$name$());\n"
  957. "if (has$name$()) {\n",
  958. "name", info->capitalized_name);
  959. printer->Indent();
  960. }
  961. field_generators_.get(field).GenerateEqualsCode(printer);
  962. if (check_has_bits) {
  963. printer->Outdent();
  964. printer->Print(
  965. "}\n");
  966. }
  967. }
  968. }
  969. // Compare oneofs.
  970. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  971. printer->Print(
  972. "result = result && get$oneof_capitalized_name$Case().equals(\n"
  973. " other.get$oneof_capitalized_name$Case());\n",
  974. "oneof_capitalized_name",
  975. context_->GetOneofGeneratorInfo(
  976. descriptor_->oneof_decl(i))->capitalized_name);
  977. printer->Print(
  978. "if (!result) return false;\n"
  979. "switch ($oneof_name$Case_) {\n",
  980. "oneof_name",
  981. context_->GetOneofGeneratorInfo(
  982. descriptor_->oneof_decl(i))->name);
  983. printer->Indent();
  984. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  985. const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
  986. printer->Print(
  987. "case $field_number$:\n",
  988. "field_number",
  989. SimpleItoa(field->number()));
  990. printer->Indent();
  991. field_generators_.get(field).GenerateEqualsCode(printer);
  992. printer->Print("break;\n");
  993. printer->Outdent();
  994. }
  995. printer->Print(
  996. "case 0:\n"
  997. "default:\n");
  998. printer->Outdent();
  999. printer->Print("}\n");
  1000. }
  1001. // Always consider unknown fields for equality. This will sometimes return
  1002. // false for non-canonical ordering when running in LITE_RUNTIME but it's
  1003. // the best we can do.
  1004. printer->Print(
  1005. "result = result && unknownFields.equals(other.unknownFields);\n");
  1006. if (descriptor_->extension_range_count() > 0) {
  1007. printer->Print(
  1008. "result = result &&\n"
  1009. " getExtensionFields().equals(other.getExtensionFields());\n");
  1010. }
  1011. printer->Print(
  1012. "return result;\n");
  1013. printer->Outdent();
  1014. printer->Print(
  1015. "}\n"
  1016. "\n");
  1017. printer->Print(
  1018. "@java.lang.Override\n"
  1019. "public int hashCode() {\n");
  1020. printer->Indent();
  1021. printer->Print(
  1022. "if (memoizedHashCode != 0) {\n");
  1023. printer->Indent();
  1024. printer->Print(
  1025. "return memoizedHashCode;\n");
  1026. printer->Outdent();
  1027. printer->Print(
  1028. "}\n"
  1029. "int hash = 41;\n");
  1030. // If we output a getDescriptor() method, use that as it is more efficient.
  1031. if (descriptor_->options().no_standard_descriptor_accessor()) {
  1032. printer->Print("hash = (19 * hash) + getDescriptorForType().hashCode();\n");
  1033. } else {
  1034. printer->Print("hash = (19 * hash) + getDescriptor().hashCode();\n");
  1035. }
  1036. // hashCode non-oneofs.
  1037. for (int i = 0; i < descriptor_->field_count(); i++) {
  1038. const FieldDescriptor* field = descriptor_->field(i);
  1039. if (field->containing_oneof() == NULL) {
  1040. const FieldGeneratorInfo* info = context_->GetFieldGeneratorInfo(field);
  1041. bool check_has_bits = CheckHasBitsForEqualsAndHashCode(field);
  1042. if (check_has_bits) {
  1043. printer->Print(
  1044. "if (has$name$()) {\n",
  1045. "name", info->capitalized_name);
  1046. printer->Indent();
  1047. }
  1048. field_generators_.get(field).GenerateHashCode(printer);
  1049. if (check_has_bits) {
  1050. printer->Outdent();
  1051. printer->Print("}\n");
  1052. }
  1053. }
  1054. }
  1055. // hashCode oneofs.
  1056. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  1057. printer->Print(
  1058. "switch ($oneof_name$Case_) {\n",
  1059. "oneof_name",
  1060. context_->GetOneofGeneratorInfo(
  1061. descriptor_->oneof_decl(i))->name);
  1062. printer->Indent();
  1063. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  1064. const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
  1065. printer->Print(
  1066. "case $field_number$:\n",
  1067. "field_number",
  1068. SimpleItoa(field->number()));
  1069. printer->Indent();
  1070. field_generators_.get(field).GenerateHashCode(printer);
  1071. printer->Print("break;\n");
  1072. printer->Outdent();
  1073. }
  1074. printer->Print(
  1075. "case 0:\n"
  1076. "default:\n");
  1077. printer->Outdent();
  1078. printer->Print("}\n");
  1079. }
  1080. if (descriptor_->extension_range_count() > 0) {
  1081. printer->Print(
  1082. "hash = hashFields(hash, getExtensionFields());\n");
  1083. }
  1084. printer->Print(
  1085. "hash = (29 * hash) + unknownFields.hashCode();\n");
  1086. printer->Print(
  1087. "memoizedHashCode = hash;\n"
  1088. "return hash;\n");
  1089. printer->Outdent();
  1090. printer->Print(
  1091. "}\n"
  1092. "\n");
  1093. }
  1094. // ===================================================================
  1095. void ImmutableMessageGenerator::
  1096. GenerateExtensionRegistrationCode(io::Printer* printer) {
  1097. for (int i = 0; i < descriptor_->extension_count(); i++) {
  1098. ImmutableExtensionGenerator(descriptor_->extension(i), context_)
  1099. .GenerateRegistrationCode(printer);
  1100. }
  1101. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1102. ImmutableMessageGenerator(descriptor_->nested_type(i), context_)
  1103. .GenerateExtensionRegistrationCode(printer);
  1104. }
  1105. }
  1106. // ===================================================================
  1107. void ImmutableMessageGenerator::
  1108. GenerateParsingConstructor(io::Printer* printer) {
  1109. std::unique_ptr<const FieldDescriptor * []> sorted_fields(
  1110. SortFieldsByNumber(descriptor_));
  1111. printer->Print(
  1112. "private $classname$(\n"
  1113. " com.google.protobuf.CodedInputStream input,\n"
  1114. " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
  1115. " throws com.google.protobuf.InvalidProtocolBufferException {\n",
  1116. "classname", descriptor_->name());
  1117. printer->Indent();
  1118. // Initialize all fields to default.
  1119. printer->Print(
  1120. "this();\n"
  1121. "if (extensionRegistry == null) {\n"
  1122. " throw new java.lang.NullPointerException();\n"
  1123. "}\n");
  1124. // Use builder bits to track mutable repeated fields.
  1125. int totalBuilderBits = 0;
  1126. for (int i = 0; i < descriptor_->field_count(); i++) {
  1127. const ImmutableFieldGenerator& field =
  1128. field_generators_.get(descriptor_->field(i));
  1129. totalBuilderBits += field.GetNumBitsForBuilder();
  1130. }
  1131. int totalBuilderInts = (totalBuilderBits + 31) / 32;
  1132. for (int i = 0; i < totalBuilderInts; i++) {
  1133. printer->Print("int mutable_$bit_field_name$ = 0;\n",
  1134. "bit_field_name", GetBitFieldName(i));
  1135. }
  1136. printer->Print(
  1137. "com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n"
  1138. " com.google.protobuf.UnknownFieldSet.newBuilder();\n");
  1139. printer->Print(
  1140. "try {\n");
  1141. printer->Indent();
  1142. printer->Print(
  1143. "boolean done = false;\n"
  1144. "while (!done) {\n");
  1145. printer->Indent();
  1146. printer->Print(
  1147. "int tag = input.readTag();\n"
  1148. "switch (tag) {\n");
  1149. printer->Indent();
  1150. printer->Print(
  1151. "case 0:\n" // zero signals EOF / limit reached
  1152. " done = true;\n"
  1153. " break;\n");
  1154. for (int i = 0; i < descriptor_->field_count(); i++) {
  1155. const FieldDescriptor* field = sorted_fields[i];
  1156. uint32 tag = WireFormatLite::MakeTag(field->number(),
  1157. WireFormat::WireTypeForFieldType(field->type()));
  1158. printer->Print(
  1159. "case $tag$: {\n",
  1160. "tag", SimpleItoa(static_cast<int32>(tag)));
  1161. printer->Indent();
  1162. field_generators_.get(field).GenerateParsingCode(printer);
  1163. printer->Outdent();
  1164. printer->Print(
  1165. " break;\n"
  1166. "}\n");
  1167. if (field->is_packable()) {
  1168. // To make packed = true wire compatible, we generate parsing code from a
  1169. // packed version of this field regardless of field->options().packed().
  1170. uint32 packed_tag = WireFormatLite::MakeTag(field->number(),
  1171. WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
  1172. printer->Print(
  1173. "case $tag$: {\n",
  1174. "tag", SimpleItoa(static_cast<int32>(packed_tag)));
  1175. printer->Indent();
  1176. field_generators_.get(field).GenerateParsingCodeFromPacked(printer);
  1177. printer->Outdent();
  1178. printer->Print(
  1179. " break;\n"
  1180. "}\n");
  1181. }
  1182. }
  1183. printer->Print(
  1184. "default: {\n"
  1185. " if (!parseUnknownField$suffix$(\n"
  1186. " input, unknownFields, extensionRegistry, tag)) {\n"
  1187. " done = true;\n" // it's an endgroup tag
  1188. " }\n"
  1189. " break;\n"
  1190. "}\n",
  1191. "suffix",
  1192. descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO3 ? "Proto3"
  1193. : "");
  1194. printer->Outdent();
  1195. printer->Outdent();
  1196. printer->Print(
  1197. " }\n" // switch (tag)
  1198. "}\n"); // while (!done)
  1199. printer->Outdent();
  1200. printer->Print(
  1201. "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n"
  1202. " throw e.setUnfinishedMessage(this);\n"
  1203. "} catch (java.io.IOException e) {\n"
  1204. " throw new com.google.protobuf.InvalidProtocolBufferException(\n"
  1205. " e).setUnfinishedMessage(this);\n"
  1206. "} finally {\n");
  1207. printer->Indent();
  1208. // Make repeated field list immutable.
  1209. for (int i = 0; i < descriptor_->field_count(); i++) {
  1210. const FieldDescriptor* field = sorted_fields[i];
  1211. field_generators_.get(field).GenerateParsingDoneCode(printer);
  1212. }
  1213. // Make unknown fields immutable.
  1214. printer->Print("this.unknownFields = unknownFields.build();\n");
  1215. // Make extensions immutable.
  1216. printer->Print(
  1217. "makeExtensionsImmutable();\n");
  1218. printer->Outdent();
  1219. printer->Outdent();
  1220. printer->Print(
  1221. " }\n" // finally
  1222. "}\n");
  1223. }
  1224. // ===================================================================
  1225. void ImmutableMessageGenerator::GenerateParser(io::Printer* printer) {
  1226. printer->Print(
  1227. "$visibility$ static final com.google.protobuf.Parser<$classname$>\n"
  1228. " PARSER = new com.google.protobuf.AbstractParser<$classname$>() {\n",
  1229. "visibility",
  1230. ExposePublicParser(descriptor_->file()) ? "@java.lang.Deprecated public"
  1231. : "private",
  1232. "classname", descriptor_->name());
  1233. printer->Indent();
  1234. printer->Print(
  1235. "@java.lang.Override\n"
  1236. "public $classname$ parsePartialFrom(\n"
  1237. " com.google.protobuf.CodedInputStream input,\n"
  1238. " com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n"
  1239. " throws com.google.protobuf.InvalidProtocolBufferException {\n",
  1240. "classname", descriptor_->name());
  1241. if (EnableExperimentalRuntime(context_) && !IsDescriptorProto(descriptor_)) {
  1242. printer->Indent();
  1243. printer->Print(
  1244. "$classname$ msg = new $classname$();\n"
  1245. "msg.mergeFromInternal(input, extensionRegistry);\n"
  1246. "msg.makeImmutableInternal();\n"
  1247. "return msg;\n",
  1248. "classname", descriptor_->name());
  1249. printer->Outdent();
  1250. } else if (context_->HasGeneratedMethods(descriptor_)) {
  1251. printer->Print(" return new $classname$(input, extensionRegistry);\n",
  1252. "classname", descriptor_->name());
  1253. } else {
  1254. // When parsing constructor isn't generated, use builder to parse
  1255. // messages. Note, will fallback to use reflection based mergeFieldFrom()
  1256. // in AbstractMessage.Builder.
  1257. printer->Indent();
  1258. printer->Print(
  1259. "Builder builder = newBuilder();\n"
  1260. "try {\n"
  1261. " builder.mergeFrom(input, extensionRegistry);\n"
  1262. "} catch (com.google.protobuf.InvalidProtocolBufferException e) {\n"
  1263. " throw e.setUnfinishedMessage(builder.buildPartial());\n"
  1264. "} catch (java.io.IOException e) {\n"
  1265. " throw new com.google.protobuf.InvalidProtocolBufferException(\n"
  1266. " e.getMessage()).setUnfinishedMessage(\n"
  1267. " builder.buildPartial());\n"
  1268. "}\n"
  1269. "return builder.buildPartial();\n");
  1270. printer->Outdent();
  1271. }
  1272. printer->Print(
  1273. "}\n");
  1274. printer->Outdent();
  1275. printer->Print(
  1276. "};\n"
  1277. "\n");
  1278. printer->Print(
  1279. "public static com.google.protobuf.Parser<$classname$> parser() {\n"
  1280. " return PARSER;\n"
  1281. "}\n"
  1282. "\n"
  1283. "@java.lang.Override\n"
  1284. "public com.google.protobuf.Parser<$classname$> getParserForType() {\n"
  1285. " return PARSER;\n"
  1286. "}\n"
  1287. "\n",
  1288. "classname", descriptor_->name());
  1289. }
  1290. // ===================================================================
  1291. void ImmutableMessageGenerator::GenerateInitializers(io::Printer* printer) {
  1292. for (int i = 0; i < descriptor_->field_count(); i++) {
  1293. if (!descriptor_->field(i)->containing_oneof()) {
  1294. field_generators_.get(descriptor_->field(i))
  1295. .GenerateInitializationCode(printer);
  1296. }
  1297. }
  1298. }
  1299. void ImmutableMessageGenerator::GenerateAnyMethods(io::Printer* printer) {
  1300. printer->Print(
  1301. "private static String getTypeUrl(\n"
  1302. " java.lang.String typeUrlPrefix,\n"
  1303. " com.google.protobuf.Descriptors.Descriptor descriptor) {\n"
  1304. " return typeUrlPrefix.endsWith(\"/\")\n"
  1305. " ? typeUrlPrefix + descriptor.getFullName()\n"
  1306. " : typeUrlPrefix + \"/\" + descriptor.getFullName();\n"
  1307. "}\n"
  1308. "\n"
  1309. "private static String getTypeNameFromTypeUrl(\n"
  1310. " java.lang.String typeUrl) {\n"
  1311. " int pos = typeUrl.lastIndexOf('/');\n"
  1312. " return pos == -1 ? \"\" : typeUrl.substring(pos + 1);\n"
  1313. "}\n"
  1314. "\n"
  1315. "public static <T extends com.google.protobuf.Message> Any pack(\n"
  1316. " T message) {\n"
  1317. " return Any.newBuilder()\n"
  1318. " .setTypeUrl(getTypeUrl(\"type.googleapis.com\",\n"
  1319. " message.getDescriptorForType()))\n"
  1320. " .setValue(message.toByteString())\n"
  1321. " .build();\n"
  1322. "}\n"
  1323. "\n"
  1324. "/**\n"
  1325. " * Packs a message using the given type URL prefix. The type URL will\n"
  1326. " * be constructed by concatenating the message type's full name to the\n"
  1327. " * prefix with an optional \"/\" separator if the prefix doesn't end\n"
  1328. " * with \"/\" already.\n"
  1329. " */\n"
  1330. "public static <T extends com.google.protobuf.Message> Any pack(\n"
  1331. " T message, java.lang.String typeUrlPrefix) {\n"
  1332. " return Any.newBuilder()\n"
  1333. " .setTypeUrl(getTypeUrl(typeUrlPrefix,\n"
  1334. " message.getDescriptorForType()))\n"
  1335. " .setValue(message.toByteString())\n"
  1336. " .build();\n"
  1337. "}\n"
  1338. "\n"
  1339. "public <T extends com.google.protobuf.Message> boolean is(\n"
  1340. " java.lang.Class<T> clazz) {\n"
  1341. " T defaultInstance =\n"
  1342. " com.google.protobuf.Internal.getDefaultInstance(clazz);\n"
  1343. " return getTypeNameFromTypeUrl(getTypeUrl()).equals(\n"
  1344. " defaultInstance.getDescriptorForType().getFullName());\n"
  1345. "}\n"
  1346. "\n"
  1347. "private volatile com.google.protobuf.Message cachedUnpackValue;\n"
  1348. "\n"
  1349. "@java.lang.SuppressWarnings(\"unchecked\")\n"
  1350. "public <T extends com.google.protobuf.Message> T unpack(\n"
  1351. " java.lang.Class<T> clazz)\n"
  1352. " throws com.google.protobuf.InvalidProtocolBufferException {\n"
  1353. " if (!is(clazz)) {\n"
  1354. " throw new com.google.protobuf.InvalidProtocolBufferException(\n"
  1355. " \"Type of the Any message does not match the given class.\");\n"
  1356. " }\n"
  1357. " if (cachedUnpackValue != null) {\n"
  1358. " return (T) cachedUnpackValue;\n"
  1359. " }\n"
  1360. " T defaultInstance =\n"
  1361. " com.google.protobuf.Internal.getDefaultInstance(clazz);\n"
  1362. " T result = (T) defaultInstance.getParserForType()\n"
  1363. " .parseFrom(getValue());\n"
  1364. " cachedUnpackValue = result;\n"
  1365. " return result;\n"
  1366. "}\n");
  1367. }
  1368. } // namespace java
  1369. } // namespace compiler
  1370. } // namespace protobuf
  1371. } // namespace google