PageRenderTime 81ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/src/cpp/cpp_message.cc

http://protoc-gen-luabind.googlecode.com/
C++ | 1936 lines | 1448 code | 274 blank | 214 comment | 208 complexity | dc8d6074b72f2c5a629ffe6d4c15382d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  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 <algorithm>
  34. #include <google/protobuf/stubs/hash.h>
  35. #include <map>
  36. #include <utility>
  37. #include <vector>
  38. #include "cpp/cpp_message.h"
  39. #include "cpp/cpp_field.h"
  40. #include "cpp/cpp_enum.h"
  41. #include "cpp/cpp_extension.h"
  42. #include "cpp/cpp_helpers.h"
  43. #include <google/protobuf/stubs/strutil.h>
  44. #include <google/protobuf/io/printer.h>
  45. #include <google/protobuf/io/coded_stream.h>
  46. #include <google/protobuf/wire_format.h>
  47. #include <google/protobuf/descriptor.pb.h>
  48. namespace google {
  49. namespace protobuf {
  50. namespace compiler {
  51. namespace cpp {
  52. using internal::WireFormat;
  53. using internal::WireFormatLite;
  54. namespace {
  55. void PrintFieldComment(io::Printer* printer, const FieldDescriptor* field) {
  56. // Print the field's proto-syntax definition as a comment. We don't want to
  57. // print group bodies so we cut off after the first line.
  58. string def = field->DebugString();
  59. printer->Print("// $def$\n",
  60. "def", def.substr(0, def.find_first_of('\n')));
  61. }
  62. struct FieldOrderingByNumber {
  63. inline bool operator()(const FieldDescriptor* a,
  64. const FieldDescriptor* b) const {
  65. return a->number() < b->number();
  66. }
  67. };
  68. const char* kWireTypeNames[] = {
  69. "VARINT",
  70. "FIXED64",
  71. "LENGTH_DELIMITED",
  72. "START_GROUP",
  73. "END_GROUP",
  74. "FIXED32",
  75. };
  76. // Sort the fields of the given Descriptor by number into a new[]'d array
  77. // and return it.
  78. const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
  79. const FieldDescriptor** fields =
  80. new const FieldDescriptor*[descriptor->field_count()];
  81. for (int i = 0; i < descriptor->field_count(); i++) {
  82. fields[i] = descriptor->field(i);
  83. }
  84. sort(fields, fields + descriptor->field_count(),
  85. FieldOrderingByNumber());
  86. return fields;
  87. }
  88. // Functor for sorting extension ranges by their "start" field number.
  89. struct ExtensionRangeSorter {
  90. bool operator()(const Descriptor::ExtensionRange* left,
  91. const Descriptor::ExtensionRange* right) const {
  92. return left->start < right->start;
  93. }
  94. };
  95. // Returns true if the message type has any required fields. If it doesn't,
  96. // we can optimize out calls to its IsInitialized() method.
  97. //
  98. // already_seen is used to avoid checking the same type multiple times
  99. // (and also to protect against recursion).
  100. static bool HasRequiredFields(
  101. const Descriptor* type,
  102. hash_set<const Descriptor*>* already_seen) {
  103. if (already_seen->count(type) > 0) {
  104. // Since the first occurrence of a required field causes the whole
  105. // function to return true, we can assume that if the type is already
  106. // in the cache it didn't have any required fields.
  107. return false;
  108. }
  109. already_seen->insert(type);
  110. // If the type has extensions, an extension with message type could contain
  111. // required fields, so we have to be conservative and assume such an
  112. // extension exists.
  113. if (type->extension_range_count() > 0) return true;
  114. for (int i = 0; i < type->field_count(); i++) {
  115. const FieldDescriptor* field = type->field(i);
  116. if (field->is_required()) {
  117. return true;
  118. }
  119. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  120. if (HasRequiredFields(field->message_type(), already_seen)) {
  121. return true;
  122. }
  123. }
  124. }
  125. return false;
  126. }
  127. static bool HasRequiredFields(const Descriptor* type) {
  128. hash_set<const Descriptor*> already_seen;
  129. return HasRequiredFields(type, &already_seen);
  130. }
  131. // This returns an estimate of the compiler's alignment for the field. This
  132. // can't guarantee to be correct because the generated code could be compiled on
  133. // different systems with different alignment rules. The estimates below assume
  134. // 64-bit pointers.
  135. int EstimateAlignmentSize(const FieldDescriptor* field) {
  136. if (field == NULL) return 0;
  137. if (field->is_repeated()) return 8;
  138. switch (field->cpp_type()) {
  139. case FieldDescriptor::CPPTYPE_BOOL:
  140. return 1;
  141. case FieldDescriptor::CPPTYPE_INT32:
  142. case FieldDescriptor::CPPTYPE_UINT32:
  143. case FieldDescriptor::CPPTYPE_ENUM:
  144. case FieldDescriptor::CPPTYPE_FLOAT:
  145. return 4;
  146. case FieldDescriptor::CPPTYPE_INT64:
  147. case FieldDescriptor::CPPTYPE_UINT64:
  148. case FieldDescriptor::CPPTYPE_DOUBLE:
  149. case FieldDescriptor::CPPTYPE_STRING:
  150. case FieldDescriptor::CPPTYPE_MESSAGE:
  151. return 8;
  152. }
  153. GOOGLE_LOG(FATAL) << "Can't get here.";
  154. return -1; // Make compiler happy.
  155. }
  156. // FieldGroup is just a helper for OptimizePadding below. It holds a vector of
  157. // fields that are grouped together because they have compatible alignment, and
  158. // a preferred location in the final field ordering.
  159. class FieldGroup {
  160. public:
  161. FieldGroup()
  162. : preferred_location_(0) {}
  163. // A group with a single field.
  164. FieldGroup(float preferred_location, const FieldDescriptor* field)
  165. : preferred_location_(preferred_location),
  166. fields_(1, field) {}
  167. // Append the fields in 'other' to this group.
  168. void Append(const FieldGroup& other) {
  169. if (other.fields_.empty()) {
  170. return;
  171. }
  172. // Preferred location is the average among all the fields, so we weight by
  173. // the number of fields on each FieldGroup object.
  174. preferred_location_ =
  175. (preferred_location_ * fields_.size() +
  176. (other.preferred_location_ * other.fields_.size())) /
  177. (fields_.size() + other.fields_.size());
  178. fields_.insert(fields_.end(), other.fields_.begin(), other.fields_.end());
  179. }
  180. void SetPreferredLocation(float location) { preferred_location_ = location; }
  181. const vector<const FieldDescriptor*>& fields() const { return fields_; }
  182. // FieldGroup objects sort by their preferred location.
  183. bool operator<(const FieldGroup& other) const {
  184. return preferred_location_ < other.preferred_location_;
  185. }
  186. private:
  187. // "preferred_location_" is an estimate of where this group should go in the
  188. // final list of fields. We compute this by taking the average index of each
  189. // field in this group in the original ordering of fields. This is very
  190. // approximate, but should put this group close to where its member fields
  191. // originally went.
  192. float preferred_location_;
  193. vector<const FieldDescriptor*> fields_;
  194. // We rely on the default copy constructor and operator= so this type can be
  195. // used in a vector.
  196. };
  197. // Reorder 'fields' so that if the fields are output into a c++ class in the new
  198. // order, the alignment padding is minimized. We try to do this while keeping
  199. // each field as close as possible to its original position so that we don't
  200. // reduce cache locality much for function that access each field in order.
  201. void OptimizePadding(vector<const FieldDescriptor*>* fields) {
  202. // First divide fields into those that align to 1 byte, 4 bytes or 8 bytes.
  203. vector<FieldGroup> aligned_to_1, aligned_to_4, aligned_to_8;
  204. for (int i = 0; i < fields->size(); ++i) {
  205. switch (EstimateAlignmentSize((*fields)[i])) {
  206. case 1: aligned_to_1.push_back(FieldGroup(i, (*fields)[i])); break;
  207. case 4: aligned_to_4.push_back(FieldGroup(i, (*fields)[i])); break;
  208. case 8: aligned_to_8.push_back(FieldGroup(i, (*fields)[i])); break;
  209. default:
  210. GOOGLE_LOG(FATAL) << "Unknown alignment size.";
  211. }
  212. }
  213. // Now group fields aligned to 1 byte into sets of 4, and treat those like a
  214. // single field aligned to 4 bytes.
  215. for (int i = 0; i < aligned_to_1.size(); i += 4) {
  216. FieldGroup field_group;
  217. for (int j = i; j < aligned_to_1.size() && j < i + 4; ++j) {
  218. field_group.Append(aligned_to_1[j]);
  219. }
  220. aligned_to_4.push_back(field_group);
  221. }
  222. // Sort by preferred location to keep fields as close to their original
  223. // location as possible.
  224. sort(aligned_to_4.begin(), aligned_to_4.end());
  225. // Now group fields aligned to 4 bytes (or the 4-field groups created above)
  226. // into pairs, and treat those like a single field aligned to 8 bytes.
  227. for (int i = 0; i < aligned_to_4.size(); i += 2) {
  228. FieldGroup field_group;
  229. for (int j = i; j < aligned_to_4.size() && j < i + 2; ++j) {
  230. field_group.Append(aligned_to_4[j]);
  231. }
  232. if (i == aligned_to_4.size() - 1) {
  233. // Move incomplete 4-byte block to the end.
  234. field_group.SetPreferredLocation(fields->size() + 1);
  235. }
  236. aligned_to_8.push_back(field_group);
  237. }
  238. // Sort by preferred location to keep fields as close to their original
  239. // location as possible.
  240. sort(aligned_to_8.begin(), aligned_to_8.end());
  241. // Now pull out all the FieldDescriptors in order.
  242. fields->clear();
  243. for (int i = 0; i < aligned_to_8.size(); ++i) {
  244. fields->insert(fields->end(),
  245. aligned_to_8[i].fields().begin(),
  246. aligned_to_8[i].fields().end());
  247. }
  248. }
  249. }
  250. // ===================================================================
  251. MessageGenerator::MessageGenerator(const Descriptor* descriptor,
  252. const string& dllexport_decl)
  253. : descriptor_(descriptor),
  254. classname_(ClassName(descriptor, false)),
  255. dllexport_decl_(dllexport_decl),
  256. field_generators_(descriptor),
  257. nested_generators_(new scoped_ptr<MessageGenerator>[
  258. descriptor->nested_type_count()]),
  259. enum_generators_(new scoped_ptr<EnumGenerator>[
  260. descriptor->enum_type_count()]),
  261. extension_generators_(new scoped_ptr<ExtensionGenerator>[
  262. descriptor->extension_count()]) {
  263. for (int i = 0; i < descriptor->nested_type_count(); i++) {
  264. nested_generators_[i].reset(
  265. new MessageGenerator(descriptor->nested_type(i), dllexport_decl));
  266. }
  267. for (int i = 0; i < descriptor->enum_type_count(); i++) {
  268. enum_generators_[i].reset(
  269. new EnumGenerator(descriptor->enum_type(i), dllexport_decl));
  270. }
  271. for (int i = 0; i < descriptor->extension_count(); i++) {
  272. extension_generators_[i].reset(
  273. new ExtensionGenerator(descriptor->extension(i), dllexport_decl));
  274. }
  275. }
  276. MessageGenerator::~MessageGenerator() {}
  277. void MessageGenerator::
  278. GenerateForwardDeclaration(io::Printer* printer) {
  279. printer->Print("class $classname$;\n",
  280. "classname", classname_);
  281. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  282. nested_generators_[i]->GenerateForwardDeclaration(printer);
  283. }
  284. }
  285. void MessageGenerator::
  286. GenerateEnumDefinitions(io::Printer* printer) {
  287. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  288. nested_generators_[i]->GenerateEnumDefinitions(printer);
  289. }
  290. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  291. enum_generators_[i]->GenerateDefinition(printer);
  292. }
  293. }
  294. void MessageGenerator::
  295. GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
  296. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  297. nested_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
  298. }
  299. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  300. enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
  301. }
  302. }
  303. void MessageGenerator::
  304. GenerateFieldAccessorDeclarations(io::Printer* printer) {
  305. for (int i = 0; i < descriptor_->field_count(); i++) {
  306. const FieldDescriptor* field = descriptor_->field(i);
  307. PrintFieldComment(printer, field);
  308. map<string, string> vars;
  309. SetCommonFieldVariables(field, &vars);
  310. vars["constant_name"] = FieldConstantName(field);
  311. if (field->is_repeated()) {
  312. printer->Print(vars, "inline int $name$_size() const$deprecation$;\n");
  313. } else {
  314. printer->Print(vars, "inline bool has_$name$() const$deprecation$;\n");
  315. }
  316. printer->Print(vars, "inline void clear_$name$()$deprecation$;\n");
  317. printer->Print(vars, "static const int $constant_name$ = $number$;\n");
  318. // Generate type-specific accessor declarations.
  319. field_generators_.get(field).GenerateAccessorDeclarations(printer);
  320. printer->Print("\n");
  321. }
  322. if (descriptor_->extension_range_count() > 0) {
  323. // Generate accessors for extensions. We just call a macro located in
  324. // extension_set.h since the accessors about 80 lines of static code.
  325. printer->Print(
  326. "GOOGLE_PROTOBUF_EXTENSION_ACCESSORS($classname$)\n",
  327. "classname", classname_);
  328. }
  329. }
  330. void MessageGenerator::
  331. GenerateFieldAccessorDefinitions(io::Printer* printer) {
  332. printer->Print("// $classname$\n\n", "classname", classname_);
  333. for (int i = 0; i < descriptor_->field_count(); i++) {
  334. const FieldDescriptor* field = descriptor_->field(i);
  335. PrintFieldComment(printer, field);
  336. map<string, string> vars;
  337. SetCommonFieldVariables(field, &vars);
  338. // Generate has_$name$() or $name$_size().
  339. if (field->is_repeated()) {
  340. printer->Print(vars,
  341. "inline int $classname$::$name$_size() const {\n"
  342. " return $name$_.size();\n"
  343. "}\n");
  344. } else {
  345. // Singular field.
  346. char buffer[kFastToBufferSize];
  347. vars["has_array_index"] = SimpleItoa(field->index() / 32);
  348. vars["has_mask"] = FastHex32ToBuffer(1u << (field->index() % 32), buffer);
  349. printer->Print(vars,
  350. "inline bool $classname$::has_$name$() const {\n"
  351. " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"
  352. "}\n"
  353. "inline void $classname$::set_has_$name$() {\n"
  354. " _has_bits_[$has_array_index$] |= 0x$has_mask$u;\n"
  355. "}\n"
  356. "inline void $classname$::clear_has_$name$() {\n"
  357. " _has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n"
  358. "}\n"
  359. );
  360. }
  361. // Generate clear_$name$()
  362. printer->Print(vars,
  363. "inline void $classname$::clear_$name$() {\n");
  364. printer->Indent();
  365. field_generators_.get(field).GenerateClearingCode(printer);
  366. printer->Outdent();
  367. if (!field->is_repeated()) {
  368. printer->Print(vars,
  369. " clear_has_$name$();\n");
  370. }
  371. printer->Print("}\n");
  372. // Generate type-specific accessors.
  373. field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
  374. printer->Print("\n");
  375. }
  376. }
  377. void MessageGenerator::
  378. GenerateClassDefinition(io::Printer* printer) {
  379. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  380. nested_generators_[i]->GenerateClassDefinition(printer);
  381. printer->Print("\n");
  382. printer->Print(kThinSeparator);
  383. printer->Print("\n");
  384. }
  385. map<string, string> vars;
  386. vars["classname"] = classname_;
  387. vars["field_count"] = SimpleItoa(descriptor_->field_count());
  388. if (dllexport_decl_.empty()) {
  389. vars["dllexport"] = "";
  390. } else {
  391. vars["dllexport"] = dllexport_decl_ + " ";
  392. }
  393. vars["superclass"] = SuperClassName(descriptor_);
  394. printer->Print(vars,
  395. "class $dllexport$$classname$ : public $superclass$ {\n"
  396. " public:\n");
  397. printer->Indent();
  398. printer->Print(vars,
  399. "$classname$();\n"
  400. "virtual ~$classname$();\n"
  401. "\n"
  402. "$classname$(const $classname$& from);\n"
  403. "\n"
  404. "inline $classname$& operator=(const $classname$& from) {\n"
  405. " CopyFrom(from);\n"
  406. " return *this;\n"
  407. "}\n"
  408. "\n");
  409. if (HasUnknownFields(descriptor_->file())) {
  410. printer->Print(
  411. "inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {\n"
  412. " return _unknown_fields_;\n"
  413. "}\n"
  414. "\n"
  415. "inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {\n"
  416. " return &_unknown_fields_;\n"
  417. "}\n"
  418. "\n");
  419. }
  420. // Only generate this member if it's not disabled.
  421. if (HasDescriptorMethods(descriptor_->file()) &&
  422. !descriptor_->options().no_standard_descriptor_accessor()) {
  423. printer->Print(vars,
  424. "static const ::google::protobuf::Descriptor* descriptor();\n");
  425. }
  426. printer->Print(vars,
  427. "static const $classname$& default_instance();\n"
  428. "\n");
  429. printer->Print(vars,
  430. "void Swap($classname$* other);\n"
  431. "\n"
  432. "// implements Message ----------------------------------------------\n"
  433. "\n"
  434. "$classname$* New() const;\n");
  435. if (HasGeneratedMethods(descriptor_->file())) {
  436. if (HasDescriptorMethods(descriptor_->file())) {
  437. printer->Print(vars,
  438. "void CopyFrom(const ::google::protobuf::Message& from);\n"
  439. "void MergeFrom(const ::google::protobuf::Message& from);\n");
  440. } else {
  441. printer->Print(vars,
  442. "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);\n");
  443. }
  444. printer->Print(vars,
  445. "void CopyFrom(const $classname$& from);\n"
  446. "void MergeFrom(const $classname$& from);\n"
  447. "void Clear();\n"
  448. "bool IsInitialized() const;\n"
  449. "\n"
  450. "int ByteSize() const;\n"
  451. "bool MergePartialFromCodedStream(\n"
  452. " ::google::protobuf::io::CodedInputStream* input);\n"
  453. "void SerializeWithCachedSizes(\n"
  454. " ::google::protobuf::io::CodedOutputStream* output) const;\n");
  455. if (HasFastArraySerialization(descriptor_->file())) {
  456. printer->Print(
  457. "::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;\n");
  458. }
  459. }
  460. printer->Print(vars,
  461. "int GetCachedSize() const { return _cached_size_; }\n"
  462. "private:\n"
  463. "void SharedCtor();\n"
  464. "void SharedDtor();\n"
  465. "void SetCachedSize(int size) const;\n"
  466. "public:\n"
  467. "\n");
  468. if (HasDescriptorMethods(descriptor_->file())) {
  469. printer->Print(
  470. "::google::protobuf::Metadata GetMetadata() const;\n"
  471. "\n");
  472. } else {
  473. printer->Print(
  474. "::std::string GetTypeName() const;\n"
  475. "\n");
  476. }
  477. printer->Print(
  478. "// nested types ----------------------------------------------------\n"
  479. "\n");
  480. // Import all nested message classes into this class's scope with typedefs.
  481. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  482. const Descriptor* nested_type = descriptor_->nested_type(i);
  483. printer->Print("typedef $nested_full_name$ $nested_name$;\n",
  484. "nested_name", nested_type->name(),
  485. "nested_full_name", ClassName(nested_type, false));
  486. }
  487. if (descriptor_->nested_type_count() > 0) {
  488. printer->Print("\n");
  489. }
  490. // Import all nested enums and their values into this class's scope with
  491. // typedefs and constants.
  492. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  493. enum_generators_[i]->GenerateSymbolImports(printer);
  494. printer->Print("\n");
  495. }
  496. printer->Print(
  497. "// accessors -------------------------------------------------------\n"
  498. "\n");
  499. // Generate accessor methods for all fields.
  500. GenerateFieldAccessorDeclarations(printer);
  501. // Declare extension identifiers.
  502. for (int i = 0; i < descriptor_->extension_count(); i++) {
  503. extension_generators_[i]->GenerateDeclaration(printer);
  504. }
  505. printer->Print(
  506. "// @@protoc_insertion_point(class_scope:$full_name$)\n",
  507. "full_name", descriptor_->full_name());
  508. // Generate private members.
  509. printer->Outdent();
  510. printer->Print(" private:\n");
  511. printer->Indent();
  512. for (int i = 0; i < descriptor_->field_count(); i++) {
  513. if (!descriptor_->field(i)->is_repeated()) {
  514. printer->Print(
  515. "inline void set_has_$name$();\n",
  516. "name", FieldName(descriptor_->field(i)));
  517. printer->Print(
  518. "inline void clear_has_$name$();\n",
  519. "name", FieldName(descriptor_->field(i)));
  520. }
  521. }
  522. printer->Print("\n");
  523. // To minimize padding, data members are divided into three sections:
  524. // (1) members assumed to align to 8 bytes
  525. // (2) members corresponding to message fields, re-ordered to optimize
  526. // alignment.
  527. // (3) members assumed to align to 4 bytes.
  528. // Members assumed to align to 8 bytes:
  529. if (descriptor_->extension_range_count() > 0) {
  530. printer->Print(
  531. "::google::protobuf::internal::ExtensionSet _extensions_;\n"
  532. "\n");
  533. }
  534. if (HasUnknownFields(descriptor_->file())) {
  535. printer->Print(
  536. "::google::protobuf::UnknownFieldSet _unknown_fields_;\n"
  537. "\n");
  538. }
  539. // Field members:
  540. vector<const FieldDescriptor*> fields;
  541. for (int i = 0; i < descriptor_->field_count(); i++) {
  542. fields.push_back(descriptor_->field(i));
  543. }
  544. OptimizePadding(&fields);
  545. for (int i = 0; i < fields.size(); ++i) {
  546. field_generators_.get(fields[i]).GeneratePrivateMembers(printer);
  547. }
  548. // Members assumed to align to 4 bytes:
  549. // TODO(kenton): Make _cached_size_ an atomic<int> when C++ supports it.
  550. printer->Print(
  551. "\n"
  552. "mutable int _cached_size_;\n");
  553. // Generate _has_bits_.
  554. if (descriptor_->field_count() > 0) {
  555. printer->Print(vars,
  556. "::google::protobuf::uint32 _has_bits_[($field_count$ + 31) / 32];\n"
  557. "\n");
  558. } else {
  559. // Zero-size arrays aren't technically allowed, and MSVC in particular
  560. // doesn't like them. We still need to declare these arrays to make
  561. // other code compile. Since this is an uncommon case, we'll just declare
  562. // them with size 1 and waste some space. Oh well.
  563. printer->Print(
  564. "::google::protobuf::uint32 _has_bits_[1];\n"
  565. "\n");
  566. }
  567. // Declare AddDescriptors(), BuildDescriptors(), and ShutdownFile() as
  568. // friends so that they can access private static variables like
  569. // default_instance_ and reflection_.
  570. printer->Print(
  571. "friend void $dllexport_decl$ $adddescriptorsname$();\n",
  572. "dllexport_decl", dllexport_decl_,
  573. "adddescriptorsname",
  574. GlobalAddDescriptorsName(descriptor_->file()->name()));
  575. printer->Print(
  576. "friend void $assigndescriptorsname$();\n"
  577. "friend void $shutdownfilename$();\n"
  578. "\n",
  579. "assigndescriptorsname",
  580. GlobalAssignDescriptorsName(descriptor_->file()->name()),
  581. "shutdownfilename", GlobalShutdownFileName(descriptor_->file()->name()));
  582. printer->Print(
  583. "void InitAsDefaultInstance();\n"
  584. "static $classname$* default_instance_;\n",
  585. "classname", classname_);
  586. GenerateLuaBindDefinition(printer);
  587. printer->Outdent();
  588. printer->Print(vars, "};");
  589. }
  590. void MessageGenerator::
  591. GenerateInlineMethods(io::Printer* printer) {
  592. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  593. nested_generators_[i]->GenerateInlineMethods(printer);
  594. printer->Print(kThinSeparator);
  595. printer->Print("\n");
  596. }
  597. GenerateFieldAccessorDefinitions(printer);
  598. }
  599. void MessageGenerator::
  600. GenerateDescriptorDeclarations(io::Printer* printer) {
  601. printer->Print(
  602. "const ::google::protobuf::Descriptor* $name$_descriptor_ = NULL;\n"
  603. "const ::google::protobuf::internal::GeneratedMessageReflection*\n"
  604. " $name$_reflection_ = NULL;\n",
  605. "name", classname_);
  606. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  607. nested_generators_[i]->GenerateDescriptorDeclarations(printer);
  608. }
  609. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  610. printer->Print(
  611. "const ::google::protobuf::EnumDescriptor* $name$_descriptor_ = NULL;\n",
  612. "name", ClassName(descriptor_->enum_type(i), false));
  613. }
  614. }
  615. void MessageGenerator::
  616. GenerateDescriptorInitializer(io::Printer* printer, int index) {
  617. // TODO(kenton): Passing the index to this method is redundant; just use
  618. // descriptor_->index() instead.
  619. map<string, string> vars;
  620. vars["classname"] = classname_;
  621. vars["index"] = SimpleItoa(index);
  622. // Obtain the descriptor from the parent's descriptor.
  623. if (descriptor_->containing_type() == NULL) {
  624. printer->Print(vars,
  625. "$classname$_descriptor_ = file->message_type($index$);\n");
  626. } else {
  627. vars["parent"] = ClassName(descriptor_->containing_type(), false);
  628. printer->Print(vars,
  629. "$classname$_descriptor_ = "
  630. "$parent$_descriptor_->nested_type($index$);\n");
  631. }
  632. // Generate the offsets.
  633. GenerateOffsets(printer);
  634. // Construct the reflection object.
  635. printer->Print(vars,
  636. "$classname$_reflection_ =\n"
  637. " new ::google::protobuf::internal::GeneratedMessageReflection(\n"
  638. " $classname$_descriptor_,\n"
  639. " $classname$::default_instance_,\n"
  640. " $classname$_offsets_,\n"
  641. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_[0]),\n"
  642. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  643. "$classname$, _unknown_fields_),\n");
  644. if (descriptor_->extension_range_count() > 0) {
  645. printer->Print(vars,
  646. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  647. "$classname$, _extensions_),\n");
  648. } else {
  649. // No extensions.
  650. printer->Print(vars,
  651. " -1,\n");
  652. }
  653. printer->Print(vars,
  654. " ::google::protobuf::DescriptorPool::generated_pool(),\n"
  655. " ::google::protobuf::MessageFactory::generated_factory(),\n"
  656. " sizeof($classname$));\n");
  657. // Handle nested types.
  658. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  659. nested_generators_[i]->GenerateDescriptorInitializer(printer, i);
  660. }
  661. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  662. enum_generators_[i]->GenerateDescriptorInitializer(printer, i);
  663. }
  664. }
  665. void MessageGenerator::
  666. GenerateTypeRegistrations(io::Printer* printer) {
  667. // Register this message type with the message factory.
  668. printer->Print(
  669. "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
  670. " $classname$_descriptor_, &$classname$::default_instance());\n",
  671. "classname", classname_);
  672. // Handle nested types.
  673. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  674. nested_generators_[i]->GenerateTypeRegistrations(printer);
  675. }
  676. }
  677. void MessageGenerator::
  678. GenerateDefaultInstanceAllocator(io::Printer* printer) {
  679. // Construct the default instance. We can't call InitAsDefaultInstance() yet
  680. // because we need to make sure all default instances that this one might
  681. // depend on are constructed first.
  682. printer->Print(
  683. "$classname$::default_instance_ = new $classname$();\n",
  684. "classname", classname_);
  685. // Handle nested types.
  686. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  687. nested_generators_[i]->GenerateDefaultInstanceAllocator(printer);
  688. }
  689. }
  690. void MessageGenerator::
  691. GenerateDefaultInstanceInitializer(io::Printer* printer) {
  692. printer->Print(
  693. "$classname$::default_instance_->InitAsDefaultInstance();\n",
  694. "classname", classname_);
  695. // Register extensions.
  696. for (int i = 0; i < descriptor_->extension_count(); i++) {
  697. extension_generators_[i]->GenerateRegistration(printer);
  698. }
  699. // Handle nested types.
  700. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  701. nested_generators_[i]->GenerateDefaultInstanceInitializer(printer);
  702. }
  703. }
  704. void MessageGenerator::
  705. GenerateShutdownCode(io::Printer* printer) {
  706. printer->Print(
  707. "delete $classname$::default_instance_;\n",
  708. "classname", classname_);
  709. if (HasDescriptorMethods(descriptor_->file())) {
  710. printer->Print(
  711. "delete $classname$_reflection_;\n",
  712. "classname", classname_);
  713. }
  714. // Handle nested types.
  715. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  716. nested_generators_[i]->GenerateShutdownCode(printer);
  717. }
  718. }
  719. void MessageGenerator::
  720. GenerateClassMethods(io::Printer* printer) {
  721. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  722. enum_generators_[i]->GenerateMethods(printer);
  723. }
  724. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  725. nested_generators_[i]->GenerateClassMethods(printer);
  726. printer->Print("\n");
  727. printer->Print(kThinSeparator);
  728. printer->Print("\n");
  729. }
  730. // Generate non-inline field definitions.
  731. for (int i = 0; i < descriptor_->field_count(); i++) {
  732. field_generators_.get(descriptor_->field(i))
  733. .GenerateNonInlineAccessorDefinitions(printer);
  734. }
  735. // Generate field number constants.
  736. printer->Print("#ifndef _MSC_VER\n");
  737. for (int i = 0; i < descriptor_->field_count(); i++) {
  738. const FieldDescriptor *field = descriptor_->field(i);
  739. printer->Print(
  740. "const int $classname$::$constant_name$;\n",
  741. "classname", ClassName(FieldScope(field), false),
  742. "constant_name", FieldConstantName(field));
  743. }
  744. printer->Print(
  745. "#endif // !_MSC_VER\n"
  746. "\n");
  747. // Define extension identifiers.
  748. for (int i = 0; i < descriptor_->extension_count(); i++) {
  749. extension_generators_[i]->GenerateDefinition(printer);
  750. }
  751. GenerateStructors(printer);
  752. printer->Print("\n");
  753. if (HasGeneratedMethods(descriptor_->file())) {
  754. GenerateClear(printer);
  755. printer->Print("\n");
  756. GenerateMergeFromCodedStream(printer);
  757. printer->Print("\n");
  758. GenerateSerializeWithCachedSizes(printer);
  759. printer->Print("\n");
  760. if (HasFastArraySerialization(descriptor_->file())) {
  761. GenerateSerializeWithCachedSizesToArray(printer);
  762. printer->Print("\n");
  763. }
  764. GenerateByteSize(printer);
  765. printer->Print("\n");
  766. GenerateMergeFrom(printer);
  767. printer->Print("\n");
  768. GenerateCopyFrom(printer);
  769. printer->Print("\n");
  770. GenerateIsInitialized(printer);
  771. printer->Print("\n");
  772. }
  773. GenerateSwap(printer);
  774. printer->Print("\n");
  775. if (HasDescriptorMethods(descriptor_->file())) {
  776. printer->Print(
  777. "::google::protobuf::Metadata $classname$::GetMetadata() const {\n"
  778. " protobuf_AssignDescriptorsOnce();\n"
  779. " ::google::protobuf::Metadata metadata;\n"
  780. " metadata.descriptor = $classname$_descriptor_;\n"
  781. " metadata.reflection = $classname$_reflection_;\n"
  782. " return metadata;\n"
  783. "}\n"
  784. "\n",
  785. "classname", classname_);
  786. } else {
  787. printer->Print(
  788. "::std::string $classname$::GetTypeName() const {\n"
  789. " return \"$type_name$\";\n"
  790. "}\n"
  791. "\n",
  792. "classname", classname_,
  793. "type_name", descriptor_->full_name());
  794. }
  795. GenerateLuaBindMethods(printer);
  796. }
  797. void MessageGenerator::
  798. GenerateOffsets(io::Printer* printer) {
  799. printer->Print(
  800. "static const int $classname$_offsets_[$field_count$] = {\n",
  801. "classname", classname_,
  802. "field_count", SimpleItoa(max(1, descriptor_->field_count())));
  803. printer->Indent();
  804. for (int i = 0; i < descriptor_->field_count(); i++) {
  805. const FieldDescriptor* field = descriptor_->field(i);
  806. printer->Print(
  807. "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n",
  808. "classname", classname_,
  809. "name", FieldName(field));
  810. }
  811. printer->Outdent();
  812. printer->Print("};\n");
  813. }
  814. void MessageGenerator::
  815. GenerateSharedConstructorCode(io::Printer* printer) {
  816. printer->Print(
  817. "void $classname$::SharedCtor() {\n",
  818. "classname", classname_);
  819. printer->Indent();
  820. printer->Print(
  821. "_cached_size_ = 0;\n");
  822. for (int i = 0; i < descriptor_->field_count(); i++) {
  823. field_generators_.get(descriptor_->field(i))
  824. .GenerateConstructorCode(printer);
  825. }
  826. printer->Print(
  827. "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
  828. printer->Outdent();
  829. printer->Print("}\n\n");
  830. }
  831. void MessageGenerator::
  832. GenerateSharedDestructorCode(io::Printer* printer) {
  833. printer->Print(
  834. "void $classname$::SharedDtor() {\n",
  835. "classname", classname_);
  836. printer->Indent();
  837. // Write the destructors for each field.
  838. for (int i = 0; i < descriptor_->field_count(); i++) {
  839. field_generators_.get(descriptor_->field(i))
  840. .GenerateDestructorCode(printer);
  841. }
  842. printer->Print(
  843. "if (this != default_instance_) {\n");
  844. // We need to delete all embedded messages.
  845. // TODO(kenton): If we make unset messages point at default instances
  846. // instead of NULL, then it would make sense to move this code into
  847. // MessageFieldGenerator::GenerateDestructorCode().
  848. for (int i = 0; i < descriptor_->field_count(); i++) {
  849. const FieldDescriptor* field = descriptor_->field(i);
  850. if (!field->is_repeated() &&
  851. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  852. printer->Print(" delete $name$_;\n",
  853. "name", FieldName(field));
  854. }
  855. }
  856. printer->Outdent();
  857. printer->Print(
  858. " }\n"
  859. "}\n"
  860. "\n");
  861. }
  862. void MessageGenerator::
  863. GenerateStructors(io::Printer* printer) {
  864. string superclass = SuperClassName(descriptor_);
  865. // Generate the default constructor.
  866. printer->Print(
  867. "$classname$::$classname$()\n"
  868. " : $superclass$() {\n"
  869. " SharedCtor();\n"
  870. "}\n",
  871. "classname", classname_,
  872. "superclass", superclass);
  873. printer->Print(
  874. "\n"
  875. "void $classname$::InitAsDefaultInstance() {\n",
  876. "classname", classname_);
  877. // The default instance needs all of its embedded message pointers
  878. // cross-linked to other default instances. We can't do this initialization
  879. // in the constructor because some other default instances may not have been
  880. // constructed yet at that time.
  881. // TODO(kenton): Maybe all message fields (even for non-default messages)
  882. // should be initialized to point at default instances rather than NULL?
  883. for (int i = 0; i < descriptor_->field_count(); i++) {
  884. const FieldDescriptor* field = descriptor_->field(i);
  885. if (!field->is_repeated() &&
  886. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  887. printer->Print(
  888. " $name$_ = const_cast< $type$*>(&$type$::default_instance());\n",
  889. "name", FieldName(field),
  890. "type", FieldMessageTypeName(field));
  891. }
  892. }
  893. printer->Print(
  894. "}\n"
  895. "\n");
  896. // Generate the copy constructor.
  897. printer->Print(
  898. "$classname$::$classname$(const $classname$& from)\n"
  899. " : $superclass$() {\n"
  900. " SharedCtor();\n"
  901. " MergeFrom(from);\n"
  902. "}\n"
  903. "\n",
  904. "classname", classname_,
  905. "superclass", superclass);
  906. // Generate the shared constructor code.
  907. GenerateSharedConstructorCode(printer);
  908. // Generate the destructor.
  909. printer->Print(
  910. "$classname$::~$classname$() {\n"
  911. " SharedDtor();\n"
  912. "}\n"
  913. "\n",
  914. "classname", classname_);
  915. // Generate the shared destructor code.
  916. GenerateSharedDestructorCode(printer);
  917. // Generate SetCachedSize.
  918. printer->Print(
  919. "void $classname$::SetCachedSize(int size) const {\n"
  920. " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
  921. " _cached_size_ = size;\n"
  922. " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
  923. "}\n",
  924. "classname", classname_);
  925. // Only generate this member if it's not disabled.
  926. if (HasDescriptorMethods(descriptor_->file()) &&
  927. !descriptor_->options().no_standard_descriptor_accessor()) {
  928. printer->Print(
  929. "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
  930. " protobuf_AssignDescriptorsOnce();\n"
  931. " return $classname$_descriptor_;\n"
  932. "}\n"
  933. "\n",
  934. "classname", classname_,
  935. "adddescriptorsname",
  936. GlobalAddDescriptorsName(descriptor_->file()->name()));
  937. }
  938. printer->Print(
  939. "const $classname$& $classname$::default_instance() {\n"
  940. " if (default_instance_ == NULL) $adddescriptorsname$();"
  941. " return *default_instance_;\n"
  942. "}\n"
  943. "\n"
  944. "$classname$* $classname$::default_instance_ = NULL;\n"
  945. "\n"
  946. "$classname$* $classname$::New() const {\n"
  947. " return new $classname$;\n"
  948. "}\n",
  949. "classname", classname_,
  950. "adddescriptorsname",
  951. GlobalAddDescriptorsName(descriptor_->file()->name()));
  952. }
  953. void MessageGenerator::
  954. GenerateClear(io::Printer* printer) {
  955. printer->Print("void $classname$::Clear() {\n",
  956. "classname", classname_);
  957. printer->Indent();
  958. int last_index = -1;
  959. if (descriptor_->extension_range_count() > 0) {
  960. printer->Print("_extensions_.Clear();\n");
  961. }
  962. for (int i = 0; i < descriptor_->field_count(); i++) {
  963. const FieldDescriptor* field = descriptor_->field(i);
  964. if (!field->is_repeated()) {
  965. // We can use the fact that _has_bits_ is a giant bitfield to our
  966. // advantage: We can check up to 32 bits at a time for equality to
  967. // zero, and skip the whole range if so. This can improve the speed
  968. // of Clear() for messages which contain a very large number of
  969. // optional fields of which only a few are used at a time. Here,
  970. // we've chosen to check 8 bits at a time rather than 32.
  971. if (i / 8 != last_index / 8 || last_index < 0) {
  972. if (last_index >= 0) {
  973. printer->Outdent();
  974. printer->Print("}\n");
  975. }
  976. printer->Print(
  977. "if (_has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
  978. "index", SimpleItoa(field->index()));
  979. printer->Indent();
  980. }
  981. last_index = i;
  982. // It's faster to just overwrite primitive types, but we should
  983. // only clear strings and messages if they were set.
  984. // TODO(kenton): Let the CppFieldGenerator decide this somehow.
  985. bool should_check_bit =
  986. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
  987. field->cpp_type() == FieldDescriptor::CPPTYPE_STRING;
  988. if (should_check_bit) {
  989. printer->Print(
  990. "if (has_$name$()) {\n",
  991. "name", FieldName(field));
  992. printer->Indent();
  993. }
  994. field_generators_.get(field).GenerateClearingCode(printer);
  995. if (should_check_bit) {
  996. printer->Outdent();
  997. printer->Print("}\n");
  998. }
  999. }
  1000. }
  1001. if (last_index >= 0) {
  1002. printer->Outdent();
  1003. printer->Print("}\n");
  1004. }
  1005. // Repeated fields don't use _has_bits_ so we clear them in a separate
  1006. // pass.
  1007. for (int i = 0; i < descriptor_->field_count(); i++) {
  1008. const FieldDescriptor* field = descriptor_->field(i);
  1009. if (field->is_repeated()) {
  1010. field_generators_.get(field).GenerateClearingCode(printer);
  1011. }
  1012. }
  1013. printer->Print(
  1014. "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
  1015. if (HasUnknownFields(descriptor_->file())) {
  1016. printer->Print(
  1017. "mutable_unknown_fields()->Clear();\n");
  1018. }
  1019. printer->Outdent();
  1020. printer->Print("}\n");
  1021. }
  1022. void MessageGenerator::
  1023. GenerateSwap(io::Printer* printer) {
  1024. // Generate the Swap member function.
  1025. printer->Print("void $classname$::Swap($classname$* other) {\n",
  1026. "classname", classname_);
  1027. printer->Indent();
  1028. printer->Print("if (other != this) {\n");
  1029. printer->Indent();
  1030. if (HasGeneratedMethods(descriptor_->file())) {
  1031. for (int i = 0; i < descriptor_->field_count(); i++) {
  1032. const FieldDescriptor* field = descriptor_->field(i);
  1033. field_generators_.get(field).GenerateSwappingCode(printer);
  1034. }
  1035. for (int i = 0; i < (descriptor_->field_count() + 31) / 32; ++i) {
  1036. printer->Print("std::swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n",
  1037. "i", SimpleItoa(i));
  1038. }
  1039. if (HasUnknownFields(descriptor_->file())) {
  1040. printer->Print("_unknown_fields_.Swap(&other->_unknown_fields_);\n");
  1041. }
  1042. printer->Print("std::swap(_cached_size_, other->_cached_size_);\n");
  1043. if (descriptor_->extension_range_count() > 0) {
  1044. printer->Print("_extensions_.Swap(&other->_extensions_);\n");
  1045. }
  1046. } else {
  1047. printer->Print("GetReflection()->Swap(this, other);");
  1048. }
  1049. printer->Outdent();
  1050. printer->Print("}\n");
  1051. printer->Outdent();
  1052. printer->Print("}\n");
  1053. }
  1054. void MessageGenerator::
  1055. GenerateMergeFrom(io::Printer* printer) {
  1056. if (HasDescriptorMethods(descriptor_->file())) {
  1057. // Generate the generalized MergeFrom (aka that which takes in the Message
  1058. // base class as a parameter).
  1059. printer->Print(
  1060. "void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n"
  1061. " GOOGLE_CHECK_NE(&from, this);\n",
  1062. "classname", classname_);
  1063. printer->Indent();
  1064. // Cast the message to the proper type. If we find that the message is
  1065. // *not* of the proper type, we can still call Merge via the reflection
  1066. // system, as the GOOGLE_CHECK above ensured that we have the same descriptor
  1067. // for each message.
  1068. printer->Print(
  1069. "const $classname$* source =\n"
  1070. " ::google::protobuf::internal::dynamic_cast_if_available<const $classname$*>(\n"
  1071. " &from);\n"
  1072. "if (source == NULL) {\n"
  1073. " ::google::protobuf::internal::ReflectionOps::Merge(from, this);\n"
  1074. "} else {\n"
  1075. " MergeFrom(*source);\n"
  1076. "}\n",
  1077. "classname", classname_);
  1078. printer->Outdent();
  1079. printer->Print("}\n\n");
  1080. } else {
  1081. // Generate CheckTypeAndMergeFrom().
  1082. printer->Print(
  1083. "void $classname$::CheckTypeAndMergeFrom(\n"
  1084. " const ::google::protobuf::MessageLite& from) {\n"
  1085. " MergeFrom(*::google::protobuf::down_cast<const $classname$*>(&from));\n"
  1086. "}\n"
  1087. "\n",
  1088. "classname", classname_);
  1089. }
  1090. // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast.
  1091. printer->Print(
  1092. "void $classname$::MergeFrom(const $classname$& from) {\n"
  1093. " GOOGLE_CHECK_NE(&from, this);\n",
  1094. "classname", classname_);
  1095. printer->Indent();
  1096. // Merge Repeated fields. These fields do not require a
  1097. // check as we can simply iterate over them.
  1098. for (int i = 0; i < descriptor_->field_count(); ++i) {
  1099. const FieldDescriptor* field = descriptor_->field(i);
  1100. if (field->is_repeated()) {
  1101. field_generators_.get(field).GenerateMergingCode(printer);
  1102. }
  1103. }
  1104. // Merge Optional and Required fields (after a _has_bit check).
  1105. int last_index = -1;
  1106. for (int i = 0; i < descriptor_->field_count(); ++i) {
  1107. const FieldDescriptor* field = descriptor_->field(i);
  1108. if (!field->is_repeated()) {
  1109. // See above in GenerateClear for an explanation of this.
  1110. if (i / 8 != last_index / 8 || last_index < 0) {
  1111. if (last_index >= 0) {
  1112. printer->Outdent();
  1113. printer->Print("}\n");
  1114. }
  1115. printer->Print(
  1116. "if (from._has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
  1117. "index", SimpleItoa(field->index()));
  1118. printer->Indent();
  1119. }
  1120. last_index = i;
  1121. printer->Print(
  1122. "if (from.has_$name$()) {\n",
  1123. "name", FieldName(field));
  1124. printer->Indent();
  1125. field_generators_.get(field).GenerateMergingCode(printer);
  1126. printer->Outdent();
  1127. printer->Print("}\n");
  1128. }
  1129. }
  1130. if (last_index >= 0) {
  1131. printer->Outdent();
  1132. printer->Print("}\n");
  1133. }
  1134. if (descriptor_->extension_range_count() > 0) {
  1135. printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
  1136. }
  1137. if (HasUnknownFields(descriptor_->file())) {
  1138. printer->Print(
  1139. "mutable_unknown_fields()->MergeFrom(from.unknown_fields());\n");
  1140. }
  1141. printer->Outdent();
  1142. printer->Print("}\n");
  1143. }
  1144. void MessageGenerator::
  1145. GenerateCopyFrom(io::Printer* printer) {
  1146. if (HasDescriptorMethods(descriptor_->file())) {
  1147. // Generate the generalized CopyFrom (aka that which takes in the Message
  1148. // base class as a parameter).
  1149. printer->Print(
  1150. "void $classname$::CopyFrom(const ::google::protobuf::Message& from) {\n",
  1151. "classname", classname_);
  1152. printer->Indent();
  1153. printer->Print(
  1154. "if (&from == this) return;\n"
  1155. "Clear();\n"
  1156. "MergeFrom(from);\n");
  1157. printer->Outdent();
  1158. printer->Print("}\n\n");
  1159. }
  1160. // Generate the class-specific CopyFrom.
  1161. printer->Print(
  1162. "void $classname$::CopyFrom(const $classname$& from) {\n",
  1163. "classname", classname_);
  1164. printer->Indent();
  1165. printer->Print(
  1166. "if (&from == this) return;\n"
  1167. "Clear();\n"
  1168. "MergeFrom(from);\n");
  1169. printer->Outdent();
  1170. printer->Print("}\n");
  1171. }
  1172. void MessageGenerator::
  1173. GenerateMergeFromCodedStream(io::Printer* printer) {
  1174. if (descriptor_->options().message_set_wire_format()) {
  1175. // Special-case MessageSet.
  1176. printer->Print(
  1177. "bool $classname$::MergePartialFromCodedStream(\n"
  1178. " ::google::protobuf::io::CodedInputStream* input) {\n"
  1179. " return _extensions_.ParseMessageSet(input, default_instance_,\n"
  1180. " mutable_unknown_fields());\n"
  1181. "}\n",
  1182. "classname", classname_);
  1183. return;
  1184. }
  1185. printer->Print(
  1186. "bool $classname$::MergePartialFromCodedStream(\n"
  1187. " ::google::protobuf::io::CodedInputStream* input) {\n"
  1188. "#define DO_(EXPRESSION) if (!(EXPRESSION)) return false\n"
  1189. " ::google::protobuf::uint32 tag;\n"
  1190. " while ((tag = input->ReadTag()) != 0) {\n",
  1191. "classname", classname_);
  1192. printer->Indent();
  1193. printer->Indent();
  1194. if (descriptor_->field_count() > 0) {
  1195. // We don't even want to print the switch() if we have no fields because
  1196. // MSVC dislikes switch() statements that contain only a default value.
  1197. // Note: If we just switched on the tag rather than the field number, we
  1198. // could avoid the need for the if() to check the wire type at the beginning
  1199. // of each case. However, this is actually a bit slower in practice as it
  1200. // creates a jump table that is 8x larger and sparser, and meanwhile the
  1201. // if()s are highly predictable.
  1202. printer->Print(
  1203. "switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {\n");
  1204. printer->Indent();
  1205. scoped_array<const FieldDescriptor*> ordered_fields(
  1206. SortFieldsByNumber(descriptor_));
  1207. for (int i = 0; i < descriptor_->field_count(); i++) {
  1208. const FieldDescriptor* field = ordered_fields[i];
  1209. PrintFieldComment(printer, field);
  1210. printer->Print(
  1211. "case $number$: {\n",
  1212. "number", SimpleItoa(field->number()));
  1213. printer->Indent();
  1214. const FieldGenerator& field_generator = field_generators_.get(field);
  1215. // Emit code to parse the common, expected case.
  1216. printer->Print(
  1217. "if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
  1218. " ::google::protobuf::internal::WireFormatLite::WIRETYPE_$wiretype$) {\n",
  1219. "wiretype", kWireTypeNames[WireFormat::WireTypeForField(field)]);
  1220. if (i > 0 || (field->is_repeated() && !field->options().packed())) {
  1221. printer->Print(
  1222. " parse_$name$:\n",
  1223. "name", field->name());
  1224. }
  1225. printer->Indent();
  1226. if (field->options().packed()) {
  1227. field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
  1228. } else {
  1229. field_generator.GenerateMergeFromCodedStream(printer);
  1230. }
  1231. printer->Outdent();
  1232. // Emit code to parse unexpectedly packed or unpacked values.
  1233. if (field->is_packable() && field->options().packed()) {
  1234. printer->Print(
  1235. "} else if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag)\n"
  1236. " == ::google::protobuf::internal::WireFormatLite::\n"
  1237. " WIRETYPE_$wiretype$) {\n",
  1238. "wiretype",
  1239. kWireTypeNames[WireFormat::WireTypeForFieldType(field->type())]);
  1240. printer->Indent();
  1241. field_generator.GenerateMergeFromCodedStream(printer);
  1242. printer->Outdent();
  1243. } else if (field->is_packable() && !field->options().packed()) {
  1244. printer->Print(
  1245. "} else if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag)\n"
  1246. " == ::google::protobuf::internal::WireFormatLite::\n"
  1247. " WIRETYPE_LENGTH_DELIMITED) {\n");
  1248. printer->Indent();
  1249. field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
  1250. printer->Outdent();
  1251. }
  1252. printer->Print(
  1253. "} else {\n"
  1254. " goto handle_uninterpreted;\n"
  1255. "}\n");
  1256. // switch() is slow since it can't be predicted well. Insert some if()s
  1257. // here that attempt to predict the next tag.
  1258. if (field->is_repeated() && !field->options().packed()) {
  1259. // Expect repeats of this field.
  1260. printer->Print(
  1261. "if (input->ExpectTag($tag$)) goto parse_$name$;\n",
  1262. "tag", SimpleItoa(WireFormat::MakeTag(field)),
  1263. "name", field->name());
  1264. }
  1265. if (i + 1 < descriptor_->field_count()) {
  1266. // Expect the next field in order.
  1267. const FieldDescriptor* next_field = ordered_fields[i + 1];
  1268. printer->Print(
  1269. "if (input->ExpectTag($next_tag$)) goto parse_$next_name$;\n",
  1270. "next_tag", SimpleItoa(WireFormat::MakeTag(next_field)),
  1271. "next_name", next_field->name());
  1272. } else {
  1273. // Expect EOF.
  1274. // TODO(kenton): Expect group end-tag?
  1275. printer->Print(
  1276. "if (input->ExpectAtEnd()) return true;\n");
  1277. }
  1278. printer->Print(
  1279. "break;\n");
  1280. printer->Outdent();
  1281. printer->Print("}\n\n");
  1282. }
  1283. printer->Print(
  1284. "default: {\n"
  1285. "handle_uninterpreted:\n");
  1286. printer->Indent();
  1287. }
  1288. // Is this an end-group tag? If so, this must be the end of the message.
  1289. printer->Print(
  1290. "if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
  1291. " ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n"
  1292. " return true;\n"
  1293. "}\n");
  1294. // Handle extension ranges.
  1295. if (descriptor_->extension_range_count

Large files files are truncated, but you can click here to view the full file