javanano_primitive_field.cc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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 <map>
  34. #include <math.h>
  35. #include <string>
  36. #include <google/protobuf/compiler/javanano/javanano_primitive_field.h>
  37. #include <google/protobuf/stubs/common.h>
  38. #include <google/protobuf/compiler/javanano/javanano_helpers.h>
  39. #include <google/protobuf/io/printer.h>
  40. #include <google/protobuf/wire_format.h>
  41. #include <google/protobuf/stubs/strutil.h>
  42. #include <google/protobuf/stubs/substitute.h>
  43. namespace google {
  44. namespace protobuf {
  45. namespace compiler {
  46. namespace javanano {
  47. using internal::WireFormat;
  48. using internal::WireFormatLite;
  49. namespace {
  50. bool IsReferenceType(JavaType type) {
  51. switch (type) {
  52. case JAVATYPE_INT : return false;
  53. case JAVATYPE_LONG : return false;
  54. case JAVATYPE_FLOAT : return false;
  55. case JAVATYPE_DOUBLE : return false;
  56. case JAVATYPE_BOOLEAN: return false;
  57. case JAVATYPE_STRING : return true;
  58. case JAVATYPE_BYTES : return true;
  59. case JAVATYPE_ENUM : return false;
  60. case JAVATYPE_MESSAGE: return true;
  61. // No default because we want the compiler to complain if any new
  62. // JavaTypes are added.
  63. }
  64. GOOGLE_LOG(FATAL) << "Can't get here.";
  65. return false;
  66. }
  67. bool IsArrayType(JavaType type) {
  68. switch (type) {
  69. case JAVATYPE_INT : return false;
  70. case JAVATYPE_LONG : return false;
  71. case JAVATYPE_FLOAT : return false;
  72. case JAVATYPE_DOUBLE : return false;
  73. case JAVATYPE_BOOLEAN: return false;
  74. case JAVATYPE_STRING : return false;
  75. case JAVATYPE_BYTES : return true;
  76. case JAVATYPE_ENUM : return false;
  77. case JAVATYPE_MESSAGE: return false;
  78. // No default because we want the compiler to complain if any new
  79. // JavaTypes are added.
  80. }
  81. GOOGLE_LOG(FATAL) << "Can't get here.";
  82. return false;
  83. }
  84. const char* GetCapitalizedType(const FieldDescriptor* field) {
  85. switch (field->type()) {
  86. case FieldDescriptor::TYPE_INT32 : return "Int32" ;
  87. case FieldDescriptor::TYPE_UINT32 : return "UInt32" ;
  88. case FieldDescriptor::TYPE_SINT32 : return "SInt32" ;
  89. case FieldDescriptor::TYPE_FIXED32 : return "Fixed32" ;
  90. case FieldDescriptor::TYPE_SFIXED32: return "SFixed32";
  91. case FieldDescriptor::TYPE_INT64 : return "Int64" ;
  92. case FieldDescriptor::TYPE_UINT64 : return "UInt64" ;
  93. case FieldDescriptor::TYPE_SINT64 : return "SInt64" ;
  94. case FieldDescriptor::TYPE_FIXED64 : return "Fixed64" ;
  95. case FieldDescriptor::TYPE_SFIXED64: return "SFixed64";
  96. case FieldDescriptor::TYPE_FLOAT : return "Float" ;
  97. case FieldDescriptor::TYPE_DOUBLE : return "Double" ;
  98. case FieldDescriptor::TYPE_BOOL : return "Bool" ;
  99. case FieldDescriptor::TYPE_STRING : return "String" ;
  100. case FieldDescriptor::TYPE_BYTES : return "Bytes" ;
  101. case FieldDescriptor::TYPE_ENUM : return "Enum" ;
  102. case FieldDescriptor::TYPE_GROUP : return "Group" ;
  103. case FieldDescriptor::TYPE_MESSAGE : return "Message" ;
  104. // No default because we want the compiler to complain if any new
  105. // types are added.
  106. }
  107. GOOGLE_LOG(FATAL) << "Can't get here.";
  108. return NULL;
  109. }
  110. // For encodings with fixed sizes, returns that size in bytes. Otherwise
  111. // returns -1.
  112. int FixedSize(FieldDescriptor::Type type) {
  113. switch (type) {
  114. case FieldDescriptor::TYPE_INT32 : return -1;
  115. case FieldDescriptor::TYPE_INT64 : return -1;
  116. case FieldDescriptor::TYPE_UINT32 : return -1;
  117. case FieldDescriptor::TYPE_UINT64 : return -1;
  118. case FieldDescriptor::TYPE_SINT32 : return -1;
  119. case FieldDescriptor::TYPE_SINT64 : return -1;
  120. case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size;
  121. case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size;
  122. case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size;
  123. case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size;
  124. case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize;
  125. case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize;
  126. case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize;
  127. case FieldDescriptor::TYPE_ENUM : return -1;
  128. case FieldDescriptor::TYPE_STRING : return -1;
  129. case FieldDescriptor::TYPE_BYTES : return -1;
  130. case FieldDescriptor::TYPE_GROUP : return -1;
  131. case FieldDescriptor::TYPE_MESSAGE : return -1;
  132. // No default because we want the compiler to complain if any new
  133. // types are added.
  134. }
  135. GOOGLE_LOG(FATAL) << "Can't get here.";
  136. return -1;
  137. }
  138. bool AllAscii(const string& text) {
  139. for (int i = 0; i < text.size(); i++) {
  140. if ((text[i] & 0x80) != 0) {
  141. return false;
  142. }
  143. }
  144. return true;
  145. }
  146. void SetPrimitiveVariables(const FieldDescriptor* descriptor, const Params params,
  147. std::map<string, string>* variables) {
  148. (*variables)["name"] =
  149. RenameJavaKeywords(UnderscoresToCamelCase(descriptor));
  150. (*variables)["capitalized_name"] =
  151. RenameJavaKeywords(UnderscoresToCapitalizedCamelCase(descriptor));
  152. (*variables)["number"] = SimpleItoa(descriptor->number());
  153. if (params.use_reference_types_for_primitives()
  154. && !descriptor->is_repeated()) {
  155. (*variables)["type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor));
  156. } else {
  157. (*variables)["type"] = PrimitiveTypeName(GetJavaType(descriptor));
  158. }
  159. // Deals with defaults. For C++-string types (string and bytes),
  160. // we might need to have the generated code do the unicode decoding
  161. // (see comments in InternalNano.java for gory details.). We would
  162. // like to do this once into a static field and re-use that from
  163. // then on.
  164. if (descriptor->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
  165. !descriptor->default_value_string().empty() &&
  166. !params.use_reference_types_for_primitives()) {
  167. if (descriptor->type() == FieldDescriptor::TYPE_BYTES) {
  168. (*variables)["default"] = DefaultValue(params, descriptor);
  169. (*variables)["default_constant"] = FieldDefaultConstantName(descriptor);
  170. (*variables)["default_constant_value"] = strings::Substitute(
  171. "com.google.protobuf.nano.InternalNano.bytesDefaultValue(\"$0\")",
  172. CEscape(descriptor->default_value_string()));
  173. (*variables)["default_copy_if_needed"] =
  174. (*variables)["default"] + ".clone()";
  175. } else if (AllAscii(descriptor->default_value_string())) {
  176. // All chars are ASCII. In this case directly referencing a
  177. // CEscape()'d string literal works fine.
  178. (*variables)["default"] =
  179. "\"" + CEscape(descriptor->default_value_string()) + "\"";
  180. (*variables)["default_copy_if_needed"] = (*variables)["default"];
  181. } else {
  182. // Strings where some chars are non-ASCII. We need to save the
  183. // default value.
  184. (*variables)["default"] = DefaultValue(params, descriptor);
  185. (*variables)["default_constant"] = FieldDefaultConstantName(descriptor);
  186. (*variables)["default_constant_value"] = strings::Substitute(
  187. "com.google.protobuf.nano.InternalNano.stringDefaultValue(\"$0\")",
  188. CEscape(descriptor->default_value_string()));
  189. (*variables)["default_copy_if_needed"] = (*variables)["default"];
  190. }
  191. } else {
  192. // Non-string, non-bytes field. Defaults are literals.
  193. (*variables)["default"] = DefaultValue(params, descriptor);
  194. (*variables)["default_copy_if_needed"] = (*variables)["default"];
  195. }
  196. (*variables)["boxed_type"] = BoxedPrimitiveTypeName(GetJavaType(descriptor));
  197. (*variables)["capitalized_type"] = GetCapitalizedType(descriptor);
  198. (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor));
  199. (*variables)["tag_size"] = SimpleItoa(
  200. WireFormat::TagSize(descriptor->number(), descriptor->type()));
  201. (*variables)["non_packed_tag"] = SimpleItoa(
  202. internal::WireFormatLite::MakeTag(descriptor->number(),
  203. internal::WireFormat::WireTypeForFieldType(descriptor->type())));
  204. int fixed_size = FixedSize(descriptor->type());
  205. if (fixed_size != -1) {
  206. (*variables)["fixed_size"] = SimpleItoa(fixed_size);
  207. }
  208. (*variables)["message_name"] = descriptor->containing_type()->name();
  209. (*variables)["empty_array_name"] = EmptyArrayName(params, descriptor);
  210. }
  211. } // namespace
  212. // ===================================================================
  213. PrimitiveFieldGenerator::
  214. PrimitiveFieldGenerator(const FieldDescriptor* descriptor, const Params& params)
  215. : FieldGenerator(params), descriptor_(descriptor) {
  216. SetPrimitiveVariables(descriptor, params, &variables_);
  217. }
  218. PrimitiveFieldGenerator::~PrimitiveFieldGenerator() {}
  219. bool PrimitiveFieldGenerator::SavedDefaultNeeded() const {
  220. return variables_.find("default_constant") != variables_.end();
  221. }
  222. void PrimitiveFieldGenerator::GenerateInitSavedDefaultCode(io::Printer* printer) const {
  223. if (variables_.find("default_constant") != variables_.end()) {
  224. printer->Print(variables_,
  225. "$default_constant$ = $default_constant_value$;\n");
  226. }
  227. }
  228. void PrimitiveFieldGenerator::
  229. GenerateMembers(io::Printer* printer, bool lazy_init) const {
  230. if (variables_.find("default_constant") != variables_.end()) {
  231. // Those primitive types that need a saved default.
  232. if (lazy_init) {
  233. printer->Print(variables_,
  234. "private static $type$ $default_constant$;\n");
  235. } else {
  236. printer->Print(variables_,
  237. "private static final $type$ $default_constant$ =\n"
  238. " $default_constant_value$;\n");
  239. }
  240. }
  241. printer->Print(variables_,
  242. "public $type$ $name$;\n");
  243. if (params_.generate_has()) {
  244. printer->Print(variables_,
  245. "public boolean has$capitalized_name$;\n");
  246. }
  247. }
  248. void PrimitiveFieldGenerator::
  249. GenerateClearCode(io::Printer* printer) const {
  250. printer->Print(variables_,
  251. "$name$ = $default_copy_if_needed$;\n");
  252. if (params_.generate_has()) {
  253. printer->Print(variables_,
  254. "has$capitalized_name$ = false;\n");
  255. }
  256. }
  257. void PrimitiveFieldGenerator::
  258. GenerateMergingCode(io::Printer* printer) const {
  259. printer->Print(variables_,
  260. "this.$name$ = input.read$capitalized_type$();\n");
  261. if (params_.generate_has()) {
  262. printer->Print(variables_,
  263. "has$capitalized_name$ = true;\n");
  264. }
  265. }
  266. void PrimitiveFieldGenerator::
  267. GenerateSerializationConditional(io::Printer* printer) const {
  268. if (params_.use_reference_types_for_primitives()) {
  269. // For reference type mode, serialize based on equality
  270. // to null.
  271. printer->Print(variables_,
  272. "if (this.$name$ != null) {\n");
  273. return;
  274. }
  275. if (params_.generate_has()) {
  276. printer->Print(variables_,
  277. "if (has$capitalized_name$ || ");
  278. } else {
  279. printer->Print(variables_,
  280. "if (");
  281. }
  282. JavaType java_type = GetJavaType(descriptor_);
  283. if (IsArrayType(java_type)) {
  284. printer->Print(variables_,
  285. "!java.util.Arrays.equals(this.$name$, $default$)) {\n");
  286. } else if (IsReferenceType(java_type)) {
  287. printer->Print(variables_,
  288. "!this.$name$.equals($default$)) {\n");
  289. } else if (java_type == JAVATYPE_FLOAT) {
  290. printer->Print(variables_,
  291. "java.lang.Float.floatToIntBits(this.$name$)\n"
  292. " != java.lang.Float.floatToIntBits($default$)) {\n");
  293. } else if (java_type == JAVATYPE_DOUBLE) {
  294. printer->Print(variables_,
  295. "java.lang.Double.doubleToLongBits(this.$name$)\n"
  296. " != java.lang.Double.doubleToLongBits($default$)) {\n");
  297. } else {
  298. printer->Print(variables_,
  299. "this.$name$ != $default$) {\n");
  300. }
  301. }
  302. void PrimitiveFieldGenerator::
  303. GenerateSerializationCode(io::Printer* printer) const {
  304. if (descriptor_->is_required() && !params_.generate_has()) {
  305. // Always serialize a required field if we don't have the 'has' signal.
  306. printer->Print(variables_,
  307. "output.write$capitalized_type$($number$, this.$name$);\n");
  308. } else {
  309. GenerateSerializationConditional(printer);
  310. printer->Print(variables_,
  311. " output.write$capitalized_type$($number$, this.$name$);\n"
  312. "}\n");
  313. }
  314. }
  315. void PrimitiveFieldGenerator::
  316. GenerateSerializedSizeCode(io::Printer* printer) const {
  317. if (descriptor_->is_required() && !params_.generate_has()) {
  318. printer->Print(variables_,
  319. "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
  320. " .compute$capitalized_type$Size($number$, this.$name$);\n");
  321. } else {
  322. GenerateSerializationConditional(printer);
  323. printer->Print(variables_,
  324. " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
  325. " .compute$capitalized_type$Size($number$, this.$name$);\n"
  326. "}\n");
  327. }
  328. }
  329. void RepeatedPrimitiveFieldGenerator::
  330. GenerateFixClonedCode(io::Printer* printer) const {
  331. printer->Print(variables_,
  332. "if (this.$name$ != null && this.$name$.length > 0) {\n"
  333. " cloned.$name$ = this.$name$.clone();\n"
  334. "}\n");
  335. }
  336. void PrimitiveFieldGenerator::
  337. GenerateEqualsCode(io::Printer* printer) const {
  338. // We define equality as serialized form equality. If generate_has(),
  339. // then if the field value equals the default value in both messages,
  340. // but one's 'has' field is set and the other's is not, the serialized
  341. // forms are different and we should return false.
  342. JavaType java_type = GetJavaType(descriptor_);
  343. if (java_type == JAVATYPE_BYTES) {
  344. printer->Print(variables_,
  345. "if (!java.util.Arrays.equals(this.$name$, other.$name$)");
  346. if (params_.generate_has()) {
  347. printer->Print(variables_,
  348. "\n"
  349. " || (java.util.Arrays.equals(this.$name$, $default$)\n"
  350. " && this.has$capitalized_name$ != other.has$capitalized_name$)");
  351. }
  352. printer->Print(") {\n"
  353. " return false;\n"
  354. "}\n");
  355. } else if (java_type == JAVATYPE_STRING
  356. || params_.use_reference_types_for_primitives()) {
  357. printer->Print(variables_,
  358. "if (this.$name$ == null) {\n"
  359. " if (other.$name$ != null) {\n"
  360. " return false;\n"
  361. " }\n"
  362. "} else if (!this.$name$.equals(other.$name$)");
  363. if (params_.generate_has()) {
  364. printer->Print(variables_,
  365. "\n"
  366. " || (this.$name$.equals($default$)\n"
  367. " && this.has$capitalized_name$ != other.has$capitalized_name$)");
  368. }
  369. printer->Print(") {\n"
  370. " return false;\n"
  371. "}\n");
  372. } else if (java_type == JAVATYPE_FLOAT) {
  373. printer->Print(variables_,
  374. "{\n"
  375. " int bits = java.lang.Float.floatToIntBits(this.$name$);\n"
  376. " if (bits != java.lang.Float.floatToIntBits(other.$name$)");
  377. if (params_.generate_has()) {
  378. printer->Print(variables_,
  379. "\n"
  380. " || (bits == java.lang.Float.floatToIntBits($default$)\n"
  381. " && this.has$capitalized_name$ != other.has$capitalized_name$)");
  382. }
  383. printer->Print(") {\n"
  384. " return false;\n"
  385. " }\n"
  386. "}\n");
  387. } else if (java_type == JAVATYPE_DOUBLE) {
  388. printer->Print(variables_,
  389. "{\n"
  390. " long bits = java.lang.Double.doubleToLongBits(this.$name$);\n"
  391. " if (bits != java.lang.Double.doubleToLongBits(other.$name$)");
  392. if (params_.generate_has()) {
  393. printer->Print(variables_,
  394. "\n"
  395. " || (bits == java.lang.Double.doubleToLongBits($default$)\n"
  396. " && this.has$capitalized_name$ != other.has$capitalized_name$)");
  397. }
  398. printer->Print(") {\n"
  399. " return false;\n"
  400. " }\n"
  401. "}\n");
  402. } else {
  403. printer->Print(variables_,
  404. "if (this.$name$ != other.$name$");
  405. if (params_.generate_has()) {
  406. printer->Print(variables_,
  407. "\n"
  408. " || (this.$name$ == $default$\n"
  409. " && this.has$capitalized_name$ != other.has$capitalized_name$)");
  410. }
  411. printer->Print(") {\n"
  412. " return false;\n"
  413. "}\n");
  414. }
  415. }
  416. void PrimitiveFieldGenerator::
  417. GenerateHashCodeCode(io::Printer* printer) const {
  418. JavaType java_type = GetJavaType(descriptor_);
  419. if (java_type == JAVATYPE_BYTES) {
  420. printer->Print(variables_,
  421. "result = 31 * result + java.util.Arrays.hashCode(this.$name$);\n");
  422. } else if (java_type == JAVATYPE_STRING
  423. || params_.use_reference_types_for_primitives()) {
  424. printer->Print(variables_,
  425. "result = 31 * result\n"
  426. " + (this.$name$ == null ? 0 : this.$name$.hashCode());\n");
  427. } else {
  428. switch (java_type) {
  429. // For all Java primitive types below, the hash codes match the
  430. // results of BoxedType.valueOf(primitiveValue).hashCode().
  431. case JAVATYPE_INT:
  432. printer->Print(variables_,
  433. "result = 31 * result + this.$name$;\n");
  434. break;
  435. case JAVATYPE_LONG:
  436. printer->Print(variables_,
  437. "result = 31 * result\n"
  438. " + (int) (this.$name$ ^ (this.$name$ >>> 32));\n");
  439. break;
  440. case JAVATYPE_FLOAT:
  441. printer->Print(variables_,
  442. "result = 31 * result\n"
  443. " + java.lang.Float.floatToIntBits(this.$name$);\n");
  444. break;
  445. case JAVATYPE_DOUBLE:
  446. printer->Print(variables_,
  447. "{\n"
  448. " long v = java.lang.Double.doubleToLongBits(this.$name$);\n"
  449. " result = 31 * result + (int) (v ^ (v >>> 32));\n"
  450. "}\n");
  451. break;
  452. case JAVATYPE_BOOLEAN:
  453. printer->Print(variables_,
  454. "result = 31 * result + (this.$name$ ? 1231 : 1237);\n");
  455. break;
  456. default:
  457. GOOGLE_LOG(ERROR) << "unknown java type for primitive field";
  458. break;
  459. }
  460. }
  461. }
  462. // ===================================================================
  463. AccessorPrimitiveFieldGenerator::
  464. AccessorPrimitiveFieldGenerator(const FieldDescriptor* descriptor,
  465. const Params& params, int has_bit_index)
  466. : FieldGenerator(params), descriptor_(descriptor) {
  467. SetPrimitiveVariables(descriptor, params, &variables_);
  468. SetBitOperationVariables("has", has_bit_index, &variables_);
  469. }
  470. AccessorPrimitiveFieldGenerator::~AccessorPrimitiveFieldGenerator() {}
  471. bool AccessorPrimitiveFieldGenerator::SavedDefaultNeeded() const {
  472. return variables_.find("default_constant") != variables_.end();
  473. }
  474. void AccessorPrimitiveFieldGenerator::
  475. GenerateInitSavedDefaultCode(io::Printer* printer) const {
  476. if (variables_.find("default_constant") != variables_.end()) {
  477. printer->Print(variables_,
  478. "$default_constant$ = $default_constant_value$;\n");
  479. }
  480. }
  481. void AccessorPrimitiveFieldGenerator::
  482. GenerateMembers(io::Printer* printer, bool lazy_init) const {
  483. if (variables_.find("default_constant") != variables_.end()) {
  484. // Those primitive types that need a saved default.
  485. if (lazy_init) {
  486. printer->Print(variables_,
  487. "private static $type$ $default_constant$;\n");
  488. } else {
  489. printer->Print(variables_,
  490. "private static final $type$ $default_constant$ =\n"
  491. " $default_constant_value$;\n");
  492. }
  493. }
  494. printer->Print(variables_,
  495. "private $type$ $name$_;\n"
  496. "public $type$ get$capitalized_name$() {\n"
  497. " return $name$_;\n"
  498. "}\n"
  499. "public $message_name$ set$capitalized_name$($type$ value) {\n");
  500. if (IsReferenceType(GetJavaType(descriptor_))) {
  501. printer->Print(variables_,
  502. " if (value == null) {\n"
  503. " throw new java.lang.NullPointerException();\n"
  504. " }\n");
  505. }
  506. printer->Print(variables_,
  507. " $name$_ = value;\n"
  508. " $set_has$;\n"
  509. " return this;\n"
  510. "}\n"
  511. "public boolean has$capitalized_name$() {\n"
  512. " return $get_has$;\n"
  513. "}\n"
  514. "public $message_name$ clear$capitalized_name$() {\n"
  515. " $name$_ = $default_copy_if_needed$;\n"
  516. " $clear_has$;\n"
  517. " return this;\n"
  518. "}\n");
  519. }
  520. void AccessorPrimitiveFieldGenerator::
  521. GenerateClearCode(io::Printer* printer) const {
  522. printer->Print(variables_,
  523. "$name$_ = $default_copy_if_needed$;\n");
  524. }
  525. void AccessorPrimitiveFieldGenerator::
  526. GenerateMergingCode(io::Printer* printer) const {
  527. printer->Print(variables_,
  528. "$name$_ = input.read$capitalized_type$();\n"
  529. "$set_has$;\n");
  530. }
  531. void AccessorPrimitiveFieldGenerator::
  532. GenerateSerializationCode(io::Printer* printer) const {
  533. printer->Print(variables_,
  534. "if ($get_has$) {\n"
  535. " output.write$capitalized_type$($number$, $name$_);\n"
  536. "}\n");
  537. }
  538. void AccessorPrimitiveFieldGenerator::
  539. GenerateSerializedSizeCode(io::Printer* printer) const {
  540. printer->Print(variables_,
  541. "if ($get_has$) {\n"
  542. " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
  543. " .compute$capitalized_type$Size($number$, $name$_);\n"
  544. "}\n");
  545. }
  546. void AccessorPrimitiveFieldGenerator::
  547. GenerateEqualsCode(io::Printer* printer) const {
  548. switch (GetJavaType(descriptor_)) {
  549. // For all Java primitive types below, the equality checks match the
  550. // results of BoxedType.valueOf(primitiveValue).equals(otherValue).
  551. case JAVATYPE_FLOAT:
  552. printer->Print(variables_,
  553. "if ($different_has$\n"
  554. " || java.lang.Float.floatToIntBits($name$_)\n"
  555. " != java.lang.Float.floatToIntBits(other.$name$_)) {\n"
  556. " return false;\n"
  557. "}\n");
  558. break;
  559. case JAVATYPE_DOUBLE:
  560. printer->Print(variables_,
  561. "if ($different_has$\n"
  562. " || java.lang.Double.doubleToLongBits($name$_)\n"
  563. " != java.lang.Double.doubleToLongBits(other.$name$_)) {\n"
  564. " return false;\n"
  565. "}\n");
  566. break;
  567. case JAVATYPE_INT:
  568. case JAVATYPE_LONG:
  569. case JAVATYPE_BOOLEAN:
  570. printer->Print(variables_,
  571. "if ($different_has$\n"
  572. " || $name$_ != other.$name$_) {\n"
  573. " return false;\n"
  574. "}\n");
  575. break;
  576. case JAVATYPE_STRING:
  577. // Accessor style would guarantee $name$_ non-null
  578. printer->Print(variables_,
  579. "if ($different_has$\n"
  580. " || !$name$_.equals(other.$name$_)) {\n"
  581. " return false;\n"
  582. "}\n");
  583. break;
  584. case JAVATYPE_BYTES:
  585. // Accessor style would guarantee $name$_ non-null
  586. printer->Print(variables_,
  587. "if ($different_has$\n"
  588. " || !java.util.Arrays.equals($name$_, other.$name$_)) {\n"
  589. " return false;\n"
  590. "}\n");
  591. break;
  592. default:
  593. GOOGLE_LOG(ERROR) << "unknown java type for primitive field";
  594. break;
  595. }
  596. }
  597. void AccessorPrimitiveFieldGenerator::
  598. GenerateHashCodeCode(io::Printer* printer) const {
  599. switch (GetJavaType(descriptor_)) {
  600. // For all Java primitive types below, the hash codes match the
  601. // results of BoxedType.valueOf(primitiveValue).hashCode().
  602. case JAVATYPE_INT:
  603. printer->Print(variables_,
  604. "result = 31 * result + $name$_;\n");
  605. break;
  606. case JAVATYPE_LONG:
  607. printer->Print(variables_,
  608. "result = 31 * result + (int) ($name$_ ^ ($name$_ >>> 32));\n");
  609. break;
  610. case JAVATYPE_FLOAT:
  611. printer->Print(variables_,
  612. "result = 31 * result +\n"
  613. " java.lang.Float.floatToIntBits($name$_);\n");
  614. break;
  615. case JAVATYPE_DOUBLE:
  616. printer->Print(variables_,
  617. "{\n"
  618. " long v = java.lang.Double.doubleToLongBits($name$_);\n"
  619. " result = 31 * result + (int) (v ^ (v >>> 32));\n"
  620. "}\n");
  621. break;
  622. case JAVATYPE_BOOLEAN:
  623. printer->Print(variables_,
  624. "result = 31 * result + ($name$_ ? 1231 : 1237);\n");
  625. break;
  626. case JAVATYPE_STRING:
  627. // Accessor style would guarantee $name$_ non-null
  628. printer->Print(variables_,
  629. "result = 31 * result + $name$_.hashCode();\n");
  630. break;
  631. case JAVATYPE_BYTES:
  632. // Accessor style would guarantee $name$_ non-null
  633. printer->Print(variables_,
  634. "result = 31 * result + java.util.Arrays.hashCode($name$_);\n");
  635. break;
  636. default:
  637. GOOGLE_LOG(ERROR) << "unknown java type for primitive field";
  638. break;
  639. }
  640. }
  641. // ===================================================================
  642. PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator(
  643. const FieldDescriptor* descriptor, const Params& params)
  644. : FieldGenerator(params), descriptor_(descriptor) {
  645. SetPrimitiveVariables(descriptor, params, &variables_);
  646. SetCommonOneofVariables(descriptor, &variables_);
  647. }
  648. PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() {}
  649. void PrimitiveOneofFieldGenerator::GenerateMembers(
  650. io::Printer* printer, bool /*unused lazy_init*/) const {
  651. printer->Print(variables_,
  652. "public boolean has$capitalized_name$() {\n"
  653. " return $has_oneof_case$;\n"
  654. "}\n"
  655. "public $type$ get$capitalized_name$() {\n"
  656. " if ($has_oneof_case$) {\n"
  657. " return ($type$) ($boxed_type$) this.$oneof_name$_;\n"
  658. " }\n"
  659. " return $default$;\n"
  660. "}\n"
  661. "public $message_name$ set$capitalized_name$($type$ value) {\n"
  662. " $set_oneof_case$;\n"
  663. " this.$oneof_name$_ = value;\n"
  664. " return this;\n"
  665. "}\n");
  666. }
  667. void PrimitiveOneofFieldGenerator::GenerateClearCode(
  668. io::Printer* printer) const {
  669. // No clear method for oneof fields.
  670. }
  671. void PrimitiveOneofFieldGenerator::GenerateMergingCode(
  672. io::Printer* printer) const {
  673. printer->Print(variables_,
  674. "this.$oneof_name$_ = input.read$capitalized_type$();\n"
  675. "$set_oneof_case$;\n");
  676. }
  677. void PrimitiveOneofFieldGenerator::GenerateSerializationCode(
  678. io::Printer* printer) const {
  679. printer->Print(variables_,
  680. "if ($has_oneof_case$) {\n"
  681. " output.write$capitalized_type$(\n"
  682. " $number$, ($boxed_type$) this.$oneof_name$_);\n"
  683. "}\n");
  684. }
  685. void PrimitiveOneofFieldGenerator::GenerateSerializedSizeCode(
  686. io::Printer* printer) const {
  687. printer->Print(variables_,
  688. "if ($has_oneof_case$) {\n"
  689. " size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
  690. " .compute$capitalized_type$Size(\n"
  691. " $number$, ($boxed_type$) this.$oneof_name$_);\n"
  692. "}\n");
  693. }
  694. void PrimitiveOneofFieldGenerator::GenerateEqualsCode(
  695. io::Printer* printer) const {
  696. GenerateOneofFieldEquals(descriptor_, variables_, printer);
  697. }
  698. void PrimitiveOneofFieldGenerator::GenerateHashCodeCode(
  699. io::Printer* printer) const {
  700. GenerateOneofFieldHashCode(descriptor_, variables_, printer);
  701. }
  702. // ===================================================================
  703. RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator(
  704. const FieldDescriptor* descriptor, const Params& params)
  705. : FieldGenerator(params), descriptor_(descriptor) {
  706. SetPrimitiveVariables(descriptor, params, &variables_);
  707. }
  708. RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() {}
  709. void RepeatedPrimitiveFieldGenerator::
  710. GenerateMembers(io::Printer* printer, bool /*unused init_defaults*/) const {
  711. printer->Print(variables_,
  712. "public $type$[] $name$;\n");
  713. }
  714. void RepeatedPrimitiveFieldGenerator::
  715. GenerateClearCode(io::Printer* printer) const {
  716. printer->Print(variables_,
  717. "$name$ = $default$;\n");
  718. }
  719. void RepeatedPrimitiveFieldGenerator::
  720. GenerateMergingCode(io::Printer* printer) const {
  721. // First, figure out the length of the array, then parse.
  722. printer->Print(variables_,
  723. "int arrayLength = com.google.protobuf.nano.WireFormatNano\n"
  724. " .getRepeatedFieldArrayLength(input, $non_packed_tag$);\n"
  725. "int i = this.$name$ == null ? 0 : this.$name$.length;\n");
  726. if (GetJavaType(descriptor_) == JAVATYPE_BYTES) {
  727. printer->Print(variables_,
  728. "byte[][] newArray = new byte[i + arrayLength][];\n");
  729. } else {
  730. printer->Print(variables_,
  731. "$type$[] newArray = new $type$[i + arrayLength];\n");
  732. }
  733. printer->Print(variables_,
  734. "if (i != 0) {\n"
  735. " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
  736. "}\n"
  737. "for (; i < newArray.length - 1; i++) {\n"
  738. " newArray[i] = input.read$capitalized_type$();\n"
  739. " input.readTag();\n"
  740. "}\n"
  741. "// Last one without readTag.\n"
  742. "newArray[i] = input.read$capitalized_type$();\n"
  743. "this.$name$ = newArray;\n");
  744. }
  745. void RepeatedPrimitiveFieldGenerator::
  746. GenerateMergingCodeFromPacked(io::Printer* printer) const {
  747. printer->Print(
  748. "int length = input.readRawVarint32();\n"
  749. "int limit = input.pushLimit(length);\n");
  750. // If we know the elements will all be of the same size, the arrayLength
  751. // can be calculated much more easily. However, FixedSize() returns 1 for
  752. // repeated bool fields, which are guaranteed to have the fixed size of
  753. // 1 byte per value only if we control the output. On the wire they can
  754. // legally appear as variable-size integers, so we need to use the slow
  755. // way for repeated bool fields.
  756. if (descriptor_->type() == FieldDescriptor::TYPE_BOOL
  757. || FixedSize(descriptor_->type()) == -1) {
  758. printer->Print(variables_,
  759. "// First pass to compute array length.\n"
  760. "int arrayLength = 0;\n"
  761. "int startPos = input.getPosition();\n"
  762. "while (input.getBytesUntilLimit() > 0) {\n"
  763. " input.read$capitalized_type$();\n"
  764. " arrayLength++;\n"
  765. "}\n"
  766. "input.rewindToPosition(startPos);\n");
  767. } else {
  768. printer->Print(variables_,
  769. "int arrayLength = length / $fixed_size$;\n");
  770. }
  771. printer->Print(variables_,
  772. "int i = this.$name$ == null ? 0 : this.$name$.length;\n"
  773. "$type$[] newArray = new $type$[i + arrayLength];\n"
  774. "if (i != 0) {\n"
  775. " java.lang.System.arraycopy(this.$name$, 0, newArray, 0, i);\n"
  776. "}\n"
  777. "for (; i < newArray.length; i++) {\n"
  778. " newArray[i] = input.read$capitalized_type$();\n"
  779. "}\n"
  780. "this.$name$ = newArray;\n"
  781. "input.popLimit(limit);\n");
  782. }
  783. void RepeatedPrimitiveFieldGenerator::
  784. GenerateRepeatedDataSizeCode(io::Printer* printer) const {
  785. // Creates a variable dataSize and puts the serialized size in there.
  786. // If the element type is a Java reference type, also generates
  787. // dataCount which stores the number of non-null elements in the field.
  788. if (IsReferenceType(GetJavaType(descriptor_))) {
  789. printer->Print(variables_,
  790. "int dataCount = 0;\n"
  791. "int dataSize = 0;\n"
  792. "for (int i = 0; i < this.$name$.length; i++) {\n"
  793. " $type$ element = this.$name$[i];\n"
  794. " if (element != null) {\n"
  795. " dataCount++;\n"
  796. " dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
  797. " .compute$capitalized_type$SizeNoTag(element);\n"
  798. " }\n"
  799. "}\n");
  800. } else if (FixedSize(descriptor_->type()) == -1) {
  801. printer->Print(variables_,
  802. "int dataSize = 0;\n"
  803. "for (int i = 0; i < this.$name$.length; i++) {\n"
  804. " $type$ element = this.$name$[i];\n"
  805. " dataSize += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
  806. " .compute$capitalized_type$SizeNoTag(element);\n"
  807. "}\n");
  808. } else {
  809. printer->Print(variables_,
  810. "int dataSize = $fixed_size$ * this.$name$.length;\n");
  811. }
  812. }
  813. void RepeatedPrimitiveFieldGenerator::
  814. GenerateSerializationCode(io::Printer* printer) const {
  815. printer->Print(variables_,
  816. "if (this.$name$ != null && this.$name$.length > 0) {\n");
  817. printer->Indent();
  818. if (descriptor_->is_packable() && descriptor_->options().packed()) {
  819. GenerateRepeatedDataSizeCode(printer);
  820. printer->Print(variables_,
  821. "output.writeRawVarint32($tag$);\n"
  822. "output.writeRawVarint32(dataSize);\n"
  823. "for (int i = 0; i < this.$name$.length; i++) {\n"
  824. " output.write$capitalized_type$NoTag(this.$name$[i]);\n"
  825. "}\n");
  826. } else if (IsReferenceType(GetJavaType(descriptor_))) {
  827. printer->Print(variables_,
  828. "for (int i = 0; i < this.$name$.length; i++) {\n"
  829. " $type$ element = this.$name$[i];\n"
  830. " if (element != null) {\n"
  831. " output.write$capitalized_type$($number$, element);\n"
  832. " }\n"
  833. "}\n");
  834. } else {
  835. printer->Print(variables_,
  836. "for (int i = 0; i < this.$name$.length; i++) {\n"
  837. " output.write$capitalized_type$($number$, this.$name$[i]);\n"
  838. "}\n");
  839. }
  840. printer->Outdent();
  841. printer->Print("}\n");
  842. }
  843. void RepeatedPrimitiveFieldGenerator::
  844. GenerateSerializedSizeCode(io::Printer* printer) const {
  845. printer->Print(variables_,
  846. "if (this.$name$ != null && this.$name$.length > 0) {\n");
  847. printer->Indent();
  848. GenerateRepeatedDataSizeCode(printer);
  849. printer->Print(
  850. "size += dataSize;\n");
  851. if (descriptor_->is_packable() && descriptor_->options().packed()) {
  852. printer->Print(variables_,
  853. "size += $tag_size$;\n"
  854. "size += com.google.protobuf.nano.CodedOutputByteBufferNano\n"
  855. " .computeRawVarint32Size(dataSize);\n");
  856. } else if (IsReferenceType(GetJavaType(descriptor_))) {
  857. printer->Print(variables_,
  858. "size += $tag_size$ * dataCount;\n");
  859. } else {
  860. printer->Print(variables_,
  861. "size += $tag_size$ * this.$name$.length;\n");
  862. }
  863. printer->Outdent();
  864. printer->Print(
  865. "}\n");
  866. }
  867. void RepeatedPrimitiveFieldGenerator::
  868. GenerateEqualsCode(io::Printer* printer) const {
  869. printer->Print(variables_,
  870. "if (!com.google.protobuf.nano.InternalNano.equals(\n"
  871. " this.$name$, other.$name$)) {\n"
  872. " return false;\n"
  873. "}\n");
  874. }
  875. void RepeatedPrimitiveFieldGenerator::
  876. GenerateHashCodeCode(io::Printer* printer) const {
  877. printer->Print(variables_,
  878. "result = 31 * result\n"
  879. " + com.google.protobuf.nano.InternalNano.hashCode(this.$name$);\n");
  880. }
  881. } // namespace javanano
  882. } // namespace compiler
  883. } // namespace protobuf
  884. } // namespace google