cpp_message.cc 49 KB

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