cpp_message.cc 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. #include <algorithm>
  34. #include <google/protobuf/stubs/hash.h>
  35. #include <map>
  36. #include <memory>
  37. #ifndef _SHARED_PTR_H
  38. #include <google/protobuf/stubs/shared_ptr.h>
  39. #endif
  40. #include <utility>
  41. #include <vector>
  42. #include <google/protobuf/compiler/cpp/cpp_message.h>
  43. #include <google/protobuf/compiler/cpp/cpp_field.h>
  44. #include <google/protobuf/compiler/cpp/cpp_enum.h>
  45. #include <google/protobuf/compiler/cpp/cpp_extension.h>
  46. #include <google/protobuf/compiler/cpp/cpp_helpers.h>
  47. #include <google/protobuf/stubs/strutil.h>
  48. #include <google/protobuf/io/printer.h>
  49. #include <google/protobuf/io/coded_stream.h>
  50. #include <google/protobuf/wire_format.h>
  51. #include <google/protobuf/descriptor.pb.h>
  52. namespace google {
  53. namespace protobuf {
  54. namespace compiler {
  55. namespace cpp {
  56. using internal::WireFormat;
  57. using internal::WireFormatLite;
  58. namespace {
  59. template <class T>
  60. void PrintFieldComment(io::Printer* printer, const T* field) {
  61. // Print the field's (or oneof's) proto-syntax definition as a comment.
  62. // We don't want to print group bodies so we cut off after the first
  63. // line.
  64. DebugStringOptions options;
  65. options.elide_group_body = true;
  66. options.elide_oneof_body = true;
  67. string def = field->DebugStringWithOptions(options);
  68. printer->Print("// $def$\n",
  69. "def", def.substr(0, def.find_first_of('\n')));
  70. }
  71. struct FieldOrderingByNumber {
  72. inline bool operator()(const FieldDescriptor* a,
  73. const FieldDescriptor* b) const {
  74. return a->number() < b->number();
  75. }
  76. };
  77. // Sort the fields of the given Descriptor by number into a new[]'d array
  78. // and return it.
  79. const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) {
  80. const FieldDescriptor** fields =
  81. new const FieldDescriptor*[descriptor->field_count()];
  82. for (int i = 0; i < descriptor->field_count(); i++) {
  83. fields[i] = descriptor->field(i);
  84. }
  85. std::sort(fields, fields + descriptor->field_count(),
  86. FieldOrderingByNumber());
  87. return fields;
  88. }
  89. // Functor for sorting extension ranges by their "start" field number.
  90. struct ExtensionRangeSorter {
  91. bool operator()(const Descriptor::ExtensionRange* left,
  92. const Descriptor::ExtensionRange* right) const {
  93. return left->start < right->start;
  94. }
  95. };
  96. // Returns true if the "required" restriction check should be ignored for the
  97. // given field.
  98. inline static bool ShouldIgnoreRequiredFieldCheck(
  99. const FieldDescriptor* field) {
  100. return false;
  101. }
  102. // Returns true if the message type has any required fields. If it doesn't,
  103. // we can optimize out calls to its IsInitialized() method.
  104. //
  105. // already_seen is used to avoid checking the same type multiple times
  106. // (and also to protect against recursion).
  107. static bool HasRequiredFields(
  108. const Descriptor* type,
  109. hash_set<const Descriptor*>* already_seen) {
  110. if (already_seen->count(type) > 0) {
  111. // Since the first occurrence of a required field causes the whole
  112. // function to return true, we can assume that if the type is already
  113. // in the cache it didn't have any required fields.
  114. return false;
  115. }
  116. already_seen->insert(type);
  117. // If the type has extensions, an extension with message type could contain
  118. // required fields, so we have to be conservative and assume such an
  119. // extension exists.
  120. if (type->extension_range_count() > 0) return true;
  121. for (int i = 0; i < type->field_count(); i++) {
  122. const FieldDescriptor* field = type->field(i);
  123. if (field->is_required()) {
  124. return true;
  125. }
  126. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  127. !ShouldIgnoreRequiredFieldCheck(field)) {
  128. if (HasRequiredFields(field->message_type(), already_seen)) {
  129. return true;
  130. }
  131. }
  132. }
  133. return false;
  134. }
  135. static bool HasRequiredFields(const Descriptor* type) {
  136. hash_set<const Descriptor*> already_seen;
  137. return HasRequiredFields(type, &already_seen);
  138. }
  139. // This returns an estimate of the compiler's alignment for the field. This
  140. // can't guarantee to be correct because the generated code could be compiled on
  141. // different systems with different alignment rules. The estimates below assume
  142. // 64-bit pointers.
  143. int EstimateAlignmentSize(const FieldDescriptor* field) {
  144. if (field == NULL) return 0;
  145. if (field->is_repeated()) return 8;
  146. switch (field->cpp_type()) {
  147. case FieldDescriptor::CPPTYPE_BOOL:
  148. return 1;
  149. case FieldDescriptor::CPPTYPE_INT32:
  150. case FieldDescriptor::CPPTYPE_UINT32:
  151. case FieldDescriptor::CPPTYPE_ENUM:
  152. case FieldDescriptor::CPPTYPE_FLOAT:
  153. return 4;
  154. case FieldDescriptor::CPPTYPE_INT64:
  155. case FieldDescriptor::CPPTYPE_UINT64:
  156. case FieldDescriptor::CPPTYPE_DOUBLE:
  157. case FieldDescriptor::CPPTYPE_STRING:
  158. case FieldDescriptor::CPPTYPE_MESSAGE:
  159. return 8;
  160. }
  161. GOOGLE_LOG(FATAL) << "Can't get here.";
  162. return -1; // Make compiler happy.
  163. }
  164. // FieldGroup is just a helper for OptimizePadding below. It holds a vector of
  165. // fields that are grouped together because they have compatible alignment, and
  166. // a preferred location in the final field ordering.
  167. class FieldGroup {
  168. public:
  169. FieldGroup()
  170. : preferred_location_(0) {}
  171. // A group with a single field.
  172. FieldGroup(float preferred_location, const FieldDescriptor* field)
  173. : preferred_location_(preferred_location),
  174. fields_(1, field) {}
  175. // Append the fields in 'other' to this group.
  176. void Append(const FieldGroup& other) {
  177. if (other.fields_.empty()) {
  178. return;
  179. }
  180. // Preferred location is the average among all the fields, so we weight by
  181. // the number of fields on each FieldGroup object.
  182. preferred_location_ =
  183. (preferred_location_ * fields_.size() +
  184. (other.preferred_location_ * other.fields_.size())) /
  185. (fields_.size() + other.fields_.size());
  186. fields_.insert(fields_.end(), other.fields_.begin(), other.fields_.end());
  187. }
  188. void SetPreferredLocation(float location) { preferred_location_ = location; }
  189. const vector<const FieldDescriptor*>& fields() const { return fields_; }
  190. // FieldGroup objects sort by their preferred location.
  191. bool operator<(const FieldGroup& other) const {
  192. return preferred_location_ < other.preferred_location_;
  193. }
  194. private:
  195. // "preferred_location_" is an estimate of where this group should go in the
  196. // final list of fields. We compute this by taking the average index of each
  197. // field in this group in the original ordering of fields. This is very
  198. // approximate, but should put this group close to where its member fields
  199. // originally went.
  200. float preferred_location_;
  201. vector<const FieldDescriptor*> fields_;
  202. // We rely on the default copy constructor and operator= so this type can be
  203. // used in a vector.
  204. };
  205. // Reorder 'fields' so that if the fields are output into a c++ class in the new
  206. // order, the alignment padding is minimized. We try to do this while keeping
  207. // each field as close as possible to its original position so that we don't
  208. // reduce cache locality much for function that access each field in order.
  209. void OptimizePadding(vector<const FieldDescriptor*>* fields) {
  210. // First divide fields into those that align to 1 byte, 4 bytes or 8 bytes.
  211. vector<FieldGroup> aligned_to_1, aligned_to_4, aligned_to_8;
  212. for (int i = 0; i < fields->size(); ++i) {
  213. switch (EstimateAlignmentSize((*fields)[i])) {
  214. case 1: aligned_to_1.push_back(FieldGroup(i, (*fields)[i])); break;
  215. case 4: aligned_to_4.push_back(FieldGroup(i, (*fields)[i])); break;
  216. case 8: aligned_to_8.push_back(FieldGroup(i, (*fields)[i])); break;
  217. default:
  218. GOOGLE_LOG(FATAL) << "Unknown alignment size.";
  219. }
  220. }
  221. // Now group fields aligned to 1 byte into sets of 4, and treat those like a
  222. // single field aligned to 4 bytes.
  223. for (int i = 0; i < aligned_to_1.size(); i += 4) {
  224. FieldGroup field_group;
  225. for (int j = i; j < aligned_to_1.size() && j < i + 4; ++j) {
  226. field_group.Append(aligned_to_1[j]);
  227. }
  228. aligned_to_4.push_back(field_group);
  229. }
  230. // Sort by preferred location to keep fields as close to their original
  231. // location as possible. Using stable_sort ensures that the output is
  232. // consistent across runs.
  233. std::stable_sort(aligned_to_4.begin(), aligned_to_4.end());
  234. // Now group fields aligned to 4 bytes (or the 4-field groups created above)
  235. // into pairs, and treat those like a single field aligned to 8 bytes.
  236. for (int i = 0; i < aligned_to_4.size(); i += 2) {
  237. FieldGroup field_group;
  238. for (int j = i; j < aligned_to_4.size() && j < i + 2; ++j) {
  239. field_group.Append(aligned_to_4[j]);
  240. }
  241. if (i == aligned_to_4.size() - 1) {
  242. // Move incomplete 4-byte block to the end.
  243. field_group.SetPreferredLocation(fields->size() + 1);
  244. }
  245. aligned_to_8.push_back(field_group);
  246. }
  247. // Sort by preferred location.
  248. std::stable_sort(aligned_to_8.begin(), aligned_to_8.end());
  249. // Now pull out all the FieldDescriptors in order.
  250. fields->clear();
  251. for (int i = 0; i < aligned_to_8.size(); ++i) {
  252. fields->insert(fields->end(),
  253. aligned_to_8[i].fields().begin(),
  254. aligned_to_8[i].fields().end());
  255. }
  256. }
  257. string MessageTypeProtoName(const FieldDescriptor* field) {
  258. return field->message_type()->full_name();
  259. }
  260. // Emits an if-statement with a condition that evaluates to true if |field| is
  261. // considered non-default (will be sent over the wire), for message types
  262. // without true field presence. Should only be called if
  263. // !HasFieldPresence(message_descriptor).
  264. bool EmitFieldNonDefaultCondition(io::Printer* printer,
  265. const string& prefix,
  266. const FieldDescriptor* field) {
  267. // Merge and serialize semantics: primitive fields are merged/serialized only
  268. // if non-zero (numeric) or non-empty (string).
  269. if (!field->is_repeated() && !field->containing_oneof()) {
  270. if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
  271. printer->Print(
  272. "if ($prefix$$name$().size() > 0) {\n",
  273. "prefix", prefix,
  274. "name", FieldName(field));
  275. } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  276. // Message fields still have has_$name$() methods.
  277. printer->Print(
  278. "if ($prefix$has_$name$()) {\n",
  279. "prefix", prefix,
  280. "name", FieldName(field));
  281. } else {
  282. printer->Print(
  283. "if ($prefix$$name$() != 0) {\n",
  284. "prefix", prefix,
  285. "name", FieldName(field));
  286. }
  287. printer->Indent();
  288. return true;
  289. } else if (field->containing_oneof()) {
  290. printer->Print(
  291. "if (has_$name$()) {\n",
  292. "name", FieldName(field));
  293. printer->Indent();
  294. return true;
  295. }
  296. return false;
  297. }
  298. // Does the given field have a has_$name$() method?
  299. bool HasHasMethod(const FieldDescriptor* field) {
  300. if (HasFieldPresence(field->file())) {
  301. // In proto1/proto2, every field has a has_$name$() method.
  302. return true;
  303. }
  304. // For message types without true field presence, only fields with a message
  305. // type have a has_$name$() method.
  306. return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE;
  307. }
  308. // Collects map entry message type information.
  309. void CollectMapInfo(const Descriptor* descriptor,
  310. map<string, string>* variables) {
  311. GOOGLE_CHECK(IsMapEntryMessage(descriptor));
  312. const FieldDescriptor* key = descriptor->FindFieldByName("key");
  313. const FieldDescriptor* val = descriptor->FindFieldByName("value");
  314. (*variables)["key"] = PrimitiveTypeName(key->cpp_type());
  315. switch (val->cpp_type()) {
  316. case FieldDescriptor::CPPTYPE_MESSAGE:
  317. (*variables)["val"] = FieldMessageTypeName(val);
  318. break;
  319. case FieldDescriptor::CPPTYPE_ENUM:
  320. (*variables)["val"] = ClassName(val->enum_type(), true);
  321. break;
  322. default:
  323. (*variables)["val"] = PrimitiveTypeName(val->cpp_type());
  324. }
  325. (*variables)["key_wire_type"] =
  326. "::google::protobuf::internal::WireFormatLite::TYPE_" +
  327. ToUpper(DeclaredTypeMethodName(key->type()));
  328. (*variables)["val_wire_type"] =
  329. "::google::protobuf::internal::WireFormatLite::TYPE_" +
  330. ToUpper(DeclaredTypeMethodName(val->type()));
  331. }
  332. // Does the given field have a private (internal helper only) has_$name$()
  333. // method?
  334. bool HasPrivateHasMethod(const FieldDescriptor* field) {
  335. // Only for oneofs in message types with no field presence. has_$name$(),
  336. // based on the oneof case, is still useful internally for generated code.
  337. return (!HasFieldPresence(field->file()) &&
  338. field->containing_oneof() != NULL);
  339. }
  340. } // anonymous namespace
  341. // ===================================================================
  342. MessageGenerator::MessageGenerator(const Descriptor* descriptor,
  343. const Options& options)
  344. : descriptor_(descriptor),
  345. classname_(ClassName(descriptor, false)),
  346. options_(options),
  347. field_generators_(descriptor, options),
  348. nested_generators_(new google::protobuf::scoped_ptr<
  349. MessageGenerator>[descriptor->nested_type_count()]),
  350. enum_generators_(
  351. new google::protobuf::scoped_ptr<EnumGenerator>[descriptor->enum_type_count()]),
  352. extension_generators_(new google::protobuf::scoped_ptr<
  353. ExtensionGenerator>[descriptor->extension_count()]),
  354. use_dependent_base_(false) {
  355. for (int i = 0; i < descriptor->nested_type_count(); i++) {
  356. nested_generators_[i].reset(
  357. new MessageGenerator(descriptor->nested_type(i), options));
  358. }
  359. for (int i = 0; i < descriptor->enum_type_count(); i++) {
  360. enum_generators_[i].reset(
  361. new EnumGenerator(descriptor->enum_type(i), options));
  362. }
  363. for (int i = 0; i < descriptor->extension_count(); i++) {
  364. extension_generators_[i].reset(
  365. new ExtensionGenerator(descriptor->extension(i), options));
  366. }
  367. num_required_fields_ = 0;
  368. for (int i = 0; i < descriptor->field_count(); i++) {
  369. if (descriptor->field(i)->is_required()) {
  370. ++num_required_fields_;
  371. }
  372. if (options.proto_h && IsFieldDependent(descriptor->field(i))) {
  373. use_dependent_base_ = true;
  374. }
  375. }
  376. if (options.proto_h && descriptor->oneof_decl_count() > 0) {
  377. // Always make oneofs dependent.
  378. use_dependent_base_ = true;
  379. }
  380. }
  381. MessageGenerator::~MessageGenerator() {}
  382. void MessageGenerator::
  383. FillMessageForwardDeclarations(map<string, const Descriptor*>* class_names) {
  384. (*class_names)[classname_] = descriptor_;
  385. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  386. // map entry message doesn't need forward declaration. Since map entry
  387. // message cannot be a top level class, we just need to avoid calling
  388. // GenerateForwardDeclaration here.
  389. if (IsMapEntryMessage(descriptor_->nested_type(i))) continue;
  390. nested_generators_[i]->FillMessageForwardDeclarations(class_names);
  391. }
  392. }
  393. void MessageGenerator::
  394. FillEnumForwardDeclarations(map<string, const EnumDescriptor*>* enum_names) {
  395. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  396. nested_generators_[i]->FillEnumForwardDeclarations(enum_names);
  397. }
  398. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  399. enum_generators_[i]->FillForwardDeclaration(enum_names);
  400. }
  401. }
  402. void MessageGenerator::
  403. GenerateEnumDefinitions(io::Printer* printer) {
  404. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  405. nested_generators_[i]->GenerateEnumDefinitions(printer);
  406. }
  407. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  408. enum_generators_[i]->GenerateDefinition(printer);
  409. }
  410. }
  411. void MessageGenerator::
  412. GenerateGetEnumDescriptorSpecializations(io::Printer* printer) {
  413. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  414. nested_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
  415. }
  416. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  417. enum_generators_[i]->GenerateGetEnumDescriptorSpecializations(printer);
  418. }
  419. }
  420. void MessageGenerator::
  421. GenerateDependentFieldAccessorDeclarations(io::Printer* printer) {
  422. for (int i = 0; i < descriptor_->field_count(); i++) {
  423. const FieldDescriptor* field = descriptor_->field(i);
  424. PrintFieldComment(printer, field);
  425. map<string, string> vars;
  426. SetCommonFieldVariables(field, &vars, options_);
  427. if (use_dependent_base_ && IsFieldDependent(field)) {
  428. // If the message is dependent, the inline clear_*() method will need
  429. // to delete the message type, so it must be in the dependent base
  430. // class. (See also GenerateFieldAccessorDeclarations.)
  431. printer->Print(vars, "void clear_$name$()$deprecation$;\n");
  432. }
  433. // Generate type-specific accessor declarations.
  434. field_generators_.get(field).GenerateDependentAccessorDeclarations(printer);
  435. printer->Print("\n");
  436. }
  437. }
  438. void MessageGenerator::
  439. GenerateFieldAccessorDeclarations(io::Printer* printer) {
  440. for (int i = 0; i < descriptor_->field_count(); i++) {
  441. const FieldDescriptor* field = descriptor_->field(i);
  442. PrintFieldComment(printer, field);
  443. map<string, string> vars;
  444. SetCommonFieldVariables(field, &vars, options_);
  445. vars["constant_name"] = FieldConstantName(field);
  446. bool dependent_field = use_dependent_base_ && IsFieldDependent(field);
  447. if (dependent_field &&
  448. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  449. !field->is_map()) {
  450. // If this field is dependent, the dependent base class determines
  451. // the message type from the derived class (which is a template
  452. // parameter). This typedef is for that:
  453. printer->Print(
  454. "private:\n"
  455. "typedef $field_type$ $dependent_type$;\n"
  456. "public:\n",
  457. "field_type", FieldMessageTypeName(field),
  458. "dependent_type", DependentTypeName(field));
  459. }
  460. if (field->is_repeated()) {
  461. printer->Print(vars, "int $name$_size() const$deprecation$;\n");
  462. } else if (HasHasMethod(field)) {
  463. printer->Print(vars, "bool has_$name$() const$deprecation$;\n");
  464. } else if (HasPrivateHasMethod(field)) {
  465. printer->Print(vars,
  466. "private:\n"
  467. "bool has_$name$() const$deprecation$;\n"
  468. "public:\n");
  469. }
  470. if (!dependent_field) {
  471. // If this field is dependent, then its clear_() method is in the
  472. // depenent base class. (See also GenerateDependentAccessorDeclarations.)
  473. printer->Print(vars, "void clear_$name$()$deprecation$;\n");
  474. }
  475. printer->Print(vars, "static const int $constant_name$ = $number$;\n");
  476. // Generate type-specific accessor declarations.
  477. field_generators_.get(field).GenerateAccessorDeclarations(printer);
  478. printer->Print("\n");
  479. }
  480. if (descriptor_->extension_range_count() > 0) {
  481. // Generate accessors for extensions. We just call a macro located in
  482. // extension_set.h since the accessors about 80 lines of static code.
  483. printer->Print(
  484. "GOOGLE_PROTOBUF_EXTENSION_ACCESSORS($classname$)\n",
  485. "classname", classname_);
  486. }
  487. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  488. printer->Print(
  489. "$camel_oneof_name$Case $oneof_name$_case() const;\n",
  490. "camel_oneof_name",
  491. UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true),
  492. "oneof_name", descriptor_->oneof_decl(i)->name());
  493. }
  494. }
  495. void MessageGenerator::
  496. GenerateDependentFieldAccessorDefinitions(io::Printer* printer) {
  497. if (!use_dependent_base_) return;
  498. printer->Print("// $classname$\n\n", "classname",
  499. DependentBaseClassTemplateName(descriptor_));
  500. for (int i = 0; i < descriptor_->field_count(); i++) {
  501. const FieldDescriptor* field = descriptor_->field(i);
  502. PrintFieldComment(printer, field);
  503. // These functions are not really dependent: they are part of the
  504. // (non-dependent) derived class. However, they need to live outside
  505. // any #ifdef guards, so we treat them as if they were dependent.
  506. //
  507. // See the comment in FileGenerator::GenerateInlineFunctionDefinitions
  508. // for a more complete explanation.
  509. if (use_dependent_base_ && IsFieldDependent(field)) {
  510. map<string, string> vars;
  511. SetCommonFieldVariables(field, &vars, options_);
  512. vars["inline"] = "inline ";
  513. if (field->containing_oneof()) {
  514. vars["field_name"] = UnderscoresToCamelCase(field->name(), true);
  515. vars["oneof_name"] = field->containing_oneof()->name();
  516. vars["oneof_index"] = SimpleItoa(field->containing_oneof()->index());
  517. GenerateOneofMemberHasBits(field, vars, printer);
  518. } else if (!field->is_repeated()) {
  519. // There will be no header guard, so this always has to be inline.
  520. GenerateSingularFieldHasBits(field, vars, printer);
  521. }
  522. // vars needed for clear_(), which is in the dependent base:
  523. // (See also GenerateDependentFieldAccessorDeclarations.)
  524. vars["tmpl"] = "template<class T>\n";
  525. vars["dependent_classname"] =
  526. DependentBaseClassTemplateName(descriptor_) + "<T>";
  527. vars["this_message"] = DependentBaseDownCast();
  528. vars["this_const_message"] = DependentBaseConstDownCast();
  529. GenerateFieldClear(field, vars, printer);
  530. }
  531. // Generate type-specific accessors.
  532. field_generators_.get(field)
  533. .GenerateDependentInlineAccessorDefinitions(printer);
  534. printer->Print("\n");
  535. }
  536. // Generate has_$name$() and clear_has_$name$() functions for oneofs
  537. // Similar to other has-bits, these must always be in the header if we
  538. // are using a dependent base class.
  539. GenerateOneofHasBits(printer, true /* is_inline */);
  540. }
  541. void MessageGenerator::
  542. GenerateSingularFieldHasBits(const FieldDescriptor* field,
  543. map<string, string> vars,
  544. io::Printer* printer) {
  545. if (HasFieldPresence(descriptor_->file())) {
  546. // N.B.: without field presence, we do not use has-bits or generate
  547. // has_$name$() methods.
  548. vars["has_array_index"] = SimpleItoa(field->index() / 32);
  549. vars["has_mask"] = StrCat(strings::Hex(1u << (field->index() % 32),
  550. strings::ZERO_PAD_8));
  551. printer->Print(vars,
  552. "$inline$"
  553. "bool $classname$::has_$name$() const {\n"
  554. " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"
  555. "}\n"
  556. "$inline$"
  557. "void $classname$::set_has_$name$() {\n"
  558. " _has_bits_[$has_array_index$] |= 0x$has_mask$u;\n"
  559. "}\n"
  560. "$inline$"
  561. "void $classname$::clear_has_$name$() {\n"
  562. " _has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n"
  563. "}\n");
  564. } else {
  565. // Message fields have a has_$name$() method.
  566. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  567. bool is_lazy = false;
  568. if (is_lazy) {
  569. printer->Print(vars,
  570. "$inline$"
  571. "bool $classname$::has_$name$() const {\n"
  572. " return !$name$_.IsCleared();\n"
  573. "}\n");
  574. } else {
  575. printer->Print(vars,
  576. "$inline$"
  577. "bool $classname$::has_$name$() const {\n"
  578. " return !_is_default_instance_ && $name$_ != NULL;\n"
  579. "}\n");
  580. }
  581. }
  582. }
  583. }
  584. void MessageGenerator::
  585. GenerateOneofHasBits(io::Printer* printer, bool is_inline) {
  586. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  587. map<string, string> vars;
  588. vars["oneof_name"] = descriptor_->oneof_decl(i)->name();
  589. vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
  590. vars["cap_oneof_name"] =
  591. ToUpper(descriptor_->oneof_decl(i)->name());
  592. vars["classname"] = classname_;
  593. vars["inline"] = (is_inline ? "inline " : "");
  594. printer->Print(
  595. vars,
  596. "$inline$"
  597. "bool $classname$::has_$oneof_name$() const {\n"
  598. " return $oneof_name$_case() != $cap_oneof_name$_NOT_SET;\n"
  599. "}\n"
  600. "$inline$"
  601. "void $classname$::clear_has_$oneof_name$() {\n"
  602. " _oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n"
  603. "}\n");
  604. }
  605. }
  606. void MessageGenerator::
  607. GenerateOneofMemberHasBits(const FieldDescriptor* field,
  608. const map<string, string>& vars,
  609. io::Printer* printer) {
  610. // Singular field in a oneof
  611. // N.B.: Without field presence, we do not use has-bits or generate
  612. // has_$name$() methods, but oneofs still have set_has_$name$().
  613. // Oneofs also have has_$name$() but only as a private helper
  614. // method, so that generated code is slightly cleaner (vs. comparing
  615. // _oneof_case_[index] against a constant everywhere).
  616. printer->Print(vars,
  617. "$inline$"
  618. "bool $classname$::has_$name$() const {\n"
  619. " return $oneof_name$_case() == k$field_name$;\n"
  620. "}\n");
  621. printer->Print(vars,
  622. "$inline$"
  623. "void $classname$::set_has_$name$() {\n"
  624. " _oneof_case_[$oneof_index$] = k$field_name$;\n"
  625. "}\n");
  626. }
  627. void MessageGenerator::
  628. GenerateFieldClear(const FieldDescriptor* field,
  629. const map<string, string>& vars,
  630. io::Printer* printer) {
  631. // Generate clear_$name$() (See GenerateFieldAccessorDeclarations and
  632. // GenerateDependentFieldAccessorDeclarations, $dependent_classname$ is
  633. // set by the Generate*Definitions functions.)
  634. printer->Print(vars,
  635. "$tmpl$"
  636. "$inline$"
  637. "void $dependent_classname$::clear_$name$() {\n");
  638. printer->Indent();
  639. if (field->containing_oneof()) {
  640. // Clear this field only if it is the active field in this oneof,
  641. // otherwise ignore
  642. printer->Print(vars,
  643. "if ($this_message$has_$name$()) {\n");
  644. printer->Indent();
  645. field_generators_.get(field)
  646. .GenerateClearingCode(printer);
  647. printer->Print(vars,
  648. "$this_message$clear_has_$oneof_name$();\n");
  649. printer->Outdent();
  650. printer->Print("}\n");
  651. } else {
  652. field_generators_.get(field)
  653. .GenerateClearingCode(printer);
  654. if (HasFieldPresence(descriptor_->file())) {
  655. if (!field->is_repeated()) {
  656. printer->Print(vars,
  657. "$this_message$clear_has_$name$();\n");
  658. }
  659. }
  660. }
  661. printer->Outdent();
  662. printer->Print("}\n");
  663. }
  664. void MessageGenerator::
  665. GenerateFieldAccessorDefinitions(io::Printer* printer, bool is_inline) {
  666. printer->Print("// $classname$\n\n", "classname", classname_);
  667. for (int i = 0; i < descriptor_->field_count(); i++) {
  668. const FieldDescriptor* field = descriptor_->field(i);
  669. PrintFieldComment(printer, field);
  670. map<string, string> vars;
  671. SetCommonFieldVariables(field, &vars, options_);
  672. vars["inline"] = is_inline ? "inline " : "";
  673. if (use_dependent_base_ && IsFieldDependent(field)) {
  674. vars["tmpl"] = "template<class T>\n";
  675. vars["dependent_classname"] =
  676. DependentBaseClassTemplateName(descriptor_) + "<T>";
  677. vars["this_message"] = "reinterpret_cast<T*>(this)->";
  678. vars["this_const_message"] = "reinterpret_cast<const T*>(this)->";
  679. } else {
  680. vars["tmpl"] = "";
  681. vars["dependent_classname"] = vars["classname"];
  682. vars["this_message"] = "";
  683. vars["this_const_message"] = "";
  684. }
  685. // Generate has_$name$() or $name$_size().
  686. if (field->is_repeated()) {
  687. printer->Print(vars,
  688. "$inline$"
  689. "int $classname$::$name$_size() const {\n"
  690. " return $name$_.size();\n"
  691. "}\n");
  692. } else if (field->containing_oneof()) {
  693. vars["field_name"] = UnderscoresToCamelCase(field->name(), true);
  694. vars["oneof_name"] = field->containing_oneof()->name();
  695. vars["oneof_index"] = SimpleItoa(field->containing_oneof()->index());
  696. if (!use_dependent_base_ || !IsFieldDependent(field)) {
  697. GenerateOneofMemberHasBits(field, vars, printer);
  698. }
  699. } else {
  700. // Singular field.
  701. if (!use_dependent_base_ || !IsFieldDependent(field)) {
  702. GenerateSingularFieldHasBits(field, vars, printer);
  703. }
  704. }
  705. if (!use_dependent_base_ || !IsFieldDependent(field)) {
  706. GenerateFieldClear(field, vars, printer);
  707. }
  708. // Generate type-specific accessors.
  709. field_generators_.get(field).GenerateInlineAccessorDefinitions(printer,
  710. is_inline);
  711. printer->Print("\n");
  712. }
  713. if (!use_dependent_base_) {
  714. // Generate has_$name$() and clear_has_$name$() functions for oneofs
  715. // If we aren't using a dependent base, they can be with the other functions
  716. // that are #ifdef-guarded.
  717. GenerateOneofHasBits(printer, is_inline);
  718. }
  719. }
  720. // Helper for the code that emits the Clear() method.
  721. static bool CanClearByZeroing(const FieldDescriptor* field) {
  722. if (field->is_repeated() || field->is_extension()) return false;
  723. switch (field->cpp_type()) {
  724. case internal::WireFormatLite::CPPTYPE_ENUM:
  725. return field->default_value_enum()->number() == 0;
  726. case internal::WireFormatLite::CPPTYPE_INT32:
  727. return field->default_value_int32() == 0;
  728. case internal::WireFormatLite::CPPTYPE_INT64:
  729. return field->default_value_int64() == 0;
  730. case internal::WireFormatLite::CPPTYPE_UINT32:
  731. return field->default_value_uint32() == 0;
  732. case internal::WireFormatLite::CPPTYPE_UINT64:
  733. return field->default_value_uint64() == 0;
  734. case internal::WireFormatLite::CPPTYPE_FLOAT:
  735. return field->default_value_float() == 0;
  736. case internal::WireFormatLite::CPPTYPE_DOUBLE:
  737. return field->default_value_double() == 0;
  738. case internal::WireFormatLite::CPPTYPE_BOOL:
  739. return field->default_value_bool() == false;
  740. default:
  741. return false;
  742. }
  743. }
  744. void MessageGenerator::
  745. GenerateDependentBaseClassDefinition(io::Printer* printer) {
  746. if (!use_dependent_base_) {
  747. return;
  748. }
  749. map<string, string> vars;
  750. vars["classname"] = DependentBaseClassTemplateName(descriptor_);
  751. vars["superclass"] = SuperClassName(descriptor_);
  752. printer->Print(vars,
  753. "template <class T>\n"
  754. "class $classname$ : public $superclass$ {\n"
  755. " public:\n");
  756. printer->Indent();
  757. printer->Print(vars,
  758. "$classname$() {}\n"
  759. "virtual ~$classname$() {}\n"
  760. "\n");
  761. // Generate dependent accessor methods for all fields.
  762. GenerateDependentFieldAccessorDeclarations(printer);
  763. printer->Outdent();
  764. printer->Print("};\n");
  765. }
  766. void MessageGenerator::
  767. GenerateClassDefinition(io::Printer* printer) {
  768. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  769. // map entry message doesn't need class definition. Since map entry message
  770. // cannot be a top level class, we just need to avoid calling
  771. // GenerateClassDefinition here.
  772. if (IsMapEntryMessage(descriptor_->nested_type(i))) continue;
  773. nested_generators_[i]->GenerateClassDefinition(printer);
  774. printer->Print("\n");
  775. printer->Print(kThinSeparator);
  776. printer->Print("\n");
  777. }
  778. if (use_dependent_base_) {
  779. GenerateDependentBaseClassDefinition(printer);
  780. printer->Print("\n");
  781. }
  782. map<string, string> vars;
  783. vars["classname"] = classname_;
  784. vars["field_count"] = SimpleItoa(descriptor_->field_count());
  785. vars["oneof_decl_count"] = SimpleItoa(descriptor_->oneof_decl_count());
  786. if (options_.dllexport_decl.empty()) {
  787. vars["dllexport"] = "";
  788. } else {
  789. vars["dllexport"] = options_.dllexport_decl + " ";
  790. }
  791. if (use_dependent_base_) {
  792. vars["superclass"] =
  793. DependentBaseClassTemplateName(descriptor_) + "<" + classname_ + ">";
  794. } else {
  795. vars["superclass"] = SuperClassName(descriptor_);
  796. }
  797. printer->Print(vars,
  798. "class $dllexport$$classname$ : public $superclass$ {\n");
  799. printer->Annotate("classname", descriptor_);
  800. if (use_dependent_base_) {
  801. printer->Print(vars, " friend class $superclass$;\n");
  802. }
  803. printer->Print(" public:\n");
  804. printer->Indent();
  805. printer->Print(vars,
  806. "$classname$();\n"
  807. "virtual ~$classname$();\n"
  808. "\n"
  809. "$classname$(const $classname$& from);\n"
  810. "\n"
  811. "inline $classname$& operator=(const $classname$& from) {\n"
  812. " CopyFrom(from);\n"
  813. " return *this;\n"
  814. "}\n"
  815. "\n");
  816. if (PreserveUnknownFields(descriptor_)) {
  817. if (UseUnknownFieldSet(descriptor_->file())) {
  818. printer->Print(
  819. "inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {\n"
  820. " return _internal_metadata_.unknown_fields();\n"
  821. "}\n"
  822. "\n"
  823. "inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {\n"
  824. " return _internal_metadata_.mutable_unknown_fields();\n"
  825. "}\n"
  826. "\n");
  827. } else {
  828. if (SupportsArenas(descriptor_)) {
  829. printer->Print(
  830. "inline const ::std::string& unknown_fields() const {\n"
  831. " return _unknown_fields_.Get(\n"
  832. " &::google::protobuf::internal::GetEmptyStringAlreadyInited());\n"
  833. "}\n"
  834. "\n"
  835. "inline ::std::string* mutable_unknown_fields() {\n"
  836. " return _unknown_fields_.Mutable(\n"
  837. " &::google::protobuf::internal::GetEmptyStringAlreadyInited(),\n"
  838. " GetArenaNoVirtual());\n"
  839. "}\n"
  840. "\n");
  841. } else {
  842. printer->Print(
  843. "inline const ::std::string& unknown_fields() const {\n"
  844. " return _unknown_fields_.GetNoArena(\n"
  845. " &::google::protobuf::internal::GetEmptyStringAlreadyInited());\n"
  846. "}\n"
  847. "\n"
  848. "inline ::std::string* mutable_unknown_fields() {\n"
  849. " return _unknown_fields_.MutableNoArena(\n"
  850. " &::google::protobuf::internal::GetEmptyStringAlreadyInited());\n"
  851. "}\n"
  852. "\n");
  853. }
  854. }
  855. }
  856. // N.B.: We exclude GetArena() when arena support is disabled, falling back on
  857. // MessageLite's implementation which returns NULL rather than generating our
  858. // own method which returns NULL, in order to reduce code size.
  859. if (SupportsArenas(descriptor_)) {
  860. // virtual method version of GetArenaNoVirtual(), required for generic dispatch given a
  861. // MessageLite* (e.g., in RepeatedField::AddAllocated()).
  862. printer->Print(
  863. "inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }\n"
  864. "inline void* GetMaybeArenaPointer() const {\n"
  865. " return MaybeArenaPtr();\n"
  866. "}\n");
  867. }
  868. // Only generate this member if it's not disabled.
  869. if (HasDescriptorMethods(descriptor_->file()) &&
  870. !descriptor_->options().no_standard_descriptor_accessor()) {
  871. printer->Print(vars,
  872. "static const ::google::protobuf::Descriptor* descriptor();\n");
  873. }
  874. printer->Print(vars,
  875. "static const $classname$& default_instance();\n"
  876. "\n");
  877. // Generate enum values for every field in oneofs. One list is generated for
  878. // each oneof with an additional *_NOT_SET value.
  879. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  880. printer->Print(
  881. "enum $camel_oneof_name$Case {\n",
  882. "camel_oneof_name",
  883. UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true));
  884. printer->Indent();
  885. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  886. printer->Print(
  887. "k$field_name$ = $field_number$,\n",
  888. "field_name",
  889. UnderscoresToCamelCase(
  890. descriptor_->oneof_decl(i)->field(j)->name(), true),
  891. "field_number",
  892. SimpleItoa(descriptor_->oneof_decl(i)->field(j)->number()));
  893. }
  894. printer->Print(
  895. "$cap_oneof_name$_NOT_SET = 0,\n",
  896. "cap_oneof_name",
  897. ToUpper(descriptor_->oneof_decl(i)->name()));
  898. printer->Outdent();
  899. printer->Print(
  900. "};\n"
  901. "\n");
  902. }
  903. if (!StaticInitializersForced(descriptor_->file())) {
  904. printer->Print(vars,
  905. "#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER\n"
  906. "// Returns the internal default instance pointer. This function can\n"
  907. "// return NULL thus should not be used by the user. This is intended\n"
  908. "// for Protobuf internal code. Please use default_instance() declared\n"
  909. "// above instead.\n"
  910. "static inline const $classname$* internal_default_instance() {\n"
  911. " return default_instance_;\n"
  912. "}\n"
  913. "#endif\n"
  914. "\n");
  915. }
  916. if (SupportsArenas(descriptor_)) {
  917. printer->Print(vars,
  918. "void UnsafeArenaSwap($classname$* other);\n");
  919. }
  920. if (IsAnyMessage(descriptor_)) {
  921. printer->Print(vars,
  922. "// implements Any -----------------------------------------------\n"
  923. "\n"
  924. "void PackFrom(const ::google::protobuf::Message& message);\n"
  925. "void PackFrom(const ::google::protobuf::Message& message,\n"
  926. " const ::std::string& type_url_prefix);\n"
  927. "bool UnpackTo(::google::protobuf::Message* message) const;\n"
  928. "template<typename T> bool Is() const {\n"
  929. " return _any_metadata_.Is<T>();\n"
  930. "}\n"
  931. "\n");
  932. }
  933. printer->Print(vars,
  934. "void Swap($classname$* other);\n"
  935. "\n"
  936. "// implements Message ----------------------------------------------\n"
  937. "\n"
  938. "inline $classname$* New() const { return New(NULL); }\n"
  939. "\n"
  940. "$classname$* New(::google::protobuf::Arena* arena) const;\n");
  941. if (HasGeneratedMethods(descriptor_->file())) {
  942. if (HasDescriptorMethods(descriptor_->file())) {
  943. printer->Print(vars,
  944. "void CopyFrom(const ::google::protobuf::Message& from);\n"
  945. "void MergeFrom(const ::google::protobuf::Message& from);\n");
  946. } else {
  947. printer->Print(vars,
  948. "void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from);\n");
  949. }
  950. printer->Print(vars,
  951. "void CopyFrom(const $classname$& from);\n"
  952. "void MergeFrom(const $classname$& from);\n"
  953. "void Clear();\n"
  954. "bool IsInitialized() const;\n"
  955. "\n"
  956. "int ByteSize() const;\n"
  957. "bool MergePartialFromCodedStream(\n"
  958. " ::google::protobuf::io::CodedInputStream* input);\n"
  959. "void SerializeWithCachedSizes(\n"
  960. " ::google::protobuf::io::CodedOutputStream* output) const;\n");
  961. // DiscardUnknownFields() is implemented in message.cc using reflections. We
  962. // need to implement this function in generated code for messages.
  963. if (!UseUnknownFieldSet(descriptor_->file())) {
  964. printer->Print(
  965. "void DiscardUnknownFields();\n");
  966. }
  967. if (HasFastArraySerialization(descriptor_->file())) {
  968. printer->Print(
  969. "::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;\n");
  970. }
  971. }
  972. // Check all FieldDescriptors including those in oneofs to estimate
  973. // whether ::std::string is likely to be used, and depending on that
  974. // estimate, set uses_string_ to true or false. That contols
  975. // whether to force initialization of empty_string_ in SharedCtor().
  976. // It's often advantageous to do so to keep "is empty_string_
  977. // inited?" code from appearing all over the place.
  978. vector<const FieldDescriptor*> descriptors;
  979. for (int i = 0; i < descriptor_->field_count(); i++) {
  980. descriptors.push_back(descriptor_->field(i));
  981. }
  982. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  983. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  984. descriptors.push_back(descriptor_->oneof_decl(i)->field(j));
  985. }
  986. }
  987. uses_string_ = false;
  988. if (PreserveUnknownFields(descriptor_) &&
  989. !UseUnknownFieldSet(descriptor_->file())) {
  990. uses_string_ = true;
  991. }
  992. for (int i = 0; i < descriptors.size(); i++) {
  993. const FieldDescriptor* field = descriptors[i];
  994. if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
  995. switch (field->options().ctype()) {
  996. default: uses_string_ = true; break;
  997. }
  998. }
  999. }
  1000. printer->Print(
  1001. "int GetCachedSize() const { return _cached_size_; }\n"
  1002. "private:\n"
  1003. "void SharedCtor();\n"
  1004. "void SharedDtor();\n"
  1005. "void SetCachedSize(int size) const;\n"
  1006. "void InternalSwap($classname$* other);\n",
  1007. "classname", classname_);
  1008. if (SupportsArenas(descriptor_)) {
  1009. printer->Print(
  1010. "protected:\n"
  1011. "explicit $classname$(::google::protobuf::Arena* arena);\n"
  1012. "private:\n"
  1013. "static void ArenaDtor(void* object);\n"
  1014. "inline void RegisterArenaDtor(::google::protobuf::Arena* arena);\n",
  1015. "classname", classname_);
  1016. }
  1017. if (UseUnknownFieldSet(descriptor_->file())) {
  1018. printer->Print(
  1019. "private:\n"
  1020. "inline ::google::protobuf::Arena* GetArenaNoVirtual() const {\n"
  1021. " return _internal_metadata_.arena();\n"
  1022. "}\n"
  1023. "inline void* MaybeArenaPtr() const {\n"
  1024. " return _internal_metadata_.raw_arena_ptr();\n"
  1025. "}\n"
  1026. "public:\n"
  1027. "\n");
  1028. } else {
  1029. printer->Print(
  1030. "private:\n"
  1031. "inline ::google::protobuf::Arena* GetArenaNoVirtual() const {\n"
  1032. " return _arena_ptr_;\n"
  1033. "}\n"
  1034. "inline ::google::protobuf::Arena* MaybeArenaPtr() const {\n"
  1035. " return _arena_ptr_;\n"
  1036. "}\n"
  1037. "public:\n"
  1038. "\n");
  1039. }
  1040. if (HasDescriptorMethods(descriptor_->file())) {
  1041. printer->Print(
  1042. "::google::protobuf::Metadata GetMetadata() const;\n"
  1043. "\n");
  1044. } else {
  1045. printer->Print(
  1046. "::std::string GetTypeName() const;\n"
  1047. "\n");
  1048. }
  1049. printer->Print(
  1050. "// nested types ----------------------------------------------------\n"
  1051. "\n");
  1052. // Import all nested message classes into this class's scope with typedefs.
  1053. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1054. const Descriptor* nested_type = descriptor_->nested_type(i);
  1055. if (!IsMapEntryMessage(nested_type)) {
  1056. printer->Print("typedef $nested_full_name$ $nested_name$;\n",
  1057. "nested_name", nested_type->name(),
  1058. "nested_full_name", ClassName(nested_type, false));
  1059. }
  1060. }
  1061. if (descriptor_->nested_type_count() > 0) {
  1062. printer->Print("\n");
  1063. }
  1064. // Import all nested enums and their values into this class's scope with
  1065. // typedefs and constants.
  1066. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  1067. enum_generators_[i]->GenerateSymbolImports(printer);
  1068. printer->Print("\n");
  1069. }
  1070. printer->Print(
  1071. "// accessors -------------------------------------------------------\n"
  1072. "\n");
  1073. // Generate accessor methods for all fields.
  1074. GenerateFieldAccessorDeclarations(printer);
  1075. // Declare extension identifiers.
  1076. for (int i = 0; i < descriptor_->extension_count(); i++) {
  1077. extension_generators_[i]->GenerateDeclaration(printer);
  1078. }
  1079. printer->Print(
  1080. "// @@protoc_insertion_point(class_scope:$full_name$)\n",
  1081. "full_name", descriptor_->full_name());
  1082. // Generate private members.
  1083. printer->Outdent();
  1084. printer->Print(" private:\n");
  1085. printer->Indent();
  1086. for (int i = 0; i < descriptor_->field_count(); i++) {
  1087. if (!descriptor_->field(i)->is_repeated()) {
  1088. // set_has_***() generated in all proto1/2 code and in oneofs (only) for
  1089. // messages without true field presence.
  1090. if (HasFieldPresence(descriptor_->file()) ||
  1091. descriptor_->field(i)->containing_oneof()) {
  1092. printer->Print(
  1093. "inline void set_has_$name$();\n",
  1094. "name", FieldName(descriptor_->field(i)));
  1095. }
  1096. // clear_has_***() generated only for non-oneof fields
  1097. // in proto1/2.
  1098. if (!descriptor_->field(i)->containing_oneof() &&
  1099. HasFieldPresence(descriptor_->file())) {
  1100. printer->Print(
  1101. "inline void clear_has_$name$();\n",
  1102. "name", FieldName(descriptor_->field(i)));
  1103. }
  1104. }
  1105. }
  1106. printer->Print("\n");
  1107. // Generate oneof function declarations
  1108. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  1109. printer->Print(
  1110. "inline bool has_$oneof_name$() const;\n"
  1111. "void clear_$oneof_name$();\n"
  1112. "inline void clear_has_$oneof_name$();\n\n",
  1113. "oneof_name", descriptor_->oneof_decl(i)->name());
  1114. }
  1115. if (HasGeneratedMethods(descriptor_->file()) &&
  1116. !descriptor_->options().message_set_wire_format() &&
  1117. num_required_fields_ > 1) {
  1118. printer->Print(
  1119. "// helper for ByteSize()\n"
  1120. "int RequiredFieldsByteSizeFallback() const;\n\n");
  1121. }
  1122. // Prepare decls for _cached_size_ and _has_bits_. Their position in the
  1123. // output will be determined later.
  1124. bool need_to_emit_cached_size = true;
  1125. // TODO(kenton): Make _cached_size_ an atomic<int> when C++ supports it.
  1126. const string cached_size_decl = "mutable int _cached_size_;\n";
  1127. // TODO(jieluo) - Optimize _has_bits_ for repeated and oneof fields.
  1128. size_t sizeof_has_bits = (descriptor_->field_count() + 31) / 32 * 4;
  1129. if (descriptor_->field_count() == 0) {
  1130. // Zero-size arrays aren't technically allowed, and MSVC in particular
  1131. // doesn't like them. We still need to declare these arrays to make
  1132. // other code compile. Since this is an uncommon case, we'll just declare
  1133. // them with size 1 and waste some space. Oh well.
  1134. sizeof_has_bits = 4;
  1135. }
  1136. const string has_bits_decl = sizeof_has_bits == 0 ? "" :
  1137. "::google::protobuf::uint32 _has_bits_[" + SimpleItoa(sizeof_has_bits / 4) + "];\n";
  1138. // To minimize padding, data members are divided into three sections:
  1139. // (1) members assumed to align to 8 bytes
  1140. // (2) members corresponding to message fields, re-ordered to optimize
  1141. // alignment.
  1142. // (3) members assumed to align to 4 bytes.
  1143. // Members assumed to align to 8 bytes:
  1144. if (descriptor_->extension_range_count() > 0) {
  1145. printer->Print(
  1146. "::google::protobuf::internal::ExtensionSet _extensions_;\n"
  1147. "\n");
  1148. }
  1149. if (UseUnknownFieldSet(descriptor_->file())) {
  1150. printer->Print(
  1151. "::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;\n");
  1152. } else {
  1153. printer->Print(
  1154. "::google::protobuf::internal::ArenaStringPtr _unknown_fields_;\n"
  1155. "::google::protobuf::Arena* _arena_ptr_;\n"
  1156. "\n");
  1157. }
  1158. if (SupportsArenas(descriptor_)) {
  1159. printer->Print(
  1160. "friend class ::google::protobuf::Arena;\n"
  1161. "typedef void InternalArenaConstructable_;\n"
  1162. "typedef void DestructorSkippable_;\n");
  1163. }
  1164. if (HasFieldPresence(descriptor_->file())) {
  1165. // _has_bits_ is frequently accessed, so to reduce code size and improve
  1166. // speed, it should be close to the start of the object. But, try not to
  1167. // waste space:_has_bits_ by itself always makes sense if its size is a
  1168. // multiple of 8, but, otherwise, maybe _has_bits_ and cached_size_ together
  1169. // will work well.
  1170. printer->Print(has_bits_decl.c_str());
  1171. if ((sizeof_has_bits % 8) != 0) {
  1172. printer->Print(cached_size_decl.c_str());
  1173. need_to_emit_cached_size = false;
  1174. }
  1175. } else {
  1176. // Without field presence, we need another way to disambiguate the default
  1177. // instance, because the default instance's submessage fields (if any) store
  1178. // pointers to the default instances of the submessages even when they
  1179. // aren't present. Alternatives to this approach might be to (i) use a
  1180. // tagged pointer on all message fields, setting a tag bit for "not really
  1181. // present, just default instance"; or (ii) comparing |this| against the
  1182. // return value from GeneratedMessageFactory::GetPrototype() in all
  1183. // has_$field$() calls. However, both of these options are much more
  1184. // expensive (in code size and CPU overhead) than just checking a field in
  1185. // the message. Long-term, the best solution would be to rearchitect the
  1186. // default instance design not to store pointers to submessage default
  1187. // instances, and have reflection get those some other way; but that change
  1188. // would have too much impact on proto2.
  1189. printer->Print(
  1190. "bool _is_default_instance_;\n");
  1191. }
  1192. // Field members:
  1193. // List fields which doesn't belong to any oneof
  1194. vector<const FieldDescriptor*> fields;
  1195. hash_map<string, int> fieldname_to_chunk;
  1196. for (int i = 0; i < descriptor_->field_count(); i++) {
  1197. if (!descriptor_->field(i)->containing_oneof()) {
  1198. const FieldDescriptor* field = descriptor_->field(i);
  1199. fields.push_back(field);
  1200. fieldname_to_chunk[FieldName(field)] = i / 8;
  1201. }
  1202. }
  1203. OptimizePadding(&fields);
  1204. // Emit some private and static members
  1205. runs_of_fields_ = vector< vector<string> >(1);
  1206. for (int i = 0; i < fields.size(); ++i) {
  1207. const FieldDescriptor* field = fields[i];
  1208. const FieldGenerator& generator = field_generators_.get(field);
  1209. generator.GenerateStaticMembers(printer);
  1210. generator.GeneratePrivateMembers(printer);
  1211. if (CanClearByZeroing(field)) {
  1212. const string& fieldname = FieldName(field);
  1213. if (!runs_of_fields_.back().empty() &&
  1214. (fieldname_to_chunk[runs_of_fields_.back().back()] !=
  1215. fieldname_to_chunk[fieldname])) {
  1216. runs_of_fields_.push_back(vector<string>());
  1217. }
  1218. runs_of_fields_.back().push_back(fieldname);
  1219. } else if (!runs_of_fields_.back().empty()) {
  1220. runs_of_fields_.push_back(vector<string>());
  1221. }
  1222. }
  1223. // For each oneof generate a union
  1224. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  1225. printer->Print(
  1226. "union $camel_oneof_name$Union {\n"
  1227. // explicit empty constructor is needed when union contains
  1228. // ArenaStringPtr members for string fields.
  1229. " $camel_oneof_name$Union() {}\n",
  1230. "camel_oneof_name",
  1231. UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true));
  1232. printer->Indent();
  1233. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  1234. field_generators_.get(descriptor_->oneof_decl(i)->
  1235. field(j)).GeneratePrivateMembers(printer);
  1236. }
  1237. printer->Outdent();
  1238. printer->Print(
  1239. "} $oneof_name$_;\n",
  1240. "oneof_name", descriptor_->oneof_decl(i)->name());
  1241. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  1242. field_generators_.get(descriptor_->oneof_decl(i)->
  1243. field(j)).GenerateStaticMembers(printer);
  1244. }
  1245. }
  1246. // Members assumed to align to 4 bytes:
  1247. if (need_to_emit_cached_size) {
  1248. printer->Print(cached_size_decl.c_str());
  1249. need_to_emit_cached_size = false;
  1250. }
  1251. // Generate _oneof_case_.
  1252. if (descriptor_->oneof_decl_count() > 0) {
  1253. printer->Print(vars,
  1254. "::google::protobuf::uint32 _oneof_case_[$oneof_decl_count$];\n"
  1255. "\n");
  1256. }
  1257. // Generate _any_metadata_ for the Any type.
  1258. if (IsAnyMessage(descriptor_)) {
  1259. printer->Print(vars,
  1260. "::google::protobuf::internal::AnyMetadata _any_metadata_;\n");
  1261. }
  1262. // Declare AddDescriptors(), BuildDescriptors(), and ShutdownFile() as
  1263. // friends so that they can access private static variables like
  1264. // default_instance_ and reflection_.
  1265. PrintHandlingOptionalStaticInitializers(
  1266. descriptor_->file(), printer,
  1267. // With static initializers.
  1268. "friend void $dllexport_decl$ $adddescriptorsname$();\n",
  1269. // Without.
  1270. "friend void $dllexport_decl$ $adddescriptorsname$_impl();\n",
  1271. // Vars.
  1272. "dllexport_decl", options_.dllexport_decl,
  1273. "adddescriptorsname",
  1274. GlobalAddDescriptorsName(descriptor_->file()->name()));
  1275. printer->Print(
  1276. "friend void $assigndescriptorsname$();\n"
  1277. "friend void $shutdownfilename$();\n"
  1278. "\n",
  1279. "assigndescriptorsname",
  1280. GlobalAssignDescriptorsName(descriptor_->file()->name()),
  1281. "shutdownfilename", GlobalShutdownFileName(descriptor_->file()->name()));
  1282. printer->Print(
  1283. "void InitAsDefaultInstance();\n"
  1284. "static $classname$* default_instance_;\n",
  1285. "classname", classname_);
  1286. printer->Outdent();
  1287. printer->Print(vars, "};");
  1288. GOOGLE_DCHECK(!need_to_emit_cached_size);
  1289. }
  1290. void MessageGenerator::
  1291. GenerateDependentInlineMethods(io::Printer* printer) {
  1292. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1293. // map entry message doesn't need inline methods. Since map entry message
  1294. // cannot be a top level class, we just need to avoid calling
  1295. // GenerateInlineMethods here.
  1296. if (IsMapEntryMessage(descriptor_->nested_type(i))) continue;
  1297. nested_generators_[i]->GenerateDependentInlineMethods(printer);
  1298. printer->Print(kThinSeparator);
  1299. printer->Print("\n");
  1300. }
  1301. GenerateDependentFieldAccessorDefinitions(printer);
  1302. }
  1303. void MessageGenerator::
  1304. GenerateInlineMethods(io::Printer* printer, bool is_inline) {
  1305. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1306. // map entry message doesn't need inline methods. Since map entry message
  1307. // cannot be a top level class, we just need to avoid calling
  1308. // GenerateInlineMethods here.
  1309. if (IsMapEntryMessage(descriptor_->nested_type(i))) continue;
  1310. nested_generators_[i]->GenerateInlineMethods(printer, is_inline);
  1311. printer->Print(kThinSeparator);
  1312. printer->Print("\n");
  1313. }
  1314. GenerateFieldAccessorDefinitions(printer, is_inline);
  1315. // Generate oneof_case() functions.
  1316. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  1317. map<string, string> vars;
  1318. vars["class_name"] = classname_;
  1319. vars["camel_oneof_name"] = UnderscoresToCamelCase(
  1320. descriptor_->oneof_decl(i)->name(), true);
  1321. vars["oneof_name"] = descriptor_->oneof_decl(i)->name();
  1322. vars["oneof_index"] = SimpleItoa(descriptor_->oneof_decl(i)->index());
  1323. vars["inline"] = is_inline ? "inline " : "";
  1324. printer->Print(
  1325. vars,
  1326. "$inline$"
  1327. "$class_name$::$camel_oneof_name$Case $class_name$::"
  1328. "$oneof_name$_case() const {\n"
  1329. " return $class_name$::$camel_oneof_name$Case("
  1330. "_oneof_case_[$oneof_index$]);\n"
  1331. "}\n");
  1332. }
  1333. }
  1334. void MessageGenerator::
  1335. GenerateDescriptorDeclarations(io::Printer* printer) {
  1336. if (!IsMapEntryMessage(descriptor_)) {
  1337. printer->Print(
  1338. "const ::google::protobuf::Descriptor* $name$_descriptor_ = NULL;\n"
  1339. "const ::google::protobuf::internal::GeneratedMessageReflection*\n"
  1340. " $name$_reflection_ = NULL;\n",
  1341. "name", classname_);
  1342. } else {
  1343. printer->Print(
  1344. "const ::google::protobuf::Descriptor* $name$_descriptor_ = NULL;\n",
  1345. "name", classname_);
  1346. }
  1347. // Generate oneof default instance for reflection usage.
  1348. if (descriptor_->oneof_decl_count() > 0) {
  1349. printer->Print("struct $name$OneofInstance {\n",
  1350. "name", classname_);
  1351. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  1352. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  1353. const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
  1354. printer->Print(" ");
  1355. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
  1356. (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
  1357. EffectiveStringCType(field) != FieldOptions::STRING)) {
  1358. printer->Print("const ");
  1359. }
  1360. field_generators_.get(field).GeneratePrivateMembers(printer);
  1361. }
  1362. }
  1363. printer->Print("}* $name$_default_oneof_instance_ = NULL;\n",
  1364. "name", classname_);
  1365. }
  1366. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1367. nested_generators_[i]->GenerateDescriptorDeclarations(printer);
  1368. }
  1369. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  1370. printer->Print(
  1371. "const ::google::protobuf::EnumDescriptor* $name$_descriptor_ = NULL;\n",
  1372. "name", ClassName(descriptor_->enum_type(i), false));
  1373. }
  1374. }
  1375. void MessageGenerator::
  1376. GenerateDescriptorInitializer(io::Printer* printer, int index) {
  1377. // TODO(kenton): Passing the index to this method is redundant; just use
  1378. // descriptor_->index() instead.
  1379. map<string, string> vars;
  1380. vars["classname"] = classname_;
  1381. vars["index"] = SimpleItoa(index);
  1382. // Obtain the descriptor from the parent's descriptor.
  1383. if (descriptor_->containing_type() == NULL) {
  1384. printer->Print(vars,
  1385. "$classname$_descriptor_ = file->message_type($index$);\n");
  1386. } else {
  1387. vars["parent"] = ClassName(descriptor_->containing_type(), false);
  1388. printer->Print(vars,
  1389. "$classname$_descriptor_ = "
  1390. "$parent$_descriptor_->nested_type($index$);\n");
  1391. }
  1392. if (IsMapEntryMessage(descriptor_)) return;
  1393. // Generate the offsets.
  1394. GenerateOffsets(printer);
  1395. const bool pass_pool_and_factory = false;
  1396. vars["fn"] = pass_pool_and_factory ?
  1397. "new ::google::protobuf::internal::GeneratedMessageReflection" :
  1398. "::google::protobuf::internal::GeneratedMessageReflection"
  1399. "::NewGeneratedMessageReflection";
  1400. // Construct the reflection object.
  1401. printer->Print(vars,
  1402. "$classname$_reflection_ =\n"
  1403. " $fn$(\n"
  1404. " $classname$_descriptor_,\n"
  1405. " $classname$::default_instance_,\n"
  1406. " $classname$_offsets_,\n");
  1407. if (!HasFieldPresence(descriptor_->file())) {
  1408. // If we don't have field presence, then _has_bits_ does not exist.
  1409. printer->Print(vars,
  1410. " -1,\n");
  1411. } else {
  1412. printer->Print(vars,
  1413. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, _has_bits_[0]),\n");
  1414. }
  1415. // Unknown field offset: either points to the unknown field set if embedded
  1416. // directly, or indicates that the unknown field set is stored as part of the
  1417. // internal metadata if not.
  1418. if (UseUnknownFieldSet(descriptor_->file())) {
  1419. printer->Print(vars,
  1420. " -1,\n");
  1421. } else {
  1422. printer->Print(vars,
  1423. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  1424. "$classname$, _unknown_fields_),\n");
  1425. }
  1426. if (descriptor_->extension_range_count() > 0) {
  1427. printer->Print(vars,
  1428. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  1429. "$classname$, _extensions_),\n");
  1430. } else {
  1431. // No extensions.
  1432. printer->Print(vars,
  1433. " -1,\n");
  1434. }
  1435. if (descriptor_->oneof_decl_count() > 0) {
  1436. printer->Print(vars,
  1437. " $classname$_default_oneof_instance_,\n"
  1438. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  1439. "$classname$, _oneof_case_[0]),\n");
  1440. }
  1441. if (pass_pool_and_factory) {
  1442. printer->Print(
  1443. " ::google::protobuf::DescriptorPool::generated_pool(),\n");
  1444. printer->Print(vars,
  1445. " ::google::protobuf::MessageFactory::generated_factory(),\n");
  1446. }
  1447. printer->Print(vars,
  1448. " sizeof($classname$),\n");
  1449. // Arena offset: either an offset to the metadata struct that contains the
  1450. // arena pointer and unknown field set (in a space-efficient way) if we use
  1451. // that implementation strategy, or an offset directly to the arena pointer if
  1452. // not (because e.g. we don't have an unknown field set).
  1453. if (UseUnknownFieldSet(descriptor_->file())) {
  1454. printer->Print(vars,
  1455. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  1456. "$classname$, _internal_metadata_),\n");
  1457. } else {
  1458. printer->Print(vars,
  1459. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  1460. "$classname$, _arena_),\n");
  1461. }
  1462. // is_default_instance_ offset.
  1463. if (HasFieldPresence(descriptor_->file())) {
  1464. printer->Print(vars,
  1465. " -1);\n");
  1466. } else {
  1467. printer->Print(vars,
  1468. " GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET("
  1469. "$classname$, _is_default_instance_));\n");
  1470. }
  1471. // Handle nested types.
  1472. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1473. nested_generators_[i]->GenerateDescriptorInitializer(printer, i);
  1474. }
  1475. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  1476. enum_generators_[i]->GenerateDescriptorInitializer(printer, i);
  1477. }
  1478. }
  1479. void MessageGenerator::
  1480. GenerateTypeRegistrations(io::Printer* printer) {
  1481. // Register this message type with the message factory.
  1482. if (!IsMapEntryMessage(descriptor_)) {
  1483. printer->Print(
  1484. "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
  1485. " $classname$_descriptor_, &$classname$::default_instance());\n",
  1486. "classname", classname_);
  1487. }
  1488. else {
  1489. map<string, string> vars;
  1490. CollectMapInfo(descriptor_, &vars);
  1491. vars["classname"] = classname_;
  1492. const FieldDescriptor* val = descriptor_->FindFieldByName("value");
  1493. if (descriptor_->file()->syntax() == FileDescriptor::SYNTAX_PROTO2 &&
  1494. val->type() == FieldDescriptor::TYPE_ENUM) {
  1495. const EnumValueDescriptor* default_value = val->default_value_enum();
  1496. vars["default_enum_value"] = Int32ToString(default_value->number());
  1497. } else {
  1498. vars["default_enum_value"] = "0";
  1499. }
  1500. printer->Print(vars,
  1501. "::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(\n"
  1502. " $classname$_descriptor_,\n"
  1503. " ::google::protobuf::internal::MapEntry<\n"
  1504. " $key$,\n"
  1505. " $val$,\n"
  1506. " $key_wire_type$,\n"
  1507. " $val_wire_type$,\n"
  1508. " $default_enum_value$>::CreateDefaultInstance(\n"
  1509. " $classname$_descriptor_));\n");
  1510. }
  1511. // Handle nested types.
  1512. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1513. nested_generators_[i]->GenerateTypeRegistrations(printer);
  1514. }
  1515. }
  1516. void MessageGenerator::
  1517. GenerateDefaultInstanceAllocator(io::Printer* printer) {
  1518. // Construct the default instances of all fields, as they will be used
  1519. // when creating the default instance of the entire message.
  1520. for (int i = 0; i < descriptor_->field_count(); i++) {
  1521. field_generators_.get(descriptor_->field(i))
  1522. .GenerateDefaultInstanceAllocator(printer);
  1523. }
  1524. if (IsMapEntryMessage(descriptor_)) return;
  1525. // Construct the default instance. We can't call InitAsDefaultInstance() yet
  1526. // because we need to make sure all default instances that this one might
  1527. // depend on are constructed first.
  1528. printer->Print(
  1529. "$classname$::default_instance_ = new $classname$();\n",
  1530. "classname", classname_);
  1531. if ((descriptor_->oneof_decl_count() > 0) &&
  1532. HasDescriptorMethods(descriptor_->file())) {
  1533. printer->Print(
  1534. "$classname$_default_oneof_instance_ = new $classname$OneofInstance();\n",
  1535. "classname", classname_);
  1536. }
  1537. // Handle nested types.
  1538. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1539. nested_generators_[i]->GenerateDefaultInstanceAllocator(printer);
  1540. }
  1541. }
  1542. void MessageGenerator::
  1543. GenerateDefaultInstanceInitializer(io::Printer* printer) {
  1544. printer->Print(
  1545. "$classname$::default_instance_->InitAsDefaultInstance();\n",
  1546. "classname", classname_);
  1547. // Register extensions.
  1548. for (int i = 0; i < descriptor_->extension_count(); i++) {
  1549. extension_generators_[i]->GenerateRegistration(printer);
  1550. }
  1551. // Handle nested types.
  1552. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1553. // map entry message doesn't need to initialize default instance manually.
  1554. // Since map entry message cannot be a top level class, we just need to
  1555. // avoid calling DefaultInstanceInitializer here.
  1556. if (IsMapEntryMessage(descriptor_->nested_type(i))) continue;
  1557. nested_generators_[i]->GenerateDefaultInstanceInitializer(printer);
  1558. }
  1559. }
  1560. void MessageGenerator::
  1561. GenerateShutdownCode(io::Printer* printer) {
  1562. printer->Print(
  1563. "delete $classname$::default_instance_;\n",
  1564. "classname", classname_);
  1565. if (HasDescriptorMethods(descriptor_->file())) {
  1566. if (descriptor_->oneof_decl_count() > 0) {
  1567. printer->Print(
  1568. "delete $classname$_default_oneof_instance_;\n",
  1569. "classname", classname_);
  1570. }
  1571. printer->Print(
  1572. "delete $classname$_reflection_;\n",
  1573. "classname", classname_);
  1574. }
  1575. // Handle default instances of fields.
  1576. for (int i = 0; i < descriptor_->field_count(); i++) {
  1577. field_generators_.get(descriptor_->field(i))
  1578. .GenerateShutdownCode(printer);
  1579. }
  1580. // Handle nested types.
  1581. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1582. if (IsMapEntryMessage(descriptor_->nested_type(i))) continue;
  1583. nested_generators_[i]->GenerateShutdownCode(printer);
  1584. }
  1585. }
  1586. void MessageGenerator::
  1587. GenerateClassMethods(io::Printer* printer) {
  1588. // mutable_unknown_fields wrapper function for LazyStringOutputStream
  1589. // callback.
  1590. if (PreserveUnknownFields(descriptor_) &&
  1591. !UseUnknownFieldSet(descriptor_->file())) {
  1592. printer->Print(
  1593. "static ::std::string* MutableUnknownFieldsFor$classname$(\n"
  1594. " $classname$* ptr) {\n"
  1595. " return ptr->mutable_unknown_fields();\n"
  1596. "}\n"
  1597. "\n",
  1598. "classname", classname_);
  1599. }
  1600. if (IsAnyMessage(descriptor_)) {
  1601. printer->Print(
  1602. "void $classname$::PackFrom(const ::google::protobuf::Message& message) {\n"
  1603. " _any_metadata_.PackFrom(message);\n"
  1604. "}\n"
  1605. "\n"
  1606. "void $classname$::PackFrom(const ::google::protobuf::Message& message,\n"
  1607. " const ::std::string& type_url_prefix) {\n"
  1608. " _any_metadata_.PackFrom(message, type_url_prefix);\n"
  1609. "}\n"
  1610. "\n"
  1611. "bool $classname$::UnpackTo(::google::protobuf::Message* message) const {\n"
  1612. " return _any_metadata_.UnpackTo(message);\n"
  1613. "}\n"
  1614. "\n",
  1615. "classname", classname_);
  1616. }
  1617. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  1618. enum_generators_[i]->GenerateMethods(printer);
  1619. }
  1620. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1621. // map entry message doesn't need class methods. Since map entry message
  1622. // cannot be a top level class, we just need to avoid calling
  1623. // GenerateClassMethods here.
  1624. if (IsMapEntryMessage(descriptor_->nested_type(i))) continue;
  1625. nested_generators_[i]->GenerateClassMethods(printer);
  1626. printer->Print("\n");
  1627. printer->Print(kThinSeparator);
  1628. printer->Print("\n");
  1629. }
  1630. // Generate non-inline field definitions.
  1631. for (int i = 0; i < descriptor_->field_count(); i++) {
  1632. field_generators_.get(descriptor_->field(i))
  1633. .GenerateNonInlineAccessorDefinitions(printer);
  1634. }
  1635. // Generate field number constants.
  1636. printer->Print("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n");
  1637. for (int i = 0; i < descriptor_->field_count(); i++) {
  1638. const FieldDescriptor *field = descriptor_->field(i);
  1639. printer->Print(
  1640. "const int $classname$::$constant_name$;\n",
  1641. "classname", ClassName(FieldScope(field), false),
  1642. "constant_name", FieldConstantName(field));
  1643. }
  1644. printer->Print(
  1645. "#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n"
  1646. "\n");
  1647. // Define extension identifiers.
  1648. for (int i = 0; i < descriptor_->extension_count(); i++) {
  1649. extension_generators_[i]->GenerateDefinition(printer);
  1650. }
  1651. GenerateStructors(printer);
  1652. printer->Print("\n");
  1653. if (descriptor_->oneof_decl_count() > 0) {
  1654. GenerateOneofClear(printer);
  1655. printer->Print("\n");
  1656. }
  1657. if (HasGeneratedMethods(descriptor_->file())) {
  1658. GenerateClear(printer);
  1659. printer->Print("\n");
  1660. GenerateMergeFromCodedStream(printer);
  1661. printer->Print("\n");
  1662. GenerateSerializeWithCachedSizes(printer);
  1663. printer->Print("\n");
  1664. if (HasFastArraySerialization(descriptor_->file())) {
  1665. GenerateSerializeWithCachedSizesToArray(printer);
  1666. printer->Print("\n");
  1667. }
  1668. GenerateByteSize(printer);
  1669. printer->Print("\n");
  1670. GenerateMergeFrom(printer);
  1671. printer->Print("\n");
  1672. GenerateCopyFrom(printer);
  1673. printer->Print("\n");
  1674. GenerateIsInitialized(printer);
  1675. printer->Print("\n");
  1676. }
  1677. GenerateSwap(printer);
  1678. printer->Print("\n");
  1679. if (HasDescriptorMethods(descriptor_->file())) {
  1680. printer->Print(
  1681. "::google::protobuf::Metadata $classname$::GetMetadata() const {\n"
  1682. " protobuf_AssignDescriptorsOnce();\n"
  1683. " ::google::protobuf::Metadata metadata;\n"
  1684. " metadata.descriptor = $classname$_descriptor_;\n"
  1685. " metadata.reflection = $classname$_reflection_;\n"
  1686. " return metadata;\n"
  1687. "}\n"
  1688. "\n",
  1689. "classname", classname_);
  1690. } else {
  1691. printer->Print(
  1692. "::std::string $classname$::GetTypeName() const {\n"
  1693. " return \"$type_name$\";\n"
  1694. "}\n"
  1695. "\n",
  1696. "classname", classname_,
  1697. "type_name", descriptor_->full_name());
  1698. }
  1699. }
  1700. void MessageGenerator::
  1701. GenerateOffsets(io::Printer* printer) {
  1702. printer->Print("static const int $classname$_offsets_[$field_count$] = {\n",
  1703. "classname", classname_, "field_count",
  1704. SimpleItoa(std::max(1, descriptor_->field_count() +
  1705. descriptor_->oneof_decl_count())));
  1706. printer->Indent();
  1707. for (int i = 0; i < descriptor_->field_count(); i++) {
  1708. const FieldDescriptor* field = descriptor_->field(i);
  1709. if (field->containing_oneof()) {
  1710. printer->Print(
  1711. "PROTO2_GENERATED_DEFAULT_ONEOF_FIELD_OFFSET("
  1712. "$classname$_default_oneof_instance_, $name$_),\n",
  1713. "classname", classname_,
  1714. "name", FieldName(field));
  1715. } else {
  1716. printer->Print(
  1717. "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, "
  1718. "$name$_),\n",
  1719. "classname", classname_,
  1720. "name", FieldName(field));
  1721. }
  1722. }
  1723. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  1724. const OneofDescriptor* oneof = descriptor_->oneof_decl(i);
  1725. printer->Print(
  1726. "GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET($classname$, $name$_),\n",
  1727. "classname", classname_,
  1728. "name", oneof->name());
  1729. }
  1730. printer->Outdent();
  1731. printer->Print("};\n");
  1732. }
  1733. void MessageGenerator::
  1734. GenerateSharedConstructorCode(io::Printer* printer) {
  1735. printer->Print(
  1736. "void $classname$::SharedCtor() {\n",
  1737. "classname", classname_);
  1738. printer->Indent();
  1739. if (!HasFieldPresence(descriptor_->file())) {
  1740. printer->Print(
  1741. " _is_default_instance_ = false;\n");
  1742. }
  1743. printer->Print(StrCat(
  1744. uses_string_ ? "::google::protobuf::internal::GetEmptyString();\n" : "",
  1745. "_cached_size_ = 0;\n").c_str());
  1746. if (PreserveUnknownFields(descriptor_) &&
  1747. !UseUnknownFieldSet(descriptor_->file())) {
  1748. printer->Print(
  1749. "_unknown_fields_.UnsafeSetDefault(\n"
  1750. " &::google::protobuf::internal::GetEmptyStringAlreadyInited());\n");
  1751. }
  1752. for (int i = 0; i < descriptor_->field_count(); i++) {
  1753. if (!descriptor_->field(i)->containing_oneof()) {
  1754. field_generators_.get(descriptor_->field(i))
  1755. .GenerateConstructorCode(printer);
  1756. }
  1757. }
  1758. if (HasFieldPresence(descriptor_->file())) {
  1759. printer->Print(
  1760. "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
  1761. }
  1762. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  1763. printer->Print(
  1764. "clear_has_$oneof_name$();\n",
  1765. "oneof_name", descriptor_->oneof_decl(i)->name());
  1766. }
  1767. printer->Outdent();
  1768. printer->Print("}\n\n");
  1769. }
  1770. void MessageGenerator::
  1771. GenerateSharedDestructorCode(io::Printer* printer) {
  1772. printer->Print(
  1773. "void $classname$::SharedDtor() {\n",
  1774. "classname", classname_);
  1775. printer->Indent();
  1776. if (SupportsArenas(descriptor_)) {
  1777. // Do nothing when the message is allocated in an arena.
  1778. printer->Print(
  1779. "if (GetArenaNoVirtual() != NULL) {\n"
  1780. " return;\n"
  1781. "}\n"
  1782. "\n");
  1783. }
  1784. // Write the desctructor for _unknown_fields_ in lite runtime.
  1785. if (PreserveUnknownFields(descriptor_) &&
  1786. !UseUnknownFieldSet(descriptor_->file())) {
  1787. if (SupportsArenas(descriptor_)) {
  1788. printer->Print(
  1789. "_unknown_fields_.Destroy(\n"
  1790. " &::google::protobuf::internal::GetEmptyStringAlreadyInited(),\n"
  1791. " GetArenaNoVirtual());\n");
  1792. } else {
  1793. printer->Print(
  1794. "_unknown_fields_.DestroyNoArena(\n"
  1795. " &::google::protobuf::internal::GetEmptyStringAlreadyInited());\n");
  1796. }
  1797. }
  1798. // Write the destructors for each field except oneof members.
  1799. for (int i = 0; i < descriptor_->field_count(); i++) {
  1800. if (!descriptor_->field(i)->containing_oneof()) {
  1801. field_generators_.get(descriptor_->field(i))
  1802. .GenerateDestructorCode(printer);
  1803. }
  1804. }
  1805. // Generate code to destruct oneofs. Clearing should do the work.
  1806. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  1807. printer->Print(
  1808. "if (has_$oneof_name$()) {\n"
  1809. " clear_$oneof_name$();\n"
  1810. "}\n",
  1811. "oneof_name", descriptor_->oneof_decl(i)->name());
  1812. }
  1813. PrintHandlingOptionalStaticInitializers(
  1814. descriptor_->file(), printer,
  1815. // With static initializers.
  1816. "if (this != default_instance_) {\n",
  1817. // Without.
  1818. "if (this != &default_instance()) {\n");
  1819. // We need to delete all embedded messages.
  1820. // TODO(kenton): If we make unset messages point at default instances
  1821. // instead of NULL, then it would make sense to move this code into
  1822. // MessageFieldGenerator::GenerateDestructorCode().
  1823. for (int i = 0; i < descriptor_->field_count(); i++) {
  1824. const FieldDescriptor* field = descriptor_->field(i);
  1825. if (!field->is_repeated() &&
  1826. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1827. // Skip oneof members
  1828. if (!field->containing_oneof()) {
  1829. printer->Print(
  1830. " delete $name$_;\n",
  1831. "name", FieldName(field));
  1832. }
  1833. }
  1834. }
  1835. printer->Outdent();
  1836. printer->Print(
  1837. " }\n"
  1838. "}\n"
  1839. "\n");
  1840. }
  1841. void MessageGenerator::
  1842. GenerateArenaDestructorCode(io::Printer* printer) {
  1843. // Generate the ArenaDtor() method. Track whether any fields actually produced
  1844. // code that needs to be called.
  1845. printer->Print(
  1846. "void $classname$::ArenaDtor(void* object) {\n",
  1847. "classname", classname_);
  1848. printer->Indent();
  1849. // This code is placed inside a static method, rather than an ordinary one,
  1850. // since that simplifies Arena's destructor list (ordinary function pointers
  1851. // rather than member function pointers). _this is the object being
  1852. // destructed.
  1853. printer->Print(
  1854. "$classname$* _this = reinterpret_cast< $classname$* >(object);\n"
  1855. // avoid an "unused variable" warning in case no fields have dtor code.
  1856. "(void)_this;\n",
  1857. "classname", classname_);
  1858. bool need_registration = false;
  1859. for (int i = 0; i < descriptor_->field_count(); i++) {
  1860. if (field_generators_.get(descriptor_->field(i))
  1861. .GenerateArenaDestructorCode(printer)) {
  1862. need_registration = true;
  1863. }
  1864. }
  1865. printer->Outdent();
  1866. printer->Print(
  1867. "}\n");
  1868. if (need_registration) {
  1869. printer->Print(
  1870. "inline void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n"
  1871. " if (arena != NULL) {\n"
  1872. " arena->OwnCustomDestructor(this, &$classname$::ArenaDtor);\n"
  1873. " }\n"
  1874. "}\n",
  1875. "classname", classname_);
  1876. } else {
  1877. printer->Print(
  1878. "void $classname$::RegisterArenaDtor(::google::protobuf::Arena* arena) {\n"
  1879. "}\n",
  1880. "classname", classname_);
  1881. }
  1882. }
  1883. void MessageGenerator::
  1884. GenerateStructors(io::Printer* printer) {
  1885. string superclass;
  1886. if (use_dependent_base_) {
  1887. superclass =
  1888. DependentBaseClassTemplateName(descriptor_) + "<" + classname_ + ">";
  1889. } else {
  1890. superclass = SuperClassName(descriptor_);
  1891. }
  1892. string initializer_with_arena = superclass + "()";
  1893. if (descriptor_->extension_range_count() > 0) {
  1894. initializer_with_arena += ",\n _extensions_(arena)";
  1895. }
  1896. if (UseUnknownFieldSet(descriptor_->file())) {
  1897. initializer_with_arena += ",\n _internal_metadata_(arena)";
  1898. } else {
  1899. initializer_with_arena += ",\n _arena_ptr_(arena)";
  1900. }
  1901. // Initialize member variables with arena constructor.
  1902. for (int i = 0; i < descriptor_->field_count(); i++) {
  1903. bool has_arena_constructor = descriptor_->field(i)->is_repeated();
  1904. if (has_arena_constructor) {
  1905. initializer_with_arena += string(",\n ") +
  1906. FieldName(descriptor_->field(i)) + string("_(arena)");
  1907. }
  1908. }
  1909. if (IsAnyMessage(descriptor_)) {
  1910. initializer_with_arena += ",\n _any_metadata_(&type_url, &value_)";
  1911. }
  1912. string initializer_null;
  1913. initializer_null = (UseUnknownFieldSet(descriptor_->file()) ?
  1914. ", _internal_metadata_(NULL)" : ", _arena_ptr_(NULL)");
  1915. if (IsAnyMessage(descriptor_)) {
  1916. initializer_null += ", _any_metadata_(&type_url_, &value_)";
  1917. }
  1918. printer->Print(
  1919. "$classname$::$classname$()\n"
  1920. " : $superclass$()$initializer$ {\n"
  1921. " SharedCtor();\n"
  1922. " // @@protoc_insertion_point(constructor:$full_name$)\n"
  1923. "}\n",
  1924. "classname", classname_,
  1925. "superclass", superclass,
  1926. "full_name", descriptor_->full_name(),
  1927. "initializer", initializer_null);
  1928. if (SupportsArenas(descriptor_)) {
  1929. printer->Print(
  1930. "\n"
  1931. "$classname$::$classname$(::google::protobuf::Arena* arena)\n"
  1932. " : $initializer$ {\n"
  1933. " SharedCtor();\n"
  1934. " RegisterArenaDtor(arena);\n"
  1935. " // @@protoc_insertion_point(arena_constructor:$full_name$)\n"
  1936. "}\n",
  1937. "initializer", initializer_with_arena,
  1938. "classname", classname_,
  1939. "superclass", superclass,
  1940. "full_name", descriptor_->full_name());
  1941. }
  1942. printer->Print(
  1943. "\n"
  1944. "void $classname$::InitAsDefaultInstance() {\n",
  1945. "classname", classname_);
  1946. if (!HasFieldPresence(descriptor_->file())) {
  1947. printer->Print(
  1948. " _is_default_instance_ = true;\n");
  1949. }
  1950. // The default instance needs all of its embedded message pointers
  1951. // cross-linked to other default instances. We can't do this initialization
  1952. // in the constructor because some other default instances may not have been
  1953. // constructed yet at that time.
  1954. // TODO(kenton): Maybe all message fields (even for non-default messages)
  1955. // should be initialized to point at default instances rather than NULL?
  1956. for (int i = 0; i < descriptor_->field_count(); i++) {
  1957. const FieldDescriptor* field = descriptor_->field(i);
  1958. if (!field->is_repeated() &&
  1959. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  1960. (field->containing_oneof() == NULL ||
  1961. HasDescriptorMethods(descriptor_->file()))) {
  1962. string name;
  1963. if (field->containing_oneof()) {
  1964. name = classname_ + "_default_oneof_instance_->";
  1965. }
  1966. name += FieldName(field);
  1967. PrintHandlingOptionalStaticInitializers(
  1968. descriptor_->file(), printer,
  1969. // With static initializers.
  1970. " $name$_ = const_cast< $type$*>(&$type$::default_instance());\n",
  1971. // Without.
  1972. " $name$_ = const_cast< $type$*>(\n"
  1973. " $type$::internal_default_instance());\n",
  1974. // Vars.
  1975. "name", name,
  1976. "type", FieldMessageTypeName(field));
  1977. } else if (field->containing_oneof() &&
  1978. HasDescriptorMethods(descriptor_->file())) {
  1979. field_generators_.get(descriptor_->field(i))
  1980. .GenerateConstructorCode(printer);
  1981. }
  1982. }
  1983. printer->Print(
  1984. "}\n"
  1985. "\n");
  1986. // Generate the copy constructor.
  1987. printer->Print(
  1988. "$classname$::$classname$(const $classname$& from)\n"
  1989. " : $superclass$()",
  1990. "classname", classname_,
  1991. "superclass", superclass,
  1992. "full_name", descriptor_->full_name());
  1993. if (UseUnknownFieldSet(descriptor_->file())) {
  1994. printer->Print(
  1995. ",\n _internal_metadata_(NULL)");
  1996. } else if (!UseUnknownFieldSet(descriptor_->file())) {
  1997. printer->Print(",\n _arena_ptr_(NULL)");
  1998. }
  1999. if (IsAnyMessage(descriptor_)) {
  2000. printer->Print(",\n _any_metadata_(&type_url_, &value_)");
  2001. }
  2002. printer->Print(" {\n");
  2003. printer->Print(
  2004. " SharedCtor();\n"
  2005. " MergeFrom(from);\n"
  2006. " // @@protoc_insertion_point(copy_constructor:$full_name$)\n"
  2007. "}\n"
  2008. "\n",
  2009. "classname", classname_,
  2010. "superclass", superclass,
  2011. "full_name", descriptor_->full_name());
  2012. // Generate the shared constructor code.
  2013. GenerateSharedConstructorCode(printer);
  2014. // Generate the destructor.
  2015. printer->Print(
  2016. "$classname$::~$classname$() {\n"
  2017. " // @@protoc_insertion_point(destructor:$full_name$)\n"
  2018. " SharedDtor();\n"
  2019. "}\n"
  2020. "\n",
  2021. "classname", classname_,
  2022. "full_name", descriptor_->full_name());
  2023. // Generate the shared destructor code.
  2024. GenerateSharedDestructorCode(printer);
  2025. // Generate the arena-specific destructor code.
  2026. if (SupportsArenas(descriptor_)) {
  2027. GenerateArenaDestructorCode(printer);
  2028. }
  2029. // Generate SetCachedSize.
  2030. printer->Print(
  2031. "void $classname$::SetCachedSize(int size) const {\n"
  2032. " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
  2033. " _cached_size_ = size;\n"
  2034. " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
  2035. "}\n",
  2036. "classname", classname_);
  2037. // Only generate this member if it's not disabled.
  2038. if (HasDescriptorMethods(descriptor_->file()) &&
  2039. !descriptor_->options().no_standard_descriptor_accessor()) {
  2040. printer->Print(
  2041. "const ::google::protobuf::Descriptor* $classname$::descriptor() {\n"
  2042. " protobuf_AssignDescriptorsOnce();\n"
  2043. " return $classname$_descriptor_;\n"
  2044. "}\n"
  2045. "\n",
  2046. "classname", classname_,
  2047. "adddescriptorsname",
  2048. GlobalAddDescriptorsName(descriptor_->file()->name()));
  2049. }
  2050. printer->Print(
  2051. "const $classname$& $classname$::default_instance() {\n",
  2052. "classname", classname_);
  2053. PrintHandlingOptionalStaticInitializers(
  2054. descriptor_->file(), printer,
  2055. // With static initializers.
  2056. " if (default_instance_ == NULL) $adddescriptorsname$();\n",
  2057. // Without.
  2058. " $adddescriptorsname$();\n",
  2059. // Vars.
  2060. "adddescriptorsname",
  2061. GlobalAddDescriptorsName(descriptor_->file()->name()));
  2062. printer->Print(
  2063. " return *default_instance_;\n"
  2064. "}\n"
  2065. "\n"
  2066. "$classname$* $classname$::default_instance_ = NULL;\n"
  2067. "\n",
  2068. "classname", classname_);
  2069. if (SupportsArenas(descriptor_)) {
  2070. printer->Print(
  2071. "$classname$* $classname$::New(::google::protobuf::Arena* arena) const {\n"
  2072. " return ::google::protobuf::Arena::CreateMessage<$classname$>(arena);\n"
  2073. "}\n",
  2074. "classname", classname_);
  2075. } else {
  2076. printer->Print(
  2077. "$classname$* $classname$::New(::google::protobuf::Arena* arena) const {\n"
  2078. " $classname$* n = new $classname$;\n"
  2079. " if (arena != NULL) {\n"
  2080. " arena->Own(n);\n"
  2081. " }\n"
  2082. " return n;\n"
  2083. "}\n",
  2084. "classname", classname_);
  2085. }
  2086. }
  2087. // Return the number of bits set in n, a non-negative integer.
  2088. static int popcnt(uint32 n) {
  2089. int result = 0;
  2090. while (n != 0) {
  2091. result += (n & 1);
  2092. n = n / 2;
  2093. }
  2094. return result;
  2095. }
  2096. void MessageGenerator::
  2097. GenerateClear(io::Printer* printer) {
  2098. printer->Print("void $classname$::Clear() {\n",
  2099. "classname", classname_);
  2100. printer->Indent();
  2101. // Step 1: Extensions
  2102. if (descriptor_->extension_range_count() > 0) {
  2103. printer->Print("_extensions_.Clear();\n");
  2104. }
  2105. // Step 2: Everything but extensions, repeateds, unions.
  2106. // These are handled in chunks of 8. The first chunk is
  2107. // the non-extensions-non-repeateds-non-unions in
  2108. // descriptor_->field(0), descriptor_->field(1), ... descriptor_->field(7),
  2109. // and the second chunk is the same for
  2110. // descriptor_->field(8), descriptor_->field(9), ... descriptor_->field(15),
  2111. // etc.
  2112. set<int> step2_indices;
  2113. hash_map<string, int> fieldname_to_chunk;
  2114. hash_map<int, string> memsets_for_chunk;
  2115. hash_map<int, int> memset_field_count_for_chunk;
  2116. hash_set<string> handled; // fields that appear anywhere in memsets_for_chunk
  2117. hash_map<int, uint32> fields_mask_for_chunk;
  2118. for (int i = 0; i < descriptor_->field_count(); i++) {
  2119. const FieldDescriptor* field = descriptor_->field(i);
  2120. if (!field->is_repeated() && !field->containing_oneof()) {
  2121. step2_indices.insert(i);
  2122. int chunk = i / 8;
  2123. fieldname_to_chunk[FieldName(field)] = chunk;
  2124. fields_mask_for_chunk[chunk] |= static_cast<uint32>(1) << (i % 32);
  2125. }
  2126. }
  2127. // Step 2a: Greedily seek runs of fields that can be cleared by memset-to-0.
  2128. // The generated code uses two macros to help it clear runs of fields:
  2129. // ZR_HELPER_(f1) - ZR_HELPER_(f0) computes the difference, in bytes, of the
  2130. // positions of two fields in the Message.
  2131. // ZR_ zeroes a non-empty range of fields via memset.
  2132. const char* macros =
  2133. "#define ZR_HELPER_(f) reinterpret_cast<char*>(\\\n"
  2134. " &reinterpret_cast<$classname$*>(16)->f)\n\n"
  2135. "#define ZR_(first, last) do {\\\n"
  2136. " ::memset(&first, 0,\\\n"
  2137. " ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\\\n"
  2138. "} while (0)\n\n";
  2139. for (int i = 0; i < runs_of_fields_.size(); i++) {
  2140. const vector<string>& run = runs_of_fields_[i];
  2141. if (run.size() < 2) continue;
  2142. const string& first_field_name = run[0];
  2143. const string& last_field_name = run.back();
  2144. int chunk = fieldname_to_chunk[run[0]];
  2145. memsets_for_chunk[chunk].append(
  2146. "ZR_(" + first_field_name + "_, " + last_field_name + "_);\n");
  2147. for (int j = 0; j < run.size(); j++) {
  2148. GOOGLE_DCHECK_EQ(chunk, fieldname_to_chunk[run[j]]);
  2149. handled.insert(run[j]);
  2150. }
  2151. memset_field_count_for_chunk[chunk] += run.size();
  2152. }
  2153. const bool macros_are_needed = handled.size() > 0;
  2154. if (macros_are_needed) {
  2155. printer->Outdent();
  2156. printer->Print(macros,
  2157. "classname", classname_);
  2158. printer->Indent();
  2159. }
  2160. // Step 2b: Finish step 2, ignoring fields handled in step 2a.
  2161. int last_index = -1;
  2162. bool chunk_block_in_progress = false;
  2163. for (int i = 0; i < descriptor_->field_count(); i++) {
  2164. if (step2_indices.count(i) == 0) continue;
  2165. const FieldDescriptor* field = descriptor_->field(i);
  2166. const string fieldname = FieldName(field);
  2167. if (i / 8 != last_index / 8 || last_index < 0) {
  2168. // End previous chunk, if there was one.
  2169. if (chunk_block_in_progress) {
  2170. printer->Outdent();
  2171. printer->Print("}\n");
  2172. chunk_block_in_progress = false;
  2173. }
  2174. // Start chunk.
  2175. const string& memsets = memsets_for_chunk[i / 8];
  2176. uint32 mask = fields_mask_for_chunk[i / 8];
  2177. int count = popcnt(mask);
  2178. GOOGLE_DCHECK_GE(count, 1);
  2179. if (count == 1 ||
  2180. (count <= 4 && count == memset_field_count_for_chunk[i / 8])) {
  2181. // No "if" here because the chunk is trivial.
  2182. } else {
  2183. if (HasFieldPresence(descriptor_->file())) {
  2184. printer->Print(
  2185. "if (_has_bits_[$index$ / 32] & $mask$u) {\n",
  2186. "index", SimpleItoa(i / 8 * 8),
  2187. "mask", SimpleItoa(mask));
  2188. printer->Indent();
  2189. chunk_block_in_progress = true;
  2190. }
  2191. }
  2192. printer->Print(memsets.c_str());
  2193. }
  2194. last_index = i;
  2195. if (handled.count(fieldname) > 0) continue;
  2196. // It's faster to just overwrite primitive types, but we should
  2197. // only clear strings and messages if they were set.
  2198. // TODO(kenton): Let the CppFieldGenerator decide this somehow.
  2199. bool should_check_bit =
  2200. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
  2201. field->cpp_type() == FieldDescriptor::CPPTYPE_STRING;
  2202. bool have_enclosing_if = false;
  2203. if (should_check_bit &&
  2204. // If no field presence, then always clear strings/messages as well.
  2205. HasFieldPresence(descriptor_->file())) {
  2206. printer->Print("if (has_$name$()) {\n", "name", fieldname);
  2207. printer->Indent();
  2208. have_enclosing_if = true;
  2209. }
  2210. if (use_dependent_base_ && IsFieldDependent(field)) {
  2211. printer->Print("clear_$name$();\n", "name", fieldname);
  2212. } else {
  2213. field_generators_.get(field).GenerateClearingCode(printer);
  2214. }
  2215. if (have_enclosing_if) {
  2216. printer->Outdent();
  2217. printer->Print("}\n");
  2218. }
  2219. }
  2220. if (chunk_block_in_progress) {
  2221. printer->Outdent();
  2222. printer->Print("}\n");
  2223. }
  2224. if (macros_are_needed) {
  2225. printer->Outdent();
  2226. printer->Print("\n#undef ZR_HELPER_\n#undef ZR_\n\n");
  2227. printer->Indent();
  2228. }
  2229. // Step 3: Repeated fields don't use _has_bits_; emit code to clear them here.
  2230. for (int i = 0; i < descriptor_->field_count(); i++) {
  2231. const FieldDescriptor* field = descriptor_->field(i);
  2232. if (field->is_repeated()) {
  2233. if (use_dependent_base_ && IsFieldDependent(field)) {
  2234. printer->Print("clear_$name$();\n", "name", FieldName(field));
  2235. } else {
  2236. field_generators_.get(field).GenerateClearingCode(printer);
  2237. }
  2238. }
  2239. }
  2240. // Step 4: Unions.
  2241. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  2242. printer->Print(
  2243. "clear_$oneof_name$();\n",
  2244. "oneof_name", descriptor_->oneof_decl(i)->name());
  2245. }
  2246. if (HasFieldPresence(descriptor_->file())) {
  2247. // Step 5: Everything else.
  2248. printer->Print(
  2249. "::memset(_has_bits_, 0, sizeof(_has_bits_));\n");
  2250. }
  2251. if (PreserveUnknownFields(descriptor_)) {
  2252. if (UseUnknownFieldSet(descriptor_->file())) {
  2253. printer->Print(
  2254. "if (_internal_metadata_.have_unknown_fields()) {\n"
  2255. " mutable_unknown_fields()->Clear();\n"
  2256. "}\n");
  2257. } else {
  2258. if (SupportsArenas(descriptor_)) {
  2259. printer->Print(
  2260. "_unknown_fields_.ClearToEmpty(\n"
  2261. " &::google::protobuf::internal::GetEmptyStringAlreadyInited(),\n"
  2262. " GetArenaNoVirtual());\n");
  2263. } else {
  2264. printer->Print(
  2265. "_unknown_fields_.ClearToEmptyNoArena(\n"
  2266. " &::google::protobuf::internal::GetEmptyStringAlreadyInited());\n");
  2267. }
  2268. }
  2269. }
  2270. printer->Outdent();
  2271. printer->Print("}\n");
  2272. }
  2273. void MessageGenerator::
  2274. GenerateOneofClear(io::Printer* printer) {
  2275. // Generated function clears the active field and union case (e.g. foo_case_).
  2276. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  2277. map<string, string> oneof_vars;
  2278. oneof_vars["classname"] = classname_;
  2279. oneof_vars["oneofname"] = descriptor_->oneof_decl(i)->name();
  2280. string message_class;
  2281. printer->Print(oneof_vars,
  2282. "void $classname$::clear_$oneofname$() {\n");
  2283. printer->Indent();
  2284. printer->Print(oneof_vars,
  2285. "switch($oneofname$_case()) {\n");
  2286. printer->Indent();
  2287. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  2288. const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
  2289. printer->Print(
  2290. "case k$field_name$: {\n",
  2291. "field_name", UnderscoresToCamelCase(field->name(), true));
  2292. printer->Indent();
  2293. // We clear only allocated objects in oneofs
  2294. if (!IsStringOrMessage(field)) {
  2295. printer->Print(
  2296. "// No need to clear\n");
  2297. } else {
  2298. field_generators_.get(field).GenerateClearingCode(printer);
  2299. }
  2300. printer->Print(
  2301. "break;\n");
  2302. printer->Outdent();
  2303. printer->Print(
  2304. "}\n");
  2305. }
  2306. printer->Print(
  2307. "case $cap_oneof_name$_NOT_SET: {\n"
  2308. " break;\n"
  2309. "}\n",
  2310. "cap_oneof_name",
  2311. ToUpper(descriptor_->oneof_decl(i)->name()));
  2312. printer->Outdent();
  2313. printer->Print(
  2314. "}\n"
  2315. "_oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n",
  2316. "oneof_index", SimpleItoa(i),
  2317. "cap_oneof_name",
  2318. ToUpper(descriptor_->oneof_decl(i)->name()));
  2319. printer->Outdent();
  2320. printer->Print(
  2321. "}\n"
  2322. "\n");
  2323. }
  2324. }
  2325. void MessageGenerator::
  2326. GenerateSwap(io::Printer* printer) {
  2327. if (SupportsArenas(descriptor_)) {
  2328. // Generate the Swap member function. This is a lightweight wrapper around
  2329. // UnsafeArenaSwap() / MergeFrom() with temporaries, depending on the memory
  2330. // ownership situation: swapping across arenas or between an arena and a
  2331. // heap requires copying.
  2332. printer->Print(
  2333. "void $classname$::Swap($classname$* other) {\n"
  2334. " if (other == this) return;\n"
  2335. " if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {\n"
  2336. " InternalSwap(other);\n"
  2337. " } else {\n"
  2338. " $classname$ temp;\n"
  2339. " temp.MergeFrom(*this);\n"
  2340. " CopyFrom(*other);\n"
  2341. " other->CopyFrom(temp);\n"
  2342. " }\n"
  2343. "}\n"
  2344. "void $classname$::UnsafeArenaSwap($classname$* other) {\n"
  2345. " if (other == this) return;\n"
  2346. " GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());\n"
  2347. " InternalSwap(other);\n"
  2348. "}\n",
  2349. "classname", classname_);
  2350. } else {
  2351. printer->Print(
  2352. "void $classname$::Swap($classname$* other) {\n"
  2353. " if (other == this) return;\n"
  2354. " InternalSwap(other);\n"
  2355. "}\n",
  2356. "classname", classname_);
  2357. }
  2358. // Generate the UnsafeArenaSwap member function.
  2359. printer->Print("void $classname$::InternalSwap($classname$* other) {\n",
  2360. "classname", classname_);
  2361. printer->Indent();
  2362. if (HasGeneratedMethods(descriptor_->file())) {
  2363. for (int i = 0; i < descriptor_->field_count(); i++) {
  2364. const FieldDescriptor* field = descriptor_->field(i);
  2365. field_generators_.get(field).GenerateSwappingCode(printer);
  2366. }
  2367. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  2368. printer->Print(
  2369. "std::swap($oneof_name$_, other->$oneof_name$_);\n"
  2370. "std::swap(_oneof_case_[$i$], other->_oneof_case_[$i$]);\n",
  2371. "oneof_name", descriptor_->oneof_decl(i)->name(),
  2372. "i", SimpleItoa(i));
  2373. }
  2374. if (HasFieldPresence(descriptor_->file())) {
  2375. for (int i = 0; i < (descriptor_->field_count() + 31) / 32; ++i) {
  2376. printer->Print("std::swap(_has_bits_[$i$], other->_has_bits_[$i$]);\n",
  2377. "i", SimpleItoa(i));
  2378. }
  2379. }
  2380. // Ignore PreserveUnknownFields here - always swap internal_metadata as it
  2381. // may contain more than just unknown fields.
  2382. if (UseUnknownFieldSet(descriptor_->file())) {
  2383. printer->Print(
  2384. "_internal_metadata_.Swap(&other->_internal_metadata_);\n");
  2385. } else {
  2386. printer->Print("_unknown_fields_.Swap(&other->_unknown_fields_);\n");
  2387. }
  2388. printer->Print("std::swap(_cached_size_, other->_cached_size_);\n");
  2389. if (descriptor_->extension_range_count() > 0) {
  2390. printer->Print("_extensions_.Swap(&other->_extensions_);\n");
  2391. }
  2392. } else {
  2393. printer->Print("GetReflection()->Swap(this, other);");
  2394. }
  2395. printer->Outdent();
  2396. printer->Print("}\n");
  2397. }
  2398. void MessageGenerator::
  2399. GenerateMergeFrom(io::Printer* printer) {
  2400. if (HasDescriptorMethods(descriptor_->file())) {
  2401. // Generate the generalized MergeFrom (aka that which takes in the Message
  2402. // base class as a parameter).
  2403. printer->Print(
  2404. "void $classname$::MergeFrom(const ::google::protobuf::Message& from) {\n"
  2405. " if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);\n",
  2406. "classname", classname_);
  2407. printer->Indent();
  2408. // Cast the message to the proper type. If we find that the message is
  2409. // *not* of the proper type, we can still call Merge via the reflection
  2410. // system, as the GOOGLE_CHECK above ensured that we have the same descriptor
  2411. // for each message.
  2412. printer->Print(
  2413. "const $classname$* source = \n"
  2414. " ::google::protobuf::internal::DynamicCastToGenerated<const $classname$>(\n"
  2415. " &from);\n"
  2416. "if (source == NULL) {\n"
  2417. " ::google::protobuf::internal::ReflectionOps::Merge(from, this);\n"
  2418. "} else {\n"
  2419. " MergeFrom(*source);\n"
  2420. "}\n",
  2421. "classname", classname_);
  2422. printer->Outdent();
  2423. printer->Print("}\n\n");
  2424. } else {
  2425. // Generate CheckTypeAndMergeFrom().
  2426. printer->Print(
  2427. "void $classname$::CheckTypeAndMergeFrom(\n"
  2428. " const ::google::protobuf::MessageLite& from) {\n"
  2429. " MergeFrom(*::google::protobuf::down_cast<const $classname$*>(&from));\n"
  2430. "}\n"
  2431. "\n",
  2432. "classname", classname_);
  2433. }
  2434. // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast.
  2435. printer->Print(
  2436. "void $classname$::MergeFrom(const $classname$& from) {\n"
  2437. " if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);\n",
  2438. "classname", classname_);
  2439. printer->Indent();
  2440. // Merge Repeated fields. These fields do not require a
  2441. // check as we can simply iterate over them.
  2442. for (int i = 0; i < descriptor_->field_count(); ++i) {
  2443. const FieldDescriptor* field = descriptor_->field(i);
  2444. if (field->is_repeated()) {
  2445. field_generators_.get(field).GenerateMergingCode(printer);
  2446. }
  2447. }
  2448. // Merge oneof fields. Oneof field requires oneof case check.
  2449. for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) {
  2450. printer->Print(
  2451. "switch (from.$oneofname$_case()) {\n",
  2452. "oneofname", descriptor_->oneof_decl(i)->name());
  2453. printer->Indent();
  2454. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  2455. const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
  2456. printer->Print(
  2457. "case k$field_name$: {\n",
  2458. "field_name", UnderscoresToCamelCase(field->name(), true));
  2459. printer->Indent();
  2460. field_generators_.get(field).GenerateMergingCode(printer);
  2461. printer->Print(
  2462. "break;\n");
  2463. printer->Outdent();
  2464. printer->Print(
  2465. "}\n");
  2466. }
  2467. printer->Print(
  2468. "case $cap_oneof_name$_NOT_SET: {\n"
  2469. " break;\n"
  2470. "}\n",
  2471. "cap_oneof_name",
  2472. ToUpper(descriptor_->oneof_decl(i)->name()));
  2473. printer->Outdent();
  2474. printer->Print(
  2475. "}\n");
  2476. }
  2477. // Merge Optional and Required fields (after a _has_bit check).
  2478. int last_index = -1;
  2479. for (int i = 0; i < descriptor_->field_count(); ++i) {
  2480. const FieldDescriptor* field = descriptor_->field(i);
  2481. if (!field->is_repeated() && !field->containing_oneof()) {
  2482. if (HasFieldPresence(descriptor_->file())) {
  2483. // See above in GenerateClear for an explanation of this.
  2484. if (i / 8 != last_index / 8 || last_index < 0) {
  2485. if (last_index >= 0) {
  2486. printer->Outdent();
  2487. printer->Print("}\n");
  2488. }
  2489. printer->Print(
  2490. "if (from._has_bits_[$index$ / 32] & "
  2491. "(0xffu << ($index$ % 32))) {\n",
  2492. "index", SimpleItoa(field->index()));
  2493. printer->Indent();
  2494. }
  2495. }
  2496. last_index = i;
  2497. bool have_enclosing_if = false;
  2498. if (HasFieldPresence(descriptor_->file())) {
  2499. printer->Print(
  2500. "if (from.has_$name$()) {\n",
  2501. "name", FieldName(field));
  2502. printer->Indent();
  2503. have_enclosing_if = true;
  2504. } else {
  2505. // Merge semantics without true field presence: primitive fields are
  2506. // merged only if non-zero (numeric) or non-empty (string).
  2507. have_enclosing_if = EmitFieldNonDefaultCondition(
  2508. printer, "from.", field);
  2509. }
  2510. field_generators_.get(field).GenerateMergingCode(printer);
  2511. if (have_enclosing_if) {
  2512. printer->Outdent();
  2513. printer->Print("}\n");
  2514. }
  2515. }
  2516. }
  2517. if (HasFieldPresence(descriptor_->file()) &&
  2518. last_index >= 0) {
  2519. printer->Outdent();
  2520. printer->Print("}\n");
  2521. }
  2522. if (descriptor_->extension_range_count() > 0) {
  2523. printer->Print("_extensions_.MergeFrom(from._extensions_);\n");
  2524. }
  2525. if (PreserveUnknownFields(descriptor_)) {
  2526. if (UseUnknownFieldSet(descriptor_->file())) {
  2527. printer->Print(
  2528. "if (from._internal_metadata_.have_unknown_fields()) {\n"
  2529. " mutable_unknown_fields()->MergeFrom(from.unknown_fields());\n"
  2530. "}\n");
  2531. } else {
  2532. printer->Print(
  2533. "if (!from.unknown_fields().empty()) {\n"
  2534. " mutable_unknown_fields()->append(from.unknown_fields());\n"
  2535. "}\n");
  2536. }
  2537. }
  2538. printer->Outdent();
  2539. printer->Print("}\n");
  2540. }
  2541. void MessageGenerator::
  2542. GenerateCopyFrom(io::Printer* printer) {
  2543. if (HasDescriptorMethods(descriptor_->file())) {
  2544. // Generate the generalized CopyFrom (aka that which takes in the Message
  2545. // base class as a parameter).
  2546. printer->Print(
  2547. "void $classname$::CopyFrom(const ::google::protobuf::Message& from) {\n",
  2548. "classname", classname_);
  2549. printer->Indent();
  2550. printer->Print(
  2551. "if (&from == this) return;\n"
  2552. "Clear();\n"
  2553. "MergeFrom(from);\n");
  2554. printer->Outdent();
  2555. printer->Print("}\n\n");
  2556. }
  2557. // Generate the class-specific CopyFrom.
  2558. printer->Print(
  2559. "void $classname$::CopyFrom(const $classname$& from) {\n",
  2560. "classname", classname_);
  2561. printer->Indent();
  2562. printer->Print(
  2563. "if (&from == this) return;\n"
  2564. "Clear();\n"
  2565. "MergeFrom(from);\n");
  2566. printer->Outdent();
  2567. printer->Print("}\n");
  2568. }
  2569. void MessageGenerator::
  2570. GenerateMergeFromCodedStream(io::Printer* printer) {
  2571. if (descriptor_->options().message_set_wire_format()) {
  2572. // Special-case MessageSet.
  2573. printer->Print(
  2574. "bool $classname$::MergePartialFromCodedStream(\n"
  2575. " ::google::protobuf::io::CodedInputStream* input) {\n",
  2576. "classname", classname_);
  2577. PrintHandlingOptionalStaticInitializers(
  2578. descriptor_->file(), printer,
  2579. // With static initializers.
  2580. " return _extensions_.ParseMessageSet(input, default_instance_,\n"
  2581. " mutable_unknown_fields());\n",
  2582. // Without.
  2583. " return _extensions_.ParseMessageSet(input, &default_instance(),\n"
  2584. " mutable_unknown_fields());\n",
  2585. // Vars.
  2586. "classname", classname_);
  2587. printer->Print(
  2588. "}\n");
  2589. return;
  2590. }
  2591. printer->Print(
  2592. "bool $classname$::MergePartialFromCodedStream(\n"
  2593. " ::google::protobuf::io::CodedInputStream* input) {\n"
  2594. "#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure\n"
  2595. " ::google::protobuf::uint32 tag;\n",
  2596. "classname", classname_);
  2597. if (PreserveUnknownFields(descriptor_) &&
  2598. !UseUnknownFieldSet(descriptor_->file())) {
  2599. // Use LazyStringOutputString to avoid initializing unknown fields string
  2600. // unless it is actually needed. For the same reason, disable eager refresh
  2601. // on the CodedOutputStream.
  2602. printer->Print(
  2603. " ::google::protobuf::io::LazyStringOutputStream unknown_fields_string(\n"
  2604. " google::protobuf::internal::NewPermanentCallback(\n"
  2605. " &MutableUnknownFieldsFor$classname$, this));\n"
  2606. " ::google::protobuf::io::CodedOutputStream unknown_fields_stream(\n"
  2607. " &unknown_fields_string, false);\n",
  2608. "classname", classname_);
  2609. }
  2610. printer->Print(
  2611. " // @@protoc_insertion_point(parse_start:$full_name$)\n",
  2612. "full_name", descriptor_->full_name());
  2613. printer->Indent();
  2614. printer->Print("for (;;) {\n");
  2615. printer->Indent();
  2616. google::protobuf::scoped_array<const FieldDescriptor * > ordered_fields(
  2617. SortFieldsByNumber(descriptor_));
  2618. uint32 maxtag = descriptor_->field_count() == 0 ? 0 :
  2619. WireFormat::MakeTag(ordered_fields[descriptor_->field_count() - 1]);
  2620. const int kCutoff0 = 127; // fits in 1-byte varint
  2621. const int kCutoff1 = (127 << 7) + 127; // fits in 2-byte varint
  2622. printer->Print("::std::pair< ::google::protobuf::uint32, bool> p = "
  2623. "input->ReadTagWithCutoff($max$);\n"
  2624. "tag = p.first;\n"
  2625. "if (!p.second) goto handle_unusual;\n",
  2626. "max", SimpleItoa(maxtag <= kCutoff0 ? kCutoff0 :
  2627. (maxtag <= kCutoff1 ? kCutoff1 :
  2628. maxtag)));
  2629. if (descriptor_->field_count() > 0) {
  2630. // We don't even want to print the switch() if we have no fields because
  2631. // MSVC dislikes switch() statements that contain only a default value.
  2632. // Note: If we just switched on the tag rather than the field number, we
  2633. // could avoid the need for the if() to check the wire type at the beginning
  2634. // of each case. However, this is actually a bit slower in practice as it
  2635. // creates a jump table that is 8x larger and sparser, and meanwhile the
  2636. // if()s are highly predictable.
  2637. printer->Print("switch (::google::protobuf::internal::WireFormatLite::"
  2638. "GetTagFieldNumber(tag)) {\n");
  2639. printer->Indent();
  2640. // Find repeated messages and groups now, to simplify what follows.
  2641. hash_set<int> fields_with_parse_loop;
  2642. for (int i = 0; i < descriptor_->field_count(); i++) {
  2643. const FieldDescriptor* field = ordered_fields[i];
  2644. if (field->is_repeated() &&
  2645. (field->type() == FieldDescriptor::TYPE_MESSAGE ||
  2646. field->type() == FieldDescriptor::TYPE_GROUP)) {
  2647. fields_with_parse_loop.insert(i);
  2648. }
  2649. }
  2650. // need_label is true if we generated "goto parse_$name$" while handling the
  2651. // previous field.
  2652. bool need_label = false;
  2653. for (int i = 0; i < descriptor_->field_count(); i++) {
  2654. const FieldDescriptor* field = ordered_fields[i];
  2655. const bool loops = fields_with_parse_loop.count(i) > 0;
  2656. const bool next_field_loops = fields_with_parse_loop.count(i + 1) > 0;
  2657. PrintFieldComment(printer, field);
  2658. printer->Print(
  2659. "case $number$: {\n",
  2660. "number", SimpleItoa(field->number()));
  2661. printer->Indent();
  2662. const FieldGenerator& field_generator = field_generators_.get(field);
  2663. // Emit code to parse the common, expected case.
  2664. printer->Print("if (tag == $commontag$) {\n",
  2665. "commontag", SimpleItoa(WireFormat::MakeTag(field)));
  2666. if (need_label ||
  2667. (field->is_repeated() && !field->is_packed() && !loops)) {
  2668. printer->Print(
  2669. " parse_$name$:\n",
  2670. "name", field->name());
  2671. }
  2672. if (loops) {
  2673. printer->Print(
  2674. " DO_(input->IncrementRecursionDepth());\n"
  2675. " parse_loop_$name$:\n",
  2676. "name", field->name());
  2677. }
  2678. printer->Indent();
  2679. if (field->is_packed()) {
  2680. field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
  2681. } else {
  2682. field_generator.GenerateMergeFromCodedStream(printer);
  2683. }
  2684. printer->Outdent();
  2685. // Emit code to parse unexpectedly packed or unpacked values.
  2686. if (field->is_packed()) {
  2687. internal::WireFormatLite::WireType wiretype =
  2688. WireFormat::WireTypeForFieldType(field->type());
  2689. printer->Print("} else if (tag == $uncommontag$) {\n",
  2690. "uncommontag", SimpleItoa(
  2691. internal::WireFormatLite::MakeTag(
  2692. field->number(), wiretype)));
  2693. printer->Indent();
  2694. field_generator.GenerateMergeFromCodedStream(printer);
  2695. printer->Outdent();
  2696. } else if (field->is_packable() && !field->is_packed()) {
  2697. internal::WireFormatLite::WireType wiretype =
  2698. internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
  2699. printer->Print("} else if (tag == $uncommontag$) {\n",
  2700. "uncommontag", SimpleItoa(
  2701. internal::WireFormatLite::MakeTag(
  2702. field->number(), wiretype)));
  2703. printer->Indent();
  2704. field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
  2705. printer->Outdent();
  2706. }
  2707. printer->Print(
  2708. "} else {\n"
  2709. " goto handle_unusual;\n"
  2710. "}\n");
  2711. // switch() is slow since it can't be predicted well. Insert some if()s
  2712. // here that attempt to predict the next tag.
  2713. // For non-packed repeated fields, expect the same tag again.
  2714. if (loops) {
  2715. printer->Print(
  2716. "if (input->ExpectTag($tag$)) goto parse_loop_$name$;\n",
  2717. "tag", SimpleItoa(WireFormat::MakeTag(field)),
  2718. "name", field->name());
  2719. } else if (field->is_repeated() && !field->is_packed()) {
  2720. printer->Print(
  2721. "if (input->ExpectTag($tag$)) goto parse_$name$;\n",
  2722. "tag", SimpleItoa(WireFormat::MakeTag(field)),
  2723. "name", field->name());
  2724. }
  2725. // Have we emitted "if (input->ExpectTag($next_tag$)) ..." yet?
  2726. bool emitted_goto_next_tag = false;
  2727. // For repeated messages/groups, we need to decrement recursion depth,
  2728. // unless the next tag is also for a repeated message/group.
  2729. if (loops) {
  2730. if (next_field_loops) {
  2731. const FieldDescriptor* next_field = ordered_fields[i + 1];
  2732. printer->Print(
  2733. "if (input->ExpectTag($next_tag$)) goto parse_loop_$next_name$;\n",
  2734. "next_tag", SimpleItoa(WireFormat::MakeTag(next_field)),
  2735. "next_name", next_field->name());
  2736. emitted_goto_next_tag = true;
  2737. }
  2738. printer->Print(
  2739. "input->UnsafeDecrementRecursionDepth();\n");
  2740. }
  2741. // If there are more fields, expect the next one.
  2742. need_label = false;
  2743. if (!emitted_goto_next_tag) {
  2744. if (i + 1 == descriptor_->field_count()) {
  2745. // Expect EOF.
  2746. // TODO(kenton): Expect group end-tag?
  2747. printer->Print(
  2748. "if (input->ExpectAtEnd()) goto success;\n");
  2749. } else {
  2750. const FieldDescriptor* next_field = ordered_fields[i + 1];
  2751. printer->Print(
  2752. "if (input->ExpectTag($next_tag$)) goto parse_$next_name$;\n",
  2753. "next_tag", SimpleItoa(WireFormat::MakeTag(next_field)),
  2754. "next_name", next_field->name());
  2755. need_label = true;
  2756. }
  2757. }
  2758. printer->Print(
  2759. "break;\n");
  2760. printer->Outdent();
  2761. printer->Print("}\n\n");
  2762. }
  2763. printer->Print("default: {\n");
  2764. printer->Indent();
  2765. }
  2766. printer->Outdent();
  2767. printer->Print("handle_unusual:\n");
  2768. printer->Indent();
  2769. // If tag is 0 or an end-group tag then this must be the end of the message.
  2770. printer->Print(
  2771. "if (tag == 0 ||\n"
  2772. " ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==\n"
  2773. " ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n"
  2774. " goto success;\n"
  2775. "}\n");
  2776. // Handle extension ranges.
  2777. if (descriptor_->extension_range_count() > 0) {
  2778. printer->Print(
  2779. "if (");
  2780. for (int i = 0; i < descriptor_->extension_range_count(); i++) {
  2781. const Descriptor::ExtensionRange* range =
  2782. descriptor_->extension_range(i);
  2783. if (i > 0) printer->Print(" ||\n ");
  2784. uint32 start_tag = WireFormatLite::MakeTag(
  2785. range->start, static_cast<WireFormatLite::WireType>(0));
  2786. uint32 end_tag = WireFormatLite::MakeTag(
  2787. range->end, static_cast<WireFormatLite::WireType>(0));
  2788. if (range->end > FieldDescriptor::kMaxNumber) {
  2789. printer->Print(
  2790. "($start$u <= tag)",
  2791. "start", SimpleItoa(start_tag));
  2792. } else {
  2793. printer->Print(
  2794. "($start$u <= tag && tag < $end$u)",
  2795. "start", SimpleItoa(start_tag),
  2796. "end", SimpleItoa(end_tag));
  2797. }
  2798. }
  2799. printer->Print(") {\n");
  2800. if (PreserveUnknownFields(descriptor_)) {
  2801. if (UseUnknownFieldSet(descriptor_->file())) {
  2802. PrintHandlingOptionalStaticInitializers(
  2803. descriptor_->file(), printer,
  2804. // With static initializers.
  2805. " DO_(_extensions_.ParseField(tag, input, default_instance_,\n"
  2806. " mutable_unknown_fields()));\n",
  2807. // Without.
  2808. " DO_(_extensions_.ParseField(tag, input, &default_instance(),\n"
  2809. " mutable_unknown_fields()));\n");
  2810. } else {
  2811. PrintHandlingOptionalStaticInitializers(
  2812. descriptor_->file(), printer,
  2813. // With static initializers.
  2814. " DO_(_extensions_.ParseField(tag, input, default_instance_,\n"
  2815. " &unknown_fields_stream));\n",
  2816. // Without.
  2817. " DO_(_extensions_.ParseField(tag, input, &default_instance(),\n"
  2818. " &unknown_fields_stream));\n");
  2819. }
  2820. } else {
  2821. PrintHandlingOptionalStaticInitializers(
  2822. descriptor_->file(), printer,
  2823. // With static initializers.
  2824. " DO_(_extensions_.ParseField(tag, input, default_instance_);\n",
  2825. // Without.
  2826. " DO_(_extensions_.ParseField(tag, input, &default_instance());\n");
  2827. }
  2828. printer->Print(
  2829. " continue;\n"
  2830. "}\n");
  2831. }
  2832. // We really don't recognize this tag. Skip it.
  2833. if (PreserveUnknownFields(descriptor_)) {
  2834. if (UseUnknownFieldSet(descriptor_->file())) {
  2835. printer->Print(
  2836. "DO_(::google::protobuf::internal::WireFormat::SkipField(\n"
  2837. " input, tag, mutable_unknown_fields()));\n");
  2838. } else {
  2839. printer->Print(
  2840. "DO_(::google::protobuf::internal::WireFormatLite::SkipField(\n"
  2841. " input, tag, &unknown_fields_stream));\n");
  2842. }
  2843. } else {
  2844. printer->Print(
  2845. "DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));\n");
  2846. }
  2847. if (descriptor_->field_count() > 0) {
  2848. printer->Print("break;\n");
  2849. printer->Outdent();
  2850. printer->Print("}\n"); // default:
  2851. printer->Outdent();
  2852. printer->Print("}\n"); // switch
  2853. }
  2854. printer->Outdent();
  2855. printer->Outdent();
  2856. printer->Print(
  2857. " }\n" // for (;;)
  2858. "success:\n"
  2859. " // @@protoc_insertion_point(parse_success:$full_name$)\n"
  2860. " return true;\n"
  2861. "failure:\n"
  2862. " // @@protoc_insertion_point(parse_failure:$full_name$)\n"
  2863. " return false;\n"
  2864. "#undef DO_\n"
  2865. "}\n", "full_name", descriptor_->full_name());
  2866. }
  2867. void MessageGenerator::GenerateSerializeOneField(
  2868. io::Printer* printer, const FieldDescriptor* field, bool to_array) {
  2869. PrintFieldComment(printer, field);
  2870. bool have_enclosing_if = false;
  2871. if (!field->is_repeated() && HasFieldPresence(descriptor_->file())) {
  2872. printer->Print(
  2873. "if (has_$name$()) {\n",
  2874. "name", FieldName(field));
  2875. printer->Indent();
  2876. have_enclosing_if = true;
  2877. } else if (!HasFieldPresence(descriptor_->file())) {
  2878. have_enclosing_if = EmitFieldNonDefaultCondition(printer, "this->", field);
  2879. }
  2880. if (to_array) {
  2881. field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(
  2882. printer);
  2883. } else {
  2884. field_generators_.get(field).GenerateSerializeWithCachedSizes(printer);
  2885. }
  2886. if (have_enclosing_if) {
  2887. printer->Outdent();
  2888. printer->Print("}\n");
  2889. }
  2890. printer->Print("\n");
  2891. }
  2892. void MessageGenerator::GenerateSerializeOneExtensionRange(
  2893. io::Printer* printer, const Descriptor::ExtensionRange* range,
  2894. bool to_array) {
  2895. map<string, string> vars;
  2896. vars["start"] = SimpleItoa(range->start);
  2897. vars["end"] = SimpleItoa(range->end);
  2898. printer->Print(vars,
  2899. "// Extension range [$start$, $end$)\n");
  2900. if (to_array) {
  2901. printer->Print(vars,
  2902. "target = _extensions_.SerializeWithCachedSizesToArray(\n"
  2903. " $start$, $end$, target);\n\n");
  2904. } else {
  2905. printer->Print(vars,
  2906. "_extensions_.SerializeWithCachedSizes(\n"
  2907. " $start$, $end$, output);\n\n");
  2908. }
  2909. }
  2910. void MessageGenerator::
  2911. GenerateSerializeWithCachedSizes(io::Printer* printer) {
  2912. if (descriptor_->options().message_set_wire_format()) {
  2913. // Special-case MessageSet.
  2914. printer->Print(
  2915. "void $classname$::SerializeWithCachedSizes(\n"
  2916. " ::google::protobuf::io::CodedOutputStream* output) const {\n"
  2917. " _extensions_.SerializeMessageSetWithCachedSizes(output);\n",
  2918. "classname", classname_);
  2919. GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file()));
  2920. printer->Print(
  2921. " ::google::protobuf::internal::WireFormat::SerializeUnknownMessageSetItems(\n"
  2922. " unknown_fields(), output);\n");
  2923. printer->Print(
  2924. "}\n");
  2925. return;
  2926. }
  2927. printer->Print(
  2928. "void $classname$::SerializeWithCachedSizes(\n"
  2929. " ::google::protobuf::io::CodedOutputStream* output) const {\n",
  2930. "classname", classname_);
  2931. printer->Indent();
  2932. printer->Print(
  2933. "// @@protoc_insertion_point(serialize_start:$full_name$)\n",
  2934. "full_name", descriptor_->full_name());
  2935. GenerateSerializeWithCachedSizesBody(printer, false);
  2936. printer->Print(
  2937. "// @@protoc_insertion_point(serialize_end:$full_name$)\n",
  2938. "full_name", descriptor_->full_name());
  2939. printer->Outdent();
  2940. printer->Print(
  2941. "}\n");
  2942. }
  2943. void MessageGenerator::
  2944. GenerateSerializeWithCachedSizesToArray(io::Printer* printer) {
  2945. if (descriptor_->options().message_set_wire_format()) {
  2946. // Special-case MessageSet.
  2947. printer->Print(
  2948. "::google::protobuf::uint8* $classname$::SerializeWithCachedSizesToArray(\n"
  2949. " ::google::protobuf::uint8* target) const {\n"
  2950. " target =\n"
  2951. " _extensions_.SerializeMessageSetWithCachedSizesToArray(target);\n",
  2952. "classname", classname_);
  2953. GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file()));
  2954. printer->Print(
  2955. " target = ::google::protobuf::internal::WireFormat::\n"
  2956. " SerializeUnknownMessageSetItemsToArray(\n"
  2957. " unknown_fields(), target);\n");
  2958. printer->Print(
  2959. " return target;\n"
  2960. "}\n");
  2961. return;
  2962. }
  2963. printer->Print(
  2964. "::google::protobuf::uint8* $classname$::SerializeWithCachedSizesToArray(\n"
  2965. " ::google::protobuf::uint8* target) const {\n",
  2966. "classname", classname_);
  2967. printer->Indent();
  2968. printer->Print(
  2969. "// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n",
  2970. "full_name", descriptor_->full_name());
  2971. GenerateSerializeWithCachedSizesBody(printer, true);
  2972. printer->Print(
  2973. "// @@protoc_insertion_point(serialize_to_array_end:$full_name$)\n",
  2974. "full_name", descriptor_->full_name());
  2975. printer->Outdent();
  2976. printer->Print(
  2977. " return target;\n"
  2978. "}\n");
  2979. }
  2980. void MessageGenerator::
  2981. GenerateSerializeWithCachedSizesBody(io::Printer* printer, bool to_array) {
  2982. google::protobuf::scoped_array<const FieldDescriptor * > ordered_fields(
  2983. SortFieldsByNumber(descriptor_));
  2984. vector<const Descriptor::ExtensionRange*> sorted_extensions;
  2985. for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
  2986. sorted_extensions.push_back(descriptor_->extension_range(i));
  2987. }
  2988. std::sort(sorted_extensions.begin(), sorted_extensions.end(),
  2989. ExtensionRangeSorter());
  2990. // Merge the fields and the extension ranges, both sorted by field number.
  2991. int i, j;
  2992. for (i = 0, j = 0;
  2993. i < descriptor_->field_count() || j < sorted_extensions.size();
  2994. ) {
  2995. if (i == descriptor_->field_count()) {
  2996. GenerateSerializeOneExtensionRange(printer,
  2997. sorted_extensions[j++],
  2998. to_array);
  2999. } else if (j == sorted_extensions.size()) {
  3000. GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
  3001. } else if (ordered_fields[i]->number() < sorted_extensions[j]->start) {
  3002. GenerateSerializeOneField(printer, ordered_fields[i++], to_array);
  3003. } else {
  3004. GenerateSerializeOneExtensionRange(printer,
  3005. sorted_extensions[j++],
  3006. to_array);
  3007. }
  3008. }
  3009. if (PreserveUnknownFields(descriptor_)) {
  3010. if (UseUnknownFieldSet(descriptor_->file())) {
  3011. printer->Print("if (_internal_metadata_.have_unknown_fields()) {\n");
  3012. printer->Indent();
  3013. if (to_array) {
  3014. printer->Print(
  3015. "target = "
  3016. "::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(\n"
  3017. " unknown_fields(), target);\n");
  3018. } else {
  3019. printer->Print(
  3020. "::google::protobuf::internal::WireFormat::SerializeUnknownFields(\n"
  3021. " unknown_fields(), output);\n");
  3022. }
  3023. printer->Outdent();
  3024. printer->Print(
  3025. "}\n");
  3026. } else {
  3027. printer->Print(
  3028. "output->WriteRaw(unknown_fields().data(),\n"
  3029. " static_cast<int>(unknown_fields().size()));\n");
  3030. }
  3031. }
  3032. }
  3033. static vector<uint32> RequiredFieldsBitMask(const Descriptor* desc) {
  3034. vector<uint32> result;
  3035. uint32 mask = 0;
  3036. for (int i = 0; i < desc->field_count(); i++) {
  3037. if (i > 0 && i % 32 == 0) {
  3038. result.push_back(mask);
  3039. mask = 0;
  3040. }
  3041. if (desc->field(i)->is_required()) {
  3042. mask |= (1 << (i & 31));
  3043. }
  3044. }
  3045. if (mask != 0) {
  3046. result.push_back(mask);
  3047. }
  3048. return result;
  3049. }
  3050. // Create an expression that evaluates to
  3051. // "for all i, (_has_bits_[i] & masks[i]) == masks[i]"
  3052. // masks is allowed to be shorter than _has_bits_, but at least one element of
  3053. // masks must be non-zero.
  3054. static string ConditionalToCheckBitmasks(const vector<uint32>& masks) {
  3055. vector<string> parts;
  3056. for (int i = 0; i < masks.size(); i++) {
  3057. if (masks[i] == 0) continue;
  3058. string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
  3059. // Each xor evaluates to 0 if the expected bits are present.
  3060. parts.push_back(StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")"));
  3061. }
  3062. GOOGLE_CHECK(!parts.empty());
  3063. // If we have multiple parts, each expected to be 0, then bitwise-or them.
  3064. string result = parts.size() == 1 ? parts[0] :
  3065. StrCat("(", Join(parts, "\n | "), ")");
  3066. return result + " == 0";
  3067. }
  3068. void MessageGenerator::
  3069. GenerateByteSize(io::Printer* printer) {
  3070. if (descriptor_->options().message_set_wire_format()) {
  3071. // Special-case MessageSet.
  3072. printer->Print(
  3073. "int $classname$::ByteSize() const {\n"
  3074. " int total_size = _extensions_.MessageSetByteSize();\n",
  3075. "classname", classname_);
  3076. GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file()));
  3077. printer->Print(
  3078. "if (_internal_metadata_.have_unknown_fields()) {\n"
  3079. " total_size += ::google::protobuf::internal::WireFormat::\n"
  3080. " ComputeUnknownMessageSetItemsSize(unknown_fields());\n"
  3081. "}\n");
  3082. printer->Print(
  3083. " GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
  3084. " _cached_size_ = total_size;\n"
  3085. " GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
  3086. " return total_size;\n"
  3087. "}\n");
  3088. return;
  3089. }
  3090. if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) {
  3091. // Emit a function (rarely used, we hope) that handles the required fields
  3092. // by checking for each one individually.
  3093. printer->Print(
  3094. "int $classname$::RequiredFieldsByteSizeFallback() const {\n",
  3095. "classname", classname_);
  3096. printer->Indent();
  3097. printer->Print("int total_size = 0;\n");
  3098. for (int i = 0; i < descriptor_->field_count(); i++) {
  3099. const FieldDescriptor* field = descriptor_->field(i);
  3100. if (field->is_required()) {
  3101. printer->Print("\n"
  3102. "if (has_$name$()) {\n",
  3103. "name", FieldName(field));
  3104. printer->Indent();
  3105. PrintFieldComment(printer, field);
  3106. field_generators_.get(field).GenerateByteSize(printer);
  3107. printer->Outdent();
  3108. printer->Print("}\n");
  3109. }
  3110. }
  3111. printer->Print("\n"
  3112. "return total_size;\n");
  3113. printer->Outdent();
  3114. printer->Print("}\n");
  3115. }
  3116. printer->Print(
  3117. "int $classname$::ByteSize() const {\n",
  3118. "classname", classname_);
  3119. printer->Indent();
  3120. printer->Print(
  3121. "int total_size = 0;\n"
  3122. "\n");
  3123. // Handle required fields (if any). We expect all of them to be
  3124. // present, so emit one conditional that checks for that. If they are all
  3125. // present then the fast path executes; otherwise the slow path executes.
  3126. if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) {
  3127. // The fast path works if all required fields are present.
  3128. vector<uint32> masks_for_has_bits = RequiredFieldsBitMask(descriptor_);
  3129. printer->Print((string("if (") +
  3130. ConditionalToCheckBitmasks(masks_for_has_bits) +
  3131. ") { // All required fields are present.\n").c_str());
  3132. printer->Indent();
  3133. for (int i = 0; i < descriptor_->field_count(); i++) {
  3134. const FieldDescriptor* field = descriptor_->field(i);
  3135. if (!field->is_required()) continue;
  3136. PrintFieldComment(printer, field);
  3137. field_generators_.get(field).GenerateByteSize(printer);
  3138. printer->Print("\n");
  3139. }
  3140. printer->Outdent();
  3141. printer->Print("} else {\n" // the slow path
  3142. " total_size += RequiredFieldsByteSizeFallback();\n"
  3143. "}\n");
  3144. } else {
  3145. // num_required_fields_ <= 1: no need to be tricky
  3146. for (int i = 0; i < descriptor_->field_count(); i++) {
  3147. const FieldDescriptor* field = descriptor_->field(i);
  3148. if (!field->is_required()) continue;
  3149. PrintFieldComment(printer, field);
  3150. printer->Print("if (has_$name$()) {\n",
  3151. "name", FieldName(field));
  3152. printer->Indent();
  3153. field_generators_.get(field).GenerateByteSize(printer);
  3154. printer->Outdent();
  3155. printer->Print("}\n");
  3156. }
  3157. }
  3158. // Handle optional fields (worry below about repeateds, oneofs, etc.).
  3159. // These are handled in chunks of 8. The first chunk is
  3160. // the non-requireds-non-repeateds-non-unions-non-extensions in
  3161. // descriptor_->field(0), descriptor_->field(1), ... descriptor_->field(7),
  3162. // and the second chunk is the same for
  3163. // descriptor_->field(8), descriptor_->field(9), ... descriptor_->field(15),
  3164. // etc.
  3165. hash_map<int, uint32> fields_mask_for_chunk;
  3166. for (int i = 0; i < descriptor_->field_count(); i++) {
  3167. const FieldDescriptor* field = descriptor_->field(i);
  3168. if (!field->is_required() && !field->is_repeated() &&
  3169. !field->containing_oneof()) {
  3170. fields_mask_for_chunk[i / 8] |= static_cast<uint32>(1) << (i % 32);
  3171. }
  3172. }
  3173. int last_index = -1;
  3174. bool chunk_block_in_progress = false;
  3175. for (int i = 0; i < descriptor_->field_count(); i++) {
  3176. const FieldDescriptor* field = descriptor_->field(i);
  3177. if (!field->is_required() && !field->is_repeated() &&
  3178. !field->containing_oneof()) {
  3179. // See above in GenerateClear for an explanation of this.
  3180. // TODO(kenton): Share code? Unclear how to do so without
  3181. // over-engineering.
  3182. if (i / 8 != last_index / 8 || last_index < 0) {
  3183. // End previous chunk, if there was one.
  3184. if (chunk_block_in_progress) {
  3185. printer->Outdent();
  3186. printer->Print("}\n");
  3187. chunk_block_in_progress = false;
  3188. }
  3189. // Start chunk.
  3190. uint32 mask = fields_mask_for_chunk[i / 8];
  3191. int count = popcnt(mask);
  3192. GOOGLE_DCHECK_GE(count, 1);
  3193. if (count == 1) {
  3194. // No "if" here because the chunk is trivial.
  3195. } else {
  3196. if (HasFieldPresence(descriptor_->file())) {
  3197. printer->Print(
  3198. "if (_has_bits_[$index$ / 32] & $mask$u) {\n",
  3199. "index", SimpleItoa(i),
  3200. "mask", SimpleItoa(mask));
  3201. printer->Indent();
  3202. chunk_block_in_progress = true;
  3203. }
  3204. }
  3205. }
  3206. last_index = i;
  3207. PrintFieldComment(printer, field);
  3208. bool have_enclosing_if = false;
  3209. if (HasFieldPresence(descriptor_->file())) {
  3210. printer->Print(
  3211. "if (has_$name$()) {\n",
  3212. "name", FieldName(field));
  3213. printer->Indent();
  3214. have_enclosing_if = true;
  3215. } else {
  3216. // Without field presence: field is serialized only if it has a
  3217. // non-default value.
  3218. have_enclosing_if = EmitFieldNonDefaultCondition(
  3219. printer, "this->", field);
  3220. }
  3221. field_generators_.get(field).GenerateByteSize(printer);
  3222. if (have_enclosing_if) {
  3223. printer->Outdent();
  3224. printer->Print(
  3225. "}\n"
  3226. "\n");
  3227. }
  3228. }
  3229. }
  3230. if (chunk_block_in_progress) {
  3231. printer->Outdent();
  3232. printer->Print("}\n");
  3233. }
  3234. // Repeated fields don't use _has_bits_ so we count them in a separate
  3235. // pass.
  3236. for (int i = 0; i < descriptor_->field_count(); i++) {
  3237. const FieldDescriptor* field = descriptor_->field(i);
  3238. if (field->is_repeated()) {
  3239. PrintFieldComment(printer, field);
  3240. field_generators_.get(field).GenerateByteSize(printer);
  3241. printer->Print("\n");
  3242. }
  3243. }
  3244. // Fields inside a oneof don't use _has_bits_ so we count them in a separate
  3245. // pass.
  3246. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  3247. printer->Print(
  3248. "switch ($oneofname$_case()) {\n",
  3249. "oneofname", descriptor_->oneof_decl(i)->name());
  3250. printer->Indent();
  3251. for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) {
  3252. const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j);
  3253. PrintFieldComment(printer, field);
  3254. printer->Print(
  3255. "case k$field_name$: {\n",
  3256. "field_name", UnderscoresToCamelCase(field->name(), true));
  3257. printer->Indent();
  3258. field_generators_.get(field).GenerateByteSize(printer);
  3259. printer->Print(
  3260. "break;\n");
  3261. printer->Outdent();
  3262. printer->Print(
  3263. "}\n");
  3264. }
  3265. printer->Print(
  3266. "case $cap_oneof_name$_NOT_SET: {\n"
  3267. " break;\n"
  3268. "}\n",
  3269. "cap_oneof_name",
  3270. ToUpper(descriptor_->oneof_decl(i)->name()));
  3271. printer->Outdent();
  3272. printer->Print(
  3273. "}\n");
  3274. }
  3275. if (descriptor_->extension_range_count() > 0) {
  3276. printer->Print(
  3277. "total_size += _extensions_.ByteSize();\n"
  3278. "\n");
  3279. }
  3280. if (PreserveUnknownFields(descriptor_)) {
  3281. if (UseUnknownFieldSet(descriptor_->file())) {
  3282. printer->Print(
  3283. "if (_internal_metadata_.have_unknown_fields()) {\n"
  3284. " total_size +=\n"
  3285. " ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(\n"
  3286. " unknown_fields());\n"
  3287. "}\n");
  3288. } else {
  3289. printer->Print(
  3290. "total_size += unknown_fields().size();\n"
  3291. "\n");
  3292. }
  3293. }
  3294. // We update _cached_size_ even though this is a const method. In theory,
  3295. // this is not thread-compatible, because concurrent writes have undefined
  3296. // results. In practice, since any concurrent writes will be writing the
  3297. // exact same value, it works on all common processors. In a future version
  3298. // of C++, _cached_size_ should be made into an atomic<int>.
  3299. printer->Print(
  3300. "GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();\n"
  3301. "_cached_size_ = total_size;\n"
  3302. "GOOGLE_SAFE_CONCURRENT_WRITES_END();\n"
  3303. "return total_size;\n");
  3304. printer->Outdent();
  3305. printer->Print("}\n");
  3306. }
  3307. void MessageGenerator::
  3308. GenerateIsInitialized(io::Printer* printer) {
  3309. printer->Print(
  3310. "bool $classname$::IsInitialized() const {\n",
  3311. "classname", classname_);
  3312. printer->Indent();
  3313. if (HasFieldPresence(descriptor_->file())) {
  3314. // Check that all required fields in this message are set. We can do this
  3315. // most efficiently by checking 32 "has bits" at a time.
  3316. int has_bits_array_size = (descriptor_->field_count() + 31) / 32;
  3317. for (int i = 0; i < has_bits_array_size; i++) {
  3318. uint32 mask = 0;
  3319. for (int bit = 0; bit < 32; bit++) {
  3320. int index = i * 32 + bit;
  3321. if (index >= descriptor_->field_count()) break;
  3322. const FieldDescriptor* field = descriptor_->field(index);
  3323. if (field->is_required()) {
  3324. mask |= 1 << bit;
  3325. }
  3326. }
  3327. if (mask != 0) {
  3328. printer->Print(
  3329. "if ((_has_bits_[$i$] & 0x$mask$) != 0x$mask$) return false;\n",
  3330. "i", SimpleItoa(i),
  3331. "mask", StrCat(strings::Hex(mask, strings::ZERO_PAD_8)));
  3332. }
  3333. }
  3334. }
  3335. // Now check that all embedded messages are initialized.
  3336. printer->Print("\n");
  3337. for (int i = 0; i < descriptor_->field_count(); i++) {
  3338. const FieldDescriptor* field = descriptor_->field(i);
  3339. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  3340. !ShouldIgnoreRequiredFieldCheck(field) &&
  3341. HasRequiredFields(field->message_type())) {
  3342. if (field->is_repeated()) {
  3343. printer->Print(
  3344. "if (!::google::protobuf::internal::AllAreInitialized(this->$name$()))"
  3345. " return false;\n",
  3346. "name", FieldName(field));
  3347. } else {
  3348. if (field->options().weak() || !field->containing_oneof()) {
  3349. // For weak fields, use the data member (::google::protobuf::Message*) instead
  3350. // of the getter to avoid a link dependency on the weak message type
  3351. // which is only forward declared.
  3352. printer->Print(
  3353. "if (has_$name$()) {\n"
  3354. " if (!this->$name$_->IsInitialized()) return false;\n"
  3355. "}\n",
  3356. "name", FieldName(field));
  3357. } else {
  3358. printer->Print(
  3359. "if (has_$name$()) {\n"
  3360. " if (!this->$name$().IsInitialized()) return false;\n"
  3361. "}\n",
  3362. "name", FieldName(field));
  3363. }
  3364. }
  3365. }
  3366. }
  3367. if (descriptor_->extension_range_count() > 0) {
  3368. printer->Print(
  3369. "\n"
  3370. "if (!_extensions_.IsInitialized()) return false;");
  3371. }
  3372. printer->Outdent();
  3373. printer->Print(
  3374. " return true;\n"
  3375. "}\n");
  3376. }
  3377. } // namespace cpp
  3378. } // namespace compiler
  3379. } // namespace protobuf
  3380. } // namespace google