cpp_message.cc 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466
  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 <google/protobuf/compiler/cpp/cpp_message.h>
  34. #include <algorithm>
  35. #include <map>
  36. #include <memory>
  37. #include <unordered_map>
  38. #include <utility>
  39. #include <vector>
  40. #include <google/protobuf/compiler/cpp/cpp_enum.h>
  41. #include <google/protobuf/compiler/cpp/cpp_extension.h>
  42. #include <google/protobuf/compiler/cpp/cpp_field.h>
  43. #include <google/protobuf/compiler/cpp/cpp_helpers.h>
  44. #include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h>
  45. #include <google/protobuf/descriptor.pb.h>
  46. #include <google/protobuf/io/coded_stream.h>
  47. #include <google/protobuf/io/printer.h>
  48. #include <google/protobuf/generated_message_table_driven.h>
  49. #include <google/protobuf/generated_message_util.h>
  50. #include <google/protobuf/map_entry_lite.h>
  51. #include <google/protobuf/wire_format.h>
  52. #include <google/protobuf/stubs/strutil.h>
  53. #include <google/protobuf/stubs/substitute.h>
  54. #include <google/protobuf/stubs/hash.h>
  55. namespace google {
  56. namespace protobuf {
  57. namespace compiler {
  58. namespace cpp {
  59. using internal::WireFormat;
  60. using internal::WireFormatLite;
  61. namespace {
  62. template <class T>
  63. void PrintFieldComment(const Formatter& format, const T* field) {
  64. // Print the field's (or oneof's) proto-syntax definition as a comment.
  65. // We don't want to print group bodies so we cut off after the first
  66. // line.
  67. DebugStringOptions options;
  68. options.elide_group_body = true;
  69. options.elide_oneof_body = true;
  70. std::string def = field->DebugStringWithOptions(options);
  71. format("// $1$\n", def.substr(0, def.find_first_of('\n')));
  72. }
  73. void PrintPresenceCheck(const Formatter& format, const FieldDescriptor* field,
  74. const std::vector<int>& has_bit_indices,
  75. io::Printer* printer, int* cached_has_bit_index) {
  76. if (!field->options().weak()) {
  77. int has_bit_index = has_bit_indices[field->index()];
  78. if (*cached_has_bit_index != (has_bit_index / 32)) {
  79. *cached_has_bit_index = (has_bit_index / 32);
  80. format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_bit_index);
  81. }
  82. const std::string mask =
  83. StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
  84. format("if (cached_has_bits & 0x$1$u) {\n", mask);
  85. } else {
  86. format("if (has_$1$()) {\n", FieldName(field));
  87. }
  88. format.Indent();
  89. }
  90. struct FieldOrderingByNumber {
  91. inline bool operator()(const FieldDescriptor* a,
  92. const FieldDescriptor* b) const {
  93. return a->number() < b->number();
  94. }
  95. };
  96. // Sort the fields of the given Descriptor by number into a new[]'d array
  97. // and return it.
  98. std::vector<const FieldDescriptor*> SortFieldsByNumber(
  99. const Descriptor* descriptor) {
  100. std::vector<const FieldDescriptor*> fields(descriptor->field_count());
  101. for (int i = 0; i < descriptor->field_count(); i++) {
  102. fields[i] = descriptor->field(i);
  103. }
  104. std::sort(fields.begin(), fields.end(), FieldOrderingByNumber());
  105. return fields;
  106. }
  107. // Functor for sorting extension ranges by their "start" field number.
  108. struct ExtensionRangeSorter {
  109. bool operator()(const Descriptor::ExtensionRange* left,
  110. const Descriptor::ExtensionRange* right) const {
  111. return left->start < right->start;
  112. }
  113. };
  114. bool IsPOD(const FieldDescriptor* field) {
  115. if (field->is_repeated() || field->is_extension()) return false;
  116. switch (field->cpp_type()) {
  117. case FieldDescriptor::CPPTYPE_ENUM:
  118. case FieldDescriptor::CPPTYPE_INT32:
  119. case FieldDescriptor::CPPTYPE_INT64:
  120. case FieldDescriptor::CPPTYPE_UINT32:
  121. case FieldDescriptor::CPPTYPE_UINT64:
  122. case FieldDescriptor::CPPTYPE_FLOAT:
  123. case FieldDescriptor::CPPTYPE_DOUBLE:
  124. case FieldDescriptor::CPPTYPE_BOOL:
  125. return true;
  126. case FieldDescriptor::CPPTYPE_STRING:
  127. return false;
  128. default:
  129. return false;
  130. }
  131. }
  132. // Helper for the code that emits the SharedCtor() method.
  133. bool CanConstructByZeroing(const FieldDescriptor* field,
  134. const Options& options) {
  135. bool ret = CanInitializeByZeroing(field);
  136. // Non-repeated, non-lazy message fields are simply raw pointers, so we can
  137. // use memset to initialize these in SharedCtor. We cannot use this in
  138. // Clear, as we need to potentially delete the existing value.
  139. ret = ret || (!field->is_repeated() &&
  140. !IsLazy(field, options) &&
  141. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE);
  142. return ret;
  143. }
  144. // Emits an if-statement with a condition that evaluates to true if |field| is
  145. // considered non-default (will be sent over the wire), for message types
  146. // without true field presence. Should only be called if
  147. // !HasFieldPresence(message_descriptor).
  148. bool EmitFieldNonDefaultCondition(io::Printer* printer,
  149. const std::string& prefix,
  150. const FieldDescriptor* field) {
  151. Formatter format(printer);
  152. format.Set("prefix", prefix);
  153. format.Set("name", FieldName(field));
  154. // Merge and serialize semantics: primitive fields are merged/serialized only
  155. // if non-zero (numeric) or non-empty (string).
  156. if (!field->is_repeated() && !field->containing_oneof()) {
  157. if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
  158. format("if ($prefix$$name$().size() > 0) {\n");
  159. } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  160. // Message fields still have has_$name$() methods.
  161. format("if ($prefix$has_$name$()) {\n");
  162. } else {
  163. format("if ($prefix$$name$() != 0) {\n");
  164. }
  165. format.Indent();
  166. return true;
  167. } else if (field->containing_oneof()) {
  168. format("if (has_$name$()) {\n");
  169. format.Indent();
  170. return true;
  171. }
  172. return false;
  173. }
  174. // Does the given field have a has_$name$() method?
  175. bool HasHasMethod(const FieldDescriptor* field) {
  176. if (HasFieldPresence(field->file())) {
  177. // In proto1/proto2, every field has a has_$name$() method.
  178. return true;
  179. }
  180. // For message types without true field presence, only fields with a message
  181. // type have a has_$name$() method.
  182. return field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE;
  183. }
  184. // Collects map entry message type information.
  185. void CollectMapInfo(const Options& options, const Descriptor* descriptor,
  186. std::map<std::string, std::string>* variables) {
  187. GOOGLE_CHECK(IsMapEntryMessage(descriptor));
  188. std::map<std::string, std::string>& vars = *variables;
  189. const FieldDescriptor* key = descriptor->FindFieldByName("key");
  190. const FieldDescriptor* val = descriptor->FindFieldByName("value");
  191. vars["key_cpp"] = PrimitiveTypeName(options, key->cpp_type());
  192. switch (val->cpp_type()) {
  193. case FieldDescriptor::CPPTYPE_MESSAGE:
  194. vars["val_cpp"] = FieldMessageTypeName(val, options);
  195. break;
  196. case FieldDescriptor::CPPTYPE_ENUM:
  197. vars["val_cpp"] = ClassName(val->enum_type(), true);
  198. break;
  199. default:
  200. vars["val_cpp"] = PrimitiveTypeName(options, val->cpp_type());
  201. }
  202. vars["key_wire_type"] =
  203. "TYPE_" + ToUpper(DeclaredTypeMethodName(key->type()));
  204. vars["val_wire_type"] =
  205. "TYPE_" + ToUpper(DeclaredTypeMethodName(val->type()));
  206. if (descriptor->file()->syntax() != FileDescriptor::SYNTAX_PROTO3 &&
  207. val->type() == FieldDescriptor::TYPE_ENUM) {
  208. const EnumValueDescriptor* default_value = val->default_value_enum();
  209. vars["default_enum_value"] = Int32ToString(default_value->number());
  210. } else {
  211. vars["default_enum_value"] = "0";
  212. }
  213. }
  214. // Does the given field have a private (internal helper only) has_$name$()
  215. // method?
  216. bool HasPrivateHasMethod(const FieldDescriptor* field) {
  217. // Only for oneofs in message types with no field presence. has_$name$(),
  218. // based on the oneof case, is still useful internally for generated code.
  219. return (!HasFieldPresence(field->file()) &&
  220. field->containing_oneof() != NULL);
  221. }
  222. // TODO(ckennelly): Cull these exclusions if/when these protos do not have
  223. // their methods overriden by subclasses.
  224. bool ShouldMarkClassAsFinal(const Descriptor* descriptor,
  225. const Options& options) {
  226. return false;
  227. }
  228. bool ShouldMarkClearAsFinal(const Descriptor* descriptor,
  229. const Options& options) {
  230. static std::set<std::string> exclusions{
  231. };
  232. const std::string name = ClassName(descriptor, true);
  233. return exclusions.find(name) == exclusions.end() ||
  234. options.opensource_runtime;
  235. }
  236. bool ShouldMarkIsInitializedAsFinal(const Descriptor* descriptor,
  237. const Options& options) {
  238. static std::set<std::string> exclusions{
  239. };
  240. const std::string name = ClassName(descriptor, true);
  241. return exclusions.find(name) == exclusions.end() ||
  242. options.opensource_runtime;
  243. }
  244. bool ShouldMarkMergePartialAsFinal(const Descriptor* descriptor,
  245. const Options& options) {
  246. static std::set<std::string> exclusions{
  247. };
  248. const std::string name = ClassName(descriptor, true);
  249. return exclusions.find(name) == exclusions.end() ||
  250. options.opensource_runtime;
  251. }
  252. bool ShouldMarkNewAsFinal(const Descriptor* descriptor,
  253. const Options& options) {
  254. static std::set<std::string> exclusions{
  255. };
  256. const std::string name = ClassName(descriptor, true);
  257. return exclusions.find(name) == exclusions.end() ||
  258. options.opensource_runtime;
  259. }
  260. bool TableDrivenParsingEnabled(const Descriptor* descriptor,
  261. const Options& options) {
  262. if (!options.table_driven_parsing) {
  263. return false;
  264. }
  265. // Consider table-driven parsing. We only do this if:
  266. // - We have has_bits for fields. This avoids a check on every field we set
  267. // when are present (the common case).
  268. if (!HasFieldPresence(descriptor->file())) {
  269. return false;
  270. }
  271. const double table_sparseness = 0.5;
  272. int max_field_number = 0;
  273. for (auto field : FieldRange(descriptor)) {
  274. if (max_field_number < field->number()) {
  275. max_field_number = field->number();
  276. }
  277. // - There are no weak fields.
  278. if (IsWeak(field, options)) {
  279. return false;
  280. }
  281. // - There are no lazy fields (they require the non-lite library).
  282. if (IsLazy(field, options)) {
  283. return false;
  284. }
  285. }
  286. // - There range of field numbers is "small"
  287. if (max_field_number >= (2 << 14)) {
  288. return false;
  289. }
  290. // - Field numbers are relatively dense within the actual number of fields.
  291. // We check for strictly greater than in the case where there are no fields
  292. // (only extensions) so max_field_number == descriptor->field_count() == 0.
  293. if (max_field_number * table_sparseness > descriptor->field_count()) {
  294. return false;
  295. }
  296. // - This is not a MapEntryMessage.
  297. if (IsMapEntryMessage(descriptor)) {
  298. return false;
  299. }
  300. return true;
  301. }
  302. void SetUnknkownFieldsVariable(const Descriptor* descriptor,
  303. const Options& options,
  304. std::map<std::string, std::string>* variables) {
  305. std::string proto_ns = ProtobufNamespace(options);
  306. if (UseUnknownFieldSet(descriptor->file(), options)) {
  307. (*variables)["unknown_fields_type"] = "::" + proto_ns + "::UnknownFieldSet";
  308. } else {
  309. (*variables)["unknown_fields_type"] =
  310. PrimitiveTypeName(options, FieldDescriptor::CPPTYPE_STRING);
  311. }
  312. (*variables)["have_unknown_fields"] =
  313. "_internal_metadata_.have_unknown_fields()";
  314. (*variables)["unknown_fields"] = "_internal_metadata_.unknown_fields()";
  315. (*variables)["mutable_unknown_fields"] =
  316. "_internal_metadata_.mutable_unknown_fields()";
  317. }
  318. bool IsCrossFileMapField(const FieldDescriptor* field) {
  319. if (!field->is_map()) {
  320. return false;
  321. }
  322. const Descriptor* d = field->message_type();
  323. const FieldDescriptor* value = d->FindFieldByNumber(2);
  324. return IsCrossFileMessage(value);
  325. }
  326. bool IsCrossFileMaybeMap(const FieldDescriptor* field) {
  327. if (IsCrossFileMapField(field)) {
  328. return true;
  329. }
  330. return IsCrossFileMessage(field);
  331. }
  332. bool IsRequired(const std::vector<const FieldDescriptor*>& v) {
  333. return v.front()->is_required();
  334. }
  335. // Allows chunking repeated fields together and non-repeated fields if the
  336. // fields share the same has_byte index.
  337. // TODO(seongkim): use lambda with capture instead of functor.
  338. class MatchRepeatedAndHasByte {
  339. public:
  340. MatchRepeatedAndHasByte(const std::vector<int>* has_bit_indices,
  341. bool has_field_presence)
  342. : has_bit_indices_(*has_bit_indices),
  343. has_field_presence_(has_field_presence) {}
  344. // Returns true if the following conditions are met:
  345. // --both fields are repeated fields
  346. // --both fields are non-repeated fields with either has_field_presence is
  347. // false or have the same has_byte index.
  348. bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
  349. return a->is_repeated() == b->is_repeated() &&
  350. (!has_field_presence_ || a->is_repeated() ||
  351. has_bit_indices_[a->index()] / 8 ==
  352. has_bit_indices_[b->index()] / 8);
  353. }
  354. private:
  355. const std::vector<int>& has_bit_indices_;
  356. const bool has_field_presence_;
  357. };
  358. // Allows chunking required fields separately after chunking with
  359. // MatchRepeatedAndHasByte.
  360. class MatchRepeatedAndHasByteAndRequired : public MatchRepeatedAndHasByte {
  361. public:
  362. MatchRepeatedAndHasByteAndRequired(const std::vector<int>* has_bit_indices,
  363. bool has_field_presence)
  364. : MatchRepeatedAndHasByte(has_bit_indices, has_field_presence) {}
  365. bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
  366. return MatchRepeatedAndHasByte::operator()(a, b) &&
  367. a->is_required() == b->is_required();
  368. }
  369. };
  370. // Allows chunking zero-initializable fields separately after chunking with
  371. // MatchRepeatedAndHasByte.
  372. class MatchRepeatedAndHasByteAndZeroInits : public MatchRepeatedAndHasByte {
  373. public:
  374. MatchRepeatedAndHasByteAndZeroInits(const std::vector<int>* has_bit_indices,
  375. bool has_field_presence)
  376. : MatchRepeatedAndHasByte(has_bit_indices, has_field_presence) {}
  377. bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const {
  378. return MatchRepeatedAndHasByte::operator()(a, b) &&
  379. CanInitializeByZeroing(a) == CanInitializeByZeroing(b);
  380. }
  381. };
  382. // Collects neighboring fields based on a given criteria (equivalent predicate).
  383. template <typename Predicate>
  384. std::vector<std::vector<const FieldDescriptor*> > CollectFields(
  385. const std::vector<const FieldDescriptor*>& fields,
  386. const Predicate& equivalent) {
  387. std::vector<std::vector<const FieldDescriptor*> > chunks;
  388. if (fields.empty()) {
  389. return chunks;
  390. }
  391. const FieldDescriptor* last_field = fields.front();
  392. std::vector<const FieldDescriptor*> chunk;
  393. for (auto field : fields) {
  394. if (!equivalent(last_field, field) && !chunk.empty()) {
  395. chunks.push_back(chunk);
  396. chunk.clear();
  397. }
  398. chunk.push_back(field);
  399. last_field = field;
  400. }
  401. if (!chunk.empty()) {
  402. chunks.push_back(chunk);
  403. }
  404. return chunks;
  405. }
  406. // Returns a bit mask based on has_bit index of "fields" that are typically on
  407. // the same chunk. It is used in a group presence check where _has_bits_ is
  408. // masked to tell if any thing in "fields" is present.
  409. uint32 GenChunkMask(const std::vector<const FieldDescriptor*>& fields,
  410. const std::vector<int>& has_bit_indices) {
  411. GOOGLE_CHECK(!fields.empty());
  412. int first_index_offset = has_bit_indices[fields.front()->index()] / 32;
  413. uint32 chunk_mask = 0;
  414. for (auto field : fields) {
  415. // "index" defines where in the _has_bits_ the field appears.
  416. int index = has_bit_indices[field->index()];
  417. GOOGLE_CHECK_EQ(first_index_offset, index / 32);
  418. chunk_mask |= static_cast<uint32>(1) << (index % 32);
  419. }
  420. GOOGLE_CHECK_NE(0, chunk_mask);
  421. return chunk_mask;
  422. }
  423. // Return the number of bits set in n, a non-negative integer.
  424. static int popcnt(uint32 n) {
  425. int result = 0;
  426. while (n != 0) {
  427. result += (n & 1);
  428. n = n / 2;
  429. }
  430. return result;
  431. }
  432. // For a run of cold chunks, opens and closes an external if statement that
  433. // checks multiple has_bits words to skip bulk of cold fields.
  434. class ColdChunkSkipper {
  435. public:
  436. ColdChunkSkipper(
  437. const Options& options,
  438. const std::vector<std::vector<const FieldDescriptor*>>& chunks,
  439. const std::vector<int>& has_bit_indices, const double cold_threshold,
  440. bool has_field_presence)
  441. : chunks_(chunks),
  442. has_bit_indices_(has_bit_indices),
  443. access_info_map_(options.access_info_map),
  444. cold_threshold_(cold_threshold),
  445. has_field_presence_(has_field_presence) {
  446. SetCommonVars(options, &variables_);
  447. }
  448. // May open an external if check for a batch of cold fields. "from" is the
  449. // prefix to _has_bits_ to allow MergeFrom to use "from._has_bits_".
  450. // Otherwise, it should be "".
  451. void OnStartChunk(int chunk, int cached_has_bit_index,
  452. const std::string& from, io::Printer* printer);
  453. bool OnEndChunk(int chunk, io::Printer* printer);
  454. private:
  455. bool IsColdChunk(int chunk);
  456. int HasbitWord(int chunk, int offset) {
  457. return has_bit_indices_[chunks_[chunk][offset]->index()] / 32;
  458. }
  459. const std::vector<std::vector<const FieldDescriptor*> >& chunks_;
  460. const std::vector<int>& has_bit_indices_;
  461. const AccessInfoMap* access_info_map_;
  462. const double cold_threshold_;
  463. std::map<std::string, std::string> variables_;
  464. int limit_chunk_ = -1;
  465. bool has_field_presence_;
  466. };
  467. // Tuning parameters for ColdChunkSkipper.
  468. const double kColdRatio = 0.005;
  469. bool ColdChunkSkipper::IsColdChunk(int chunk) { return false; }
  470. void ColdChunkSkipper::OnStartChunk(int chunk, int cached_has_bit_index,
  471. const std::string& from,
  472. io::Printer* printer) {
  473. Formatter format(printer, variables_);
  474. if (!access_info_map_ || !has_field_presence_) {
  475. return;
  476. } else if (chunk < limit_chunk_) {
  477. // We are already inside a run of cold chunks.
  478. return;
  479. } else if (!IsColdChunk(chunk)) {
  480. // We can't start a run of cold chunks.
  481. return;
  482. }
  483. // Find the end of consecutive cold chunks.
  484. limit_chunk_ = chunk;
  485. while (limit_chunk_ < chunks_.size() && IsColdChunk(limit_chunk_)) {
  486. limit_chunk_++;
  487. }
  488. if (limit_chunk_ <= chunk + 1) {
  489. // Require at least two chunks to emit external has_bit checks.
  490. limit_chunk_ = -1;
  491. return;
  492. }
  493. // Emit has_bit check for each has_bit_dword index.
  494. format("if (PROTOBUF_PREDICT_FALSE(");
  495. int first_word = HasbitWord(chunk, 0);
  496. while (chunk < limit_chunk_) {
  497. uint32 mask = 0;
  498. int this_word = HasbitWord(chunk, 0);
  499. // Generate mask for chunks on the same word.
  500. for (; chunk < limit_chunk_ && HasbitWord(chunk, 0) == this_word; chunk++) {
  501. for (auto field : chunks_[chunk]) {
  502. int hasbit_index = has_bit_indices_[field->index()];
  503. // Fields on a chunk must be in the same word.
  504. GOOGLE_CHECK_EQ(this_word, hasbit_index / 32);
  505. mask |= 1 << (hasbit_index % 32);
  506. }
  507. }
  508. if (this_word != first_word) {
  509. format(" ||\n ");
  510. }
  511. format.Set("mask", strings::Hex(mask, strings::ZERO_PAD_8));
  512. if (this_word == cached_has_bit_index) {
  513. format("(cached_has_bits & 0x$mask$u) != 0");
  514. } else {
  515. format("($1$_has_bits_[$2$] & 0x$mask$u) != 0", from, this_word);
  516. }
  517. }
  518. format(")) {\n");
  519. format.Indent();
  520. }
  521. bool ColdChunkSkipper::OnEndChunk(int chunk, io::Printer* printer) {
  522. Formatter format(printer, variables_);
  523. if (chunk != limit_chunk_ - 1) {
  524. return false;
  525. }
  526. format.Outdent();
  527. format("}\n");
  528. return true;
  529. }
  530. } // anonymous namespace
  531. // ===================================================================
  532. MessageGenerator::MessageGenerator(
  533. const Descriptor* descriptor,
  534. const std::map<std::string, std::string>& vars, int index_in_file_messages,
  535. const Options& options, MessageSCCAnalyzer* scc_analyzer)
  536. : descriptor_(descriptor),
  537. index_in_file_messages_(index_in_file_messages),
  538. classname_(ClassName(descriptor, false)),
  539. options_(options),
  540. field_generators_(descriptor, options, scc_analyzer),
  541. max_has_bit_index_(0),
  542. num_weak_fields_(0),
  543. scc_analyzer_(scc_analyzer),
  544. variables_(vars) {
  545. if (!message_layout_helper_) {
  546. message_layout_helper_.reset(new PaddingOptimizer());
  547. }
  548. // Variables that apply to this class
  549. variables_["classname"] = classname_;
  550. variables_["classtype"] = QualifiedClassName(descriptor_, options);
  551. std::string scc_name =
  552. ClassName(scc_analyzer_->GetSCC(descriptor_)->GetRepresentative());
  553. variables_["scc_name"] = UniqueName(scc_name, descriptor_, options_);
  554. variables_["full_name"] = descriptor_->full_name();
  555. variables_["superclass"] = SuperClassName(descriptor_, options_);
  556. // Compute optimized field order to be used for layout and initialization
  557. // purposes.
  558. for (auto field : FieldRange(descriptor_)) {
  559. if (IsWeak(field, options_)) {
  560. num_weak_fields_++;
  561. } else if (!field->containing_oneof()) {
  562. optimized_order_.push_back(field);
  563. }
  564. }
  565. message_layout_helper_->OptimizeLayout(&optimized_order_, options_);
  566. if (HasFieldPresence(descriptor_->file())) {
  567. // We use -1 as a sentinel.
  568. has_bit_indices_.resize(descriptor_->field_count(), -1);
  569. for (auto field : optimized_order_) {
  570. // Skip fields that do not have has bits.
  571. if (field->is_repeated()) {
  572. continue;
  573. }
  574. has_bit_indices_[field->index()] = max_has_bit_index_++;
  575. }
  576. field_generators_.SetHasBitIndices(has_bit_indices_);
  577. }
  578. num_required_fields_ = 0;
  579. for (int i = 0; i < descriptor->field_count(); i++) {
  580. if (descriptor->field(i)->is_required()) {
  581. ++num_required_fields_;
  582. }
  583. }
  584. table_driven_ = TableDrivenParsingEnabled(descriptor_, options_);
  585. }
  586. MessageGenerator::~MessageGenerator() = default;
  587. size_t MessageGenerator::HasBitsSize() const {
  588. size_t sizeof_has_bits = (max_has_bit_index_ + 31) / 32 * 4;
  589. if (sizeof_has_bits == 0) {
  590. // Zero-size arrays aren't technically allowed, and MSVC in particular
  591. // doesn't like them. We still need to declare these arrays to make
  592. // other code compile. Since this is an uncommon case, we'll just declare
  593. // them with size 1 and waste some space. Oh well.
  594. sizeof_has_bits = 4;
  595. }
  596. return sizeof_has_bits;
  597. }
  598. void MessageGenerator::AddGenerators(
  599. std::vector<std::unique_ptr<EnumGenerator>>* enum_generators,
  600. std::vector<std::unique_ptr<ExtensionGenerator>>* extension_generators) {
  601. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  602. enum_generators->emplace_back(
  603. new EnumGenerator(descriptor_->enum_type(i), variables_, options_));
  604. enum_generators_.push_back(enum_generators->back().get());
  605. }
  606. for (int i = 0; i < descriptor_->extension_count(); i++) {
  607. extension_generators->emplace_back(
  608. new ExtensionGenerator(descriptor_->extension(i), options_));
  609. extension_generators_.push_back(extension_generators->back().get());
  610. }
  611. }
  612. void MessageGenerator::GenerateFieldAccessorDeclarations(io::Printer* printer) {
  613. Formatter format(printer, variables_);
  614. // optimized_fields_ does not contain fields where
  615. // field->containing_oneof() != NULL
  616. // so we need to iterate over those as well.
  617. //
  618. // We place the non-oneof fields in optimized_order_, as that controls the
  619. // order of the _has_bits_ entries and we want GDB's pretty printers to be
  620. // able to infer these indices from the k[FIELDNAME]FieldNumber order.
  621. std::vector<const FieldDescriptor*> ordered_fields;
  622. ordered_fields.reserve(descriptor_->field_count());
  623. ordered_fields.insert(ordered_fields.begin(), optimized_order_.begin(),
  624. optimized_order_.end());
  625. for (auto field : FieldRange(descriptor_)) {
  626. if (field->containing_oneof() == NULL && !field->options().weak()) {
  627. continue;
  628. }
  629. ordered_fields.push_back(field);
  630. }
  631. for (auto field : ordered_fields) {
  632. PrintFieldComment(format, field);
  633. Formatter::SaveState save(&format);
  634. std::map<std::string, std::string> vars;
  635. SetCommonFieldVariables(field, &vars, options_);
  636. format.AddMap(vars);
  637. if (field->is_repeated()) {
  638. format("$deprecated_attr$int ${1$$name$_size$}$() const;\n", field);
  639. } else if (HasHasMethod(field)) {
  640. format("$deprecated_attr$bool ${1$has_$name$$}$() const;\n", field);
  641. } else if (HasPrivateHasMethod(field)) {
  642. format(
  643. "private:\n"
  644. "bool ${1$has_$name$$}$() const;\n"
  645. "public:\n",
  646. field);
  647. }
  648. format(
  649. "$deprecated_attr$void ${1$clear_$name$$}$();\n"
  650. "$deprecated_attr$static const int ${1$$2$$}$ = $number$;\n",
  651. field, FieldConstantName(field));
  652. // Generate type-specific accessor declarations.
  653. field_generators_.get(field).GenerateAccessorDeclarations(printer);
  654. format("\n");
  655. }
  656. if (descriptor_->extension_range_count() > 0) {
  657. // Generate accessors for extensions. We just call a macro located in
  658. // extension_set.h since the accessors about 80 lines of static code.
  659. format("$GOOGLE_PROTOBUF$_EXTENSION_ACCESSORS($classname$)\n");
  660. // Generate MessageSet specific APIs for proto2 MessageSet.
  661. // For testing purposes we don't check for bridge.MessageSet, so
  662. // we don't use IsProto2MessageSet
  663. if (descriptor_->options().message_set_wire_format() &&
  664. !options_.opensource_runtime && !options_.lite_implicit_weak_fields) {
  665. // Special-case MessageSet
  666. format("GOOGLE_PROTOBUF_EXTENSION_MESSAGE_SET_ACCESSORS($classname$)\n");
  667. }
  668. }
  669. for (auto oneof : OneOfRange(descriptor_)) {
  670. Formatter::SaveState saver(&format);
  671. format.Set("oneof_name", oneof->name());
  672. format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true));
  673. format(
  674. "void clear_$oneof_name$();\n"
  675. "$camel_oneof_name$Case $oneof_name$_case() const;\n");
  676. }
  677. }
  678. void MessageGenerator::GenerateSingularFieldHasBits(
  679. const FieldDescriptor* field, Formatter format) {
  680. if (field->options().weak()) {
  681. format(
  682. "inline bool $classname$::has_$name$() const {\n"
  683. " return _weak_field_map_.Has($number$);\n"
  684. "}\n");
  685. return;
  686. }
  687. if (HasFieldPresence(descriptor_->file())) {
  688. // N.B.: without field presence, we do not use has-bits or generate
  689. // has_$name$() methods.
  690. int has_bit_index = has_bit_indices_[field->index()];
  691. GOOGLE_CHECK_GE(has_bit_index, 0);
  692. format.Set("has_array_index", has_bit_index / 32);
  693. format.Set("has_mask",
  694. strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
  695. format(
  696. "inline bool $classname$::has_$name$() const {\n"
  697. " return (_has_bits_[$has_array_index$] & 0x$has_mask$u) != 0;\n"
  698. "}\n");
  699. } else {
  700. // Message fields have a has_$name$() method.
  701. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  702. if (IsLazy(field, options_)) {
  703. format(
  704. "inline bool $classname$::has_$name$() const {\n"
  705. " return !$name$_.IsCleared();\n"
  706. "}\n");
  707. } else {
  708. format(
  709. "inline bool $classname$::has_$name$() const {\n"
  710. " return this != internal_default_instance() "
  711. "&& $name$_ != nullptr;\n"
  712. "}\n");
  713. }
  714. }
  715. }
  716. }
  717. void MessageGenerator::GenerateOneofHasBits(io::Printer* printer) {
  718. Formatter format(printer, variables_);
  719. for (auto oneof : OneOfRange(descriptor_)) {
  720. format.Set("oneof_name", oneof->name());
  721. format.Set("oneof_index", oneof->index());
  722. format.Set("cap_oneof_name", ToUpper(oneof->name()));
  723. format(
  724. "inline bool $classname$::has_$oneof_name$() const {\n"
  725. " return $oneof_name$_case() != $cap_oneof_name$_NOT_SET;\n"
  726. "}\n"
  727. "inline void $classname$::clear_has_$oneof_name$() {\n"
  728. " _oneof_case_[$oneof_index$] = $cap_oneof_name$_NOT_SET;\n"
  729. "}\n");
  730. }
  731. }
  732. void MessageGenerator::GenerateOneofMemberHasBits(const FieldDescriptor* field,
  733. const Formatter& format) {
  734. // Singular field in a oneof
  735. // N.B.: Without field presence, we do not use has-bits or generate
  736. // has_$name$() methods, but oneofs still have set_has_$name$().
  737. // Oneofs also have has_$name$() but only as a private helper
  738. // method, so that generated code is slightly cleaner (vs. comparing
  739. // _oneof_case_[index] against a constant everywhere).
  740. format(
  741. "inline bool $classname$::has_$name$() const {\n"
  742. " return $oneof_name$_case() == k$field_name$;\n"
  743. "}\n"
  744. "inline void $classname$::set_has_$name$() {\n"
  745. " _oneof_case_[$oneof_index$] = k$field_name$;\n"
  746. "}\n");
  747. }
  748. void MessageGenerator::GenerateFieldClear(const FieldDescriptor* field,
  749. bool is_inline,
  750. Formatter format) {
  751. // Generate clear_$name$().
  752. if (is_inline) {
  753. format("inline ");
  754. }
  755. format("void $classname$::clear_$name$() {\n");
  756. format.Indent();
  757. if (field->containing_oneof()) {
  758. // Clear this field only if it is the active field in this oneof,
  759. // otherwise ignore
  760. format("if (has_$name$()) {\n");
  761. format.Indent();
  762. field_generators_.get(field).GenerateClearingCode(format.printer());
  763. format("clear_has_$oneof_name$();\n");
  764. format.Outdent();
  765. format("}\n");
  766. } else {
  767. field_generators_.get(field).GenerateClearingCode(format.printer());
  768. if (HasFieldPresence(descriptor_->file())) {
  769. if (!field->is_repeated() && !field->options().weak()) {
  770. int has_bit_index = has_bit_indices_[field->index()];
  771. GOOGLE_CHECK_GE(has_bit_index, 0);
  772. format.Set("has_array_index", has_bit_index / 32);
  773. format.Set("has_mask",
  774. strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
  775. format("_has_bits_[$has_array_index$] &= ~0x$has_mask$u;\n");
  776. }
  777. }
  778. }
  779. format.Outdent();
  780. format("}\n");
  781. }
  782. void MessageGenerator::GenerateFieldAccessorDefinitions(io::Printer* printer) {
  783. Formatter format(printer, variables_);
  784. format("// $classname$\n\n");
  785. for (auto field : FieldRange(descriptor_)) {
  786. PrintFieldComment(format, field);
  787. std::map<std::string, std::string> vars;
  788. SetCommonFieldVariables(field, &vars, options_);
  789. Formatter::SaveState saver(&format);
  790. format.AddMap(vars);
  791. // Generate has_$name$() or $name$_size().
  792. if (field->is_repeated()) {
  793. format(
  794. "inline int $classname$::$name$_size() const {\n"
  795. " return $name$_.size();\n"
  796. "}\n");
  797. } else if (field->containing_oneof()) {
  798. format.Set("field_name", UnderscoresToCamelCase(field->name(), true));
  799. format.Set("oneof_name", field->containing_oneof()->name());
  800. format.Set("oneof_index",
  801. StrCat(field->containing_oneof()->index()));
  802. GenerateOneofMemberHasBits(field, format);
  803. } else {
  804. // Singular field.
  805. GenerateSingularFieldHasBits(field, format);
  806. }
  807. if (!IsCrossFileMaybeMap(field)) {
  808. GenerateFieldClear(field, true, format);
  809. }
  810. // Generate type-specific accessors.
  811. field_generators_.get(field).GenerateInlineAccessorDefinitions(printer);
  812. format("\n");
  813. }
  814. // Generate has_$name$() and clear_has_$name$() functions for oneofs.
  815. GenerateOneofHasBits(printer);
  816. }
  817. void MessageGenerator::GenerateClassDefinition(io::Printer* printer) {
  818. Formatter format(printer, variables_);
  819. format.Set("class_final",
  820. ShouldMarkClassAsFinal(descriptor_, options_) ? "final": "");
  821. if (IsMapEntryMessage(descriptor_)) {
  822. std::map<std::string, std::string> vars;
  823. CollectMapInfo(options_, descriptor_, &vars);
  824. vars["lite"] =
  825. HasDescriptorMethods(descriptor_->file(), options_) ? "" : "Lite";
  826. format.AddMap(vars);
  827. format(
  828. "class $classname$ : public "
  829. "::$proto_ns$::internal::MapEntry$lite$<$classname$, \n"
  830. " $key_cpp$, $val_cpp$,\n"
  831. " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n"
  832. " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n"
  833. " $default_enum_value$ > {\n"
  834. "public:\n"
  835. " typedef ::$proto_ns$::internal::MapEntry$lite$<$classname$, \n"
  836. " $key_cpp$, $val_cpp$,\n"
  837. " ::$proto_ns$::internal::WireFormatLite::$key_wire_type$,\n"
  838. " ::$proto_ns$::internal::WireFormatLite::$val_wire_type$,\n"
  839. " $default_enum_value$ > SuperType;\n"
  840. " $classname$();\n"
  841. " $classname$(::$proto_ns$::Arena* arena);\n"
  842. " void MergeFrom(const $classname$& other);\n"
  843. " static const $classname$* internal_default_instance() { return "
  844. "reinterpret_cast<const "
  845. "$classname$*>(&_$classname$_default_instance_); }\n");
  846. std::string suffix = GetUtf8Suffix(descriptor_->field(0), options_);
  847. if (descriptor_->field(0)->type() == FieldDescriptor::TYPE_STRING &&
  848. !suffix.empty()) {
  849. if (suffix == "UTF8") {
  850. format(
  851. " bool ValidateKey() const {\n"
  852. " return ::$proto_ns$::internal::WireFormatLite::"
  853. "VerifyUtf8String(key().data(), key().size(), "
  854. "::$proto_ns$::internal::WireFormatLite::PARSE, \"$1$\");\n"
  855. " }\n",
  856. descriptor_->field(0)->full_name());
  857. } else {
  858. GOOGLE_CHECK(suffix == "UTF8Verify");
  859. format(
  860. " bool ValidateKey() const {\n"
  861. "#ifndef NDEBUG\n"
  862. " ::$proto_ns$::internal::WireFormatLite::VerifyUtf8String(\n"
  863. " key().data(), key().size(), ::$proto_ns$::internal::"
  864. "WireFormatLite::PARSE, \"$1$\");\n"
  865. "#endif\n"
  866. " return true;\n"
  867. " }\n",
  868. descriptor_->field(0)->full_name());
  869. }
  870. } else {
  871. format(" bool ValidateKey() const { return true; }\n");
  872. }
  873. if (descriptor_->field(1)->type() == FieldDescriptor::TYPE_STRING &&
  874. !suffix.empty()) {
  875. if (suffix == "UTF8") {
  876. format(
  877. " bool ValidateValue() const {\n"
  878. " return ::$proto_ns$::internal::WireFormatLite::"
  879. "VerifyUtf8String(value().data(), value().size(), "
  880. "::$proto_ns$::internal::WireFormatLite::PARSE, \"$1$\");\n"
  881. " }\n",
  882. descriptor_->field(1)->full_name());
  883. } else {
  884. GOOGLE_CHECK(suffix == "UTF8Verify");
  885. format(
  886. " bool ValidateValue() const {\n"
  887. "#ifndef NDEBUG\n"
  888. " ::$proto_ns$::internal::WireFormatLite::VerifyUtf8String(\n"
  889. " value().data(), value().size(), ::$proto_ns$::internal::"
  890. "WireFormatLite::PARSE, \"$1$\");\n"
  891. "#endif\n"
  892. " return true;\n"
  893. " }\n",
  894. descriptor_->field(1)->full_name());
  895. }
  896. } else {
  897. format(" bool ValidateValue() const { return true; }\n");
  898. }
  899. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  900. format(
  901. " void MergeFrom(const ::$proto_ns$::Message& other) final;\n"
  902. " ::$proto_ns$::Metadata GetMetadata() const;\n"
  903. "};\n");
  904. } else {
  905. format("};\n");
  906. }
  907. return;
  908. }
  909. format(
  910. "class $dllexport_decl $${1$$classname$$}$$ class_final$ :\n"
  911. " public $superclass$ /* @@protoc_insertion_point("
  912. "class_definition:$full_name$) */ {\n",
  913. descriptor_);
  914. format(" public:\n");
  915. format.Indent();
  916. format(
  917. "$classname$();\n"
  918. "virtual ~$classname$();\n"
  919. "\n"
  920. "$classname$(const $classname$& from);\n"
  921. "$classname$($classname$&& from) noexcept\n"
  922. " : $classname$() {\n"
  923. " *this = ::std::move(from);\n"
  924. "}\n"
  925. "\n"
  926. "inline $classname$& operator=(const $classname$& from) {\n"
  927. " CopyFrom(from);\n"
  928. " return *this;\n"
  929. "}\n"
  930. "inline $classname$& operator=($classname$&& from) noexcept {\n"
  931. " if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {\n"
  932. " if (this != &from) InternalSwap(&from);\n"
  933. " } else {\n"
  934. " CopyFrom(from);\n"
  935. " }\n"
  936. " return *this;\n"
  937. "}\n"
  938. "\n");
  939. if (options_.table_driven_serialization) {
  940. format(
  941. "private:\n"
  942. "const void* InternalGetTable() const;\n"
  943. "public:\n"
  944. "\n");
  945. }
  946. std::map<std::string, std::string> vars;
  947. SetUnknkownFieldsVariable(descriptor_, options_, &vars);
  948. format.AddMap(vars);
  949. if (PublicUnknownFieldsAccessors(descriptor_)) {
  950. format(
  951. "inline const $unknown_fields_type$& unknown_fields() const {\n"
  952. " return $unknown_fields$;\n"
  953. "}\n"
  954. "inline $unknown_fields_type$* mutable_unknown_fields() {\n"
  955. " return $mutable_unknown_fields$;\n"
  956. "}\n"
  957. "\n");
  958. }
  959. // N.B.: We exclude GetArena() when arena support is disabled, falling back on
  960. // MessageLite's implementation which returns NULL rather than generating our
  961. // own method which returns NULL, in order to reduce code size.
  962. if (SupportsArenas(descriptor_)) {
  963. // virtual method version of GetArenaNoVirtual(), required for generic
  964. // dispatch given a MessageLite* (e.g., in RepeatedField::AddAllocated()).
  965. format(
  966. "inline ::$proto_ns$::Arena* GetArena() const final {\n"
  967. " return GetArenaNoVirtual();\n"
  968. "}\n"
  969. "inline void* GetMaybeArenaPointer() const final {\n"
  970. " return MaybeArenaPtr();\n"
  971. "}\n");
  972. }
  973. // Only generate this member if it's not disabled.
  974. if (HasDescriptorMethods(descriptor_->file(), options_) &&
  975. !descriptor_->options().no_standard_descriptor_accessor()) {
  976. format(
  977. "static const ::$proto_ns$::Descriptor* descriptor() {\n"
  978. " return default_instance().GetDescriptor();\n"
  979. "}\n");
  980. }
  981. format(
  982. "static const $classname$& default_instance();\n"
  983. "\n");
  984. // Generate enum values for every field in oneofs. One list is generated for
  985. // each oneof with an additional *_NOT_SET value.
  986. for (auto oneof : OneOfRange(descriptor_)) {
  987. format("enum $1$Case {\n", UnderscoresToCamelCase(oneof->name(), true));
  988. format.Indent();
  989. for (auto field : FieldRange(oneof)) {
  990. std::string oneof_enum_case_field_name =
  991. UnderscoresToCamelCase(field->name(), true);
  992. format("k$1$ = $2$,\n", oneof_enum_case_field_name, // 1
  993. field->number()); // 2
  994. }
  995. format("$1$_NOT_SET = 0,\n", ToUpper(oneof->name()));
  996. format.Outdent();
  997. format(
  998. "};\n"
  999. "\n");
  1000. }
  1001. // TODO(gerbens) make this private, while still granting other protos access.
  1002. format(
  1003. "static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY\n"
  1004. "static inline const $classname$* internal_default_instance() {\n"
  1005. " return reinterpret_cast<const $classname$*>(\n"
  1006. " &_$classname$_default_instance_);\n"
  1007. "}\n"
  1008. "static constexpr int kIndexInFileMessages =\n"
  1009. " $1$;\n"
  1010. "\n", index_in_file_messages_);
  1011. if (SupportsArenas(descriptor_)) {
  1012. format("void UnsafeArenaSwap($classname$* other);\n");
  1013. }
  1014. if (IsAnyMessage(descriptor_, options_)) {
  1015. format(
  1016. "// implements Any -----------------------------------------------\n"
  1017. "\n");
  1018. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  1019. format(
  1020. "void PackFrom(const ::$proto_ns$::Message& message);\n"
  1021. "void PackFrom(const ::$proto_ns$::Message& message,\n"
  1022. " const std::string& type_url_prefix);\n"
  1023. "bool UnpackTo(::$proto_ns$::Message* message) const;\n"
  1024. "static bool GetAnyFieldDescriptors(\n"
  1025. " const ::$proto_ns$::Message& message,\n"
  1026. " const ::$proto_ns$::FieldDescriptor** type_url_field,\n"
  1027. " const ::$proto_ns$::FieldDescriptor** value_field);\n");
  1028. } else {
  1029. format(
  1030. "template <typename T>\n"
  1031. "void PackFrom(const T& message) {\n"
  1032. " _any_metadata_.PackFrom(message);\n"
  1033. "}\n"
  1034. "template <typename T>\n"
  1035. "void PackFrom(const T& message,\n"
  1036. " const std::string& type_url_prefix) {\n"
  1037. " _any_metadata_.PackFrom(message, type_url_prefix);"
  1038. "}\n"
  1039. "template <typename T>\n"
  1040. "bool UnpackTo(T* message) const {\n"
  1041. " return _any_metadata_.UnpackTo(message);\n"
  1042. "}\n");
  1043. }
  1044. format(
  1045. "template<typename T> bool Is() const {\n"
  1046. " return _any_metadata_.Is<T>();\n"
  1047. "}\n"
  1048. "static bool ParseAnyTypeUrl(const string& type_url,\n"
  1049. " std::string* full_type_name);\n");
  1050. }
  1051. format.Set("new_final",
  1052. ShouldMarkNewAsFinal(descriptor_, options_) ? "final" : "");
  1053. format(
  1054. "void Swap($classname$* other);\n"
  1055. "friend void swap($classname$& a, $classname$& b) {\n"
  1056. " a.Swap(&b);\n"
  1057. "}\n"
  1058. "\n"
  1059. "// implements Message ----------------------------------------------\n"
  1060. "\n"
  1061. "inline $classname$* New() const$ new_final$ {\n"
  1062. " return CreateMaybeMessage<$classname$>(nullptr);\n"
  1063. "}\n"
  1064. "\n"
  1065. "$classname$* New(::$proto_ns$::Arena* arena) const$ new_final$ {\n"
  1066. " return CreateMaybeMessage<$classname$>(arena);\n"
  1067. "}\n");
  1068. // For instances that derive from Message (rather than MessageLite), some
  1069. // methods are virtual and should be marked as final.
  1070. format.Set("full_final", HasDescriptorMethods(descriptor_->file(), options_)
  1071. ? "final"
  1072. : "");
  1073. if (HasGeneratedMethods(descriptor_->file(), options_)) {
  1074. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  1075. format(
  1076. "void CopyFrom(const ::$proto_ns$::Message& from) final;\n"
  1077. "void MergeFrom(const ::$proto_ns$::Message& from) final;\n");
  1078. } else {
  1079. format(
  1080. "void CheckTypeAndMergeFrom(const ::$proto_ns$::MessageLite& from)\n"
  1081. " final;\n");
  1082. }
  1083. format.Set("clear_final",
  1084. ShouldMarkClearAsFinal(descriptor_, options_) ? "final" : "");
  1085. format.Set(
  1086. "is_initialized_final",
  1087. ShouldMarkIsInitializedAsFinal(descriptor_, options_) ? "final" : "");
  1088. format.Set(
  1089. "merge_partial_final",
  1090. ShouldMarkMergePartialAsFinal(descriptor_, options_) ? "final" : "");
  1091. format(
  1092. "void CopyFrom(const $classname$& from);\n"
  1093. "void MergeFrom(const $classname$& from);\n"
  1094. "PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear()$ clear_final$;\n"
  1095. "bool IsInitialized() const$ is_initialized_final$;\n"
  1096. "\n"
  1097. "size_t ByteSizeLong() const final;\n"
  1098. "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"
  1099. "const char* _InternalParse(const char* ptr, "
  1100. "::$proto_ns$::internal::ParseContext* ctx) final;\n"
  1101. "#else\n"
  1102. "bool MergePartialFromCodedStream(\n"
  1103. " ::$proto_ns$::io::CodedInputStream* input)$ "
  1104. "merge_partial_final$;\n"
  1105. "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
  1106. if (!options_.table_driven_serialization ||
  1107. descriptor_->options().message_set_wire_format()) {
  1108. format(
  1109. "void SerializeWithCachedSizes(\n"
  1110. " ::$proto_ns$::io::CodedOutputStream* output) const final;\n");
  1111. }
  1112. // DiscardUnknownFields() is implemented in message.cc using reflections. We
  1113. // need to implement this function in generated code for messages.
  1114. if (!UseUnknownFieldSet(descriptor_->file(), options_)) {
  1115. format("void DiscardUnknownFields()$ full_final$;\n");
  1116. }
  1117. if (HasFastArraySerialization(descriptor_->file(), options_)) {
  1118. format(
  1119. "$uint8$* InternalSerializeWithCachedSizesToArray(\n"
  1120. " $uint8$* target) const final;\n");
  1121. }
  1122. }
  1123. format(
  1124. "int GetCachedSize() const final { return _cached_size_.Get(); }"
  1125. "\n\nprivate:\n"
  1126. "inline void SharedCtor();\n"
  1127. "inline void SharedDtor();\n"
  1128. "void SetCachedSize(int size) const$ full_final$;\n"
  1129. "void InternalSwap($classname$* other);\n");
  1130. format(
  1131. // Friend AnyMetadata so that it can call this FullMessageName() method.
  1132. "friend class ::$proto_ns$::internal::AnyMetadata;\n"
  1133. "static $1$ FullMessageName() {\n"
  1134. " return \"$full_name$\";\n"
  1135. "}\n",
  1136. options_.opensource_runtime ? "::PROTOBUF_NAMESPACE_ID::StringPiece"
  1137. : "::StringPiece");
  1138. if (SupportsArenas(descriptor_)) {
  1139. format(
  1140. // TODO(gerbens) Make this private! Currently people are deriving from
  1141. // protos to give access to this constructor, breaking the invariants
  1142. // we rely on.
  1143. "protected:\n"
  1144. "explicit $classname$(::$proto_ns$::Arena* arena);\n"
  1145. "private:\n"
  1146. "static void ArenaDtor(void* object);\n"
  1147. "inline void RegisterArenaDtor(::$proto_ns$::Arena* arena);\n");
  1148. }
  1149. if (SupportsArenas(descriptor_)) {
  1150. format(
  1151. "private:\n"
  1152. "inline ::$proto_ns$::Arena* GetArenaNoVirtual() const {\n"
  1153. " return _internal_metadata_.arena();\n"
  1154. "}\n"
  1155. "inline void* MaybeArenaPtr() const {\n"
  1156. " return _internal_metadata_.raw_arena_ptr();\n"
  1157. "}\n");
  1158. } else {
  1159. format(
  1160. "private:\n"
  1161. "inline ::$proto_ns$::Arena* GetArenaNoVirtual() const {\n"
  1162. " return nullptr;\n"
  1163. "}\n"
  1164. "inline void* MaybeArenaPtr() const {\n"
  1165. " return nullptr;\n"
  1166. "}\n");
  1167. }
  1168. format(
  1169. "public:\n"
  1170. "\n");
  1171. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  1172. format(
  1173. "::$proto_ns$::Metadata GetMetadata() const final;\n"
  1174. "\n");
  1175. } else {
  1176. format(
  1177. "std::string GetTypeName() const final;\n"
  1178. "\n");
  1179. }
  1180. format(
  1181. "// nested types ----------------------------------------------------\n"
  1182. "\n");
  1183. // Import all nested message classes into this class's scope with typedefs.
  1184. for (int i = 0; i < descriptor_->nested_type_count(); i++) {
  1185. const Descriptor* nested_type = descriptor_->nested_type(i);
  1186. if (!IsMapEntryMessage(nested_type)) {
  1187. format.Set("nested_full_name", ClassName(nested_type, false));
  1188. format.Set("nested_name", ResolveKeyword(nested_type->name()));
  1189. format("typedef ${1$$nested_full_name$$}$ ${1$$nested_name$$}$;\n",
  1190. nested_type);
  1191. }
  1192. }
  1193. if (descriptor_->nested_type_count() > 0) {
  1194. format("\n");
  1195. }
  1196. // Import all nested enums and their values into this class's scope with
  1197. // typedefs and constants.
  1198. for (int i = 0; i < descriptor_->enum_type_count(); i++) {
  1199. enum_generators_[i]->GenerateSymbolImports(printer);
  1200. format("\n");
  1201. }
  1202. format(
  1203. "// accessors -------------------------------------------------------\n"
  1204. "\n");
  1205. // Generate accessor methods for all fields.
  1206. GenerateFieldAccessorDeclarations(printer);
  1207. // Declare extension identifiers.
  1208. for (int i = 0; i < descriptor_->extension_count(); i++) {
  1209. extension_generators_[i]->GenerateDeclaration(printer);
  1210. }
  1211. format("// @@protoc_insertion_point(class_scope:$full_name$)\n");
  1212. // Generate private members.
  1213. format.Outdent();
  1214. format(" private:\n");
  1215. format.Indent();
  1216. // TODO(seongkim): Remove hack to track field access and remove this class.
  1217. format("class HasBitSetters;\n");
  1218. for (auto field : FieldRange(descriptor_)) {
  1219. // set_has_***() generated in all oneofs.
  1220. if (!field->is_repeated() && !field->options().weak() &&
  1221. field->containing_oneof()) {
  1222. format("void set_has_$1$();\n", FieldName(field));
  1223. }
  1224. }
  1225. format("\n");
  1226. // Generate oneof function declarations
  1227. for (auto oneof : OneOfRange(descriptor_)) {
  1228. format(
  1229. "inline bool has_$1$() const;\n"
  1230. "inline void clear_has_$1$();\n\n",
  1231. oneof->name());
  1232. }
  1233. if (HasGeneratedMethods(descriptor_->file(), options_) &&
  1234. !descriptor_->options().message_set_wire_format() &&
  1235. num_required_fields_ > 1) {
  1236. format(
  1237. "// helper for ByteSizeLong()\n"
  1238. "size_t RequiredFieldsByteSizeFallback() const;\n\n");
  1239. }
  1240. // Prepare decls for _cached_size_ and _has_bits_. Their position in the
  1241. // output will be determined later.
  1242. bool need_to_emit_cached_size = true;
  1243. const std::string cached_size_decl =
  1244. "mutable ::$proto_ns$::internal::CachedSize _cached_size_;\n";
  1245. const size_t sizeof_has_bits = HasBitsSize();
  1246. const std::string has_bits_decl =
  1247. sizeof_has_bits == 0
  1248. ? ""
  1249. : StrCat("::$proto_ns$::internal::HasBits<",
  1250. sizeof_has_bits / 4, "> _has_bits_;\n");
  1251. // To minimize padding, data members are divided into three sections:
  1252. // (1) members assumed to align to 8 bytes
  1253. // (2) members corresponding to message fields, re-ordered to optimize
  1254. // alignment.
  1255. // (3) members assumed to align to 4 bytes.
  1256. // Members assumed to align to 8 bytes:
  1257. if (descriptor_->extension_range_count() > 0) {
  1258. format(
  1259. "::$proto_ns$::internal::ExtensionSet _extensions_;\n"
  1260. "\n");
  1261. }
  1262. if (UseUnknownFieldSet(descriptor_->file(), options_)) {
  1263. format(
  1264. "::$proto_ns$::internal::InternalMetadataWithArena "
  1265. "_internal_metadata_;\n");
  1266. } else {
  1267. format(
  1268. "::$proto_ns$::internal::InternalMetadataWithArenaLite "
  1269. "_internal_metadata_;\n");
  1270. }
  1271. if (SupportsArenas(descriptor_)) {
  1272. if (!options_.opensource_runtime) {
  1273. format(
  1274. "template <typename T> friend struct "
  1275. "::proto::internal::EmbeddedMessageHolder;\n");
  1276. }
  1277. format(
  1278. "template <typename T> friend class "
  1279. "::$proto_ns$::Arena::InternalHelper;\n"
  1280. "typedef void InternalArenaConstructable_;\n"
  1281. "typedef void DestructorSkippable_;\n");
  1282. }
  1283. if (HasFieldPresence(descriptor_->file())) {
  1284. // _has_bits_ is frequently accessed, so to reduce code size and improve
  1285. // speed, it should be close to the start of the object. Placing
  1286. // _cached_size_ together with _has_bits_ improves cache locality despite
  1287. // potential alignment padding.
  1288. format(has_bits_decl.c_str());
  1289. format(cached_size_decl.c_str());
  1290. need_to_emit_cached_size = false;
  1291. }
  1292. // Field members:
  1293. // Emit some private and static members
  1294. for (auto field : optimized_order_) {
  1295. const FieldGenerator& generator = field_generators_.get(field);
  1296. generator.GenerateStaticMembers(printer);
  1297. generator.GeneratePrivateMembers(printer);
  1298. }
  1299. // For each oneof generate a union
  1300. for (auto oneof : OneOfRange(descriptor_)) {
  1301. std::string camel_oneof_name = UnderscoresToCamelCase(oneof->name(), true);
  1302. format(
  1303. "union $1$Union {\n"
  1304. // explicit empty constructor is needed when union contains
  1305. // ArenaStringPtr members for string fields.
  1306. " $1$Union() {}\n",
  1307. camel_oneof_name);
  1308. format.Indent();
  1309. for (auto field : FieldRange(oneof)) {
  1310. field_generators_.get(field).GeneratePrivateMembers(printer);
  1311. }
  1312. format.Outdent();
  1313. format("} $1$_;\n", oneof->name());
  1314. for (auto field : FieldRange(oneof)) {
  1315. field_generators_.get(field).GenerateStaticMembers(printer);
  1316. }
  1317. }
  1318. // Members assumed to align to 4 bytes:
  1319. if (need_to_emit_cached_size) {
  1320. format(cached_size_decl.c_str());
  1321. need_to_emit_cached_size = false;
  1322. }
  1323. // Generate _oneof_case_.
  1324. if (descriptor_->oneof_decl_count() > 0) {
  1325. format(
  1326. "$uint32$ _oneof_case_[$1$];\n"
  1327. "\n",
  1328. descriptor_->oneof_decl_count());
  1329. }
  1330. if (num_weak_fields_) {
  1331. format("::$proto_ns$::internal::WeakFieldMap _weak_field_map_;\n");
  1332. }
  1333. // Generate _any_metadata_ for the Any type.
  1334. if (IsAnyMessage(descriptor_, options_)) {
  1335. format("::$proto_ns$::internal::AnyMetadata _any_metadata_;\n");
  1336. }
  1337. // The TableStruct struct needs access to the private parts, in order to
  1338. // construct the offsets of all members.
  1339. format("friend struct ::$tablename$;\n");
  1340. format.Outdent();
  1341. format("};");
  1342. GOOGLE_DCHECK(!need_to_emit_cached_size);
  1343. }
  1344. void MessageGenerator::GenerateInlineMethods(io::Printer* printer) {
  1345. if (IsMapEntryMessage(descriptor_)) return;
  1346. GenerateFieldAccessorDefinitions(printer);
  1347. // Generate oneof_case() functions.
  1348. for (auto oneof : OneOfRange(descriptor_)) {
  1349. Formatter format(printer, variables_);
  1350. format.Set("camel_oneof_name", UnderscoresToCamelCase(oneof->name(), true));
  1351. format.Set("oneof_name", oneof->name());
  1352. format.Set("oneof_index", oneof->index());
  1353. format(
  1354. "inline $classname$::$camel_oneof_name$Case $classname$::"
  1355. "$oneof_name$_case() const {\n"
  1356. " return $classname$::$camel_oneof_name$Case("
  1357. "_oneof_case_[$oneof_index$]);\n"
  1358. "}\n");
  1359. }
  1360. }
  1361. void MessageGenerator::GenerateExtraDefaultFields(io::Printer* printer) {
  1362. // Generate oneof default instance and weak field instances for reflection
  1363. // usage.
  1364. Formatter format(printer, variables_);
  1365. if (descriptor_->oneof_decl_count() > 0 || num_weak_fields_ > 0) {
  1366. for (auto oneof : OneOfRange(descriptor_)) {
  1367. for (auto field : FieldRange(oneof)) {
  1368. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
  1369. (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING &&
  1370. EffectiveStringCType(field, options_) != FieldOptions::STRING)) {
  1371. format("const ");
  1372. }
  1373. field_generators_.get(field).GeneratePrivateMembers(printer);
  1374. }
  1375. }
  1376. for (auto field : FieldRange(descriptor_)) {
  1377. if (field->options().weak()) {
  1378. format(" const ::$proto_ns$::Message* $1$_;\n", FieldName(field));
  1379. }
  1380. }
  1381. }
  1382. }
  1383. bool MessageGenerator::GenerateParseTable(io::Printer* printer, size_t offset,
  1384. size_t aux_offset) {
  1385. Formatter format(printer, variables_);
  1386. if (!table_driven_) {
  1387. format("{ nullptr, nullptr, 0, -1, -1, -1, -1, nullptr, false },\n");
  1388. return false;
  1389. }
  1390. int max_field_number = 0;
  1391. for (auto field : FieldRange(descriptor_)) {
  1392. if (max_field_number < field->number()) {
  1393. max_field_number = field->number();
  1394. }
  1395. }
  1396. format("{\n");
  1397. format.Indent();
  1398. format(
  1399. "$tablename$::entries + $1$,\n"
  1400. "$tablename$::aux + $2$,\n"
  1401. "$3$,\n",
  1402. offset, aux_offset, max_field_number);
  1403. if (!HasFieldPresence(descriptor_->file())) {
  1404. // If we don't have field presence, then _has_bits_ does not exist.
  1405. format("-1,\n");
  1406. } else {
  1407. format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n");
  1408. }
  1409. if (descriptor_->oneof_decl_count() > 0) {
  1410. format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_),\n");
  1411. } else {
  1412. format("-1, // no _oneof_case_\n");
  1413. }
  1414. if (descriptor_->extension_range_count() > 0) {
  1415. format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n");
  1416. } else {
  1417. format("-1, // no _extensions_\n");
  1418. }
  1419. // TODO(ckennelly): Consolidate this with the calculation for
  1420. // AuxillaryParseTableField.
  1421. format(
  1422. "PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n"
  1423. "&$package_ns$::_$classname$_default_instance_,\n");
  1424. if (UseUnknownFieldSet(descriptor_->file(), options_)) {
  1425. format("true,\n");
  1426. } else {
  1427. format("false,\n");
  1428. }
  1429. format.Outdent();
  1430. format("},\n");
  1431. return true;
  1432. }
  1433. void MessageGenerator::GenerateSchema(io::Printer* printer, int offset,
  1434. int has_offset) {
  1435. Formatter format(printer, variables_);
  1436. has_offset =
  1437. HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)
  1438. ? offset + has_offset
  1439. : -1;
  1440. format("{ $1$, $2$, sizeof($classtype$)},\n", offset, has_offset);
  1441. }
  1442. namespace {
  1443. // We need to calculate for each field what function the table driven code
  1444. // should use to serialize it. This returns the index in a lookup table.
  1445. uint32 CalcFieldNum(const FieldGenerator& generator,
  1446. const FieldDescriptor* field, const Options& options) {
  1447. bool is_a_map = IsMapEntryMessage(field->containing_type());
  1448. int type = field->type();
  1449. if (type == FieldDescriptor::TYPE_STRING ||
  1450. type == FieldDescriptor::TYPE_BYTES) {
  1451. if (generator.IsInlined()) {
  1452. type = internal::FieldMetadata::kInlinedType;
  1453. }
  1454. // string field
  1455. if (IsCord(field, options)) {
  1456. type = internal::FieldMetadata::kCordType;
  1457. } else if (IsStringPiece(field, options)) {
  1458. type = internal::FieldMetadata::kStringPieceType;
  1459. }
  1460. }
  1461. if (field->containing_oneof()) {
  1462. return internal::FieldMetadata::CalculateType(
  1463. type, internal::FieldMetadata::kOneOf);
  1464. }
  1465. if (field->is_packed()) {
  1466. return internal::FieldMetadata::CalculateType(
  1467. type, internal::FieldMetadata::kPacked);
  1468. } else if (field->is_repeated()) {
  1469. return internal::FieldMetadata::CalculateType(
  1470. type, internal::FieldMetadata::kRepeated);
  1471. } else if (!HasFieldPresence(field->file()) &&
  1472. field->containing_oneof() == NULL && !is_a_map) {
  1473. return internal::FieldMetadata::CalculateType(
  1474. type, internal::FieldMetadata::kNoPresence);
  1475. } else {
  1476. return internal::FieldMetadata::CalculateType(
  1477. type, internal::FieldMetadata::kPresence);
  1478. }
  1479. }
  1480. int FindMessageIndexInFile(const Descriptor* descriptor) {
  1481. std::vector<const Descriptor*> flatten =
  1482. FlattenMessagesInFile(descriptor->file());
  1483. return std::find(flatten.begin(), flatten.end(), descriptor) -
  1484. flatten.begin();
  1485. }
  1486. } // namespace
  1487. int MessageGenerator::GenerateFieldMetadata(io::Printer* printer) {
  1488. Formatter format(printer, variables_);
  1489. if (!options_.table_driven_serialization) {
  1490. return 0;
  1491. }
  1492. std::vector<const FieldDescriptor*> sorted = SortFieldsByNumber(descriptor_);
  1493. if (IsMapEntryMessage(descriptor_)) {
  1494. for (int i = 0; i < 2; i++) {
  1495. const FieldDescriptor* field = sorted[i];
  1496. const FieldGenerator& generator = field_generators_.get(field);
  1497. uint32 tag = internal::WireFormatLite::MakeTag(
  1498. field->number(), WireFormat::WireTypeForFieldType(field->type()));
  1499. std::map<std::string, std::string> vars;
  1500. vars["classtype"] = QualifiedClassName(descriptor_, options_);
  1501. vars["field_name"] = FieldName(field);
  1502. vars["tag"] = StrCat(tag);
  1503. vars["hasbit"] = StrCat(i);
  1504. vars["type"] = StrCat(CalcFieldNum(generator, field, options_));
  1505. vars["ptr"] = "nullptr";
  1506. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1507. GOOGLE_CHECK(!IsMapEntryMessage(field->message_type()));
  1508. if (!IsProto1(field->message_type()->file(), options_)) {
  1509. vars["ptr"] =
  1510. "::" +
  1511. UniqueName("TableStruct", field->message_type(), options_) +
  1512. "::serialization_table + " +
  1513. StrCat(FindMessageIndexInFile(field->message_type()));
  1514. }
  1515. }
  1516. Formatter::SaveState saver(&format);
  1517. format.AddMap(vars);
  1518. format(
  1519. "{PROTOBUF_FIELD_OFFSET("
  1520. "::$proto_ns$::internal::MapEntryHelper<$classtype$::"
  1521. "SuperType>, $field_name$_), $tag$,"
  1522. "PROTOBUF_FIELD_OFFSET("
  1523. "::$proto_ns$::internal::MapEntryHelper<$classtype$::"
  1524. "SuperType>, _has_bits_) * 8 + $hasbit$, $type$, "
  1525. "$ptr$},\n");
  1526. }
  1527. return 2;
  1528. }
  1529. format(
  1530. "{PROTOBUF_FIELD_OFFSET($classtype$, _cached_size_),"
  1531. " 0, 0, 0, nullptr},\n");
  1532. std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
  1533. sorted_extensions.reserve(descriptor_->extension_range_count());
  1534. for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
  1535. sorted_extensions.push_back(descriptor_->extension_range(i));
  1536. }
  1537. std::sort(sorted_extensions.begin(), sorted_extensions.end(),
  1538. ExtensionRangeSorter());
  1539. for (int i = 0, extension_idx = 0; /* no range */; i++) {
  1540. for (; extension_idx < sorted_extensions.size() &&
  1541. (i == sorted.size() ||
  1542. sorted_extensions[extension_idx]->start < sorted[i]->number());
  1543. extension_idx++) {
  1544. const Descriptor::ExtensionRange* range =
  1545. sorted_extensions[extension_idx];
  1546. format(
  1547. "{PROTOBUF_FIELD_OFFSET($classtype$, _extensions_), "
  1548. "$1$, $2$, ::$proto_ns$::internal::FieldMetadata::kSpecial, "
  1549. "reinterpret_cast<const "
  1550. "void*>(::$proto_ns$::internal::ExtensionSerializer)},\n",
  1551. range->start, range->end);
  1552. }
  1553. if (i == sorted.size()) break;
  1554. const FieldDescriptor* field = sorted[i];
  1555. uint32 tag = internal::WireFormatLite::MakeTag(
  1556. field->number(), WireFormat::WireTypeForFieldType(field->type()));
  1557. if (field->is_packed()) {
  1558. tag = internal::WireFormatLite::MakeTag(
  1559. field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
  1560. }
  1561. std::string classfieldname = FieldName(field);
  1562. if (field->containing_oneof()) {
  1563. classfieldname = field->containing_oneof()->name();
  1564. }
  1565. format.Set("field_name", classfieldname);
  1566. std::string ptr = "nullptr";
  1567. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1568. if (IsMapEntryMessage(field->message_type())) {
  1569. format(
  1570. "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$, $2$, "
  1571. "::$proto_ns$::internal::FieldMetadata::kSpecial, "
  1572. "reinterpret_cast<const void*>(static_cast< "
  1573. "::$proto_ns$::internal::SpecialSerializer>("
  1574. "::$proto_ns$::internal::MapFieldSerializer< "
  1575. "::$proto_ns$::internal::MapEntryToMapField<"
  1576. "$3$>::MapFieldType, "
  1577. "$tablename$::serialization_table>))},\n",
  1578. tag, FindMessageIndexInFile(field->message_type()),
  1579. QualifiedClassName(field->message_type(), options_));
  1580. continue;
  1581. } else if (!IsProto1(field->message_type()->file(), options_) &&
  1582. !field->message_type()->options().message_set_wire_format()) {
  1583. // Proto1 or message_set don't have the usual table and we need to
  1584. // dispatch to generated serializer, hence ptr stays zero.
  1585. ptr =
  1586. "::" + UniqueName("TableStruct", field->message_type(), options_) +
  1587. "::serialization_table + " +
  1588. StrCat(FindMessageIndexInFile(field->message_type()));
  1589. }
  1590. }
  1591. const FieldGenerator& generator = field_generators_.get(field);
  1592. int type = CalcFieldNum(generator, field, options_);
  1593. if (IsLazy(field, options_)) {
  1594. type = internal::FieldMetadata::kSpecial;
  1595. ptr = "reinterpret_cast<const void*>(::" + variables_["proto_ns"] +
  1596. "::internal::LazyFieldSerializer";
  1597. if (field->containing_oneof()) {
  1598. ptr += "OneOf";
  1599. } else if (!HasFieldPresence(descriptor_->file()) ||
  1600. has_bit_indices_[field->index()] == -1) {
  1601. ptr += "NoPresence";
  1602. }
  1603. ptr += ")";
  1604. }
  1605. if (field->options().weak()) {
  1606. // TODO(gerbens) merge weak fields into ranges
  1607. format(
  1608. "{PROTOBUF_FIELD_OFFSET("
  1609. "$classtype$, _weak_field_map_), $1$, $1$, "
  1610. "::$proto_ns$::internal::FieldMetadata::kSpecial, "
  1611. "reinterpret_cast<const "
  1612. "void*>(::$proto_ns$::internal::WeakFieldSerializer)},\n",
  1613. tag);
  1614. } else if (field->containing_oneof()) {
  1615. format.Set("oneofoffset",
  1616. sizeof(uint32) * field->containing_oneof()->index());
  1617. format(
  1618. "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), $1$,"
  1619. " PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_) + "
  1620. "$oneofoffset$, $2$, $3$},\n",
  1621. tag, type, ptr);
  1622. } else if (HasFieldPresence(descriptor_->file()) &&
  1623. has_bit_indices_[field->index()] != -1) {
  1624. format.Set("hasbitsoffset", has_bit_indices_[field->index()]);
  1625. format(
  1626. "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), "
  1627. "$1$, PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_) * 8 + "
  1628. "$hasbitsoffset$, $2$, $3$},\n",
  1629. tag, type, ptr);
  1630. } else {
  1631. format(
  1632. "{PROTOBUF_FIELD_OFFSET($classtype$, $field_name$_), "
  1633. "$1$, ~0u, $2$, $3$},\n",
  1634. tag, type, ptr);
  1635. }
  1636. }
  1637. int num_field_metadata = 1 + sorted.size() + sorted_extensions.size();
  1638. num_field_metadata++;
  1639. std::string serializer = UseUnknownFieldSet(descriptor_->file(), options_)
  1640. ? "UnknownFieldSetSerializer"
  1641. : "UnknownFieldSerializerLite";
  1642. format(
  1643. "{PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_), 0, ~0u, "
  1644. "::$proto_ns$::internal::FieldMetadata::kSpecial, reinterpret_cast<const "
  1645. "void*>(::$proto_ns$::internal::$1$)},\n",
  1646. serializer);
  1647. return num_field_metadata;
  1648. }
  1649. void MessageGenerator::GenerateFieldDefaultInstances(io::Printer* printer) {
  1650. // Construct the default instances for all fields that need one.
  1651. for (auto field : FieldRange(descriptor_)) {
  1652. field_generators_.get(field).GenerateDefaultInstanceAllocator(printer);
  1653. }
  1654. }
  1655. void MessageGenerator::GenerateDefaultInstanceInitializer(
  1656. io::Printer* printer) {
  1657. Formatter format(printer, variables_);
  1658. // The default instance needs all of its embedded message pointers
  1659. // cross-linked to other default instances. We can't do this initialization
  1660. // in the constructor because some other default instances may not have been
  1661. // constructed yet at that time.
  1662. // TODO(kenton): Maybe all message fields (even for non-default messages)
  1663. // should be initialized to point at default instances rather than NULL?
  1664. for (auto field : FieldRange(descriptor_)) {
  1665. Formatter::SaveState saver(&format);
  1666. if (!field->is_repeated() &&
  1667. !IsLazy(field, options_) &&
  1668. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  1669. (field->containing_oneof() == NULL ||
  1670. HasDescriptorMethods(descriptor_->file(), options_))) {
  1671. std::string name;
  1672. if (field->containing_oneof() || field->options().weak()) {
  1673. name = "_" + classname_ + "_default_instance_.";
  1674. } else {
  1675. name =
  1676. "_" + classname_ + "_default_instance_._instance.get_mutable()->";
  1677. }
  1678. name += FieldName(field);
  1679. format.Set("name", name);
  1680. if (IsWeak(field, options_)) {
  1681. format(
  1682. "$package_ns$::$name$_ = reinterpret_cast<const "
  1683. "::$proto_ns$::Message*>(&$1$);\n"
  1684. "if ($package_ns$::$name$_ == nullptr) {\n"
  1685. " $package_ns$::$name$_ = "
  1686. "::$proto_ns$::Empty::internal_default_instance();\n"
  1687. "}\n",
  1688. DefaultInstanceName(field->message_type(), options_)); // 1
  1689. continue;
  1690. }
  1691. format(
  1692. "$package_ns$::$name$_ = const_cast< $1$*>(\n"
  1693. " $1$::internal_default_instance());\n",
  1694. FieldMessageTypeName(field, options_));
  1695. } else if (field->containing_oneof() &&
  1696. HasDescriptorMethods(descriptor_->file(), options_)) {
  1697. field_generators_.get(field).GenerateConstructorCode(printer);
  1698. }
  1699. }
  1700. }
  1701. void MessageGenerator::GenerateClassMethods(io::Printer* printer) {
  1702. Formatter format(printer, variables_);
  1703. if (IsMapEntryMessage(descriptor_)) {
  1704. format(
  1705. "$classname$::$classname$() {}\n"
  1706. "$classname$::$classname$(::$proto_ns$::Arena* arena)\n"
  1707. " : SuperType(arena) {}\n"
  1708. "void $classname$::MergeFrom(const $classname$& other) {\n"
  1709. " MergeFromInternal(other);\n"
  1710. "}\n");
  1711. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  1712. format(
  1713. "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n"
  1714. " "
  1715. "::$proto_ns$::internal::AssignDescriptors(&::$assign_desc_table$);\n"
  1716. " return ::$file_level_metadata$[$1$];\n"
  1717. "}\n",
  1718. index_in_file_messages_);
  1719. format(
  1720. "void $classname$::MergeFrom(\n"
  1721. " const ::$proto_ns$::Message& other) {\n"
  1722. " ::$proto_ns$::Message::MergeFrom(other);\n"
  1723. "}\n"
  1724. "\n");
  1725. }
  1726. return;
  1727. }
  1728. // TODO(gerbens) Remove this function. With a little bit of cleanup and
  1729. // refactoring this is superfluous.
  1730. format("void $classname$::InitAsDefaultInstance() {\n");
  1731. format.Indent();
  1732. GenerateDefaultInstanceInitializer(printer);
  1733. format.Outdent();
  1734. format("}\n");
  1735. if (IsAnyMessage(descriptor_, options_)) {
  1736. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  1737. format(
  1738. "void $classname$::PackFrom(const ::$proto_ns$::Message& message) {\n"
  1739. " _any_metadata_.PackFrom(message);\n"
  1740. "}\n"
  1741. "\n"
  1742. "void $classname$::PackFrom(const ::$proto_ns$::Message& message,\n"
  1743. " const std::string& type_url_prefix) {\n"
  1744. " _any_metadata_.PackFrom(message, type_url_prefix);\n"
  1745. "}\n"
  1746. "\n"
  1747. "bool $classname$::UnpackTo(::$proto_ns$::Message* message) const {\n"
  1748. " return _any_metadata_.UnpackTo(message);\n"
  1749. "}\n"
  1750. "bool $classname$::GetAnyFieldDescriptors(\n"
  1751. " const ::$proto_ns$::Message& message,\n"
  1752. " const ::$proto_ns$::FieldDescriptor** type_url_field,\n"
  1753. " const ::$proto_ns$::FieldDescriptor** value_field) {\n"
  1754. " return ::$proto_ns$::internal::GetAnyFieldDescriptors(\n"
  1755. " message, type_url_field, value_field);\n"
  1756. "}\n");
  1757. }
  1758. format(
  1759. "bool $classname$::ParseAnyTypeUrl(const string& type_url,\n"
  1760. " std::string* full_type_name) {\n"
  1761. " return ::$proto_ns$::internal::ParseAnyTypeUrl(type_url,\n"
  1762. " full_type_name);\n"
  1763. "}\n"
  1764. "\n");
  1765. }
  1766. format(
  1767. "class $classname$::HasBitSetters {\n"
  1768. " public:\n");
  1769. format.Indent();
  1770. for (auto field : FieldRange(descriptor_)) {
  1771. field_generators_.get(field).GenerateInternalAccessorDeclarations(printer);
  1772. if (HasFieldPresence(descriptor_->file()) && !field->is_repeated() &&
  1773. !field->options().weak() && !field->containing_oneof()) {
  1774. int has_bit_index = has_bit_indices_[field->index()];
  1775. GOOGLE_CHECK_GE(has_bit_index, 0);
  1776. format.Set("has_array_index", has_bit_index / 32);
  1777. format.Set("has_mask",
  1778. strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
  1779. format(
  1780. "static void set_has_$1$($classname$* msg) {\n"
  1781. " msg->_has_bits_[$has_array_index$] |= 0x$has_mask$u;\n"
  1782. "}\n",
  1783. FieldName(field));
  1784. }
  1785. }
  1786. format.Outdent();
  1787. format("};\n\n");
  1788. for (auto field : FieldRange(descriptor_)) {
  1789. field_generators_.get(field).GenerateInternalAccessorDefinitions(printer);
  1790. }
  1791. // Generate non-inline field definitions.
  1792. for (auto field : FieldRange(descriptor_)) {
  1793. field_generators_.get(field).GenerateNonInlineAccessorDefinitions(printer);
  1794. if (IsCrossFileMaybeMap(field)) {
  1795. Formatter::SaveState saver(&format);
  1796. std::map<std::string, std::string> vars;
  1797. SetCommonFieldVariables(field, &vars, options_);
  1798. if (field->containing_oneof()) {
  1799. SetCommonOneofFieldVariables(field, &vars);
  1800. }
  1801. format.AddMap(vars);
  1802. GenerateFieldClear(field, false, format);
  1803. }
  1804. }
  1805. // Generate field number constants.
  1806. format("#if !defined(_MSC_VER) || _MSC_VER >= 1900\n");
  1807. for (auto field : FieldRange(descriptor_)) {
  1808. format("const int $classname$::$1$;\n", FieldConstantName(field));
  1809. }
  1810. format(
  1811. "#endif // !defined(_MSC_VER) || _MSC_VER >= 1900\n"
  1812. "\n");
  1813. GenerateStructors(printer);
  1814. format("\n");
  1815. if (descriptor_->oneof_decl_count() > 0) {
  1816. GenerateOneofClear(printer);
  1817. format("\n");
  1818. }
  1819. if (HasGeneratedMethods(descriptor_->file(), options_)) {
  1820. GenerateClear(printer);
  1821. format("\n");
  1822. GenerateMergeFromCodedStream(printer);
  1823. format("\n");
  1824. GenerateSerializeWithCachedSizes(printer);
  1825. format("\n");
  1826. if (HasFastArraySerialization(descriptor_->file(), options_)) {
  1827. GenerateSerializeWithCachedSizesToArray(printer);
  1828. format("\n");
  1829. }
  1830. GenerateByteSize(printer);
  1831. format("\n");
  1832. GenerateMergeFrom(printer);
  1833. format("\n");
  1834. GenerateCopyFrom(printer);
  1835. format("\n");
  1836. GenerateIsInitialized(printer);
  1837. format("\n");
  1838. }
  1839. GenerateSwap(printer);
  1840. format("\n");
  1841. if (options_.table_driven_serialization) {
  1842. format(
  1843. "const void* $classname$::InternalGetTable() const {\n"
  1844. " return ::$tablename$::serialization_table + $1$;\n"
  1845. "}\n"
  1846. "\n",
  1847. index_in_file_messages_);
  1848. }
  1849. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  1850. format(
  1851. "::$proto_ns$::Metadata $classname$::GetMetadata() const {\n"
  1852. " ::$proto_ns$::internal::AssignDescriptors(&::$assign_desc_table$);\n"
  1853. " return ::$file_level_metadata$[kIndexInFileMessages];\n"
  1854. "}\n"
  1855. "\n");
  1856. } else {
  1857. format(
  1858. "std::string $classname$::GetTypeName() const {\n"
  1859. " return \"$full_name$\";\n"
  1860. "}\n"
  1861. "\n");
  1862. }
  1863. }
  1864. size_t MessageGenerator::GenerateParseOffsets(io::Printer* printer) {
  1865. Formatter format(printer, variables_);
  1866. if (!table_driven_) {
  1867. return 0;
  1868. }
  1869. // Field "0" is special: We use it in our switch statement of processing
  1870. // types to handle the successful end tag case.
  1871. format("{0, 0, 0, ::$proto_ns$::internal::kInvalidMask, 0, 0},\n");
  1872. int last_field_number = 1;
  1873. std::vector<const FieldDescriptor*> ordered_fields =
  1874. SortFieldsByNumber(descriptor_);
  1875. for (auto field : ordered_fields) {
  1876. Formatter::SaveState saver(&format);
  1877. GOOGLE_CHECK_GE(field->number(), last_field_number);
  1878. for (; last_field_number < field->number(); last_field_number++) {
  1879. format(
  1880. "{ 0, 0, ::$proto_ns$::internal::kInvalidMask,\n"
  1881. " ::$proto_ns$::internal::kInvalidMask, 0, 0 },\n");
  1882. }
  1883. last_field_number++;
  1884. unsigned char normal_wiretype, packed_wiretype, processing_type;
  1885. normal_wiretype = WireFormat::WireTypeForFieldType(field->type());
  1886. if (field->is_packable()) {
  1887. packed_wiretype = WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
  1888. } else {
  1889. packed_wiretype = internal::kNotPackedMask;
  1890. }
  1891. processing_type = static_cast<unsigned>(field->type());
  1892. const FieldGenerator& generator = field_generators_.get(field);
  1893. if (field->type() == FieldDescriptor::TYPE_STRING) {
  1894. switch (EffectiveStringCType(field, options_)) {
  1895. case FieldOptions::STRING:
  1896. if (generator.IsInlined()) {
  1897. processing_type = internal::TYPE_STRING_INLINED;
  1898. break;
  1899. }
  1900. break;
  1901. case FieldOptions::CORD:
  1902. processing_type = internal::TYPE_STRING_CORD;
  1903. break;
  1904. case FieldOptions::STRING_PIECE:
  1905. processing_type = internal::TYPE_STRING_STRING_PIECE;
  1906. break;
  1907. }
  1908. } else if (field->type() == FieldDescriptor::TYPE_BYTES) {
  1909. switch (EffectiveStringCType(field, options_)) {
  1910. case FieldOptions::STRING:
  1911. if (generator.IsInlined()) {
  1912. processing_type = internal::TYPE_BYTES_INLINED;
  1913. break;
  1914. }
  1915. break;
  1916. case FieldOptions::CORD:
  1917. processing_type = internal::TYPE_BYTES_CORD;
  1918. break;
  1919. case FieldOptions::STRING_PIECE:
  1920. processing_type = internal::TYPE_BYTES_STRING_PIECE;
  1921. break;
  1922. }
  1923. }
  1924. processing_type |= static_cast<unsigned>(
  1925. field->is_repeated() ? internal::kRepeatedMask : 0);
  1926. processing_type |= static_cast<unsigned>(
  1927. field->containing_oneof() ? internal::kOneofMask : 0);
  1928. if (field->is_map()) {
  1929. processing_type = internal::TYPE_MAP;
  1930. }
  1931. const unsigned char tag_size =
  1932. WireFormat::TagSize(field->number(), field->type());
  1933. std::map<std::string, std::string> vars;
  1934. if (field->containing_oneof() != NULL) {
  1935. vars["name"] = field->containing_oneof()->name();
  1936. vars["presence"] = StrCat(field->containing_oneof()->index());
  1937. } else {
  1938. vars["name"] = FieldName(field);
  1939. vars["presence"] = StrCat(has_bit_indices_[field->index()]);
  1940. }
  1941. vars["nwtype"] = StrCat(normal_wiretype);
  1942. vars["pwtype"] = StrCat(packed_wiretype);
  1943. vars["ptype"] = StrCat(processing_type);
  1944. vars["tag_size"] = StrCat(tag_size);
  1945. format.AddMap(vars);
  1946. format(
  1947. "{\n"
  1948. " PROTOBUF_FIELD_OFFSET($classtype$, $name$_),\n"
  1949. " static_cast<$uint32$>($presence$),\n"
  1950. " $nwtype$, $pwtype$, $ptype$, $tag_size$\n"
  1951. "},\n");
  1952. }
  1953. return last_field_number;
  1954. }
  1955. size_t MessageGenerator::GenerateParseAuxTable(io::Printer* printer) {
  1956. Formatter format(printer, variables_);
  1957. if (!table_driven_) {
  1958. return 0;
  1959. }
  1960. std::vector<const FieldDescriptor*> ordered_fields =
  1961. SortFieldsByNumber(descriptor_);
  1962. format("::$proto_ns$::internal::AuxillaryParseTableField(),\n");
  1963. int last_field_number = 1;
  1964. for (auto field : ordered_fields) {
  1965. Formatter::SaveState saver(&format);
  1966. GOOGLE_CHECK_GE(field->number(), last_field_number);
  1967. for (; last_field_number < field->number(); last_field_number++) {
  1968. format("::$proto_ns$::internal::AuxillaryParseTableField(),\n");
  1969. }
  1970. std::map<std::string, std::string> vars;
  1971. SetCommonFieldVariables(field, &vars, options_);
  1972. format.AddMap(vars);
  1973. switch (field->cpp_type()) {
  1974. case FieldDescriptor::CPPTYPE_ENUM:
  1975. if (HasPreservingUnknownEnumSemantics(field)) {
  1976. format(
  1977. "{::$proto_ns$::internal::AuxillaryParseTableField::enum_aux{"
  1978. "nullptr}},\n");
  1979. } else {
  1980. format(
  1981. "{::$proto_ns$::internal::AuxillaryParseTableField::enum_aux{"
  1982. "$1$_IsValid}},\n",
  1983. ClassName(field->enum_type(), true));
  1984. }
  1985. last_field_number++;
  1986. break;
  1987. case FieldDescriptor::CPPTYPE_MESSAGE: {
  1988. if (field->is_map()) {
  1989. format(
  1990. "{::$proto_ns$::internal::AuxillaryParseTableField::map_"
  1991. "aux{&::$proto_ns$::internal::ParseMap<$1$>}},\n",
  1992. QualifiedClassName(field->message_type(), options_));
  1993. last_field_number++;
  1994. break;
  1995. }
  1996. format.Set("field_classname", ClassName(field->message_type(), false));
  1997. format.Set("default_instance",
  1998. DefaultInstanceName(field->message_type(), options_));
  1999. format(
  2000. "{::$proto_ns$::internal::AuxillaryParseTableField::message_aux{\n"
  2001. " &$default_instance$}},\n");
  2002. last_field_number++;
  2003. break;
  2004. }
  2005. case FieldDescriptor::CPPTYPE_STRING: {
  2006. std::string default_val;
  2007. switch (EffectiveStringCType(field, options_)) {
  2008. case FieldOptions::STRING:
  2009. default_val = field->default_value_string().empty()
  2010. ? "&::" + variables_["proto_ns"] +
  2011. "::internal::fixed_address_empty_string"
  2012. : "&" + QualifiedClassName(descriptor_, options_) +
  2013. "::" + MakeDefaultName(field);
  2014. break;
  2015. case FieldOptions::CORD:
  2016. case FieldOptions::STRING_PIECE:
  2017. default_val =
  2018. "\"" + CEscape(field->default_value_string()) + "\"";
  2019. break;
  2020. }
  2021. format(
  2022. "{::$proto_ns$::internal::AuxillaryParseTableField::string_aux{\n"
  2023. " $1$,\n"
  2024. " \"$2$\"\n"
  2025. "}},\n",
  2026. default_val, field->full_name());
  2027. last_field_number++;
  2028. break;
  2029. }
  2030. default:
  2031. break;
  2032. }
  2033. }
  2034. return last_field_number;
  2035. }
  2036. std::pair<size_t, size_t> MessageGenerator::GenerateOffsets(
  2037. io::Printer* printer) {
  2038. Formatter format(printer, variables_);
  2039. if (HasFieldPresence(descriptor_->file()) || IsMapEntryMessage(descriptor_)) {
  2040. format("PROTOBUF_FIELD_OFFSET($classtype$, _has_bits_),\n");
  2041. } else {
  2042. format("~0u, // no _has_bits_\n");
  2043. }
  2044. format("PROTOBUF_FIELD_OFFSET($classtype$, _internal_metadata_),\n");
  2045. if (descriptor_->extension_range_count() > 0) {
  2046. format("PROTOBUF_FIELD_OFFSET($classtype$, _extensions_),\n");
  2047. } else {
  2048. format("~0u, // no _extensions_\n");
  2049. }
  2050. if (descriptor_->oneof_decl_count() > 0) {
  2051. format("PROTOBUF_FIELD_OFFSET($classtype$, _oneof_case_[0]),\n");
  2052. } else {
  2053. format("~0u, // no _oneof_case_\n");
  2054. }
  2055. if (num_weak_fields_ > 0) {
  2056. format("PROTOBUF_FIELD_OFFSET($classtype$, _weak_field_map_),\n");
  2057. } else {
  2058. format("~0u, // no _weak_field_map_\n");
  2059. }
  2060. const int kNumGenericOffsets = 5; // the number of fixed offsets above
  2061. const size_t offsets = kNumGenericOffsets + descriptor_->field_count() +
  2062. descriptor_->oneof_decl_count();
  2063. size_t entries = offsets;
  2064. for (auto field : FieldRange(descriptor_)) {
  2065. if (field->containing_oneof() || field->options().weak()) {
  2066. format("offsetof($classtype$DefaultTypeInternal, $1$_)",
  2067. FieldName(field));
  2068. } else {
  2069. format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_)", FieldName(field));
  2070. }
  2071. uint32 tag = field_generators_.get(field).CalculateFieldTag();
  2072. if (tag != 0) {
  2073. format(" | $1$", tag);
  2074. }
  2075. format(",\n");
  2076. }
  2077. for (auto oneof : OneOfRange(descriptor_)) {
  2078. format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_),\n", oneof->name());
  2079. }
  2080. if (IsMapEntryMessage(descriptor_)) {
  2081. entries += 2;
  2082. format(
  2083. "0,\n"
  2084. "1,\n");
  2085. } else if (HasFieldPresence(descriptor_->file())) {
  2086. entries += has_bit_indices_.size();
  2087. for (int i = 0; i < has_bit_indices_.size(); i++) {
  2088. const std::string index =
  2089. has_bit_indices_[i] >= 0 ? StrCat(has_bit_indices_[i]) : "~0u";
  2090. format("$1$,\n", index);
  2091. }
  2092. }
  2093. return std::make_pair(entries, offsets);
  2094. }
  2095. void MessageGenerator::GenerateSharedConstructorCode(io::Printer* printer) {
  2096. Formatter format(printer, variables_);
  2097. format("void $classname$::SharedCtor() {\n");
  2098. if (scc_analyzer_
  2099. ->GetSCCAnalysis(scc_analyzer_->GetSCC(descriptor_))
  2100. .constructor_requires_initialization) {
  2101. format(
  2102. " ::$proto_ns$::internal::InitSCC(\n"
  2103. " &scc_info_$scc_name$.base);\n");
  2104. }
  2105. format.Indent();
  2106. std::vector<bool> processed(optimized_order_.size(), false);
  2107. GenerateConstructorBody(printer, processed, false);
  2108. for (auto oneof : OneOfRange(descriptor_)) {
  2109. format("clear_has_$1$();\n", oneof->name());
  2110. }
  2111. format.Outdent();
  2112. format("}\n\n");
  2113. }
  2114. void MessageGenerator::GenerateSharedDestructorCode(io::Printer* printer) {
  2115. Formatter format(printer, variables_);
  2116. format("void $classname$::SharedDtor() {\n");
  2117. format.Indent();
  2118. if (SupportsArenas(descriptor_)) {
  2119. format("$DCHK$(GetArenaNoVirtual() == nullptr);\n");
  2120. }
  2121. // Write the destructors for each field except oneof members.
  2122. // optimized_order_ does not contain oneof fields.
  2123. for (auto field : optimized_order_) {
  2124. field_generators_.get(field).GenerateDestructorCode(printer);
  2125. }
  2126. // Generate code to destruct oneofs. Clearing should do the work.
  2127. for (auto oneof : OneOfRange(descriptor_)) {
  2128. format(
  2129. "if (has_$1$()) {\n"
  2130. " clear_$1$();\n"
  2131. "}\n",
  2132. oneof->name());
  2133. }
  2134. if (num_weak_fields_) {
  2135. format("_weak_field_map_.ClearAll();\n");
  2136. }
  2137. format.Outdent();
  2138. format(
  2139. "}\n"
  2140. "\n");
  2141. }
  2142. void MessageGenerator::GenerateArenaDestructorCode(io::Printer* printer) {
  2143. Formatter format(printer, variables_);
  2144. // Generate the ArenaDtor() method. Track whether any fields actually produced
  2145. // code that needs to be called.
  2146. format("void $classname$::ArenaDtor(void* object) {\n");
  2147. format.Indent();
  2148. // This code is placed inside a static method, rather than an ordinary one,
  2149. // since that simplifies Arena's destructor list (ordinary function pointers
  2150. // rather than member function pointers). _this is the object being
  2151. // destructed.
  2152. format(
  2153. "$classname$* _this = reinterpret_cast< $classname$* >(object);\n"
  2154. // avoid an "unused variable" warning in case no fields have dtor code.
  2155. "(void)_this;\n");
  2156. bool need_registration = false;
  2157. // Process non-oneof fields first.
  2158. for (auto field : optimized_order_) {
  2159. if (field_generators_.get(field).GenerateArenaDestructorCode(printer)) {
  2160. need_registration = true;
  2161. }
  2162. }
  2163. // Process oneof fields.
  2164. //
  2165. // Note: As of 10/5/2016, GenerateArenaDestructorCode does not emit anything
  2166. // and returns false for oneof fields.
  2167. for (auto oneof : OneOfRange(descriptor_)) {
  2168. for (auto field : FieldRange(oneof)) {
  2169. if (field_generators_.get(field).GenerateArenaDestructorCode(printer)) {
  2170. need_registration = true;
  2171. }
  2172. }
  2173. }
  2174. if (num_weak_fields_) {
  2175. // _this is the object being destructed (we are inside a static method
  2176. // here).
  2177. format("_this->_weak_field_map_.ClearAll();\n");
  2178. need_registration = true;
  2179. }
  2180. format.Outdent();
  2181. format("}\n");
  2182. if (need_registration) {
  2183. format(
  2184. "inline void $classname$::RegisterArenaDtor(::$proto_ns$::Arena* "
  2185. "arena) {\n"
  2186. " if (arena != nullptr) {\n"
  2187. " arena->OwnCustomDestructor(this, &$classname$::ArenaDtor);\n"
  2188. " }\n"
  2189. "}\n");
  2190. } else {
  2191. format(
  2192. "void $classname$::RegisterArenaDtor(::$proto_ns$::Arena*) {\n"
  2193. "}\n");
  2194. }
  2195. }
  2196. void MessageGenerator::GenerateConstructorBody(io::Printer* printer,
  2197. std::vector<bool> processed,
  2198. bool copy_constructor) const {
  2199. Formatter format(printer, variables_);
  2200. const FieldDescriptor* last_start = NULL;
  2201. // RunMap maps from fields that start each run to the number of fields in that
  2202. // run. This is optimized for the common case that there are very few runs in
  2203. // a message and that most of the eligible fields appear together.
  2204. typedef std::unordered_map<const FieldDescriptor*, size_t> RunMap;
  2205. RunMap runs;
  2206. for (auto field : optimized_order_) {
  2207. if ((copy_constructor && IsPOD(field)) ||
  2208. (!copy_constructor && CanConstructByZeroing(field, options_))) {
  2209. if (last_start == NULL) {
  2210. last_start = field;
  2211. }
  2212. runs[last_start]++;
  2213. } else {
  2214. last_start = NULL;
  2215. }
  2216. }
  2217. std::string pod_template;
  2218. if (copy_constructor) {
  2219. pod_template =
  2220. "::memcpy(&$first$_, &from.$first$_,\n"
  2221. " static_cast<size_t>(reinterpret_cast<char*>(&$last$_) -\n"
  2222. " reinterpret_cast<char*>(&$first$_)) + sizeof($last$_));\n";
  2223. } else {
  2224. pod_template =
  2225. "::memset(&$first$_, 0, static_cast<size_t>(\n"
  2226. " reinterpret_cast<char*>(&$last$_) -\n"
  2227. " reinterpret_cast<char*>(&$first$_)) + sizeof($last$_));\n";
  2228. }
  2229. for (int i = 0; i < optimized_order_.size(); ++i) {
  2230. if (processed[i]) {
  2231. continue;
  2232. }
  2233. const FieldDescriptor* field = optimized_order_[i];
  2234. RunMap::const_iterator it = runs.find(field);
  2235. // We only apply the memset technique to runs of more than one field, as
  2236. // assignment is better than memset for generated code clarity.
  2237. if (it != runs.end() && it->second > 1) {
  2238. // Use a memset, then skip run_length fields.
  2239. const size_t run_length = it->second;
  2240. const std::string first_field_name = FieldName(field);
  2241. const std::string last_field_name =
  2242. FieldName(optimized_order_[i + run_length - 1]);
  2243. format.Set("first", first_field_name);
  2244. format.Set("last", last_field_name);
  2245. format(pod_template.c_str());
  2246. i += run_length - 1;
  2247. // ++i at the top of the loop.
  2248. } else {
  2249. if (copy_constructor) {
  2250. field_generators_.get(field).GenerateCopyConstructorCode(printer);
  2251. } else {
  2252. field_generators_.get(field).GenerateConstructorCode(printer);
  2253. }
  2254. }
  2255. }
  2256. }
  2257. void MessageGenerator::GenerateStructors(io::Printer* printer) {
  2258. Formatter format(printer, variables_);
  2259. std::string superclass;
  2260. superclass = SuperClassName(descriptor_, options_);
  2261. std::string initializer_with_arena = superclass + "()";
  2262. if (descriptor_->extension_range_count() > 0) {
  2263. initializer_with_arena += ",\n _extensions_(arena)";
  2264. }
  2265. initializer_with_arena += ",\n _internal_metadata_(arena)";
  2266. // Initialize member variables with arena constructor.
  2267. for (auto field : optimized_order_) {
  2268. bool has_arena_constructor = field->is_repeated();
  2269. if (field->containing_oneof() == NULL &&
  2270. (IsLazy(field, options_) || IsStringPiece(field, options_))) {
  2271. has_arena_constructor = true;
  2272. }
  2273. if (has_arena_constructor) {
  2274. initializer_with_arena +=
  2275. std::string(",\n ") + FieldName(field) + std::string("_(arena)");
  2276. }
  2277. }
  2278. if (IsAnyMessage(descriptor_, options_)) {
  2279. initializer_with_arena += ",\n _any_metadata_(&type_url_, &value_)";
  2280. }
  2281. if (num_weak_fields_ > 0) {
  2282. initializer_with_arena += ", _weak_field_map_(arena)";
  2283. }
  2284. std::string initializer_null =
  2285. superclass + "(), _internal_metadata_(nullptr)";
  2286. if (IsAnyMessage(descriptor_, options_)) {
  2287. initializer_null += ", _any_metadata_(&type_url_, &value_)";
  2288. }
  2289. if (num_weak_fields_ > 0) {
  2290. initializer_null += ", _weak_field_map_(nullptr)";
  2291. }
  2292. format(
  2293. "$classname$::$classname$()\n"
  2294. " : $1$ {\n"
  2295. " SharedCtor();\n"
  2296. " // @@protoc_insertion_point(constructor:$full_name$)\n"
  2297. "}\n",
  2298. initializer_null);
  2299. if (SupportsArenas(descriptor_)) {
  2300. format(
  2301. "$classname$::$classname$(::$proto_ns$::Arena* arena)\n"
  2302. " : $1$ {\n"
  2303. " SharedCtor();\n"
  2304. " RegisterArenaDtor(arena);\n"
  2305. " // @@protoc_insertion_point(arena_constructor:$full_name$)\n"
  2306. "}\n",
  2307. initializer_with_arena);
  2308. }
  2309. // Generate the copy constructor.
  2310. if (UsingImplicitWeakFields(descriptor_->file(), options_)) {
  2311. // If we are in lite mode and using implicit weak fields, we generate a
  2312. // one-liner copy constructor that delegates to MergeFrom. This saves some
  2313. // code size and also cuts down on the complexity of implicit weak fields.
  2314. // We might eventually want to do this for all lite protos.
  2315. format(
  2316. "$classname$::$classname$(const $classname$& from)\n"
  2317. " : $classname$() {\n"
  2318. " MergeFrom(from);\n"
  2319. "}\n");
  2320. } else {
  2321. format(
  2322. "$classname$::$classname$(const $classname$& from)\n"
  2323. " : $superclass$()");
  2324. format.Indent();
  2325. format.Indent();
  2326. format.Indent();
  2327. format(",\n_internal_metadata_(nullptr)");
  2328. if (HasFieldPresence(descriptor_->file())) {
  2329. if (!IsProto2MessageSet(descriptor_, options_)) {
  2330. format(",\n_has_bits_(from._has_bits_)");
  2331. }
  2332. }
  2333. std::vector<bool> processed(optimized_order_.size(), false);
  2334. for (int i = 0; i < optimized_order_.size(); i++) {
  2335. auto field = optimized_order_[i];
  2336. if (!(field->is_repeated() && !(field->is_map())) &&
  2337. !IsCord(field, options_)) {
  2338. continue;
  2339. }
  2340. processed[i] = true;
  2341. format(",\n$1$_(from.$1$_)", FieldName(field));
  2342. }
  2343. if (IsAnyMessage(descriptor_, options_)) {
  2344. format(",\n_any_metadata_(&type_url_, &value_)");
  2345. }
  2346. if (num_weak_fields_ > 0) {
  2347. format(",\n_weak_field_map_(from._weak_field_map_)");
  2348. }
  2349. format.Outdent();
  2350. format.Outdent();
  2351. format(" {\n");
  2352. format("_internal_metadata_.MergeFrom(from._internal_metadata_);\n");
  2353. if (descriptor_->extension_range_count() > 0) {
  2354. format("_extensions_.MergeFrom(from._extensions_);\n");
  2355. }
  2356. GenerateConstructorBody(printer, processed, true);
  2357. // Copy oneof fields. Oneof field requires oneof case check.
  2358. for (auto oneof : OneOfRange(descriptor_)) {
  2359. format(
  2360. "clear_has_$1$();\n"
  2361. "switch (from.$1$_case()) {\n",
  2362. oneof->name());
  2363. format.Indent();
  2364. for (auto field : FieldRange(oneof)) {
  2365. format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
  2366. format.Indent();
  2367. field_generators_.get(field).GenerateMergingCode(printer);
  2368. format("break;\n");
  2369. format.Outdent();
  2370. format("}\n");
  2371. }
  2372. format(
  2373. "case $1$_NOT_SET: {\n"
  2374. " break;\n"
  2375. "}\n",
  2376. ToUpper(oneof->name()));
  2377. format.Outdent();
  2378. format("}\n");
  2379. }
  2380. format.Outdent();
  2381. format(
  2382. " // @@protoc_insertion_point(copy_constructor:$full_name$)\n"
  2383. "}\n"
  2384. "\n");
  2385. }
  2386. // Generate the shared constructor code.
  2387. GenerateSharedConstructorCode(printer);
  2388. // Generate the destructor.
  2389. format(
  2390. "$classname$::~$classname$() {\n"
  2391. " // @@protoc_insertion_point(destructor:$full_name$)\n"
  2392. " SharedDtor();\n"
  2393. "}\n"
  2394. "\n");
  2395. // Generate the shared destructor code.
  2396. GenerateSharedDestructorCode(printer);
  2397. // Generate the arena-specific destructor code.
  2398. if (SupportsArenas(descriptor_)) {
  2399. GenerateArenaDestructorCode(printer);
  2400. }
  2401. // Generate SetCachedSize.
  2402. format(
  2403. "void $classname$::SetCachedSize(int size) const {\n"
  2404. " _cached_size_.Set(size);\n"
  2405. "}\n");
  2406. format(
  2407. "const $classname$& $classname$::default_instance() {\n"
  2408. " "
  2409. "::$proto_ns$::internal::InitSCC(&::scc_info_$scc_name$.base)"
  2410. ";\n"
  2411. " return *internal_default_instance();\n"
  2412. "}\n\n");
  2413. }
  2414. void MessageGenerator::GenerateSourceInProto2Namespace(io::Printer* printer) {
  2415. Formatter format(printer, variables_);
  2416. format(
  2417. "template<> "
  2418. "PROTOBUF_NOINLINE "
  2419. "$classtype$* Arena::CreateMaybeMessage< $classtype$ >(Arena* arena) {\n"
  2420. " return Arena::$1$Internal< $classtype$ >(arena);\n"
  2421. "}\n",
  2422. MessageCreateFunction(descriptor_));
  2423. }
  2424. bool MessageGenerator::MaybeGenerateOptionalFieldCondition(
  2425. io::Printer* printer, const FieldDescriptor* field,
  2426. int expected_has_bits_index) {
  2427. Formatter format(printer, variables_);
  2428. int has_bit_index = has_bit_indices_[field->index()];
  2429. if (!field->options().weak() &&
  2430. expected_has_bits_index == has_bit_index / 32) {
  2431. const std::string mask =
  2432. StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
  2433. format("if (cached_has_bits & 0x$1$u) {\n", mask);
  2434. return true;
  2435. }
  2436. return false;
  2437. }
  2438. void MessageGenerator::GenerateClear(io::Printer* printer) {
  2439. Formatter format(printer, variables_);
  2440. // Performance tuning parameters
  2441. const int kMaxUnconditionalPrimitiveBytesClear = 4;
  2442. format(
  2443. "void $classname$::Clear() {\n"
  2444. "// @@protoc_insertion_point(message_clear_start:$full_name$)\n");
  2445. format.Indent();
  2446. format(
  2447. // TODO(jwb): It would be better to avoid emitting this if it is not used,
  2448. // rather than emitting a workaround for the resulting warning.
  2449. "$uint32$ cached_has_bits = 0;\n"
  2450. "// Prevent compiler warnings about cached_has_bits being unused\n"
  2451. "(void) cached_has_bits;\n\n");
  2452. int cached_has_bit_index = -1;
  2453. // Step 1: Extensions
  2454. if (descriptor_->extension_range_count() > 0) {
  2455. format("_extensions_.Clear();\n");
  2456. }
  2457. int unconditional_budget = kMaxUnconditionalPrimitiveBytesClear;
  2458. for (int i = 0; i < optimized_order_.size(); i++) {
  2459. const FieldDescriptor* field = optimized_order_[i];
  2460. if (!CanInitializeByZeroing(field)) {
  2461. continue;
  2462. }
  2463. unconditional_budget -= EstimateAlignmentSize(field);
  2464. }
  2465. std::vector<std::vector<const FieldDescriptor*> > chunks_frag = CollectFields(
  2466. optimized_order_,
  2467. MatchRepeatedAndHasByteAndZeroInits(
  2468. &has_bit_indices_, HasFieldPresence(descriptor_->file())));
  2469. // Merge next non-zero initializable chunk if it has the same has_byte index
  2470. // and not meeting unconditional clear condition.
  2471. std::vector<std::vector<const FieldDescriptor*> > chunks;
  2472. if (!HasFieldPresence(descriptor_->file())) {
  2473. // Don't bother with merging without has_bit field.
  2474. chunks = chunks_frag;
  2475. } else {
  2476. // Note that only the next chunk is considered for merging.
  2477. for (int i = 0; i < chunks_frag.size(); i++) {
  2478. chunks.push_back(chunks_frag[i]);
  2479. const FieldDescriptor* field = chunks_frag[i].front();
  2480. const FieldDescriptor* next_field =
  2481. (i + 1) < chunks_frag.size() ? chunks_frag[i + 1].front() : nullptr;
  2482. if (CanInitializeByZeroing(field) &&
  2483. (chunks_frag[i].size() == 1 || unconditional_budget < 0) &&
  2484. next_field != nullptr &&
  2485. has_bit_indices_[field->index()] / 8 ==
  2486. has_bit_indices_[next_field->index()] / 8) {
  2487. GOOGLE_CHECK(!CanInitializeByZeroing(next_field));
  2488. // Insert next chunk to the current one and skip next chunk.
  2489. chunks.back().insert(chunks.back().end(), chunks_frag[i + 1].begin(),
  2490. chunks_frag[i + 1].end());
  2491. i++;
  2492. }
  2493. }
  2494. }
  2495. ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio,
  2496. HasFieldPresence(descriptor_->file()));
  2497. for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
  2498. std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
  2499. GOOGLE_CHECK(!chunk.empty());
  2500. // Step 2: Repeated fields don't use _has_bits_; emit code to clear them
  2501. // here.
  2502. if (chunk.front()->is_repeated()) {
  2503. for (int i = 0; i < chunk.size(); i++) {
  2504. const FieldDescriptor* field = chunk[i];
  2505. const FieldGenerator& generator = field_generators_.get(field);
  2506. generator.GenerateMessageClearingCode(printer);
  2507. }
  2508. continue;
  2509. }
  2510. cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "", printer);
  2511. // Step 3: Non-repeated fields that can be cleared by memset-to-0, then
  2512. // non-repeated, non-zero initializable fields.
  2513. int last_chunk = HasFieldPresence(descriptor_->file())
  2514. ? has_bit_indices_[chunk.front()->index()] / 8
  2515. : 0;
  2516. int last_chunk_start = 0;
  2517. int memset_run_start = -1;
  2518. int memset_run_end = -1;
  2519. for (int i = 0; i < chunk.size(); i++) {
  2520. const FieldDescriptor* field = chunk[i];
  2521. if (CanInitializeByZeroing(field)) {
  2522. if (memset_run_start == -1) {
  2523. memset_run_start = i;
  2524. }
  2525. memset_run_end = i;
  2526. }
  2527. }
  2528. const bool have_outer_if =
  2529. HasFieldPresence(descriptor_->file()) && chunk.size() > 1 &&
  2530. (memset_run_end != chunk.size() - 1 || unconditional_budget < 0);
  2531. if (have_outer_if) {
  2532. uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
  2533. const int count = popcnt(last_chunk_mask);
  2534. // Check (up to) 8 has_bits at a time if we have more than one field in
  2535. // this chunk. Due to field layout ordering, we may check
  2536. // _has_bits_[last_chunk * 8 / 32] multiple times.
  2537. GOOGLE_DCHECK_LE(2, count);
  2538. GOOGLE_DCHECK_GE(8, count);
  2539. if (cached_has_bit_index != last_chunk / 4) {
  2540. cached_has_bit_index = last_chunk / 4;
  2541. format("cached_has_bits = _has_bits_[$1$];\n", cached_has_bit_index);
  2542. }
  2543. format("if (cached_has_bits & 0x$1$u) {\n",
  2544. StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
  2545. format.Indent();
  2546. }
  2547. if (memset_run_start != -1) {
  2548. if (memset_run_start == memset_run_end) {
  2549. // For clarity, do not memset a single field.
  2550. const FieldGenerator& generator =
  2551. field_generators_.get(chunk[memset_run_start]);
  2552. generator.GenerateMessageClearingCode(printer);
  2553. } else {
  2554. const std::string first_field_name = FieldName(chunk[memset_run_start]);
  2555. const std::string last_field_name = FieldName(chunk[memset_run_end]);
  2556. format(
  2557. "::memset(&$1$_, 0, static_cast<size_t>(\n"
  2558. " reinterpret_cast<char*>(&$2$_) -\n"
  2559. " reinterpret_cast<char*>(&$1$_)) + sizeof($2$_));\n",
  2560. first_field_name, last_field_name);
  2561. }
  2562. // Advance last_chunk_start to skip over the fields we zeroed/memset.
  2563. last_chunk_start = memset_run_end + 1;
  2564. }
  2565. // Go back and emit clears for each of the fields we processed.
  2566. for (int j = last_chunk_start; j < chunk.size(); j++) {
  2567. const FieldDescriptor* field = chunk[j];
  2568. const FieldGenerator& generator = field_generators_.get(field);
  2569. // It's faster to just overwrite primitive types, but we should only
  2570. // clear strings and messages if they were set.
  2571. //
  2572. // TODO(kenton): Let the CppFieldGenerator decide this somehow.
  2573. bool should_check_bit =
  2574. field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
  2575. field->cpp_type() == FieldDescriptor::CPPTYPE_STRING;
  2576. bool have_enclosing_if = false;
  2577. if (should_check_bit &&
  2578. // If no field presence, then always clear strings/messages as well.
  2579. HasFieldPresence(descriptor_->file())) {
  2580. PrintPresenceCheck(format, field, has_bit_indices_, printer,
  2581. &cached_has_bit_index);
  2582. have_enclosing_if = true;
  2583. }
  2584. generator.GenerateMessageClearingCode(printer);
  2585. if (have_enclosing_if) {
  2586. format.Outdent();
  2587. format("}\n");
  2588. }
  2589. }
  2590. if (have_outer_if) {
  2591. format.Outdent();
  2592. format("}\n");
  2593. }
  2594. if (cold_skipper.OnEndChunk(chunk_index, printer)) {
  2595. // Reset here as it may have been updated in just closed if statement.
  2596. cached_has_bit_index = -1;
  2597. }
  2598. }
  2599. // Step 4: Unions.
  2600. for (auto oneof : OneOfRange(descriptor_)) {
  2601. format("clear_$1$();\n", oneof->name());
  2602. }
  2603. if (num_weak_fields_) {
  2604. format("_weak_field_map_.ClearAll();\n");
  2605. }
  2606. if (HasFieldPresence(descriptor_->file())) {
  2607. // Step 5: Everything else.
  2608. format("_has_bits_.Clear();\n");
  2609. }
  2610. format("_internal_metadata_.Clear();\n");
  2611. format.Outdent();
  2612. format("}\n");
  2613. }
  2614. void MessageGenerator::GenerateOneofClear(io::Printer* printer) {
  2615. // Generated function clears the active field and union case (e.g. foo_case_).
  2616. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  2617. auto oneof = descriptor_->oneof_decl(i);
  2618. Formatter format(printer, variables_);
  2619. format.Set("oneofname", oneof->name());
  2620. format(
  2621. "void $classname$::clear_$oneofname$() {\n"
  2622. "// @@protoc_insertion_point(one_of_clear_start:$full_name$)\n");
  2623. format.Indent();
  2624. format("switch ($oneofname$_case()) {\n");
  2625. format.Indent();
  2626. for (auto field : FieldRange(oneof)) {
  2627. format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
  2628. format.Indent();
  2629. // We clear only allocated objects in oneofs
  2630. if (!IsStringOrMessage(field)) {
  2631. format("// No need to clear\n");
  2632. } else {
  2633. field_generators_.get(field).GenerateClearingCode(printer);
  2634. }
  2635. format("break;\n");
  2636. format.Outdent();
  2637. format("}\n");
  2638. }
  2639. format(
  2640. "case $1$_NOT_SET: {\n"
  2641. " break;\n"
  2642. "}\n",
  2643. ToUpper(oneof->name()));
  2644. format.Outdent();
  2645. format(
  2646. "}\n"
  2647. "_oneof_case_[$1$] = $2$_NOT_SET;\n",
  2648. i, ToUpper(oneof->name()));
  2649. format.Outdent();
  2650. format(
  2651. "}\n"
  2652. "\n");
  2653. }
  2654. }
  2655. void MessageGenerator::GenerateSwap(io::Printer* printer) {
  2656. Formatter format(printer, variables_);
  2657. if (SupportsArenas(descriptor_)) {
  2658. // Generate the Swap member function. This is a lightweight wrapper around
  2659. // UnsafeArenaSwap() / MergeFrom() with temporaries, depending on the memory
  2660. // ownership situation: swapping across arenas or between an arena and a
  2661. // heap requires copying.
  2662. format(
  2663. "void $classname$::Swap($classname$* other) {\n"
  2664. " if (other == this) return;\n"
  2665. " if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {\n"
  2666. " InternalSwap(other);\n"
  2667. " } else {\n"
  2668. " $classname$* temp = New(GetArenaNoVirtual());\n"
  2669. " temp->MergeFrom(*other);\n"
  2670. " other->CopyFrom(*this);\n"
  2671. " InternalSwap(temp);\n"
  2672. " if (GetArenaNoVirtual() == nullptr) {\n"
  2673. " delete temp;\n"
  2674. " }\n"
  2675. " }\n"
  2676. "}\n"
  2677. "void $classname$::UnsafeArenaSwap($classname$* other) {\n"
  2678. " if (other == this) return;\n"
  2679. " $DCHK$(GetArenaNoVirtual() == other->GetArenaNoVirtual());\n"
  2680. " InternalSwap(other);\n"
  2681. "}\n");
  2682. } else {
  2683. format(
  2684. "void $classname$::Swap($classname$* other) {\n"
  2685. " if (other == this) return;\n"
  2686. " InternalSwap(other);\n"
  2687. "}\n");
  2688. }
  2689. // Generate the UnsafeArenaSwap member function.
  2690. format("void $classname$::InternalSwap($classname$* other) {\n");
  2691. format.Indent();
  2692. format("using std::swap;\n");
  2693. if (HasGeneratedMethods(descriptor_->file(), options_)) {
  2694. if (descriptor_->extension_range_count() > 0) {
  2695. format("_extensions_.Swap(&other->_extensions_);\n");
  2696. }
  2697. format("_internal_metadata_.Swap(&other->_internal_metadata_);\n");
  2698. if (HasFieldPresence(descriptor_->file())) {
  2699. for (int i = 0; i < HasBitsSize() / 4; ++i) {
  2700. format("swap(_has_bits_[$1$], other->_has_bits_[$1$]);\n", i);
  2701. }
  2702. }
  2703. for (int i = 0; i < optimized_order_.size(); i++) {
  2704. // optimized_order_ does not contain oneof fields, but the field
  2705. // generators for these fields do not emit swapping code on their own.
  2706. const FieldDescriptor* field = optimized_order_[i];
  2707. field_generators_.get(field).GenerateSwappingCode(printer);
  2708. }
  2709. for (auto oneof : OneOfRange(descriptor_)) {
  2710. format("swap($1$_, other->$1$_);\n", oneof->name());
  2711. }
  2712. for (int i = 0; i < descriptor_->oneof_decl_count(); i++) {
  2713. format(
  2714. "swap(_oneof_case_[$1$], other->_oneof_case_[$1$]);\n", i);
  2715. }
  2716. if (num_weak_fields_) {
  2717. format("_weak_field_map_.UnsafeArenaSwap(&other->_weak_field_map_);\n");
  2718. }
  2719. } else {
  2720. format("GetReflection()->Swap(this, other);");
  2721. }
  2722. format.Outdent();
  2723. format("}\n");
  2724. }
  2725. void MessageGenerator::GenerateMergeFrom(io::Printer* printer) {
  2726. Formatter format(printer, variables_);
  2727. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  2728. // Generate the generalized MergeFrom (aka that which takes in the Message
  2729. // base class as a parameter).
  2730. format(
  2731. "void $classname$::MergeFrom(const ::$proto_ns$::Message& from) {\n"
  2732. "// @@protoc_insertion_point(generalized_merge_from_start:"
  2733. "$full_name$)\n"
  2734. " $DCHK$_NE(&from, this);\n");
  2735. format.Indent();
  2736. // Cast the message to the proper type. If we find that the message is
  2737. // *not* of the proper type, we can still call Merge via the reflection
  2738. // system, as the GOOGLE_CHECK above ensured that we have the same descriptor
  2739. // for each message.
  2740. format(
  2741. "const $classname$* source =\n"
  2742. " ::$proto_ns$::DynamicCastToGenerated<$classname$>(\n"
  2743. " &from);\n"
  2744. "if (source == nullptr) {\n"
  2745. "// @@protoc_insertion_point(generalized_merge_from_cast_fail:"
  2746. "$full_name$)\n"
  2747. " ::$proto_ns$::internal::ReflectionOps::Merge(from, this);\n"
  2748. "} else {\n"
  2749. "// @@protoc_insertion_point(generalized_merge_from_cast_success:"
  2750. "$full_name$)\n"
  2751. " MergeFrom(*source);\n"
  2752. "}\n");
  2753. format.Outdent();
  2754. format("}\n\n");
  2755. } else {
  2756. // Generate CheckTypeAndMergeFrom().
  2757. format(
  2758. "void $classname$::CheckTypeAndMergeFrom(\n"
  2759. " const ::$proto_ns$::MessageLite& from) {\n"
  2760. " MergeFrom(*::$proto_ns$::internal::DownCast<const $classname$*>(\n"
  2761. " &from));\n"
  2762. "}\n"
  2763. "\n");
  2764. }
  2765. // Generate the class-specific MergeFrom, which avoids the GOOGLE_CHECK and cast.
  2766. format(
  2767. "void $classname$::MergeFrom(const $classname$& from) {\n"
  2768. "// @@protoc_insertion_point(class_specific_merge_from_start:"
  2769. "$full_name$)\n"
  2770. " $DCHK$_NE(&from, this);\n");
  2771. format.Indent();
  2772. if (descriptor_->extension_range_count() > 0) {
  2773. format("_extensions_.MergeFrom(from._extensions_);\n");
  2774. }
  2775. format(
  2776. "_internal_metadata_.MergeFrom(from._internal_metadata_);\n"
  2777. "$uint32$ cached_has_bits = 0;\n"
  2778. "(void) cached_has_bits;\n\n");
  2779. if (HasFieldPresence(descriptor_->file())) {
  2780. std::vector<std::vector<const FieldDescriptor*>> chunks = CollectFields(
  2781. optimized_order_, MatchRepeatedAndHasByte(&has_bit_indices_, true));
  2782. ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_,
  2783. kColdRatio, true);
  2784. // cached_has_bit_index maintains that:
  2785. // cached_has_bits = from._has_bits_[cached_has_bit_index]
  2786. // for cached_has_bit_index >= 0
  2787. int cached_has_bit_index = -1;
  2788. for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
  2789. const std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
  2790. GOOGLE_CHECK(!chunk.empty());
  2791. // Merge Repeated fields. These fields do not require a
  2792. // check as we can simply iterate over them.
  2793. if (chunk.front()->is_repeated()) {
  2794. for (int i = 0; i < chunk.size(); i++) {
  2795. const FieldDescriptor* field = chunk[i];
  2796. const FieldGenerator& generator = field_generators_.get(field);
  2797. generator.GenerateMergingCode(printer);
  2798. }
  2799. continue;
  2800. }
  2801. // Merge Optional and Required fields (after a _has_bit_ check).
  2802. cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "from.",
  2803. printer);
  2804. int last_chunk = has_bit_indices_[chunk.front()->index()] / 8;
  2805. GOOGLE_DCHECK_NE(-1, last_chunk);
  2806. const bool have_outer_if = chunk.size() > 1;
  2807. if (have_outer_if) {
  2808. uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
  2809. const int count = popcnt(last_chunk_mask);
  2810. // Check (up to) 8 has_bits at a time if we have more than one field in
  2811. // this chunk. Due to field layout ordering, we may check
  2812. // _has_bits_[last_chunk * 8 / 32] multiple times.
  2813. GOOGLE_DCHECK_LE(2, count);
  2814. GOOGLE_DCHECK_GE(8, count);
  2815. if (cached_has_bit_index != last_chunk / 4) {
  2816. cached_has_bit_index = last_chunk / 4;
  2817. format("cached_has_bits = from._has_bits_[$1$];\n",
  2818. cached_has_bit_index);
  2819. }
  2820. format("if (cached_has_bits & 0x$1$u) {\n",
  2821. StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
  2822. format.Indent();
  2823. }
  2824. // Go back and emit merging code for each of the fields we processed.
  2825. bool deferred_has_bit_changes = false;
  2826. for (const auto field : chunk) {
  2827. const FieldGenerator& generator = field_generators_.get(field);
  2828. // Attempt to use the state of cached_has_bits, if possible.
  2829. int has_bit_index = has_bit_indices_[field->index()];
  2830. if (!field->options().weak() &&
  2831. cached_has_bit_index == has_bit_index / 32) {
  2832. const std::string mask = StrCat(
  2833. strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
  2834. format("if (cached_has_bits & 0x$1$u) {\n", mask);
  2835. } else {
  2836. format("if (from.has_$1$()) {\n", FieldName(field));
  2837. }
  2838. format.Indent();
  2839. if (have_outer_if && IsPOD(field)) {
  2840. // GenerateCopyConstructorCode for enum and primitive scalar fields
  2841. // does not do _has_bits_ modifications. We defer _has_bits_
  2842. // manipulation until the end of the outer if.
  2843. //
  2844. // This can reduce the number of loads/stores by up to 7 per 8 fields.
  2845. deferred_has_bit_changes = true;
  2846. generator.GenerateCopyConstructorCode(printer);
  2847. } else {
  2848. generator.GenerateMergingCode(printer);
  2849. }
  2850. format.Outdent();
  2851. format("}\n");
  2852. }
  2853. if (have_outer_if) {
  2854. if (deferred_has_bit_changes) {
  2855. // Flush the has bits for the primitives we deferred.
  2856. GOOGLE_CHECK_LE(0, cached_has_bit_index);
  2857. format("_has_bits_[$1$] |= cached_has_bits;\n", cached_has_bit_index);
  2858. }
  2859. format.Outdent();
  2860. format("}\n");
  2861. }
  2862. if (cold_skipper.OnEndChunk(chunk_index, printer)) {
  2863. // Reset here as it may have been updated in just closed if statement.
  2864. cached_has_bit_index = -1;
  2865. }
  2866. }
  2867. } else {
  2868. // proto3
  2869. for (const auto field : optimized_order_) {
  2870. const FieldGenerator& generator = field_generators_.get(field);
  2871. // Merge semantics without true field presence: primitive fields are
  2872. // merged only if non-zero (numeric) or non-empty (string).
  2873. bool have_enclosing_if =
  2874. EmitFieldNonDefaultCondition(printer, "from.", field);
  2875. generator.GenerateMergingCode(printer);
  2876. if (have_enclosing_if) {
  2877. format.Outdent();
  2878. format("}\n");
  2879. }
  2880. }
  2881. }
  2882. // Merge oneof fields. Oneof field requires oneof case check.
  2883. for (auto oneof : OneOfRange(descriptor_)) {
  2884. format("switch (from.$1$_case()) {\n", oneof->name());
  2885. format.Indent();
  2886. for (auto field : FieldRange(oneof)) {
  2887. format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
  2888. format.Indent();
  2889. field_generators_.get(field).GenerateMergingCode(printer);
  2890. format("break;\n");
  2891. format.Outdent();
  2892. format("}\n");
  2893. }
  2894. format(
  2895. "case $1$_NOT_SET: {\n"
  2896. " break;\n"
  2897. "}\n",
  2898. ToUpper(oneof->name()));
  2899. format.Outdent();
  2900. format("}\n");
  2901. }
  2902. if (num_weak_fields_) {
  2903. format("_weak_field_map_.MergeFrom(from._weak_field_map_);\n");
  2904. }
  2905. format.Outdent();
  2906. format("}\n");
  2907. }
  2908. void MessageGenerator::GenerateCopyFrom(io::Printer* printer) {
  2909. Formatter format(printer, variables_);
  2910. if (HasDescriptorMethods(descriptor_->file(), options_)) {
  2911. // Generate the generalized CopyFrom (aka that which takes in the Message
  2912. // base class as a parameter).
  2913. format(
  2914. "void $classname$::CopyFrom(const ::$proto_ns$::Message& from) {\n"
  2915. "// @@protoc_insertion_point(generalized_copy_from_start:"
  2916. "$full_name$)\n");
  2917. format.Indent();
  2918. format("if (&from == this) return;\n");
  2919. if (!options_.opensource_runtime) {
  2920. // This check is disabled in the opensource release because we're
  2921. // concerned that many users do not define NDEBUG in their release
  2922. // builds.
  2923. format(
  2924. "#ifndef NDEBUG\n"
  2925. "size_t from_size = from.ByteSizeLong();\n"
  2926. "#endif\n"
  2927. "Clear();\n"
  2928. "#ifndef NDEBUG\n"
  2929. "$CHK$_EQ(from_size, from.ByteSizeLong())\n"
  2930. " << \"Source of CopyFrom changed when clearing target. Either \"\n"
  2931. " << \"source is a nested message in target (not allowed), or \"\n"
  2932. " << \"another thread is modifying the source.\";\n"
  2933. "#endif\n");
  2934. } else {
  2935. format("Clear();\n");
  2936. }
  2937. format("MergeFrom(from);\n");
  2938. format.Outdent();
  2939. format("}\n\n");
  2940. }
  2941. // Generate the class-specific CopyFrom.
  2942. format(
  2943. "void $classname$::CopyFrom(const $classname$& from) {\n"
  2944. "// @@protoc_insertion_point(class_specific_copy_from_start:"
  2945. "$full_name$)\n");
  2946. format.Indent();
  2947. format("if (&from == this) return;\n");
  2948. if (!options_.opensource_runtime) {
  2949. // This check is disabled in the opensource release because we're
  2950. // concerned that many users do not define NDEBUG in their release builds.
  2951. format(
  2952. "#ifndef NDEBUG\n"
  2953. "size_t from_size = from.ByteSizeLong();\n"
  2954. "#endif\n"
  2955. "Clear();\n"
  2956. "#ifndef NDEBUG\n"
  2957. "$CHK$_EQ(from_size, from.ByteSizeLong())\n"
  2958. " << \"Source of CopyFrom changed when clearing target. Either \"\n"
  2959. " << \"source is a nested message in target (not allowed), or \"\n"
  2960. " << \"another thread is modifying the source.\";\n"
  2961. "#endif\n");
  2962. } else {
  2963. format("Clear();\n");
  2964. }
  2965. format("MergeFrom(from);\n");
  2966. format.Outdent();
  2967. format("}\n");
  2968. }
  2969. void MessageGenerator::GenerateMergeFromCodedStream(io::Printer* printer) {
  2970. std::map<std::string, std::string> vars = variables_;
  2971. SetUnknkownFieldsVariable(descriptor_, options_, &vars);
  2972. Formatter format(printer, vars);
  2973. if (descriptor_->options().message_set_wire_format()) {
  2974. // Special-case MessageSet.
  2975. format(
  2976. "#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n"
  2977. "const char* $classname$::_InternalParse(const char* ptr,\n"
  2978. " ::$proto_ns$::internal::ParseContext* ctx) {\n"
  2979. " return _extensions_.ParseMessageSet(ptr, \n"
  2980. " internal_default_instance(), &_internal_metadata_, ctx);\n"
  2981. "}\n"
  2982. "#else\n"
  2983. "bool $classname$::MergePartialFromCodedStream(\n"
  2984. " ::$proto_ns$::io::CodedInputStream* input) {\n"
  2985. " return _extensions_.ParseMessageSet(input,\n"
  2986. " internal_default_instance(), $mutable_unknown_fields$);\n"
  2987. "}\n"
  2988. "#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
  2989. return;
  2990. }
  2991. format("#if $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
  2992. GenerateParserLoop(descriptor_, options_, scc_analyzer_, printer);
  2993. format("#else // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
  2994. std::vector<const FieldDescriptor*> ordered_fields =
  2995. SortFieldsByNumber(descriptor_);
  2996. format(
  2997. "bool $classname$::MergePartialFromCodedStream(\n"
  2998. " ::$proto_ns$::io::CodedInputStream* input) {\n");
  2999. if (table_driven_) {
  3000. format.Indent();
  3001. const std::string lite =
  3002. UseUnknownFieldSet(descriptor_->file(), options_) ? "" : "Lite";
  3003. format(
  3004. "return ::$proto_ns$::internal::MergePartialFromCodedStream$1$(\n"
  3005. " this, ::$tablename$::schema[\n"
  3006. " $classname$::kIndexInFileMessages], input);\n",
  3007. lite);
  3008. format.Outdent();
  3009. format("}\n");
  3010. format("#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
  3011. return;
  3012. }
  3013. if (SupportsArenas(descriptor_)) {
  3014. for (auto field : ordered_fields) {
  3015. const FieldGenerator& field_generator = field_generators_.get(field);
  3016. if (field_generator.MergeFromCodedStreamNeedsArena()) {
  3017. format(" ::$proto_ns$::Arena* arena = GetArenaNoVirtual();\n");
  3018. break;
  3019. }
  3020. }
  3021. }
  3022. format(
  3023. "#define DO_(EXPRESSION) if "
  3024. "(!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure\n"
  3025. " $uint32$ tag;\n");
  3026. if (!UseUnknownFieldSet(descriptor_->file(), options_)) {
  3027. format(
  3028. " ::$proto_ns$::internal::LiteUnknownFieldSetter "
  3029. "unknown_fields_setter(\n"
  3030. " &_internal_metadata_);\n"
  3031. " ::$proto_ns$::io::StringOutputStream unknown_fields_output(\n"
  3032. " unknown_fields_setter.buffer());\n"
  3033. " ::$proto_ns$::io::CodedOutputStream unknown_fields_stream(\n"
  3034. " &unknown_fields_output, false);\n");
  3035. }
  3036. format(" // @@protoc_insertion_point(parse_start:$full_name$)\n");
  3037. format.Indent();
  3038. format("for (;;) {\n");
  3039. format.Indent();
  3040. // To calculate the maximum tag to expect, we look at the highest-numbered
  3041. // field. We need to be prepared to handle more than one wire type if that
  3042. // field is a packable repeated field, so to simplify things we assume the
  3043. // highest possible wire type of 5.
  3044. uint32 maxtag =
  3045. ordered_fields.empty() ? 0 : ordered_fields.back()->number() * 8 + 5;
  3046. const int kCutoff0 = 127; // fits in 1-byte varint
  3047. const int kCutoff1 = (127 << 7) + 127; // fits in 2-byte varint
  3048. // We need to capture the last tag when parsing if this is a Group type, as
  3049. // our caller will verify (via CodedInputStream::LastTagWas) that the correct
  3050. // closing tag was received.
  3051. bool capture_last_tag = false;
  3052. const Descriptor* parent = descriptor_->containing_type();
  3053. if (parent) {
  3054. for (auto field : FieldRange(parent)) {
  3055. if (field->type() == FieldDescriptor::TYPE_GROUP &&
  3056. field->message_type() == descriptor_) {
  3057. capture_last_tag = true;
  3058. break;
  3059. }
  3060. }
  3061. for (int i = 0; i < parent->extension_count(); i++) {
  3062. const FieldDescriptor* field = parent->extension(i);
  3063. if (field->type() == FieldDescriptor::TYPE_GROUP &&
  3064. field->message_type() == descriptor_) {
  3065. capture_last_tag = true;
  3066. break;
  3067. }
  3068. }
  3069. }
  3070. for (int i = 0; i < descriptor_->file()->extension_count(); i++) {
  3071. const FieldDescriptor* field = descriptor_->file()->extension(i);
  3072. if (field->type() == FieldDescriptor::TYPE_GROUP &&
  3073. field->message_type() == descriptor_) {
  3074. capture_last_tag = true;
  3075. break;
  3076. }
  3077. }
  3078. format(
  3079. "::std::pair<$uint32$, bool> p = "
  3080. "input->ReadTagWithCutoffNoLastTag($1$u);\n"
  3081. "tag = p.first;\n"
  3082. "if (!p.second) goto handle_unusual;\n",
  3083. maxtag <= kCutoff0 ? kCutoff0 : (maxtag <= kCutoff1 ? kCutoff1 : maxtag));
  3084. if (descriptor_->field_count() > 0) {
  3085. // We don't even want to print the switch() if we have no fields because
  3086. // MSVC dislikes switch() statements that contain only a default value.
  3087. // Note: If we just switched on the tag rather than the field number, we
  3088. // could avoid the need for the if() to check the wire type at the beginning
  3089. // of each case. However, this is actually a bit slower in practice as it
  3090. // creates a jump table that is 8x larger and sparser, and meanwhile the
  3091. // if()s are highly predictable.
  3092. //
  3093. // Historically, we inserted checks to peek at the next tag on the wire and
  3094. // jump directly to the next case statement. While this avoids the jump
  3095. // table that the switch uses, it greatly increases code size (20-60%) and
  3096. // inserts branches that may fail (especially for real world protos that
  3097. // interleave--in field number order--hot and cold fields). Loadtests
  3098. // confirmed that removing this optimization is performance neutral.
  3099. if (num_weak_fields_ > 0) {
  3100. format("uint32 weak_offset;\n");
  3101. }
  3102. format(
  3103. "switch (::$proto_ns$::internal::WireFormatLite::"
  3104. "GetTagFieldNumber(tag)) {\n");
  3105. format.Indent();
  3106. for (auto field : ordered_fields) {
  3107. PrintFieldComment(format, field);
  3108. if (IsWeak(field, options_)) {
  3109. format(
  3110. "case $1$:\n"
  3111. " weak_offset = offsetof($classname$DefaultTypeInternal, $2$_);\n"
  3112. " goto handle_weak_field_map;\n",
  3113. field->number(), FieldName(field));
  3114. continue;
  3115. }
  3116. format("case $1$: {\n", field->number());
  3117. format.Indent();
  3118. const FieldGenerator& field_generator = field_generators_.get(field);
  3119. // Emit code to parse the common, expected case.
  3120. // MSVC is warning about truncating constant in the static_cast so
  3121. // we truncate the tag explicitly.
  3122. format(
  3123. "if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n",
  3124. WireFormat::MakeTag(field));
  3125. format.Indent();
  3126. if (field->is_packed()) {
  3127. field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
  3128. } else {
  3129. field_generator.GenerateMergeFromCodedStream(printer);
  3130. }
  3131. format.Outdent();
  3132. // Emit code to parse unexpectedly packed or unpacked values.
  3133. if (field->is_packed()) {
  3134. internal::WireFormatLite::WireType wiretype =
  3135. WireFormat::WireTypeForFieldType(field->type());
  3136. const uint32 tag =
  3137. internal::WireFormatLite::MakeTag(field->number(), wiretype);
  3138. format(
  3139. "} else if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n",
  3140. tag);
  3141. format.Indent();
  3142. field_generator.GenerateMergeFromCodedStream(printer);
  3143. format.Outdent();
  3144. } else if (field->is_packable() && !field->is_packed()) {
  3145. internal::WireFormatLite::WireType wiretype =
  3146. internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED;
  3147. const uint32 tag =
  3148. internal::WireFormatLite::MakeTag(field->number(), wiretype);
  3149. format(
  3150. "} else if (static_cast< $uint8$>(tag) == ($1$ & 0xFF)) {\n",
  3151. tag);
  3152. format.Indent();
  3153. field_generator.GenerateMergeFromCodedStreamWithPacking(printer);
  3154. format.Outdent();
  3155. }
  3156. format(
  3157. "} else {\n"
  3158. " goto handle_unusual;\n"
  3159. "}\n");
  3160. format("break;\n");
  3161. format.Outdent();
  3162. format("}\n\n");
  3163. }
  3164. if (num_weak_fields_ > 0) {
  3165. format("handle_weak_field_map: {\n");
  3166. format.Indent();
  3167. format(
  3168. "if ((tag & 0x7) != 2) goto handle_unusual;\n"
  3169. "DO_(_weak_field_map_.ReadMessage(input, tag >> 3,\n"
  3170. " &_$classname$_default_instance_, weak_offset));\n");
  3171. format("break;\n");
  3172. format.Outdent();
  3173. format("}\n\n");
  3174. }
  3175. format("default: {\n");
  3176. format.Indent();
  3177. }
  3178. format.Outdent();
  3179. format("handle_unusual:\n");
  3180. format.Indent();
  3181. // If tag is 0 or an end-group tag then this must be the end of the message.
  3182. if (capture_last_tag) {
  3183. format(
  3184. "if (tag == 0 ||\n"
  3185. " ::$proto_ns$::internal::WireFormatLite::GetTagWireType(tag) ==\n"
  3186. " ::$proto_ns$::internal::WireFormatLite::WIRETYPE_END_GROUP) {\n"
  3187. " input->SetLastTag(tag);\n"
  3188. " goto success;\n"
  3189. "}\n");
  3190. } else {
  3191. format(
  3192. "if (tag == 0) {\n"
  3193. " goto success;\n"
  3194. "}\n");
  3195. }
  3196. // Handle extension ranges.
  3197. if (descriptor_->extension_range_count() > 0) {
  3198. format("if (");
  3199. for (int i = 0; i < descriptor_->extension_range_count(); i++) {
  3200. const Descriptor::ExtensionRange* range = descriptor_->extension_range(i);
  3201. if (i > 0) format(" ||\n ");
  3202. uint32 start_tag = WireFormatLite::MakeTag(
  3203. range->start, static_cast<WireFormatLite::WireType>(0));
  3204. uint32 end_tag = WireFormatLite::MakeTag(
  3205. range->end, static_cast<WireFormatLite::WireType>(0));
  3206. if (range->end > FieldDescriptor::kMaxNumber) {
  3207. format("($1$u <= tag)", start_tag);
  3208. } else {
  3209. format("($1$u <= tag && tag < $2$u)", start_tag, end_tag);
  3210. }
  3211. }
  3212. format(") {\n");
  3213. if (UseUnknownFieldSet(descriptor_->file(), options_)) {
  3214. format(
  3215. " DO_(_extensions_.ParseField(tag, input,\n"
  3216. " internal_default_instance(),\n"
  3217. " $mutable_unknown_fields$));\n");
  3218. } else {
  3219. format(
  3220. " DO_(_extensions_.ParseField(tag, input,\n"
  3221. " internal_default_instance(),\n"
  3222. " &unknown_fields_stream));\n");
  3223. }
  3224. format(
  3225. " continue;\n"
  3226. "}\n");
  3227. }
  3228. // We really don't recognize this tag. Skip it.
  3229. if (UseUnknownFieldSet(descriptor_->file(), options_)) {
  3230. format(
  3231. "DO_(::$proto_ns$::internal::WireFormat::SkipField(\n"
  3232. " input, tag, $mutable_unknown_fields$));\n");
  3233. } else {
  3234. format(
  3235. "DO_(::$proto_ns$::internal::WireFormatLite::SkipField(\n"
  3236. " input, tag, &unknown_fields_stream));\n");
  3237. }
  3238. if (descriptor_->field_count() > 0) {
  3239. format("break;\n");
  3240. format.Outdent();
  3241. format("}\n"); // default:
  3242. format.Outdent();
  3243. format("}\n"); // switch
  3244. }
  3245. format.Outdent();
  3246. format.Outdent();
  3247. format(
  3248. " }\n" // for (;;)
  3249. "success:\n"
  3250. " // @@protoc_insertion_point(parse_success:$full_name$)\n"
  3251. " return true;\n"
  3252. "failure:\n"
  3253. " // @@protoc_insertion_point(parse_failure:$full_name$)\n"
  3254. " return false;\n"
  3255. "#undef DO_\n"
  3256. "}\n");
  3257. format("#endif // $GOOGLE_PROTOBUF$_ENABLE_EXPERIMENTAL_PARSER\n");
  3258. }
  3259. void MessageGenerator::GenerateSerializeOneofFields(
  3260. io::Printer* printer, const std::vector<const FieldDescriptor*>& fields,
  3261. bool to_array) {
  3262. Formatter format(printer, variables_);
  3263. GOOGLE_CHECK(!fields.empty());
  3264. if (fields.size() == 1) {
  3265. GenerateSerializeOneField(printer, fields[0], to_array, -1);
  3266. return;
  3267. }
  3268. // We have multiple mutually exclusive choices. Emit a switch statement.
  3269. const OneofDescriptor* oneof = fields[0]->containing_oneof();
  3270. format("switch ($1$_case()) {\n", oneof->name());
  3271. format.Indent();
  3272. for (auto field : fields) {
  3273. format("case k$1$:\n", UnderscoresToCamelCase(field->name(), true));
  3274. format.Indent();
  3275. if (to_array) {
  3276. field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(
  3277. printer);
  3278. } else {
  3279. field_generators_.get(field).GenerateSerializeWithCachedSizes(printer);
  3280. }
  3281. format("break;\n");
  3282. format.Outdent();
  3283. }
  3284. format.Outdent();
  3285. // Doing nothing is an option.
  3286. format(
  3287. " default: ;\n"
  3288. "}\n");
  3289. }
  3290. void MessageGenerator::GenerateSerializeOneField(io::Printer* printer,
  3291. const FieldDescriptor* field,
  3292. bool to_array,
  3293. int cached_has_bits_index) {
  3294. Formatter format(printer, variables_);
  3295. if (!field->options().weak()) {
  3296. // For weakfields, PrintFieldComment is called during iteration.
  3297. PrintFieldComment(format, field);
  3298. }
  3299. bool have_enclosing_if = false;
  3300. if (field->options().weak()) {
  3301. } else if (!field->is_repeated() && HasFieldPresence(descriptor_->file())) {
  3302. // Attempt to use the state of cached_has_bits, if possible.
  3303. int has_bit_index = has_bit_indices_[field->index()];
  3304. if (cached_has_bits_index == has_bit_index / 32) {
  3305. const std::string mask =
  3306. StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
  3307. format("if (cached_has_bits & 0x$1$u) {\n", mask);
  3308. } else {
  3309. format("if (has_$1$()) {\n", FieldName(field));
  3310. }
  3311. format.Indent();
  3312. have_enclosing_if = true;
  3313. } else if (!HasFieldPresence(descriptor_->file())) {
  3314. have_enclosing_if = EmitFieldNonDefaultCondition(printer, "this->", field);
  3315. }
  3316. if (to_array) {
  3317. field_generators_.get(field).GenerateSerializeWithCachedSizesToArray(
  3318. printer);
  3319. } else {
  3320. field_generators_.get(field).GenerateSerializeWithCachedSizes(printer);
  3321. }
  3322. if (have_enclosing_if) {
  3323. format.Outdent();
  3324. format("}\n");
  3325. }
  3326. format("\n");
  3327. }
  3328. void MessageGenerator::GenerateSerializeOneExtensionRange(
  3329. io::Printer* printer, const Descriptor::ExtensionRange* range,
  3330. bool to_array) {
  3331. std::map<std::string, std::string> vars;
  3332. vars["start"] = StrCat(range->start);
  3333. vars["end"] = StrCat(range->end);
  3334. Formatter format(printer, vars);
  3335. format("// Extension range [$start$, $end$)\n");
  3336. if (to_array) {
  3337. format(
  3338. "target = _extensions_.InternalSerializeWithCachedSizesToArray(\n"
  3339. " $start$, $end$, target);\n\n");
  3340. } else {
  3341. format(
  3342. "_extensions_.SerializeWithCachedSizes($start$, $end$, output);\n"
  3343. "\n");
  3344. }
  3345. }
  3346. void MessageGenerator::GenerateSerializeWithCachedSizes(io::Printer* printer) {
  3347. Formatter format(printer, variables_);
  3348. if (descriptor_->options().message_set_wire_format()) {
  3349. // Special-case MessageSet.
  3350. format(
  3351. "void $classname$::SerializeWithCachedSizes(\n"
  3352. " ::$proto_ns$::io::CodedOutputStream* output) const {\n"
  3353. " _extensions_.SerializeMessageSetWithCachedSizes(output);\n");
  3354. std::map<std::string, std::string> vars;
  3355. SetUnknkownFieldsVariable(descriptor_, options_, &vars);
  3356. format.AddMap(vars);
  3357. format(
  3358. " "
  3359. "::$proto_ns$::internal::SerializeUnknownMessageSetItems(\n"
  3360. " $unknown_fields$, output);\n");
  3361. format("}\n");
  3362. return;
  3363. }
  3364. if (options_.table_driven_serialization) return;
  3365. format(
  3366. "void $classname$::SerializeWithCachedSizes(\n"
  3367. " ::$proto_ns$::io::CodedOutputStream* output) const {\n");
  3368. format.Indent();
  3369. format("// @@protoc_insertion_point(serialize_start:$full_name$)\n");
  3370. GenerateSerializeWithCachedSizesBody(printer, false);
  3371. format("// @@protoc_insertion_point(serialize_end:$full_name$)\n");
  3372. format.Outdent();
  3373. format("}\n");
  3374. }
  3375. void MessageGenerator::GenerateSerializeWithCachedSizesToArray(
  3376. io::Printer* printer) {
  3377. Formatter format(printer, variables_);
  3378. if (descriptor_->options().message_set_wire_format()) {
  3379. // Special-case MessageSet.
  3380. format(
  3381. "$uint8$* $classname$::InternalSerializeWithCachedSizesToArray(\n"
  3382. " $uint8$* target) const {\n"
  3383. " target = _extensions_."
  3384. "InternalSerializeMessageSetWithCachedSizesToArray(target);\n");
  3385. GOOGLE_CHECK(UseUnknownFieldSet(descriptor_->file(), options_));
  3386. std::map<std::string, std::string> vars;
  3387. SetUnknkownFieldsVariable(descriptor_, options_, &vars);
  3388. format.AddMap(vars);
  3389. format(
  3390. " target = ::$proto_ns$::internal::WireFormat::\n"
  3391. " SerializeUnknownMessageSetItemsToArray(\n"
  3392. " $unknown_fields$, target);\n");
  3393. format(
  3394. " return target;\n"
  3395. "}\n");
  3396. return;
  3397. }
  3398. format(
  3399. "$uint8$* $classname$::InternalSerializeWithCachedSizesToArray(\n"
  3400. " $uint8$* target) const {\n");
  3401. format.Indent();
  3402. format("// @@protoc_insertion_point(serialize_to_array_start:$full_name$)\n");
  3403. GenerateSerializeWithCachedSizesBody(printer, true);
  3404. format("// @@protoc_insertion_point(serialize_to_array_end:$full_name$)\n");
  3405. format.Outdent();
  3406. format(
  3407. " return target;\n"
  3408. "}\n");
  3409. }
  3410. void MessageGenerator::GenerateSerializeWithCachedSizesBody(
  3411. io::Printer* printer, bool to_array) {
  3412. Formatter format(printer, variables_);
  3413. // If there are multiple fields in a row from the same oneof then we
  3414. // coalesce them and emit a switch statement. This is more efficient
  3415. // because it lets the C++ compiler know this is a "at most one can happen"
  3416. // situation. If we emitted "if (has_x()) ...; if (has_y()) ..." the C++
  3417. // compiler's emitted code might check has_y() even when has_x() is true.
  3418. class LazySerializerEmitter {
  3419. public:
  3420. LazySerializerEmitter(MessageGenerator* mg, io::Printer* printer,
  3421. bool to_array)
  3422. : mg_(mg),
  3423. format_(printer),
  3424. to_array_(to_array),
  3425. eager_(!HasFieldPresence(mg->descriptor_->file())),
  3426. cached_has_bit_index_(-1) {}
  3427. ~LazySerializerEmitter() { Flush(); }
  3428. // If conditions allow, try to accumulate a run of fields from the same
  3429. // oneof, and handle them at the next Flush().
  3430. void Emit(const FieldDescriptor* field) {
  3431. if (eager_ || MustFlush(field)) {
  3432. Flush();
  3433. }
  3434. if (field->containing_oneof() == NULL) {
  3435. // TODO(ckennelly): Defer non-oneof fields similarly to oneof fields.
  3436. if (!field->options().weak() && !field->is_repeated() && !eager_) {
  3437. // We speculatively load the entire _has_bits_[index] contents, even
  3438. // if it is for only one field. Deferring non-oneof emitting would
  3439. // allow us to determine whether this is going to be useful.
  3440. int has_bit_index = mg_->has_bit_indices_[field->index()];
  3441. if (cached_has_bit_index_ != has_bit_index / 32) {
  3442. // Reload.
  3443. int new_index = has_bit_index / 32;
  3444. format_("cached_has_bits = _has_bits_[$1$];\n", new_index);
  3445. cached_has_bit_index_ = new_index;
  3446. }
  3447. }
  3448. mg_->GenerateSerializeOneField(format_.printer(), field, to_array_,
  3449. cached_has_bit_index_);
  3450. } else {
  3451. v_.push_back(field);
  3452. }
  3453. }
  3454. void Flush() {
  3455. if (!v_.empty()) {
  3456. mg_->GenerateSerializeOneofFields(format_.printer(), v_, to_array_);
  3457. v_.clear();
  3458. }
  3459. }
  3460. private:
  3461. // If we have multiple fields in v_ then they all must be from the same
  3462. // oneof. Would adding field to v_ break that invariant?
  3463. bool MustFlush(const FieldDescriptor* field) {
  3464. return !v_.empty() &&
  3465. v_[0]->containing_oneof() != field->containing_oneof();
  3466. }
  3467. MessageGenerator* mg_;
  3468. Formatter format_;
  3469. const bool to_array_;
  3470. const bool eager_;
  3471. std::vector<const FieldDescriptor*> v_;
  3472. // cached_has_bit_index_ maintains that:
  3473. // cached_has_bits = from._has_bits_[cached_has_bit_index_]
  3474. // for cached_has_bit_index_ >= 0
  3475. int cached_has_bit_index_;
  3476. };
  3477. std::vector<const FieldDescriptor*> ordered_fields =
  3478. SortFieldsByNumber(descriptor_);
  3479. std::vector<const Descriptor::ExtensionRange*> sorted_extensions;
  3480. sorted_extensions.reserve(descriptor_->extension_range_count());
  3481. for (int i = 0; i < descriptor_->extension_range_count(); ++i) {
  3482. sorted_extensions.push_back(descriptor_->extension_range(i));
  3483. }
  3484. std::sort(sorted_extensions.begin(), sorted_extensions.end(),
  3485. ExtensionRangeSorter());
  3486. if (num_weak_fields_) {
  3487. format(
  3488. "::$proto_ns$::internal::WeakFieldMap::FieldWriter field_writer("
  3489. "_weak_field_map_);\n");
  3490. }
  3491. format(
  3492. "$uint32$ cached_has_bits = 0;\n"
  3493. "(void) cached_has_bits;\n\n");
  3494. // Merge the fields and the extension ranges, both sorted by field number.
  3495. {
  3496. LazySerializerEmitter e(this, printer, to_array);
  3497. const FieldDescriptor* last_weak_field = nullptr;
  3498. int i, j;
  3499. for (i = 0, j = 0;
  3500. i < ordered_fields.size() || j < sorted_extensions.size();) {
  3501. if ((j == sorted_extensions.size()) ||
  3502. (i < descriptor_->field_count() &&
  3503. ordered_fields[i]->number() < sorted_extensions[j]->start)) {
  3504. const FieldDescriptor* field = ordered_fields[i++];
  3505. if (field->options().weak()) {
  3506. last_weak_field = field;
  3507. PrintFieldComment(format, field);
  3508. } else {
  3509. if (last_weak_field != nullptr) {
  3510. e.Emit(last_weak_field);
  3511. last_weak_field = nullptr;
  3512. }
  3513. e.Emit(field);
  3514. }
  3515. } else {
  3516. if (last_weak_field != nullptr) {
  3517. e.Emit(last_weak_field);
  3518. last_weak_field = nullptr;
  3519. }
  3520. e.Flush();
  3521. GenerateSerializeOneExtensionRange(printer, sorted_extensions[j++],
  3522. to_array);
  3523. }
  3524. }
  3525. if (last_weak_field != nullptr) {
  3526. e.Emit(last_weak_field);
  3527. }
  3528. }
  3529. std::map<std::string, std::string> vars;
  3530. SetUnknkownFieldsVariable(descriptor_, options_, &vars);
  3531. format.AddMap(vars);
  3532. if (UseUnknownFieldSet(descriptor_->file(), options_)) {
  3533. format("if ($have_unknown_fields$) {\n");
  3534. format.Indent();
  3535. if (to_array) {
  3536. format(
  3537. "target = "
  3538. "::$proto_ns$::internal::WireFormat::SerializeUnknownFieldsToArray(\n"
  3539. " $unknown_fields$, target);\n");
  3540. } else {
  3541. format(
  3542. "::$proto_ns$::internal::WireFormat::SerializeUnknownFields(\n"
  3543. " $unknown_fields$, output);\n");
  3544. }
  3545. format.Outdent();
  3546. format("}\n");
  3547. } else {
  3548. format(
  3549. "output->WriteRaw($unknown_fields$.data(),\n"
  3550. " static_cast<int>($unknown_fields$.size()));\n");
  3551. }
  3552. }
  3553. std::vector<uint32> MessageGenerator::RequiredFieldsBitMask() const {
  3554. const int array_size = HasBitsSize();
  3555. std::vector<uint32> masks(array_size, 0);
  3556. for (auto field : FieldRange(descriptor_)) {
  3557. if (!field->is_required()) {
  3558. continue;
  3559. }
  3560. const int has_bit_index = has_bit_indices_[field->index()];
  3561. masks[has_bit_index / 32] |= static_cast<uint32>(1) << (has_bit_index % 32);
  3562. }
  3563. return masks;
  3564. }
  3565. // Create an expression that evaluates to
  3566. // "for all i, (_has_bits_[i] & masks[i]) == masks[i]"
  3567. // masks is allowed to be shorter than _has_bits_, but at least one element of
  3568. // masks must be non-zero.
  3569. static std::string ConditionalToCheckBitmasks(
  3570. const std::vector<uint32>& masks) {
  3571. std::vector<std::string> parts;
  3572. for (int i = 0; i < masks.size(); i++) {
  3573. if (masks[i] == 0) continue;
  3574. std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
  3575. // Each xor evaluates to 0 if the expected bits are present.
  3576. parts.push_back(
  3577. StrCat("((_has_bits_[", i, "] & ", m, ") ^ ", m, ")"));
  3578. }
  3579. GOOGLE_CHECK(!parts.empty());
  3580. // If we have multiple parts, each expected to be 0, then bitwise-or them.
  3581. std::string result =
  3582. parts.size() == 1
  3583. ? parts[0]
  3584. : StrCat("(", Join(parts, "\n | "), ")");
  3585. return result + " == 0";
  3586. }
  3587. void MessageGenerator::GenerateByteSize(io::Printer* printer) {
  3588. Formatter format(printer, variables_);
  3589. if (descriptor_->options().message_set_wire_format()) {
  3590. // Special-case MessageSet.
  3591. std::map<std::string, std::string> vars;
  3592. SetUnknkownFieldsVariable(descriptor_, options_, &vars);
  3593. format.AddMap(vars);
  3594. format(
  3595. "size_t $classname$::ByteSizeLong() const {\n"
  3596. "// @@protoc_insertion_point(message_set_byte_size_start:$full_name$)\n"
  3597. " size_t total_size = _extensions_.MessageSetByteSize();\n"
  3598. " if ($have_unknown_fields$) {\n"
  3599. " total_size += ::$proto_ns$::internal::\n"
  3600. " ComputeUnknownMessageSetItemsSize($unknown_fields$);\n"
  3601. " }\n"
  3602. " int cached_size = "
  3603. "::$proto_ns$::internal::ToCachedSize(total_size);\n"
  3604. " SetCachedSize(cached_size);\n"
  3605. " return total_size;\n"
  3606. "}\n");
  3607. return;
  3608. }
  3609. if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) {
  3610. // Emit a function (rarely used, we hope) that handles the required fields
  3611. // by checking for each one individually.
  3612. format(
  3613. "size_t $classname$::RequiredFieldsByteSizeFallback() const {\n"
  3614. "// @@protoc_insertion_point(required_fields_byte_size_fallback_start:"
  3615. "$full_name$)\n");
  3616. format.Indent();
  3617. format("size_t total_size = 0;\n");
  3618. for (auto field : optimized_order_) {
  3619. if (field->is_required()) {
  3620. format(
  3621. "\n"
  3622. "if (has_$1$()) {\n",
  3623. FieldName(field));
  3624. format.Indent();
  3625. PrintFieldComment(format, field);
  3626. field_generators_.get(field).GenerateByteSize(printer);
  3627. format.Outdent();
  3628. format("}\n");
  3629. }
  3630. }
  3631. format(
  3632. "\n"
  3633. "return total_size;\n");
  3634. format.Outdent();
  3635. format("}\n");
  3636. }
  3637. format(
  3638. "size_t $classname$::ByteSizeLong() const {\n"
  3639. "// @@protoc_insertion_point(message_byte_size_start:$full_name$)\n");
  3640. format.Indent();
  3641. format(
  3642. "size_t total_size = 0;\n"
  3643. "\n");
  3644. if (descriptor_->extension_range_count() > 0) {
  3645. format(
  3646. "total_size += _extensions_.ByteSize();\n"
  3647. "\n");
  3648. }
  3649. std::map<std::string, std::string> vars;
  3650. SetUnknkownFieldsVariable(descriptor_, options_, &vars);
  3651. format.AddMap(vars);
  3652. if (UseUnknownFieldSet(descriptor_->file(), options_)) {
  3653. format(
  3654. "if ($have_unknown_fields$) {\n"
  3655. " total_size +=\n"
  3656. " ::$proto_ns$::internal::WireFormat::ComputeUnknownFieldsSize(\n"
  3657. " $unknown_fields$);\n"
  3658. "}\n");
  3659. } else {
  3660. format(
  3661. "total_size += $unknown_fields$.size();\n"
  3662. "\n");
  3663. }
  3664. // Handle required fields (if any). We expect all of them to be
  3665. // present, so emit one conditional that checks for that. If they are all
  3666. // present then the fast path executes; otherwise the slow path executes.
  3667. if (num_required_fields_ > 1 && HasFieldPresence(descriptor_->file())) {
  3668. // The fast path works if all required fields are present.
  3669. const std::vector<uint32> masks_for_has_bits = RequiredFieldsBitMask();
  3670. format("if ($1$) { // All required fields are present.\n",
  3671. ConditionalToCheckBitmasks(masks_for_has_bits));
  3672. format.Indent();
  3673. // Oneof fields cannot be required, so optimized_order_ contains all of the
  3674. // fields that we need to potentially emit.
  3675. for (auto field : optimized_order_) {
  3676. if (!field->is_required()) continue;
  3677. PrintFieldComment(format, field);
  3678. field_generators_.get(field).GenerateByteSize(printer);
  3679. format("\n");
  3680. }
  3681. format.Outdent();
  3682. format(
  3683. "} else {\n" // the slow path
  3684. " total_size += RequiredFieldsByteSizeFallback();\n"
  3685. "}\n");
  3686. } else {
  3687. // num_required_fields_ <= 1: no need to be tricky
  3688. for (auto field : optimized_order_) {
  3689. if (!field->is_required()) continue;
  3690. PrintFieldComment(format, field);
  3691. format("if (has_$1$()) {\n", FieldName(field));
  3692. format.Indent();
  3693. field_generators_.get(field).GenerateByteSize(printer);
  3694. format.Outdent();
  3695. format("}\n");
  3696. }
  3697. }
  3698. std::vector<std::vector<const FieldDescriptor*> > chunks = CollectFields(
  3699. optimized_order_,
  3700. MatchRepeatedAndHasByteAndRequired(
  3701. &has_bit_indices_, HasFieldPresence(descriptor_->file())));
  3702. // Remove chunks with required fields.
  3703. chunks.erase(std::remove_if(chunks.begin(), chunks.end(), IsRequired),
  3704. chunks.end());
  3705. ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio,
  3706. HasFieldPresence(descriptor_->file()));
  3707. format(
  3708. "$uint32$ cached_has_bits = 0;\n"
  3709. "// Prevent compiler warnings about cached_has_bits being unused\n"
  3710. "(void) cached_has_bits;\n\n");
  3711. int cached_has_bit_index = -1;
  3712. for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) {
  3713. const std::vector<const FieldDescriptor*>& chunk = chunks[chunk_index];
  3714. GOOGLE_CHECK(!chunk.empty());
  3715. // Handle repeated fields.
  3716. if (chunk.front()->is_repeated()) {
  3717. for (int i = 0; i < chunk.size(); i++) {
  3718. const FieldDescriptor* field = chunk[i];
  3719. PrintFieldComment(format, field);
  3720. const FieldGenerator& generator = field_generators_.get(field);
  3721. generator.GenerateByteSize(printer);
  3722. format("\n");
  3723. }
  3724. continue;
  3725. }
  3726. cold_skipper.OnStartChunk(chunk_index, cached_has_bit_index, "", printer);
  3727. // Handle optional (non-repeated/oneof) fields.
  3728. //
  3729. // These are handled in chunks of 8. The first chunk is
  3730. // the non-requireds-non-repeateds-non-unions-non-extensions in
  3731. // descriptor_->field(0), descriptor_->field(1), ... descriptor_->field(7),
  3732. // and the second chunk is the same for
  3733. // descriptor_->field(8), descriptor_->field(9), ...
  3734. // descriptor_->field(15),
  3735. // etc.
  3736. int last_chunk = HasFieldPresence(descriptor_->file())
  3737. ? has_bit_indices_[chunk.front()->index()] / 8
  3738. : 0;
  3739. GOOGLE_DCHECK_NE(-1, last_chunk);
  3740. const bool have_outer_if =
  3741. HasFieldPresence(descriptor_->file()) && chunk.size() > 1;
  3742. if (have_outer_if) {
  3743. uint32 last_chunk_mask = GenChunkMask(chunk, has_bit_indices_);
  3744. const int count = popcnt(last_chunk_mask);
  3745. // Check (up to) 8 has_bits at a time if we have more than one field in
  3746. // this chunk. Due to field layout ordering, we may check
  3747. // _has_bits_[last_chunk * 8 / 32] multiple times.
  3748. GOOGLE_DCHECK_LE(2, count);
  3749. GOOGLE_DCHECK_GE(8, count);
  3750. if (cached_has_bit_index != last_chunk / 4) {
  3751. cached_has_bit_index = last_chunk / 4;
  3752. format("cached_has_bits = _has_bits_[$1$];\n", cached_has_bit_index);
  3753. }
  3754. format("if (cached_has_bits & 0x$1$u) {\n",
  3755. StrCat(strings::Hex(last_chunk_mask, strings::ZERO_PAD_8)));
  3756. format.Indent();
  3757. }
  3758. // Go back and emit checks for each of the fields we processed.
  3759. for (int j = 0; j < chunk.size(); j++) {
  3760. const FieldDescriptor* field = chunk[j];
  3761. const FieldGenerator& generator = field_generators_.get(field);
  3762. PrintFieldComment(format, field);
  3763. bool have_enclosing_if = false;
  3764. if (HasFieldPresence(descriptor_->file())) {
  3765. PrintPresenceCheck(format, field, has_bit_indices_, printer,
  3766. &cached_has_bit_index);
  3767. have_enclosing_if = true;
  3768. } else {
  3769. // Without field presence: field is serialized only if it has a
  3770. // non-default value.
  3771. have_enclosing_if =
  3772. EmitFieldNonDefaultCondition(printer, "this->", field);
  3773. }
  3774. generator.GenerateByteSize(printer);
  3775. if (have_enclosing_if) {
  3776. format.Outdent();
  3777. format(
  3778. "}\n"
  3779. "\n");
  3780. }
  3781. }
  3782. if (have_outer_if) {
  3783. format.Outdent();
  3784. format("}\n");
  3785. }
  3786. if (cold_skipper.OnEndChunk(chunk_index, printer)) {
  3787. // Reset here as it may have been updated in just closed if statement.
  3788. cached_has_bit_index = -1;
  3789. }
  3790. }
  3791. // Fields inside a oneof don't use _has_bits_ so we count them in a separate
  3792. // pass.
  3793. for (auto oneof : OneOfRange(descriptor_)) {
  3794. format("switch ($1$_case()) {\n", oneof->name());
  3795. format.Indent();
  3796. for (auto field : FieldRange(oneof)) {
  3797. PrintFieldComment(format, field);
  3798. format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
  3799. format.Indent();
  3800. field_generators_.get(field).GenerateByteSize(printer);
  3801. format("break;\n");
  3802. format.Outdent();
  3803. format("}\n");
  3804. }
  3805. format(
  3806. "case $1$_NOT_SET: {\n"
  3807. " break;\n"
  3808. "}\n",
  3809. ToUpper(oneof->name()));
  3810. format.Outdent();
  3811. format("}\n");
  3812. }
  3813. if (num_weak_fields_) {
  3814. // TagSize + MessageSize
  3815. format("total_size += _weak_field_map_.ByteSizeLong();\n");
  3816. }
  3817. // We update _cached_size_ even though this is a const method. Because
  3818. // const methods might be called concurrently this needs to be atomic
  3819. // operations or the program is undefined. In practice, since any concurrent
  3820. // writes will be writing the exact same value, normal writes will work on
  3821. // all common processors. We use a dedicated wrapper class to abstract away
  3822. // the underlying atomic. This makes it easier on platforms where even relaxed
  3823. // memory order might have perf impact to replace it with ordinary loads and
  3824. // stores.
  3825. format(
  3826. "int cached_size = ::$proto_ns$::internal::ToCachedSize(total_size);\n"
  3827. "SetCachedSize(cached_size);\n"
  3828. "return total_size;\n");
  3829. format.Outdent();
  3830. format("}\n");
  3831. }
  3832. void MessageGenerator::GenerateIsInitialized(io::Printer* printer) {
  3833. Formatter format(printer, variables_);
  3834. format("bool $classname$::IsInitialized() const {\n");
  3835. format.Indent();
  3836. if (descriptor_->extension_range_count() > 0) {
  3837. format(
  3838. "if (!_extensions_.IsInitialized()) {\n"
  3839. " return false;\n"
  3840. "}\n\n");
  3841. }
  3842. if (HasFieldPresence(descriptor_->file())) {
  3843. // Check that all required fields in this message are set. We can do this
  3844. // most efficiently by checking 32 "has bits" at a time.
  3845. const std::vector<uint32> masks = RequiredFieldsBitMask();
  3846. for (int i = 0; i < masks.size(); i++) {
  3847. uint32 mask = masks[i];
  3848. if (mask == 0) {
  3849. continue;
  3850. }
  3851. // TODO(ckennelly): Consider doing something similar to ByteSizeLong(),
  3852. // where we check all of the required fields in a single branch (assuming
  3853. // that we aren't going to benefit from early termination).
  3854. format("if ((_has_bits_[$1$] & 0x$2$) != 0x$2$) return false;\n",
  3855. i, // 1
  3856. StrCat(strings::Hex(mask, strings::ZERO_PAD_8))); // 2
  3857. }
  3858. }
  3859. // Now check that all non-oneof embedded messages are initialized.
  3860. for (auto field : optimized_order_) {
  3861. // TODO(ckennelly): Push this down into a generator?
  3862. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  3863. !ShouldIgnoreRequiredFieldCheck(field, options_) &&
  3864. scc_analyzer_->HasRequiredFields(field->message_type())) {
  3865. if (field->is_repeated()) {
  3866. if (IsImplicitWeakField(field, options_, scc_analyzer_)) {
  3867. format(
  3868. "if (!::$proto_ns$::internal::AllAreInitializedWeak(this->$1$_))"
  3869. " return false;\n",
  3870. FieldName(field));
  3871. } else {
  3872. format(
  3873. "if (!::$proto_ns$::internal::AllAreInitialized(this->$1$()))"
  3874. " return false;\n",
  3875. FieldName(field));
  3876. }
  3877. } else if (field->options().weak()) {
  3878. continue;
  3879. } else {
  3880. GOOGLE_CHECK(!field->containing_oneof());
  3881. format(
  3882. "if (has_$1$()) {\n"
  3883. " if (!this->$1$_->IsInitialized()) return false;\n"
  3884. "}\n",
  3885. FieldName(field));
  3886. }
  3887. }
  3888. }
  3889. if (num_weak_fields_) {
  3890. // For Weak fields.
  3891. format("if (!_weak_field_map_.IsInitialized()) return false;\n");
  3892. }
  3893. // Go through the oneof fields, emitting a switch if any might have required
  3894. // fields.
  3895. for (auto oneof : OneOfRange(descriptor_)) {
  3896. bool has_required_fields = false;
  3897. for (auto field : FieldRange(oneof)) {
  3898. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  3899. !ShouldIgnoreRequiredFieldCheck(field, options_) &&
  3900. scc_analyzer_->HasRequiredFields(field->message_type())) {
  3901. has_required_fields = true;
  3902. break;
  3903. }
  3904. }
  3905. if (!has_required_fields) {
  3906. continue;
  3907. }
  3908. format("switch ($1$_case()) {\n", oneof->name());
  3909. format.Indent();
  3910. for (auto field : FieldRange(oneof)) {
  3911. format("case k$1$: {\n", UnderscoresToCamelCase(field->name(), true));
  3912. format.Indent();
  3913. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
  3914. !ShouldIgnoreRequiredFieldCheck(field, options_) &&
  3915. scc_analyzer_->HasRequiredFields(field->message_type())) {
  3916. GOOGLE_CHECK(!(field->options().weak() || !field->containing_oneof()));
  3917. if (field->options().weak()) {
  3918. // Just skip.
  3919. } else {
  3920. format(
  3921. "if (has_$1$()) {\n"
  3922. " if (!this->$1$().IsInitialized()) return false;\n"
  3923. "}\n",
  3924. FieldName(field));
  3925. }
  3926. }
  3927. format("break;\n");
  3928. format.Outdent();
  3929. format("}\n");
  3930. }
  3931. format(
  3932. "case $1$_NOT_SET: {\n"
  3933. " break;\n"
  3934. "}\n",
  3935. ToUpper(oneof->name()));
  3936. format.Outdent();
  3937. format("}\n");
  3938. }
  3939. format.Outdent();
  3940. format(
  3941. " return true;\n"
  3942. "}\n");
  3943. }
  3944. } // namespace cpp
  3945. } // namespace compiler
  3946. } // namespace protobuf
  3947. } // namespace google