descriptor.cc 230 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144
  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/stubs/hash.h>
  34. #include <map>
  35. #include <set>
  36. #include <string>
  37. #include <vector>
  38. #include <algorithm>
  39. #include <limits>
  40. #include <google/protobuf/descriptor.h>
  41. #include <google/protobuf/descriptor_database.h>
  42. #include <google/protobuf/descriptor.pb.h>
  43. #include <google/protobuf/dynamic_message.h>
  44. #include <google/protobuf/generated_message_util.h>
  45. #include <google/protobuf/text_format.h>
  46. #include <google/protobuf/unknown_field_set.h>
  47. #include <google/protobuf/wire_format.h>
  48. #include <google/protobuf/io/strtod.h>
  49. #include <google/protobuf/io/coded_stream.h>
  50. #include <google/protobuf/io/tokenizer.h>
  51. #include <google/protobuf/io/zero_copy_stream_impl.h>
  52. #include <google/protobuf/stubs/common.h>
  53. #include <google/protobuf/stubs/logging.h>
  54. #include <google/protobuf/stubs/mutex.h>
  55. #include <google/protobuf/stubs/once.h>
  56. #include <google/protobuf/stubs/stringprintf.h>
  57. #include <google/protobuf/stubs/strutil.h>
  58. #include <google/protobuf/stubs/substitute.h>
  59. #include <google/protobuf/stubs/map_util.h>
  60. #include <google/protobuf/stubs/stl_util.h>
  61. #undef PACKAGE // autoheader #defines this. :(
  62. namespace google {
  63. namespace protobuf {
  64. const FieldDescriptor::CppType
  65. FieldDescriptor::kTypeToCppTypeMap[MAX_TYPE + 1] = {
  66. static_cast<CppType>(0), // 0 is reserved for errors
  67. CPPTYPE_DOUBLE, // TYPE_DOUBLE
  68. CPPTYPE_FLOAT, // TYPE_FLOAT
  69. CPPTYPE_INT64, // TYPE_INT64
  70. CPPTYPE_UINT64, // TYPE_UINT64
  71. CPPTYPE_INT32, // TYPE_INT32
  72. CPPTYPE_UINT64, // TYPE_FIXED64
  73. CPPTYPE_UINT32, // TYPE_FIXED32
  74. CPPTYPE_BOOL, // TYPE_BOOL
  75. CPPTYPE_STRING, // TYPE_STRING
  76. CPPTYPE_MESSAGE, // TYPE_GROUP
  77. CPPTYPE_MESSAGE, // TYPE_MESSAGE
  78. CPPTYPE_STRING, // TYPE_BYTES
  79. CPPTYPE_UINT32, // TYPE_UINT32
  80. CPPTYPE_ENUM, // TYPE_ENUM
  81. CPPTYPE_INT32, // TYPE_SFIXED32
  82. CPPTYPE_INT64, // TYPE_SFIXED64
  83. CPPTYPE_INT32, // TYPE_SINT32
  84. CPPTYPE_INT64, // TYPE_SINT64
  85. };
  86. const char * const FieldDescriptor::kTypeToName[MAX_TYPE + 1] = {
  87. "ERROR", // 0 is reserved for errors
  88. "double", // TYPE_DOUBLE
  89. "float", // TYPE_FLOAT
  90. "int64", // TYPE_INT64
  91. "uint64", // TYPE_UINT64
  92. "int32", // TYPE_INT32
  93. "fixed64", // TYPE_FIXED64
  94. "fixed32", // TYPE_FIXED32
  95. "bool", // TYPE_BOOL
  96. "string", // TYPE_STRING
  97. "group", // TYPE_GROUP
  98. "message", // TYPE_MESSAGE
  99. "bytes", // TYPE_BYTES
  100. "uint32", // TYPE_UINT32
  101. "enum", // TYPE_ENUM
  102. "sfixed32", // TYPE_SFIXED32
  103. "sfixed64", // TYPE_SFIXED64
  104. "sint32", // TYPE_SINT32
  105. "sint64", // TYPE_SINT64
  106. };
  107. const char * const FieldDescriptor::kCppTypeToName[MAX_CPPTYPE + 1] = {
  108. "ERROR", // 0 is reserved for errors
  109. "int32", // CPPTYPE_INT32
  110. "int64", // CPPTYPE_INT64
  111. "uint32", // CPPTYPE_UINT32
  112. "uint64", // CPPTYPE_UINT64
  113. "double", // CPPTYPE_DOUBLE
  114. "float", // CPPTYPE_FLOAT
  115. "bool", // CPPTYPE_BOOL
  116. "enum", // CPPTYPE_ENUM
  117. "string", // CPPTYPE_STRING
  118. "message", // CPPTYPE_MESSAGE
  119. };
  120. const char * const FieldDescriptor::kLabelToName[MAX_LABEL + 1] = {
  121. "ERROR", // 0 is reserved for errors
  122. "optional", // LABEL_OPTIONAL
  123. "required", // LABEL_REQUIRED
  124. "repeated", // LABEL_REPEATED
  125. };
  126. const char* FileDescriptor::SyntaxName(FileDescriptor::Syntax syntax) {
  127. switch (syntax) {
  128. case SYNTAX_PROTO2:
  129. return "proto2";
  130. case SYNTAX_PROTO3:
  131. return "proto3";
  132. case SYNTAX_UNKNOWN:
  133. return "unknown";
  134. }
  135. GOOGLE_LOG(FATAL) << "can't reach here.";
  136. return NULL;
  137. }
  138. static const char * const kNonLinkedWeakMessageReplacementName = "google.protobuf.Empty";
  139. #ifndef _MSC_VER // MSVC doesn't need these and won't even accept them.
  140. const int FieldDescriptor::kMaxNumber;
  141. const int FieldDescriptor::kFirstReservedNumber;
  142. const int FieldDescriptor::kLastReservedNumber;
  143. #endif
  144. namespace {
  145. string ToCamelCase(const string& input, bool lower_first) {
  146. bool capitalize_next = !lower_first;
  147. string result;
  148. result.reserve(input.size());
  149. for (int i = 0; i < input.size(); i++) {
  150. if (input[i] == '_') {
  151. capitalize_next = true;
  152. } else if (capitalize_next) {
  153. // Note: I distrust ctype.h due to locales.
  154. if ('a' <= input[i] && input[i] <= 'z') {
  155. result.push_back(input[i] - 'a' + 'A');
  156. } else {
  157. result.push_back(input[i]);
  158. }
  159. capitalize_next = false;
  160. } else {
  161. result.push_back(input[i]);
  162. }
  163. }
  164. // Lower-case the first letter.
  165. if (lower_first && !result.empty() && 'A' <= result[0] && result[0] <= 'Z') {
  166. result[0] = result[0] - 'A' + 'a';
  167. }
  168. return result;
  169. }
  170. // A DescriptorPool contains a bunch of hash_maps to implement the
  171. // various Find*By*() methods. Since hashtable lookups are O(1), it's
  172. // most efficient to construct a fixed set of large hash_maps used by
  173. // all objects in the pool rather than construct one or more small
  174. // hash_maps for each object.
  175. //
  176. // The keys to these hash_maps are (parent, name) or (parent, number)
  177. // pairs. Unfortunately STL doesn't provide hash functions for pair<>,
  178. // so we must invent our own.
  179. //
  180. // TODO(kenton): Use StringPiece rather than const char* in keys? It would
  181. // be a lot cleaner but we'd just have to convert it back to const char*
  182. // for the open source release.
  183. typedef pair<const void*, const char*> PointerStringPair;
  184. struct PointerStringPairEqual {
  185. inline bool operator()(const PointerStringPair& a,
  186. const PointerStringPair& b) const {
  187. return a.first == b.first && strcmp(a.second, b.second) == 0;
  188. }
  189. };
  190. template<typename PairType>
  191. struct PointerIntegerPairHash {
  192. size_t operator()(const PairType& p) const {
  193. // FIXME(kenton): What is the best way to compute this hash? I have
  194. // no idea! This seems a bit better than an XOR.
  195. return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) + p.second;
  196. }
  197. #ifdef _MSC_VER
  198. // Used only by MSVC and platforms where hash_map is not available.
  199. static const size_t bucket_size = 4;
  200. static const size_t min_buckets = 8;
  201. #endif
  202. inline bool operator()(const PairType& a, const PairType& b) const {
  203. return a.first < b.first ||
  204. (a.first == b.first && a.second < b.second);
  205. }
  206. };
  207. typedef pair<const Descriptor*, int> DescriptorIntPair;
  208. typedef pair<const EnumDescriptor*, int> EnumIntPair;
  209. struct PointerStringPairHash {
  210. size_t operator()(const PointerStringPair& p) const {
  211. // FIXME(kenton): What is the best way to compute this hash? I have
  212. // no idea! This seems a bit better than an XOR.
  213. hash<const char*> cstring_hash;
  214. return reinterpret_cast<intptr_t>(p.first) * ((1 << 16) - 1) +
  215. cstring_hash(p.second);
  216. }
  217. #ifdef _MSC_VER
  218. // Used only by MSVC and platforms where hash_map is not available.
  219. static const size_t bucket_size = 4;
  220. static const size_t min_buckets = 8;
  221. #endif
  222. inline bool operator()(const PointerStringPair& a,
  223. const PointerStringPair& b) const {
  224. if (a.first < b.first) return true;
  225. if (a.first > b.first) return false;
  226. return strcmp(a.second, b.second) < 0;
  227. }
  228. };
  229. struct Symbol {
  230. enum Type {
  231. NULL_SYMBOL, MESSAGE, FIELD, ONEOF, ENUM, ENUM_VALUE, SERVICE, METHOD,
  232. PACKAGE
  233. };
  234. Type type;
  235. union {
  236. const Descriptor* descriptor;
  237. const FieldDescriptor* field_descriptor;
  238. const OneofDescriptor* oneof_descriptor;
  239. const EnumDescriptor* enum_descriptor;
  240. const EnumValueDescriptor* enum_value_descriptor;
  241. const ServiceDescriptor* service_descriptor;
  242. const MethodDescriptor* method_descriptor;
  243. const FileDescriptor* package_file_descriptor;
  244. };
  245. inline Symbol() : type(NULL_SYMBOL) { descriptor = NULL; }
  246. inline bool IsNull() const { return type == NULL_SYMBOL; }
  247. inline bool IsType() const {
  248. return type == MESSAGE || type == ENUM;
  249. }
  250. inline bool IsAggregate() const {
  251. return type == MESSAGE || type == PACKAGE
  252. || type == ENUM || type == SERVICE;
  253. }
  254. #define CONSTRUCTOR(TYPE, TYPE_CONSTANT, FIELD) \
  255. inline explicit Symbol(const TYPE* value) { \
  256. type = TYPE_CONSTANT; \
  257. this->FIELD = value; \
  258. }
  259. CONSTRUCTOR(Descriptor , MESSAGE , descriptor )
  260. CONSTRUCTOR(FieldDescriptor , FIELD , field_descriptor )
  261. CONSTRUCTOR(OneofDescriptor , ONEOF , oneof_descriptor )
  262. CONSTRUCTOR(EnumDescriptor , ENUM , enum_descriptor )
  263. CONSTRUCTOR(EnumValueDescriptor, ENUM_VALUE, enum_value_descriptor )
  264. CONSTRUCTOR(ServiceDescriptor , SERVICE , service_descriptor )
  265. CONSTRUCTOR(MethodDescriptor , METHOD , method_descriptor )
  266. CONSTRUCTOR(FileDescriptor , PACKAGE , package_file_descriptor)
  267. #undef CONSTRUCTOR
  268. const FileDescriptor* GetFile() const {
  269. switch (type) {
  270. case NULL_SYMBOL: return NULL;
  271. case MESSAGE : return descriptor ->file();
  272. case FIELD : return field_descriptor ->file();
  273. case ONEOF : return oneof_descriptor ->containing_type()->file();
  274. case ENUM : return enum_descriptor ->file();
  275. case ENUM_VALUE : return enum_value_descriptor->type()->file();
  276. case SERVICE : return service_descriptor ->file();
  277. case METHOD : return method_descriptor ->service()->file();
  278. case PACKAGE : return package_file_descriptor;
  279. }
  280. return NULL;
  281. }
  282. };
  283. const Symbol kNullSymbol;
  284. typedef hash_map<const char*, Symbol,
  285. hash<const char*>, streq>
  286. SymbolsByNameMap;
  287. typedef hash_map<PointerStringPair, Symbol,
  288. PointerStringPairHash, PointerStringPairEqual>
  289. SymbolsByParentMap;
  290. typedef hash_map<const char*, const FileDescriptor*,
  291. hash<const char*>, streq>
  292. FilesByNameMap;
  293. typedef hash_map<PointerStringPair, const FieldDescriptor*,
  294. PointerStringPairHash, PointerStringPairEqual>
  295. FieldsByNameMap;
  296. typedef hash_map<DescriptorIntPair, const FieldDescriptor*,
  297. PointerIntegerPairHash<DescriptorIntPair> >
  298. FieldsByNumberMap;
  299. typedef hash_map<EnumIntPair, const EnumValueDescriptor*,
  300. PointerIntegerPairHash<EnumIntPair> >
  301. EnumValuesByNumberMap;
  302. // This is a map rather than a hash_map, since we use it to iterate
  303. // through all the extensions that extend a given Descriptor, and an
  304. // ordered data structure that implements lower_bound is convenient
  305. // for that.
  306. typedef map<DescriptorIntPair, const FieldDescriptor*>
  307. ExtensionsGroupedByDescriptorMap;
  308. typedef hash_map<string, const SourceCodeInfo_Location*> LocationsByPathMap;
  309. set<string>* allowed_proto3_extendees_ = NULL;
  310. GOOGLE_PROTOBUF_DECLARE_ONCE(allowed_proto3_extendees_init_);
  311. void DeleteAllowedProto3Extendee() {
  312. delete allowed_proto3_extendees_;
  313. }
  314. void InitAllowedProto3Extendee() {
  315. allowed_proto3_extendees_ = new set<string>;
  316. allowed_proto3_extendees_->insert("google.protobuf.FileOptions");
  317. allowed_proto3_extendees_->insert("google.protobuf.MessageOptions");
  318. allowed_proto3_extendees_->insert("google.protobuf.FieldOptions");
  319. allowed_proto3_extendees_->insert("google.protobuf.EnumOptions");
  320. allowed_proto3_extendees_->insert("google.protobuf.EnumValueOptions");
  321. allowed_proto3_extendees_->insert("google.protobuf.ServiceOptions");
  322. allowed_proto3_extendees_->insert("google.protobuf.MethodOptions");
  323. google::protobuf::internal::OnShutdown(&DeleteAllowedProto3Extendee);
  324. }
  325. // Checks whether the extendee type is allowed in proto3.
  326. // Only extensions to descriptor options are allowed. We use name comparison
  327. // instead of comparing the descriptor directly because the extensions may be
  328. // defined in a different pool.
  329. bool AllowedExtendeeInProto3(const string& name) {
  330. ::google::protobuf::GoogleOnceInit(&allowed_proto3_extendees_init_, &InitAllowedProto3Extendee);
  331. return allowed_proto3_extendees_->find(name) !=
  332. allowed_proto3_extendees_->end();
  333. }
  334. } // anonymous namespace
  335. // ===================================================================
  336. // DescriptorPool::Tables
  337. class DescriptorPool::Tables {
  338. public:
  339. Tables();
  340. ~Tables();
  341. // Record the current state of the tables to the stack of checkpoints.
  342. // Each call to AddCheckpoint() must be paired with exactly one call to either
  343. // ClearLastCheckpoint() or RollbackToLastCheckpoint().
  344. //
  345. // This is used when building files, since some kinds of validation errors
  346. // cannot be detected until the file's descriptors have already been added to
  347. // the tables.
  348. //
  349. // This supports recursive checkpoints, since building a file may trigger
  350. // recursive building of other files. Note that recursive checkpoints are not
  351. // normally necessary; explicit dependencies are built prior to checkpointing.
  352. // So although we recursively build transitive imports, there is at most one
  353. // checkpoint in the stack during dependency building.
  354. //
  355. // Recursive checkpoints only arise during cross-linking of the descriptors.
  356. // Symbol references must be resolved, via DescriptorBuilder::FindSymbol and
  357. // friends. If the pending file references an unknown symbol
  358. // (e.g., it is not defined in the pending file's explicit dependencies), and
  359. // the pool is using a fallback database, and that database contains a file
  360. // defining that symbol, and that file has not yet been built by the pool,
  361. // the pool builds the file during cross-linking, leading to another
  362. // checkpoint.
  363. void AddCheckpoint();
  364. // Mark the last checkpoint as having cleared successfully, removing it from
  365. // the stack. If the stack is empty, all pending symbols will be committed.
  366. //
  367. // Note that this does not guarantee that the symbols added since the last
  368. // checkpoint won't be rolled back: if a checkpoint gets rolled back,
  369. // everything past that point gets rolled back, including symbols added after
  370. // checkpoints that were pushed onto the stack after it and marked as cleared.
  371. void ClearLastCheckpoint();
  372. // Roll back the Tables to the state of the checkpoint at the top of the
  373. // stack, removing everything that was added after that point.
  374. void RollbackToLastCheckpoint();
  375. // The stack of files which are currently being built. Used to detect
  376. // cyclic dependencies when loading files from a DescriptorDatabase. Not
  377. // used when fallback_database_ == NULL.
  378. vector<string> pending_files_;
  379. // A set of files which we have tried to load from the fallback database
  380. // and encountered errors. We will not attempt to load them again during
  381. // execution of the current public API call, but for compatibility with
  382. // legacy clients, this is cleared at the beginning of each public API call.
  383. // Not used when fallback_database_ == NULL.
  384. hash_set<string> known_bad_files_;
  385. // A set of symbols which we have tried to load from the fallback database
  386. // and encountered errors. We will not attempt to load them again during
  387. // execution of the current public API call, but for compatibility with
  388. // legacy clients, this is cleared at the beginning of each public API call.
  389. hash_set<string> known_bad_symbols_;
  390. // The set of descriptors for which we've already loaded the full
  391. // set of extensions numbers from fallback_database_.
  392. hash_set<const Descriptor*> extensions_loaded_from_db_;
  393. // -----------------------------------------------------------------
  394. // Finding items.
  395. // Find symbols. This returns a null Symbol (symbol.IsNull() is true)
  396. // if not found.
  397. inline Symbol FindSymbol(const string& key) const;
  398. // This implements the body of DescriptorPool::Find*ByName(). It should
  399. // really be a private method of DescriptorPool, but that would require
  400. // declaring Symbol in descriptor.h, which would drag all kinds of other
  401. // stuff into the header. Yay C++.
  402. Symbol FindByNameHelper(
  403. const DescriptorPool* pool, const string& name);
  404. // These return NULL if not found.
  405. inline const FileDescriptor* FindFile(const string& key) const;
  406. inline const FieldDescriptor* FindExtension(const Descriptor* extendee,
  407. int number);
  408. inline void FindAllExtensions(const Descriptor* extendee,
  409. vector<const FieldDescriptor*>* out) const;
  410. // -----------------------------------------------------------------
  411. // Adding items.
  412. // These add items to the corresponding tables. They return false if
  413. // the key already exists in the table. For AddSymbol(), the string passed
  414. // in must be one that was constructed using AllocateString(), as it will
  415. // be used as a key in the symbols_by_name_ map without copying.
  416. bool AddSymbol(const string& full_name, Symbol symbol);
  417. bool AddFile(const FileDescriptor* file);
  418. bool AddExtension(const FieldDescriptor* field);
  419. // -----------------------------------------------------------------
  420. // Allocating memory.
  421. // Allocate an object which will be reclaimed when the pool is
  422. // destroyed. Note that the object's destructor will never be called,
  423. // so its fields must be plain old data (primitive data types and
  424. // pointers). All of the descriptor types are such objects.
  425. template<typename Type> Type* Allocate();
  426. // Allocate an array of objects which will be reclaimed when the
  427. // pool in destroyed. Again, destructors are never called.
  428. template<typename Type> Type* AllocateArray(int count);
  429. // Allocate a string which will be destroyed when the pool is destroyed.
  430. // The string is initialized to the given value for convenience.
  431. string* AllocateString(const string& value);
  432. // Allocate a protocol message object. Some older versions of GCC have
  433. // trouble understanding explicit template instantiations in some cases, so
  434. // in those cases we have to pass a dummy pointer of the right type as the
  435. // parameter instead of specifying the type explicitly.
  436. template<typename Type> Type* AllocateMessage(Type* dummy = NULL);
  437. // Allocate a FileDescriptorTables object.
  438. FileDescriptorTables* AllocateFileTables();
  439. private:
  440. vector<string*> strings_; // All strings in the pool.
  441. vector<Message*> messages_; // All messages in the pool.
  442. vector<FileDescriptorTables*> file_tables_; // All file tables in the pool.
  443. vector<void*> allocations_; // All other memory allocated in the pool.
  444. SymbolsByNameMap symbols_by_name_;
  445. FilesByNameMap files_by_name_;
  446. ExtensionsGroupedByDescriptorMap extensions_;
  447. struct CheckPoint {
  448. explicit CheckPoint(const Tables* tables)
  449. : strings_before_checkpoint(tables->strings_.size()),
  450. messages_before_checkpoint(tables->messages_.size()),
  451. file_tables_before_checkpoint(tables->file_tables_.size()),
  452. allocations_before_checkpoint(tables->allocations_.size()),
  453. pending_symbols_before_checkpoint(
  454. tables->symbols_after_checkpoint_.size()),
  455. pending_files_before_checkpoint(
  456. tables->files_after_checkpoint_.size()),
  457. pending_extensions_before_checkpoint(
  458. tables->extensions_after_checkpoint_.size()) {
  459. }
  460. int strings_before_checkpoint;
  461. int messages_before_checkpoint;
  462. int file_tables_before_checkpoint;
  463. int allocations_before_checkpoint;
  464. int pending_symbols_before_checkpoint;
  465. int pending_files_before_checkpoint;
  466. int pending_extensions_before_checkpoint;
  467. };
  468. vector<CheckPoint> checkpoints_;
  469. vector<const char* > symbols_after_checkpoint_;
  470. vector<const char* > files_after_checkpoint_;
  471. vector<DescriptorIntPair> extensions_after_checkpoint_;
  472. // Allocate some bytes which will be reclaimed when the pool is
  473. // destroyed.
  474. void* AllocateBytes(int size);
  475. };
  476. // Contains tables specific to a particular file. These tables are not
  477. // modified once the file has been constructed, so they need not be
  478. // protected by a mutex. This makes operations that depend only on the
  479. // contents of a single file -- e.g. Descriptor::FindFieldByName() --
  480. // lock-free.
  481. //
  482. // For historical reasons, the definitions of the methods of
  483. // FileDescriptorTables and DescriptorPool::Tables are interleaved below.
  484. // These used to be a single class.
  485. class FileDescriptorTables {
  486. public:
  487. FileDescriptorTables();
  488. ~FileDescriptorTables();
  489. // Empty table, used with placeholder files.
  490. static const FileDescriptorTables kEmpty;
  491. // -----------------------------------------------------------------
  492. // Finding items.
  493. // Find symbols. These return a null Symbol (symbol.IsNull() is true)
  494. // if not found.
  495. inline Symbol FindNestedSymbol(const void* parent,
  496. const string& name) const;
  497. inline Symbol FindNestedSymbolOfType(const void* parent,
  498. const string& name,
  499. const Symbol::Type type) const;
  500. // These return NULL if not found.
  501. inline const FieldDescriptor* FindFieldByNumber(
  502. const Descriptor* parent, int number) const;
  503. inline const FieldDescriptor* FindFieldByLowercaseName(
  504. const void* parent, const string& lowercase_name) const;
  505. inline const FieldDescriptor* FindFieldByCamelcaseName(
  506. const void* parent, const string& camelcase_name) const;
  507. inline const EnumValueDescriptor* FindEnumValueByNumber(
  508. const EnumDescriptor* parent, int number) const;
  509. // This creates a new EnumValueDescriptor if not found, in a thread-safe way.
  510. inline const EnumValueDescriptor* FindEnumValueByNumberCreatingIfUnknown(
  511. const EnumDescriptor* parent, int number) const;
  512. // -----------------------------------------------------------------
  513. // Adding items.
  514. // These add items to the corresponding tables. They return false if
  515. // the key already exists in the table. For AddAliasUnderParent(), the
  516. // string passed in must be one that was constructed using AllocateString(),
  517. // as it will be used as a key in the symbols_by_parent_ map without copying.
  518. bool AddAliasUnderParent(const void* parent, const string& name,
  519. Symbol symbol);
  520. bool AddFieldByNumber(const FieldDescriptor* field);
  521. bool AddEnumValueByNumber(const EnumValueDescriptor* value);
  522. // Adds the field to the lowercase_name and camelcase_name maps. Never
  523. // fails because we allow duplicates; the first field by the name wins.
  524. void AddFieldByStylizedNames(const FieldDescriptor* field);
  525. // Populates p->first->locations_by_path_ from p->second.
  526. // Unusual signature dictated by GoogleOnceDynamic.
  527. static void BuildLocationsByPath(
  528. pair<const FileDescriptorTables*, const SourceCodeInfo*>* p);
  529. // Returns the location denoted by the specified path through info,
  530. // or NULL if not found.
  531. // The value of info must be that of the corresponding FileDescriptor.
  532. // (Conceptually a pure function, but stateful as an optimisation.)
  533. const SourceCodeInfo_Location* GetSourceLocation(
  534. const vector<int>& path, const SourceCodeInfo* info) const;
  535. private:
  536. SymbolsByParentMap symbols_by_parent_;
  537. FieldsByNameMap fields_by_lowercase_name_;
  538. FieldsByNameMap fields_by_camelcase_name_;
  539. FieldsByNumberMap fields_by_number_; // Not including extensions.
  540. EnumValuesByNumberMap enum_values_by_number_;
  541. mutable EnumValuesByNumberMap unknown_enum_values_by_number_
  542. GOOGLE_GUARDED_BY(unknown_enum_values_mu_);
  543. // Populated on first request to save space, hence constness games.
  544. mutable GoogleOnceDynamic locations_by_path_once_;
  545. mutable LocationsByPathMap locations_by_path_;
  546. // Mutex to protect the unknown-enum-value map due to dynamic
  547. // EnumValueDescriptor creation on unknown values.
  548. mutable Mutex unknown_enum_values_mu_;
  549. };
  550. DescriptorPool::Tables::Tables()
  551. // Start some hash_map and hash_set objects with a small # of buckets
  552. : known_bad_files_(3),
  553. known_bad_symbols_(3),
  554. extensions_loaded_from_db_(3),
  555. symbols_by_name_(3),
  556. files_by_name_(3) {}
  557. DescriptorPool::Tables::~Tables() {
  558. GOOGLE_DCHECK(checkpoints_.empty());
  559. // Note that the deletion order is important, since the destructors of some
  560. // messages may refer to objects in allocations_.
  561. STLDeleteElements(&messages_);
  562. for (int i = 0; i < allocations_.size(); i++) {
  563. operator delete(allocations_[i]);
  564. }
  565. STLDeleteElements(&strings_);
  566. STLDeleteElements(&file_tables_);
  567. }
  568. FileDescriptorTables::FileDescriptorTables()
  569. // Initialize all the hash tables to start out with a small # of buckets
  570. : symbols_by_parent_(3),
  571. fields_by_lowercase_name_(3),
  572. fields_by_camelcase_name_(3),
  573. fields_by_number_(3),
  574. enum_values_by_number_(3),
  575. unknown_enum_values_by_number_(3) {
  576. }
  577. FileDescriptorTables::~FileDescriptorTables() {}
  578. const FileDescriptorTables FileDescriptorTables::kEmpty;
  579. void DescriptorPool::Tables::AddCheckpoint() {
  580. checkpoints_.push_back(CheckPoint(this));
  581. }
  582. void DescriptorPool::Tables::ClearLastCheckpoint() {
  583. GOOGLE_DCHECK(!checkpoints_.empty());
  584. checkpoints_.pop_back();
  585. if (checkpoints_.empty()) {
  586. // All checkpoints have been cleared: we can now commit all of the pending
  587. // data.
  588. symbols_after_checkpoint_.clear();
  589. files_after_checkpoint_.clear();
  590. extensions_after_checkpoint_.clear();
  591. }
  592. }
  593. void DescriptorPool::Tables::RollbackToLastCheckpoint() {
  594. GOOGLE_DCHECK(!checkpoints_.empty());
  595. const CheckPoint& checkpoint = checkpoints_.back();
  596. for (int i = checkpoint.pending_symbols_before_checkpoint;
  597. i < symbols_after_checkpoint_.size();
  598. i++) {
  599. symbols_by_name_.erase(symbols_after_checkpoint_[i]);
  600. }
  601. for (int i = checkpoint.pending_files_before_checkpoint;
  602. i < files_after_checkpoint_.size();
  603. i++) {
  604. files_by_name_.erase(files_after_checkpoint_[i]);
  605. }
  606. for (int i = checkpoint.pending_extensions_before_checkpoint;
  607. i < extensions_after_checkpoint_.size();
  608. i++) {
  609. extensions_.erase(extensions_after_checkpoint_[i]);
  610. }
  611. symbols_after_checkpoint_.resize(
  612. checkpoint.pending_symbols_before_checkpoint);
  613. files_after_checkpoint_.resize(checkpoint.pending_files_before_checkpoint);
  614. extensions_after_checkpoint_.resize(
  615. checkpoint.pending_extensions_before_checkpoint);
  616. STLDeleteContainerPointers(
  617. strings_.begin() + checkpoint.strings_before_checkpoint, strings_.end());
  618. STLDeleteContainerPointers(
  619. messages_.begin() + checkpoint.messages_before_checkpoint,
  620. messages_.end());
  621. STLDeleteContainerPointers(
  622. file_tables_.begin() + checkpoint.file_tables_before_checkpoint,
  623. file_tables_.end());
  624. for (int i = checkpoint.allocations_before_checkpoint;
  625. i < allocations_.size();
  626. i++) {
  627. operator delete(allocations_[i]);
  628. }
  629. strings_.resize(checkpoint.strings_before_checkpoint);
  630. messages_.resize(checkpoint.messages_before_checkpoint);
  631. file_tables_.resize(checkpoint.file_tables_before_checkpoint);
  632. allocations_.resize(checkpoint.allocations_before_checkpoint);
  633. checkpoints_.pop_back();
  634. }
  635. // -------------------------------------------------------------------
  636. inline Symbol DescriptorPool::Tables::FindSymbol(const string& key) const {
  637. const Symbol* result = FindOrNull(symbols_by_name_, key.c_str());
  638. if (result == NULL) {
  639. return kNullSymbol;
  640. } else {
  641. return *result;
  642. }
  643. }
  644. inline Symbol FileDescriptorTables::FindNestedSymbol(
  645. const void* parent, const string& name) const {
  646. const Symbol* result =
  647. FindOrNull(symbols_by_parent_, PointerStringPair(parent, name.c_str()));
  648. if (result == NULL) {
  649. return kNullSymbol;
  650. } else {
  651. return *result;
  652. }
  653. }
  654. inline Symbol FileDescriptorTables::FindNestedSymbolOfType(
  655. const void* parent, const string& name, const Symbol::Type type) const {
  656. Symbol result = FindNestedSymbol(parent, name);
  657. if (result.type != type) return kNullSymbol;
  658. return result;
  659. }
  660. Symbol DescriptorPool::Tables::FindByNameHelper(
  661. const DescriptorPool* pool, const string& name) {
  662. MutexLockMaybe lock(pool->mutex_);
  663. known_bad_symbols_.clear();
  664. known_bad_files_.clear();
  665. Symbol result = FindSymbol(name);
  666. if (result.IsNull() && pool->underlay_ != NULL) {
  667. // Symbol not found; check the underlay.
  668. result =
  669. pool->underlay_->tables_->FindByNameHelper(pool->underlay_, name);
  670. }
  671. if (result.IsNull()) {
  672. // Symbol still not found, so check fallback database.
  673. if (pool->TryFindSymbolInFallbackDatabase(name)) {
  674. result = FindSymbol(name);
  675. }
  676. }
  677. return result;
  678. }
  679. inline const FileDescriptor* DescriptorPool::Tables::FindFile(
  680. const string& key) const {
  681. return FindPtrOrNull(files_by_name_, key.c_str());
  682. }
  683. inline const FieldDescriptor* FileDescriptorTables::FindFieldByNumber(
  684. const Descriptor* parent, int number) const {
  685. return FindPtrOrNull(fields_by_number_, std::make_pair(parent, number));
  686. }
  687. inline const FieldDescriptor* FileDescriptorTables::FindFieldByLowercaseName(
  688. const void* parent, const string& lowercase_name) const {
  689. return FindPtrOrNull(fields_by_lowercase_name_,
  690. PointerStringPair(parent, lowercase_name.c_str()));
  691. }
  692. inline const FieldDescriptor* FileDescriptorTables::FindFieldByCamelcaseName(
  693. const void* parent, const string& camelcase_name) const {
  694. return FindPtrOrNull(fields_by_camelcase_name_,
  695. PointerStringPair(parent, camelcase_name.c_str()));
  696. }
  697. inline const EnumValueDescriptor* FileDescriptorTables::FindEnumValueByNumber(
  698. const EnumDescriptor* parent, int number) const {
  699. return FindPtrOrNull(enum_values_by_number_, std::make_pair(parent, number));
  700. }
  701. inline const EnumValueDescriptor*
  702. FileDescriptorTables::FindEnumValueByNumberCreatingIfUnknown(
  703. const EnumDescriptor* parent, int number) const {
  704. // First try, with map of compiled-in values.
  705. {
  706. const EnumValueDescriptor* desc =
  707. FindPtrOrNull(enum_values_by_number_, std::make_pair(parent, number));
  708. if (desc != NULL) {
  709. return desc;
  710. }
  711. }
  712. // Second try, with reader lock held on unknown enum values: common case.
  713. {
  714. ReaderMutexLock l(&unknown_enum_values_mu_);
  715. const EnumValueDescriptor* desc = FindPtrOrNull(
  716. unknown_enum_values_by_number_, std::make_pair(parent, number));
  717. if (desc != NULL) {
  718. return desc;
  719. }
  720. }
  721. // If not found, try again with writer lock held, and create new descriptor if
  722. // necessary.
  723. {
  724. WriterMutexLock l(&unknown_enum_values_mu_);
  725. const EnumValueDescriptor* desc = FindPtrOrNull(
  726. unknown_enum_values_by_number_, std::make_pair(parent, number));
  727. if (desc != NULL) {
  728. return desc;
  729. }
  730. // Create an EnumValueDescriptor dynamically. We don't insert it into the
  731. // EnumDescriptor (it's not a part of the enum as originally defined), but
  732. // we do insert it into the table so that we can return the same pointer
  733. // later.
  734. string enum_value_name = StringPrintf(
  735. "UNKNOWN_ENUM_VALUE_%s_%d", parent->name().c_str(), number);
  736. DescriptorPool::Tables* tables =
  737. const_cast<DescriptorPool::Tables*>(DescriptorPool::generated_pool()->
  738. tables_.get());
  739. EnumValueDescriptor* result = tables->Allocate<EnumValueDescriptor>();
  740. result->name_ = tables->AllocateString(enum_value_name);
  741. result->full_name_ = tables->AllocateString(parent->full_name() +
  742. "." + enum_value_name);
  743. result->number_ = number;
  744. result->type_ = parent;
  745. result->options_ = &EnumValueOptions::default_instance();
  746. InsertIfNotPresent(&unknown_enum_values_by_number_,
  747. std::make_pair(parent, number), result);
  748. return result;
  749. }
  750. }
  751. inline const FieldDescriptor* DescriptorPool::Tables::FindExtension(
  752. const Descriptor* extendee, int number) {
  753. return FindPtrOrNull(extensions_, std::make_pair(extendee, number));
  754. }
  755. inline void DescriptorPool::Tables::FindAllExtensions(
  756. const Descriptor* extendee, vector<const FieldDescriptor*>* out) const {
  757. ExtensionsGroupedByDescriptorMap::const_iterator it =
  758. extensions_.lower_bound(std::make_pair(extendee, 0));
  759. for (; it != extensions_.end() && it->first.first == extendee; ++it) {
  760. out->push_back(it->second);
  761. }
  762. }
  763. // -------------------------------------------------------------------
  764. bool DescriptorPool::Tables::AddSymbol(
  765. const string& full_name, Symbol symbol) {
  766. if (InsertIfNotPresent(&symbols_by_name_, full_name.c_str(), symbol)) {
  767. symbols_after_checkpoint_.push_back(full_name.c_str());
  768. return true;
  769. } else {
  770. return false;
  771. }
  772. }
  773. bool FileDescriptorTables::AddAliasUnderParent(
  774. const void* parent, const string& name, Symbol symbol) {
  775. PointerStringPair by_parent_key(parent, name.c_str());
  776. return InsertIfNotPresent(&symbols_by_parent_, by_parent_key, symbol);
  777. }
  778. bool DescriptorPool::Tables::AddFile(const FileDescriptor* file) {
  779. if (InsertIfNotPresent(&files_by_name_, file->name().c_str(), file)) {
  780. files_after_checkpoint_.push_back(file->name().c_str());
  781. return true;
  782. } else {
  783. return false;
  784. }
  785. }
  786. void FileDescriptorTables::AddFieldByStylizedNames(
  787. const FieldDescriptor* field) {
  788. const void* parent;
  789. if (field->is_extension()) {
  790. if (field->extension_scope() == NULL) {
  791. parent = field->file();
  792. } else {
  793. parent = field->extension_scope();
  794. }
  795. } else {
  796. parent = field->containing_type();
  797. }
  798. PointerStringPair lowercase_key(parent, field->lowercase_name().c_str());
  799. InsertIfNotPresent(&fields_by_lowercase_name_, lowercase_key, field);
  800. PointerStringPair camelcase_key(parent, field->camelcase_name().c_str());
  801. InsertIfNotPresent(&fields_by_camelcase_name_, camelcase_key, field);
  802. }
  803. bool FileDescriptorTables::AddFieldByNumber(const FieldDescriptor* field) {
  804. DescriptorIntPair key(field->containing_type(), field->number());
  805. return InsertIfNotPresent(&fields_by_number_, key, field);
  806. }
  807. bool FileDescriptorTables::AddEnumValueByNumber(
  808. const EnumValueDescriptor* value) {
  809. EnumIntPair key(value->type(), value->number());
  810. return InsertIfNotPresent(&enum_values_by_number_, key, value);
  811. }
  812. bool DescriptorPool::Tables::AddExtension(const FieldDescriptor* field) {
  813. DescriptorIntPair key(field->containing_type(), field->number());
  814. if (InsertIfNotPresent(&extensions_, key, field)) {
  815. extensions_after_checkpoint_.push_back(key);
  816. return true;
  817. } else {
  818. return false;
  819. }
  820. }
  821. // -------------------------------------------------------------------
  822. template<typename Type>
  823. Type* DescriptorPool::Tables::Allocate() {
  824. return reinterpret_cast<Type*>(AllocateBytes(sizeof(Type)));
  825. }
  826. template<typename Type>
  827. Type* DescriptorPool::Tables::AllocateArray(int count) {
  828. return reinterpret_cast<Type*>(AllocateBytes(sizeof(Type) * count));
  829. }
  830. string* DescriptorPool::Tables::AllocateString(const string& value) {
  831. string* result = new string(value);
  832. strings_.push_back(result);
  833. return result;
  834. }
  835. template<typename Type>
  836. Type* DescriptorPool::Tables::AllocateMessage(Type* /* dummy */) {
  837. Type* result = new Type;
  838. messages_.push_back(result);
  839. return result;
  840. }
  841. FileDescriptorTables* DescriptorPool::Tables::AllocateFileTables() {
  842. FileDescriptorTables* result = new FileDescriptorTables;
  843. file_tables_.push_back(result);
  844. return result;
  845. }
  846. void* DescriptorPool::Tables::AllocateBytes(int size) {
  847. // TODO(kenton): Would it be worthwhile to implement this in some more
  848. // sophisticated way? Probably not for the open source release, but for
  849. // internal use we could easily plug in one of our existing memory pool
  850. // allocators...
  851. if (size == 0) return NULL;
  852. void* result = operator new(size);
  853. allocations_.push_back(result);
  854. return result;
  855. }
  856. void FileDescriptorTables::BuildLocationsByPath(
  857. pair<const FileDescriptorTables*, const SourceCodeInfo*>* p) {
  858. for (int i = 0, len = p->second->location_size(); i < len; ++i) {
  859. const SourceCodeInfo_Location* loc = &p->second->location().Get(i);
  860. p->first->locations_by_path_[Join(loc->path(), ",")] = loc;
  861. }
  862. }
  863. const SourceCodeInfo_Location* FileDescriptorTables::GetSourceLocation(
  864. const vector<int>& path, const SourceCodeInfo* info) const {
  865. pair<const FileDescriptorTables*, const SourceCodeInfo*> p(
  866. std::make_pair(this, info));
  867. locations_by_path_once_.Init(&FileDescriptorTables::BuildLocationsByPath, &p);
  868. return FindPtrOrNull(locations_by_path_, Join(path, ","));
  869. }
  870. // ===================================================================
  871. // DescriptorPool
  872. DescriptorPool::ErrorCollector::~ErrorCollector() {}
  873. DescriptorPool::DescriptorPool()
  874. : mutex_(NULL),
  875. fallback_database_(NULL),
  876. default_error_collector_(NULL),
  877. underlay_(NULL),
  878. tables_(new Tables),
  879. enforce_dependencies_(true),
  880. allow_unknown_(false),
  881. enforce_weak_(false) {}
  882. DescriptorPool::DescriptorPool(DescriptorDatabase* fallback_database,
  883. ErrorCollector* error_collector)
  884. : mutex_(new Mutex),
  885. fallback_database_(fallback_database),
  886. default_error_collector_(error_collector),
  887. underlay_(NULL),
  888. tables_(new Tables),
  889. enforce_dependencies_(true),
  890. allow_unknown_(false),
  891. enforce_weak_(false) {
  892. }
  893. DescriptorPool::DescriptorPool(const DescriptorPool* underlay)
  894. : mutex_(NULL),
  895. fallback_database_(NULL),
  896. default_error_collector_(NULL),
  897. underlay_(underlay),
  898. tables_(new Tables),
  899. enforce_dependencies_(true),
  900. allow_unknown_(false),
  901. enforce_weak_(false) {}
  902. DescriptorPool::~DescriptorPool() {
  903. if (mutex_ != NULL) delete mutex_;
  904. }
  905. // DescriptorPool::BuildFile() defined later.
  906. // DescriptorPool::BuildFileCollectingErrors() defined later.
  907. void DescriptorPool::InternalDontEnforceDependencies() {
  908. enforce_dependencies_ = false;
  909. }
  910. void DescriptorPool::AddUnusedImportTrackFile(const string& file_name) {
  911. unused_import_track_files_.insert(file_name);
  912. }
  913. void DescriptorPool::ClearUnusedImportTrackFiles() {
  914. unused_import_track_files_.clear();
  915. }
  916. bool DescriptorPool::InternalIsFileLoaded(const string& filename) const {
  917. MutexLockMaybe lock(mutex_);
  918. return tables_->FindFile(filename) != NULL;
  919. }
  920. // generated_pool ====================================================
  921. namespace {
  922. EncodedDescriptorDatabase* generated_database_ = NULL;
  923. DescriptorPool* generated_pool_ = NULL;
  924. GOOGLE_PROTOBUF_DECLARE_ONCE(generated_pool_init_);
  925. void DeleteGeneratedPool() {
  926. delete generated_database_;
  927. generated_database_ = NULL;
  928. delete generated_pool_;
  929. generated_pool_ = NULL;
  930. }
  931. static void InitGeneratedPool() {
  932. generated_database_ = new EncodedDescriptorDatabase;
  933. generated_pool_ = new DescriptorPool(generated_database_);
  934. internal::OnShutdown(&DeleteGeneratedPool);
  935. }
  936. inline void InitGeneratedPoolOnce() {
  937. ::google::protobuf::GoogleOnceInit(&generated_pool_init_, &InitGeneratedPool);
  938. }
  939. } // anonymous namespace
  940. const DescriptorPool* DescriptorPool::generated_pool() {
  941. InitGeneratedPoolOnce();
  942. return generated_pool_;
  943. }
  944. DescriptorPool* DescriptorPool::internal_generated_pool() {
  945. InitGeneratedPoolOnce();
  946. return generated_pool_;
  947. }
  948. void DescriptorPool::InternalAddGeneratedFile(
  949. const void* encoded_file_descriptor, int size) {
  950. // So, this function is called in the process of initializing the
  951. // descriptors for generated proto classes. Each generated .pb.cc file
  952. // has an internal procedure called AddDescriptors() which is called at
  953. // process startup, and that function calls this one in order to register
  954. // the raw bytes of the FileDescriptorProto representing the file.
  955. //
  956. // We do not actually construct the descriptor objects right away. We just
  957. // hang on to the bytes until they are actually needed. We actually construct
  958. // the descriptor the first time one of the following things happens:
  959. // * Someone calls a method like descriptor(), GetDescriptor(), or
  960. // GetReflection() on the generated types, which requires returning the
  961. // descriptor or an object based on it.
  962. // * Someone looks up the descriptor in DescriptorPool::generated_pool().
  963. //
  964. // Once one of these happens, the DescriptorPool actually parses the
  965. // FileDescriptorProto and generates a FileDescriptor (and all its children)
  966. // based on it.
  967. //
  968. // Note that FileDescriptorProto is itself a generated protocol message.
  969. // Therefore, when we parse one, we have to be very careful to avoid using
  970. // any descriptor-based operations, since this might cause infinite recursion
  971. // or deadlock.
  972. InitGeneratedPoolOnce();
  973. GOOGLE_CHECK(generated_database_->Add(encoded_file_descriptor, size));
  974. }
  975. // Find*By* methods ==================================================
  976. // TODO(kenton): There's a lot of repeated code here, but I'm not sure if
  977. // there's any good way to factor it out. Think about this some time when
  978. // there's nothing more important to do (read: never).
  979. const FileDescriptor* DescriptorPool::FindFileByName(const string& name) const {
  980. MutexLockMaybe lock(mutex_);
  981. tables_->known_bad_symbols_.clear();
  982. tables_->known_bad_files_.clear();
  983. const FileDescriptor* result = tables_->FindFile(name);
  984. if (result != NULL) return result;
  985. if (underlay_ != NULL) {
  986. result = underlay_->FindFileByName(name);
  987. if (result != NULL) return result;
  988. }
  989. if (TryFindFileInFallbackDatabase(name)) {
  990. result = tables_->FindFile(name);
  991. if (result != NULL) return result;
  992. }
  993. return NULL;
  994. }
  995. const FileDescriptor* DescriptorPool::FindFileContainingSymbol(
  996. const string& symbol_name) const {
  997. MutexLockMaybe lock(mutex_);
  998. tables_->known_bad_symbols_.clear();
  999. tables_->known_bad_files_.clear();
  1000. Symbol result = tables_->FindSymbol(symbol_name);
  1001. if (!result.IsNull()) return result.GetFile();
  1002. if (underlay_ != NULL) {
  1003. const FileDescriptor* file_result =
  1004. underlay_->FindFileContainingSymbol(symbol_name);
  1005. if (file_result != NULL) return file_result;
  1006. }
  1007. if (TryFindSymbolInFallbackDatabase(symbol_name)) {
  1008. result = tables_->FindSymbol(symbol_name);
  1009. if (!result.IsNull()) return result.GetFile();
  1010. }
  1011. return NULL;
  1012. }
  1013. const Descriptor* DescriptorPool::FindMessageTypeByName(
  1014. const string& name) const {
  1015. Symbol result = tables_->FindByNameHelper(this, name);
  1016. return (result.type == Symbol::MESSAGE) ? result.descriptor : NULL;
  1017. }
  1018. const FieldDescriptor* DescriptorPool::FindFieldByName(
  1019. const string& name) const {
  1020. Symbol result = tables_->FindByNameHelper(this, name);
  1021. if (result.type == Symbol::FIELD &&
  1022. !result.field_descriptor->is_extension()) {
  1023. return result.field_descriptor;
  1024. } else {
  1025. return NULL;
  1026. }
  1027. }
  1028. const FieldDescriptor* DescriptorPool::FindExtensionByName(
  1029. const string& name) const {
  1030. Symbol result = tables_->FindByNameHelper(this, name);
  1031. if (result.type == Symbol::FIELD &&
  1032. result.field_descriptor->is_extension()) {
  1033. return result.field_descriptor;
  1034. } else {
  1035. return NULL;
  1036. }
  1037. }
  1038. const OneofDescriptor* DescriptorPool::FindOneofByName(
  1039. const string& name) const {
  1040. Symbol result = tables_->FindByNameHelper(this, name);
  1041. return (result.type == Symbol::ONEOF) ? result.oneof_descriptor : NULL;
  1042. }
  1043. const EnumDescriptor* DescriptorPool::FindEnumTypeByName(
  1044. const string& name) const {
  1045. Symbol result = tables_->FindByNameHelper(this, name);
  1046. return (result.type == Symbol::ENUM) ? result.enum_descriptor : NULL;
  1047. }
  1048. const EnumValueDescriptor* DescriptorPool::FindEnumValueByName(
  1049. const string& name) const {
  1050. Symbol result = tables_->FindByNameHelper(this, name);
  1051. return (result.type == Symbol::ENUM_VALUE) ?
  1052. result.enum_value_descriptor : NULL;
  1053. }
  1054. const ServiceDescriptor* DescriptorPool::FindServiceByName(
  1055. const string& name) const {
  1056. Symbol result = tables_->FindByNameHelper(this, name);
  1057. return (result.type == Symbol::SERVICE) ? result.service_descriptor : NULL;
  1058. }
  1059. const MethodDescriptor* DescriptorPool::FindMethodByName(
  1060. const string& name) const {
  1061. Symbol result = tables_->FindByNameHelper(this, name);
  1062. return (result.type == Symbol::METHOD) ? result.method_descriptor : NULL;
  1063. }
  1064. const FieldDescriptor* DescriptorPool::FindExtensionByNumber(
  1065. const Descriptor* extendee, int number) const {
  1066. MutexLockMaybe lock(mutex_);
  1067. tables_->known_bad_symbols_.clear();
  1068. tables_->known_bad_files_.clear();
  1069. const FieldDescriptor* result = tables_->FindExtension(extendee, number);
  1070. if (result != NULL) {
  1071. return result;
  1072. }
  1073. if (underlay_ != NULL) {
  1074. result = underlay_->FindExtensionByNumber(extendee, number);
  1075. if (result != NULL) return result;
  1076. }
  1077. if (TryFindExtensionInFallbackDatabase(extendee, number)) {
  1078. result = tables_->FindExtension(extendee, number);
  1079. if (result != NULL) {
  1080. return result;
  1081. }
  1082. }
  1083. return NULL;
  1084. }
  1085. void DescriptorPool::FindAllExtensions(
  1086. const Descriptor* extendee, vector<const FieldDescriptor*>* out) const {
  1087. MutexLockMaybe lock(mutex_);
  1088. tables_->known_bad_symbols_.clear();
  1089. tables_->known_bad_files_.clear();
  1090. // Initialize tables_->extensions_ from the fallback database first
  1091. // (but do this only once per descriptor).
  1092. if (fallback_database_ != NULL &&
  1093. tables_->extensions_loaded_from_db_.count(extendee) == 0) {
  1094. vector<int> numbers;
  1095. if (fallback_database_->FindAllExtensionNumbers(extendee->full_name(),
  1096. &numbers)) {
  1097. for (int i = 0; i < numbers.size(); ++i) {
  1098. int number = numbers[i];
  1099. if (tables_->FindExtension(extendee, number) == NULL) {
  1100. TryFindExtensionInFallbackDatabase(extendee, number);
  1101. }
  1102. }
  1103. tables_->extensions_loaded_from_db_.insert(extendee);
  1104. }
  1105. }
  1106. tables_->FindAllExtensions(extendee, out);
  1107. if (underlay_ != NULL) {
  1108. underlay_->FindAllExtensions(extendee, out);
  1109. }
  1110. }
  1111. // -------------------------------------------------------------------
  1112. const FieldDescriptor*
  1113. Descriptor::FindFieldByNumber(int key) const {
  1114. const FieldDescriptor* result =
  1115. file()->tables_->FindFieldByNumber(this, key);
  1116. if (result == NULL || result->is_extension()) {
  1117. return NULL;
  1118. } else {
  1119. return result;
  1120. }
  1121. }
  1122. const FieldDescriptor*
  1123. Descriptor::FindFieldByLowercaseName(const string& key) const {
  1124. const FieldDescriptor* result =
  1125. file()->tables_->FindFieldByLowercaseName(this, key);
  1126. if (result == NULL || result->is_extension()) {
  1127. return NULL;
  1128. } else {
  1129. return result;
  1130. }
  1131. }
  1132. const FieldDescriptor*
  1133. Descriptor::FindFieldByCamelcaseName(const string& key) const {
  1134. const FieldDescriptor* result =
  1135. file()->tables_->FindFieldByCamelcaseName(this, key);
  1136. if (result == NULL || result->is_extension()) {
  1137. return NULL;
  1138. } else {
  1139. return result;
  1140. }
  1141. }
  1142. const FieldDescriptor*
  1143. Descriptor::FindFieldByName(const string& key) const {
  1144. Symbol result =
  1145. file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD);
  1146. if (!result.IsNull() && !result.field_descriptor->is_extension()) {
  1147. return result.field_descriptor;
  1148. } else {
  1149. return NULL;
  1150. }
  1151. }
  1152. const OneofDescriptor*
  1153. Descriptor::FindOneofByName(const string& key) const {
  1154. Symbol result =
  1155. file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ONEOF);
  1156. if (!result.IsNull()) {
  1157. return result.oneof_descriptor;
  1158. } else {
  1159. return NULL;
  1160. }
  1161. }
  1162. const FieldDescriptor*
  1163. Descriptor::FindExtensionByName(const string& key) const {
  1164. Symbol result =
  1165. file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD);
  1166. if (!result.IsNull() && result.field_descriptor->is_extension()) {
  1167. return result.field_descriptor;
  1168. } else {
  1169. return NULL;
  1170. }
  1171. }
  1172. const FieldDescriptor*
  1173. Descriptor::FindExtensionByLowercaseName(const string& key) const {
  1174. const FieldDescriptor* result =
  1175. file()->tables_->FindFieldByLowercaseName(this, key);
  1176. if (result == NULL || !result->is_extension()) {
  1177. return NULL;
  1178. } else {
  1179. return result;
  1180. }
  1181. }
  1182. const FieldDescriptor*
  1183. Descriptor::FindExtensionByCamelcaseName(const string& key) const {
  1184. const FieldDescriptor* result =
  1185. file()->tables_->FindFieldByCamelcaseName(this, key);
  1186. if (result == NULL || !result->is_extension()) {
  1187. return NULL;
  1188. } else {
  1189. return result;
  1190. }
  1191. }
  1192. const Descriptor*
  1193. Descriptor::FindNestedTypeByName(const string& key) const {
  1194. Symbol result =
  1195. file()->tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE);
  1196. if (!result.IsNull()) {
  1197. return result.descriptor;
  1198. } else {
  1199. return NULL;
  1200. }
  1201. }
  1202. const EnumDescriptor*
  1203. Descriptor::FindEnumTypeByName(const string& key) const {
  1204. Symbol result =
  1205. file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM);
  1206. if (!result.IsNull()) {
  1207. return result.enum_descriptor;
  1208. } else {
  1209. return NULL;
  1210. }
  1211. }
  1212. const EnumValueDescriptor*
  1213. Descriptor::FindEnumValueByName(const string& key) const {
  1214. Symbol result =
  1215. file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE);
  1216. if (!result.IsNull()) {
  1217. return result.enum_value_descriptor;
  1218. } else {
  1219. return NULL;
  1220. }
  1221. }
  1222. const EnumValueDescriptor*
  1223. EnumDescriptor::FindValueByName(const string& key) const {
  1224. Symbol result =
  1225. file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE);
  1226. if (!result.IsNull()) {
  1227. return result.enum_value_descriptor;
  1228. } else {
  1229. return NULL;
  1230. }
  1231. }
  1232. const EnumValueDescriptor*
  1233. EnumDescriptor::FindValueByNumber(int key) const {
  1234. return file()->tables_->FindEnumValueByNumber(this, key);
  1235. }
  1236. const EnumValueDescriptor*
  1237. EnumDescriptor::FindValueByNumberCreatingIfUnknown(int key) const {
  1238. return file()->tables_->FindEnumValueByNumberCreatingIfUnknown(this, key);
  1239. }
  1240. const MethodDescriptor*
  1241. ServiceDescriptor::FindMethodByName(const string& key) const {
  1242. Symbol result =
  1243. file()->tables_->FindNestedSymbolOfType(this, key, Symbol::METHOD);
  1244. if (!result.IsNull()) {
  1245. return result.method_descriptor;
  1246. } else {
  1247. return NULL;
  1248. }
  1249. }
  1250. const Descriptor*
  1251. FileDescriptor::FindMessageTypeByName(const string& key) const {
  1252. Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE);
  1253. if (!result.IsNull()) {
  1254. return result.descriptor;
  1255. } else {
  1256. return NULL;
  1257. }
  1258. }
  1259. const EnumDescriptor*
  1260. FileDescriptor::FindEnumTypeByName(const string& key) const {
  1261. Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM);
  1262. if (!result.IsNull()) {
  1263. return result.enum_descriptor;
  1264. } else {
  1265. return NULL;
  1266. }
  1267. }
  1268. const EnumValueDescriptor*
  1269. FileDescriptor::FindEnumValueByName(const string& key) const {
  1270. Symbol result =
  1271. tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE);
  1272. if (!result.IsNull()) {
  1273. return result.enum_value_descriptor;
  1274. } else {
  1275. return NULL;
  1276. }
  1277. }
  1278. const ServiceDescriptor*
  1279. FileDescriptor::FindServiceByName(const string& key) const {
  1280. Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::SERVICE);
  1281. if (!result.IsNull()) {
  1282. return result.service_descriptor;
  1283. } else {
  1284. return NULL;
  1285. }
  1286. }
  1287. const FieldDescriptor*
  1288. FileDescriptor::FindExtensionByName(const string& key) const {
  1289. Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD);
  1290. if (!result.IsNull() && result.field_descriptor->is_extension()) {
  1291. return result.field_descriptor;
  1292. } else {
  1293. return NULL;
  1294. }
  1295. }
  1296. const FieldDescriptor*
  1297. FileDescriptor::FindExtensionByLowercaseName(const string& key) const {
  1298. const FieldDescriptor* result = tables_->FindFieldByLowercaseName(this, key);
  1299. if (result == NULL || !result->is_extension()) {
  1300. return NULL;
  1301. } else {
  1302. return result;
  1303. }
  1304. }
  1305. const FieldDescriptor*
  1306. FileDescriptor::FindExtensionByCamelcaseName(const string& key) const {
  1307. const FieldDescriptor* result = tables_->FindFieldByCamelcaseName(this, key);
  1308. if (result == NULL || !result->is_extension()) {
  1309. return NULL;
  1310. } else {
  1311. return result;
  1312. }
  1313. }
  1314. const Descriptor::ExtensionRange*
  1315. Descriptor::FindExtensionRangeContainingNumber(int number) const {
  1316. // Linear search should be fine because we don't expect a message to have
  1317. // more than a couple extension ranges.
  1318. for (int i = 0; i < extension_range_count(); i++) {
  1319. if (number >= extension_range(i)->start &&
  1320. number < extension_range(i)->end) {
  1321. return extension_range(i);
  1322. }
  1323. }
  1324. return NULL;
  1325. }
  1326. const Descriptor::ReservedRange*
  1327. Descriptor::FindReservedRangeContainingNumber(int number) const {
  1328. // TODO(chrisn): Consider a non-linear search.
  1329. for (int i = 0; i < reserved_range_count(); i++) {
  1330. if (number >= reserved_range(i)->start &&
  1331. number < reserved_range(i)->end) {
  1332. return reserved_range(i);
  1333. }
  1334. }
  1335. return NULL;
  1336. }
  1337. // -------------------------------------------------------------------
  1338. bool DescriptorPool::TryFindFileInFallbackDatabase(const string& name) const {
  1339. if (fallback_database_ == NULL) return false;
  1340. if (tables_->known_bad_files_.count(name) > 0) return false;
  1341. FileDescriptorProto file_proto;
  1342. if (!fallback_database_->FindFileByName(name, &file_proto) ||
  1343. BuildFileFromDatabase(file_proto) == NULL) {
  1344. tables_->known_bad_files_.insert(name);
  1345. return false;
  1346. }
  1347. return true;
  1348. }
  1349. bool DescriptorPool::IsSubSymbolOfBuiltType(const string& name) const {
  1350. string prefix = name;
  1351. for (;;) {
  1352. string::size_type dot_pos = prefix.find_last_of('.');
  1353. if (dot_pos == string::npos) {
  1354. break;
  1355. }
  1356. prefix = prefix.substr(0, dot_pos);
  1357. Symbol symbol = tables_->FindSymbol(prefix);
  1358. // If the symbol type is anything other than PACKAGE, then its complete
  1359. // definition is already known.
  1360. if (!symbol.IsNull() && symbol.type != Symbol::PACKAGE) {
  1361. return true;
  1362. }
  1363. }
  1364. if (underlay_ != NULL) {
  1365. // Check to see if any prefix of this symbol exists in the underlay.
  1366. return underlay_->IsSubSymbolOfBuiltType(name);
  1367. }
  1368. return false;
  1369. }
  1370. bool DescriptorPool::TryFindSymbolInFallbackDatabase(const string& name) const {
  1371. if (fallback_database_ == NULL) return false;
  1372. if (tables_->known_bad_symbols_.count(name) > 0) return false;
  1373. FileDescriptorProto file_proto;
  1374. if (// We skip looking in the fallback database if the name is a sub-symbol
  1375. // of any descriptor that already exists in the descriptor pool (except
  1376. // for package descriptors). This is valid because all symbols except
  1377. // for packages are defined in a single file, so if the symbol exists
  1378. // then we should already have its definition.
  1379. //
  1380. // The other reason to do this is to support "overriding" type
  1381. // definitions by merging two databases that define the same type. (Yes,
  1382. // people do this.) The main difficulty with making this work is that
  1383. // FindFileContainingSymbol() is allowed to return both false positives
  1384. // (e.g., SimpleDescriptorDatabase, UpgradedDescriptorDatabase) and false
  1385. // negatives (e.g. ProtoFileParser, SourceTreeDescriptorDatabase).
  1386. // When two such databases are merged, looking up a non-existent
  1387. // sub-symbol of a type that already exists in the descriptor pool can
  1388. // result in an attempt to load multiple definitions of the same type.
  1389. // The check below avoids this.
  1390. IsSubSymbolOfBuiltType(name)
  1391. // Look up file containing this symbol in fallback database.
  1392. || !fallback_database_->FindFileContainingSymbol(name, &file_proto)
  1393. // Check if we've already built this file. If so, it apparently doesn't
  1394. // contain the symbol we're looking for. Some DescriptorDatabases
  1395. // return false positives.
  1396. || tables_->FindFile(file_proto.name()) != NULL
  1397. // Build the file.
  1398. || BuildFileFromDatabase(file_proto) == NULL) {
  1399. tables_->known_bad_symbols_.insert(name);
  1400. return false;
  1401. }
  1402. return true;
  1403. }
  1404. bool DescriptorPool::TryFindExtensionInFallbackDatabase(
  1405. const Descriptor* containing_type, int field_number) const {
  1406. if (fallback_database_ == NULL) return false;
  1407. FileDescriptorProto file_proto;
  1408. if (!fallback_database_->FindFileContainingExtension(
  1409. containing_type->full_name(), field_number, &file_proto)) {
  1410. return false;
  1411. }
  1412. if (tables_->FindFile(file_proto.name()) != NULL) {
  1413. // We've already loaded this file, and it apparently doesn't contain the
  1414. // extension we're looking for. Some DescriptorDatabases return false
  1415. // positives.
  1416. return false;
  1417. }
  1418. if (BuildFileFromDatabase(file_proto) == NULL) {
  1419. return false;
  1420. }
  1421. return true;
  1422. }
  1423. // ===================================================================
  1424. bool FieldDescriptor::is_map() const {
  1425. return type() == TYPE_MESSAGE && message_type()->options().map_entry();
  1426. }
  1427. string FieldDescriptor::DefaultValueAsString(bool quote_string_type) const {
  1428. GOOGLE_CHECK(has_default_value()) << "No default value";
  1429. switch (cpp_type()) {
  1430. case CPPTYPE_INT32:
  1431. return SimpleItoa(default_value_int32());
  1432. break;
  1433. case CPPTYPE_INT64:
  1434. return SimpleItoa(default_value_int64());
  1435. break;
  1436. case CPPTYPE_UINT32:
  1437. return SimpleItoa(default_value_uint32());
  1438. break;
  1439. case CPPTYPE_UINT64:
  1440. return SimpleItoa(default_value_uint64());
  1441. break;
  1442. case CPPTYPE_FLOAT:
  1443. return SimpleFtoa(default_value_float());
  1444. break;
  1445. case CPPTYPE_DOUBLE:
  1446. return SimpleDtoa(default_value_double());
  1447. break;
  1448. case CPPTYPE_BOOL:
  1449. return default_value_bool() ? "true" : "false";
  1450. break;
  1451. case CPPTYPE_STRING:
  1452. if (quote_string_type) {
  1453. return "\"" + CEscape(default_value_string()) + "\"";
  1454. } else {
  1455. if (type() == TYPE_BYTES) {
  1456. return CEscape(default_value_string());
  1457. } else {
  1458. return default_value_string();
  1459. }
  1460. }
  1461. break;
  1462. case CPPTYPE_ENUM:
  1463. return default_value_enum()->name();
  1464. break;
  1465. case CPPTYPE_MESSAGE:
  1466. GOOGLE_LOG(DFATAL) << "Messages can't have default values!";
  1467. break;
  1468. }
  1469. GOOGLE_LOG(FATAL) << "Can't get here: failed to get default value as string";
  1470. return "";
  1471. }
  1472. // CopyTo methods ====================================================
  1473. void FileDescriptor::CopyTo(FileDescriptorProto* proto) const {
  1474. proto->set_name(name());
  1475. if (!package().empty()) proto->set_package(package());
  1476. // TODO(liujisi): Also populate when syntax="proto2".
  1477. if (syntax() == SYNTAX_PROTO3) proto->set_syntax(SyntaxName(syntax()));
  1478. for (int i = 0; i < dependency_count(); i++) {
  1479. proto->add_dependency(dependency(i)->name());
  1480. }
  1481. for (int i = 0; i < public_dependency_count(); i++) {
  1482. proto->add_public_dependency(public_dependencies_[i]);
  1483. }
  1484. for (int i = 0; i < weak_dependency_count(); i++) {
  1485. proto->add_weak_dependency(weak_dependencies_[i]);
  1486. }
  1487. for (int i = 0; i < message_type_count(); i++) {
  1488. message_type(i)->CopyTo(proto->add_message_type());
  1489. }
  1490. for (int i = 0; i < enum_type_count(); i++) {
  1491. enum_type(i)->CopyTo(proto->add_enum_type());
  1492. }
  1493. for (int i = 0; i < service_count(); i++) {
  1494. service(i)->CopyTo(proto->add_service());
  1495. }
  1496. for (int i = 0; i < extension_count(); i++) {
  1497. extension(i)->CopyTo(proto->add_extension());
  1498. }
  1499. if (&options() != &FileOptions::default_instance()) {
  1500. proto->mutable_options()->CopyFrom(options());
  1501. }
  1502. }
  1503. void FileDescriptor::CopySourceCodeInfoTo(FileDescriptorProto* proto) const {
  1504. if (source_code_info_ &&
  1505. source_code_info_ != &SourceCodeInfo::default_instance()) {
  1506. proto->mutable_source_code_info()->CopyFrom(*source_code_info_);
  1507. }
  1508. }
  1509. void Descriptor::CopyTo(DescriptorProto* proto) const {
  1510. proto->set_name(name());
  1511. for (int i = 0; i < field_count(); i++) {
  1512. field(i)->CopyTo(proto->add_field());
  1513. }
  1514. for (int i = 0; i < oneof_decl_count(); i++) {
  1515. oneof_decl(i)->CopyTo(proto->add_oneof_decl());
  1516. }
  1517. for (int i = 0; i < nested_type_count(); i++) {
  1518. nested_type(i)->CopyTo(proto->add_nested_type());
  1519. }
  1520. for (int i = 0; i < enum_type_count(); i++) {
  1521. enum_type(i)->CopyTo(proto->add_enum_type());
  1522. }
  1523. for (int i = 0; i < extension_range_count(); i++) {
  1524. DescriptorProto::ExtensionRange* range = proto->add_extension_range();
  1525. range->set_start(extension_range(i)->start);
  1526. range->set_end(extension_range(i)->end);
  1527. }
  1528. for (int i = 0; i < extension_count(); i++) {
  1529. extension(i)->CopyTo(proto->add_extension());
  1530. }
  1531. for (int i = 0; i < reserved_range_count(); i++) {
  1532. DescriptorProto::ReservedRange* range = proto->add_reserved_range();
  1533. range->set_start(reserved_range(i)->start);
  1534. range->set_end(reserved_range(i)->end);
  1535. }
  1536. for (int i = 0; i < reserved_name_count(); i++) {
  1537. proto->add_reserved_name(reserved_name(i));
  1538. }
  1539. if (&options() != &MessageOptions::default_instance()) {
  1540. proto->mutable_options()->CopyFrom(options());
  1541. }
  1542. }
  1543. void FieldDescriptor::CopyTo(FieldDescriptorProto* proto) const {
  1544. proto->set_name(name());
  1545. proto->set_number(number());
  1546. // Some compilers do not allow static_cast directly between two enum types,
  1547. // so we must cast to int first.
  1548. proto->set_label(static_cast<FieldDescriptorProto::Label>(
  1549. implicit_cast<int>(label())));
  1550. proto->set_type(static_cast<FieldDescriptorProto::Type>(
  1551. implicit_cast<int>(type())));
  1552. if (is_extension()) {
  1553. if (!containing_type()->is_unqualified_placeholder_) {
  1554. proto->set_extendee(".");
  1555. }
  1556. proto->mutable_extendee()->append(containing_type()->full_name());
  1557. }
  1558. if (cpp_type() == CPPTYPE_MESSAGE) {
  1559. if (message_type()->is_placeholder_) {
  1560. // We don't actually know if the type is a message type. It could be
  1561. // an enum.
  1562. proto->clear_type();
  1563. }
  1564. if (!message_type()->is_unqualified_placeholder_) {
  1565. proto->set_type_name(".");
  1566. }
  1567. proto->mutable_type_name()->append(message_type()->full_name());
  1568. } else if (cpp_type() == CPPTYPE_ENUM) {
  1569. if (!enum_type()->is_unqualified_placeholder_) {
  1570. proto->set_type_name(".");
  1571. }
  1572. proto->mutable_type_name()->append(enum_type()->full_name());
  1573. }
  1574. if (has_default_value()) {
  1575. proto->set_default_value(DefaultValueAsString(false));
  1576. }
  1577. if (containing_oneof() != NULL && !is_extension()) {
  1578. proto->set_oneof_index(containing_oneof()->index());
  1579. }
  1580. if (&options() != &FieldOptions::default_instance()) {
  1581. proto->mutable_options()->CopyFrom(options());
  1582. }
  1583. }
  1584. void OneofDescriptor::CopyTo(OneofDescriptorProto* proto) const {
  1585. proto->set_name(name());
  1586. }
  1587. void EnumDescriptor::CopyTo(EnumDescriptorProto* proto) const {
  1588. proto->set_name(name());
  1589. for (int i = 0; i < value_count(); i++) {
  1590. value(i)->CopyTo(proto->add_value());
  1591. }
  1592. if (&options() != &EnumOptions::default_instance()) {
  1593. proto->mutable_options()->CopyFrom(options());
  1594. }
  1595. }
  1596. void EnumValueDescriptor::CopyTo(EnumValueDescriptorProto* proto) const {
  1597. proto->set_name(name());
  1598. proto->set_number(number());
  1599. if (&options() != &EnumValueOptions::default_instance()) {
  1600. proto->mutable_options()->CopyFrom(options());
  1601. }
  1602. }
  1603. void ServiceDescriptor::CopyTo(ServiceDescriptorProto* proto) const {
  1604. proto->set_name(name());
  1605. for (int i = 0; i < method_count(); i++) {
  1606. method(i)->CopyTo(proto->add_method());
  1607. }
  1608. if (&options() != &ServiceOptions::default_instance()) {
  1609. proto->mutable_options()->CopyFrom(options());
  1610. }
  1611. }
  1612. void MethodDescriptor::CopyTo(MethodDescriptorProto* proto) const {
  1613. proto->set_name(name());
  1614. if (!input_type()->is_unqualified_placeholder_) {
  1615. proto->set_input_type(".");
  1616. }
  1617. proto->mutable_input_type()->append(input_type()->full_name());
  1618. if (!output_type()->is_unqualified_placeholder_) {
  1619. proto->set_output_type(".");
  1620. }
  1621. proto->mutable_output_type()->append(output_type()->full_name());
  1622. if (&options() != &MethodOptions::default_instance()) {
  1623. proto->mutable_options()->CopyFrom(options());
  1624. }
  1625. if (client_streaming_) {
  1626. proto->set_client_streaming(true);
  1627. }
  1628. if (server_streaming_) {
  1629. proto->set_server_streaming(true);
  1630. }
  1631. }
  1632. // DebugString methods ===============================================
  1633. namespace {
  1634. // Used by each of the option formatters.
  1635. bool RetrieveOptions(int depth,
  1636. const Message &options,
  1637. vector<string> *option_entries) {
  1638. option_entries->clear();
  1639. const Reflection* reflection = options.GetReflection();
  1640. vector<const FieldDescriptor*> fields;
  1641. reflection->ListFields(options, &fields);
  1642. for (int i = 0; i < fields.size(); i++) {
  1643. int count = 1;
  1644. bool repeated = false;
  1645. if (fields[i]->is_repeated()) {
  1646. count = reflection->FieldSize(options, fields[i]);
  1647. repeated = true;
  1648. }
  1649. for (int j = 0; j < count; j++) {
  1650. string fieldval;
  1651. if (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  1652. string tmp;
  1653. TextFormat::Printer printer;
  1654. printer.SetInitialIndentLevel(depth + 1);
  1655. printer.PrintFieldValueToString(options, fields[i],
  1656. repeated ? j : -1, &tmp);
  1657. fieldval.append("{\n");
  1658. fieldval.append(tmp);
  1659. fieldval.append(depth * 2, ' ');
  1660. fieldval.append("}");
  1661. } else {
  1662. TextFormat::PrintFieldValueToString(options, fields[i],
  1663. repeated ? j : -1, &fieldval);
  1664. }
  1665. string name;
  1666. if (fields[i]->is_extension()) {
  1667. name = "(." + fields[i]->full_name() + ")";
  1668. } else {
  1669. name = fields[i]->name();
  1670. }
  1671. option_entries->push_back(name + " = " + fieldval);
  1672. }
  1673. }
  1674. return !option_entries->empty();
  1675. }
  1676. // Formats options that all appear together in brackets. Does not include
  1677. // brackets.
  1678. bool FormatBracketedOptions(int depth, const Message &options, string *output) {
  1679. vector<string> all_options;
  1680. if (RetrieveOptions(depth, options, &all_options)) {
  1681. output->append(Join(all_options, ", "));
  1682. }
  1683. return !all_options.empty();
  1684. }
  1685. // Formats options one per line
  1686. bool FormatLineOptions(int depth, const Message &options, string *output) {
  1687. string prefix(depth * 2, ' ');
  1688. vector<string> all_options;
  1689. if (RetrieveOptions(depth, options, &all_options)) {
  1690. for (int i = 0; i < all_options.size(); i++) {
  1691. strings::SubstituteAndAppend(output, "$0option $1;\n",
  1692. prefix, all_options[i]);
  1693. }
  1694. }
  1695. return !all_options.empty();
  1696. }
  1697. class SourceLocationCommentPrinter {
  1698. public:
  1699. template<typename DescType>
  1700. SourceLocationCommentPrinter(const DescType* desc,
  1701. const string& prefix,
  1702. const DebugStringOptions& options)
  1703. : options_(options), prefix_(prefix) {
  1704. // Perform the SourceLocation lookup only if we're including user comments,
  1705. // because the lookup is fairly expensive.
  1706. have_source_loc_ = options.include_comments &&
  1707. desc->GetSourceLocation(&source_loc_);
  1708. }
  1709. SourceLocationCommentPrinter(const FileDescriptor* file,
  1710. const vector<int>& path,
  1711. const string& prefix,
  1712. const DebugStringOptions& options)
  1713. : options_(options), prefix_(prefix) {
  1714. // Perform the SourceLocation lookup only if we're including user comments,
  1715. // because the lookup is fairly expensive.
  1716. have_source_loc_ = options.include_comments &&
  1717. file->GetSourceLocation(path, &source_loc_);
  1718. }
  1719. void AddPreComment(string* output) {
  1720. if (have_source_loc_) {
  1721. // Detached leading comments.
  1722. for (int i = 0 ; i < source_loc_.leading_detached_comments.size(); ++i) {
  1723. *output += FormatComment(source_loc_.leading_detached_comments[i]);
  1724. *output += "\n";
  1725. }
  1726. // Attached leading comments.
  1727. if (!source_loc_.leading_comments.empty()) {
  1728. *output += FormatComment(source_loc_.leading_comments);
  1729. }
  1730. }
  1731. }
  1732. void AddPostComment(string* output) {
  1733. if (have_source_loc_ && source_loc_.trailing_comments.size() > 0) {
  1734. *output += FormatComment(source_loc_.trailing_comments);
  1735. }
  1736. }
  1737. // Format comment such that each line becomes a full-line C++-style comment in
  1738. // the DebugString() output.
  1739. string FormatComment(const string& comment_text) {
  1740. string stripped_comment = comment_text;
  1741. StripWhitespace(&stripped_comment);
  1742. vector<string> lines = Split(stripped_comment, "\n");
  1743. string output;
  1744. for (int i = 0; i < lines.size(); ++i) {
  1745. const string& line = lines[i];
  1746. strings::SubstituteAndAppend(&output, "$0// $1\n", prefix_, line);
  1747. }
  1748. return output;
  1749. }
  1750. private:
  1751. bool have_source_loc_;
  1752. SourceLocation source_loc_;
  1753. DebugStringOptions options_;
  1754. string prefix_;
  1755. };
  1756. } // anonymous namespace
  1757. string FileDescriptor::DebugString() const {
  1758. DebugStringOptions options; // default options
  1759. return DebugStringWithOptions(options);
  1760. }
  1761. string FileDescriptor::DebugStringWithOptions(
  1762. const DebugStringOptions& debug_string_options) const {
  1763. string contents;
  1764. {
  1765. vector<int> path;
  1766. path.push_back(FileDescriptorProto::kSyntaxFieldNumber);
  1767. SourceLocationCommentPrinter syntax_comment(
  1768. this, path, "", debug_string_options);
  1769. syntax_comment.AddPreComment(&contents);
  1770. strings::SubstituteAndAppend(&contents, "syntax = \"$0\";\n\n",
  1771. SyntaxName(syntax()));
  1772. syntax_comment.AddPostComment(&contents);
  1773. }
  1774. SourceLocationCommentPrinter
  1775. comment_printer(this, "", debug_string_options);
  1776. comment_printer.AddPreComment(&contents);
  1777. set<int> public_dependencies;
  1778. set<int> weak_dependencies;
  1779. public_dependencies.insert(public_dependencies_,
  1780. public_dependencies_ + public_dependency_count_);
  1781. weak_dependencies.insert(weak_dependencies_,
  1782. weak_dependencies_ + weak_dependency_count_);
  1783. for (int i = 0; i < dependency_count(); i++) {
  1784. if (public_dependencies.count(i) > 0) {
  1785. strings::SubstituteAndAppend(&contents, "import public \"$0\";\n",
  1786. dependency(i)->name());
  1787. } else if (weak_dependencies.count(i) > 0) {
  1788. strings::SubstituteAndAppend(&contents, "import weak \"$0\";\n",
  1789. dependency(i)->name());
  1790. } else {
  1791. strings::SubstituteAndAppend(&contents, "import \"$0\";\n",
  1792. dependency(i)->name());
  1793. }
  1794. }
  1795. if (!package().empty()) {
  1796. vector<int> path;
  1797. path.push_back(FileDescriptorProto::kPackageFieldNumber);
  1798. SourceLocationCommentPrinter package_comment(
  1799. this, path, "", debug_string_options);
  1800. package_comment.AddPreComment(&contents);
  1801. strings::SubstituteAndAppend(&contents, "package $0;\n\n", package());
  1802. package_comment.AddPostComment(&contents);
  1803. }
  1804. if (FormatLineOptions(0, options(), &contents)) {
  1805. contents.append("\n"); // add some space if we had options
  1806. }
  1807. for (int i = 0; i < enum_type_count(); i++) {
  1808. enum_type(i)->DebugString(0, &contents, debug_string_options);
  1809. contents.append("\n");
  1810. }
  1811. // Find all the 'group' type extensions; we will not output their nested
  1812. // definitions (those will be done with their group field descriptor).
  1813. set<const Descriptor*> groups;
  1814. for (int i = 0; i < extension_count(); i++) {
  1815. if (extension(i)->type() == FieldDescriptor::TYPE_GROUP) {
  1816. groups.insert(extension(i)->message_type());
  1817. }
  1818. }
  1819. for (int i = 0; i < message_type_count(); i++) {
  1820. if (groups.count(message_type(i)) == 0) {
  1821. message_type(i)->DebugString(0, &contents, debug_string_options,
  1822. /* include_opening_clause */ true);
  1823. contents.append("\n");
  1824. }
  1825. }
  1826. for (int i = 0; i < service_count(); i++) {
  1827. service(i)->DebugString(&contents, debug_string_options);
  1828. contents.append("\n");
  1829. }
  1830. const Descriptor* containing_type = NULL;
  1831. for (int i = 0; i < extension_count(); i++) {
  1832. if (extension(i)->containing_type() != containing_type) {
  1833. if (i > 0) contents.append("}\n\n");
  1834. containing_type = extension(i)->containing_type();
  1835. strings::SubstituteAndAppend(&contents, "extend .$0 {\n",
  1836. containing_type->full_name());
  1837. }
  1838. extension(i)->DebugString(1, FieldDescriptor::PRINT_LABEL, &contents,
  1839. debug_string_options);
  1840. }
  1841. if (extension_count() > 0) contents.append("}\n\n");
  1842. comment_printer.AddPostComment(&contents);
  1843. return contents;
  1844. }
  1845. string Descriptor::DebugString() const {
  1846. DebugStringOptions options; // default options
  1847. return DebugStringWithOptions(options);
  1848. }
  1849. string Descriptor::DebugStringWithOptions(
  1850. const DebugStringOptions& options) const {
  1851. string contents;
  1852. DebugString(0, &contents, options, /* include_opening_clause */ true);
  1853. return contents;
  1854. }
  1855. void Descriptor::DebugString(int depth, string *contents,
  1856. const DebugStringOptions&
  1857. debug_string_options,
  1858. bool include_opening_clause) const {
  1859. if (options().map_entry()) {
  1860. // Do not generate debug string for auto-generated map-entry type.
  1861. return;
  1862. }
  1863. string prefix(depth * 2, ' ');
  1864. ++depth;
  1865. SourceLocationCommentPrinter
  1866. comment_printer(this, prefix, debug_string_options);
  1867. comment_printer.AddPreComment(contents);
  1868. if (include_opening_clause) {
  1869. strings::SubstituteAndAppend(contents, "$0message $1", prefix, name());
  1870. }
  1871. contents->append(" {\n");
  1872. FormatLineOptions(depth, options(), contents);
  1873. // Find all the 'group' types for fields and extensions; we will not output
  1874. // their nested definitions (those will be done with their group field
  1875. // descriptor).
  1876. set<const Descriptor*> groups;
  1877. for (int i = 0; i < field_count(); i++) {
  1878. if (field(i)->type() == FieldDescriptor::TYPE_GROUP) {
  1879. groups.insert(field(i)->message_type());
  1880. }
  1881. }
  1882. for (int i = 0; i < extension_count(); i++) {
  1883. if (extension(i)->type() == FieldDescriptor::TYPE_GROUP) {
  1884. groups.insert(extension(i)->message_type());
  1885. }
  1886. }
  1887. for (int i = 0; i < nested_type_count(); i++) {
  1888. if (groups.count(nested_type(i)) == 0) {
  1889. nested_type(i)->DebugString(depth, contents, debug_string_options,
  1890. /* include_opening_clause */ true);
  1891. }
  1892. }
  1893. for (int i = 0; i < enum_type_count(); i++) {
  1894. enum_type(i)->DebugString(depth, contents, debug_string_options);
  1895. }
  1896. for (int i = 0; i < field_count(); i++) {
  1897. if (field(i)->containing_oneof() == NULL) {
  1898. field(i)->DebugString(depth, FieldDescriptor::PRINT_LABEL, contents,
  1899. debug_string_options);
  1900. } else if (field(i)->containing_oneof()->field(0) == field(i)) {
  1901. // This is the first field in this oneof, so print the whole oneof.
  1902. field(i)->containing_oneof()->DebugString(depth, contents,
  1903. debug_string_options);
  1904. }
  1905. }
  1906. for (int i = 0; i < extension_range_count(); i++) {
  1907. strings::SubstituteAndAppend(contents, "$0 extensions $1 to $2;\n",
  1908. prefix,
  1909. extension_range(i)->start,
  1910. extension_range(i)->end - 1);
  1911. }
  1912. // Group extensions by what they extend, so they can be printed out together.
  1913. const Descriptor* containing_type = NULL;
  1914. for (int i = 0; i < extension_count(); i++) {
  1915. if (extension(i)->containing_type() != containing_type) {
  1916. if (i > 0) strings::SubstituteAndAppend(contents, "$0 }\n", prefix);
  1917. containing_type = extension(i)->containing_type();
  1918. strings::SubstituteAndAppend(contents, "$0 extend .$1 {\n",
  1919. prefix, containing_type->full_name());
  1920. }
  1921. extension(i)->DebugString(
  1922. depth + 1, FieldDescriptor::PRINT_LABEL, contents,
  1923. debug_string_options);
  1924. }
  1925. if (extension_count() > 0)
  1926. strings::SubstituteAndAppend(contents, "$0 }\n", prefix);
  1927. if (reserved_range_count() > 0) {
  1928. strings::SubstituteAndAppend(contents, "$0 reserved ", prefix);
  1929. for (int i = 0; i < reserved_range_count(); i++) {
  1930. const Descriptor::ReservedRange* range = reserved_range(i);
  1931. if (range->end == range->start + 1) {
  1932. strings::SubstituteAndAppend(contents, "$0, ", range->start);
  1933. } else {
  1934. strings::SubstituteAndAppend(contents, "$0 to $1, ",
  1935. range->start, range->end - 1);
  1936. }
  1937. }
  1938. contents->replace(contents->size() - 2, 2, ";\n");
  1939. }
  1940. if (reserved_name_count() > 0) {
  1941. strings::SubstituteAndAppend(contents, "$0 reserved ", prefix);
  1942. for (int i = 0; i < reserved_name_count(); i++) {
  1943. strings::SubstituteAndAppend(contents, "\"$0\", ",
  1944. CEscape(reserved_name(i)));
  1945. }
  1946. contents->replace(contents->size() - 2, 2, ";\n");
  1947. }
  1948. strings::SubstituteAndAppend(contents, "$0}\n", prefix);
  1949. comment_printer.AddPostComment(contents);
  1950. }
  1951. string FieldDescriptor::DebugString() const {
  1952. DebugStringOptions options; // default options
  1953. return DebugStringWithOptions(options);
  1954. }
  1955. string FieldDescriptor::DebugStringWithOptions(
  1956. const DebugStringOptions& debug_string_options) const {
  1957. string contents;
  1958. int depth = 0;
  1959. if (is_extension()) {
  1960. strings::SubstituteAndAppend(&contents, "extend .$0 {\n",
  1961. containing_type()->full_name());
  1962. depth = 1;
  1963. }
  1964. DebugString(depth, PRINT_LABEL, &contents, debug_string_options);
  1965. if (is_extension()) {
  1966. contents.append("}\n");
  1967. }
  1968. return contents;
  1969. }
  1970. // The field type string used in FieldDescriptor::DebugString()
  1971. string FieldDescriptor::FieldTypeNameDebugString() const {
  1972. switch(type()) {
  1973. case TYPE_MESSAGE:
  1974. return "." + message_type()->full_name();
  1975. case TYPE_ENUM:
  1976. return "." + enum_type()->full_name();
  1977. default:
  1978. return kTypeToName[type()];
  1979. }
  1980. }
  1981. void FieldDescriptor::DebugString(int depth,
  1982. PrintLabelFlag print_label_flag,
  1983. string *contents,
  1984. const DebugStringOptions&
  1985. debug_string_options) const {
  1986. string prefix(depth * 2, ' ');
  1987. string field_type;
  1988. // Special case map fields.
  1989. if (is_map()) {
  1990. strings::SubstituteAndAppend(
  1991. &field_type, "map<$0, $1>",
  1992. message_type()->field(0)->FieldTypeNameDebugString(),
  1993. message_type()->field(1)->FieldTypeNameDebugString());
  1994. } else {
  1995. field_type = FieldTypeNameDebugString();
  1996. }
  1997. string label;
  1998. if (print_label_flag == PRINT_LABEL && !is_map()) {
  1999. label = kLabelToName[this->label()];
  2000. label.push_back(' ');
  2001. }
  2002. SourceLocationCommentPrinter
  2003. comment_printer(this, prefix, debug_string_options);
  2004. comment_printer.AddPreComment(contents);
  2005. strings::SubstituteAndAppend(contents, "$0$1$2 $3 = $4",
  2006. prefix,
  2007. label,
  2008. field_type,
  2009. type() == TYPE_GROUP ? message_type()->name() :
  2010. name(),
  2011. number());
  2012. bool bracketed = false;
  2013. if (has_default_value()) {
  2014. bracketed = true;
  2015. strings::SubstituteAndAppend(contents, " [default = $0",
  2016. DefaultValueAsString(true));
  2017. }
  2018. string formatted_options;
  2019. if (FormatBracketedOptions(depth, options(), &formatted_options)) {
  2020. contents->append(bracketed ? ", " : " [");
  2021. bracketed = true;
  2022. contents->append(formatted_options);
  2023. }
  2024. if (bracketed) {
  2025. contents->append("]");
  2026. }
  2027. if (type() == TYPE_GROUP) {
  2028. if (debug_string_options.elide_group_body) {
  2029. contents->append(" { ... };\n");
  2030. } else {
  2031. message_type()->DebugString(depth, contents, debug_string_options,
  2032. /* include_opening_clause */ false);
  2033. }
  2034. } else {
  2035. contents->append(";\n");
  2036. }
  2037. comment_printer.AddPostComment(contents);
  2038. }
  2039. string OneofDescriptor::DebugString() const {
  2040. DebugStringOptions options; // default values
  2041. return DebugStringWithOptions(options);
  2042. }
  2043. string OneofDescriptor::DebugStringWithOptions(
  2044. const DebugStringOptions& options) const {
  2045. string contents;
  2046. DebugString(0, &contents, options);
  2047. return contents;
  2048. }
  2049. void OneofDescriptor::DebugString(int depth, string* contents,
  2050. const DebugStringOptions&
  2051. debug_string_options) const {
  2052. string prefix(depth * 2, ' ');
  2053. ++depth;
  2054. SourceLocationCommentPrinter
  2055. comment_printer(this, prefix, debug_string_options);
  2056. comment_printer.AddPreComment(contents);
  2057. strings::SubstituteAndAppend(
  2058. contents, "$0 oneof $1 {", prefix, name());
  2059. if (debug_string_options.elide_oneof_body) {
  2060. contents->append(" ... }\n");
  2061. } else {
  2062. for (int i = 0; i < field_count(); i++) {
  2063. field(i)->DebugString(depth, FieldDescriptor::OMIT_LABEL, contents,
  2064. debug_string_options);
  2065. }
  2066. strings::SubstituteAndAppend(contents, "$0}\n", prefix);
  2067. }
  2068. comment_printer.AddPostComment(contents);
  2069. }
  2070. string EnumDescriptor::DebugString() const {
  2071. DebugStringOptions options; // default values
  2072. return DebugStringWithOptions(options);
  2073. }
  2074. string EnumDescriptor::DebugStringWithOptions(
  2075. const DebugStringOptions& options) const {
  2076. string contents;
  2077. DebugString(0, &contents, options);
  2078. return contents;
  2079. }
  2080. void EnumDescriptor::DebugString(int depth, string *contents,
  2081. const DebugStringOptions&
  2082. debug_string_options) const {
  2083. string prefix(depth * 2, ' ');
  2084. ++depth;
  2085. SourceLocationCommentPrinter
  2086. comment_printer(this, prefix, debug_string_options);
  2087. comment_printer.AddPreComment(contents);
  2088. strings::SubstituteAndAppend(contents, "$0enum $1 {\n",
  2089. prefix, name());
  2090. FormatLineOptions(depth, options(), contents);
  2091. for (int i = 0; i < value_count(); i++) {
  2092. value(i)->DebugString(depth, contents, debug_string_options);
  2093. }
  2094. strings::SubstituteAndAppend(contents, "$0}\n", prefix);
  2095. comment_printer.AddPostComment(contents);
  2096. }
  2097. string EnumValueDescriptor::DebugString() const {
  2098. DebugStringOptions options; // default values
  2099. return DebugStringWithOptions(options);
  2100. }
  2101. string EnumValueDescriptor::DebugStringWithOptions(
  2102. const DebugStringOptions& options) const {
  2103. string contents;
  2104. DebugString(0, &contents, options);
  2105. return contents;
  2106. }
  2107. void EnumValueDescriptor::DebugString(int depth, string *contents,
  2108. const DebugStringOptions&
  2109. debug_string_options) const {
  2110. string prefix(depth * 2, ' ');
  2111. SourceLocationCommentPrinter
  2112. comment_printer(this, prefix, debug_string_options);
  2113. comment_printer.AddPreComment(contents);
  2114. strings::SubstituteAndAppend(contents, "$0$1 = $2",
  2115. prefix, name(), number());
  2116. string formatted_options;
  2117. if (FormatBracketedOptions(depth, options(), &formatted_options)) {
  2118. strings::SubstituteAndAppend(contents, " [$0]", formatted_options);
  2119. }
  2120. contents->append(";\n");
  2121. comment_printer.AddPostComment(contents);
  2122. }
  2123. string ServiceDescriptor::DebugString() const {
  2124. DebugStringOptions options; // default values
  2125. return DebugStringWithOptions(options);
  2126. }
  2127. string ServiceDescriptor::DebugStringWithOptions(
  2128. const DebugStringOptions& options) const {
  2129. string contents;
  2130. DebugString(&contents, options);
  2131. return contents;
  2132. }
  2133. void ServiceDescriptor::DebugString(string *contents,
  2134. const DebugStringOptions&
  2135. debug_string_options) const {
  2136. SourceLocationCommentPrinter
  2137. comment_printer(this, /* prefix */ "", debug_string_options);
  2138. comment_printer.AddPreComment(contents);
  2139. strings::SubstituteAndAppend(contents, "service $0 {\n", name());
  2140. FormatLineOptions(1, options(), contents);
  2141. for (int i = 0; i < method_count(); i++) {
  2142. method(i)->DebugString(1, contents, debug_string_options);
  2143. }
  2144. contents->append("}\n");
  2145. comment_printer.AddPostComment(contents);
  2146. }
  2147. string MethodDescriptor::DebugString() const {
  2148. DebugStringOptions options; // default values
  2149. return DebugStringWithOptions(options);
  2150. }
  2151. string MethodDescriptor::DebugStringWithOptions(
  2152. const DebugStringOptions& options) const {
  2153. string contents;
  2154. DebugString(0, &contents, options);
  2155. return contents;
  2156. }
  2157. void MethodDescriptor::DebugString(int depth, string *contents,
  2158. const DebugStringOptions&
  2159. debug_string_options) const {
  2160. string prefix(depth * 2, ' ');
  2161. ++depth;
  2162. SourceLocationCommentPrinter
  2163. comment_printer(this, prefix, debug_string_options);
  2164. comment_printer.AddPreComment(contents);
  2165. strings::SubstituteAndAppend(contents, "$0rpc $1($4.$2) returns ($5.$3)",
  2166. prefix, name(),
  2167. input_type()->full_name(),
  2168. output_type()->full_name(),
  2169. client_streaming() ? "stream " : "",
  2170. server_streaming() ? "stream " : "");
  2171. string formatted_options;
  2172. if (FormatLineOptions(depth, options(), &formatted_options)) {
  2173. strings::SubstituteAndAppend(contents, " {\n$0$1}\n",
  2174. formatted_options, prefix);
  2175. } else {
  2176. contents->append(";\n");
  2177. }
  2178. comment_printer.AddPostComment(contents);
  2179. }
  2180. // Location methods ===============================================
  2181. bool FileDescriptor::GetSourceLocation(const vector<int>& path,
  2182. SourceLocation* out_location) const {
  2183. GOOGLE_CHECK_NOTNULL(out_location);
  2184. if (source_code_info_) {
  2185. if (const SourceCodeInfo_Location* loc =
  2186. tables_->GetSourceLocation(path, source_code_info_)) {
  2187. const RepeatedField<int32>& span = loc->span();
  2188. if (span.size() == 3 || span.size() == 4) {
  2189. out_location->start_line = span.Get(0);
  2190. out_location->start_column = span.Get(1);
  2191. out_location->end_line = span.Get(span.size() == 3 ? 0 : 2);
  2192. out_location->end_column = span.Get(span.size() - 1);
  2193. out_location->leading_comments = loc->leading_comments();
  2194. out_location->trailing_comments = loc->trailing_comments();
  2195. out_location->leading_detached_comments.assign(
  2196. loc->leading_detached_comments().begin(),
  2197. loc->leading_detached_comments().end());
  2198. return true;
  2199. }
  2200. }
  2201. }
  2202. return false;
  2203. }
  2204. bool FileDescriptor::GetSourceLocation(SourceLocation* out_location) const {
  2205. vector<int> path; // empty path for root FileDescriptor
  2206. return GetSourceLocation(path, out_location);
  2207. }
  2208. bool FieldDescriptor::is_packed() const {
  2209. if (!is_packable()) return false;
  2210. if (file_->syntax() == FileDescriptor::SYNTAX_PROTO2) {
  2211. return (options_ != NULL) && options_->packed();
  2212. } else {
  2213. return options_ == NULL || !options_->has_packed() || options_->packed();
  2214. }
  2215. }
  2216. bool Descriptor::GetSourceLocation(SourceLocation* out_location) const {
  2217. vector<int> path;
  2218. GetLocationPath(&path);
  2219. return file()->GetSourceLocation(path, out_location);
  2220. }
  2221. bool FieldDescriptor::GetSourceLocation(SourceLocation* out_location) const {
  2222. vector<int> path;
  2223. GetLocationPath(&path);
  2224. return file()->GetSourceLocation(path, out_location);
  2225. }
  2226. bool OneofDescriptor::GetSourceLocation(SourceLocation* out_location) const {
  2227. vector<int> path;
  2228. GetLocationPath(&path);
  2229. return containing_type()->file()->GetSourceLocation(path, out_location);
  2230. }
  2231. bool EnumDescriptor::GetSourceLocation(SourceLocation* out_location) const {
  2232. vector<int> path;
  2233. GetLocationPath(&path);
  2234. return file()->GetSourceLocation(path, out_location);
  2235. }
  2236. bool MethodDescriptor::GetSourceLocation(SourceLocation* out_location) const {
  2237. vector<int> path;
  2238. GetLocationPath(&path);
  2239. return service()->file()->GetSourceLocation(path, out_location);
  2240. }
  2241. bool ServiceDescriptor::GetSourceLocation(SourceLocation* out_location) const {
  2242. vector<int> path;
  2243. GetLocationPath(&path);
  2244. return file()->GetSourceLocation(path, out_location);
  2245. }
  2246. bool EnumValueDescriptor::GetSourceLocation(
  2247. SourceLocation* out_location) const {
  2248. vector<int> path;
  2249. GetLocationPath(&path);
  2250. return type()->file()->GetSourceLocation(path, out_location);
  2251. }
  2252. void Descriptor::GetLocationPath(vector<int>* output) const {
  2253. if (containing_type()) {
  2254. containing_type()->GetLocationPath(output);
  2255. output->push_back(DescriptorProto::kNestedTypeFieldNumber);
  2256. output->push_back(index());
  2257. } else {
  2258. output->push_back(FileDescriptorProto::kMessageTypeFieldNumber);
  2259. output->push_back(index());
  2260. }
  2261. }
  2262. void FieldDescriptor::GetLocationPath(vector<int>* output) const {
  2263. if (is_extension()) {
  2264. if (extension_scope() == NULL) {
  2265. output->push_back(FileDescriptorProto::kExtensionFieldNumber);
  2266. output->push_back(index());
  2267. } else {
  2268. extension_scope()->GetLocationPath(output);
  2269. output->push_back(DescriptorProto::kExtensionFieldNumber);
  2270. output->push_back(index());
  2271. }
  2272. } else {
  2273. containing_type()->GetLocationPath(output);
  2274. output->push_back(DescriptorProto::kFieldFieldNumber);
  2275. output->push_back(index());
  2276. }
  2277. }
  2278. void OneofDescriptor::GetLocationPath(vector<int>* output) const {
  2279. containing_type()->GetLocationPath(output);
  2280. output->push_back(DescriptorProto::kOneofDeclFieldNumber);
  2281. output->push_back(index());
  2282. }
  2283. void EnumDescriptor::GetLocationPath(vector<int>* output) const {
  2284. if (containing_type()) {
  2285. containing_type()->GetLocationPath(output);
  2286. output->push_back(DescriptorProto::kEnumTypeFieldNumber);
  2287. output->push_back(index());
  2288. } else {
  2289. output->push_back(FileDescriptorProto::kEnumTypeFieldNumber);
  2290. output->push_back(index());
  2291. }
  2292. }
  2293. void EnumValueDescriptor::GetLocationPath(vector<int>* output) const {
  2294. type()->GetLocationPath(output);
  2295. output->push_back(EnumDescriptorProto::kValueFieldNumber);
  2296. output->push_back(index());
  2297. }
  2298. void ServiceDescriptor::GetLocationPath(vector<int>* output) const {
  2299. output->push_back(FileDescriptorProto::kServiceFieldNumber);
  2300. output->push_back(index());
  2301. }
  2302. void MethodDescriptor::GetLocationPath(vector<int>* output) const {
  2303. service()->GetLocationPath(output);
  2304. output->push_back(ServiceDescriptorProto::kMethodFieldNumber);
  2305. output->push_back(index());
  2306. }
  2307. // ===================================================================
  2308. namespace {
  2309. // Represents an options message to interpret. Extension names in the option
  2310. // name are resolved relative to name_scope. element_name and orig_opt are
  2311. // used only for error reporting (since the parser records locations against
  2312. // pointers in the original options, not the mutable copy). The Message must be
  2313. // one of the Options messages in descriptor.proto.
  2314. struct OptionsToInterpret {
  2315. OptionsToInterpret(const string& ns,
  2316. const string& el,
  2317. const Message* orig_opt,
  2318. Message* opt)
  2319. : name_scope(ns),
  2320. element_name(el),
  2321. original_options(orig_opt),
  2322. options(opt) {
  2323. }
  2324. string name_scope;
  2325. string element_name;
  2326. const Message* original_options;
  2327. Message* options;
  2328. };
  2329. } // namespace
  2330. class DescriptorBuilder {
  2331. public:
  2332. DescriptorBuilder(const DescriptorPool* pool,
  2333. DescriptorPool::Tables* tables,
  2334. DescriptorPool::ErrorCollector* error_collector);
  2335. ~DescriptorBuilder();
  2336. const FileDescriptor* BuildFile(const FileDescriptorProto& proto);
  2337. private:
  2338. friend class OptionInterpreter;
  2339. const DescriptorPool* pool_;
  2340. DescriptorPool::Tables* tables_; // for convenience
  2341. DescriptorPool::ErrorCollector* error_collector_;
  2342. // As we build descriptors we store copies of the options messages in
  2343. // them. We put pointers to those copies in this vector, as we build, so we
  2344. // can later (after cross-linking) interpret those options.
  2345. vector<OptionsToInterpret> options_to_interpret_;
  2346. bool had_errors_;
  2347. string filename_;
  2348. FileDescriptor* file_;
  2349. FileDescriptorTables* file_tables_;
  2350. set<const FileDescriptor*> dependencies_;
  2351. // unused_dependency_ is used to record the unused imported files.
  2352. // Note: public import is not considered.
  2353. set<const FileDescriptor*> unused_dependency_;
  2354. // If LookupSymbol() finds a symbol that is in a file which is not a declared
  2355. // dependency of this file, it will fail, but will set
  2356. // possible_undeclared_dependency_ to point at that file. This is only used
  2357. // by AddNotDefinedError() to report a more useful error message.
  2358. // possible_undeclared_dependency_name_ is the name of the symbol that was
  2359. // actually found in possible_undeclared_dependency_, which may be a parent
  2360. // of the symbol actually looked for.
  2361. const FileDescriptor* possible_undeclared_dependency_;
  2362. string possible_undeclared_dependency_name_;
  2363. // If LookupSymbol() could resolve a symbol which is not defined,
  2364. // record the resolved name. This is only used by AddNotDefinedError()
  2365. // to report a more useful error message.
  2366. string undefine_resolved_name_;
  2367. void AddError(const string& element_name,
  2368. const Message& descriptor,
  2369. DescriptorPool::ErrorCollector::ErrorLocation location,
  2370. const string& error);
  2371. void AddError(const string& element_name,
  2372. const Message& descriptor,
  2373. DescriptorPool::ErrorCollector::ErrorLocation location,
  2374. const char* error);
  2375. void AddRecursiveImportError(const FileDescriptorProto& proto, int from_here);
  2376. void AddTwiceListedError(const FileDescriptorProto& proto, int index);
  2377. void AddImportError(const FileDescriptorProto& proto, int index);
  2378. // Adds an error indicating that undefined_symbol was not defined. Must
  2379. // only be called after LookupSymbol() fails.
  2380. void AddNotDefinedError(
  2381. const string& element_name,
  2382. const Message& descriptor,
  2383. DescriptorPool::ErrorCollector::ErrorLocation location,
  2384. const string& undefined_symbol);
  2385. void AddWarning(const string& element_name, const Message& descriptor,
  2386. DescriptorPool::ErrorCollector::ErrorLocation location,
  2387. const string& error);
  2388. // Silly helper which determines if the given file is in the given package.
  2389. // I.e., either file->package() == package_name or file->package() is a
  2390. // nested package within package_name.
  2391. bool IsInPackage(const FileDescriptor* file, const string& package_name);
  2392. // Helper function which finds all public dependencies of the given file, and
  2393. // stores the them in the dependencies_ set in the builder.
  2394. void RecordPublicDependencies(const FileDescriptor* file);
  2395. // Like tables_->FindSymbol(), but additionally:
  2396. // - Search the pool's underlay if not found in tables_.
  2397. // - Insure that the resulting Symbol is from one of the file's declared
  2398. // dependencies.
  2399. Symbol FindSymbol(const string& name);
  2400. // Like FindSymbol() but does not require that the symbol is in one of the
  2401. // file's declared dependencies.
  2402. Symbol FindSymbolNotEnforcingDeps(const string& name);
  2403. // This implements the body of FindSymbolNotEnforcingDeps().
  2404. Symbol FindSymbolNotEnforcingDepsHelper(const DescriptorPool* pool,
  2405. const string& name);
  2406. // Like FindSymbol(), but looks up the name relative to some other symbol
  2407. // name. This first searches siblings of relative_to, then siblings of its
  2408. // parents, etc. For example, LookupSymbol("foo.bar", "baz.qux.corge") makes
  2409. // the following calls, returning the first non-null result:
  2410. // FindSymbol("baz.qux.foo.bar"), FindSymbol("baz.foo.bar"),
  2411. // FindSymbol("foo.bar"). If AllowUnknownDependencies() has been called
  2412. // on the DescriptorPool, this will generate a placeholder type if
  2413. // the name is not found (unless the name itself is malformed). The
  2414. // placeholder_type parameter indicates what kind of placeholder should be
  2415. // constructed in this case. The resolve_mode parameter determines whether
  2416. // any symbol is returned, or only symbols that are types. Note, however,
  2417. // that LookupSymbol may still return a non-type symbol in LOOKUP_TYPES mode,
  2418. // if it believes that's all it could refer to. The caller should always
  2419. // check that it receives the type of symbol it was expecting.
  2420. enum PlaceholderType {
  2421. PLACEHOLDER_MESSAGE,
  2422. PLACEHOLDER_ENUM,
  2423. PLACEHOLDER_EXTENDABLE_MESSAGE
  2424. };
  2425. enum ResolveMode {
  2426. LOOKUP_ALL, LOOKUP_TYPES
  2427. };
  2428. Symbol LookupSymbol(const string& name, const string& relative_to,
  2429. PlaceholderType placeholder_type = PLACEHOLDER_MESSAGE,
  2430. ResolveMode resolve_mode = LOOKUP_ALL);
  2431. // Like LookupSymbol() but will not return a placeholder even if
  2432. // AllowUnknownDependencies() has been used.
  2433. Symbol LookupSymbolNoPlaceholder(const string& name,
  2434. const string& relative_to,
  2435. ResolveMode resolve_mode = LOOKUP_ALL);
  2436. // Creates a placeholder type suitable for return from LookupSymbol(). May
  2437. // return kNullSymbol if the name is not a valid type name.
  2438. Symbol NewPlaceholder(const string& name, PlaceholderType placeholder_type);
  2439. // Creates a placeholder file. Never returns NULL. This is used when an
  2440. // import is not found and AllowUnknownDependencies() is enabled.
  2441. FileDescriptor* NewPlaceholderFile(const string& name);
  2442. // Calls tables_->AddSymbol() and records an error if it fails. Returns
  2443. // true if successful or false if failed, though most callers can ignore
  2444. // the return value since an error has already been recorded.
  2445. bool AddSymbol(const string& full_name,
  2446. const void* parent, const string& name,
  2447. const Message& proto, Symbol symbol);
  2448. // Like AddSymbol(), but succeeds if the symbol is already defined as long
  2449. // as the existing definition is also a package (because it's OK to define
  2450. // the same package in two different files). Also adds all parents of the
  2451. // packgae to the symbol table (e.g. AddPackage("foo.bar", ...) will add
  2452. // "foo.bar" and "foo" to the table).
  2453. void AddPackage(const string& name, const Message& proto,
  2454. const FileDescriptor* file);
  2455. // Checks that the symbol name contains only alphanumeric characters and
  2456. // underscores. Records an error otherwise.
  2457. void ValidateSymbolName(const string& name, const string& full_name,
  2458. const Message& proto);
  2459. // Like ValidateSymbolName(), but the name is allowed to contain periods and
  2460. // an error is indicated by returning false (not recording the error).
  2461. bool ValidateQualifiedName(const string& name);
  2462. // Used by BUILD_ARRAY macro (below) to avoid having to have the type
  2463. // specified as a macro parameter.
  2464. template <typename Type>
  2465. inline void AllocateArray(int size, Type** output) {
  2466. *output = tables_->AllocateArray<Type>(size);
  2467. }
  2468. // Allocates a copy of orig_options in tables_ and stores it in the
  2469. // descriptor. Remembers its uninterpreted options, to be interpreted
  2470. // later. DescriptorT must be one of the Descriptor messages from
  2471. // descriptor.proto.
  2472. template<class DescriptorT> void AllocateOptions(
  2473. const typename DescriptorT::OptionsType& orig_options,
  2474. DescriptorT* descriptor);
  2475. // Specialization for FileOptions.
  2476. void AllocateOptions(const FileOptions& orig_options,
  2477. FileDescriptor* descriptor);
  2478. // Implementation for AllocateOptions(). Don't call this directly.
  2479. template<class DescriptorT> void AllocateOptionsImpl(
  2480. const string& name_scope,
  2481. const string& element_name,
  2482. const typename DescriptorT::OptionsType& orig_options,
  2483. DescriptorT* descriptor);
  2484. // These methods all have the same signature for the sake of the BUILD_ARRAY
  2485. // macro, below.
  2486. void BuildMessage(const DescriptorProto& proto,
  2487. const Descriptor* parent,
  2488. Descriptor* result);
  2489. void BuildFieldOrExtension(const FieldDescriptorProto& proto,
  2490. const Descriptor* parent,
  2491. FieldDescriptor* result,
  2492. bool is_extension);
  2493. void BuildField(const FieldDescriptorProto& proto,
  2494. const Descriptor* parent,
  2495. FieldDescriptor* result) {
  2496. BuildFieldOrExtension(proto, parent, result, false);
  2497. }
  2498. void BuildExtension(const FieldDescriptorProto& proto,
  2499. const Descriptor* parent,
  2500. FieldDescriptor* result) {
  2501. BuildFieldOrExtension(proto, parent, result, true);
  2502. }
  2503. void BuildExtensionRange(const DescriptorProto::ExtensionRange& proto,
  2504. const Descriptor* parent,
  2505. Descriptor::ExtensionRange* result);
  2506. void BuildReservedRange(const DescriptorProto::ReservedRange& proto,
  2507. const Descriptor* parent,
  2508. Descriptor::ReservedRange* result);
  2509. void BuildOneof(const OneofDescriptorProto& proto,
  2510. Descriptor* parent,
  2511. OneofDescriptor* result);
  2512. void BuildEnum(const EnumDescriptorProto& proto,
  2513. const Descriptor* parent,
  2514. EnumDescriptor* result);
  2515. void BuildEnumValue(const EnumValueDescriptorProto& proto,
  2516. const EnumDescriptor* parent,
  2517. EnumValueDescriptor* result);
  2518. void BuildService(const ServiceDescriptorProto& proto,
  2519. const void* dummy,
  2520. ServiceDescriptor* result);
  2521. void BuildMethod(const MethodDescriptorProto& proto,
  2522. const ServiceDescriptor* parent,
  2523. MethodDescriptor* result);
  2524. void LogUnusedDependency(const FileDescriptor* result);
  2525. // Must be run only after building.
  2526. //
  2527. // NOTE: Options will not be available during cross-linking, as they
  2528. // have not yet been interpreted. Defer any handling of options to the
  2529. // Validate*Options methods.
  2530. void CrossLinkFile(FileDescriptor* file, const FileDescriptorProto& proto);
  2531. void CrossLinkMessage(Descriptor* message, const DescriptorProto& proto);
  2532. void CrossLinkField(FieldDescriptor* field,
  2533. const FieldDescriptorProto& proto);
  2534. void CrossLinkEnum(EnumDescriptor* enum_type,
  2535. const EnumDescriptorProto& proto);
  2536. void CrossLinkEnumValue(EnumValueDescriptor* enum_value,
  2537. const EnumValueDescriptorProto& proto);
  2538. void CrossLinkService(ServiceDescriptor* service,
  2539. const ServiceDescriptorProto& proto);
  2540. void CrossLinkMethod(MethodDescriptor* method,
  2541. const MethodDescriptorProto& proto);
  2542. // Must be run only after cross-linking.
  2543. void InterpretOptions();
  2544. // A helper class for interpreting options.
  2545. class OptionInterpreter {
  2546. public:
  2547. // Creates an interpreter that operates in the context of the pool of the
  2548. // specified builder, which must not be NULL. We don't take ownership of the
  2549. // builder.
  2550. explicit OptionInterpreter(DescriptorBuilder* builder);
  2551. ~OptionInterpreter();
  2552. // Interprets the uninterpreted options in the specified Options message.
  2553. // On error, calls AddError() on the underlying builder and returns false.
  2554. // Otherwise returns true.
  2555. bool InterpretOptions(OptionsToInterpret* options_to_interpret);
  2556. class AggregateOptionFinder;
  2557. private:
  2558. // Interprets uninterpreted_option_ on the specified message, which
  2559. // must be the mutable copy of the original options message to which
  2560. // uninterpreted_option_ belongs.
  2561. bool InterpretSingleOption(Message* options);
  2562. // Adds the uninterpreted_option to the given options message verbatim.
  2563. // Used when AllowUnknownDependencies() is in effect and we can't find
  2564. // the option's definition.
  2565. void AddWithoutInterpreting(const UninterpretedOption& uninterpreted_option,
  2566. Message* options);
  2567. // A recursive helper function that drills into the intermediate fields
  2568. // in unknown_fields to check if field innermost_field is set on the
  2569. // innermost message. Returns false and sets an error if so.
  2570. bool ExamineIfOptionIsSet(
  2571. vector<const FieldDescriptor*>::const_iterator intermediate_fields_iter,
  2572. vector<const FieldDescriptor*>::const_iterator intermediate_fields_end,
  2573. const FieldDescriptor* innermost_field, const string& debug_msg_name,
  2574. const UnknownFieldSet& unknown_fields);
  2575. // Validates the value for the option field of the currently interpreted
  2576. // option and then sets it on the unknown_field.
  2577. bool SetOptionValue(const FieldDescriptor* option_field,
  2578. UnknownFieldSet* unknown_fields);
  2579. // Parses an aggregate value for a CPPTYPE_MESSAGE option and
  2580. // saves it into *unknown_fields.
  2581. bool SetAggregateOption(const FieldDescriptor* option_field,
  2582. UnknownFieldSet* unknown_fields);
  2583. // Convenience functions to set an int field the right way, depending on
  2584. // its wire type (a single int CppType can represent multiple wire types).
  2585. void SetInt32(int number, int32 value, FieldDescriptor::Type type,
  2586. UnknownFieldSet* unknown_fields);
  2587. void SetInt64(int number, int64 value, FieldDescriptor::Type type,
  2588. UnknownFieldSet* unknown_fields);
  2589. void SetUInt32(int number, uint32 value, FieldDescriptor::Type type,
  2590. UnknownFieldSet* unknown_fields);
  2591. void SetUInt64(int number, uint64 value, FieldDescriptor::Type type,
  2592. UnknownFieldSet* unknown_fields);
  2593. // A helper function that adds an error at the specified location of the
  2594. // option we're currently interpreting, and returns false.
  2595. bool AddOptionError(DescriptorPool::ErrorCollector::ErrorLocation location,
  2596. const string& msg) {
  2597. builder_->AddError(options_to_interpret_->element_name,
  2598. *uninterpreted_option_, location, msg);
  2599. return false;
  2600. }
  2601. // A helper function that adds an error at the location of the option name
  2602. // and returns false.
  2603. bool AddNameError(const string& msg) {
  2604. return AddOptionError(DescriptorPool::ErrorCollector::OPTION_NAME, msg);
  2605. }
  2606. // A helper function that adds an error at the location of the option name
  2607. // and returns false.
  2608. bool AddValueError(const string& msg) {
  2609. return AddOptionError(DescriptorPool::ErrorCollector::OPTION_VALUE, msg);
  2610. }
  2611. // We interpret against this builder's pool. Is never NULL. We don't own
  2612. // this pointer.
  2613. DescriptorBuilder* builder_;
  2614. // The options we're currently interpreting, or NULL if we're not in a call
  2615. // to InterpretOptions.
  2616. const OptionsToInterpret* options_to_interpret_;
  2617. // The option we're currently interpreting within options_to_interpret_, or
  2618. // NULL if we're not in a call to InterpretOptions(). This points to a
  2619. // submessage of the original option, not the mutable copy. Therefore we
  2620. // can use it to find locations recorded by the parser.
  2621. const UninterpretedOption* uninterpreted_option_;
  2622. // Factory used to create the dynamic messages we need to parse
  2623. // any aggregate option values we encounter.
  2624. DynamicMessageFactory dynamic_factory_;
  2625. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OptionInterpreter);
  2626. };
  2627. // Work-around for broken compilers: According to the C++ standard,
  2628. // OptionInterpreter should have access to the private members of any class
  2629. // which has declared DescriptorBuilder as a friend. Unfortunately some old
  2630. // versions of GCC and other compilers do not implement this correctly. So,
  2631. // we have to have these intermediate methods to provide access. We also
  2632. // redundantly declare OptionInterpreter a friend just to make things extra
  2633. // clear for these bad compilers.
  2634. friend class OptionInterpreter;
  2635. friend class OptionInterpreter::AggregateOptionFinder;
  2636. static inline bool get_allow_unknown(const DescriptorPool* pool) {
  2637. return pool->allow_unknown_;
  2638. }
  2639. static inline bool get_enforce_weak(const DescriptorPool* pool) {
  2640. return pool->enforce_weak_;
  2641. }
  2642. static inline bool get_is_placeholder(const Descriptor* descriptor) {
  2643. return descriptor->is_placeholder_;
  2644. }
  2645. static inline void assert_mutex_held(const DescriptorPool* pool) {
  2646. if (pool->mutex_ != NULL) {
  2647. pool->mutex_->AssertHeld();
  2648. }
  2649. }
  2650. // Must be run only after options have been interpreted.
  2651. //
  2652. // NOTE: Validation code must only reference the options in the mutable
  2653. // descriptors, which are the ones that have been interpreted. The const
  2654. // proto references are passed in only so they can be provided to calls to
  2655. // AddError(). Do not look at their options, which have not been interpreted.
  2656. void ValidateFileOptions(FileDescriptor* file,
  2657. const FileDescriptorProto& proto);
  2658. void ValidateMessageOptions(Descriptor* message,
  2659. const DescriptorProto& proto);
  2660. void ValidateFieldOptions(FieldDescriptor* field,
  2661. const FieldDescriptorProto& proto);
  2662. void ValidateEnumOptions(EnumDescriptor* enm,
  2663. const EnumDescriptorProto& proto);
  2664. void ValidateEnumValueOptions(EnumValueDescriptor* enum_value,
  2665. const EnumValueDescriptorProto& proto);
  2666. void ValidateServiceOptions(ServiceDescriptor* service,
  2667. const ServiceDescriptorProto& proto);
  2668. void ValidateMethodOptions(MethodDescriptor* method,
  2669. const MethodDescriptorProto& proto);
  2670. void ValidateProto3(FileDescriptor* file,
  2671. const FileDescriptorProto& proto);
  2672. void ValidateProto3Message(Descriptor* message,
  2673. const DescriptorProto& proto);
  2674. void ValidateProto3Field(FieldDescriptor* field,
  2675. const FieldDescriptorProto& proto);
  2676. void ValidateProto3Enum(EnumDescriptor* enm,
  2677. const EnumDescriptorProto& proto);
  2678. // Returns true if the map entry message is compatible with the
  2679. // auto-generated entry message from map fields syntax.
  2680. bool ValidateMapEntry(FieldDescriptor* field,
  2681. const FieldDescriptorProto& proto);
  2682. // Recursively detects naming conflicts with map entry types for a
  2683. // better error message.
  2684. void DetectMapConflicts(const Descriptor* message,
  2685. const DescriptorProto& proto);
  2686. };
  2687. const FileDescriptor* DescriptorPool::BuildFile(
  2688. const FileDescriptorProto& proto) {
  2689. GOOGLE_CHECK(fallback_database_ == NULL)
  2690. << "Cannot call BuildFile on a DescriptorPool that uses a "
  2691. "DescriptorDatabase. You must instead find a way to get your file "
  2692. "into the underlying database.";
  2693. GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK.
  2694. tables_->known_bad_symbols_.clear();
  2695. tables_->known_bad_files_.clear();
  2696. return DescriptorBuilder(this, tables_.get(), NULL).BuildFile(proto);
  2697. }
  2698. const FileDescriptor* DescriptorPool::BuildFileCollectingErrors(
  2699. const FileDescriptorProto& proto,
  2700. ErrorCollector* error_collector) {
  2701. GOOGLE_CHECK(fallback_database_ == NULL)
  2702. << "Cannot call BuildFile on a DescriptorPool that uses a "
  2703. "DescriptorDatabase. You must instead find a way to get your file "
  2704. "into the underlying database.";
  2705. GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK.
  2706. tables_->known_bad_symbols_.clear();
  2707. tables_->known_bad_files_.clear();
  2708. return DescriptorBuilder(this, tables_.get(),
  2709. error_collector).BuildFile(proto);
  2710. }
  2711. const FileDescriptor* DescriptorPool::BuildFileFromDatabase(
  2712. const FileDescriptorProto& proto) const {
  2713. mutex_->AssertHeld();
  2714. if (tables_->known_bad_files_.count(proto.name()) > 0) {
  2715. return NULL;
  2716. }
  2717. const FileDescriptor* result =
  2718. DescriptorBuilder(this, tables_.get(),
  2719. default_error_collector_).BuildFile(proto);
  2720. if (result == NULL) {
  2721. tables_->known_bad_files_.insert(proto.name());
  2722. }
  2723. return result;
  2724. }
  2725. DescriptorBuilder::DescriptorBuilder(
  2726. const DescriptorPool* pool,
  2727. DescriptorPool::Tables* tables,
  2728. DescriptorPool::ErrorCollector* error_collector)
  2729. : pool_(pool),
  2730. tables_(tables),
  2731. error_collector_(error_collector),
  2732. had_errors_(false),
  2733. possible_undeclared_dependency_(NULL),
  2734. undefine_resolved_name_("") {}
  2735. DescriptorBuilder::~DescriptorBuilder() {}
  2736. void DescriptorBuilder::AddError(
  2737. const string& element_name,
  2738. const Message& descriptor,
  2739. DescriptorPool::ErrorCollector::ErrorLocation location,
  2740. const string& error) {
  2741. if (error_collector_ == NULL) {
  2742. if (!had_errors_) {
  2743. GOOGLE_LOG(ERROR) << "Invalid proto descriptor for file \"" << filename_
  2744. << "\":";
  2745. }
  2746. GOOGLE_LOG(ERROR) << " " << element_name << ": " << error;
  2747. } else {
  2748. error_collector_->AddError(filename_, element_name,
  2749. &descriptor, location, error);
  2750. }
  2751. had_errors_ = true;
  2752. }
  2753. void DescriptorBuilder::AddError(
  2754. const string& element_name,
  2755. const Message& descriptor,
  2756. DescriptorPool::ErrorCollector::ErrorLocation location,
  2757. const char* error) {
  2758. AddError(element_name, descriptor, location, string(error));
  2759. }
  2760. void DescriptorBuilder::AddNotDefinedError(
  2761. const string& element_name,
  2762. const Message& descriptor,
  2763. DescriptorPool::ErrorCollector::ErrorLocation location,
  2764. const string& undefined_symbol) {
  2765. if (possible_undeclared_dependency_ == NULL &&
  2766. undefine_resolved_name_.empty()) {
  2767. AddError(element_name, descriptor, location,
  2768. "\"" + undefined_symbol + "\" is not defined.");
  2769. } else {
  2770. if (possible_undeclared_dependency_ != NULL) {
  2771. AddError(element_name, descriptor, location,
  2772. "\"" + possible_undeclared_dependency_name_ +
  2773. "\" seems to be defined in \"" +
  2774. possible_undeclared_dependency_->name() + "\", which is not "
  2775. "imported by \"" + filename_ + "\". To use it here, please "
  2776. "add the necessary import.");
  2777. }
  2778. if (!undefine_resolved_name_.empty()) {
  2779. AddError(element_name, descriptor, location,
  2780. "\"" + undefined_symbol + "\" is resolved to \"" +
  2781. undefine_resolved_name_ + "\", which is not defined. "
  2782. "The innermost scope is searched first in name resolution. "
  2783. "Consider using a leading '.'(i.e., \"."
  2784. + undefined_symbol +
  2785. "\") to start from the outermost scope.");
  2786. }
  2787. }
  2788. }
  2789. void DescriptorBuilder::AddWarning(
  2790. const string& element_name, const Message& descriptor,
  2791. DescriptorPool::ErrorCollector::ErrorLocation location,
  2792. const string& error) {
  2793. if (error_collector_ == NULL) {
  2794. GOOGLE_LOG(WARNING) << filename_ << " " << element_name << ": " << error;
  2795. } else {
  2796. error_collector_->AddWarning(filename_, element_name, &descriptor, location,
  2797. error);
  2798. }
  2799. }
  2800. bool DescriptorBuilder::IsInPackage(const FileDescriptor* file,
  2801. const string& package_name) {
  2802. return HasPrefixString(file->package(), package_name) &&
  2803. (file->package().size() == package_name.size() ||
  2804. file->package()[package_name.size()] == '.');
  2805. }
  2806. void DescriptorBuilder::RecordPublicDependencies(const FileDescriptor* file) {
  2807. if (file == NULL || !dependencies_.insert(file).second) return;
  2808. for (int i = 0; file != NULL && i < file->public_dependency_count(); i++) {
  2809. RecordPublicDependencies(file->public_dependency(i));
  2810. }
  2811. }
  2812. Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper(
  2813. const DescriptorPool* pool, const string& name) {
  2814. // If we are looking at an underlay, we must lock its mutex_, since we are
  2815. // accessing the underlay's tables_ directly.
  2816. MutexLockMaybe lock((pool == pool_) ? NULL : pool->mutex_);
  2817. Symbol result = pool->tables_->FindSymbol(name);
  2818. if (result.IsNull() && pool->underlay_ != NULL) {
  2819. // Symbol not found; check the underlay.
  2820. result = FindSymbolNotEnforcingDepsHelper(pool->underlay_, name);
  2821. }
  2822. if (result.IsNull()) {
  2823. // In theory, we shouldn't need to check fallback_database_ because the
  2824. // symbol should be in one of its file's direct dependencies, and we have
  2825. // already loaded those by the time we get here. But we check anyway so
  2826. // that we can generate better error message when dependencies are missing
  2827. // (i.e., "missing dependency" rather than "type is not defined").
  2828. if (pool->TryFindSymbolInFallbackDatabase(name)) {
  2829. result = pool->tables_->FindSymbol(name);
  2830. }
  2831. }
  2832. return result;
  2833. }
  2834. Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const string& name) {
  2835. return FindSymbolNotEnforcingDepsHelper(pool_, name);
  2836. }
  2837. Symbol DescriptorBuilder::FindSymbol(const string& name) {
  2838. Symbol result = FindSymbolNotEnforcingDeps(name);
  2839. if (result.IsNull()) return result;
  2840. if (!pool_->enforce_dependencies_) {
  2841. // Hack for CompilerUpgrader.
  2842. return result;
  2843. }
  2844. // Only find symbols which were defined in this file or one of its
  2845. // dependencies.
  2846. const FileDescriptor* file = result.GetFile();
  2847. if (file == file_ || dependencies_.count(file) > 0) {
  2848. unused_dependency_.erase(file);
  2849. return result;
  2850. }
  2851. if (result.type == Symbol::PACKAGE) {
  2852. // Arg, this is overcomplicated. The symbol is a package name. It could
  2853. // be that the package was defined in multiple files. result.GetFile()
  2854. // returns the first file we saw that used this package. We've determined
  2855. // that that file is not a direct dependency of the file we are currently
  2856. // building, but it could be that some other file which *is* a direct
  2857. // dependency also defines the same package. We can't really rule out this
  2858. // symbol unless none of the dependencies define it.
  2859. if (IsInPackage(file_, name)) return result;
  2860. for (set<const FileDescriptor*>::const_iterator it = dependencies_.begin();
  2861. it != dependencies_.end(); ++it) {
  2862. // Note: A dependency may be NULL if it was not found or had errors.
  2863. if (*it != NULL && IsInPackage(*it, name)) return result;
  2864. }
  2865. }
  2866. possible_undeclared_dependency_ = file;
  2867. possible_undeclared_dependency_name_ = name;
  2868. return kNullSymbol;
  2869. }
  2870. Symbol DescriptorBuilder::LookupSymbolNoPlaceholder(
  2871. const string& name, const string& relative_to, ResolveMode resolve_mode) {
  2872. possible_undeclared_dependency_ = NULL;
  2873. undefine_resolved_name_.clear();
  2874. if (name.size() > 0 && name[0] == '.') {
  2875. // Fully-qualified name.
  2876. return FindSymbol(name.substr(1));
  2877. }
  2878. // If name is something like "Foo.Bar.baz", and symbols named "Foo" are
  2879. // defined in multiple parent scopes, we only want to find "Bar.baz" in the
  2880. // innermost one. E.g., the following should produce an error:
  2881. // message Bar { message Baz {} }
  2882. // message Foo {
  2883. // message Bar {
  2884. // }
  2885. // optional Bar.Baz baz = 1;
  2886. // }
  2887. // So, we look for just "Foo" first, then look for "Bar.baz" within it if
  2888. // found.
  2889. string::size_type name_dot_pos = name.find_first_of('.');
  2890. string first_part_of_name;
  2891. if (name_dot_pos == string::npos) {
  2892. first_part_of_name = name;
  2893. } else {
  2894. first_part_of_name = name.substr(0, name_dot_pos);
  2895. }
  2896. string scope_to_try(relative_to);
  2897. while (true) {
  2898. // Chop off the last component of the scope.
  2899. string::size_type dot_pos = scope_to_try.find_last_of('.');
  2900. if (dot_pos == string::npos) {
  2901. return FindSymbol(name);
  2902. } else {
  2903. scope_to_try.erase(dot_pos);
  2904. }
  2905. // Append ".first_part_of_name" and try to find.
  2906. string::size_type old_size = scope_to_try.size();
  2907. scope_to_try.append(1, '.');
  2908. scope_to_try.append(first_part_of_name);
  2909. Symbol result = FindSymbol(scope_to_try);
  2910. if (!result.IsNull()) {
  2911. if (first_part_of_name.size() < name.size()) {
  2912. // name is a compound symbol, of which we only found the first part.
  2913. // Now try to look up the rest of it.
  2914. if (result.IsAggregate()) {
  2915. scope_to_try.append(name, first_part_of_name.size(),
  2916. name.size() - first_part_of_name.size());
  2917. result = FindSymbol(scope_to_try);
  2918. if (result.IsNull()) {
  2919. undefine_resolved_name_ = scope_to_try;
  2920. }
  2921. return result;
  2922. } else {
  2923. // We found a symbol but it's not an aggregate. Continue the loop.
  2924. }
  2925. } else {
  2926. if (resolve_mode == LOOKUP_TYPES && !result.IsType()) {
  2927. // We found a symbol but it's not a type. Continue the loop.
  2928. } else {
  2929. return result;
  2930. }
  2931. }
  2932. }
  2933. // Not found. Remove the name so we can try again.
  2934. scope_to_try.erase(old_size);
  2935. }
  2936. }
  2937. Symbol DescriptorBuilder::LookupSymbol(
  2938. const string& name, const string& relative_to,
  2939. PlaceholderType placeholder_type, ResolveMode resolve_mode) {
  2940. Symbol result = LookupSymbolNoPlaceholder(
  2941. name, relative_to, resolve_mode);
  2942. if (result.IsNull() && pool_->allow_unknown_) {
  2943. // Not found, but AllowUnknownDependencies() is enabled. Return a
  2944. // placeholder instead.
  2945. result = NewPlaceholder(name, placeholder_type);
  2946. }
  2947. return result;
  2948. }
  2949. Symbol DescriptorBuilder::NewPlaceholder(const string& name,
  2950. PlaceholderType placeholder_type) {
  2951. // Compute names.
  2952. const string* placeholder_full_name;
  2953. const string* placeholder_name;
  2954. const string* placeholder_package;
  2955. if (!ValidateQualifiedName(name)) return kNullSymbol;
  2956. if (name[0] == '.') {
  2957. // Fully-qualified.
  2958. placeholder_full_name = tables_->AllocateString(name.substr(1));
  2959. } else {
  2960. placeholder_full_name = tables_->AllocateString(name);
  2961. }
  2962. string::size_type dotpos = placeholder_full_name->find_last_of('.');
  2963. if (dotpos != string::npos) {
  2964. placeholder_package = tables_->AllocateString(
  2965. placeholder_full_name->substr(0, dotpos));
  2966. placeholder_name = tables_->AllocateString(
  2967. placeholder_full_name->substr(dotpos + 1));
  2968. } else {
  2969. placeholder_package = &internal::GetEmptyString();
  2970. placeholder_name = placeholder_full_name;
  2971. }
  2972. // Create the placeholders.
  2973. FileDescriptor* placeholder_file = NewPlaceholderFile(
  2974. *placeholder_full_name + ".placeholder.proto");
  2975. placeholder_file->package_ = placeholder_package;
  2976. if (placeholder_type == PLACEHOLDER_ENUM) {
  2977. placeholder_file->enum_type_count_ = 1;
  2978. placeholder_file->enum_types_ =
  2979. tables_->AllocateArray<EnumDescriptor>(1);
  2980. EnumDescriptor* placeholder_enum = &placeholder_file->enum_types_[0];
  2981. memset(placeholder_enum, 0, sizeof(*placeholder_enum));
  2982. placeholder_enum->full_name_ = placeholder_full_name;
  2983. placeholder_enum->name_ = placeholder_name;
  2984. placeholder_enum->file_ = placeholder_file;
  2985. placeholder_enum->options_ = &EnumOptions::default_instance();
  2986. placeholder_enum->is_placeholder_ = true;
  2987. placeholder_enum->is_unqualified_placeholder_ = (name[0] != '.');
  2988. // Enums must have at least one value.
  2989. placeholder_enum->value_count_ = 1;
  2990. placeholder_enum->values_ = tables_->AllocateArray<EnumValueDescriptor>(1);
  2991. EnumValueDescriptor* placeholder_value = &placeholder_enum->values_[0];
  2992. memset(placeholder_value, 0, sizeof(*placeholder_value));
  2993. placeholder_value->name_ = tables_->AllocateString("PLACEHOLDER_VALUE");
  2994. // Note that enum value names are siblings of their type, not children.
  2995. placeholder_value->full_name_ =
  2996. placeholder_package->empty() ? placeholder_value->name_ :
  2997. tables_->AllocateString(*placeholder_package + ".PLACEHOLDER_VALUE");
  2998. placeholder_value->number_ = 0;
  2999. placeholder_value->type_ = placeholder_enum;
  3000. placeholder_value->options_ = &EnumValueOptions::default_instance();
  3001. return Symbol(placeholder_enum);
  3002. } else {
  3003. placeholder_file->message_type_count_ = 1;
  3004. placeholder_file->message_types_ =
  3005. tables_->AllocateArray<Descriptor>(1);
  3006. Descriptor* placeholder_message = &placeholder_file->message_types_[0];
  3007. memset(placeholder_message, 0, sizeof(*placeholder_message));
  3008. placeholder_message->full_name_ = placeholder_full_name;
  3009. placeholder_message->name_ = placeholder_name;
  3010. placeholder_message->file_ = placeholder_file;
  3011. placeholder_message->options_ = &MessageOptions::default_instance();
  3012. placeholder_message->is_placeholder_ = true;
  3013. placeholder_message->is_unqualified_placeholder_ = (name[0] != '.');
  3014. if (placeholder_type == PLACEHOLDER_EXTENDABLE_MESSAGE) {
  3015. placeholder_message->extension_range_count_ = 1;
  3016. placeholder_message->extension_ranges_ =
  3017. tables_->AllocateArray<Descriptor::ExtensionRange>(1);
  3018. placeholder_message->extension_ranges_->start = 1;
  3019. // kMaxNumber + 1 because ExtensionRange::end is exclusive.
  3020. placeholder_message->extension_ranges_->end =
  3021. FieldDescriptor::kMaxNumber + 1;
  3022. }
  3023. return Symbol(placeholder_message);
  3024. }
  3025. }
  3026. FileDescriptor* DescriptorBuilder::NewPlaceholderFile(
  3027. const string& name) {
  3028. FileDescriptor* placeholder = tables_->Allocate<FileDescriptor>();
  3029. memset(placeholder, 0, sizeof(*placeholder));
  3030. placeholder->name_ = tables_->AllocateString(name);
  3031. placeholder->package_ = &internal::GetEmptyString();
  3032. placeholder->pool_ = pool_;
  3033. placeholder->options_ = &FileOptions::default_instance();
  3034. placeholder->tables_ = &FileDescriptorTables::kEmpty;
  3035. placeholder->source_code_info_ = &SourceCodeInfo::default_instance();
  3036. placeholder->is_placeholder_ = true;
  3037. placeholder->syntax_ = FileDescriptor::SYNTAX_PROTO2;
  3038. // All other fields are zero or NULL.
  3039. return placeholder;
  3040. }
  3041. bool DescriptorBuilder::AddSymbol(
  3042. const string& full_name, const void* parent, const string& name,
  3043. const Message& proto, Symbol symbol) {
  3044. // If the caller passed NULL for the parent, the symbol is at file scope.
  3045. // Use its file as the parent instead.
  3046. if (parent == NULL) parent = file_;
  3047. if (tables_->AddSymbol(full_name, symbol)) {
  3048. if (!file_tables_->AddAliasUnderParent(parent, name, symbol)) {
  3049. GOOGLE_LOG(DFATAL) << "\"" << full_name << "\" not previously defined in "
  3050. "symbols_by_name_, but was defined in symbols_by_parent_; "
  3051. "this shouldn't be possible.";
  3052. return false;
  3053. }
  3054. return true;
  3055. } else {
  3056. const FileDescriptor* other_file = tables_->FindSymbol(full_name).GetFile();
  3057. if (other_file == file_) {
  3058. string::size_type dot_pos = full_name.find_last_of('.');
  3059. if (dot_pos == string::npos) {
  3060. AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME,
  3061. "\"" + full_name + "\" is already defined.");
  3062. } else {
  3063. AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME,
  3064. "\"" + full_name.substr(dot_pos + 1) +
  3065. "\" is already defined in \"" +
  3066. full_name.substr(0, dot_pos) + "\".");
  3067. }
  3068. } else {
  3069. // Symbol seems to have been defined in a different file.
  3070. AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME,
  3071. "\"" + full_name + "\" is already defined in file \"" +
  3072. other_file->name() + "\".");
  3073. }
  3074. return false;
  3075. }
  3076. }
  3077. void DescriptorBuilder::AddPackage(
  3078. const string& name, const Message& proto, const FileDescriptor* file) {
  3079. if (tables_->AddSymbol(name, Symbol(file))) {
  3080. // Success. Also add parent package, if any.
  3081. string::size_type dot_pos = name.find_last_of('.');
  3082. if (dot_pos == string::npos) {
  3083. // No parents.
  3084. ValidateSymbolName(name, name, proto);
  3085. } else {
  3086. // Has parent.
  3087. string* parent_name = tables_->AllocateString(name.substr(0, dot_pos));
  3088. AddPackage(*parent_name, proto, file);
  3089. ValidateSymbolName(name.substr(dot_pos + 1), name, proto);
  3090. }
  3091. } else {
  3092. Symbol existing_symbol = tables_->FindSymbol(name);
  3093. // It's OK to redefine a package.
  3094. if (existing_symbol.type != Symbol::PACKAGE) {
  3095. // Symbol seems to have been defined in a different file.
  3096. AddError(name, proto, DescriptorPool::ErrorCollector::NAME,
  3097. "\"" + name + "\" is already defined (as something other than "
  3098. "a package) in file \"" + existing_symbol.GetFile()->name() +
  3099. "\".");
  3100. }
  3101. }
  3102. }
  3103. void DescriptorBuilder::ValidateSymbolName(
  3104. const string& name, const string& full_name, const Message& proto) {
  3105. if (name.empty()) {
  3106. AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME,
  3107. "Missing name.");
  3108. } else {
  3109. for (int i = 0; i < name.size(); i++) {
  3110. // I don't trust isalnum() due to locales. :(
  3111. if ((name[i] < 'a' || 'z' < name[i]) &&
  3112. (name[i] < 'A' || 'Z' < name[i]) &&
  3113. (name[i] < '0' || '9' < name[i]) &&
  3114. (name[i] != '_')) {
  3115. AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME,
  3116. "\"" + name + "\" is not a valid identifier.");
  3117. }
  3118. }
  3119. }
  3120. }
  3121. bool DescriptorBuilder::ValidateQualifiedName(const string& name) {
  3122. bool last_was_period = false;
  3123. for (int i = 0; i < name.size(); i++) {
  3124. // I don't trust isalnum() due to locales. :(
  3125. if (('a' <= name[i] && name[i] <= 'z') ||
  3126. ('A' <= name[i] && name[i] <= 'Z') ||
  3127. ('0' <= name[i] && name[i] <= '9') ||
  3128. (name[i] == '_')) {
  3129. last_was_period = false;
  3130. } else if (name[i] == '.') {
  3131. if (last_was_period) return false;
  3132. last_was_period = true;
  3133. } else {
  3134. return false;
  3135. }
  3136. }
  3137. return !name.empty() && !last_was_period;
  3138. }
  3139. // -------------------------------------------------------------------
  3140. // This generic implementation is good for all descriptors except
  3141. // FileDescriptor.
  3142. template<class DescriptorT> void DescriptorBuilder::AllocateOptions(
  3143. const typename DescriptorT::OptionsType& orig_options,
  3144. DescriptorT* descriptor) {
  3145. AllocateOptionsImpl(descriptor->full_name(), descriptor->full_name(),
  3146. orig_options, descriptor);
  3147. }
  3148. // We specialize for FileDescriptor.
  3149. void DescriptorBuilder::AllocateOptions(const FileOptions& orig_options,
  3150. FileDescriptor* descriptor) {
  3151. // We add the dummy token so that LookupSymbol does the right thing.
  3152. AllocateOptionsImpl(descriptor->package() + ".dummy", descriptor->name(),
  3153. orig_options, descriptor);
  3154. }
  3155. template<class DescriptorT> void DescriptorBuilder::AllocateOptionsImpl(
  3156. const string& name_scope,
  3157. const string& element_name,
  3158. const typename DescriptorT::OptionsType& orig_options,
  3159. DescriptorT* descriptor) {
  3160. // We need to use a dummy pointer to work around a bug in older versions of
  3161. // GCC. Otherwise, the following two lines could be replaced with:
  3162. // typename DescriptorT::OptionsType* options =
  3163. // tables_->AllocateMessage<typename DescriptorT::OptionsType>();
  3164. typename DescriptorT::OptionsType* const dummy = NULL;
  3165. typename DescriptorT::OptionsType* options = tables_->AllocateMessage(dummy);
  3166. // Avoid using MergeFrom()/CopyFrom() in this class to make it -fno-rtti
  3167. // friendly. Without RTTI, MergeFrom() and CopyFrom() will fallback to the
  3168. // reflection based method, which requires the Descriptor. However, we are in
  3169. // the middle of building the descriptors, thus the deadlock.
  3170. options->ParseFromString(orig_options.SerializeAsString());
  3171. descriptor->options_ = options;
  3172. // Don't add to options_to_interpret_ unless there were uninterpreted
  3173. // options. This not only avoids unnecessary work, but prevents a
  3174. // bootstrapping problem when building descriptors for descriptor.proto.
  3175. // descriptor.proto does not contain any uninterpreted options, but
  3176. // attempting to interpret options anyway will cause
  3177. // OptionsType::GetDescriptor() to be called which may then deadlock since
  3178. // we're still trying to build it.
  3179. if (options->uninterpreted_option_size() > 0) {
  3180. options_to_interpret_.push_back(
  3181. OptionsToInterpret(name_scope, element_name, &orig_options, options));
  3182. }
  3183. }
  3184. // A common pattern: We want to convert a repeated field in the descriptor
  3185. // to an array of values, calling some method to build each value.
  3186. #define BUILD_ARRAY(INPUT, OUTPUT, NAME, METHOD, PARENT) \
  3187. OUTPUT->NAME##_count_ = INPUT.NAME##_size(); \
  3188. AllocateArray(INPUT.NAME##_size(), &OUTPUT->NAME##s_); \
  3189. for (int i = 0; i < INPUT.NAME##_size(); i++) { \
  3190. METHOD(INPUT.NAME(i), PARENT, OUTPUT->NAME##s_ + i); \
  3191. }
  3192. void DescriptorBuilder::AddRecursiveImportError(
  3193. const FileDescriptorProto& proto, int from_here) {
  3194. string error_message("File recursively imports itself: ");
  3195. for (int i = from_here; i < tables_->pending_files_.size(); i++) {
  3196. error_message.append(tables_->pending_files_[i]);
  3197. error_message.append(" -> ");
  3198. }
  3199. error_message.append(proto.name());
  3200. AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER,
  3201. error_message);
  3202. }
  3203. void DescriptorBuilder::AddTwiceListedError(const FileDescriptorProto& proto,
  3204. int index) {
  3205. AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER,
  3206. "Import \"" + proto.dependency(index) + "\" was listed twice.");
  3207. }
  3208. void DescriptorBuilder::AddImportError(const FileDescriptorProto& proto,
  3209. int index) {
  3210. string message;
  3211. if (pool_->fallback_database_ == NULL) {
  3212. message = "Import \"" + proto.dependency(index) +
  3213. "\" has not been loaded.";
  3214. } else {
  3215. message = "Import \"" + proto.dependency(index) +
  3216. "\" was not found or had errors.";
  3217. }
  3218. AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, message);
  3219. }
  3220. static bool ExistingFileMatchesProto(const FileDescriptor* existing_file,
  3221. const FileDescriptorProto& proto) {
  3222. FileDescriptorProto existing_proto;
  3223. existing_file->CopyTo(&existing_proto);
  3224. // TODO(liujisi): Remove it when CopyTo supports copying syntax params when
  3225. // syntax="proto2".
  3226. if (existing_file->syntax() == FileDescriptor::SYNTAX_PROTO2 &&
  3227. proto.has_syntax()) {
  3228. existing_proto.set_syntax(
  3229. existing_file->SyntaxName(existing_file->syntax()));
  3230. }
  3231. return existing_proto.SerializeAsString() == proto.SerializeAsString();
  3232. }
  3233. const FileDescriptor* DescriptorBuilder::BuildFile(
  3234. const FileDescriptorProto& proto) {
  3235. filename_ = proto.name();
  3236. // Check if the file already exists and is identical to the one being built.
  3237. // Note: This only works if the input is canonical -- that is, it
  3238. // fully-qualifies all type names, has no UninterpretedOptions, etc.
  3239. // This is fine, because this idempotency "feature" really only exists to
  3240. // accommodate one hack in the proto1->proto2 migration layer.
  3241. const FileDescriptor* existing_file = tables_->FindFile(filename_);
  3242. if (existing_file != NULL) {
  3243. // File already in pool. Compare the existing one to the input.
  3244. if (ExistingFileMatchesProto(existing_file, proto)) {
  3245. // They're identical. Return the existing descriptor.
  3246. return existing_file;
  3247. }
  3248. // Not a match. The error will be detected and handled later.
  3249. }
  3250. // Check to see if this file is already on the pending files list.
  3251. // TODO(kenton): Allow recursive imports? It may not work with some
  3252. // (most?) programming languages. E.g., in C++, a forward declaration
  3253. // of a type is not sufficient to allow it to be used even in a
  3254. // generated header file due to inlining. This could perhaps be
  3255. // worked around using tricks involving inserting #include statements
  3256. // mid-file, but that's pretty ugly, and I'm pretty sure there are
  3257. // some languages out there that do not allow recursive dependencies
  3258. // at all.
  3259. for (int i = 0; i < tables_->pending_files_.size(); i++) {
  3260. if (tables_->pending_files_[i] == proto.name()) {
  3261. AddRecursiveImportError(proto, i);
  3262. return NULL;
  3263. }
  3264. }
  3265. // If we have a fallback_database_, attempt to load all dependencies now,
  3266. // before checkpointing tables_. This avoids confusion with recursive
  3267. // checkpoints.
  3268. if (pool_->fallback_database_ != NULL) {
  3269. tables_->pending_files_.push_back(proto.name());
  3270. for (int i = 0; i < proto.dependency_size(); i++) {
  3271. if (tables_->FindFile(proto.dependency(i)) == NULL &&
  3272. (pool_->underlay_ == NULL ||
  3273. pool_->underlay_->FindFileByName(proto.dependency(i)) == NULL)) {
  3274. // We don't care what this returns since we'll find out below anyway.
  3275. pool_->TryFindFileInFallbackDatabase(proto.dependency(i));
  3276. }
  3277. }
  3278. tables_->pending_files_.pop_back();
  3279. }
  3280. // Checkpoint the tables so that we can roll back if something goes wrong.
  3281. tables_->AddCheckpoint();
  3282. FileDescriptor* result = tables_->Allocate<FileDescriptor>();
  3283. file_ = result;
  3284. result->is_placeholder_ = false;
  3285. if (proto.has_source_code_info()) {
  3286. SourceCodeInfo *info = tables_->AllocateMessage<SourceCodeInfo>();
  3287. info->CopyFrom(proto.source_code_info());
  3288. result->source_code_info_ = info;
  3289. } else {
  3290. result->source_code_info_ = &SourceCodeInfo::default_instance();
  3291. }
  3292. file_tables_ = tables_->AllocateFileTables();
  3293. file_->tables_ = file_tables_;
  3294. if (!proto.has_name()) {
  3295. AddError("", proto, DescriptorPool::ErrorCollector::OTHER,
  3296. "Missing field: FileDescriptorProto.name.");
  3297. }
  3298. // TODO(liujisi): Report error when the syntax is empty after all the protos
  3299. // have added the syntax statement.
  3300. if (proto.syntax().empty() || proto.syntax() == "proto2") {
  3301. file_->syntax_ = FileDescriptor::SYNTAX_PROTO2;
  3302. } else if (proto.syntax() == "proto3") {
  3303. file_->syntax_ = FileDescriptor::SYNTAX_PROTO3;
  3304. } else {
  3305. file_->syntax_ = FileDescriptor::SYNTAX_UNKNOWN;
  3306. AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER,
  3307. "Unrecognized syntax: " + proto.syntax());
  3308. }
  3309. result->name_ = tables_->AllocateString(proto.name());
  3310. if (proto.has_package()) {
  3311. result->package_ = tables_->AllocateString(proto.package());
  3312. } else {
  3313. // We cannot rely on proto.package() returning a valid string if
  3314. // proto.has_package() is false, because we might be running at static
  3315. // initialization time, in which case default values have not yet been
  3316. // initialized.
  3317. result->package_ = tables_->AllocateString("");
  3318. }
  3319. result->pool_ = pool_;
  3320. // Add to tables.
  3321. if (!tables_->AddFile(result)) {
  3322. AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER,
  3323. "A file with this name is already in the pool.");
  3324. // Bail out early so that if this is actually the exact same file, we
  3325. // don't end up reporting that every single symbol is already defined.
  3326. tables_->RollbackToLastCheckpoint();
  3327. return NULL;
  3328. }
  3329. if (!result->package().empty()) {
  3330. AddPackage(result->package(), proto, result);
  3331. }
  3332. // Make sure all dependencies are loaded.
  3333. set<string> seen_dependencies;
  3334. result->dependency_count_ = proto.dependency_size();
  3335. result->dependencies_ =
  3336. tables_->AllocateArray<const FileDescriptor*>(proto.dependency_size());
  3337. unused_dependency_.clear();
  3338. set<int> weak_deps;
  3339. for (int i = 0; i < proto.weak_dependency_size(); ++i) {
  3340. weak_deps.insert(proto.weak_dependency(i));
  3341. }
  3342. for (int i = 0; i < proto.dependency_size(); i++) {
  3343. if (!seen_dependencies.insert(proto.dependency(i)).second) {
  3344. AddTwiceListedError(proto, i);
  3345. }
  3346. const FileDescriptor* dependency = tables_->FindFile(proto.dependency(i));
  3347. if (dependency == NULL && pool_->underlay_ != NULL) {
  3348. dependency = pool_->underlay_->FindFileByName(proto.dependency(i));
  3349. }
  3350. if (dependency == NULL) {
  3351. if (pool_->allow_unknown_ ||
  3352. (!pool_->enforce_weak_ && weak_deps.find(i) != weak_deps.end())) {
  3353. dependency = NewPlaceholderFile(proto.dependency(i));
  3354. } else {
  3355. AddImportError(proto, i);
  3356. }
  3357. } else {
  3358. // Add to unused_dependency_ to track unused imported files.
  3359. // Note: do not track unused imported files for public import.
  3360. if (pool_->enforce_dependencies_ &&
  3361. (pool_->unused_import_track_files_.find(proto.name()) !=
  3362. pool_->unused_import_track_files_.end()) &&
  3363. (dependency->public_dependency_count() == 0)) {
  3364. unused_dependency_.insert(dependency);
  3365. }
  3366. }
  3367. result->dependencies_[i] = dependency;
  3368. }
  3369. // Check public dependencies.
  3370. int public_dependency_count = 0;
  3371. result->public_dependencies_ = tables_->AllocateArray<int>(
  3372. proto.public_dependency_size());
  3373. for (int i = 0; i < proto.public_dependency_size(); i++) {
  3374. // Only put valid public dependency indexes.
  3375. int index = proto.public_dependency(i);
  3376. if (index >= 0 && index < proto.dependency_size()) {
  3377. result->public_dependencies_[public_dependency_count++] = index;
  3378. // Do not track unused imported files for public import.
  3379. unused_dependency_.erase(result->dependency(index));
  3380. } else {
  3381. AddError(proto.name(), proto,
  3382. DescriptorPool::ErrorCollector::OTHER,
  3383. "Invalid public dependency index.");
  3384. }
  3385. }
  3386. result->public_dependency_count_ = public_dependency_count;
  3387. // Build dependency set
  3388. dependencies_.clear();
  3389. for (int i = 0; i < result->dependency_count(); i++) {
  3390. RecordPublicDependencies(result->dependency(i));
  3391. }
  3392. // Check weak dependencies.
  3393. int weak_dependency_count = 0;
  3394. result->weak_dependencies_ = tables_->AllocateArray<int>(
  3395. proto.weak_dependency_size());
  3396. for (int i = 0; i < proto.weak_dependency_size(); i++) {
  3397. int index = proto.weak_dependency(i);
  3398. if (index >= 0 && index < proto.dependency_size()) {
  3399. result->weak_dependencies_[weak_dependency_count++] = index;
  3400. } else {
  3401. AddError(proto.name(), proto,
  3402. DescriptorPool::ErrorCollector::OTHER,
  3403. "Invalid weak dependency index.");
  3404. }
  3405. }
  3406. result->weak_dependency_count_ = weak_dependency_count;
  3407. // Convert children.
  3408. BUILD_ARRAY(proto, result, message_type, BuildMessage , NULL);
  3409. BUILD_ARRAY(proto, result, enum_type , BuildEnum , NULL);
  3410. BUILD_ARRAY(proto, result, service , BuildService , NULL);
  3411. BUILD_ARRAY(proto, result, extension , BuildExtension, NULL);
  3412. // Copy options.
  3413. if (!proto.has_options()) {
  3414. result->options_ = NULL; // Will set to default_instance later.
  3415. } else {
  3416. AllocateOptions(proto.options(), result);
  3417. }
  3418. // Note that the following steps must occur in exactly the specified order.
  3419. // Cross-link.
  3420. CrossLinkFile(result, proto);
  3421. // Interpret any remaining uninterpreted options gathered into
  3422. // options_to_interpret_ during descriptor building. Cross-linking has made
  3423. // extension options known, so all interpretations should now succeed.
  3424. if (!had_errors_) {
  3425. OptionInterpreter option_interpreter(this);
  3426. for (vector<OptionsToInterpret>::iterator iter =
  3427. options_to_interpret_.begin();
  3428. iter != options_to_interpret_.end(); ++iter) {
  3429. option_interpreter.InterpretOptions(&(*iter));
  3430. }
  3431. options_to_interpret_.clear();
  3432. }
  3433. // Validate options.
  3434. if (!had_errors_) {
  3435. ValidateFileOptions(result, proto);
  3436. }
  3437. // Additional naming conflict check for map entry types. Only need to check
  3438. // this if there are already errors.
  3439. if (had_errors_) {
  3440. for (int i = 0; i < proto.message_type_size(); ++i) {
  3441. DetectMapConflicts(result->message_type(i), proto.message_type(i));
  3442. }
  3443. }
  3444. if (!unused_dependency_.empty()) {
  3445. LogUnusedDependency(result);
  3446. }
  3447. if (had_errors_) {
  3448. tables_->RollbackToLastCheckpoint();
  3449. return NULL;
  3450. } else {
  3451. tables_->ClearLastCheckpoint();
  3452. return result;
  3453. }
  3454. }
  3455. void DescriptorBuilder::BuildMessage(const DescriptorProto& proto,
  3456. const Descriptor* parent,
  3457. Descriptor* result) {
  3458. const string& scope = (parent == NULL) ?
  3459. file_->package() : parent->full_name();
  3460. string* full_name = tables_->AllocateString(scope);
  3461. if (!full_name->empty()) full_name->append(1, '.');
  3462. full_name->append(proto.name());
  3463. ValidateSymbolName(proto.name(), *full_name, proto);
  3464. result->name_ = tables_->AllocateString(proto.name());
  3465. result->full_name_ = full_name;
  3466. result->file_ = file_;
  3467. result->containing_type_ = parent;
  3468. result->is_placeholder_ = false;
  3469. result->is_unqualified_placeholder_ = false;
  3470. // Build oneofs first so that fields and extension ranges can refer to them.
  3471. BUILD_ARRAY(proto, result, oneof_decl , BuildOneof , result);
  3472. BUILD_ARRAY(proto, result, field , BuildField , result);
  3473. BUILD_ARRAY(proto, result, nested_type , BuildMessage , result);
  3474. BUILD_ARRAY(proto, result, enum_type , BuildEnum , result);
  3475. BUILD_ARRAY(proto, result, extension_range, BuildExtensionRange, result);
  3476. BUILD_ARRAY(proto, result, extension , BuildExtension , result);
  3477. BUILD_ARRAY(proto, result, reserved_range , BuildReservedRange , result);
  3478. // Copy reserved names.
  3479. int reserved_name_count = proto.reserved_name_size();
  3480. result->reserved_name_count_ = reserved_name_count;
  3481. result->reserved_names_ =
  3482. tables_->AllocateArray<const string*>(reserved_name_count);
  3483. for (int i = 0; i < reserved_name_count; ++i) {
  3484. result->reserved_names_[i] =
  3485. tables_->AllocateString(proto.reserved_name(i));
  3486. }
  3487. // Copy options.
  3488. if (!proto.has_options()) {
  3489. result->options_ = NULL; // Will set to default_instance later.
  3490. } else {
  3491. AllocateOptions(proto.options(), result);
  3492. }
  3493. AddSymbol(result->full_name(), parent, result->name(),
  3494. proto, Symbol(result));
  3495. for (int i = 0; i < proto.reserved_range_size(); i++) {
  3496. const DescriptorProto_ReservedRange& range1 = proto.reserved_range(i);
  3497. for (int j = i + 1; j < proto.reserved_range_size(); j++) {
  3498. const DescriptorProto_ReservedRange& range2 = proto.reserved_range(j);
  3499. if (range1.end() > range2.start() && range2.end() > range1.start()) {
  3500. AddError(result->full_name(), proto.reserved_range(i),
  3501. DescriptorPool::ErrorCollector::NUMBER,
  3502. strings::Substitute("Reserved range $0 to $1 overlaps with "
  3503. "already-defined range $2 to $3.",
  3504. range2.start(), range2.end() - 1,
  3505. range1.start(), range1.end() - 1));
  3506. }
  3507. }
  3508. }
  3509. hash_set<string> reserved_name_set;
  3510. for (int i = 0; i < proto.reserved_name_size(); i++) {
  3511. const string& name = proto.reserved_name(i);
  3512. if (reserved_name_set.find(name) == reserved_name_set.end()) {
  3513. reserved_name_set.insert(name);
  3514. } else {
  3515. AddError(name, proto, DescriptorPool::ErrorCollector::NAME,
  3516. strings::Substitute(
  3517. "Field name \"$0\" is reserved multiple times.",
  3518. name));
  3519. }
  3520. }
  3521. for (int i = 0; i < result->field_count(); i++) {
  3522. const FieldDescriptor* field = result->field(i);
  3523. for (int j = 0; j < result->extension_range_count(); j++) {
  3524. const Descriptor::ExtensionRange* range = result->extension_range(j);
  3525. if (range->start <= field->number() && field->number() < range->end) {
  3526. AddError(field->full_name(), proto.extension_range(j),
  3527. DescriptorPool::ErrorCollector::NUMBER,
  3528. strings::Substitute(
  3529. "Extension range $0 to $1 includes field \"$2\" ($3).",
  3530. range->start, range->end - 1,
  3531. field->name(), field->number()));
  3532. }
  3533. }
  3534. for (int j = 0; j < result->reserved_range_count(); j++) {
  3535. const Descriptor::ReservedRange* range = result->reserved_range(j);
  3536. if (range->start <= field->number() && field->number() < range->end) {
  3537. AddError(field->full_name(), proto.reserved_range(j),
  3538. DescriptorPool::ErrorCollector::NUMBER,
  3539. strings::Substitute(
  3540. "Field \"$0\" uses reserved number $1.",
  3541. field->name(), field->number()));
  3542. }
  3543. }
  3544. if (reserved_name_set.find(field->name()) != reserved_name_set.end()) {
  3545. AddError(field->full_name(), proto.field(i),
  3546. DescriptorPool::ErrorCollector::NAME,
  3547. strings::Substitute(
  3548. "Field name \"$0\" is reserved.", field->name()));
  3549. }
  3550. }
  3551. // Check that extension ranges don't overlap and don't include
  3552. // reserved field numbers.
  3553. for (int i = 0; i < result->extension_range_count(); i++) {
  3554. const Descriptor::ExtensionRange* range1 = result->extension_range(i);
  3555. for (int j = 0; j < result->reserved_range_count(); j++) {
  3556. const Descriptor::ReservedRange* range2 = result->reserved_range(j);
  3557. if (range1->end > range2->start && range2->end > range1->start) {
  3558. AddError(result->full_name(), proto.extension_range(j),
  3559. DescriptorPool::ErrorCollector::NUMBER,
  3560. strings::Substitute("Extension range $0 to $1 overlaps with "
  3561. "reserved range $2 to $3.",
  3562. range1->start, range1->end - 1,
  3563. range2->start, range2->end - 1));
  3564. }
  3565. }
  3566. for (int j = i + 1; j < result->extension_range_count(); j++) {
  3567. const Descriptor::ExtensionRange* range2 = result->extension_range(j);
  3568. if (range1->end > range2->start && range2->end > range1->start) {
  3569. AddError(result->full_name(), proto.extension_range(j),
  3570. DescriptorPool::ErrorCollector::NUMBER,
  3571. strings::Substitute("Extension range $0 to $1 overlaps with "
  3572. "already-defined range $2 to $3.",
  3573. range2->start, range2->end - 1,
  3574. range1->start, range1->end - 1));
  3575. }
  3576. }
  3577. }
  3578. }
  3579. void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto,
  3580. const Descriptor* parent,
  3581. FieldDescriptor* result,
  3582. bool is_extension) {
  3583. const string& scope = (parent == NULL) ?
  3584. file_->package() : parent->full_name();
  3585. string* full_name = tables_->AllocateString(scope);
  3586. if (!full_name->empty()) full_name->append(1, '.');
  3587. full_name->append(proto.name());
  3588. ValidateSymbolName(proto.name(), *full_name, proto);
  3589. result->name_ = tables_->AllocateString(proto.name());
  3590. result->full_name_ = full_name;
  3591. result->file_ = file_;
  3592. result->number_ = proto.number();
  3593. result->is_extension_ = is_extension;
  3594. // If .proto files follow the style guide then the name should already be
  3595. // lower-cased. If that's the case we can just reuse the string we already
  3596. // allocated rather than allocate a new one.
  3597. string lowercase_name(proto.name());
  3598. LowerString(&lowercase_name);
  3599. if (lowercase_name == proto.name()) {
  3600. result->lowercase_name_ = result->name_;
  3601. } else {
  3602. result->lowercase_name_ = tables_->AllocateString(lowercase_name);
  3603. }
  3604. // Don't bother with the above optimization for camel-case names since
  3605. // .proto files that follow the guide shouldn't be using names in this
  3606. // format, so the optimization wouldn't help much.
  3607. result->camelcase_name_ =
  3608. tables_->AllocateString(ToCamelCase(proto.name(),
  3609. /* lower_first = */ true));
  3610. // Some compilers do not allow static_cast directly between two enum types,
  3611. // so we must cast to int first.
  3612. result->type_ = static_cast<FieldDescriptor::Type>(
  3613. implicit_cast<int>(proto.type()));
  3614. result->label_ = static_cast<FieldDescriptor::Label>(
  3615. implicit_cast<int>(proto.label()));
  3616. // An extension cannot have a required field (b/13365836).
  3617. if (result->is_extension_ &&
  3618. result->label_ == FieldDescriptor::LABEL_REQUIRED) {
  3619. AddError(result->full_name(), proto,
  3620. // Error location `TYPE`: we would really like to indicate
  3621. // `LABEL`, but the `ErrorLocation` enum has no entry for this, and
  3622. // we don't necessarily know about all implementations of the
  3623. // `ErrorCollector` interface to extend them to handle the new
  3624. // error location type properly.
  3625. DescriptorPool::ErrorCollector::TYPE,
  3626. "Message extensions cannot have required fields.");
  3627. }
  3628. // Some of these may be filled in when cross-linking.
  3629. result->containing_type_ = NULL;
  3630. result->extension_scope_ = NULL;
  3631. result->message_type_ = NULL;
  3632. result->enum_type_ = NULL;
  3633. result->has_default_value_ = proto.has_default_value();
  3634. if (proto.has_default_value() && result->is_repeated()) {
  3635. AddError(result->full_name(), proto,
  3636. DescriptorPool::ErrorCollector::DEFAULT_VALUE,
  3637. "Repeated fields can't have default values.");
  3638. }
  3639. if (proto.has_type()) {
  3640. if (proto.has_default_value()) {
  3641. char* end_pos = NULL;
  3642. switch (result->cpp_type()) {
  3643. case FieldDescriptor::CPPTYPE_INT32:
  3644. result->default_value_int32_ =
  3645. strtol(proto.default_value().c_str(), &end_pos, 0);
  3646. break;
  3647. case FieldDescriptor::CPPTYPE_INT64:
  3648. result->default_value_int64_ =
  3649. strto64(proto.default_value().c_str(), &end_pos, 0);
  3650. break;
  3651. case FieldDescriptor::CPPTYPE_UINT32:
  3652. result->default_value_uint32_ =
  3653. strtoul(proto.default_value().c_str(), &end_pos, 0);
  3654. break;
  3655. case FieldDescriptor::CPPTYPE_UINT64:
  3656. result->default_value_uint64_ =
  3657. strtou64(proto.default_value().c_str(), &end_pos, 0);
  3658. break;
  3659. case FieldDescriptor::CPPTYPE_FLOAT:
  3660. if (proto.default_value() == "inf") {
  3661. result->default_value_float_ = numeric_limits<float>::infinity();
  3662. } else if (proto.default_value() == "-inf") {
  3663. result->default_value_float_ = -numeric_limits<float>::infinity();
  3664. } else if (proto.default_value() == "nan") {
  3665. result->default_value_float_ = numeric_limits<float>::quiet_NaN();
  3666. } else {
  3667. result->default_value_float_ =
  3668. io::NoLocaleStrtod(proto.default_value().c_str(), &end_pos);
  3669. }
  3670. break;
  3671. case FieldDescriptor::CPPTYPE_DOUBLE:
  3672. if (proto.default_value() == "inf") {
  3673. result->default_value_double_ = numeric_limits<double>::infinity();
  3674. } else if (proto.default_value() == "-inf") {
  3675. result->default_value_double_ = -numeric_limits<double>::infinity();
  3676. } else if (proto.default_value() == "nan") {
  3677. result->default_value_double_ = numeric_limits<double>::quiet_NaN();
  3678. } else {
  3679. result->default_value_double_ =
  3680. io::NoLocaleStrtod(proto.default_value().c_str(), &end_pos);
  3681. }
  3682. break;
  3683. case FieldDescriptor::CPPTYPE_BOOL:
  3684. if (proto.default_value() == "true") {
  3685. result->default_value_bool_ = true;
  3686. } else if (proto.default_value() == "false") {
  3687. result->default_value_bool_ = false;
  3688. } else {
  3689. AddError(result->full_name(), proto,
  3690. DescriptorPool::ErrorCollector::DEFAULT_VALUE,
  3691. "Boolean default must be true or false.");
  3692. }
  3693. break;
  3694. case FieldDescriptor::CPPTYPE_ENUM:
  3695. // This will be filled in when cross-linking.
  3696. result->default_value_enum_ = NULL;
  3697. break;
  3698. case FieldDescriptor::CPPTYPE_STRING:
  3699. if (result->type() == FieldDescriptor::TYPE_BYTES) {
  3700. result->default_value_string_ = tables_->AllocateString(
  3701. UnescapeCEscapeString(proto.default_value()));
  3702. } else {
  3703. result->default_value_string_ =
  3704. tables_->AllocateString(proto.default_value());
  3705. }
  3706. break;
  3707. case FieldDescriptor::CPPTYPE_MESSAGE:
  3708. AddError(result->full_name(), proto,
  3709. DescriptorPool::ErrorCollector::DEFAULT_VALUE,
  3710. "Messages can't have default values.");
  3711. result->has_default_value_ = false;
  3712. break;
  3713. }
  3714. if (end_pos != NULL) {
  3715. // end_pos is only set non-NULL by the parsers for numeric types, above.
  3716. // This checks that the default was non-empty and had no extra junk
  3717. // after the end of the number.
  3718. if (proto.default_value().empty() || *end_pos != '\0') {
  3719. AddError(result->full_name(), proto,
  3720. DescriptorPool::ErrorCollector::DEFAULT_VALUE,
  3721. "Couldn't parse default value \"" + proto.default_value() +
  3722. "\".");
  3723. }
  3724. }
  3725. } else {
  3726. // No explicit default value
  3727. switch (result->cpp_type()) {
  3728. case FieldDescriptor::CPPTYPE_INT32:
  3729. result->default_value_int32_ = 0;
  3730. break;
  3731. case FieldDescriptor::CPPTYPE_INT64:
  3732. result->default_value_int64_ = 0;
  3733. break;
  3734. case FieldDescriptor::CPPTYPE_UINT32:
  3735. result->default_value_uint32_ = 0;
  3736. break;
  3737. case FieldDescriptor::CPPTYPE_UINT64:
  3738. result->default_value_uint64_ = 0;
  3739. break;
  3740. case FieldDescriptor::CPPTYPE_FLOAT:
  3741. result->default_value_float_ = 0.0f;
  3742. break;
  3743. case FieldDescriptor::CPPTYPE_DOUBLE:
  3744. result->default_value_double_ = 0.0;
  3745. break;
  3746. case FieldDescriptor::CPPTYPE_BOOL:
  3747. result->default_value_bool_ = false;
  3748. break;
  3749. case FieldDescriptor::CPPTYPE_ENUM:
  3750. // This will be filled in when cross-linking.
  3751. result->default_value_enum_ = NULL;
  3752. break;
  3753. case FieldDescriptor::CPPTYPE_STRING:
  3754. result->default_value_string_ = &internal::GetEmptyString();
  3755. break;
  3756. case FieldDescriptor::CPPTYPE_MESSAGE:
  3757. break;
  3758. }
  3759. }
  3760. }
  3761. if (result->number() <= 0) {
  3762. AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
  3763. "Field numbers must be positive integers.");
  3764. } else if (!is_extension && result->number() > FieldDescriptor::kMaxNumber) {
  3765. // Only validate that the number is within the valid field range if it is
  3766. // not an extension. Since extension numbers are validated with the
  3767. // extendee's valid set of extension numbers, and those are in turn
  3768. // validated against the max allowed number, the check is unnecessary for
  3769. // extension fields.
  3770. // This avoids cross-linking issues that arise when attempting to check if
  3771. // the extendee is a message_set_wire_format message, which has a higher max
  3772. // on extension numbers.
  3773. AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
  3774. strings::Substitute("Field numbers cannot be greater than $0.",
  3775. FieldDescriptor::kMaxNumber));
  3776. } else if (result->number() >= FieldDescriptor::kFirstReservedNumber &&
  3777. result->number() <= FieldDescriptor::kLastReservedNumber) {
  3778. AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER,
  3779. strings::Substitute(
  3780. "Field numbers $0 through $1 are reserved for the protocol "
  3781. "buffer library implementation.",
  3782. FieldDescriptor::kFirstReservedNumber,
  3783. FieldDescriptor::kLastReservedNumber));
  3784. }
  3785. if (is_extension) {
  3786. if (!proto.has_extendee()) {
  3787. AddError(result->full_name(), proto,
  3788. DescriptorPool::ErrorCollector::EXTENDEE,
  3789. "FieldDescriptorProto.extendee not set for extension field.");
  3790. }
  3791. result->extension_scope_ = parent;
  3792. if (proto.has_oneof_index()) {
  3793. AddError(result->full_name(), proto,
  3794. DescriptorPool::ErrorCollector::OTHER,
  3795. "FieldDescriptorProto.oneof_index should not be set for "
  3796. "extensions.");
  3797. }
  3798. // Fill in later (maybe).
  3799. result->containing_oneof_ = NULL;
  3800. } else {
  3801. if (proto.has_extendee()) {
  3802. AddError(result->full_name(), proto,
  3803. DescriptorPool::ErrorCollector::EXTENDEE,
  3804. "FieldDescriptorProto.extendee set for non-extension field.");
  3805. }
  3806. result->containing_type_ = parent;
  3807. if (proto.has_oneof_index()) {
  3808. if (proto.oneof_index() < 0 ||
  3809. proto.oneof_index() >= parent->oneof_decl_count()) {
  3810. AddError(result->full_name(), proto,
  3811. DescriptorPool::ErrorCollector::OTHER,
  3812. strings::Substitute("FieldDescriptorProto.oneof_index $0 is "
  3813. "out of range for type \"$1\".",
  3814. proto.oneof_index(),
  3815. parent->name()));
  3816. result->containing_oneof_ = NULL;
  3817. } else {
  3818. result->containing_oneof_ = parent->oneof_decl(proto.oneof_index());
  3819. }
  3820. } else {
  3821. result->containing_oneof_ = NULL;
  3822. }
  3823. }
  3824. // Copy options.
  3825. if (!proto.has_options()) {
  3826. result->options_ = NULL; // Will set to default_instance later.
  3827. } else {
  3828. AllocateOptions(proto.options(), result);
  3829. }
  3830. AddSymbol(result->full_name(), parent, result->name(),
  3831. proto, Symbol(result));
  3832. }
  3833. void DescriptorBuilder::BuildExtensionRange(
  3834. const DescriptorProto::ExtensionRange& proto,
  3835. const Descriptor* parent,
  3836. Descriptor::ExtensionRange* result) {
  3837. result->start = proto.start();
  3838. result->end = proto.end();
  3839. if (result->start <= 0) {
  3840. AddError(parent->full_name(), proto,
  3841. DescriptorPool::ErrorCollector::NUMBER,
  3842. "Extension numbers must be positive integers.");
  3843. }
  3844. // Checking of the upper bound of the extension range is deferred until after
  3845. // options interpreting. This allows messages with message_set_wire_format to
  3846. // have extensions beyond FieldDescriptor::kMaxNumber, since the extension
  3847. // numbers are actually used as int32s in the message_set_wire_format.
  3848. if (result->start >= result->end) {
  3849. AddError(parent->full_name(), proto,
  3850. DescriptorPool::ErrorCollector::NUMBER,
  3851. "Extension range end number must be greater than start number.");
  3852. }
  3853. }
  3854. void DescriptorBuilder::BuildReservedRange(
  3855. const DescriptorProto::ReservedRange& proto,
  3856. const Descriptor* parent,
  3857. Descriptor::ReservedRange* result) {
  3858. result->start = proto.start();
  3859. result->end = proto.end();
  3860. if (result->start <= 0) {
  3861. AddError(parent->full_name(), proto,
  3862. DescriptorPool::ErrorCollector::NUMBER,
  3863. "Reserved numbers must be positive integers.");
  3864. }
  3865. }
  3866. void DescriptorBuilder::BuildOneof(const OneofDescriptorProto& proto,
  3867. Descriptor* parent,
  3868. OneofDescriptor* result) {
  3869. string* full_name = tables_->AllocateString(parent->full_name());
  3870. full_name->append(1, '.');
  3871. full_name->append(proto.name());
  3872. ValidateSymbolName(proto.name(), *full_name, proto);
  3873. result->name_ = tables_->AllocateString(proto.name());
  3874. result->full_name_ = full_name;
  3875. result->containing_type_ = parent;
  3876. // We need to fill these in later.
  3877. result->field_count_ = 0;
  3878. result->fields_ = NULL;
  3879. AddSymbol(result->full_name(), parent, result->name(),
  3880. proto, Symbol(result));
  3881. }
  3882. void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto,
  3883. const Descriptor* parent,
  3884. EnumDescriptor* result) {
  3885. const string& scope = (parent == NULL) ?
  3886. file_->package() : parent->full_name();
  3887. string* full_name = tables_->AllocateString(scope);
  3888. if (!full_name->empty()) full_name->append(1, '.');
  3889. full_name->append(proto.name());
  3890. ValidateSymbolName(proto.name(), *full_name, proto);
  3891. result->name_ = tables_->AllocateString(proto.name());
  3892. result->full_name_ = full_name;
  3893. result->file_ = file_;
  3894. result->containing_type_ = parent;
  3895. result->is_placeholder_ = false;
  3896. result->is_unqualified_placeholder_ = false;
  3897. if (proto.value_size() == 0) {
  3898. // We cannot allow enums with no values because this would mean there
  3899. // would be no valid default value for fields of this type.
  3900. AddError(result->full_name(), proto,
  3901. DescriptorPool::ErrorCollector::NAME,
  3902. "Enums must contain at least one value.");
  3903. }
  3904. BUILD_ARRAY(proto, result, value, BuildEnumValue, result);
  3905. // Copy options.
  3906. if (!proto.has_options()) {
  3907. result->options_ = NULL; // Will set to default_instance later.
  3908. } else {
  3909. AllocateOptions(proto.options(), result);
  3910. }
  3911. AddSymbol(result->full_name(), parent, result->name(),
  3912. proto, Symbol(result));
  3913. }
  3914. void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto,
  3915. const EnumDescriptor* parent,
  3916. EnumValueDescriptor* result) {
  3917. result->name_ = tables_->AllocateString(proto.name());
  3918. result->number_ = proto.number();
  3919. result->type_ = parent;
  3920. // Note: full_name for enum values is a sibling to the parent's name, not a
  3921. // child of it.
  3922. string* full_name = tables_->AllocateString(*parent->full_name_);
  3923. full_name->resize(full_name->size() - parent->name_->size());
  3924. full_name->append(*result->name_);
  3925. result->full_name_ = full_name;
  3926. ValidateSymbolName(proto.name(), *full_name, proto);
  3927. // Copy options.
  3928. if (!proto.has_options()) {
  3929. result->options_ = NULL; // Will set to default_instance later.
  3930. } else {
  3931. AllocateOptions(proto.options(), result);
  3932. }
  3933. // Again, enum values are weird because we makes them appear as siblings
  3934. // of the enum type instead of children of it. So, we use
  3935. // parent->containing_type() as the value's parent.
  3936. bool added_to_outer_scope =
  3937. AddSymbol(result->full_name(), parent->containing_type(), result->name(),
  3938. proto, Symbol(result));
  3939. // However, we also want to be able to search for values within a single
  3940. // enum type, so we add it as a child of the enum type itself, too.
  3941. // Note: This could fail, but if it does, the error has already been
  3942. // reported by the above AddSymbol() call, so we ignore the return code.
  3943. bool added_to_inner_scope =
  3944. file_tables_->AddAliasUnderParent(parent, result->name(), Symbol(result));
  3945. if (added_to_inner_scope && !added_to_outer_scope) {
  3946. // This value did not conflict with any values defined in the same enum,
  3947. // but it did conflict with some other symbol defined in the enum type's
  3948. // scope. Let's print an additional error to explain this.
  3949. string outer_scope;
  3950. if (parent->containing_type() == NULL) {
  3951. outer_scope = file_->package();
  3952. } else {
  3953. outer_scope = parent->containing_type()->full_name();
  3954. }
  3955. if (outer_scope.empty()) {
  3956. outer_scope = "the global scope";
  3957. } else {
  3958. outer_scope = "\"" + outer_scope + "\"";
  3959. }
  3960. AddError(result->full_name(), proto,
  3961. DescriptorPool::ErrorCollector::NAME,
  3962. "Note that enum values use C++ scoping rules, meaning that "
  3963. "enum values are siblings of their type, not children of it. "
  3964. "Therefore, \"" + result->name() + "\" must be unique within "
  3965. + outer_scope + ", not just within \"" + parent->name() + "\".");
  3966. }
  3967. // An enum is allowed to define two numbers that refer to the same value.
  3968. // FindValueByNumber() should return the first such value, so we simply
  3969. // ignore AddEnumValueByNumber()'s return code.
  3970. file_tables_->AddEnumValueByNumber(result);
  3971. }
  3972. void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto,
  3973. const void* /* dummy */,
  3974. ServiceDescriptor* result) {
  3975. string* full_name = tables_->AllocateString(file_->package());
  3976. if (!full_name->empty()) full_name->append(1, '.');
  3977. full_name->append(proto.name());
  3978. ValidateSymbolName(proto.name(), *full_name, proto);
  3979. result->name_ = tables_->AllocateString(proto.name());
  3980. result->full_name_ = full_name;
  3981. result->file_ = file_;
  3982. BUILD_ARRAY(proto, result, method, BuildMethod, result);
  3983. // Copy options.
  3984. if (!proto.has_options()) {
  3985. result->options_ = NULL; // Will set to default_instance later.
  3986. } else {
  3987. AllocateOptions(proto.options(), result);
  3988. }
  3989. AddSymbol(result->full_name(), NULL, result->name(),
  3990. proto, Symbol(result));
  3991. }
  3992. void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto,
  3993. const ServiceDescriptor* parent,
  3994. MethodDescriptor* result) {
  3995. result->name_ = tables_->AllocateString(proto.name());
  3996. result->service_ = parent;
  3997. string* full_name = tables_->AllocateString(parent->full_name());
  3998. full_name->append(1, '.');
  3999. full_name->append(*result->name_);
  4000. result->full_name_ = full_name;
  4001. ValidateSymbolName(proto.name(), *full_name, proto);
  4002. // These will be filled in when cross-linking.
  4003. result->input_type_ = NULL;
  4004. result->output_type_ = NULL;
  4005. // Copy options.
  4006. if (!proto.has_options()) {
  4007. result->options_ = NULL; // Will set to default_instance later.
  4008. } else {
  4009. AllocateOptions(proto.options(), result);
  4010. }
  4011. result->client_streaming_ = proto.client_streaming();
  4012. result->server_streaming_ = proto.server_streaming();
  4013. AddSymbol(result->full_name(), parent, result->name(),
  4014. proto, Symbol(result));
  4015. }
  4016. #undef BUILD_ARRAY
  4017. // -------------------------------------------------------------------
  4018. void DescriptorBuilder::CrossLinkFile(
  4019. FileDescriptor* file, const FileDescriptorProto& proto) {
  4020. if (file->options_ == NULL) {
  4021. file->options_ = &FileOptions::default_instance();
  4022. }
  4023. for (int i = 0; i < file->message_type_count(); i++) {
  4024. CrossLinkMessage(&file->message_types_[i], proto.message_type(i));
  4025. }
  4026. for (int i = 0; i < file->extension_count(); i++) {
  4027. CrossLinkField(&file->extensions_[i], proto.extension(i));
  4028. }
  4029. for (int i = 0; i < file->enum_type_count(); i++) {
  4030. CrossLinkEnum(&file->enum_types_[i], proto.enum_type(i));
  4031. }
  4032. for (int i = 0; i < file->service_count(); i++) {
  4033. CrossLinkService(&file->services_[i], proto.service(i));
  4034. }
  4035. }
  4036. void DescriptorBuilder::CrossLinkMessage(
  4037. Descriptor* message, const DescriptorProto& proto) {
  4038. if (message->options_ == NULL) {
  4039. message->options_ = &MessageOptions::default_instance();
  4040. }
  4041. for (int i = 0; i < message->nested_type_count(); i++) {
  4042. CrossLinkMessage(&message->nested_types_[i], proto.nested_type(i));
  4043. }
  4044. for (int i = 0; i < message->enum_type_count(); i++) {
  4045. CrossLinkEnum(&message->enum_types_[i], proto.enum_type(i));
  4046. }
  4047. for (int i = 0; i < message->field_count(); i++) {
  4048. CrossLinkField(&message->fields_[i], proto.field(i));
  4049. }
  4050. for (int i = 0; i < message->extension_count(); i++) {
  4051. CrossLinkField(&message->extensions_[i], proto.extension(i));
  4052. }
  4053. // Set up field array for each oneof.
  4054. // First count the number of fields per oneof.
  4055. for (int i = 0; i < message->field_count(); i++) {
  4056. const OneofDescriptor* oneof_decl = message->field(i)->containing_oneof();
  4057. if (oneof_decl != NULL) {
  4058. // Make sure fields belonging to the same oneof are defined consecutively.
  4059. // This enables optimizations in codegens and reflection libraries to
  4060. // skip fields in the oneof group, as only one of the field can be set.
  4061. // Note that field_count() returns how many fields in this oneof we have
  4062. // seen so far. field_count() > 0 guarantees that i > 0, so field(i-1) is
  4063. // safe.
  4064. if (oneof_decl->field_count() > 0 &&
  4065. message->field(i - 1)->containing_oneof() != oneof_decl) {
  4066. AddError(
  4067. message->full_name() + "." + message->field(i - 1)->name(),
  4068. proto.field(i - 1), DescriptorPool::ErrorCollector::OTHER,
  4069. strings::Substitute(
  4070. "Fields in the same oneof must be defined consecutively. "
  4071. "\"$0\" cannot be defined before the completion of the "
  4072. "\"$1\" oneof definition.",
  4073. message->field(i - 1)->name(), oneof_decl->name()));
  4074. }
  4075. // Must go through oneof_decls_ array to get a non-const version of the
  4076. // OneofDescriptor.
  4077. ++message->oneof_decls_[oneof_decl->index()].field_count_;
  4078. }
  4079. }
  4080. // Then allocate the arrays.
  4081. for (int i = 0; i < message->oneof_decl_count(); i++) {
  4082. OneofDescriptor* oneof_decl = &message->oneof_decls_[i];
  4083. if (oneof_decl->field_count() == 0) {
  4084. AddError(message->full_name() + "." + oneof_decl->name(),
  4085. proto.oneof_decl(i),
  4086. DescriptorPool::ErrorCollector::NAME,
  4087. "Oneof must have at least one field.");
  4088. }
  4089. oneof_decl->fields_ =
  4090. tables_->AllocateArray<const FieldDescriptor*>(oneof_decl->field_count_);
  4091. oneof_decl->field_count_ = 0;
  4092. }
  4093. // Then fill them in.
  4094. for (int i = 0; i < message->field_count(); i++) {
  4095. const OneofDescriptor* oneof_decl = message->field(i)->containing_oneof();
  4096. if (oneof_decl != NULL) {
  4097. OneofDescriptor* mutable_oneof_decl =
  4098. &message->oneof_decls_[oneof_decl->index()];
  4099. message->fields_[i].index_in_oneof_ = mutable_oneof_decl->field_count_;
  4100. mutable_oneof_decl->fields_[mutable_oneof_decl->field_count_++] =
  4101. message->field(i);
  4102. }
  4103. }
  4104. }
  4105. void DescriptorBuilder::CrossLinkField(
  4106. FieldDescriptor* field, const FieldDescriptorProto& proto) {
  4107. if (field->options_ == NULL) {
  4108. field->options_ = &FieldOptions::default_instance();
  4109. }
  4110. if (proto.has_extendee()) {
  4111. Symbol extendee = LookupSymbol(proto.extendee(), field->full_name(),
  4112. PLACEHOLDER_EXTENDABLE_MESSAGE);
  4113. if (extendee.IsNull()) {
  4114. AddNotDefinedError(field->full_name(), proto,
  4115. DescriptorPool::ErrorCollector::EXTENDEE,
  4116. proto.extendee());
  4117. return;
  4118. } else if (extendee.type != Symbol::MESSAGE) {
  4119. AddError(field->full_name(), proto,
  4120. DescriptorPool::ErrorCollector::EXTENDEE,
  4121. "\"" + proto.extendee() + "\" is not a message type.");
  4122. return;
  4123. }
  4124. field->containing_type_ = extendee.descriptor;
  4125. const Descriptor::ExtensionRange* extension_range = field->containing_type()
  4126. ->FindExtensionRangeContainingNumber(field->number());
  4127. if (extension_range == NULL) {
  4128. AddError(field->full_name(), proto,
  4129. DescriptorPool::ErrorCollector::NUMBER,
  4130. strings::Substitute("\"$0\" does not declare $1 as an "
  4131. "extension number.",
  4132. field->containing_type()->full_name(),
  4133. field->number()));
  4134. }
  4135. }
  4136. if (field->containing_oneof() != NULL) {
  4137. if (field->label() != FieldDescriptor::LABEL_OPTIONAL) {
  4138. // Note that this error will never happen when parsing .proto files.
  4139. // It can only happen if you manually construct a FileDescriptorProto
  4140. // that is incorrect.
  4141. AddError(field->full_name(), proto,
  4142. DescriptorPool::ErrorCollector::NAME,
  4143. "Fields of oneofs must themselves have label LABEL_OPTIONAL.");
  4144. }
  4145. }
  4146. if (proto.has_type_name()) {
  4147. // Assume we are expecting a message type unless the proto contains some
  4148. // evidence that it expects an enum type. This only makes a difference if
  4149. // we end up creating a placeholder.
  4150. bool expecting_enum = (proto.type() == FieldDescriptorProto::TYPE_ENUM) ||
  4151. proto.has_default_value();
  4152. Symbol type =
  4153. LookupSymbol(proto.type_name(), field->full_name(),
  4154. expecting_enum ? PLACEHOLDER_ENUM : PLACEHOLDER_MESSAGE,
  4155. LOOKUP_TYPES);
  4156. // If the type is a weak type, we change the type to a google.protobuf.Empty field.
  4157. if (type.IsNull() && !pool_->enforce_weak_ && proto.options().weak()) {
  4158. type = FindSymbol(kNonLinkedWeakMessageReplacementName);
  4159. }
  4160. if (type.IsNull()) {
  4161. AddNotDefinedError(field->full_name(), proto,
  4162. DescriptorPool::ErrorCollector::TYPE,
  4163. proto.type_name());
  4164. return;
  4165. }
  4166. if (!proto.has_type()) {
  4167. // Choose field type based on symbol.
  4168. if (type.type == Symbol::MESSAGE) {
  4169. field->type_ = FieldDescriptor::TYPE_MESSAGE;
  4170. } else if (type.type == Symbol::ENUM) {
  4171. field->type_ = FieldDescriptor::TYPE_ENUM;
  4172. } else {
  4173. AddError(field->full_name(), proto,
  4174. DescriptorPool::ErrorCollector::TYPE,
  4175. "\"" + proto.type_name() + "\" is not a type.");
  4176. return;
  4177. }
  4178. }
  4179. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
  4180. if (type.type != Symbol::MESSAGE) {
  4181. AddError(field->full_name(), proto,
  4182. DescriptorPool::ErrorCollector::TYPE,
  4183. "\"" + proto.type_name() + "\" is not a message type.");
  4184. return;
  4185. }
  4186. field->message_type_ = type.descriptor;
  4187. if (field->has_default_value()) {
  4188. AddError(field->full_name(), proto,
  4189. DescriptorPool::ErrorCollector::DEFAULT_VALUE,
  4190. "Messages can't have default values.");
  4191. }
  4192. } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
  4193. if (type.type != Symbol::ENUM) {
  4194. AddError(field->full_name(), proto,
  4195. DescriptorPool::ErrorCollector::TYPE,
  4196. "\"" + proto.type_name() + "\" is not an enum type.");
  4197. return;
  4198. }
  4199. field->enum_type_ = type.enum_descriptor;
  4200. if (field->enum_type()->is_placeholder_) {
  4201. // We can't look up default values for placeholder types. We'll have
  4202. // to just drop them.
  4203. field->has_default_value_ = false;
  4204. }
  4205. if (field->has_default_value()) {
  4206. // Ensure that the default value is an identifier. Parser cannot always
  4207. // verify this because it does not have complete type information.
  4208. // N.B. that this check yields better error messages but is not
  4209. // necessary for correctness (an enum symbol must be a valid identifier
  4210. // anyway), only for better errors.
  4211. if (!io::Tokenizer::IsIdentifier(proto.default_value())) {
  4212. AddError(field->full_name(), proto,
  4213. DescriptorPool::ErrorCollector::DEFAULT_VALUE,
  4214. "Default value for an enum field must be an identifier.");
  4215. } else {
  4216. // We can't just use field->enum_type()->FindValueByName() here
  4217. // because that locks the pool's mutex, which we have already locked
  4218. // at this point.
  4219. Symbol default_value =
  4220. LookupSymbolNoPlaceholder(proto.default_value(),
  4221. field->enum_type()->full_name());
  4222. if (default_value.type == Symbol::ENUM_VALUE &&
  4223. default_value.enum_value_descriptor->type() ==
  4224. field->enum_type()) {
  4225. field->default_value_enum_ = default_value.enum_value_descriptor;
  4226. } else {
  4227. AddError(field->full_name(), proto,
  4228. DescriptorPool::ErrorCollector::DEFAULT_VALUE,
  4229. "Enum type \"" + field->enum_type()->full_name() +
  4230. "\" has no value named \"" + proto.default_value() +
  4231. "\".");
  4232. }
  4233. }
  4234. } else if (field->enum_type()->value_count() > 0) {
  4235. // All enums must have at least one value, or we would have reported
  4236. // an error elsewhere. We use the first defined value as the default
  4237. // if a default is not explicitly defined.
  4238. field->default_value_enum_ = field->enum_type()->value(0);
  4239. }
  4240. } else {
  4241. AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
  4242. "Field with primitive type has type_name.");
  4243. }
  4244. } else {
  4245. if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ||
  4246. field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) {
  4247. AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
  4248. "Field with message or enum type missing type_name.");
  4249. }
  4250. }
  4251. // Add the field to the fields-by-number table.
  4252. // Note: We have to do this *after* cross-linking because extensions do not
  4253. // know their containing type until now.
  4254. if (!file_tables_->AddFieldByNumber(field)) {
  4255. const FieldDescriptor* conflicting_field =
  4256. file_tables_->FindFieldByNumber(field->containing_type(),
  4257. field->number());
  4258. if (field->is_extension()) {
  4259. AddError(field->full_name(), proto,
  4260. DescriptorPool::ErrorCollector::NUMBER,
  4261. strings::Substitute("Extension number $0 has already been used "
  4262. "in \"$1\" by extension \"$2\".",
  4263. field->number(),
  4264. field->containing_type()->full_name(),
  4265. conflicting_field->full_name()));
  4266. } else {
  4267. AddError(field->full_name(), proto,
  4268. DescriptorPool::ErrorCollector::NUMBER,
  4269. strings::Substitute("Field number $0 has already been used in "
  4270. "\"$1\" by field \"$2\".",
  4271. field->number(),
  4272. field->containing_type()->full_name(),
  4273. conflicting_field->name()));
  4274. }
  4275. } else {
  4276. if (field->is_extension()) {
  4277. if (!tables_->AddExtension(field)) {
  4278. const FieldDescriptor* conflicting_field =
  4279. tables_->FindExtension(field->containing_type(), field->number());
  4280. string error_msg = strings::Substitute(
  4281. "Extension number $0 has already been used in \"$1\" by extension "
  4282. "\"$2\" defined in $3.",
  4283. field->number(),
  4284. field->containing_type()->full_name(),
  4285. conflicting_field->full_name(),
  4286. conflicting_field->file()->name());
  4287. // Conflicting extension numbers should be an error. However, before
  4288. // turning this into an error we need to fix all existing broken
  4289. // protos first.
  4290. // TODO(xiaofeng): Change this to an error.
  4291. AddWarning(field->full_name(), proto,
  4292. DescriptorPool::ErrorCollector::NUMBER, error_msg);
  4293. }
  4294. }
  4295. }
  4296. // Add the field to the lowercase-name and camelcase-name tables.
  4297. file_tables_->AddFieldByStylizedNames(field);
  4298. }
  4299. void DescriptorBuilder::CrossLinkEnum(
  4300. EnumDescriptor* enum_type, const EnumDescriptorProto& proto) {
  4301. if (enum_type->options_ == NULL) {
  4302. enum_type->options_ = &EnumOptions::default_instance();
  4303. }
  4304. for (int i = 0; i < enum_type->value_count(); i++) {
  4305. CrossLinkEnumValue(&enum_type->values_[i], proto.value(i));
  4306. }
  4307. }
  4308. void DescriptorBuilder::CrossLinkEnumValue(
  4309. EnumValueDescriptor* enum_value,
  4310. const EnumValueDescriptorProto& /* proto */) {
  4311. if (enum_value->options_ == NULL) {
  4312. enum_value->options_ = &EnumValueOptions::default_instance();
  4313. }
  4314. }
  4315. void DescriptorBuilder::CrossLinkService(
  4316. ServiceDescriptor* service, const ServiceDescriptorProto& proto) {
  4317. if (service->options_ == NULL) {
  4318. service->options_ = &ServiceOptions::default_instance();
  4319. }
  4320. for (int i = 0; i < service->method_count(); i++) {
  4321. CrossLinkMethod(&service->methods_[i], proto.method(i));
  4322. }
  4323. }
  4324. void DescriptorBuilder::CrossLinkMethod(
  4325. MethodDescriptor* method, const MethodDescriptorProto& proto) {
  4326. if (method->options_ == NULL) {
  4327. method->options_ = &MethodOptions::default_instance();
  4328. }
  4329. Symbol input_type = LookupSymbol(proto.input_type(), method->full_name());
  4330. if (input_type.IsNull()) {
  4331. AddNotDefinedError(method->full_name(), proto,
  4332. DescriptorPool::ErrorCollector::INPUT_TYPE,
  4333. proto.input_type());
  4334. } else if (input_type.type != Symbol::MESSAGE) {
  4335. AddError(method->full_name(), proto,
  4336. DescriptorPool::ErrorCollector::INPUT_TYPE,
  4337. "\"" + proto.input_type() + "\" is not a message type.");
  4338. } else {
  4339. method->input_type_ = input_type.descriptor;
  4340. }
  4341. Symbol output_type = LookupSymbol(proto.output_type(), method->full_name());
  4342. if (output_type.IsNull()) {
  4343. AddNotDefinedError(method->full_name(), proto,
  4344. DescriptorPool::ErrorCollector::OUTPUT_TYPE,
  4345. proto.output_type());
  4346. } else if (output_type.type != Symbol::MESSAGE) {
  4347. AddError(method->full_name(), proto,
  4348. DescriptorPool::ErrorCollector::OUTPUT_TYPE,
  4349. "\"" + proto.output_type() + "\" is not a message type.");
  4350. } else {
  4351. method->output_type_ = output_type.descriptor;
  4352. }
  4353. }
  4354. // -------------------------------------------------------------------
  4355. #define VALIDATE_OPTIONS_FROM_ARRAY(descriptor, array_name, type) \
  4356. for (int i = 0; i < descriptor->array_name##_count(); ++i) { \
  4357. Validate##type##Options(descriptor->array_name##s_ + i, \
  4358. proto.array_name(i)); \
  4359. }
  4360. // Determine if the file uses optimize_for = LITE_RUNTIME, being careful to
  4361. // avoid problems that exist at init time.
  4362. static bool IsLite(const FileDescriptor* file) {
  4363. // TODO(kenton): I don't even remember how many of these conditions are
  4364. // actually possible. I'm just being super-safe.
  4365. return file != NULL &&
  4366. &file->options() != &FileOptions::default_instance() &&
  4367. file->options().optimize_for() == FileOptions::LITE_RUNTIME;
  4368. }
  4369. void DescriptorBuilder::ValidateFileOptions(FileDescriptor* file,
  4370. const FileDescriptorProto& proto) {
  4371. VALIDATE_OPTIONS_FROM_ARRAY(file, message_type, Message);
  4372. VALIDATE_OPTIONS_FROM_ARRAY(file, enum_type, Enum);
  4373. VALIDATE_OPTIONS_FROM_ARRAY(file, service, Service);
  4374. VALIDATE_OPTIONS_FROM_ARRAY(file, extension, Field);
  4375. // Lite files can only be imported by other Lite files.
  4376. if (!IsLite(file)) {
  4377. for (int i = 0; i < file->dependency_count(); i++) {
  4378. if (IsLite(file->dependency(i))) {
  4379. AddError(
  4380. file->name(), proto,
  4381. DescriptorPool::ErrorCollector::OTHER,
  4382. "Files that do not use optimize_for = LITE_RUNTIME cannot import "
  4383. "files which do use this option. This file is not lite, but it "
  4384. "imports \"" + file->dependency(i)->name() + "\" which is.");
  4385. break;
  4386. }
  4387. }
  4388. }
  4389. if (file->syntax() == FileDescriptor::SYNTAX_PROTO3) {
  4390. ValidateProto3(file, proto);
  4391. }
  4392. }
  4393. void DescriptorBuilder::ValidateProto3(
  4394. FileDescriptor* file, const FileDescriptorProto& proto) {
  4395. for (int i = 0; i < file->extension_count(); ++i) {
  4396. ValidateProto3Field(file->extensions_ + i, proto.extension(i));
  4397. }
  4398. for (int i = 0; i < file->message_type_count(); ++i) {
  4399. ValidateProto3Message(file->message_types_ + i, proto.message_type(i));
  4400. }
  4401. for (int i = 0; i < file->enum_type_count(); ++i) {
  4402. ValidateProto3Enum(file->enum_types_ + i, proto.enum_type(i));
  4403. }
  4404. if (IsLite(file)) {
  4405. AddError(file->name(), proto,
  4406. DescriptorPool::ErrorCollector::OTHER,
  4407. "Lite runtime is not supported in proto3.");
  4408. }
  4409. }
  4410. void DescriptorBuilder::ValidateProto3Message(
  4411. Descriptor* message, const DescriptorProto& proto) {
  4412. for (int i = 0; i < message->nested_type_count(); ++i) {
  4413. ValidateProto3Message(message->nested_types_ + i,
  4414. proto.nested_type(i));
  4415. }
  4416. for (int i = 0; i < message->enum_type_count(); ++i) {
  4417. ValidateProto3Enum(message->enum_types_ + i,
  4418. proto.enum_type(i));
  4419. }
  4420. for (int i = 0; i < message->field_count(); ++i) {
  4421. ValidateProto3Field(message->fields_ + i, proto.field(i));
  4422. }
  4423. for (int i = 0; i < message->extension_count(); ++i) {
  4424. ValidateProto3Field(message->extensions_ +i, proto.extension(i));
  4425. }
  4426. if (message->extension_range_count() > 0) {
  4427. AddError(message->full_name(), proto,
  4428. DescriptorPool::ErrorCollector::OTHER,
  4429. "Extension ranges are not allowed in proto3.");
  4430. }
  4431. if (message->options().message_set_wire_format()) {
  4432. // Using MessageSet doesn't make sense since we disallow extensions.
  4433. AddError(message->full_name(), proto,
  4434. DescriptorPool::ErrorCollector::OTHER,
  4435. "MessageSet is not supported in proto3.");
  4436. }
  4437. }
  4438. void DescriptorBuilder::ValidateProto3Field(
  4439. FieldDescriptor* field, const FieldDescriptorProto& proto) {
  4440. if (field->is_extension() &&
  4441. !AllowedExtendeeInProto3(field->containing_type()->full_name())) {
  4442. AddError(field->full_name(), proto,
  4443. DescriptorPool::ErrorCollector::OTHER,
  4444. "Extensions in proto3 are only allowed for defining options.");
  4445. }
  4446. if (field->is_required()) {
  4447. AddError(field->full_name(), proto,
  4448. DescriptorPool::ErrorCollector::OTHER,
  4449. "Required fields are not allowed in proto3.");
  4450. }
  4451. if (field->has_default_value()) {
  4452. AddError(
  4453. field->full_name(), proto, DescriptorPool::ErrorCollector::OTHER,
  4454. "Explicit default values are not allowed in proto3.");
  4455. }
  4456. if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM &&
  4457. field->enum_type() &&
  4458. field->enum_type()->file()->syntax() != FileDescriptor::SYNTAX_PROTO3) {
  4459. // Proto3 messages can only use Proto3 enum types; otherwise we can't
  4460. // guarantee that the default value is zero.
  4461. AddError(field->full_name(), proto,
  4462. DescriptorPool::ErrorCollector::TYPE,
  4463. "Enum type \"" + field->enum_type()->full_name() +
  4464. "\" is not a proto3 enum, but is used in \"" +
  4465. field->containing_type()->full_name() +
  4466. "\" which is a proto3 message type.");
  4467. }
  4468. if (field->type() == FieldDescriptor::TYPE_GROUP) {
  4469. AddError(field->full_name(), proto,
  4470. DescriptorPool::ErrorCollector::TYPE,
  4471. "Groups are not supported in proto3 syntax.");
  4472. }
  4473. }
  4474. void DescriptorBuilder::ValidateProto3Enum(
  4475. EnumDescriptor* enm, const EnumDescriptorProto& proto) {
  4476. if (enm->value_count() > 0 && enm->value(0)->number() != 0) {
  4477. AddError(
  4478. enm->full_name(), proto, DescriptorPool::ErrorCollector::OTHER,
  4479. "The first enum value must be zero in proto3.");
  4480. }
  4481. }
  4482. void DescriptorBuilder::ValidateMessageOptions(Descriptor* message,
  4483. const DescriptorProto& proto) {
  4484. VALIDATE_OPTIONS_FROM_ARRAY(message, field, Field);
  4485. VALIDATE_OPTIONS_FROM_ARRAY(message, nested_type, Message);
  4486. VALIDATE_OPTIONS_FROM_ARRAY(message, enum_type, Enum);
  4487. VALIDATE_OPTIONS_FROM_ARRAY(message, extension, Field);
  4488. const int64 max_extension_range =
  4489. static_cast<int64>(message->options().message_set_wire_format() ?
  4490. kint32max :
  4491. FieldDescriptor::kMaxNumber);
  4492. for (int i = 0; i < message->extension_range_count(); ++i) {
  4493. if (message->extension_range(i)->end > max_extension_range + 1) {
  4494. AddError(
  4495. message->full_name(), proto.extension_range(i),
  4496. DescriptorPool::ErrorCollector::NUMBER,
  4497. strings::Substitute("Extension numbers cannot be greater than $0.",
  4498. max_extension_range));
  4499. }
  4500. }
  4501. }
  4502. void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field,
  4503. const FieldDescriptorProto& proto) {
  4504. // Only message type fields may be lazy.
  4505. if (field->options().lazy()) {
  4506. if (field->type() != FieldDescriptor::TYPE_MESSAGE) {
  4507. AddError(field->full_name(), proto,
  4508. DescriptorPool::ErrorCollector::TYPE,
  4509. "[lazy = true] can only be specified for submessage fields.");
  4510. }
  4511. }
  4512. // Only repeated primitive fields may be packed.
  4513. if (field->options().packed() && !field->is_packable()) {
  4514. AddError(
  4515. field->full_name(), proto,
  4516. DescriptorPool::ErrorCollector::TYPE,
  4517. "[packed = true] can only be specified for repeated primitive fields.");
  4518. }
  4519. // Note: Default instance may not yet be initialized here, so we have to
  4520. // avoid reading from it.
  4521. if (field->containing_type_ != NULL &&
  4522. &field->containing_type()->options() !=
  4523. &MessageOptions::default_instance() &&
  4524. field->containing_type()->options().message_set_wire_format()) {
  4525. if (field->is_extension()) {
  4526. if (!field->is_optional() ||
  4527. field->type() != FieldDescriptor::TYPE_MESSAGE) {
  4528. AddError(field->full_name(), proto,
  4529. DescriptorPool::ErrorCollector::TYPE,
  4530. "Extensions of MessageSets must be optional messages.");
  4531. }
  4532. } else {
  4533. AddError(field->full_name(), proto,
  4534. DescriptorPool::ErrorCollector::NAME,
  4535. "MessageSets cannot have fields, only extensions.");
  4536. }
  4537. }
  4538. // Lite extensions can only be of Lite types.
  4539. if (IsLite(field->file()) &&
  4540. field->containing_type_ != NULL &&
  4541. !IsLite(field->containing_type()->file())) {
  4542. AddError(field->full_name(), proto,
  4543. DescriptorPool::ErrorCollector::EXTENDEE,
  4544. "Extensions to non-lite types can only be declared in non-lite "
  4545. "files. Note that you cannot extend a non-lite type to contain "
  4546. "a lite type, but the reverse is allowed.");
  4547. }
  4548. // Validate map types.
  4549. if (field->is_map()) {
  4550. if (!ValidateMapEntry(field, proto)) {
  4551. AddError(field->full_name(), proto,
  4552. DescriptorPool::ErrorCollector::OTHER,
  4553. "map_entry should not be set explicitly. Use map<KeyType, "
  4554. "ValueType> instead.");
  4555. }
  4556. }
  4557. }
  4558. void DescriptorBuilder::ValidateEnumOptions(EnumDescriptor* enm,
  4559. const EnumDescriptorProto& proto) {
  4560. VALIDATE_OPTIONS_FROM_ARRAY(enm, value, EnumValue);
  4561. if (!enm->options().has_allow_alias() || !enm->options().allow_alias()) {
  4562. map<int, string> used_values;
  4563. for (int i = 0; i < enm->value_count(); ++i) {
  4564. const EnumValueDescriptor* enum_value = enm->value(i);
  4565. if (used_values.find(enum_value->number()) != used_values.end()) {
  4566. string error =
  4567. "\"" + enum_value->full_name() +
  4568. "\" uses the same enum value as \"" +
  4569. used_values[enum_value->number()] + "\". If this is intended, set "
  4570. "'option allow_alias = true;' to the enum definition.";
  4571. if (!enm->options().allow_alias()) {
  4572. // Generate error if duplicated enum values are explicitly disallowed.
  4573. AddError(enm->full_name(), proto,
  4574. DescriptorPool::ErrorCollector::NUMBER,
  4575. error);
  4576. } else {
  4577. // Generate warning if duplicated values are found but the option
  4578. // isn't set.
  4579. GOOGLE_LOG(ERROR) << error;
  4580. }
  4581. } else {
  4582. used_values[enum_value->number()] = enum_value->full_name();
  4583. }
  4584. }
  4585. }
  4586. }
  4587. void DescriptorBuilder::ValidateEnumValueOptions(
  4588. EnumValueDescriptor* /* enum_value */,
  4589. const EnumValueDescriptorProto& /* proto */) {
  4590. // Nothing to do so far.
  4591. }
  4592. void DescriptorBuilder::ValidateServiceOptions(ServiceDescriptor* service,
  4593. const ServiceDescriptorProto& proto) {
  4594. if (IsLite(service->file()) &&
  4595. (service->file()->options().cc_generic_services() ||
  4596. service->file()->options().java_generic_services())) {
  4597. AddError(service->full_name(), proto,
  4598. DescriptorPool::ErrorCollector::NAME,
  4599. "Files with optimize_for = LITE_RUNTIME cannot define services "
  4600. "unless you set both options cc_generic_services and "
  4601. "java_generic_sevices to false.");
  4602. }
  4603. VALIDATE_OPTIONS_FROM_ARRAY(service, method, Method);
  4604. }
  4605. void DescriptorBuilder::ValidateMethodOptions(MethodDescriptor* /* method */,
  4606. const MethodDescriptorProto& /* proto */) {
  4607. // Nothing to do so far.
  4608. }
  4609. bool DescriptorBuilder::ValidateMapEntry(FieldDescriptor* field,
  4610. const FieldDescriptorProto& proto) {
  4611. const Descriptor* message = field->message_type();
  4612. if (// Must not contain extensions, extension range or nested message or
  4613. // enums
  4614. message->extension_count() != 0 ||
  4615. field->label() != FieldDescriptor::LABEL_REPEATED ||
  4616. message->extension_range_count() != 0 ||
  4617. message->nested_type_count() != 0 || message->enum_type_count() != 0 ||
  4618. // Must contain exactly two fields
  4619. message->field_count() != 2 ||
  4620. // Field name and message name must match
  4621. message->name() != ToCamelCase(field->name(), false) + "Entry" ||
  4622. // Entry message must be in the same containing type of the field.
  4623. field->containing_type() != message->containing_type()) {
  4624. return false;
  4625. }
  4626. const FieldDescriptor* key = message->field(0);
  4627. const FieldDescriptor* value = message->field(1);
  4628. if (key->label() != FieldDescriptor::LABEL_OPTIONAL || key->number() != 1 ||
  4629. key->name() != "key") {
  4630. return false;
  4631. }
  4632. if (value->label() != FieldDescriptor::LABEL_OPTIONAL ||
  4633. value->number() != 2 || value->name() != "value") {
  4634. return false;
  4635. }
  4636. // Check key types are legal.
  4637. switch (key->type()) {
  4638. case FieldDescriptor::TYPE_ENUM:
  4639. AddError(
  4640. field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
  4641. "Key in map fields cannot be enum types.");
  4642. break;
  4643. case FieldDescriptor::TYPE_FLOAT:
  4644. case FieldDescriptor::TYPE_DOUBLE:
  4645. case FieldDescriptor::TYPE_MESSAGE:
  4646. case FieldDescriptor::TYPE_GROUP:
  4647. case FieldDescriptor::TYPE_BYTES:
  4648. AddError(
  4649. field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
  4650. "Key in map fields cannot be float/double, bytes or message types.");
  4651. break;
  4652. case FieldDescriptor::TYPE_BOOL_X:
  4653. case FieldDescriptor::TYPE_INT32:
  4654. case FieldDescriptor::TYPE_INT64:
  4655. case FieldDescriptor::TYPE_SINT32:
  4656. case FieldDescriptor::TYPE_SINT64:
  4657. case FieldDescriptor::TYPE_STRING:
  4658. case FieldDescriptor::TYPE_UINT32:
  4659. case FieldDescriptor::TYPE_UINT64:
  4660. case FieldDescriptor::TYPE_FIXED32:
  4661. case FieldDescriptor::TYPE_FIXED64:
  4662. case FieldDescriptor::TYPE_SFIXED32:
  4663. case FieldDescriptor::TYPE_SFIXED64:
  4664. // Legal cases
  4665. break;
  4666. // Do not add a default, so that the compiler will complain when new types
  4667. // are added.
  4668. }
  4669. if (value->type() == FieldDescriptor::TYPE_ENUM) {
  4670. if (value->enum_type()->value(0)->number() != 0) {
  4671. AddError(
  4672. field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE,
  4673. "Enum value in map must define 0 as the first value.");
  4674. }
  4675. }
  4676. return true;
  4677. }
  4678. void DescriptorBuilder::DetectMapConflicts(const Descriptor* message,
  4679. const DescriptorProto& proto) {
  4680. map<string, const Descriptor*> seen_types;
  4681. for (int i = 0; i < message->nested_type_count(); ++i) {
  4682. const Descriptor* nested = message->nested_type(i);
  4683. pair<map<string, const Descriptor*>::iterator, bool> result =
  4684. seen_types.insert(std::make_pair(nested->name(), nested));
  4685. if (!result.second) {
  4686. if (result.first->second->options().map_entry() ||
  4687. nested->options().map_entry()) {
  4688. AddError(message->full_name(), proto,
  4689. DescriptorPool::ErrorCollector::NAME,
  4690. "Expanded map entry type " + nested->name() +
  4691. " conflicts with an existing nested message type.");
  4692. }
  4693. }
  4694. // Recursively test on the nested types.
  4695. DetectMapConflicts(message->nested_type(i), proto.nested_type(i));
  4696. }
  4697. // Check for conflicted field names.
  4698. for (int i = 0; i < message->field_count(); ++i) {
  4699. const FieldDescriptor* field = message->field(i);
  4700. map<string, const Descriptor*>::iterator iter =
  4701. seen_types.find(field->name());
  4702. if (iter != seen_types.end() && iter->second->options().map_entry()) {
  4703. AddError(message->full_name(), proto,
  4704. DescriptorPool::ErrorCollector::NAME,
  4705. "Expanded map entry type " + iter->second->name() +
  4706. " conflicts with an existing field.");
  4707. }
  4708. }
  4709. // Check for conflicted enum names.
  4710. for (int i = 0; i < message->enum_type_count(); ++i) {
  4711. const EnumDescriptor* enum_desc = message->enum_type(i);
  4712. map<string, const Descriptor*>::iterator iter =
  4713. seen_types.find(enum_desc->name());
  4714. if (iter != seen_types.end() && iter->second->options().map_entry()) {
  4715. AddError(message->full_name(), proto,
  4716. DescriptorPool::ErrorCollector::NAME,
  4717. "Expanded map entry type " + iter->second->name() +
  4718. " conflicts with an existing enum type.");
  4719. }
  4720. }
  4721. // Check for conflicted oneof names.
  4722. for (int i = 0; i < message->oneof_decl_count(); ++i) {
  4723. const OneofDescriptor* oneof_desc = message->oneof_decl(i);
  4724. map<string, const Descriptor*>::iterator iter =
  4725. seen_types.find(oneof_desc->name());
  4726. if (iter != seen_types.end() && iter->second->options().map_entry()) {
  4727. AddError(message->full_name(), proto,
  4728. DescriptorPool::ErrorCollector::NAME,
  4729. "Expanded map entry type " + iter->second->name() +
  4730. " conflicts with an existing oneof type.");
  4731. }
  4732. }
  4733. }
  4734. #undef VALIDATE_OPTIONS_FROM_ARRAY
  4735. // -------------------------------------------------------------------
  4736. DescriptorBuilder::OptionInterpreter::OptionInterpreter(
  4737. DescriptorBuilder* builder) : builder_(builder) {
  4738. GOOGLE_CHECK(builder_);
  4739. }
  4740. DescriptorBuilder::OptionInterpreter::~OptionInterpreter() {
  4741. }
  4742. bool DescriptorBuilder::OptionInterpreter::InterpretOptions(
  4743. OptionsToInterpret* options_to_interpret) {
  4744. // Note that these may be in different pools, so we can't use the same
  4745. // descriptor and reflection objects on both.
  4746. Message* options = options_to_interpret->options;
  4747. const Message* original_options = options_to_interpret->original_options;
  4748. bool failed = false;
  4749. options_to_interpret_ = options_to_interpret;
  4750. // Find the uninterpreted_option field in the mutable copy of the options
  4751. // and clear them, since we're about to interpret them.
  4752. const FieldDescriptor* uninterpreted_options_field =
  4753. options->GetDescriptor()->FindFieldByName("uninterpreted_option");
  4754. GOOGLE_CHECK(uninterpreted_options_field != NULL)
  4755. << "No field named \"uninterpreted_option\" in the Options proto.";
  4756. options->GetReflection()->ClearField(options, uninterpreted_options_field);
  4757. // Find the uninterpreted_option field in the original options.
  4758. const FieldDescriptor* original_uninterpreted_options_field =
  4759. original_options->GetDescriptor()->
  4760. FindFieldByName("uninterpreted_option");
  4761. GOOGLE_CHECK(original_uninterpreted_options_field != NULL)
  4762. << "No field named \"uninterpreted_option\" in the Options proto.";
  4763. const int num_uninterpreted_options = original_options->GetReflection()->
  4764. FieldSize(*original_options, original_uninterpreted_options_field);
  4765. for (int i = 0; i < num_uninterpreted_options; ++i) {
  4766. uninterpreted_option_ = down_cast<const UninterpretedOption*>(
  4767. &original_options->GetReflection()->GetRepeatedMessage(
  4768. *original_options, original_uninterpreted_options_field, i));
  4769. if (!InterpretSingleOption(options)) {
  4770. // Error already added by InterpretSingleOption().
  4771. failed = true;
  4772. break;
  4773. }
  4774. }
  4775. // Reset these, so we don't have any dangling pointers.
  4776. uninterpreted_option_ = NULL;
  4777. options_to_interpret_ = NULL;
  4778. if (!failed) {
  4779. // InterpretSingleOption() added the interpreted options in the
  4780. // UnknownFieldSet, in case the option isn't yet known to us. Now we
  4781. // serialize the options message and deserialize it back. That way, any
  4782. // option fields that we do happen to know about will get moved from the
  4783. // UnknownFieldSet into the real fields, and thus be available right away.
  4784. // If they are not known, that's OK too. They will get reparsed into the
  4785. // UnknownFieldSet and wait there until the message is parsed by something
  4786. // that does know about the options.
  4787. string buf;
  4788. options->AppendToString(&buf);
  4789. GOOGLE_CHECK(options->ParseFromString(buf))
  4790. << "Protocol message serialized itself in invalid fashion.";
  4791. }
  4792. return !failed;
  4793. }
  4794. bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption(
  4795. Message* options) {
  4796. // First do some basic validation.
  4797. if (uninterpreted_option_->name_size() == 0) {
  4798. // This should never happen unless the parser has gone seriously awry or
  4799. // someone has manually created the uninterpreted option badly.
  4800. return AddNameError("Option must have a name.");
  4801. }
  4802. if (uninterpreted_option_->name(0).name_part() == "uninterpreted_option") {
  4803. return AddNameError("Option must not use reserved name "
  4804. "\"uninterpreted_option\".");
  4805. }
  4806. const Descriptor* options_descriptor = NULL;
  4807. // Get the options message's descriptor from the builder's pool, so that we
  4808. // get the version that knows about any extension options declared in the
  4809. // file we're currently building. The descriptor should be there as long as
  4810. // the file we're building imported "google/protobuf/descriptors.proto".
  4811. // Note that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not
  4812. // DescriptorPool::FindMessageTypeByName() because we're already holding the
  4813. // pool's mutex, and the latter method locks it again. We don't use
  4814. // FindSymbol() because files that use custom options only need to depend on
  4815. // the file that defines the option, not descriptor.proto itself.
  4816. Symbol symbol = builder_->FindSymbolNotEnforcingDeps(
  4817. options->GetDescriptor()->full_name());
  4818. if (!symbol.IsNull() && symbol.type == Symbol::MESSAGE) {
  4819. options_descriptor = symbol.descriptor;
  4820. } else {
  4821. // The options message's descriptor was not in the builder's pool, so use
  4822. // the standard version from the generated pool. We're not holding the
  4823. // generated pool's mutex, so we can search it the straightforward way.
  4824. options_descriptor = options->GetDescriptor();
  4825. }
  4826. GOOGLE_CHECK(options_descriptor);
  4827. // We iterate over the name parts to drill into the submessages until we find
  4828. // the leaf field for the option. As we drill down we remember the current
  4829. // submessage's descriptor in |descriptor| and the next field in that
  4830. // submessage in |field|. We also track the fields we're drilling down
  4831. // through in |intermediate_fields|. As we go, we reconstruct the full option
  4832. // name in |debug_msg_name|, for use in error messages.
  4833. const Descriptor* descriptor = options_descriptor;
  4834. const FieldDescriptor* field = NULL;
  4835. vector<const FieldDescriptor*> intermediate_fields;
  4836. string debug_msg_name = "";
  4837. for (int i = 0; i < uninterpreted_option_->name_size(); ++i) {
  4838. const string& name_part = uninterpreted_option_->name(i).name_part();
  4839. if (debug_msg_name.size() > 0) {
  4840. debug_msg_name += ".";
  4841. }
  4842. if (uninterpreted_option_->name(i).is_extension()) {
  4843. debug_msg_name += "(" + name_part + ")";
  4844. // Search for the extension's descriptor as an extension in the builder's
  4845. // pool. Note that we use DescriptorBuilder::LookupSymbol(), not
  4846. // DescriptorPool::FindExtensionByName(), for two reasons: 1) It allows
  4847. // relative lookups, and 2) because we're already holding the pool's
  4848. // mutex, and the latter method locks it again.
  4849. symbol = builder_->LookupSymbol(name_part,
  4850. options_to_interpret_->name_scope);
  4851. if (!symbol.IsNull() && symbol.type == Symbol::FIELD) {
  4852. field = symbol.field_descriptor;
  4853. }
  4854. // If we don't find the field then the field's descriptor was not in the
  4855. // builder's pool, but there's no point in looking in the generated
  4856. // pool. We require that you import the file that defines any extensions
  4857. // you use, so they must be present in the builder's pool.
  4858. } else {
  4859. debug_msg_name += name_part;
  4860. // Search for the field's descriptor as a regular field.
  4861. field = descriptor->FindFieldByName(name_part);
  4862. }
  4863. if (field == NULL) {
  4864. if (get_allow_unknown(builder_->pool_)) {
  4865. // We can't find the option, but AllowUnknownDependencies() is enabled,
  4866. // so we will just leave it as uninterpreted.
  4867. AddWithoutInterpreting(*uninterpreted_option_, options);
  4868. return true;
  4869. } else if (!(builder_->undefine_resolved_name_).empty()) {
  4870. // Option is resolved to a name which is not defined.
  4871. return AddNameError(
  4872. "Option \"" + debug_msg_name + "\" is resolved to \"(" +
  4873. builder_->undefine_resolved_name_ +
  4874. ")\", which is not defined. The innermost scope is searched first "
  4875. "in name resolution. Consider using a leading '.'(i.e., \"(." +
  4876. debug_msg_name.substr(1) +
  4877. "\") to start from the outermost scope.");
  4878. } else {
  4879. return AddNameError("Option \"" + debug_msg_name + "\" unknown.");
  4880. }
  4881. } else if (field->containing_type() != descriptor) {
  4882. if (get_is_placeholder(field->containing_type())) {
  4883. // The field is an extension of a placeholder type, so we can't
  4884. // reliably verify whether it is a valid extension to use here (e.g.
  4885. // we don't know if it is an extension of the correct *Options message,
  4886. // or if it has a valid field number, etc.). Just leave it as
  4887. // uninterpreted instead.
  4888. AddWithoutInterpreting(*uninterpreted_option_, options);
  4889. return true;
  4890. } else {
  4891. // This can only happen if, due to some insane misconfiguration of the
  4892. // pools, we find the options message in one pool but the field in
  4893. // another. This would probably imply a hefty bug somewhere.
  4894. return AddNameError("Option field \"" + debug_msg_name +
  4895. "\" is not a field or extension of message \"" +
  4896. descriptor->name() + "\".");
  4897. }
  4898. } else if (i < uninterpreted_option_->name_size() - 1) {
  4899. if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) {
  4900. return AddNameError("Option \"" + debug_msg_name +
  4901. "\" is an atomic type, not a message.");
  4902. } else if (field->is_repeated()) {
  4903. return AddNameError("Option field \"" + debug_msg_name +
  4904. "\" is a repeated message. Repeated message "
  4905. "options must be initialized using an "
  4906. "aggregate value.");
  4907. } else {
  4908. // Drill down into the submessage.
  4909. intermediate_fields.push_back(field);
  4910. descriptor = field->message_type();
  4911. }
  4912. }
  4913. }
  4914. // We've found the leaf field. Now we use UnknownFieldSets to set its value
  4915. // on the options message. We do so because the message may not yet know
  4916. // about its extension fields, so we may not be able to set the fields
  4917. // directly. But the UnknownFieldSets will serialize to the same wire-format
  4918. // message, so reading that message back in once the extension fields are
  4919. // known will populate them correctly.
  4920. // First see if the option is already set.
  4921. if (!field->is_repeated() && !ExamineIfOptionIsSet(
  4922. intermediate_fields.begin(),
  4923. intermediate_fields.end(),
  4924. field, debug_msg_name,
  4925. options->GetReflection()->GetUnknownFields(*options))) {
  4926. return false; // ExamineIfOptionIsSet() already added the error.
  4927. }
  4928. // First set the value on the UnknownFieldSet corresponding to the
  4929. // innermost message.
  4930. scoped_ptr<UnknownFieldSet> unknown_fields(new UnknownFieldSet());
  4931. if (!SetOptionValue(field, unknown_fields.get())) {
  4932. return false; // SetOptionValue() already added the error.
  4933. }
  4934. // Now wrap the UnknownFieldSet with UnknownFieldSets corresponding to all
  4935. // the intermediate messages.
  4936. for (vector<const FieldDescriptor*>::reverse_iterator iter =
  4937. intermediate_fields.rbegin();
  4938. iter != intermediate_fields.rend(); ++iter) {
  4939. scoped_ptr<UnknownFieldSet> parent_unknown_fields(new UnknownFieldSet());
  4940. switch ((*iter)->type()) {
  4941. case FieldDescriptor::TYPE_MESSAGE: {
  4942. io::StringOutputStream outstr(
  4943. parent_unknown_fields->AddLengthDelimited((*iter)->number()));
  4944. io::CodedOutputStream out(&outstr);
  4945. internal::WireFormat::SerializeUnknownFields(*unknown_fields, &out);
  4946. GOOGLE_CHECK(!out.HadError())
  4947. << "Unexpected failure while serializing option submessage "
  4948. << debug_msg_name << "\".";
  4949. break;
  4950. }
  4951. case FieldDescriptor::TYPE_GROUP: {
  4952. parent_unknown_fields->AddGroup((*iter)->number())
  4953. ->MergeFrom(*unknown_fields);
  4954. break;
  4955. }
  4956. default:
  4957. GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_MESSAGE: "
  4958. << (*iter)->type();
  4959. return false;
  4960. }
  4961. unknown_fields.reset(parent_unknown_fields.release());
  4962. }
  4963. // Now merge the UnknownFieldSet corresponding to the top-level message into
  4964. // the options message.
  4965. options->GetReflection()->MutableUnknownFields(options)->MergeFrom(
  4966. *unknown_fields);
  4967. return true;
  4968. }
  4969. void DescriptorBuilder::OptionInterpreter::AddWithoutInterpreting(
  4970. const UninterpretedOption& uninterpreted_option, Message* options) {
  4971. const FieldDescriptor* field =
  4972. options->GetDescriptor()->FindFieldByName("uninterpreted_option");
  4973. GOOGLE_CHECK(field != NULL);
  4974. options->GetReflection()->AddMessage(options, field)
  4975. ->CopyFrom(uninterpreted_option);
  4976. }
  4977. bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet(
  4978. vector<const FieldDescriptor*>::const_iterator intermediate_fields_iter,
  4979. vector<const FieldDescriptor*>::const_iterator intermediate_fields_end,
  4980. const FieldDescriptor* innermost_field, const string& debug_msg_name,
  4981. const UnknownFieldSet& unknown_fields) {
  4982. // We do linear searches of the UnknownFieldSet and its sub-groups. This
  4983. // should be fine since it's unlikely that any one options structure will
  4984. // contain more than a handful of options.
  4985. if (intermediate_fields_iter == intermediate_fields_end) {
  4986. // We're at the innermost submessage.
  4987. for (int i = 0; i < unknown_fields.field_count(); i++) {
  4988. if (unknown_fields.field(i).number() == innermost_field->number()) {
  4989. return AddNameError("Option \"" + debug_msg_name +
  4990. "\" was already set.");
  4991. }
  4992. }
  4993. return true;
  4994. }
  4995. for (int i = 0; i < unknown_fields.field_count(); i++) {
  4996. if (unknown_fields.field(i).number() ==
  4997. (*intermediate_fields_iter)->number()) {
  4998. const UnknownField* unknown_field = &unknown_fields.field(i);
  4999. FieldDescriptor::Type type = (*intermediate_fields_iter)->type();
  5000. // Recurse into the next submessage.
  5001. switch (type) {
  5002. case FieldDescriptor::TYPE_MESSAGE:
  5003. if (unknown_field->type() == UnknownField::TYPE_LENGTH_DELIMITED) {
  5004. UnknownFieldSet intermediate_unknown_fields;
  5005. if (intermediate_unknown_fields.ParseFromString(
  5006. unknown_field->length_delimited()) &&
  5007. !ExamineIfOptionIsSet(intermediate_fields_iter + 1,
  5008. intermediate_fields_end,
  5009. innermost_field, debug_msg_name,
  5010. intermediate_unknown_fields)) {
  5011. return false; // Error already added.
  5012. }
  5013. }
  5014. break;
  5015. case FieldDescriptor::TYPE_GROUP:
  5016. if (unknown_field->type() == UnknownField::TYPE_GROUP) {
  5017. if (!ExamineIfOptionIsSet(intermediate_fields_iter + 1,
  5018. intermediate_fields_end,
  5019. innermost_field, debug_msg_name,
  5020. unknown_field->group())) {
  5021. return false; // Error already added.
  5022. }
  5023. }
  5024. break;
  5025. default:
  5026. GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_MESSAGE: " << type;
  5027. return false;
  5028. }
  5029. }
  5030. }
  5031. return true;
  5032. }
  5033. bool DescriptorBuilder::OptionInterpreter::SetOptionValue(
  5034. const FieldDescriptor* option_field,
  5035. UnknownFieldSet* unknown_fields) {
  5036. // We switch on the CppType to validate.
  5037. switch (option_field->cpp_type()) {
  5038. case FieldDescriptor::CPPTYPE_INT32:
  5039. if (uninterpreted_option_->has_positive_int_value()) {
  5040. if (uninterpreted_option_->positive_int_value() >
  5041. static_cast<uint64>(kint32max)) {
  5042. return AddValueError("Value out of range for int32 option \"" +
  5043. option_field->full_name() + "\".");
  5044. } else {
  5045. SetInt32(option_field->number(),
  5046. uninterpreted_option_->positive_int_value(),
  5047. option_field->type(), unknown_fields);
  5048. }
  5049. } else if (uninterpreted_option_->has_negative_int_value()) {
  5050. if (uninterpreted_option_->negative_int_value() <
  5051. static_cast<int64>(kint32min)) {
  5052. return AddValueError("Value out of range for int32 option \"" +
  5053. option_field->full_name() + "\".");
  5054. } else {
  5055. SetInt32(option_field->number(),
  5056. uninterpreted_option_->negative_int_value(),
  5057. option_field->type(), unknown_fields);
  5058. }
  5059. } else {
  5060. return AddValueError("Value must be integer for int32 option \"" +
  5061. option_field->full_name() + "\".");
  5062. }
  5063. break;
  5064. case FieldDescriptor::CPPTYPE_INT64:
  5065. if (uninterpreted_option_->has_positive_int_value()) {
  5066. if (uninterpreted_option_->positive_int_value() >
  5067. static_cast<uint64>(kint64max)) {
  5068. return AddValueError("Value out of range for int64 option \"" +
  5069. option_field->full_name() + "\".");
  5070. } else {
  5071. SetInt64(option_field->number(),
  5072. uninterpreted_option_->positive_int_value(),
  5073. option_field->type(), unknown_fields);
  5074. }
  5075. } else if (uninterpreted_option_->has_negative_int_value()) {
  5076. SetInt64(option_field->number(),
  5077. uninterpreted_option_->negative_int_value(),
  5078. option_field->type(), unknown_fields);
  5079. } else {
  5080. return AddValueError("Value must be integer for int64 option \"" +
  5081. option_field->full_name() + "\".");
  5082. }
  5083. break;
  5084. case FieldDescriptor::CPPTYPE_UINT32:
  5085. if (uninterpreted_option_->has_positive_int_value()) {
  5086. if (uninterpreted_option_->positive_int_value() > kuint32max) {
  5087. return AddValueError("Value out of range for uint32 option \"" +
  5088. option_field->name() + "\".");
  5089. } else {
  5090. SetUInt32(option_field->number(),
  5091. uninterpreted_option_->positive_int_value(),
  5092. option_field->type(), unknown_fields);
  5093. }
  5094. } else {
  5095. return AddValueError("Value must be non-negative integer for uint32 "
  5096. "option \"" + option_field->full_name() + "\".");
  5097. }
  5098. break;
  5099. case FieldDescriptor::CPPTYPE_UINT64:
  5100. if (uninterpreted_option_->has_positive_int_value()) {
  5101. SetUInt64(option_field->number(),
  5102. uninterpreted_option_->positive_int_value(),
  5103. option_field->type(), unknown_fields);
  5104. } else {
  5105. return AddValueError("Value must be non-negative integer for uint64 "
  5106. "option \"" + option_field->full_name() + "\".");
  5107. }
  5108. break;
  5109. case FieldDescriptor::CPPTYPE_FLOAT: {
  5110. float value;
  5111. if (uninterpreted_option_->has_double_value()) {
  5112. value = uninterpreted_option_->double_value();
  5113. } else if (uninterpreted_option_->has_positive_int_value()) {
  5114. value = uninterpreted_option_->positive_int_value();
  5115. } else if (uninterpreted_option_->has_negative_int_value()) {
  5116. value = uninterpreted_option_->negative_int_value();
  5117. } else {
  5118. return AddValueError("Value must be number for float option \"" +
  5119. option_field->full_name() + "\".");
  5120. }
  5121. unknown_fields->AddFixed32(option_field->number(),
  5122. google::protobuf::internal::WireFormatLite::EncodeFloat(value));
  5123. break;
  5124. }
  5125. case FieldDescriptor::CPPTYPE_DOUBLE: {
  5126. double value;
  5127. if (uninterpreted_option_->has_double_value()) {
  5128. value = uninterpreted_option_->double_value();
  5129. } else if (uninterpreted_option_->has_positive_int_value()) {
  5130. value = uninterpreted_option_->positive_int_value();
  5131. } else if (uninterpreted_option_->has_negative_int_value()) {
  5132. value = uninterpreted_option_->negative_int_value();
  5133. } else {
  5134. return AddValueError("Value must be number for double option \"" +
  5135. option_field->full_name() + "\".");
  5136. }
  5137. unknown_fields->AddFixed64(option_field->number(),
  5138. google::protobuf::internal::WireFormatLite::EncodeDouble(value));
  5139. break;
  5140. }
  5141. case FieldDescriptor::CPPTYPE_BOOL:
  5142. uint64 value;
  5143. if (!uninterpreted_option_->has_identifier_value()) {
  5144. return AddValueError("Value must be identifier for boolean option "
  5145. "\"" + option_field->full_name() + "\".");
  5146. }
  5147. if (uninterpreted_option_->identifier_value() == "true") {
  5148. value = 1;
  5149. } else if (uninterpreted_option_->identifier_value() == "false") {
  5150. value = 0;
  5151. } else {
  5152. return AddValueError("Value must be \"true\" or \"false\" for boolean "
  5153. "option \"" + option_field->full_name() + "\".");
  5154. }
  5155. unknown_fields->AddVarint(option_field->number(), value);
  5156. break;
  5157. case FieldDescriptor::CPPTYPE_ENUM: {
  5158. if (!uninterpreted_option_->has_identifier_value()) {
  5159. return AddValueError("Value must be identifier for enum-valued option "
  5160. "\"" + option_field->full_name() + "\".");
  5161. }
  5162. const EnumDescriptor* enum_type = option_field->enum_type();
  5163. const string& value_name = uninterpreted_option_->identifier_value();
  5164. const EnumValueDescriptor* enum_value = NULL;
  5165. if (enum_type->file()->pool() != DescriptorPool::generated_pool()) {
  5166. // Note that the enum value's fully-qualified name is a sibling of the
  5167. // enum's name, not a child of it.
  5168. string fully_qualified_name = enum_type->full_name();
  5169. fully_qualified_name.resize(fully_qualified_name.size() -
  5170. enum_type->name().size());
  5171. fully_qualified_name += value_name;
  5172. // Search for the enum value's descriptor in the builder's pool. Note
  5173. // that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not
  5174. // DescriptorPool::FindEnumValueByName() because we're already holding
  5175. // the pool's mutex, and the latter method locks it again.
  5176. Symbol symbol =
  5177. builder_->FindSymbolNotEnforcingDeps(fully_qualified_name);
  5178. if (!symbol.IsNull() && symbol.type == Symbol::ENUM_VALUE) {
  5179. if (symbol.enum_value_descriptor->type() != enum_type) {
  5180. return AddValueError("Enum type \"" + enum_type->full_name() +
  5181. "\" has no value named \"" + value_name + "\" for option \"" +
  5182. option_field->full_name() +
  5183. "\". This appears to be a value from a sibling type.");
  5184. } else {
  5185. enum_value = symbol.enum_value_descriptor;
  5186. }
  5187. }
  5188. } else {
  5189. // The enum type is in the generated pool, so we can search for the
  5190. // value there.
  5191. enum_value = enum_type->FindValueByName(value_name);
  5192. }
  5193. if (enum_value == NULL) {
  5194. return AddValueError("Enum type \"" +
  5195. option_field->enum_type()->full_name() +
  5196. "\" has no value named \"" + value_name + "\" for "
  5197. "option \"" + option_field->full_name() + "\".");
  5198. } else {
  5199. // Sign-extension is not a problem, since we cast directly from int32 to
  5200. // uint64, without first going through uint32.
  5201. unknown_fields->AddVarint(option_field->number(),
  5202. static_cast<uint64>(static_cast<int64>(enum_value->number())));
  5203. }
  5204. break;
  5205. }
  5206. case FieldDescriptor::CPPTYPE_STRING:
  5207. if (!uninterpreted_option_->has_string_value()) {
  5208. return AddValueError("Value must be quoted string for string option "
  5209. "\"" + option_field->full_name() + "\".");
  5210. }
  5211. // The string has already been unquoted and unescaped by the parser.
  5212. unknown_fields->AddLengthDelimited(option_field->number(),
  5213. uninterpreted_option_->string_value());
  5214. break;
  5215. case FieldDescriptor::CPPTYPE_MESSAGE:
  5216. if (!SetAggregateOption(option_field, unknown_fields)) {
  5217. return false;
  5218. }
  5219. break;
  5220. }
  5221. return true;
  5222. }
  5223. class DescriptorBuilder::OptionInterpreter::AggregateOptionFinder
  5224. : public TextFormat::Finder {
  5225. public:
  5226. DescriptorBuilder* builder_;
  5227. virtual const FieldDescriptor* FindExtension(
  5228. Message* message, const string& name) const {
  5229. assert_mutex_held(builder_->pool_);
  5230. const Descriptor* descriptor = message->GetDescriptor();
  5231. Symbol result = builder_->LookupSymbolNoPlaceholder(
  5232. name, descriptor->full_name());
  5233. if (result.type == Symbol::FIELD &&
  5234. result.field_descriptor->is_extension()) {
  5235. return result.field_descriptor;
  5236. } else if (result.type == Symbol::MESSAGE &&
  5237. descriptor->options().message_set_wire_format()) {
  5238. const Descriptor* foreign_type = result.descriptor;
  5239. // The text format allows MessageSet items to be specified using
  5240. // the type name, rather than the extension identifier. If the symbol
  5241. // lookup returned a Message, and the enclosing Message has
  5242. // message_set_wire_format = true, then return the message set
  5243. // extension, if one exists.
  5244. for (int i = 0; i < foreign_type->extension_count(); i++) {
  5245. const FieldDescriptor* extension = foreign_type->extension(i);
  5246. if (extension->containing_type() == descriptor &&
  5247. extension->type() == FieldDescriptor::TYPE_MESSAGE &&
  5248. extension->is_optional() &&
  5249. extension->message_type() == foreign_type) {
  5250. // Found it.
  5251. return extension;
  5252. }
  5253. }
  5254. }
  5255. return NULL;
  5256. }
  5257. };
  5258. // A custom error collector to record any text-format parsing errors
  5259. namespace {
  5260. class AggregateErrorCollector : public io::ErrorCollector {
  5261. public:
  5262. string error_;
  5263. virtual void AddError(int /* line */, int /* column */,
  5264. const string& message) {
  5265. if (!error_.empty()) {
  5266. error_ += "; ";
  5267. }
  5268. error_ += message;
  5269. }
  5270. virtual void AddWarning(int /* line */, int /* column */,
  5271. const string& /* message */) {
  5272. // Ignore warnings
  5273. }
  5274. };
  5275. }
  5276. // We construct a dynamic message of the type corresponding to
  5277. // option_field, parse the supplied text-format string into this
  5278. // message, and serialize the resulting message to produce the value.
  5279. bool DescriptorBuilder::OptionInterpreter::SetAggregateOption(
  5280. const FieldDescriptor* option_field,
  5281. UnknownFieldSet* unknown_fields) {
  5282. if (!uninterpreted_option_->has_aggregate_value()) {
  5283. return AddValueError("Option \"" + option_field->full_name() +
  5284. "\" is a message. To set the entire message, use "
  5285. "syntax like \"" + option_field->name() +
  5286. " = { <proto text format> }\". "
  5287. "To set fields within it, use "
  5288. "syntax like \"" + option_field->name() +
  5289. ".foo = value\".");
  5290. }
  5291. const Descriptor* type = option_field->message_type();
  5292. scoped_ptr<Message> dynamic(dynamic_factory_.GetPrototype(type)->New());
  5293. GOOGLE_CHECK(dynamic.get() != NULL)
  5294. << "Could not create an instance of " << option_field->DebugString();
  5295. AggregateErrorCollector collector;
  5296. AggregateOptionFinder finder;
  5297. finder.builder_ = builder_;
  5298. TextFormat::Parser parser;
  5299. parser.RecordErrorsTo(&collector);
  5300. parser.SetFinder(&finder);
  5301. if (!parser.ParseFromString(uninterpreted_option_->aggregate_value(),
  5302. dynamic.get())) {
  5303. AddValueError("Error while parsing option value for \"" +
  5304. option_field->name() + "\": " + collector.error_);
  5305. return false;
  5306. } else {
  5307. string serial;
  5308. dynamic->SerializeToString(&serial); // Never fails
  5309. if (option_field->type() == FieldDescriptor::TYPE_MESSAGE) {
  5310. unknown_fields->AddLengthDelimited(option_field->number(), serial);
  5311. } else {
  5312. GOOGLE_CHECK_EQ(option_field->type(), FieldDescriptor::TYPE_GROUP);
  5313. UnknownFieldSet* group = unknown_fields->AddGroup(option_field->number());
  5314. group->ParseFromString(serial);
  5315. }
  5316. return true;
  5317. }
  5318. }
  5319. void DescriptorBuilder::OptionInterpreter::SetInt32(int number, int32 value,
  5320. FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) {
  5321. switch (type) {
  5322. case FieldDescriptor::TYPE_INT32:
  5323. unknown_fields->AddVarint(number,
  5324. static_cast<uint64>(static_cast<int64>(value)));
  5325. break;
  5326. case FieldDescriptor::TYPE_SFIXED32:
  5327. unknown_fields->AddFixed32(number, static_cast<uint32>(value));
  5328. break;
  5329. case FieldDescriptor::TYPE_SINT32:
  5330. unknown_fields->AddVarint(number,
  5331. google::protobuf::internal::WireFormatLite::ZigZagEncode32(value));
  5332. break;
  5333. default:
  5334. GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_INT32: " << type;
  5335. break;
  5336. }
  5337. }
  5338. void DescriptorBuilder::OptionInterpreter::SetInt64(int number, int64 value,
  5339. FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) {
  5340. switch (type) {
  5341. case FieldDescriptor::TYPE_INT64:
  5342. unknown_fields->AddVarint(number, static_cast<uint64>(value));
  5343. break;
  5344. case FieldDescriptor::TYPE_SFIXED64:
  5345. unknown_fields->AddFixed64(number, static_cast<uint64>(value));
  5346. break;
  5347. case FieldDescriptor::TYPE_SINT64:
  5348. unknown_fields->AddVarint(number,
  5349. google::protobuf::internal::WireFormatLite::ZigZagEncode64(value));
  5350. break;
  5351. default:
  5352. GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_INT64: " << type;
  5353. break;
  5354. }
  5355. }
  5356. void DescriptorBuilder::OptionInterpreter::SetUInt32(int number, uint32 value,
  5357. FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) {
  5358. switch (type) {
  5359. case FieldDescriptor::TYPE_UINT32:
  5360. unknown_fields->AddVarint(number, static_cast<uint64>(value));
  5361. break;
  5362. case FieldDescriptor::TYPE_FIXED32:
  5363. unknown_fields->AddFixed32(number, static_cast<uint32>(value));
  5364. break;
  5365. default:
  5366. GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_UINT32: " << type;
  5367. break;
  5368. }
  5369. }
  5370. void DescriptorBuilder::OptionInterpreter::SetUInt64(int number, uint64 value,
  5371. FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) {
  5372. switch (type) {
  5373. case FieldDescriptor::TYPE_UINT64:
  5374. unknown_fields->AddVarint(number, value);
  5375. break;
  5376. case FieldDescriptor::TYPE_FIXED64:
  5377. unknown_fields->AddFixed64(number, value);
  5378. break;
  5379. default:
  5380. GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_UINT64: " << type;
  5381. break;
  5382. }
  5383. }
  5384. void DescriptorBuilder::LogUnusedDependency(const FileDescriptor* result) {
  5385. if (!unused_dependency_.empty()) {
  5386. std::set<string> annotation_extensions;
  5387. annotation_extensions.insert("google.protobuf.MessageOptions");
  5388. annotation_extensions.insert("google.protobuf.FileOptions");
  5389. annotation_extensions.insert("google.protobuf.FieldOptions");
  5390. annotation_extensions.insert("google.protobuf.EnumOptions");
  5391. annotation_extensions.insert("google.protobuf.EnumValueOptions");
  5392. annotation_extensions.insert("google.protobuf.ServiceOptions");
  5393. annotation_extensions.insert("google.protobuf.MethodOptions");
  5394. annotation_extensions.insert("google.protobuf.StreamOptions");
  5395. for (set<const FileDescriptor*>::const_iterator
  5396. it = unused_dependency_.begin();
  5397. it != unused_dependency_.end(); ++it) {
  5398. // Do not log warnings for proto files which extend annotations.
  5399. int i;
  5400. for (i = 0 ; i < (*it)->extension_count(); ++i) {
  5401. if (annotation_extensions.find(
  5402. (*it)->extension(i)->containing_type()->full_name())
  5403. != annotation_extensions.end()) {
  5404. break;
  5405. }
  5406. }
  5407. // Log warnings for unused imported files.
  5408. if (i == (*it)->extension_count()) {
  5409. GOOGLE_LOG(WARNING) << "Warning: Unused import: \"" << result->name()
  5410. << "\" imports \"" << (*it)->name()
  5411. << "\" which is not used.";
  5412. }
  5413. }
  5414. }
  5415. }
  5416. } // namespace protobuf
  5417. } // namespace google