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

/thirdparty/breakpad/third_party/protobuf/protobuf/src/google/protobuf/compiler/cpp/cpp_message.cc

http://github.com/tomahawk-player/tomahawk
C++ | 1933 lines | 1446 code | 273 blank | 214 comment | 208 complexity | 6e660f457bf4881f898a9296f8511e20 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, GPL-2.0
  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 <google/protobuf/compiler/cpp/cpp_message.h>
  39. #include <google/protobuf/compiler/cpp/cpp_field.h>
  40. #include <google/protobuf/compiler/cpp/cpp_enum.h>
  41. #include <google/protobuf/compiler/cpp/cpp_extension.h>
  42. #include <google/protobuf/compiler/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. printer->Outdent();
  587. printer->Print(vars, "};");
  588. }
  589. void MessageGenerator::
  590. GenerateInlineMethods(io::Printer* printer) {
  591. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  592. nested_generators_[i]->GenerateInlineMethods(printer);
  593. printer->Print(kThinSeparator);
  594. printer->Print("\n");
  595. }
  596. GenerateFieldAccessorDefinitions(printer);
  597. }
  598. void MessageGenerator::
  599. GenerateDescriptorDeclarations(io::Printer* printer) {
  600. printer->Print(
  601. "const ::google::protobuf::Descriptor* $name$_descriptor_ = NULL;\n"
  602. "const ::google::protobuf::internal::GeneratedMessageReflection*\n"
  603. " $name$_reflection_ = NULL;\n",
  604. "name", classname_);
  605. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  606. nested_generators_[i]->GenerateDescriptorDeclarations(printer);
  607. }
  608. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  609. printer->Print(
  610. "const ::google::protobuf::EnumDescriptor* $name$_descriptor_ = NULL;\n",
  611. "name", ClassName(descriptor_->enum_type(i), false));
  612. }
  613. }
  614. void MessageGenerator::
  615. GenerateDescriptorInitializer(io::Printer* printer, int index) {
  616. // TODO(kenton): Passing the index to this method is redundant; just use
  617. // descriptor_->index() instead.
  618. map<string, string> vars;
  619. vars["classname"] = classname_;
  620. vars["index"] = SimpleItoa(index);
  621. // Obtain the descriptor from the parent's descriptor.
  622. if (descriptor_->containing_type() == NULL) {
  623. printer->Print(vars,
  624. "$classname$_descriptor_ = file->message_type($index$);\n");
  625. } else {
  626. vars["parent"] = ClassName(descriptor_->containing_type(), false);
  627. printer->Print(vars,
  628. "$classname$_descriptor_ = "
  629. "$parent$_descriptor_->nested_type($index$);\n");
  630. }
  631. // Generate the offsets.
  632. GenerateOffsets(printer);
  633. // Construct the reflection object.
  634. printer->Print(vars,
  635. "$classname$_reflection_ =\n"
  636. " new ::google::protobuf::internal::GeneratedMessageReflection(\n"
  637. " $classname$_descriptor_,\n"
  638. " $classname$::default_instance_,\n"
  639. " $classname$_offsets_,\n"
  640. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_[0]),\n"
  641. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  642. "$classname$, _unknown_fields_),\n");
  643. if (descriptor_->extension_range_count() > 0) {
  644. printer->Print(vars,
  645. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  646. "$classname$, _extensions_),\n");
  647. } else {
  648. // No extensions.
  649. printer->Print(vars,
  650. " -1,\n");
  651. }
  652. printer->Print(vars,
  653. " ::google::protobuf::DescriptorPool::generated_pool(),\n"
  654. " ::google::protobuf::MessageFactory::generated_factory(),\n"
  655. " sizeof($classname$));\n");
  656. // Handle nested types.
  657. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  658. nested_generators_[i]->GenerateDescriptorInitializer(printer, i);
  659. }
  660. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  661. enum_generators_[i]->GenerateDescriptorInitializer(printer, i);
  662. }
  663. }
  664. void MessageGenerator::
  665. GenerateTypeRegistrations(io::Printer* printer) {
  666. // Register this message type with the message factory.
  667. printer->Print(
  668. "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
  669. " $classname$_descriptor_, &$classname$::default_instance());\n",
  670. "classname", classname_);
  671. // Handle nested types.
  672. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  673. nested_generators_[i]->GenerateTypeRegistrations(printer);
  674. }
  675. }
  676. void MessageGenerator::
  677. GenerateDefaultInstanceAllocator(io::Printer* printer) {
  678. // Construct the default instance. We can't call InitAsDefaultInstance() yet
  679. // because we need to make sure all default instances that this one might
  680. // depend on are constructed first.
  681. printer->Print(
  682. "$classname$::default_instance_ = new $classname$();\n",
  683. "classname", classname_);
  684. // Handle nested types.
  685. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  686. nested_generators_[i]->GenerateDefaultInstanceAllocator(printer);
  687. }
  688. }
  689. void MessageGenerator::
  690. GenerateDefaultInstanceInitializer(io::Printer* printer) {
  691. printer->Print(
  692. "$classname$::default_instance_->InitAsDefaultInstance();\n",
  693. "classname", classname_);
  694. // Register extensions.
  695. for (int i = 0; i < descriptor_->extension_count(); i++) {
  696. extension_generators_[i]->GenerateRegistration(printer);
  697. }
  698. // Handle nested types.
  699. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  700. nested_generators_[i]->GenerateDefaultInstanceInitializer(printer);
  701. }
  702. }
  703. void MessageGenerator::
  704. GenerateShutdownCode(io::Printer* printer) {
  705. printer->Print(
  706. "delete $classname$::default_instance_;\n",
  707. "classname", classname_);
  708. if (HasDescriptorMethods(descriptor_->file())) {
  709. printer->Print(
  710. "delete $classname$_reflection_;\n",
  711. "classname", classname_);
  712. }
  713. // Handle nested types.
  714. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  715. nested_generators_[i]->GenerateShutdownCode(printer);
  716. }
  717. }
  718. void MessageGenerator::
  719. GenerateClassMethods(io::Printer* printer) {
  720. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  721. enum_generators_[i]->GenerateMethods(printer);
  722. }
  723. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  724. nested_generators_[i]->GenerateClassMethods(printer);
  725. printer->Print("\n");
  726. printer->Print(kThinSeparator);
  727. printer->Print("\n");
  728. }
  729. // Generate non-inline field definitions.
  730. for (int i = 0; i < descriptor_->field_count(); i++) {
  731. field_generators_.get(descriptor_->field(i))
  732. .GenerateNonInlineAccessorDefinitions(printer);
  733. }
  734. // Generate field number constants.
  735. printer->Print("#ifndef _MSC_VER\n");
  736. for (int i = 0; i < descriptor_->field_count(); i++) {
  737. const FieldDescriptor *field = descriptor_->field(i);
  738. printer->Print(
  739. "const int $classname$::$constant_name$;\n",
  740. "classname", ClassName(FieldScope(field), false),
  741. "constant_name", FieldConstantName(field));
  742. }
  743. printer->Print(
  744. "#endif // !_MSC_VER\n"
  745. "\n");
  746. // Define extension identifiers.
  747. for (int i = 0; i < descriptor_->extension_count(); i++) {
  748. extension_generators_[i]->GenerateDefinition(printer);
  749. }
  750. GenerateStructors(printer);
  751. printer->Print("\n");
  752. if (HasGeneratedMethods(descriptor_->file())) {
  753. GenerateClear(printer);
  754. printer->Print("\n");
  755. GenerateMergeFromCodedStream(printer);
  756. printer->Print("\n");
  757. GenerateSerializeWithCachedSizes(printer);
  758. printer->Print("\n");
  759. if (HasFastArraySerialization(descriptor_->file())) {
  760. GenerateSerializeWithCachedSizesToArray(printer);
  761. printer->Print("\n");
  762. }
  763. GenerateByteSize(printer);
  764. printer->Print("\n");
  765. GenerateMergeFrom(printer);
  766. printer->Print("\n");
  767. GenerateCopyFrom(printer);
  768. printer->Print("\n");
  769. GenerateIsInitialized(printer);
  770. printer->Print("\n");
  771. }
  772. GenerateSwap(printer);
  773. printer->Print("\n");
  774. if (HasDescriptorMethods(descriptor_->file())) {
  775. printer->Print(
  776. "::google::protobuf::Metadata $classname$::GetMetadata() const {\n"
  777. " protobuf_AssignDescriptorsOnce();\n"
  778. " ::google::protobuf::Metadata metadata;\n"
  779. " metadata.descriptor = $classname$_descriptor_;\n"
  780. " metadata.reflection = $classname$_reflection_;\n"
  781. " return metadata;\n"
  782. "}\n"
  783. "\n",
  784. "classname", classname_);
  785. } else {
  786. printer->Print(
  787. "::std::string $classname$::GetTypeName() const {\n"
  788. " return \"$type_name$\";\n"
  789. "}\n"
  790. "\n",
  791. "classname", classname_,
  792. "type_name", descriptor_->full_name());
  793. }
  794. }
  795. void MessageGenerator::
  796. GenerateOffsets(io::Printer* printer) {
  797. printer->Print(
  798. "static const int $classname$_offsets_[$field_count$] = {\n",
  799. "classname", classname_,
  800. "field_count", SimpleItoa(max(1, descriptor_->field_count())));
  801. printer->Indent();
  802. for (int i = 0; i < descriptor_->field_count(); i++) {
  803. const FieldDescriptor* field = descriptor_->field(i);
  804. printer->Print(
  805. "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n",
  806. "classname", classname_,
  807. "name", FieldName(field));
  808. }
  809. printer->Outdent();
  810. printer->Print("};\n");
  811. }
  812. void MessageGenerator::
  813. GenerateSharedConstructorCode(io::Printer* printer) {
  814. printer->Print(
  815. "void $classname$::SharedCtor() {\n",
  816. "classname", classname_);
  817. printer->Indent();
  818. printer->Print(
  819. "_cached_size_ = 0;\n");
  820. for (int i = 0; i < descriptor_->field_count(); i++) {
  821. field_generators_.get(descriptor_->field(i))
  822. .GenerateConstructorCode(printer);
  823. }
  824. printer->Print(
  825. "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
  826. printer->Outdent();
  827. printer->Print("}\n\n");
  828. }
  829. void MessageGenerator::
  830. GenerateSharedDestructorCode(io::Printer* printer) {
  831. printer->Print(
  832. "void $classname$::SharedDtor() {\n",
  833. "classname", classname_);
  834. printer->Indent();
  835. // Write the destructors for each field.
  836. for (int i = 0; i < descriptor_->field_count(); i++) {
  837. field_generators_.get(descriptor_->field(i))
  838. .GenerateDestructorCode(printer);
  839. }
  840. printer->Print(
  841. "if (this != default_instance_) {\n");
  842. // We need to delete all embedded messages.
  843. // TODO(kenton): If we make unset messages point at default instances
  844. // instead of NULL, then it would make sense to move this code into
  845. // MessageFieldGenerator::GenerateDestructorCode().
  846. for (int i = 0; i < descriptor_->field_count(); i++) {
  847. const FieldDescriptor* field = descriptor_->field(i);
  848. if (!field->is_repeated() &&
  849. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  850. printer->Print(" delete $name$_;\n",
  851. "name", FieldName(field));
  852. }
  853. }
  854. printer->Outdent();
  855. printer->Print(
  856. " }\n"
  857. "}\n"
  858. "\n");
  859. }
  860. void MessageGenerator::
  861. GenerateStructors(io::Printer* printer) {
  862. string superclass = SuperClassName(descriptor_);
  863. // Generate the default constructor.
  864. printer->Print(
  865. "$classname$::$classname$()\n"
  866. " : $superclass$() {\n"
  867. " SharedCtor();\n"
  868. "}\n",
  869. "classname", classname_,
  870. "superclass", superclass);
  871. printer->Print(
  872. "\n"
  873. "void $classname$::InitAsDefaultInstance() {\n",
  874. "classname", classname_);
  875. // The default instance needs all of its embedded message pointers
  876. // cross-linked to other default instances. We can't do this initialization
  877. // in the constructor because some other default instances may not have been
  878. // constructed yet at that time.
  879. // TODO(kenton): Maybe all message fields (even for non-default messages)
  880. // should be initialized to point at default instances rather than NULL?
  881. for (int i = 0; i < descriptor_->field_count(); i++) {
  882. const FieldDescriptor* field = descriptor_->field(i);
  883. if (!field->is_repeated() &&
  884. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  885. printer->Print(
  886. " $name$_ = const_cast< $type$*>(&$type$::default_instance());\n",
  887. "name", FieldName(field),
  888. "type", FieldMessageTypeName(field));
  889. }
  890. }
  891. printer->Print(
  892. "}\n"
  893. "\n");
  894. // Generate the copy constructor.
  895. printer->Print(
  896. "$classname$::$classname$(const $classname$& from)\n"
  897. " : $superclass$() {\n"
  898. " SharedCtor();\n"
  899. " MergeFrom(from);\n"
  900. "}\n"
  901. "\n",
  902. "classname", classname_,
  903. "superclass", superclass);
  904. // Generate the shared constructor code.
  905. GenerateSharedConstructorCode(printer);
  906. // Generate the destructor.
  907. printer->Print(
  908. "$classname$::~$classname$() {\n"
  909. " SharedDtor();\n"
  910. "}\n"
  911. "\n",
  912. "classname", classname_);
  913. // Generate the shared destructor code.
  914. GenerateSharedDestructorCode(printer);
  915. // Generate SetCachedSize.
  916. printer->Print(
  917. "void $classname$::SetCachedSize(int size) const {\n"
  918. " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
  919. " _cached_size_ = size;\n"
  920. " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
  921. "}\n",
  922. "classname", classname_);
  923. // Only generate this member if it's not disabled.
  924. if (HasDescriptorMethods(descriptor_->file()) &&
  925. !descriptor_->options().no_standard_descriptor_accessor()) {
  926. printer->Print(
  927. "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
  928. " protobuf_AssignDescriptorsOnce();\n"
  929. " return $classname$_descriptor_;\n"
  930. "}\n"
  931. "\n",
  932. "classname", classname_,
  933. "adddescriptorsname",
  934. GlobalAddDescriptorsName(descriptor_->file()->name()));
  935. }
  936. printer->Print(
  937. "const $classname$& $classname$::default_instance() {\n"
  938. " if (default_instance_ == NULL) $adddescriptorsname$();"
  939. " return *default_instance_;\n"
  940. "}\n"
  941. "\n"
  942. "$classname$* $classname$::default_instance_ = NULL;\n"
  943. "\n"
  944. "$classname$* $classname$::New() const {\n"
  945. " return new $classname$;\n"
  946. "}\n",
  947. "classname", classname_,
  948. "adddescriptorsname",
  949. GlobalAddDescriptorsName(descriptor_->file()->name()));
  950. }
  951. void MessageGenerator::
  952. GenerateClear(io::Printer* printer) {
  953. printer->Print("void $classname$::Clear() {\n",
  954. "classname", classname_);
  955. printer->Indent();
  956. int last_index = -1;
  957. if (descriptor_->extension_range_count() > 0) {
  958. printer->Print("_extensions_.Clear();\n");
  959. }
  960. for (int i = 0; i < descriptor_->field_count(); i++) {
  961. const FieldDescriptor* field = descriptor_->field(i);
  962. if (!field->is_repeated()) {
  963. // We can use the fact that _has_bits_ is a giant bitfield to our
  964. // advantage: We can check up to 32 bits at a time for equality to
  965. // zero, and skip the whole range if so. This can improve the speed
  966. // of Clear() for messages which contain a very large number of
  967. // optional fields of which only a few are used at a time. Here,
  968. // we've chosen to check 8 bits at a time rather than 32.
  969. if (i / 8 != last_index / 8 || last_index < 0) {
  970. if (last_index >= 0) {
  971. printer->Outdent();
  972. printer->Print("}\n");
  973. }
  974. printer->Print(
  975. "if (_has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
  976. "index", SimpleItoa(field->index()));
  977. printer->Indent();
  978. }
  979. last_index = i;
  980. // It's faster to just overwrite primitive types, but we should
  981. // only clear strings and messages if they were set.
  982. // TODO(kenton): Let the CppFieldGenerator decide this somehow.
  983. bool should_check_bit =
  984. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
  985. field->cpp_type() == FieldDescriptor::CPPTYPE_STRING;
  986. if (should_check_bit) {
  987. printer->Print(
  988. "if (has_$name$()) {\n",
  989. "name", FieldName(field));
  990. printer->Indent();
  991. }
  992. field_generators_.get(field).GenerateClearingCode(printer);
  993. if (should_check_bit) {
  994. printer->Outdent();
  995. printer->Print("}\n");
  996. }
  997. }
  998. }
  999. if (last_index >= 0) {
  1000. printer->Outdent();
  1001. printer->Print("}\n");
  1002. }
  1003. // Repeated fields don't use _has_bits_ so we clear them in a separate
  1004. // pass.
  1005. for (int i = 0; i < descriptor_->field_count(); i++) {
  1006. const FieldDescriptor* field = descriptor_->field(i);
  1007. if (field->is_repeated()) {
  1008. field_generators_.get(field).GenerateClearingCode(printer);
  1009. }
  1010. }
  1011. printer->Print(
  1012. "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
  1013. if (HasUnknownFields(descriptor_->file())) {
  1014. printer->Print(
  1015. "mutable_unknown_fields()->Clear();\n");
  1016. }
  1017. printer->Outdent();
  1018. printer->Print("}\n");
  1019. }
  1020. void MessageGenerator::
  1021. GenerateSwap(io::Printer* printer) {
  1022. // Generate the Swap member function.
  1023. printer->Print("void $classname$::Swap($classname$* other) {\n",
  1024. "classname", classname_);
  1025. printer->Indent();
  1026. printer->Print("if (other != this) {\n");
  1027. printer->Indent();
  1028. if (HasGeneratedMethods(descriptor_->file())) {
  1029. for (int i = 0; i < descriptor_->field_count(); i++) {
  1030. const FieldDescriptor* field = descriptor_->field(i);
  1031. field_generators_.get(field).GenerateSwappingCode(printer);
  1032. }
  1033. for (int i = 0; i < (descriptor_->field_count() + 31) / 32; ++i) {
  1034. printer->Print("std::swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n",
  1035. "i", SimpleItoa(i));
  1036. }
  1037. if (HasUnknownFields(descriptor_->file())) {
  1038. printer->Print("_unknown_fields_.Swap(&other->_unknown_fields_);\n");
  1039. }
  1040. printer->Print("std::swap(_cached_size_, other->_cached_size_);\n");
  1041. if (descriptor_->extension_range_count() > 0) {
  1042. printer->Print("_extensions_.Swap(&other->_extensions_);\n");
  1043. }
  1044. } else {
  1045. printer->Print("GetReflection()->Swap(this, other);");
  1046. }
  1047. printer->Outdent();
  1048. printer->Print("}\n");
  1049. printer->Outdent();
  1050. printer->Print("}\n");
  1051. }
  1052. void MessageGenerator::
  1053. GenerateMergeFrom(io::Printer* printer) {
  1054. if (HasDescriptorMethods(descriptor_->file())) {
  1055. // Generate the generalized MergeFrom (aka that which takes in the Message
  1056. // base class as a parameter).
  1057. printer->Print(
  1058. "void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n"
  1059. " GOOGLE_CHECK_NE(&from, this);\n",
  1060. "classname", classname_);
  1061. printer->Indent();
  1062. // Cast the message to the proper type. If we find that the message is
  1063. // *not* of the proper type, we can still call Merge via the reflection
  1064. // system, as the GOOGLE_CHECK above ensured that we have the same descriptor
  1065. // for each message.
  1066. printer->Print(
  1067. "const $classname$* source =\n"
  1068. " ::google::protobuf::internal::dynamic_cast_if_available<const $classname$*>(\n"
  1069. " &from);\n"
  1070. "if (source == NULL) {\n"
  1071. " ::google::protobuf::internal::ReflectionOps::Merge(from, this);\n"
  1072. "} else {\n"
  1073. " MergeFrom(*source);\n"
  1074. "}\n",
  1075. "classname", classname_);
  1076. printer->Outdent();
  1077. printer->Print("}\n\n");
  1078. } else {
  1079. // Generate CheckTypeAndMergeFrom().
  1080. printer->Print(
  1081. "void $classname$::CheckTypeAndMergeFrom(\n"
  1082. " const ::google::protobuf::MessageLite& from) {\n"
  1083. " MergeFrom(*::google::protobuf::down_cast<const $classname$*>(&from));\n"
  1084. "}\n"
  1085. "\n",
  1086. "classname", classname_);
  1087. }
  1088. // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast.
  1089. printer->Print(
  1090. "void $classname$::MergeFrom(const $classname$& from) {\n"
  1091. " GOOGLE_CHECK_NE(&from, this);\n",
  1092. "classname", classname_);
  1093. printer->Indent();
  1094. // Merge Repeated fields. These fields do not require a
  1095. // check as we can simply iterate over them.
  1096. for (int i = 0; i < descriptor_->field_count(); ++i) {
  1097. const FieldDescriptor* field = descriptor_->field(i);
  1098. if (field->is_repeated()) {
  1099. field_generators_.get(field).GenerateMergingCode(printer);
  1100. }
  1101. }
  1102. // Merge Optional and Required fields (after a _has_bit check).
  1103. int last_index = -1;
  1104. for (int i = 0; i < descriptor_->field_count(); ++i) {
  1105. const FieldDescriptor* field = descriptor_->field(i);
  1106. if (!field->is_repeated()) {
  1107. // See above in GenerateClear for an explanation of this.
  1108. if (i / 8 != last_index / 8 || last_index < 0) {
  1109. if (last_index >= 0) {
  1110. printer->Outdent();
  1111. printer->Print("}\n");
  1112. }
  1113. printer->Print(
  1114. "if (from._has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
  1115. "index", SimpleItoa(field->index()));
  1116. printer->Indent();
  1117. }
  1118. last_index = i;
  1119. printer->Print(
  1120. "if (from.has_$name$()) {\n",
  1121. "name", FieldName(field));
  1122. printer->Indent();
  1123. field_generators_.get(field).GenerateMergingCode(printer);
  1124. printer->Outdent();
  1125. printer->Print("}\n");
  1126. }
  1127. }
  1128. if (last_index >= 0) {
  1129. printer->Outdent();
  1130. printer->Print("}\n");
  1131. }
  1132. if (descriptor_->extension_range_count() > 0) {
  1133. printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
  1134. }
  1135. if (HasUnknownFields(descriptor_->file())) {
  1136. printer->Print(
  1137. "mutable_unknown_fields()->MergeFrom(from.unknown_fields());\n");
  1138. }
  1139. printer->Outdent();
  1140. printer->Print("}\n");
  1141. }
  1142. void MessageGenerator::
  1143. GenerateCopyFrom(io::Printer* printer) {
  1144. if (HasDescriptorMethods(descriptor_->file())) {
  1145. // Generate the generalized CopyFrom (aka that which takes in the Message
  1146. // base class as a parameter).
  1147. printer->Print(
  1148. "void $classname$::CopyFrom(const ::google::protobuf::Message& from) {\n",
  1149. "classname", classname_);
  1150. printer->Indent();
  1151. printer->Print(
  1152. "if (&from == this) return;\n"
  1153. "Clear();\n"
  1154. "MergeFrom(from);\n");
  1155. printer->Outdent();
  1156. printer->Print("}\n\n");
  1157. }
  1158. // Generate the class-specific CopyFrom.
  1159. printer->Print(
  1160. "void $classname$::CopyFrom(const $classname$& from) {\n",
  1161. "classname", classname_);
  1162. printer->Indent();
  1163. printer->Print(
  1164. "if (&from == this) return;\n"
  1165. "Clear();\n"
  1166. "MergeFrom(from);\n");
  1167. printer->Outdent();
  1168. printer->Print("}\n");
  1169. }
  1170. void MessageGenerator::
  1171. GenerateMergeFromCodedStream(io::Printer* printer) {
  1172. if (descriptor_->options().message_set_wire_format()) {
  1173. // Special-case MessageSet.
  1174. printer->Print(
  1175. "bool $classname$::MergePartialFromCodedStream(\n"
  1176. " ::google::protobuf::io::CodedInputStream* input) {\n"
  1177. " return _extensions_.ParseMessageSet(input, default_instance_,\n"
  1178. " mutable_unknown_fields());\n"
  1179. "}\n",
  1180. "classname", classname_);
  1181. return;
  1182. }
  1183. printer->Print(
  1184. "bool $classname$::MergePartialFromCodedStream(\n"
  1185. " ::google::protobuf::io::CodedInputStream* input) {\n"
  1186. "#define DO_(EXPRESSION) if (!(EXPRESSION)) return false\n"
  1187. " ::google::protobuf::uint32 tag;\n"
  1188. " while ((tag = input->ReadTag()) != 0) {\n",
  1189. "classname", classname_);
  1190. printer->Indent();
  1191. printer->Indent();
  1192. if (descriptor_->field_count() > 0) {
  1193. // We don't even want to print the switch() if we have no fields because
  1194. // MSVC dislikes switch() statements that contain only a default value.
  1195. // Note: If we just switched on the tag rather than the field number, we
  1196. // could avoid the need for the if() to check the wire type at the beginning
  1197. // of each case. However, this is actually a bit slower in practice as it
  1198. // creates a jump table that is 8x larger and sparser, and meanwhile the
  1199. // if()s are highly predictable.
  1200. printer->Print(
  1201. "switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {\n");
  1202. printer->Indent();
  1203. scoped_array<const FieldDescriptor*> ordered_fields(
  1204. SortFieldsByNumber(descriptor_));
  1205. for (int i = 0; i < descriptor_->field_count(); i++) {
  1206. const FieldDescriptor* field = ordered_fields[i];
  1207. PrintFieldComment(printer, field);
  1208. printer->Print(
  1209. "case $number$: {\n",
  1210. "number", SimpleItoa(field->number()));
  1211. printer->Indent();
  1212. const FieldGenerator& field_generator = field_generators_.get(field);
  1213. // Emit code to parse the common, expected case.
  1214. printer->Print(
  1215. "if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
  1216. " ::google::protobuf::internal::WireFormatLite::WIRETYPE_$wiretype$) {\n",
  1217. "wiretype", kWireTypeNames[WireFormat::WireTypeForField(field)]);
  1218. if (i > 0 || (field->is_repeated() && !field->options().packed())) {
  1219. printer->Print(
  1220. " parse_$name$:\n",
  1221. "name", field->name());
  1222. }
  1223. printer->Indent();
  1224. if (field->options().packed()) {
  1225. field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
  1226. } else {
  1227. field_generator.GenerateMergeFromCodedStream(printer);
  1228. }
  1229. printer->Outdent();
  1230. // Emit code to parse unexpectedly packed or unpacked values.
  1231. if (field->is_packable() && field->options().packed()) {
  1232. printer->Print(
  1233. "} else if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag)\n"
  1234. " == ::google::protobuf::internal::WireFormatLite::\n"
  1235. " WIRETYPE_$wiretype$) {\n",
  1236. "wiretype",
  1237. kWireTypeNames[WireFormat::WireTypeForFieldType(field->type())]);
  1238. printer->Indent();
  1239. field_generator.GenerateMergeFromCodedStream(printer);
  1240. printer->Outdent();
  1241. } else if (field->is_packable() && !field->options().packed()) {
  1242. printer->Print(
  1243. "} else if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag)\n"
  1244. " == ::google::protobuf::internal::WireFormatLite::\n"
  1245. " WIRETYPE_LENGTH_DELIMITED) {\n");
  1246. printer->Indent();
  1247. field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
  1248. printer->Outdent();
  1249. }
  1250. printer->Print(
  1251. "} else {\n"
  1252. " goto handle_uninterpreted;\n"
  1253. "}\n");
  1254. // switch() is slow since it can't be predicted well. Insert some if()s
  1255. // here that attempt to predict the next tag.
  1256. if (field->is_repeated() && !field->options().packed()) {
  1257. // Expect repeats of this field.
  1258. printer->Print(
  1259. "if (input->ExpectTag($tag$)) goto parse_$name$;\n",
  1260. "tag", SimpleItoa(WireFormat::MakeTag(field)),
  1261. "name", field->name());
  1262. }
  1263. if (i + 1 < descriptor_->field_count()) {
  1264. // Expect the next field in order.
  1265. const FieldDescriptor* next_field = ordered_fields[i + 1];
  1266. printer->Print(
  1267. "if (input->ExpectTag($next_tag$)) goto parse_$next_name$;\n",
  1268. "next_tag", SimpleItoa(WireFormat::MakeTag(next_field)),
  1269. "next_name", next_field->name());
  1270. } else {
  1271. // Expect EOF.
  1272. // TODO(kenton): Expect group end-tag?
  1273. printer->Print(
  1274. "if (input->ExpectAtEnd()) return true;\n");
  1275. }
  1276. printer->Print(
  1277. "break;\n");
  1278. printer->Outdent();
  1279. printer->Print("}\n\n");
  1280. }
  1281. printer->Print(
  1282. "default: {\n"
  1283. "handle_uninterpreted:\n");
  1284. printer->Indent();
  1285. }
  1286. // Is this an end-group tag? If so, this must be the end of the message.
  1287. printer->Print(
  1288. "if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
  1289. " ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n"
  1290. " return true;\n"
  1291. "}\n");
  1292. // Handle extension ranges.
  1293. if (descriptor_->extension_range_count() > 0) {
  1294. printer->Print(
  1295. "if (");
  1296. for (int i = 0; i < descriptor_->extension_range_count(); i++) {
  1297. const Descriptor::ExtensionRange* range =
  1298. descriptor_->extension_range(i);
  1299. if (i > 0) printer->Print(" ||\n ");
  1300. uint32 start_tag = WireFormatLite::MakeTag(
  1301. range->start, static_cast<WireFormatLite::WireType>(0));
  1302. uint32 end_tag = WireFormatLite::MakeTag(
  1303. range->end, static_cast<WireFormatLite::WireType>(0));
  1304. if (range->end > FieldDescriptor::kMaxNumber) {
  1305. printer->Print(
  1306. "($start$u <= tag)",
  1307. "start", SimpleItoa(start_tag));
  1308. } else {
  1309. printer->Print(
  1310. "($start$u <= tag && tag < $end$u)",
  1311. "start", SimpleItoa(start_tag),
  1312. "end", SimpleItoa(end_tag));
  1313. }
  1314. }
  1315. printer->Print(") {\n");
  1316. if (HasUnknownFields(descriptor_->file())) {
  1317. printer->Print(
  1318. " DO_(_extensions_.ParseField(tag, input, default_instance_,\n"
  1319. " mutable_unknown_fields()));\n");
  1320. } else {
  1321. printer->Print(
  1322. " DO_(_extensions_.ParseField(tag, input, default_instance_));\n");
  1323. }
  1324. printer->Print(
  1325. " continue;\n"
  1326. "}\n");
  1327. }
  1328. // We really don't recognize this tag. Skip it.
  1329. if (HasUnknownFields(descriptor_->file())) {
  1330. printer->Print(
  1331. "DO_(::google::protobuf::internal::WireFormat::SkipField(\n"
  1332. " input, tag, mutable_unknown_fields()));\n");
  1333. } else {
  1334. printer->Print(
  1335. "DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));\n");
  1336. }
  1337. if (descriptor_->field_count() > 0) {
  1338. printer->Print("break;\n");
  1339. printer->Outdent();
  1340. printer->Print("}\n"); // default:
  1341. printer->Outdent();
  1342. printer->Print("}\n"); // switch
  1343. }
  1344. printer->Outdent();
  1345. printer->Outdent();
  1346. printer->Print(
  1347. " }\n" // while
  1348. " return true;\n"
  1349. "#undef DO_\n"
  1350. "}\n");
  1351. }
  1352. void MessageGenerator::GenerateSerializeOneField(
  1353. io::Printer* printer, const FieldDescriptor* field, bool to_array) {
  1354. PrintFieldComment(printer, field);
  1355. if (!field->is_repeated()) {
  1356. printer->Print(
  1357. "if (has_$name$()) {\n",
  1358. "name", FieldName(field));
  1359. printer->Indent();
  1360. }
  1361. if (to_array) {
  1362. field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(
  1363. printer);
  1364. } else {
  1365. field_generators_.get(field).GenerateSerializeWithCachedSizes(printer);
  1366. }
  1367. if (!field->is_repeated()) {
  1368. printer->Outdent();
  1369. printer->Print("}\n");
  1370. }
  1371. printer->Print("\n");
  1372. }
  1373. void MessageGenerator::GenerateSerializeOneExtensionRange(
  1374. io::Printer* printer, const Descriptor::ExtensionRange* range,
  1375. bool to_array) {
  1376. map<string, string> vars;
  1377. vars["start"] = SimpleItoa(range->start);
  1378. vars["end"] = SimpleItoa(range->end);
  1379. printer->Print(vars,
  1380. "// Extension range [$start$, $end$)\n");
  1381. if (to_array) {
  1382. printer->Print(vars,
  1383. "target = _extensions_.SerializeWithCachedSizesToArray(\n"
  1384. " $start$, $end$, target);\n\n");
  1385. } else {
  1386. printer->Print(vars,
  1387. "_extensions_.SerializeWithCachedSizes(\n"
  1388. " $start$, $end$, output);\n\n");
  1389. }
  1390. }
  1391. void MessageGenerator::
  1392. GenerateSerializeWithCachedSizes(io::Printer* printer) {
  1393. if (descriptor_->options().message_set_wire_format()) {
  1394. // Special-case MessageSet.
  1395. printer->Print(
  1396. "void $classname$::SerializeWithCachedSizes(\n"
  1397. " ::google::protobuf::io::CodedOutputStream* output) const {\n"
  1398. " _extensions_.SerializeMessageSetWithCachedSizes(output);\n",
  1399. "classname", classname_);
  1400. if (HasUnknownFields(descriptor_->file())) {
  1401. printer->Print(
  1402. " ::google::protobuf::internal::WireFormat::SerializeUnknownMessageSetItems(\n"
  1403. " unknown_fields(), output);\n");
  1404. }
  1405. printer->Print(
  1406. "}\n");
  1407. return;
  1408. }
  1409. printer->Print(
  1410. "void $classname$::SerializeWithCachedSizes(\n"
  1411. " ::google::protobuf::io::CodedOutputStream* output) const {\n",
  1412. "classname", classname_);
  1413. printer->Indent();
  1414. GenerateSerializeWithCachedSizesBody(printer, false);
  1415. printer->Outdent();
  1416. printer->Print(
  1417. "}\n");
  1418. }
  1419. void MessageGenerator::
  1420. GenerateSerializeWithCachedSizesToArray(io::Printer* printer) {
  1421. if (descriptor_->options().message_set_wire_format()) {
  1422. // Special-case MessageSet.
  1423. printer->Print(
  1424. "::google::protobuf::uint8* $classname$::SerializeWithCachedSizesToArray(\n"
  1425. " ::google::protobuf::uint8* target) const {\n"
  1426. " target =\n"
  1427. " _extensions_.SerializeMessageSetWithCachedSizesToArray(target);\n",
  1428. "classname", classname_);
  1429. if (HasUnknownFields(descriptor_->file())) {
  1430. printer->Print(
  1431. " target = ::google::protobuf::internal::WireFormat::\n"
  1432. " SerializeUnknownMessageSetItemsToArray(\n"
  1433. " unknown_fields(), target);\n");
  1434. }
  1435. printer->Print(
  1436. " return target;\n"
  1437. "}\n");
  1438. return;
  1439. }
  1440. printer->Print(
  1441. "::google::protobuf::uint8* $classname$::SerializeWithCachedSizesToArray(\n"
  1442. " ::google::protobuf::uint8* target) const {\n",
  1443. "classname", classname_);
  1444. printer->Indent();
  1445. GenerateSerializeWithCachedSizesBody(printer, true);
  1446. printer->Outdent();
  1447. printer->Print(
  1448. " return target;\n"
  1449. "}\n");
  1450. }
  1451. void MessageGenerator::
  1452. GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
  1453. scoped_array<const FieldDescriptor*> ordered_fields(
  1454. SortFieldsByNumber(descriptor_));
  1455. vector<const Descriptor::ExtensionRange*> sorted_extensions;
  1456. for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
  1457. sorted_extensions.push_back(descriptor_->extension_range(i));
  1458. }
  1459. sort(sorted_extensions.begin(), sorted_extensions.end(),
  1460. ExtensionRangeSorter());
  1461. // Merge the fields and the extension ranges, both sorted by field number.
  1462. int i, j;
  1463. for (i = 0, j = 0;
  1464. i < descriptor_->field_count() || j < sorted_extensions.size();
  1465. ) {
  1466. if (i == descriptor_->field_count()) {
  1467. GenerateSerializeOneExtensionRange(printer,
  1468. sorted_extensions[j++],
  1469. to_array);
  1470. } else if (j == sorted_extensions.size()) {
  1471. GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
  1472. } else if (ordered_fields[i]->number() < sorted_extensions[j]->start) {
  1473. GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
  1474. } else {
  1475. GenerateSerializeOneExtensionRange(printer,
  1476. sorted_extensions[j++],
  1477. to_array);
  1478. }
  1479. }
  1480. if (HasUnknownFields(descriptor_->file())) {
  1481. printer->Print("if (!unknown_fields().empty()) {\n");
  1482. printer->Indent();
  1483. if (to_array) {
  1484. printer->Print(
  1485. "target = "
  1486. "::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(\n"
  1487. " unknown_fields(), target);\n");
  1488. } else {
  1489. printer->Print(
  1490. "::google::protobuf::internal::WireFormat::SerializeUnknownFields(\n"
  1491. " unknown_fields(), output);\n");
  1492. }
  1493. printer->Outdent();
  1494. printer->Print(
  1495. "}\n");
  1496. }
  1497. }
  1498. void MessageGenerator::
  1499. GenerateByteSize(io::Printer* printer) {
  1500. if (descriptor_->options().message_set_wire_format()) {
  1501. // Special-case MessageSet.
  1502. printer->Print(
  1503. "int $classname$::ByteSize() const {\n"
  1504. " int total_size = _extensions_.MessageSetByteSize();\n",
  1505. "classname", classname_);
  1506. if (HasUnknownFields(descriptor_->file())) {
  1507. printer->Print(
  1508. " total_size += ::google::protobuf::internal::WireFormat::\n"
  1509. " ComputeUnknownMessageSetItemsSize(unknown_fields());\n");
  1510. }
  1511. printer->Print(
  1512. " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
  1513. " _cached_size_ = total_size;\n"
  1514. " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
  1515. " return total_size;\n"
  1516. "}\n");
  1517. return;
  1518. }
  1519. printer->Print(
  1520. "int $classname$::ByteSize() const {\n",
  1521. "classname", classname_);
  1522. printer->Indent();
  1523. printer->Print(
  1524. "int total_size = 0;\n"
  1525. "\n");
  1526. int last_index = -1;
  1527. for (int i = 0; i < descriptor_->field_count(); i++) {
  1528. const FieldDescriptor* field = descriptor_->field(i);
  1529. if (!field->is_repeated()) {
  1530. // See above in GenerateClear for an explanation of this.
  1531. // TODO(kenton): Share code? Unclear how to do so without
  1532. // over-engineering.
  1533. if ((i / 8) != (last_index / 8) ||
  1534. last_index < 0) {
  1535. if (last_index >= 0) {
  1536. printer->Outdent();
  1537. printer->Print("}\n");
  1538. }
  1539. printer->Print(
  1540. "if (_has_bits_[$index$ / 32] & (0xffu << ($index$ % 32))) {\n",
  1541. "index", SimpleItoa(field->index()));
  1542. printer->Indent();
  1543. }
  1544. last_index = i;
  1545. PrintFieldComment(printer, field);
  1546. printer->Print(
  1547. "if (has_$name$()) {\n",
  1548. "name", FieldName(field));
  1549. printer->Indent();
  1550. field_generators_.get(field).GenerateByteSize(printer);
  1551. printer->Outdent();
  1552. printer->Print(
  1553. "}\n"
  1554. "\n");
  1555. }
  1556. }
  1557. if (last_index >= 0) {
  1558. printer->Outdent();
  1559. printer->Print("}\n");
  1560. }
  1561. // Repeated fields don't use _has_bits_ so we count them in a separate
  1562. // pass.
  1563. for (int i = 0; i < descriptor_->field_count(); i++) {
  1564. const FieldDescriptor* field = descriptor_->field(i);
  1565. if (field->is_repeated()) {
  1566. PrintFieldComment(printer, field);
  1567. field_generators_.get(field).GenerateByteSize(printer);
  1568. printer->Print("\n");
  1569. }
  1570. }
  1571. if (descriptor_->extension_range_count() > 0) {
  1572. printer->Print(
  1573. "total_size += _extensions_.ByteSize();\n"
  1574. "\n");
  1575. }
  1576. if (HasUnknownFields(descriptor_->file())) {
  1577. printer->Print("if (!unknown_fields().empty()) {\n");
  1578. printer->Indent();
  1579. printer->Print(
  1580. "total_size +=\n"
  1581. " ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(\n"
  1582. " unknown_fields());\n");
  1583. printer->Outdent();
  1584. printer->Print("}\n");
  1585. }
  1586. // We update _cached_size_ even though this is a const method. In theory,
  1587. // this is not thread-compatible, because concurrent writes have undefined
  1588. // results. In practice, since any concurrent writes will be writing the
  1589. // exact same value, it works on all common processors. In a future version
  1590. // of C++, _cached_size_ should be made into an atomic<int>.
  1591. printer->Print(
  1592. "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
  1593. "_cached_size_ = total_size;\n"
  1594. "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
  1595. "return total_size;\n");
  1596. printer->Outdent();
  1597. printer->Print("}\n");
  1598. }
  1599. void MessageGenerator::
  1600. GenerateIsInitialized(io::Printer* printer) {
  1601. printer->Print(
  1602. "bool $classname$::IsInitialized() const {\n",
  1603. "classname", classname_);
  1604. printer->Indent();
  1605. // Check that all required fields in this message are set. We can do this
  1606. // most efficiently by checking 32 "has bits" at a time.
  1607. int has_bits_array_size = (descriptor_->field_count() + 31) / 32;
  1608. for (int i = 0; i < has_bits_array_size; i++) {
  1609. uint32 mask = 0;
  1610. for (int bit = 0; bit < 32; bit++) {
  1611. int index = i * 32 + bit;
  1612. if (index >= descriptor_->field_count()) break;
  1613. const FieldDescriptor* field = descriptor_->field(index);
  1614. if (field->is_required()) {
  1615. mask |= 1 << bit;
  1616. }
  1617. }
  1618. if (mask != 0) {
  1619. char buffer[kFastToBufferSize];
  1620. printer->Print(
  1621. "if ((_has_bits_[$i$] & 0x$mask$) != 0x$mask$) return false;\n",
  1622. "i", SimpleItoa(i),
  1623. "mask", FastHex32ToBuffer(mask, buffer));
  1624. }
  1625. }
  1626. // Now check that all embedded messages are initialized.
  1627. printer->Print("\n");
  1628. for (int i = 0; i < descriptor_->field_count(); i++) {
  1629. const FieldDescriptor* field = descriptor_->field(i);
  1630. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  1631. HasRequiredFields(field->message_type())) {
  1632. if (field->is_repeated()) {
  1633. printer->Print(
  1634. "for (int i = 0; i < $name$_size(); i++) {\n"
  1635. " if (!this->$name$(i).IsInitialized()) return false;\n"
  1636. "}\n",
  1637. "name", FieldName(field));
  1638. } else {
  1639. printer->Print(
  1640. "if (has_$name$()) {\n"
  1641. " if (!this->$name$().IsInitialized()) return false;\n"
  1642. "}\n",
  1643. "name", FieldName(field));
  1644. }
  1645. }
  1646. }
  1647. if (descriptor_->extension_range_count() > 0) {
  1648. printer->Print(
  1649. "\n"
  1650. "if (!_extensions_.IsInitialized()) return false;");
  1651. }
  1652. printer->Outdent();
  1653. printer->Print(
  1654. " return true;\n"
  1655. "}\n");
  1656. }
  1657. } // namespace cpp
  1658. } // namespace compiler
  1659. } // namespace protobuf
  1660. } // namespace google