cpp_message.cc 153 KB

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