descriptor.cc 271 KB

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