ParseDecl.cpp 247 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801
  1. //===--- ParseDecl.cpp - Declaration Parsing --------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the Declaration portions of the Parser interfaces.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Parse/Parser.h"
  14. #include "clang/Parse/RAIIObjectsForParser.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/DeclTemplate.h"
  17. #include "clang/Basic/AddressSpaces.h"
  18. #include "clang/Basic/Attributes.h"
  19. #include "clang/Basic/CharInfo.h"
  20. #include "clang/Basic/TargetInfo.h"
  21. #include "clang/Parse/ParseDiagnostic.h"
  22. #include "clang/Sema/Lookup.h"
  23. #include "clang/Sema/ParsedTemplate.h"
  24. #include "clang/Sema/PrettyDeclStackTrace.h"
  25. #include "clang/Sema/Scope.h"
  26. #include "clang/Sema/SemaDiagnostic.h"
  27. #include "llvm/ADT/Optional.h"
  28. #include "llvm/ADT/SmallSet.h"
  29. #include "llvm/ADT/SmallString.h"
  30. #include "llvm/ADT/StringSwitch.h"
  31. #include "llvm/Support/ScopedPrinter.h"
  32. using namespace clang;
  33. //===----------------------------------------------------------------------===//
  34. // C99 6.7: Declarations.
  35. //===----------------------------------------------------------------------===//
  36. /// ParseTypeName
  37. /// type-name: [C99 6.7.6]
  38. /// specifier-qualifier-list abstract-declarator[opt]
  39. ///
  40. /// Called type-id in C++.
  41. TypeResult Parser::ParseTypeName(SourceRange *Range,
  42. Declarator::TheContext Context,
  43. AccessSpecifier AS,
  44. Decl **OwnedType,
  45. ParsedAttributes *Attrs) {
  46. DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
  47. if (DSC == DSC_normal)
  48. DSC = DSC_type_specifier;
  49. // Parse the common declaration-specifiers piece.
  50. DeclSpec DS(AttrFactory);
  51. if (Attrs)
  52. DS.addAttributes(Attrs->getList());
  53. ParseSpecifierQualifierList(DS, AS, DSC);
  54. if (OwnedType)
  55. *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr;
  56. // Parse the abstract-declarator, if present.
  57. Declarator DeclaratorInfo(DS, Context);
  58. ParseDeclarator(DeclaratorInfo);
  59. if (Range)
  60. *Range = DeclaratorInfo.getSourceRange();
  61. if (DeclaratorInfo.isInvalidType())
  62. return true;
  63. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  64. }
  65. /// \brief Normalizes an attribute name by dropping prefixed and suffixed __.
  66. static StringRef normalizeAttrName(StringRef Name) {
  67. if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__"))
  68. return Name.drop_front(2).drop_back(2);
  69. return Name;
  70. }
  71. /// isAttributeLateParsed - Return true if the attribute has arguments that
  72. /// require late parsing.
  73. static bool isAttributeLateParsed(const IdentifierInfo &II) {
  74. #define CLANG_ATTR_LATE_PARSED_LIST
  75. return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
  76. #include "clang/Parse/AttrParserStringSwitches.inc"
  77. .Default(false);
  78. #undef CLANG_ATTR_LATE_PARSED_LIST
  79. }
  80. /// ParseGNUAttributes - Parse a non-empty attributes list.
  81. ///
  82. /// [GNU] attributes:
  83. /// attribute
  84. /// attributes attribute
  85. ///
  86. /// [GNU] attribute:
  87. /// '__attribute__' '(' '(' attribute-list ')' ')'
  88. ///
  89. /// [GNU] attribute-list:
  90. /// attrib
  91. /// attribute_list ',' attrib
  92. ///
  93. /// [GNU] attrib:
  94. /// empty
  95. /// attrib-name
  96. /// attrib-name '(' identifier ')'
  97. /// attrib-name '(' identifier ',' nonempty-expr-list ')'
  98. /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
  99. ///
  100. /// [GNU] attrib-name:
  101. /// identifier
  102. /// typespec
  103. /// typequal
  104. /// storageclass
  105. ///
  106. /// Whether an attribute takes an 'identifier' is determined by the
  107. /// attrib-name. GCC's behavior here is not worth imitating:
  108. ///
  109. /// * In C mode, if the attribute argument list starts with an identifier
  110. /// followed by a ',' or an ')', and the identifier doesn't resolve to
  111. /// a type, it is parsed as an identifier. If the attribute actually
  112. /// wanted an expression, it's out of luck (but it turns out that no
  113. /// attributes work that way, because C constant expressions are very
  114. /// limited).
  115. /// * In C++ mode, if the attribute argument list starts with an identifier,
  116. /// and the attribute *wants* an identifier, it is parsed as an identifier.
  117. /// At block scope, any additional tokens between the identifier and the
  118. /// ',' or ')' are ignored, otherwise they produce a parse error.
  119. ///
  120. /// We follow the C++ model, but don't allow junk after the identifier.
  121. void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
  122. SourceLocation *endLoc,
  123. LateParsedAttrList *LateAttrs,
  124. Declarator *D) {
  125. assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
  126. while (Tok.is(tok::kw___attribute)) {
  127. ConsumeToken();
  128. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
  129. "attribute")) {
  130. SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
  131. return;
  132. }
  133. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
  134. SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ;
  135. return;
  136. }
  137. // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
  138. while (true) {
  139. // Allow empty/non-empty attributes. ((__vector_size__(16),,,,))
  140. if (TryConsumeToken(tok::comma))
  141. continue;
  142. // Expect an identifier or declaration specifier (const, int, etc.)
  143. if (Tok.isAnnotation())
  144. break;
  145. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  146. if (!AttrName)
  147. break;
  148. SourceLocation AttrNameLoc = ConsumeToken();
  149. if (Tok.isNot(tok::l_paren)) {
  150. attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  151. AttributeList::AS_GNU);
  152. continue;
  153. }
  154. // Handle "parameterized" attributes
  155. if (!LateAttrs || !isAttributeLateParsed(*AttrName)) {
  156. ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr,
  157. SourceLocation(), AttributeList::AS_GNU, D);
  158. continue;
  159. }
  160. // Handle attributes with arguments that require late parsing.
  161. LateParsedAttribute *LA =
  162. new LateParsedAttribute(this, *AttrName, AttrNameLoc);
  163. LateAttrs->push_back(LA);
  164. // Attributes in a class are parsed at the end of the class, along
  165. // with other late-parsed declarations.
  166. if (!ClassStack.empty() && !LateAttrs->parseSoon())
  167. getCurrentClass().LateParsedDeclarations.push_back(LA);
  168. // Be sure ConsumeAndStoreUntil doesn't see the start l_paren, since it
  169. // recursively consumes balanced parens.
  170. LA->Toks.push_back(Tok);
  171. ConsumeParen();
  172. // Consume everything up to and including the matching right parens.
  173. ConsumeAndStoreUntil(tok::r_paren, LA->Toks, /*StopAtSemi=*/true);
  174. Token Eof;
  175. Eof.startToken();
  176. Eof.setLocation(Tok.getLocation());
  177. LA->Toks.push_back(Eof);
  178. }
  179. if (ExpectAndConsume(tok::r_paren))
  180. SkipUntil(tok::r_paren, StopAtSemi);
  181. SourceLocation Loc = Tok.getLocation();
  182. if (ExpectAndConsume(tok::r_paren))
  183. SkipUntil(tok::r_paren, StopAtSemi);
  184. if (endLoc)
  185. *endLoc = Loc;
  186. }
  187. }
  188. /// \brief Determine whether the given attribute has an identifier argument.
  189. static bool attributeHasIdentifierArg(const IdentifierInfo &II) {
  190. #define CLANG_ATTR_IDENTIFIER_ARG_LIST
  191. return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
  192. #include "clang/Parse/AttrParserStringSwitches.inc"
  193. .Default(false);
  194. #undef CLANG_ATTR_IDENTIFIER_ARG_LIST
  195. }
  196. /// \brief Determine whether the given attribute parses a type argument.
  197. static bool attributeIsTypeArgAttr(const IdentifierInfo &II) {
  198. #define CLANG_ATTR_TYPE_ARG_LIST
  199. return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
  200. #include "clang/Parse/AttrParserStringSwitches.inc"
  201. .Default(false);
  202. #undef CLANG_ATTR_TYPE_ARG_LIST
  203. }
  204. /// \brief Determine whether the given attribute requires parsing its arguments
  205. /// in an unevaluated context or not.
  206. static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) {
  207. #define CLANG_ATTR_ARG_CONTEXT_LIST
  208. return llvm::StringSwitch<bool>(normalizeAttrName(II.getName()))
  209. #include "clang/Parse/AttrParserStringSwitches.inc"
  210. .Default(false);
  211. #undef CLANG_ATTR_ARG_CONTEXT_LIST
  212. }
  213. IdentifierLoc *Parser::ParseIdentifierLoc() {
  214. assert(Tok.is(tok::identifier) && "expected an identifier");
  215. IdentifierLoc *IL = IdentifierLoc::create(Actions.Context,
  216. Tok.getLocation(),
  217. Tok.getIdentifierInfo());
  218. ConsumeToken();
  219. return IL;
  220. }
  221. void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
  222. SourceLocation AttrNameLoc,
  223. ParsedAttributes &Attrs,
  224. SourceLocation *EndLoc,
  225. IdentifierInfo *ScopeName,
  226. SourceLocation ScopeLoc,
  227. AttributeList::Syntax Syntax) {
  228. BalancedDelimiterTracker Parens(*this, tok::l_paren);
  229. Parens.consumeOpen();
  230. TypeResult T;
  231. if (Tok.isNot(tok::r_paren))
  232. T = ParseTypeName();
  233. if (Parens.consumeClose())
  234. return;
  235. if (T.isInvalid())
  236. return;
  237. if (T.isUsable())
  238. Attrs.addNewTypeAttr(&AttrName,
  239. SourceRange(AttrNameLoc, Parens.getCloseLocation()),
  240. ScopeName, ScopeLoc, T.get(), Syntax);
  241. else
  242. Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()),
  243. ScopeName, ScopeLoc, nullptr, 0, Syntax);
  244. }
  245. unsigned Parser::ParseAttributeArgsCommon(
  246. IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
  247. ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
  248. SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
  249. // Ignore the left paren location for now.
  250. ConsumeParen();
  251. ArgsVector ArgExprs;
  252. if (Tok.is(tok::identifier)) {
  253. // If this attribute wants an 'identifier' argument, make it so.
  254. bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName);
  255. AttributeList::Kind AttrKind =
  256. AttributeList::getKind(AttrName, ScopeName, Syntax);
  257. // If we don't know how to parse this attribute, but this is the only
  258. // token in this argument, assume it's meant to be an identifier.
  259. if (AttrKind == AttributeList::UnknownAttribute ||
  260. AttrKind == AttributeList::IgnoredAttribute) {
  261. const Token &Next = NextToken();
  262. IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma);
  263. }
  264. if (IsIdentifierArg)
  265. ArgExprs.push_back(ParseIdentifierLoc());
  266. }
  267. if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) {
  268. // Eat the comma.
  269. if (!ArgExprs.empty())
  270. ConsumeToken();
  271. // Parse the non-empty comma-separated list of expressions.
  272. do {
  273. bool Uneval = attributeParsedArgsUnevaluated(*AttrName);
  274. EnterExpressionEvaluationContext Unevaluated(
  275. Actions,
  276. Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
  277. : Sema::ExpressionEvaluationContext::ConstantEvaluated,
  278. /*LambdaContextDecl=*/nullptr,
  279. /*IsDecltype=*/false);
  280. ExprResult ArgExpr(
  281. Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
  282. if (ArgExpr.isInvalid()) {
  283. SkipUntil(tok::r_paren, StopAtSemi);
  284. return 0;
  285. }
  286. ArgExprs.push_back(ArgExpr.get());
  287. // Eat the comma, move to the next argument
  288. } while (TryConsumeToken(tok::comma));
  289. }
  290. SourceLocation RParen = Tok.getLocation();
  291. if (!ExpectAndConsume(tok::r_paren)) {
  292. SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc;
  293. Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc,
  294. ArgExprs.data(), ArgExprs.size(), Syntax);
  295. }
  296. if (EndLoc)
  297. *EndLoc = RParen;
  298. return static_cast<unsigned>(ArgExprs.size());
  299. }
  300. /// Parse the arguments to a parameterized GNU attribute or
  301. /// a C++11 attribute in "gnu" namespace.
  302. void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
  303. SourceLocation AttrNameLoc,
  304. ParsedAttributes &Attrs,
  305. SourceLocation *EndLoc,
  306. IdentifierInfo *ScopeName,
  307. SourceLocation ScopeLoc,
  308. AttributeList::Syntax Syntax,
  309. Declarator *D) {
  310. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  311. AttributeList::Kind AttrKind =
  312. AttributeList::getKind(AttrName, ScopeName, Syntax);
  313. if (AttrKind == AttributeList::AT_Availability) {
  314. ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
  315. ScopeLoc, Syntax);
  316. return;
  317. } else if (AttrKind == AttributeList::AT_ExternalSourceSymbol) {
  318. ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
  319. ScopeName, ScopeLoc, Syntax);
  320. return;
  321. } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) {
  322. ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
  323. ScopeName, ScopeLoc, Syntax);
  324. return;
  325. } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) {
  326. ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
  327. ScopeName, ScopeLoc, Syntax);
  328. return;
  329. } else if (attributeIsTypeArgAttr(*AttrName)) {
  330. ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
  331. ScopeLoc, Syntax);
  332. return;
  333. }
  334. // These may refer to the function arguments, but need to be parsed early to
  335. // participate in determining whether it's a redeclaration.
  336. llvm::Optional<ParseScope> PrototypeScope;
  337. if (normalizeAttrName(AttrName->getName()) == "enable_if" &&
  338. D && D->isFunctionDeclarator()) {
  339. DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo();
  340. PrototypeScope.emplace(this, Scope::FunctionPrototypeScope |
  341. Scope::FunctionDeclarationScope |
  342. Scope::DeclScope);
  343. for (unsigned i = 0; i != FTI.NumParams; ++i) {
  344. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  345. Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param);
  346. }
  347. }
  348. ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
  349. ScopeLoc, Syntax);
  350. }
  351. unsigned Parser::ParseClangAttributeArgs(
  352. IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
  353. ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
  354. SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
  355. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  356. AttributeList::Kind AttrKind =
  357. AttributeList::getKind(AttrName, ScopeName, Syntax);
  358. if (AttrKind == AttributeList::AT_ExternalSourceSymbol) {
  359. ParseExternalSourceSymbolAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc,
  360. ScopeName, ScopeLoc, Syntax);
  361. return Attrs.getList() ? Attrs.getList()->getNumArgs() : 0;
  362. }
  363. return ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
  364. ScopeName, ScopeLoc, Syntax);
  365. }
  366. bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
  367. SourceLocation AttrNameLoc,
  368. ParsedAttributes &Attrs) {
  369. // If the attribute isn't known, we will not attempt to parse any
  370. // arguments.
  371. if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName,
  372. getTargetInfo(), getLangOpts())) {
  373. // Eat the left paren, then skip to the ending right paren.
  374. ConsumeParen();
  375. SkipUntil(tok::r_paren);
  376. return false;
  377. }
  378. SourceLocation OpenParenLoc = Tok.getLocation();
  379. if (AttrName->getName() == "property") {
  380. // The property declspec is more complex in that it can take one or two
  381. // assignment expressions as a parameter, but the lhs of the assignment
  382. // must be named get or put.
  383. BalancedDelimiterTracker T(*this, tok::l_paren);
  384. T.expectAndConsume(diag::err_expected_lparen_after,
  385. AttrName->getNameStart(), tok::r_paren);
  386. enum AccessorKind {
  387. AK_Invalid = -1,
  388. AK_Put = 0,
  389. AK_Get = 1 // indices into AccessorNames
  390. };
  391. IdentifierInfo *AccessorNames[] = {nullptr, nullptr};
  392. bool HasInvalidAccessor = false;
  393. // Parse the accessor specifications.
  394. while (true) {
  395. // Stop if this doesn't look like an accessor spec.
  396. if (!Tok.is(tok::identifier)) {
  397. // If the user wrote a completely empty list, use a special diagnostic.
  398. if (Tok.is(tok::r_paren) && !HasInvalidAccessor &&
  399. AccessorNames[AK_Put] == nullptr &&
  400. AccessorNames[AK_Get] == nullptr) {
  401. Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter);
  402. break;
  403. }
  404. Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor);
  405. break;
  406. }
  407. AccessorKind Kind;
  408. SourceLocation KindLoc = Tok.getLocation();
  409. StringRef KindStr = Tok.getIdentifierInfo()->getName();
  410. if (KindStr == "get") {
  411. Kind = AK_Get;
  412. } else if (KindStr == "put") {
  413. Kind = AK_Put;
  414. // Recover from the common mistake of using 'set' instead of 'put'.
  415. } else if (KindStr == "set") {
  416. Diag(KindLoc, diag::err_ms_property_has_set_accessor)
  417. << FixItHint::CreateReplacement(KindLoc, "put");
  418. Kind = AK_Put;
  419. // Handle the mistake of forgetting the accessor kind by skipping
  420. // this accessor.
  421. } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) {
  422. Diag(KindLoc, diag::err_ms_property_missing_accessor_kind);
  423. ConsumeToken();
  424. HasInvalidAccessor = true;
  425. goto next_property_accessor;
  426. // Otherwise, complain about the unknown accessor kind.
  427. } else {
  428. Diag(KindLoc, diag::err_ms_property_unknown_accessor);
  429. HasInvalidAccessor = true;
  430. Kind = AK_Invalid;
  431. // Try to keep parsing unless it doesn't look like an accessor spec.
  432. if (!NextToken().is(tok::equal))
  433. break;
  434. }
  435. // Consume the identifier.
  436. ConsumeToken();
  437. // Consume the '='.
  438. if (!TryConsumeToken(tok::equal)) {
  439. Diag(Tok.getLocation(), diag::err_ms_property_expected_equal)
  440. << KindStr;
  441. break;
  442. }
  443. // Expect the method name.
  444. if (!Tok.is(tok::identifier)) {
  445. Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name);
  446. break;
  447. }
  448. if (Kind == AK_Invalid) {
  449. // Just drop invalid accessors.
  450. } else if (AccessorNames[Kind] != nullptr) {
  451. // Complain about the repeated accessor, ignore it, and keep parsing.
  452. Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr;
  453. } else {
  454. AccessorNames[Kind] = Tok.getIdentifierInfo();
  455. }
  456. ConsumeToken();
  457. next_property_accessor:
  458. // Keep processing accessors until we run out.
  459. if (TryConsumeToken(tok::comma))
  460. continue;
  461. // If we run into the ')', stop without consuming it.
  462. if (Tok.is(tok::r_paren))
  463. break;
  464. Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen);
  465. break;
  466. }
  467. // Only add the property attribute if it was well-formed.
  468. if (!HasInvalidAccessor)
  469. Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(),
  470. AccessorNames[AK_Get], AccessorNames[AK_Put],
  471. AttributeList::AS_Declspec);
  472. T.skipToEnd();
  473. return !HasInvalidAccessor;
  474. }
  475. unsigned NumArgs =
  476. ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr,
  477. SourceLocation(), AttributeList::AS_Declspec);
  478. // If this attribute's args were parsed, and it was expected to have
  479. // arguments but none were provided, emit a diagnostic.
  480. const AttributeList *Attr = Attrs.getList();
  481. if (Attr && Attr->getMaxArgs() && !NumArgs) {
  482. Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName;
  483. return false;
  484. }
  485. return true;
  486. }
  487. /// [MS] decl-specifier:
  488. /// __declspec ( extended-decl-modifier-seq )
  489. ///
  490. /// [MS] extended-decl-modifier-seq:
  491. /// extended-decl-modifier[opt]
  492. /// extended-decl-modifier extended-decl-modifier-seq
  493. void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
  494. SourceLocation *End) {
  495. assert(getLangOpts().DeclSpecKeyword && "__declspec keyword is not enabled");
  496. assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
  497. while (Tok.is(tok::kw___declspec)) {
  498. ConsumeToken();
  499. BalancedDelimiterTracker T(*this, tok::l_paren);
  500. if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
  501. tok::r_paren))
  502. return;
  503. // An empty declspec is perfectly legal and should not warn. Additionally,
  504. // you can specify multiple attributes per declspec.
  505. while (Tok.isNot(tok::r_paren)) {
  506. // Attribute not present.
  507. if (TryConsumeToken(tok::comma))
  508. continue;
  509. // We expect either a well-known identifier or a generic string. Anything
  510. // else is a malformed declspec.
  511. bool IsString = Tok.getKind() == tok::string_literal;
  512. if (!IsString && Tok.getKind() != tok::identifier &&
  513. Tok.getKind() != tok::kw_restrict) {
  514. Diag(Tok, diag::err_ms_declspec_type);
  515. T.skipToEnd();
  516. return;
  517. }
  518. IdentifierInfo *AttrName;
  519. SourceLocation AttrNameLoc;
  520. if (IsString) {
  521. SmallString<8> StrBuffer;
  522. bool Invalid = false;
  523. StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
  524. if (Invalid) {
  525. T.skipToEnd();
  526. return;
  527. }
  528. AttrName = PP.getIdentifierInfo(Str);
  529. AttrNameLoc = ConsumeStringToken();
  530. } else {
  531. AttrName = Tok.getIdentifierInfo();
  532. AttrNameLoc = ConsumeToken();
  533. }
  534. bool AttrHandled = false;
  535. // Parse attribute arguments.
  536. if (Tok.is(tok::l_paren))
  537. AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs);
  538. else if (AttrName->getName() == "property")
  539. // The property attribute must have an argument list.
  540. Diag(Tok.getLocation(), diag::err_expected_lparen_after)
  541. << AttrName->getName();
  542. if (!AttrHandled)
  543. Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  544. AttributeList::AS_Declspec);
  545. }
  546. T.consumeClose();
  547. if (End)
  548. *End = T.getCloseLocation();
  549. }
  550. }
  551. void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
  552. // Treat these like attributes
  553. while (true) {
  554. switch (Tok.getKind()) {
  555. case tok::kw___fastcall:
  556. case tok::kw___stdcall:
  557. case tok::kw___thiscall:
  558. case tok::kw___regcall:
  559. case tok::kw___cdecl:
  560. case tok::kw___vectorcall:
  561. case tok::kw___ptr64:
  562. case tok::kw___w64:
  563. case tok::kw___ptr32:
  564. case tok::kw___sptr:
  565. case tok::kw___uptr: {
  566. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  567. SourceLocation AttrNameLoc = ConsumeToken();
  568. attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  569. AttributeList::AS_Keyword);
  570. break;
  571. }
  572. default:
  573. return;
  574. }
  575. }
  576. }
  577. void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() {
  578. SourceLocation StartLoc = Tok.getLocation();
  579. SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes();
  580. if (EndLoc.isValid()) {
  581. SourceRange Range(StartLoc, EndLoc);
  582. Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range;
  583. }
  584. }
  585. SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() {
  586. SourceLocation EndLoc;
  587. while (true) {
  588. switch (Tok.getKind()) {
  589. case tok::kw_const:
  590. case tok::kw_volatile:
  591. case tok::kw___fastcall:
  592. case tok::kw___stdcall:
  593. case tok::kw___thiscall:
  594. case tok::kw___cdecl:
  595. case tok::kw___vectorcall:
  596. case tok::kw___ptr32:
  597. case tok::kw___ptr64:
  598. case tok::kw___w64:
  599. case tok::kw___unaligned:
  600. case tok::kw___sptr:
  601. case tok::kw___uptr:
  602. EndLoc = ConsumeToken();
  603. break;
  604. default:
  605. return EndLoc;
  606. }
  607. }
  608. }
  609. void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
  610. // Treat these like attributes
  611. while (Tok.is(tok::kw___pascal)) {
  612. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  613. SourceLocation AttrNameLoc = ConsumeToken();
  614. attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  615. AttributeList::AS_Keyword);
  616. }
  617. }
  618. void Parser::ParseOpenCLKernelAttributes(ParsedAttributes &attrs) {
  619. // Treat these like attributes
  620. while (Tok.is(tok::kw___kernel)) {
  621. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  622. SourceLocation AttrNameLoc = ConsumeToken();
  623. attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  624. AttributeList::AS_Keyword);
  625. }
  626. }
  627. void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) {
  628. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  629. SourceLocation AttrNameLoc = Tok.getLocation();
  630. Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  631. AttributeList::AS_Keyword);
  632. }
  633. void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) {
  634. // Treat these like attributes, even though they're type specifiers.
  635. while (true) {
  636. switch (Tok.getKind()) {
  637. case tok::kw__Nonnull:
  638. case tok::kw__Nullable:
  639. case tok::kw__Null_unspecified: {
  640. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  641. SourceLocation AttrNameLoc = ConsumeToken();
  642. if (!getLangOpts().ObjC1)
  643. Diag(AttrNameLoc, diag::ext_nullability)
  644. << AttrName;
  645. attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  646. AttributeList::AS_Keyword);
  647. break;
  648. }
  649. default:
  650. return;
  651. }
  652. }
  653. }
  654. static bool VersionNumberSeparator(const char Separator) {
  655. return (Separator == '.' || Separator == '_');
  656. }
  657. /// \brief Parse a version number.
  658. ///
  659. /// version:
  660. /// simple-integer
  661. /// simple-integer ',' simple-integer
  662. /// simple-integer ',' simple-integer ',' simple-integer
  663. VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
  664. Range = SourceRange(Tok.getLocation(), Tok.getEndLoc());
  665. if (!Tok.is(tok::numeric_constant)) {
  666. Diag(Tok, diag::err_expected_version);
  667. SkipUntil(tok::comma, tok::r_paren,
  668. StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
  669. return VersionTuple();
  670. }
  671. // Parse the major (and possibly minor and subminor) versions, which
  672. // are stored in the numeric constant. We utilize a quirk of the
  673. // lexer, which is that it handles something like 1.2.3 as a single
  674. // numeric constant, rather than two separate tokens.
  675. SmallString<512> Buffer;
  676. Buffer.resize(Tok.getLength()+1);
  677. const char *ThisTokBegin = &Buffer[0];
  678. // Get the spelling of the token, which eliminates trigraphs, etc.
  679. bool Invalid = false;
  680. unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
  681. if (Invalid)
  682. return VersionTuple();
  683. // Parse the major version.
  684. unsigned AfterMajor = 0;
  685. unsigned Major = 0;
  686. while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) {
  687. Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
  688. ++AfterMajor;
  689. }
  690. if (AfterMajor == 0) {
  691. Diag(Tok, diag::err_expected_version);
  692. SkipUntil(tok::comma, tok::r_paren,
  693. StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
  694. return VersionTuple();
  695. }
  696. if (AfterMajor == ActualLength) {
  697. ConsumeToken();
  698. // We only had a single version component.
  699. if (Major == 0) {
  700. Diag(Tok, diag::err_zero_version);
  701. return VersionTuple();
  702. }
  703. return VersionTuple(Major);
  704. }
  705. const char AfterMajorSeparator = ThisTokBegin[AfterMajor];
  706. if (!VersionNumberSeparator(AfterMajorSeparator)
  707. || (AfterMajor + 1 == ActualLength)) {
  708. Diag(Tok, diag::err_expected_version);
  709. SkipUntil(tok::comma, tok::r_paren,
  710. StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
  711. return VersionTuple();
  712. }
  713. // Parse the minor version.
  714. unsigned AfterMinor = AfterMajor + 1;
  715. unsigned Minor = 0;
  716. while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) {
  717. Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
  718. ++AfterMinor;
  719. }
  720. if (AfterMinor == ActualLength) {
  721. ConsumeToken();
  722. // We had major.minor.
  723. if (Major == 0 && Minor == 0) {
  724. Diag(Tok, diag::err_zero_version);
  725. return VersionTuple();
  726. }
  727. return VersionTuple(Major, Minor, (AfterMajorSeparator == '_'));
  728. }
  729. const char AfterMinorSeparator = ThisTokBegin[AfterMinor];
  730. // If what follows is not a '.' or '_', we have a problem.
  731. if (!VersionNumberSeparator(AfterMinorSeparator)) {
  732. Diag(Tok, diag::err_expected_version);
  733. SkipUntil(tok::comma, tok::r_paren,
  734. StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
  735. return VersionTuple();
  736. }
  737. // Warn if separators, be it '.' or '_', do not match.
  738. if (AfterMajorSeparator != AfterMinorSeparator)
  739. Diag(Tok, diag::warn_expected_consistent_version_separator);
  740. // Parse the subminor version.
  741. unsigned AfterSubminor = AfterMinor + 1;
  742. unsigned Subminor = 0;
  743. while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) {
  744. Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
  745. ++AfterSubminor;
  746. }
  747. if (AfterSubminor != ActualLength) {
  748. Diag(Tok, diag::err_expected_version);
  749. SkipUntil(tok::comma, tok::r_paren,
  750. StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
  751. return VersionTuple();
  752. }
  753. ConsumeToken();
  754. return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_'));
  755. }
  756. /// \brief Parse the contents of the "availability" attribute.
  757. ///
  758. /// availability-attribute:
  759. /// 'availability' '(' platform ',' opt-strict version-arg-list,
  760. /// opt-replacement, opt-message')'
  761. ///
  762. /// platform:
  763. /// identifier
  764. ///
  765. /// opt-strict:
  766. /// 'strict' ','
  767. ///
  768. /// version-arg-list:
  769. /// version-arg
  770. /// version-arg ',' version-arg-list
  771. ///
  772. /// version-arg:
  773. /// 'introduced' '=' version
  774. /// 'deprecated' '=' version
  775. /// 'obsoleted' = version
  776. /// 'unavailable'
  777. /// opt-replacement:
  778. /// 'replacement' '=' <string>
  779. /// opt-message:
  780. /// 'message' '=' <string>
  781. void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
  782. SourceLocation AvailabilityLoc,
  783. ParsedAttributes &attrs,
  784. SourceLocation *endLoc,
  785. IdentifierInfo *ScopeName,
  786. SourceLocation ScopeLoc,
  787. AttributeList::Syntax Syntax) {
  788. enum { Introduced, Deprecated, Obsoleted, Unknown };
  789. AvailabilityChange Changes[Unknown];
  790. ExprResult MessageExpr, ReplacementExpr;
  791. // Opening '('.
  792. BalancedDelimiterTracker T(*this, tok::l_paren);
  793. if (T.consumeOpen()) {
  794. Diag(Tok, diag::err_expected) << tok::l_paren;
  795. return;
  796. }
  797. // Parse the platform name.
  798. if (Tok.isNot(tok::identifier)) {
  799. Diag(Tok, diag::err_availability_expected_platform);
  800. SkipUntil(tok::r_paren, StopAtSemi);
  801. return;
  802. }
  803. IdentifierLoc *Platform = ParseIdentifierLoc();
  804. if (const IdentifierInfo *const Ident = Platform->Ident) {
  805. // Canonicalize platform name from "macosx" to "macos".
  806. if (Ident->getName() == "macosx")
  807. Platform->Ident = PP.getIdentifierInfo("macos");
  808. // Canonicalize platform name from "macosx_app_extension" to
  809. // "macos_app_extension".
  810. else if (Ident->getName() == "macosx_app_extension")
  811. Platform->Ident = PP.getIdentifierInfo("macos_app_extension");
  812. else
  813. Platform->Ident = PP.getIdentifierInfo(
  814. AvailabilityAttr::canonicalizePlatformName(Ident->getName()));
  815. }
  816. // Parse the ',' following the platform name.
  817. if (ExpectAndConsume(tok::comma)) {
  818. SkipUntil(tok::r_paren, StopAtSemi);
  819. return;
  820. }
  821. // If we haven't grabbed the pointers for the identifiers
  822. // "introduced", "deprecated", and "obsoleted", do so now.
  823. if (!Ident_introduced) {
  824. Ident_introduced = PP.getIdentifierInfo("introduced");
  825. Ident_deprecated = PP.getIdentifierInfo("deprecated");
  826. Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
  827. Ident_unavailable = PP.getIdentifierInfo("unavailable");
  828. Ident_message = PP.getIdentifierInfo("message");
  829. Ident_strict = PP.getIdentifierInfo("strict");
  830. Ident_replacement = PP.getIdentifierInfo("replacement");
  831. }
  832. // Parse the optional "strict", the optional "replacement" and the set of
  833. // introductions/deprecations/removals.
  834. SourceLocation UnavailableLoc, StrictLoc;
  835. do {
  836. if (Tok.isNot(tok::identifier)) {
  837. Diag(Tok, diag::err_availability_expected_change);
  838. SkipUntil(tok::r_paren, StopAtSemi);
  839. return;
  840. }
  841. IdentifierInfo *Keyword = Tok.getIdentifierInfo();
  842. SourceLocation KeywordLoc = ConsumeToken();
  843. if (Keyword == Ident_strict) {
  844. if (StrictLoc.isValid()) {
  845. Diag(KeywordLoc, diag::err_availability_redundant)
  846. << Keyword << SourceRange(StrictLoc);
  847. }
  848. StrictLoc = KeywordLoc;
  849. continue;
  850. }
  851. if (Keyword == Ident_unavailable) {
  852. if (UnavailableLoc.isValid()) {
  853. Diag(KeywordLoc, diag::err_availability_redundant)
  854. << Keyword << SourceRange(UnavailableLoc);
  855. }
  856. UnavailableLoc = KeywordLoc;
  857. continue;
  858. }
  859. if (Tok.isNot(tok::equal)) {
  860. Diag(Tok, diag::err_expected_after) << Keyword << tok::equal;
  861. SkipUntil(tok::r_paren, StopAtSemi);
  862. return;
  863. }
  864. ConsumeToken();
  865. if (Keyword == Ident_message || Keyword == Ident_replacement) {
  866. if (Tok.isNot(tok::string_literal)) {
  867. Diag(Tok, diag::err_expected_string_literal)
  868. << /*Source='availability attribute'*/2;
  869. SkipUntil(tok::r_paren, StopAtSemi);
  870. return;
  871. }
  872. if (Keyword == Ident_message)
  873. MessageExpr = ParseStringLiteralExpression();
  874. else
  875. ReplacementExpr = ParseStringLiteralExpression();
  876. // Also reject wide string literals.
  877. if (StringLiteral *MessageStringLiteral =
  878. cast_or_null<StringLiteral>(MessageExpr.get())) {
  879. if (MessageStringLiteral->getCharByteWidth() != 1) {
  880. Diag(MessageStringLiteral->getSourceRange().getBegin(),
  881. diag::err_expected_string_literal)
  882. << /*Source='availability attribute'*/ 2;
  883. SkipUntil(tok::r_paren, StopAtSemi);
  884. return;
  885. }
  886. }
  887. if (Keyword == Ident_message)
  888. break;
  889. else
  890. continue;
  891. }
  892. // Special handling of 'NA' only when applied to introduced or
  893. // deprecated.
  894. if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) &&
  895. Tok.is(tok::identifier)) {
  896. IdentifierInfo *NA = Tok.getIdentifierInfo();
  897. if (NA->getName() == "NA") {
  898. ConsumeToken();
  899. if (Keyword == Ident_introduced)
  900. UnavailableLoc = KeywordLoc;
  901. continue;
  902. }
  903. }
  904. SourceRange VersionRange;
  905. VersionTuple Version = ParseVersionTuple(VersionRange);
  906. if (Version.empty()) {
  907. SkipUntil(tok::r_paren, StopAtSemi);
  908. return;
  909. }
  910. unsigned Index;
  911. if (Keyword == Ident_introduced)
  912. Index = Introduced;
  913. else if (Keyword == Ident_deprecated)
  914. Index = Deprecated;
  915. else if (Keyword == Ident_obsoleted)
  916. Index = Obsoleted;
  917. else
  918. Index = Unknown;
  919. if (Index < Unknown) {
  920. if (!Changes[Index].KeywordLoc.isInvalid()) {
  921. Diag(KeywordLoc, diag::err_availability_redundant)
  922. << Keyword
  923. << SourceRange(Changes[Index].KeywordLoc,
  924. Changes[Index].VersionRange.getEnd());
  925. }
  926. Changes[Index].KeywordLoc = KeywordLoc;
  927. Changes[Index].Version = Version;
  928. Changes[Index].VersionRange = VersionRange;
  929. } else {
  930. Diag(KeywordLoc, diag::err_availability_unknown_change)
  931. << Keyword << VersionRange;
  932. }
  933. } while (TryConsumeToken(tok::comma));
  934. // Closing ')'.
  935. if (T.consumeClose())
  936. return;
  937. if (endLoc)
  938. *endLoc = T.getCloseLocation();
  939. // The 'unavailable' availability cannot be combined with any other
  940. // availability changes. Make sure that hasn't happened.
  941. if (UnavailableLoc.isValid()) {
  942. bool Complained = false;
  943. for (unsigned Index = Introduced; Index != Unknown; ++Index) {
  944. if (Changes[Index].KeywordLoc.isValid()) {
  945. if (!Complained) {
  946. Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
  947. << SourceRange(Changes[Index].KeywordLoc,
  948. Changes[Index].VersionRange.getEnd());
  949. Complained = true;
  950. }
  951. // Clear out the availability.
  952. Changes[Index] = AvailabilityChange();
  953. }
  954. }
  955. }
  956. // Record this attribute
  957. attrs.addNew(&Availability,
  958. SourceRange(AvailabilityLoc, T.getCloseLocation()),
  959. ScopeName, ScopeLoc,
  960. Platform,
  961. Changes[Introduced],
  962. Changes[Deprecated],
  963. Changes[Obsoleted],
  964. UnavailableLoc, MessageExpr.get(),
  965. Syntax, StrictLoc, ReplacementExpr.get());
  966. }
  967. /// \brief Parse the contents of the "external_source_symbol" attribute.
  968. ///
  969. /// external-source-symbol-attribute:
  970. /// 'external_source_symbol' '(' keyword-arg-list ')'
  971. ///
  972. /// keyword-arg-list:
  973. /// keyword-arg
  974. /// keyword-arg ',' keyword-arg-list
  975. ///
  976. /// keyword-arg:
  977. /// 'language' '=' <string>
  978. /// 'defined_in' '=' <string>
  979. /// 'generated_declaration'
  980. void Parser::ParseExternalSourceSymbolAttribute(
  981. IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc,
  982. ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName,
  983. SourceLocation ScopeLoc, AttributeList::Syntax Syntax) {
  984. // Opening '('.
  985. BalancedDelimiterTracker T(*this, tok::l_paren);
  986. if (T.expectAndConsume())
  987. return;
  988. // Initialize the pointers for the keyword identifiers when required.
  989. if (!Ident_language) {
  990. Ident_language = PP.getIdentifierInfo("language");
  991. Ident_defined_in = PP.getIdentifierInfo("defined_in");
  992. Ident_generated_declaration = PP.getIdentifierInfo("generated_declaration");
  993. }
  994. ExprResult Language;
  995. bool HasLanguage = false;
  996. ExprResult DefinedInExpr;
  997. bool HasDefinedIn = false;
  998. IdentifierLoc *GeneratedDeclaration = nullptr;
  999. // Parse the language/defined_in/generated_declaration keywords
  1000. do {
  1001. if (Tok.isNot(tok::identifier)) {
  1002. Diag(Tok, diag::err_external_source_symbol_expected_keyword);
  1003. SkipUntil(tok::r_paren, StopAtSemi);
  1004. return;
  1005. }
  1006. SourceLocation KeywordLoc = Tok.getLocation();
  1007. IdentifierInfo *Keyword = Tok.getIdentifierInfo();
  1008. if (Keyword == Ident_generated_declaration) {
  1009. if (GeneratedDeclaration) {
  1010. Diag(Tok, diag::err_external_source_symbol_duplicate_clause) << Keyword;
  1011. SkipUntil(tok::r_paren, StopAtSemi);
  1012. return;
  1013. }
  1014. GeneratedDeclaration = ParseIdentifierLoc();
  1015. continue;
  1016. }
  1017. if (Keyword != Ident_language && Keyword != Ident_defined_in) {
  1018. Diag(Tok, diag::err_external_source_symbol_expected_keyword);
  1019. SkipUntil(tok::r_paren, StopAtSemi);
  1020. return;
  1021. }
  1022. ConsumeToken();
  1023. if (ExpectAndConsume(tok::equal, diag::err_expected_after,
  1024. Keyword->getName())) {
  1025. SkipUntil(tok::r_paren, StopAtSemi);
  1026. return;
  1027. }
  1028. bool HadLanguage = HasLanguage, HadDefinedIn = HasDefinedIn;
  1029. if (Keyword == Ident_language)
  1030. HasLanguage = true;
  1031. else
  1032. HasDefinedIn = true;
  1033. if (Tok.isNot(tok::string_literal)) {
  1034. Diag(Tok, diag::err_expected_string_literal)
  1035. << /*Source='external_source_symbol attribute'*/ 3
  1036. << /*language | source container*/ (Keyword != Ident_language);
  1037. SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
  1038. continue;
  1039. }
  1040. if (Keyword == Ident_language) {
  1041. if (HadLanguage) {
  1042. Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
  1043. << Keyword;
  1044. ParseStringLiteralExpression();
  1045. continue;
  1046. }
  1047. Language = ParseStringLiteralExpression();
  1048. } else {
  1049. assert(Keyword == Ident_defined_in && "Invalid clause keyword!");
  1050. if (HadDefinedIn) {
  1051. Diag(KeywordLoc, diag::err_external_source_symbol_duplicate_clause)
  1052. << Keyword;
  1053. ParseStringLiteralExpression();
  1054. continue;
  1055. }
  1056. DefinedInExpr = ParseStringLiteralExpression();
  1057. }
  1058. } while (TryConsumeToken(tok::comma));
  1059. // Closing ')'.
  1060. if (T.consumeClose())
  1061. return;
  1062. if (EndLoc)
  1063. *EndLoc = T.getCloseLocation();
  1064. ArgsUnion Args[] = {Language.get(), DefinedInExpr.get(),
  1065. GeneratedDeclaration};
  1066. Attrs.addNew(&ExternalSourceSymbol, SourceRange(Loc, T.getCloseLocation()),
  1067. ScopeName, ScopeLoc, Args, llvm::array_lengthof(Args), Syntax);
  1068. }
  1069. /// \brief Parse the contents of the "objc_bridge_related" attribute.
  1070. /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')'
  1071. /// related_class:
  1072. /// Identifier
  1073. ///
  1074. /// opt-class_method:
  1075. /// Identifier: | <empty>
  1076. ///
  1077. /// opt-instance_method:
  1078. /// Identifier | <empty>
  1079. ///
  1080. void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
  1081. SourceLocation ObjCBridgeRelatedLoc,
  1082. ParsedAttributes &attrs,
  1083. SourceLocation *endLoc,
  1084. IdentifierInfo *ScopeName,
  1085. SourceLocation ScopeLoc,
  1086. AttributeList::Syntax Syntax) {
  1087. // Opening '('.
  1088. BalancedDelimiterTracker T(*this, tok::l_paren);
  1089. if (T.consumeOpen()) {
  1090. Diag(Tok, diag::err_expected) << tok::l_paren;
  1091. return;
  1092. }
  1093. // Parse the related class name.
  1094. if (Tok.isNot(tok::identifier)) {
  1095. Diag(Tok, diag::err_objcbridge_related_expected_related_class);
  1096. SkipUntil(tok::r_paren, StopAtSemi);
  1097. return;
  1098. }
  1099. IdentifierLoc *RelatedClass = ParseIdentifierLoc();
  1100. if (ExpectAndConsume(tok::comma)) {
  1101. SkipUntil(tok::r_paren, StopAtSemi);
  1102. return;
  1103. }
  1104. // Parse optional class method name.
  1105. IdentifierLoc *ClassMethod = nullptr;
  1106. if (Tok.is(tok::identifier)) {
  1107. ClassMethod = ParseIdentifierLoc();
  1108. if (!TryConsumeToken(tok::colon)) {
  1109. Diag(Tok, diag::err_objcbridge_related_selector_name);
  1110. SkipUntil(tok::r_paren, StopAtSemi);
  1111. return;
  1112. }
  1113. }
  1114. if (!TryConsumeToken(tok::comma)) {
  1115. if (Tok.is(tok::colon))
  1116. Diag(Tok, diag::err_objcbridge_related_selector_name);
  1117. else
  1118. Diag(Tok, diag::err_expected) << tok::comma;
  1119. SkipUntil(tok::r_paren, StopAtSemi);
  1120. return;
  1121. }
  1122. // Parse optional instance method name.
  1123. IdentifierLoc *InstanceMethod = nullptr;
  1124. if (Tok.is(tok::identifier))
  1125. InstanceMethod = ParseIdentifierLoc();
  1126. else if (Tok.isNot(tok::r_paren)) {
  1127. Diag(Tok, diag::err_expected) << tok::r_paren;
  1128. SkipUntil(tok::r_paren, StopAtSemi);
  1129. return;
  1130. }
  1131. // Closing ')'.
  1132. if (T.consumeClose())
  1133. return;
  1134. if (endLoc)
  1135. *endLoc = T.getCloseLocation();
  1136. // Record this attribute
  1137. attrs.addNew(&ObjCBridgeRelated,
  1138. SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()),
  1139. ScopeName, ScopeLoc,
  1140. RelatedClass,
  1141. ClassMethod,
  1142. InstanceMethod,
  1143. Syntax);
  1144. }
  1145. // Late Parsed Attributes:
  1146. // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
  1147. void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
  1148. void Parser::LateParsedClass::ParseLexedAttributes() {
  1149. Self->ParseLexedAttributes(*Class);
  1150. }
  1151. void Parser::LateParsedAttribute::ParseLexedAttributes() {
  1152. Self->ParseLexedAttribute(*this, true, false);
  1153. }
  1154. /// Wrapper class which calls ParseLexedAttribute, after setting up the
  1155. /// scope appropriately.
  1156. void Parser::ParseLexedAttributes(ParsingClass &Class) {
  1157. // Deal with templates
  1158. // FIXME: Test cases to make sure this does the right thing for templates.
  1159. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  1160. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
  1161. HasTemplateScope);
  1162. if (HasTemplateScope)
  1163. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  1164. // Set or update the scope flags.
  1165. bool AlreadyHasClassScope = Class.TopLevelClass;
  1166. unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
  1167. ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
  1168. ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
  1169. // Enter the scope of nested classes
  1170. if (!AlreadyHasClassScope)
  1171. Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
  1172. Class.TagOrTemplate);
  1173. if (!Class.LateParsedDeclarations.empty()) {
  1174. for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
  1175. Class.LateParsedDeclarations[i]->ParseLexedAttributes();
  1176. }
  1177. }
  1178. if (!AlreadyHasClassScope)
  1179. Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
  1180. Class.TagOrTemplate);
  1181. }
  1182. /// \brief Parse all attributes in LAs, and attach them to Decl D.
  1183. void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
  1184. bool EnterScope, bool OnDefinition) {
  1185. assert(LAs.parseSoon() &&
  1186. "Attribute list should be marked for immediate parsing.");
  1187. for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
  1188. if (D)
  1189. LAs[i]->addDecl(D);
  1190. ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
  1191. delete LAs[i];
  1192. }
  1193. LAs.clear();
  1194. }
  1195. /// \brief Finish parsing an attribute for which parsing was delayed.
  1196. /// This will be called at the end of parsing a class declaration
  1197. /// for each LateParsedAttribute. We consume the saved tokens and
  1198. /// create an attribute with the arguments filled in. We add this
  1199. /// to the Attribute list for the decl.
  1200. void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
  1201. bool EnterScope, bool OnDefinition) {
  1202. // Create a fake EOF so that attribute parsing won't go off the end of the
  1203. // attribute.
  1204. Token AttrEnd;
  1205. AttrEnd.startToken();
  1206. AttrEnd.setKind(tok::eof);
  1207. AttrEnd.setLocation(Tok.getLocation());
  1208. AttrEnd.setEofData(LA.Toks.data());
  1209. LA.Toks.push_back(AttrEnd);
  1210. // Append the current token at the end of the new token stream so that it
  1211. // doesn't get lost.
  1212. LA.Toks.push_back(Tok);
  1213. PP.EnterTokenStream(LA.Toks, true);
  1214. // Consume the previously pushed token.
  1215. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
  1216. ParsedAttributes Attrs(AttrFactory);
  1217. SourceLocation endLoc;
  1218. if (LA.Decls.size() > 0) {
  1219. Decl *D = LA.Decls[0];
  1220. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  1221. RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
  1222. // Allow 'this' within late-parsed attributes.
  1223. Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0,
  1224. ND && ND->isCXXInstanceMember());
  1225. if (LA.Decls.size() == 1) {
  1226. // If the Decl is templatized, add template parameters to scope.
  1227. bool HasTemplateScope = EnterScope && D->isTemplateDecl();
  1228. ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
  1229. if (HasTemplateScope)
  1230. Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
  1231. // If the Decl is on a function, add function parameters to the scope.
  1232. bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
  1233. ParseScope FnScope(
  1234. this, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope,
  1235. HasFunScope);
  1236. if (HasFunScope)
  1237. Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
  1238. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
  1239. nullptr, SourceLocation(), AttributeList::AS_GNU,
  1240. nullptr);
  1241. if (HasFunScope) {
  1242. Actions.ActOnExitFunctionContext();
  1243. FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
  1244. }
  1245. if (HasTemplateScope) {
  1246. TempScope.Exit();
  1247. }
  1248. } else {
  1249. // If there are multiple decls, then the decl cannot be within the
  1250. // function scope.
  1251. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc,
  1252. nullptr, SourceLocation(), AttributeList::AS_GNU,
  1253. nullptr);
  1254. }
  1255. } else {
  1256. Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
  1257. }
  1258. const AttributeList *AL = Attrs.getList();
  1259. if (OnDefinition && AL && !AL->isCXX11Attribute() &&
  1260. AL->isKnownToGCC())
  1261. Diag(Tok, diag::warn_attribute_on_function_definition)
  1262. << &LA.AttrName;
  1263. for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i)
  1264. Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
  1265. // Due to a parsing error, we either went over the cached tokens or
  1266. // there are still cached tokens left, so we skip the leftover tokens.
  1267. while (Tok.isNot(tok::eof))
  1268. ConsumeAnyToken();
  1269. if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())
  1270. ConsumeAnyToken();
  1271. }
  1272. void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
  1273. SourceLocation AttrNameLoc,
  1274. ParsedAttributes &Attrs,
  1275. SourceLocation *EndLoc,
  1276. IdentifierInfo *ScopeName,
  1277. SourceLocation ScopeLoc,
  1278. AttributeList::Syntax Syntax) {
  1279. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  1280. BalancedDelimiterTracker T(*this, tok::l_paren);
  1281. T.consumeOpen();
  1282. if (Tok.isNot(tok::identifier)) {
  1283. Diag(Tok, diag::err_expected) << tok::identifier;
  1284. T.skipToEnd();
  1285. return;
  1286. }
  1287. IdentifierLoc *ArgumentKind = ParseIdentifierLoc();
  1288. if (ExpectAndConsume(tok::comma)) {
  1289. T.skipToEnd();
  1290. return;
  1291. }
  1292. SourceRange MatchingCTypeRange;
  1293. TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
  1294. if (MatchingCType.isInvalid()) {
  1295. T.skipToEnd();
  1296. return;
  1297. }
  1298. bool LayoutCompatible = false;
  1299. bool MustBeNull = false;
  1300. while (TryConsumeToken(tok::comma)) {
  1301. if (Tok.isNot(tok::identifier)) {
  1302. Diag(Tok, diag::err_expected) << tok::identifier;
  1303. T.skipToEnd();
  1304. return;
  1305. }
  1306. IdentifierInfo *Flag = Tok.getIdentifierInfo();
  1307. if (Flag->isStr("layout_compatible"))
  1308. LayoutCompatible = true;
  1309. else if (Flag->isStr("must_be_null"))
  1310. MustBeNull = true;
  1311. else {
  1312. Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
  1313. T.skipToEnd();
  1314. return;
  1315. }
  1316. ConsumeToken(); // consume flag
  1317. }
  1318. if (!T.consumeClose()) {
  1319. Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc,
  1320. ArgumentKind, MatchingCType.get(),
  1321. LayoutCompatible, MustBeNull, Syntax);
  1322. }
  1323. if (EndLoc)
  1324. *EndLoc = T.getCloseLocation();
  1325. }
  1326. /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
  1327. /// of a C++11 attribute-specifier in a location where an attribute is not
  1328. /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
  1329. /// situation.
  1330. ///
  1331. /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
  1332. /// this doesn't appear to actually be an attribute-specifier, and the caller
  1333. /// should try to parse it.
  1334. bool Parser::DiagnoseProhibitedCXX11Attribute() {
  1335. assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
  1336. switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
  1337. case CAK_NotAttributeSpecifier:
  1338. // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
  1339. return false;
  1340. case CAK_InvalidAttributeSpecifier:
  1341. Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
  1342. return false;
  1343. case CAK_AttributeSpecifier:
  1344. // Parse and discard the attributes.
  1345. SourceLocation BeginLoc = ConsumeBracket();
  1346. ConsumeBracket();
  1347. SkipUntil(tok::r_square);
  1348. assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
  1349. SourceLocation EndLoc = ConsumeBracket();
  1350. Diag(BeginLoc, diag::err_attributes_not_allowed)
  1351. << SourceRange(BeginLoc, EndLoc);
  1352. return true;
  1353. }
  1354. llvm_unreachable("All cases handled above.");
  1355. }
  1356. /// \brief We have found the opening square brackets of a C++11
  1357. /// attribute-specifier in a location where an attribute is not permitted, but
  1358. /// we know where the attributes ought to be written. Parse them anyway, and
  1359. /// provide a fixit moving them to the right place.
  1360. void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
  1361. SourceLocation CorrectLocation) {
  1362. assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) ||
  1363. Tok.is(tok::kw_alignas));
  1364. // Consume the attributes.
  1365. SourceLocation Loc = Tok.getLocation();
  1366. ParseCXX11Attributes(Attrs);
  1367. CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true);
  1368. Diag(Loc, diag::err_attributes_not_allowed)
  1369. << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange)
  1370. << FixItHint::CreateRemoval(AttrRange);
  1371. }
  1372. void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
  1373. Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
  1374. << attrs.Range;
  1375. }
  1376. void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
  1377. unsigned DiagID) {
  1378. for (AttributeList *Attr = Attrs.getList(); Attr; Attr = Attr->getNext()) {
  1379. if (!Attr->isCXX11Attribute())
  1380. continue;
  1381. if (Attr->getKind() == AttributeList::UnknownAttribute)
  1382. Diag(Attr->getLoc(), diag::warn_unknown_attribute_ignored)
  1383. << Attr->getName();
  1384. else {
  1385. Diag(Attr->getLoc(), DiagID)
  1386. << Attr->getName();
  1387. Attr->setInvalid();
  1388. }
  1389. }
  1390. }
  1391. // Usually, `__attribute__((attrib)) class Foo {} var` means that attribute
  1392. // applies to var, not the type Foo.
  1393. // As an exception to the rule, __declspec(align(...)) before the
  1394. // class-key affects the type instead of the variable.
  1395. // Also, Microsoft-style [attributes] seem to affect the type instead of the
  1396. // variable.
  1397. // This function moves attributes that should apply to the type off DS to Attrs.
  1398. void Parser::stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
  1399. DeclSpec &DS,
  1400. Sema::TagUseKind TUK) {
  1401. if (TUK == Sema::TUK_Reference)
  1402. return;
  1403. ParsedAttributes &PA = DS.getAttributes();
  1404. AttributeList *AL = PA.getList();
  1405. AttributeList *Prev = nullptr;
  1406. AttributeList *TypeAttrHead = nullptr;
  1407. AttributeList *TypeAttrTail = nullptr;
  1408. while (AL) {
  1409. AttributeList *Next = AL->getNext();
  1410. if ((AL->getKind() == AttributeList::AT_Aligned &&
  1411. AL->isDeclspecAttribute()) ||
  1412. AL->isMicrosoftAttribute()) {
  1413. // Stitch the attribute into the tag's attribute list.
  1414. if (TypeAttrTail)
  1415. TypeAttrTail->setNext(AL);
  1416. else
  1417. TypeAttrHead = AL;
  1418. TypeAttrTail = AL;
  1419. TypeAttrTail->setNext(nullptr);
  1420. // Remove the attribute from the variable's attribute list.
  1421. if (Prev) {
  1422. // Set the last variable attribute's next attribute to be the attribute
  1423. // after the current one.
  1424. Prev->setNext(Next);
  1425. } else {
  1426. // Removing the head of the list requires us to reset the head to the
  1427. // next attribute.
  1428. PA.set(Next);
  1429. }
  1430. } else {
  1431. Prev = AL;
  1432. }
  1433. AL = Next;
  1434. }
  1435. // Find end of type attributes Attrs and add NewTypeAttributes in the same
  1436. // order they were in originally. (Remember, in AttributeList things earlier
  1437. // in source order are later in the list, since new attributes are added to
  1438. // the front of the list.)
  1439. Attrs.addAllAtEnd(TypeAttrHead);
  1440. }
  1441. /// ParseDeclaration - Parse a full 'declaration', which consists of
  1442. /// declaration-specifiers, some number of declarators, and a semicolon.
  1443. /// 'Context' should be a Declarator::TheContext value. This returns the
  1444. /// location of the semicolon in DeclEnd.
  1445. ///
  1446. /// declaration: [C99 6.7]
  1447. /// block-declaration ->
  1448. /// simple-declaration
  1449. /// others [FIXME]
  1450. /// [C++] template-declaration
  1451. /// [C++] namespace-definition
  1452. /// [C++] using-directive
  1453. /// [C++] using-declaration
  1454. /// [C++11/C11] static_assert-declaration
  1455. /// others... [FIXME]
  1456. ///
  1457. Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context,
  1458. SourceLocation &DeclEnd,
  1459. ParsedAttributesWithRange &attrs) {
  1460. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  1461. // Must temporarily exit the objective-c container scope for
  1462. // parsing c none objective-c decls.
  1463. ObjCDeclContextSwitch ObjCDC(*this);
  1464. Decl *SingleDecl = nullptr;
  1465. switch (Tok.getKind()) {
  1466. case tok::kw_template:
  1467. case tok::kw_export:
  1468. ProhibitAttributes(attrs);
  1469. SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
  1470. break;
  1471. case tok::kw_inline:
  1472. // Could be the start of an inline namespace. Allowed as an ext in C++03.
  1473. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
  1474. ProhibitAttributes(attrs);
  1475. SourceLocation InlineLoc = ConsumeToken();
  1476. return ParseNamespace(Context, DeclEnd, InlineLoc);
  1477. }
  1478. return ParseSimpleDeclaration(Context, DeclEnd, attrs,
  1479. true);
  1480. case tok::kw_namespace:
  1481. ProhibitAttributes(attrs);
  1482. return ParseNamespace(Context, DeclEnd);
  1483. case tok::kw_using:
  1484. return ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
  1485. DeclEnd, attrs);
  1486. case tok::kw_static_assert:
  1487. case tok::kw__Static_assert:
  1488. ProhibitAttributes(attrs);
  1489. SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
  1490. break;
  1491. default:
  1492. return ParseSimpleDeclaration(Context, DeclEnd, attrs, true);
  1493. }
  1494. // This routine returns a DeclGroup, if the thing we parsed only contains a
  1495. // single decl, convert it now.
  1496. return Actions.ConvertDeclToDeclGroup(SingleDecl);
  1497. }
  1498. /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
  1499. /// declaration-specifiers init-declarator-list[opt] ';'
  1500. /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
  1501. /// init-declarator-list ';'
  1502. ///[C90/C++]init-declarator-list ';' [TODO]
  1503. /// [OMP] threadprivate-directive [TODO]
  1504. ///
  1505. /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
  1506. /// attribute-specifier-seq[opt] type-specifier-seq declarator
  1507. ///
  1508. /// If RequireSemi is false, this does not check for a ';' at the end of the
  1509. /// declaration. If it is true, it checks for and eats it.
  1510. ///
  1511. /// If FRI is non-null, we might be parsing a for-range-declaration instead
  1512. /// of a simple-declaration. If we find that we are, we also parse the
  1513. /// for-range-initializer, and place it here.
  1514. Parser::DeclGroupPtrTy
  1515. Parser::ParseSimpleDeclaration(unsigned Context,
  1516. SourceLocation &DeclEnd,
  1517. ParsedAttributesWithRange &Attrs,
  1518. bool RequireSemi, ForRangeInit *FRI) {
  1519. // Parse the common declaration-specifiers piece.
  1520. ParsingDeclSpec DS(*this);
  1521. DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context);
  1522. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext);
  1523. // If we had a free-standing type definition with a missing semicolon, we
  1524. // may get this far before the problem becomes obvious.
  1525. if (DS.hasTagDefinition() &&
  1526. DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext))
  1527. return nullptr;
  1528. // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
  1529. // declaration-specifiers init-declarator-list[opt] ';'
  1530. if (Tok.is(tok::semi)) {
  1531. ProhibitAttributes(Attrs);
  1532. DeclEnd = Tok.getLocation();
  1533. if (RequireSemi) ConsumeToken();
  1534. RecordDecl *AnonRecord = nullptr;
  1535. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
  1536. DS, AnonRecord);
  1537. DS.complete(TheDecl);
  1538. if (AnonRecord) {
  1539. Decl* decls[] = {AnonRecord, TheDecl};
  1540. return Actions.BuildDeclaratorGroup(decls);
  1541. }
  1542. return Actions.ConvertDeclToDeclGroup(TheDecl);
  1543. }
  1544. DS.takeAttributesFrom(Attrs);
  1545. return ParseDeclGroup(DS, Context, &DeclEnd, FRI);
  1546. }
  1547. /// Returns true if this might be the start of a declarator, or a common typo
  1548. /// for a declarator.
  1549. bool Parser::MightBeDeclarator(unsigned Context) {
  1550. switch (Tok.getKind()) {
  1551. case tok::annot_cxxscope:
  1552. case tok::annot_template_id:
  1553. case tok::caret:
  1554. case tok::code_completion:
  1555. case tok::coloncolon:
  1556. case tok::ellipsis:
  1557. case tok::kw___attribute:
  1558. case tok::kw_operator:
  1559. case tok::l_paren:
  1560. case tok::star:
  1561. return true;
  1562. case tok::amp:
  1563. case tok::ampamp:
  1564. return getLangOpts().CPlusPlus;
  1565. case tok::l_square: // Might be an attribute on an unnamed bit-field.
  1566. return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 &&
  1567. NextToken().is(tok::l_square);
  1568. case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
  1569. return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
  1570. case tok::identifier:
  1571. switch (NextToken().getKind()) {
  1572. case tok::code_completion:
  1573. case tok::coloncolon:
  1574. case tok::comma:
  1575. case tok::equal:
  1576. case tok::equalequal: // Might be a typo for '='.
  1577. case tok::kw_alignas:
  1578. case tok::kw_asm:
  1579. case tok::kw___attribute:
  1580. case tok::l_brace:
  1581. case tok::l_paren:
  1582. case tok::l_square:
  1583. case tok::less:
  1584. case tok::r_brace:
  1585. case tok::r_paren:
  1586. case tok::r_square:
  1587. case tok::semi:
  1588. return true;
  1589. case tok::colon:
  1590. // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
  1591. // and in block scope it's probably a label. Inside a class definition,
  1592. // this is a bit-field.
  1593. return Context == Declarator::MemberContext ||
  1594. (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
  1595. case tok::identifier: // Possible virt-specifier.
  1596. return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken());
  1597. default:
  1598. return false;
  1599. }
  1600. default:
  1601. return false;
  1602. }
  1603. }
  1604. /// Skip until we reach something which seems like a sensible place to pick
  1605. /// up parsing after a malformed declaration. This will sometimes stop sooner
  1606. /// than SkipUntil(tok::r_brace) would, but will never stop later.
  1607. void Parser::SkipMalformedDecl() {
  1608. while (true) {
  1609. switch (Tok.getKind()) {
  1610. case tok::l_brace:
  1611. // Skip until matching }, then stop. We've probably skipped over
  1612. // a malformed class or function definition or similar.
  1613. ConsumeBrace();
  1614. SkipUntil(tok::r_brace);
  1615. if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) {
  1616. // This declaration isn't over yet. Keep skipping.
  1617. continue;
  1618. }
  1619. TryConsumeToken(tok::semi);
  1620. return;
  1621. case tok::l_square:
  1622. ConsumeBracket();
  1623. SkipUntil(tok::r_square);
  1624. continue;
  1625. case tok::l_paren:
  1626. ConsumeParen();
  1627. SkipUntil(tok::r_paren);
  1628. continue;
  1629. case tok::r_brace:
  1630. return;
  1631. case tok::semi:
  1632. ConsumeToken();
  1633. return;
  1634. case tok::kw_inline:
  1635. // 'inline namespace' at the start of a line is almost certainly
  1636. // a good place to pick back up parsing, except in an Objective-C
  1637. // @interface context.
  1638. if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
  1639. (!ParsingInObjCContainer || CurParsedObjCImpl))
  1640. return;
  1641. break;
  1642. case tok::kw_namespace:
  1643. // 'namespace' at the start of a line is almost certainly a good
  1644. // place to pick back up parsing, except in an Objective-C
  1645. // @interface context.
  1646. if (Tok.isAtStartOfLine() &&
  1647. (!ParsingInObjCContainer || CurParsedObjCImpl))
  1648. return;
  1649. break;
  1650. case tok::at:
  1651. // @end is very much like } in Objective-C contexts.
  1652. if (NextToken().isObjCAtKeyword(tok::objc_end) &&
  1653. ParsingInObjCContainer)
  1654. return;
  1655. break;
  1656. case tok::minus:
  1657. case tok::plus:
  1658. // - and + probably start new method declarations in Objective-C contexts.
  1659. if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
  1660. return;
  1661. break;
  1662. case tok::eof:
  1663. case tok::annot_module_begin:
  1664. case tok::annot_module_end:
  1665. case tok::annot_module_include:
  1666. return;
  1667. default:
  1668. break;
  1669. }
  1670. ConsumeAnyToken();
  1671. }
  1672. }
  1673. /// ParseDeclGroup - Having concluded that this is either a function
  1674. /// definition or a group of object declarations, actually parse the
  1675. /// result.
  1676. Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
  1677. unsigned Context,
  1678. SourceLocation *DeclEnd,
  1679. ForRangeInit *FRI) {
  1680. // Parse the first declarator.
  1681. ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
  1682. ParseDeclarator(D);
  1683. // Bail out if the first declarator didn't seem well-formed.
  1684. if (!D.hasName() && !D.mayOmitIdentifier()) {
  1685. SkipMalformedDecl();
  1686. return nullptr;
  1687. }
  1688. // Save late-parsed attributes for now; they need to be parsed in the
  1689. // appropriate function scope after the function Decl has been constructed.
  1690. // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList.
  1691. LateParsedAttrList LateParsedAttrs(true);
  1692. if (D.isFunctionDeclarator()) {
  1693. MaybeParseGNUAttributes(D, &LateParsedAttrs);
  1694. // The _Noreturn keyword can't appear here, unlike the GNU noreturn
  1695. // attribute. If we find the keyword here, tell the user to put it
  1696. // at the start instead.
  1697. if (Tok.is(tok::kw__Noreturn)) {
  1698. SourceLocation Loc = ConsumeToken();
  1699. const char *PrevSpec;
  1700. unsigned DiagID;
  1701. // We can offer a fixit if it's valid to mark this function as _Noreturn
  1702. // and we don't have any other declarators in this declaration.
  1703. bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
  1704. MaybeParseGNUAttributes(D, &LateParsedAttrs);
  1705. Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try);
  1706. Diag(Loc, diag::err_c11_noreturn_misplaced)
  1707. << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint())
  1708. << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ")
  1709. : FixItHint());
  1710. }
  1711. }
  1712. // Check to see if we have a function *definition* which must have a body.
  1713. if (D.isFunctionDeclarator() &&
  1714. // Look at the next token to make sure that this isn't a function
  1715. // declaration. We have to check this because __attribute__ might be the
  1716. // start of a function definition in GCC-extended K&R C.
  1717. !isDeclarationAfterDeclarator()) {
  1718. // Function definitions are only allowed at file scope and in C++ classes.
  1719. // The C++ inline method definition case is handled elsewhere, so we only
  1720. // need to handle the file scope definition case.
  1721. if (Context == Declarator::FileContext) {
  1722. if (isStartOfFunctionDefinition(D)) {
  1723. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  1724. Diag(Tok, diag::err_function_declared_typedef);
  1725. // Recover by treating the 'typedef' as spurious.
  1726. DS.ClearStorageClassSpecs();
  1727. }
  1728. Decl *TheDecl =
  1729. ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
  1730. return Actions.ConvertDeclToDeclGroup(TheDecl);
  1731. }
  1732. if (isDeclarationSpecifier()) {
  1733. // If there is an invalid declaration specifier right after the
  1734. // function prototype, then we must be in a missing semicolon case
  1735. // where this isn't actually a body. Just fall through into the code
  1736. // that handles it as a prototype, and let the top-level code handle
  1737. // the erroneous declspec where it would otherwise expect a comma or
  1738. // semicolon.
  1739. } else {
  1740. Diag(Tok, diag::err_expected_fn_body);
  1741. SkipUntil(tok::semi);
  1742. return nullptr;
  1743. }
  1744. } else {
  1745. if (Tok.is(tok::l_brace)) {
  1746. Diag(Tok, diag::err_function_definition_not_allowed);
  1747. SkipMalformedDecl();
  1748. return nullptr;
  1749. }
  1750. }
  1751. }
  1752. if (ParseAsmAttributesAfterDeclarator(D))
  1753. return nullptr;
  1754. // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
  1755. // must parse and analyze the for-range-initializer before the declaration is
  1756. // analyzed.
  1757. //
  1758. // Handle the Objective-C for-in loop variable similarly, although we
  1759. // don't need to parse the container in advance.
  1760. if (FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) {
  1761. bool IsForRangeLoop = false;
  1762. if (TryConsumeToken(tok::colon, FRI->ColonLoc)) {
  1763. IsForRangeLoop = true;
  1764. if (Tok.is(tok::l_brace))
  1765. FRI->RangeExpr = ParseBraceInitializer();
  1766. else
  1767. FRI->RangeExpr = ParseExpression();
  1768. }
  1769. Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
  1770. if (IsForRangeLoop)
  1771. Actions.ActOnCXXForRangeDecl(ThisDecl);
  1772. Actions.FinalizeDeclaration(ThisDecl);
  1773. D.complete(ThisDecl);
  1774. return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl);
  1775. }
  1776. SmallVector<Decl *, 8> DeclsInGroup;
  1777. Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(
  1778. D, ParsedTemplateInfo(), FRI);
  1779. if (LateParsedAttrs.size() > 0)
  1780. ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
  1781. D.complete(FirstDecl);
  1782. if (FirstDecl)
  1783. DeclsInGroup.push_back(FirstDecl);
  1784. bool ExpectSemi = Context != Declarator::ForContext;
  1785. // If we don't have a comma, it is either the end of the list (a ';') or an
  1786. // error, bail out.
  1787. SourceLocation CommaLoc;
  1788. while (TryConsumeToken(tok::comma, CommaLoc)) {
  1789. if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
  1790. // This comma was followed by a line-break and something which can't be
  1791. // the start of a declarator. The comma was probably a typo for a
  1792. // semicolon.
  1793. Diag(CommaLoc, diag::err_expected_semi_declaration)
  1794. << FixItHint::CreateReplacement(CommaLoc, ";");
  1795. ExpectSemi = false;
  1796. break;
  1797. }
  1798. // Parse the next declarator.
  1799. D.clear();
  1800. D.setCommaLoc(CommaLoc);
  1801. // Accept attributes in an init-declarator. In the first declarator in a
  1802. // declaration, these would be part of the declspec. In subsequent
  1803. // declarators, they become part of the declarator itself, so that they
  1804. // don't apply to declarators after *this* one. Examples:
  1805. // short __attribute__((common)) var; -> declspec
  1806. // short var __attribute__((common)); -> declarator
  1807. // short x, __attribute__((common)) var; -> declarator
  1808. MaybeParseGNUAttributes(D);
  1809. // MSVC parses but ignores qualifiers after the comma as an extension.
  1810. if (getLangOpts().MicrosoftExt)
  1811. DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
  1812. ParseDeclarator(D);
  1813. if (!D.isInvalidType()) {
  1814. Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
  1815. D.complete(ThisDecl);
  1816. if (ThisDecl)
  1817. DeclsInGroup.push_back(ThisDecl);
  1818. }
  1819. }
  1820. if (DeclEnd)
  1821. *DeclEnd = Tok.getLocation();
  1822. if (ExpectSemi &&
  1823. ExpectAndConsumeSemi(Context == Declarator::FileContext
  1824. ? diag::err_invalid_token_after_toplevel_declarator
  1825. : diag::err_expected_semi_declaration)) {
  1826. // Okay, there was no semicolon and one was expected. If we see a
  1827. // declaration specifier, just assume it was missing and continue parsing.
  1828. // Otherwise things are very confused and we skip to recover.
  1829. if (!isDeclarationSpecifier()) {
  1830. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  1831. TryConsumeToken(tok::semi);
  1832. }
  1833. }
  1834. return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
  1835. }
  1836. /// Parse an optional simple-asm-expr and attributes, and attach them to a
  1837. /// declarator. Returns true on an error.
  1838. bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
  1839. // If a simple-asm-expr is present, parse it.
  1840. if (Tok.is(tok::kw_asm)) {
  1841. SourceLocation Loc;
  1842. ExprResult AsmLabel(ParseSimpleAsm(&Loc));
  1843. if (AsmLabel.isInvalid()) {
  1844. SkipUntil(tok::semi, StopBeforeMatch);
  1845. return true;
  1846. }
  1847. D.setAsmLabel(AsmLabel.get());
  1848. D.SetRangeEnd(Loc);
  1849. }
  1850. MaybeParseGNUAttributes(D);
  1851. return false;
  1852. }
  1853. /// \brief Parse 'declaration' after parsing 'declaration-specifiers
  1854. /// declarator'. This method parses the remainder of the declaration
  1855. /// (including any attributes or initializer, among other things) and
  1856. /// finalizes the declaration.
  1857. ///
  1858. /// init-declarator: [C99 6.7]
  1859. /// declarator
  1860. /// declarator '=' initializer
  1861. /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
  1862. /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
  1863. /// [C++] declarator initializer[opt]
  1864. ///
  1865. /// [C++] initializer:
  1866. /// [C++] '=' initializer-clause
  1867. /// [C++] '(' expression-list ')'
  1868. /// [C++0x] '=' 'default' [TODO]
  1869. /// [C++0x] '=' 'delete'
  1870. /// [C++0x] braced-init-list
  1871. ///
  1872. /// According to the standard grammar, =default and =delete are function
  1873. /// definitions, but that definitely doesn't fit with the parser here.
  1874. ///
  1875. Decl *Parser::ParseDeclarationAfterDeclarator(
  1876. Declarator &D, const ParsedTemplateInfo &TemplateInfo) {
  1877. if (ParseAsmAttributesAfterDeclarator(D))
  1878. return nullptr;
  1879. return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
  1880. }
  1881. Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
  1882. Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
  1883. // Inform the current actions module that we just parsed this declarator.
  1884. Decl *ThisDecl = nullptr;
  1885. switch (TemplateInfo.Kind) {
  1886. case ParsedTemplateInfo::NonTemplate:
  1887. ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
  1888. break;
  1889. case ParsedTemplateInfo::Template:
  1890. case ParsedTemplateInfo::ExplicitSpecialization: {
  1891. ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
  1892. *TemplateInfo.TemplateParams,
  1893. D);
  1894. if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl))
  1895. // Re-direct this decl to refer to the templated decl so that we can
  1896. // initialize it.
  1897. ThisDecl = VT->getTemplatedDecl();
  1898. break;
  1899. }
  1900. case ParsedTemplateInfo::ExplicitInstantiation: {
  1901. if (Tok.is(tok::semi)) {
  1902. DeclResult ThisRes = Actions.ActOnExplicitInstantiation(
  1903. getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D);
  1904. if (ThisRes.isInvalid()) {
  1905. SkipUntil(tok::semi, StopBeforeMatch);
  1906. return nullptr;
  1907. }
  1908. ThisDecl = ThisRes.get();
  1909. } else {
  1910. // FIXME: This check should be for a variable template instantiation only.
  1911. // Check that this is a valid instantiation
  1912. if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
  1913. // If the declarator-id is not a template-id, issue a diagnostic and
  1914. // recover by ignoring the 'template' keyword.
  1915. Diag(Tok, diag::err_template_defn_explicit_instantiation)
  1916. << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
  1917. ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
  1918. } else {
  1919. SourceLocation LAngleLoc =
  1920. PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
  1921. Diag(D.getIdentifierLoc(),
  1922. diag::err_explicit_instantiation_with_definition)
  1923. << SourceRange(TemplateInfo.TemplateLoc)
  1924. << FixItHint::CreateInsertion(LAngleLoc, "<>");
  1925. // Recover as if it were an explicit specialization.
  1926. TemplateParameterLists FakedParamLists;
  1927. FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
  1928. 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
  1929. LAngleLoc, nullptr));
  1930. ThisDecl =
  1931. Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D);
  1932. }
  1933. }
  1934. break;
  1935. }
  1936. }
  1937. // Parse declarator '=' initializer.
  1938. // If a '==' or '+=' is found, suggest a fixit to '='.
  1939. if (isTokenEqualOrEqualTypo()) {
  1940. SourceLocation EqualLoc = ConsumeToken();
  1941. if (Tok.is(tok::kw_delete)) {
  1942. if (D.isFunctionDeclarator())
  1943. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  1944. << 1 /* delete */;
  1945. else
  1946. Diag(ConsumeToken(), diag::err_deleted_non_function);
  1947. } else if (Tok.is(tok::kw_default)) {
  1948. if (D.isFunctionDeclarator())
  1949. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  1950. << 0 /* default */;
  1951. else
  1952. Diag(ConsumeToken(), diag::err_default_special_members);
  1953. } else {
  1954. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1955. EnterScope(0);
  1956. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  1957. }
  1958. if (Tok.is(tok::code_completion)) {
  1959. Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
  1960. Actions.FinalizeDeclaration(ThisDecl);
  1961. cutOffParsing();
  1962. return nullptr;
  1963. }
  1964. ExprResult Init(ParseInitializer());
  1965. // If this is the only decl in (possibly) range based for statement,
  1966. // our best guess is that the user meant ':' instead of '='.
  1967. if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) {
  1968. Diag(EqualLoc, diag::err_single_decl_assign_in_for_range)
  1969. << FixItHint::CreateReplacement(EqualLoc, ":");
  1970. // We are trying to stop parser from looking for ';' in this for
  1971. // statement, therefore preventing spurious errors to be issued.
  1972. FRI->ColonLoc = EqualLoc;
  1973. Init = ExprError();
  1974. FRI->RangeExpr = Init;
  1975. }
  1976. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1977. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1978. ExitScope();
  1979. }
  1980. if (Init.isInvalid()) {
  1981. SmallVector<tok::TokenKind, 2> StopTokens;
  1982. StopTokens.push_back(tok::comma);
  1983. if (D.getContext() == Declarator::ForContext ||
  1984. D.getContext() == Declarator::InitStmtContext)
  1985. StopTokens.push_back(tok::r_paren);
  1986. SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch);
  1987. Actions.ActOnInitializerError(ThisDecl);
  1988. } else
  1989. Actions.AddInitializerToDecl(ThisDecl, Init.get(),
  1990. /*DirectInit=*/false);
  1991. }
  1992. } else if (Tok.is(tok::l_paren)) {
  1993. // Parse C++ direct initializer: '(' expression-list ')'
  1994. BalancedDelimiterTracker T(*this, tok::l_paren);
  1995. T.consumeOpen();
  1996. ExprVector Exprs;
  1997. CommaLocsTy CommaLocs;
  1998. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1999. EnterScope(0);
  2000. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  2001. }
  2002. if (ParseExpressionList(Exprs, CommaLocs, [&] {
  2003. Actions.CodeCompleteConstructor(getCurScope(),
  2004. cast<VarDecl>(ThisDecl)->getType()->getCanonicalTypeInternal(),
  2005. ThisDecl->getLocation(), Exprs);
  2006. })) {
  2007. Actions.ActOnInitializerError(ThisDecl);
  2008. SkipUntil(tok::r_paren, StopAtSemi);
  2009. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  2010. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  2011. ExitScope();
  2012. }
  2013. } else {
  2014. // Match the ')'.
  2015. T.consumeClose();
  2016. assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
  2017. "Unexpected number of commas!");
  2018. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  2019. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  2020. ExitScope();
  2021. }
  2022. ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
  2023. T.getCloseLocation(),
  2024. Exprs);
  2025. Actions.AddInitializerToDecl(ThisDecl, Initializer.get(),
  2026. /*DirectInit=*/true);
  2027. }
  2028. } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) &&
  2029. (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
  2030. // Parse C++0x braced-init-list.
  2031. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  2032. if (D.getCXXScopeSpec().isSet()) {
  2033. EnterScope(0);
  2034. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  2035. }
  2036. ExprResult Init(ParseBraceInitializer());
  2037. if (D.getCXXScopeSpec().isSet()) {
  2038. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  2039. ExitScope();
  2040. }
  2041. if (Init.isInvalid()) {
  2042. Actions.ActOnInitializerError(ThisDecl);
  2043. } else
  2044. Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true);
  2045. } else {
  2046. Actions.ActOnUninitializedDecl(ThisDecl);
  2047. }
  2048. Actions.FinalizeDeclaration(ThisDecl);
  2049. return ThisDecl;
  2050. }
  2051. /// ParseSpecifierQualifierList
  2052. /// specifier-qualifier-list:
  2053. /// type-specifier specifier-qualifier-list[opt]
  2054. /// type-qualifier specifier-qualifier-list[opt]
  2055. /// [GNU] attributes specifier-qualifier-list[opt]
  2056. ///
  2057. void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
  2058. DeclSpecContext DSC) {
  2059. /// specifier-qualifier-list is a subset of declaration-specifiers. Just
  2060. /// parse declaration-specifiers and complain about extra stuff.
  2061. /// TODO: diagnose attribute-specifiers and alignment-specifiers.
  2062. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
  2063. // Validate declspec for type-name.
  2064. unsigned Specs = DS.getParsedSpecifiers();
  2065. if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) {
  2066. Diag(Tok, diag::err_expected_type);
  2067. DS.SetTypeSpecError();
  2068. } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) {
  2069. Diag(Tok, diag::err_typename_requires_specqual);
  2070. if (!DS.hasTypeSpecifier())
  2071. DS.SetTypeSpecError();
  2072. }
  2073. // Issue diagnostic and remove storage class if present.
  2074. if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
  2075. if (DS.getStorageClassSpecLoc().isValid())
  2076. Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
  2077. else
  2078. Diag(DS.getThreadStorageClassSpecLoc(),
  2079. diag::err_typename_invalid_storageclass);
  2080. DS.ClearStorageClassSpecs();
  2081. }
  2082. // Issue diagnostic and remove function specifier if present.
  2083. if (Specs & DeclSpec::PQ_FunctionSpecifier) {
  2084. if (DS.isInlineSpecified())
  2085. Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
  2086. if (DS.isVirtualSpecified())
  2087. Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
  2088. if (DS.isExplicitSpecified())
  2089. Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
  2090. DS.ClearFunctionSpecs();
  2091. }
  2092. // Issue diagnostic and remove constexpr specfier if present.
  2093. if (DS.isConstexprSpecified() && DSC != DSC_condition) {
  2094. Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
  2095. DS.ClearConstexprSpec();
  2096. }
  2097. }
  2098. /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
  2099. /// specified token is valid after the identifier in a declarator which
  2100. /// immediately follows the declspec. For example, these things are valid:
  2101. ///
  2102. /// int x [ 4]; // direct-declarator
  2103. /// int x ( int y); // direct-declarator
  2104. /// int(int x ) // direct-declarator
  2105. /// int x ; // simple-declaration
  2106. /// int x = 17; // init-declarator-list
  2107. /// int x , y; // init-declarator-list
  2108. /// int x __asm__ ("foo"); // init-declarator-list
  2109. /// int x : 4; // struct-declarator
  2110. /// int x { 5}; // C++'0x unified initializers
  2111. ///
  2112. /// This is not, because 'x' does not immediately follow the declspec (though
  2113. /// ')' happens to be valid anyway).
  2114. /// int (x)
  2115. ///
  2116. static bool isValidAfterIdentifierInDeclarator(const Token &T) {
  2117. return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi,
  2118. tok::comma, tok::equal, tok::kw_asm, tok::l_brace,
  2119. tok::colon);
  2120. }
  2121. /// ParseImplicitInt - This method is called when we have an non-typename
  2122. /// identifier in a declspec (which normally terminates the decl spec) when
  2123. /// the declspec has no type specifier. In this case, the declspec is either
  2124. /// malformed or is "implicit int" (in K&R and C89).
  2125. ///
  2126. /// This method handles diagnosing this prettily and returns false if the
  2127. /// declspec is done being processed. If it recovers and thinks there may be
  2128. /// other pieces of declspec after it, it returns true.
  2129. ///
  2130. bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
  2131. const ParsedTemplateInfo &TemplateInfo,
  2132. AccessSpecifier AS, DeclSpecContext DSC,
  2133. ParsedAttributesWithRange &Attrs) {
  2134. assert(Tok.is(tok::identifier) && "should have identifier");
  2135. SourceLocation Loc = Tok.getLocation();
  2136. // If we see an identifier that is not a type name, we normally would
  2137. // parse it as the identifer being declared. However, when a typename
  2138. // is typo'd or the definition is not included, this will incorrectly
  2139. // parse the typename as the identifier name and fall over misparsing
  2140. // later parts of the diagnostic.
  2141. //
  2142. // As such, we try to do some look-ahead in cases where this would
  2143. // otherwise be an "implicit-int" case to see if this is invalid. For
  2144. // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
  2145. // an identifier with implicit int, we'd get a parse error because the
  2146. // next token is obviously invalid for a type. Parse these as a case
  2147. // with an invalid type specifier.
  2148. assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
  2149. // Since we know that this either implicit int (which is rare) or an
  2150. // error, do lookahead to try to do better recovery. This never applies
  2151. // within a type specifier. Outside of C++, we allow this even if the
  2152. // language doesn't "officially" support implicit int -- we support
  2153. // implicit int as an extension in C99 and C11.
  2154. if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus &&
  2155. isValidAfterIdentifierInDeclarator(NextToken())) {
  2156. // If this token is valid for implicit int, e.g. "static x = 4", then
  2157. // we just avoid eating the identifier, so it will be parsed as the
  2158. // identifier in the declarator.
  2159. return false;
  2160. }
  2161. if (getLangOpts().CPlusPlus &&
  2162. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  2163. // Don't require a type specifier if we have the 'auto' storage class
  2164. // specifier in C++98 -- we'll promote it to a type specifier.
  2165. if (SS)
  2166. AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
  2167. return false;
  2168. }
  2169. if (getLangOpts().CPlusPlus && (!SS || SS->isEmpty()) &&
  2170. getLangOpts().MSVCCompat) {
  2171. // Lookup of an unqualified type name has failed in MSVC compatibility mode.
  2172. // Give Sema a chance to recover if we are in a template with dependent base
  2173. // classes.
  2174. if (ParsedType T = Actions.ActOnMSVCUnknownTypeName(
  2175. *Tok.getIdentifierInfo(), Tok.getLocation(),
  2176. DSC == DSC_template_type_arg)) {
  2177. const char *PrevSpec;
  2178. unsigned DiagID;
  2179. DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
  2180. Actions.getASTContext().getPrintingPolicy());
  2181. DS.SetRangeEnd(Tok.getLocation());
  2182. ConsumeToken();
  2183. return false;
  2184. }
  2185. }
  2186. // Otherwise, if we don't consume this token, we are going to emit an
  2187. // error anyway. Try to recover from various common problems. Check
  2188. // to see if this was a reference to a tag name without a tag specified.
  2189. // This is a common problem in C (saying 'foo' instead of 'struct foo').
  2190. //
  2191. // C++ doesn't need this, and isTagName doesn't take SS.
  2192. if (SS == nullptr) {
  2193. const char *TagName = nullptr, *FixitTagName = nullptr;
  2194. tok::TokenKind TagKind = tok::unknown;
  2195. switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
  2196. default: break;
  2197. case DeclSpec::TST_enum:
  2198. TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
  2199. case DeclSpec::TST_union:
  2200. TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
  2201. case DeclSpec::TST_struct:
  2202. TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
  2203. case DeclSpec::TST_interface:
  2204. TagName="__interface"; FixitTagName = "__interface ";
  2205. TagKind=tok::kw___interface;break;
  2206. case DeclSpec::TST_class:
  2207. TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
  2208. }
  2209. if (TagName) {
  2210. IdentifierInfo *TokenName = Tok.getIdentifierInfo();
  2211. LookupResult R(Actions, TokenName, SourceLocation(),
  2212. Sema::LookupOrdinaryName);
  2213. Diag(Loc, diag::err_use_of_tag_name_without_tag)
  2214. << TokenName << TagName << getLangOpts().CPlusPlus
  2215. << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
  2216. if (Actions.LookupParsedName(R, getCurScope(), SS)) {
  2217. for (LookupResult::iterator I = R.begin(), IEnd = R.end();
  2218. I != IEnd; ++I)
  2219. Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  2220. << TokenName << TagName;
  2221. }
  2222. // Parse this as a tag as if the missing tag were present.
  2223. if (TagKind == tok::kw_enum)
  2224. ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
  2225. else
  2226. ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
  2227. /*EnteringContext*/ false, DSC_normal, Attrs);
  2228. return true;
  2229. }
  2230. }
  2231. // Determine whether this identifier could plausibly be the name of something
  2232. // being declared (with a missing type).
  2233. if (!isTypeSpecifier(DSC) &&
  2234. (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
  2235. // Look ahead to the next token to try to figure out what this declaration
  2236. // was supposed to be.
  2237. switch (NextToken().getKind()) {
  2238. case tok::l_paren: {
  2239. // static x(4); // 'x' is not a type
  2240. // x(int n); // 'x' is not a type
  2241. // x (*p)[]; // 'x' is a type
  2242. //
  2243. // Since we're in an error case, we can afford to perform a tentative
  2244. // parse to determine which case we're in.
  2245. TentativeParsingAction PA(*this);
  2246. ConsumeToken();
  2247. TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
  2248. PA.Revert();
  2249. if (TPR != TPResult::False) {
  2250. // The identifier is followed by a parenthesized declarator.
  2251. // It's supposed to be a type.
  2252. break;
  2253. }
  2254. // If we're in a context where we could be declaring a constructor,
  2255. // check whether this is a constructor declaration with a bogus name.
  2256. if (DSC == DSC_class || (DSC == DSC_top_level && SS)) {
  2257. IdentifierInfo *II = Tok.getIdentifierInfo();
  2258. if (Actions.isCurrentClassNameTypo(II, SS)) {
  2259. Diag(Loc, diag::err_constructor_bad_name)
  2260. << Tok.getIdentifierInfo() << II
  2261. << FixItHint::CreateReplacement(Tok.getLocation(), II->getName());
  2262. Tok.setIdentifierInfo(II);
  2263. }
  2264. }
  2265. // Fall through.
  2266. LLVM_FALLTHROUGH;
  2267. }
  2268. case tok::comma:
  2269. case tok::equal:
  2270. case tok::kw_asm:
  2271. case tok::l_brace:
  2272. case tok::l_square:
  2273. case tok::semi:
  2274. // This looks like a variable or function declaration. The type is
  2275. // probably missing. We're done parsing decl-specifiers.
  2276. if (SS)
  2277. AnnotateScopeToken(*SS, /*IsNewAnnotation*/false);
  2278. return false;
  2279. default:
  2280. // This is probably supposed to be a type. This includes cases like:
  2281. // int f(itn);
  2282. // struct S { unsinged : 4; };
  2283. break;
  2284. }
  2285. }
  2286. // This is almost certainly an invalid type name. Let Sema emit a diagnostic
  2287. // and attempt to recover.
  2288. ParsedType T;
  2289. IdentifierInfo *II = Tok.getIdentifierInfo();
  2290. bool IsTemplateName = getLangOpts().CPlusPlus && NextToken().is(tok::less);
  2291. Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T,
  2292. IsTemplateName);
  2293. if (T) {
  2294. // The action has suggested that the type T could be used. Set that as
  2295. // the type in the declaration specifiers, consume the would-be type
  2296. // name token, and we're done.
  2297. const char *PrevSpec;
  2298. unsigned DiagID;
  2299. DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T,
  2300. Actions.getASTContext().getPrintingPolicy());
  2301. DS.SetRangeEnd(Tok.getLocation());
  2302. ConsumeToken();
  2303. // There may be other declaration specifiers after this.
  2304. return true;
  2305. } else if (II != Tok.getIdentifierInfo()) {
  2306. // If no type was suggested, the correction is to a keyword
  2307. Tok.setKind(II->getTokenID());
  2308. // There may be other declaration specifiers after this.
  2309. return true;
  2310. }
  2311. // Otherwise, the action had no suggestion for us. Mark this as an error.
  2312. DS.SetTypeSpecError();
  2313. DS.SetRangeEnd(Tok.getLocation());
  2314. ConsumeToken();
  2315. // Eat any following template arguments.
  2316. if (IsTemplateName) {
  2317. SourceLocation LAngle, RAngle;
  2318. TemplateArgList Args;
  2319. ParseTemplateIdAfterTemplateName(true, LAngle, Args, RAngle);
  2320. }
  2321. // TODO: Could inject an invalid typedef decl in an enclosing scope to
  2322. // avoid rippling error messages on subsequent uses of the same type,
  2323. // could be useful if #include was forgotten.
  2324. return false;
  2325. }
  2326. /// \brief Determine the declaration specifier context from the declarator
  2327. /// context.
  2328. ///
  2329. /// \param Context the declarator context, which is one of the
  2330. /// Declarator::TheContext enumerator values.
  2331. Parser::DeclSpecContext
  2332. Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
  2333. if (Context == Declarator::MemberContext)
  2334. return DSC_class;
  2335. if (Context == Declarator::FileContext)
  2336. return DSC_top_level;
  2337. if (Context == Declarator::TemplateParamContext)
  2338. return DSC_template_param;
  2339. if (Context == Declarator::TemplateTypeArgContext)
  2340. return DSC_template_type_arg;
  2341. if (Context == Declarator::TrailingReturnContext)
  2342. return DSC_trailing;
  2343. if (Context == Declarator::AliasDeclContext ||
  2344. Context == Declarator::AliasTemplateContext)
  2345. return DSC_alias_declaration;
  2346. return DSC_normal;
  2347. }
  2348. /// ParseAlignArgument - Parse the argument to an alignment-specifier.
  2349. ///
  2350. /// FIXME: Simply returns an alignof() expression if the argument is a
  2351. /// type. Ideally, the type should be propagated directly into Sema.
  2352. ///
  2353. /// [C11] type-id
  2354. /// [C11] constant-expression
  2355. /// [C++0x] type-id ...[opt]
  2356. /// [C++0x] assignment-expression ...[opt]
  2357. ExprResult Parser::ParseAlignArgument(SourceLocation Start,
  2358. SourceLocation &EllipsisLoc) {
  2359. ExprResult ER;
  2360. if (isTypeIdInParens()) {
  2361. SourceLocation TypeLoc = Tok.getLocation();
  2362. ParsedType Ty = ParseTypeName().get();
  2363. SourceRange TypeRange(Start, Tok.getLocation());
  2364. ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
  2365. Ty.getAsOpaquePtr(), TypeRange);
  2366. } else
  2367. ER = ParseConstantExpression();
  2368. if (getLangOpts().CPlusPlus11)
  2369. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  2370. return ER;
  2371. }
  2372. /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
  2373. /// attribute to Attrs.
  2374. ///
  2375. /// alignment-specifier:
  2376. /// [C11] '_Alignas' '(' type-id ')'
  2377. /// [C11] '_Alignas' '(' constant-expression ')'
  2378. /// [C++11] 'alignas' '(' type-id ...[opt] ')'
  2379. /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')'
  2380. void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
  2381. SourceLocation *EndLoc) {
  2382. assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) &&
  2383. "Not an alignment-specifier!");
  2384. IdentifierInfo *KWName = Tok.getIdentifierInfo();
  2385. SourceLocation KWLoc = ConsumeToken();
  2386. BalancedDelimiterTracker T(*this, tok::l_paren);
  2387. if (T.expectAndConsume())
  2388. return;
  2389. SourceLocation EllipsisLoc;
  2390. ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
  2391. if (ArgExpr.isInvalid()) {
  2392. T.skipToEnd();
  2393. return;
  2394. }
  2395. T.consumeClose();
  2396. if (EndLoc)
  2397. *EndLoc = T.getCloseLocation();
  2398. ArgsVector ArgExprs;
  2399. ArgExprs.push_back(ArgExpr.get());
  2400. Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1,
  2401. AttributeList::AS_Keyword, EllipsisLoc);
  2402. }
  2403. /// Determine whether we're looking at something that might be a declarator
  2404. /// in a simple-declaration. If it can't possibly be a declarator, maybe
  2405. /// diagnose a missing semicolon after a prior tag definition in the decl
  2406. /// specifier.
  2407. ///
  2408. /// \return \c true if an error occurred and this can't be any kind of
  2409. /// declaration.
  2410. bool
  2411. Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS,
  2412. DeclSpecContext DSContext,
  2413. LateParsedAttrList *LateAttrs) {
  2414. assert(DS.hasTagDefinition() && "shouldn't call this");
  2415. bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
  2416. if (getLangOpts().CPlusPlus &&
  2417. Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype,
  2418. tok::annot_template_id) &&
  2419. TryAnnotateCXXScopeToken(EnteringContext)) {
  2420. SkipMalformedDecl();
  2421. return true;
  2422. }
  2423. bool HasScope = Tok.is(tok::annot_cxxscope);
  2424. // Make a copy in case GetLookAheadToken invalidates the result of NextToken.
  2425. Token AfterScope = HasScope ? NextToken() : Tok;
  2426. // Determine whether the following tokens could possibly be a
  2427. // declarator.
  2428. bool MightBeDeclarator = true;
  2429. if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) {
  2430. // A declarator-id can't start with 'typename'.
  2431. MightBeDeclarator = false;
  2432. } else if (AfterScope.is(tok::annot_template_id)) {
  2433. // If we have a type expressed as a template-id, this cannot be a
  2434. // declarator-id (such a type cannot be redeclared in a simple-declaration).
  2435. TemplateIdAnnotation *Annot =
  2436. static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue());
  2437. if (Annot->Kind == TNK_Type_template)
  2438. MightBeDeclarator = false;
  2439. } else if (AfterScope.is(tok::identifier)) {
  2440. const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken();
  2441. // These tokens cannot come after the declarator-id in a
  2442. // simple-declaration, and are likely to come after a type-specifier.
  2443. if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier,
  2444. tok::annot_cxxscope, tok::coloncolon)) {
  2445. // Missing a semicolon.
  2446. MightBeDeclarator = false;
  2447. } else if (HasScope) {
  2448. // If the declarator-id has a scope specifier, it must redeclare a
  2449. // previously-declared entity. If that's a type (and this is not a
  2450. // typedef), that's an error.
  2451. CXXScopeSpec SS;
  2452. Actions.RestoreNestedNameSpecifierAnnotation(
  2453. Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
  2454. IdentifierInfo *Name = AfterScope.getIdentifierInfo();
  2455. Sema::NameClassification Classification = Actions.ClassifyName(
  2456. getCurScope(), SS, Name, AfterScope.getLocation(), Next,
  2457. /*IsAddressOfOperand*/false);
  2458. switch (Classification.getKind()) {
  2459. case Sema::NC_Error:
  2460. SkipMalformedDecl();
  2461. return true;
  2462. case Sema::NC_Keyword:
  2463. case Sema::NC_NestedNameSpecifier:
  2464. llvm_unreachable("typo correction and nested name specifiers not "
  2465. "possible here");
  2466. case Sema::NC_Type:
  2467. case Sema::NC_TypeTemplate:
  2468. // Not a previously-declared non-type entity.
  2469. MightBeDeclarator = false;
  2470. break;
  2471. case Sema::NC_Unknown:
  2472. case Sema::NC_Expression:
  2473. case Sema::NC_VarTemplate:
  2474. case Sema::NC_FunctionTemplate:
  2475. // Might be a redeclaration of a prior entity.
  2476. break;
  2477. }
  2478. }
  2479. }
  2480. if (MightBeDeclarator)
  2481. return false;
  2482. const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
  2483. Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()),
  2484. diag::err_expected_after)
  2485. << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi;
  2486. // Try to recover from the typo, by dropping the tag definition and parsing
  2487. // the problematic tokens as a type.
  2488. //
  2489. // FIXME: Split the DeclSpec into pieces for the standalone
  2490. // declaration and pieces for the following declaration, instead
  2491. // of assuming that all the other pieces attach to new declaration,
  2492. // and call ParsedFreeStandingDeclSpec as appropriate.
  2493. DS.ClearTypeSpecType();
  2494. ParsedTemplateInfo NotATemplate;
  2495. ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs);
  2496. return false;
  2497. }
  2498. /// ParseDeclarationSpecifiers
  2499. /// declaration-specifiers: [C99 6.7]
  2500. /// storage-class-specifier declaration-specifiers[opt]
  2501. /// type-specifier declaration-specifiers[opt]
  2502. /// [C99] function-specifier declaration-specifiers[opt]
  2503. /// [C11] alignment-specifier declaration-specifiers[opt]
  2504. /// [GNU] attributes declaration-specifiers[opt]
  2505. /// [Clang] '__module_private__' declaration-specifiers[opt]
  2506. /// [ObjC1] '__kindof' declaration-specifiers[opt]
  2507. ///
  2508. /// storage-class-specifier: [C99 6.7.1]
  2509. /// 'typedef'
  2510. /// 'extern'
  2511. /// 'static'
  2512. /// 'auto'
  2513. /// 'register'
  2514. /// [C++] 'mutable'
  2515. /// [C++11] 'thread_local'
  2516. /// [C11] '_Thread_local'
  2517. /// [GNU] '__thread'
  2518. /// function-specifier: [C99 6.7.4]
  2519. /// [C99] 'inline'
  2520. /// [C++] 'virtual'
  2521. /// [C++] 'explicit'
  2522. /// [OpenCL] '__kernel'
  2523. /// 'friend': [C++ dcl.friend]
  2524. /// 'constexpr': [C++0x dcl.constexpr]
  2525. void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
  2526. const ParsedTemplateInfo &TemplateInfo,
  2527. AccessSpecifier AS,
  2528. DeclSpecContext DSContext,
  2529. LateParsedAttrList *LateAttrs) {
  2530. if (DS.getSourceRange().isInvalid()) {
  2531. // Start the range at the current token but make the end of the range
  2532. // invalid. This will make the entire range invalid unless we successfully
  2533. // consume a token.
  2534. DS.SetRangeStart(Tok.getLocation());
  2535. DS.SetRangeEnd(SourceLocation());
  2536. }
  2537. bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
  2538. bool AttrsLastTime = false;
  2539. ParsedAttributesWithRange attrs(AttrFactory);
  2540. // We use Sema's policy to get bool macros right.
  2541. PrintingPolicy Policy = Actions.getPrintingPolicy();
  2542. while (1) {
  2543. bool isInvalid = false;
  2544. bool isStorageClass = false;
  2545. const char *PrevSpec = nullptr;
  2546. unsigned DiagID = 0;
  2547. // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
  2548. // implementation for VS2013 uses _Atomic as an identifier for one of the
  2549. // classes in <atomic>.
  2550. //
  2551. // A typedef declaration containing _Atomic<...> is among the places where
  2552. // the class is used. If we are currently parsing such a declaration, treat
  2553. // the token as an identifier.
  2554. if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
  2555. DS.getStorageClassSpec() == clang::DeclSpec::SCS_typedef &&
  2556. !DS.hasTypeSpecifier() && GetLookAheadToken(1).is(tok::less))
  2557. Tok.setKind(tok::identifier);
  2558. SourceLocation Loc = Tok.getLocation();
  2559. switch (Tok.getKind()) {
  2560. default:
  2561. DoneWithDeclSpec:
  2562. if (!AttrsLastTime)
  2563. ProhibitAttributes(attrs);
  2564. else {
  2565. // Reject C++11 attributes that appertain to decl specifiers as
  2566. // we don't support any C++11 attributes that appertain to decl
  2567. // specifiers. This also conforms to what g++ 4.8 is doing.
  2568. ProhibitCXX11Attributes(attrs, diag::err_attribute_not_type_attr);
  2569. DS.takeAttributesFrom(attrs);
  2570. }
  2571. // If this is not a declaration specifier token, we're done reading decl
  2572. // specifiers. First verify that DeclSpec's are consistent.
  2573. DS.Finish(Actions, Policy);
  2574. return;
  2575. case tok::l_square:
  2576. case tok::kw_alignas:
  2577. if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier())
  2578. goto DoneWithDeclSpec;
  2579. ProhibitAttributes(attrs);
  2580. // FIXME: It would be good to recover by accepting the attributes,
  2581. // but attempting to do that now would cause serious
  2582. // madness in terms of diagnostics.
  2583. attrs.clear();
  2584. attrs.Range = SourceRange();
  2585. ParseCXX11Attributes(attrs);
  2586. AttrsLastTime = true;
  2587. continue;
  2588. case tok::code_completion: {
  2589. Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
  2590. if (DS.hasTypeSpecifier()) {
  2591. bool AllowNonIdentifiers
  2592. = (getCurScope()->getFlags() & (Scope::ControlScope |
  2593. Scope::BlockScope |
  2594. Scope::TemplateParamScope |
  2595. Scope::FunctionPrototypeScope |
  2596. Scope::AtCatchScope)) == 0;
  2597. bool AllowNestedNameSpecifiers
  2598. = DSContext == DSC_top_level ||
  2599. (DSContext == DSC_class && DS.isFriendSpecified());
  2600. Actions.CodeCompleteDeclSpec(getCurScope(), DS,
  2601. AllowNonIdentifiers,
  2602. AllowNestedNameSpecifiers);
  2603. return cutOffParsing();
  2604. }
  2605. if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
  2606. CCC = Sema::PCC_LocalDeclarationSpecifiers;
  2607. else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
  2608. CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
  2609. : Sema::PCC_Template;
  2610. else if (DSContext == DSC_class)
  2611. CCC = Sema::PCC_Class;
  2612. else if (CurParsedObjCImpl)
  2613. CCC = Sema::PCC_ObjCImplementation;
  2614. Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
  2615. return cutOffParsing();
  2616. }
  2617. case tok::coloncolon: // ::foo::bar
  2618. // C++ scope specifier. Annotate and loop, or bail out on error.
  2619. if (TryAnnotateCXXScopeToken(EnteringContext)) {
  2620. if (!DS.hasTypeSpecifier())
  2621. DS.SetTypeSpecError();
  2622. goto DoneWithDeclSpec;
  2623. }
  2624. if (Tok.is(tok::coloncolon)) // ::new or ::delete
  2625. goto DoneWithDeclSpec;
  2626. continue;
  2627. case tok::annot_cxxscope: {
  2628. if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
  2629. goto DoneWithDeclSpec;
  2630. CXXScopeSpec SS;
  2631. Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
  2632. Tok.getAnnotationRange(),
  2633. SS);
  2634. // We are looking for a qualified typename.
  2635. Token Next = NextToken();
  2636. if (Next.is(tok::annot_template_id) &&
  2637. static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
  2638. ->Kind == TNK_Type_template) {
  2639. // We have a qualified template-id, e.g., N::A<int>
  2640. // If this would be a valid constructor declaration with template
  2641. // arguments, we will reject the attempt to form an invalid type-id
  2642. // referring to the injected-class-name when we annotate the token,
  2643. // per C++ [class.qual]p2.
  2644. //
  2645. // To improve diagnostics for this case, parse the declaration as a
  2646. // constructor (and reject the extra template arguments later).
  2647. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
  2648. if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
  2649. TemplateId->Name &&
  2650. Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS) &&
  2651. isConstructorDeclarator(/*Unqualified*/false)) {
  2652. // The user meant this to be an out-of-line constructor
  2653. // definition, but template arguments are not allowed
  2654. // there. Just allow this as a constructor; we'll
  2655. // complain about it later.
  2656. goto DoneWithDeclSpec;
  2657. }
  2658. DS.getTypeSpecScope() = SS;
  2659. ConsumeAnnotationToken(); // The C++ scope.
  2660. assert(Tok.is(tok::annot_template_id) &&
  2661. "ParseOptionalCXXScopeSpecifier not working");
  2662. AnnotateTemplateIdTokenAsType();
  2663. continue;
  2664. }
  2665. if (Next.is(tok::annot_typename)) {
  2666. DS.getTypeSpecScope() = SS;
  2667. ConsumeAnnotationToken(); // The C++ scope.
  2668. if (Tok.getAnnotationValue()) {
  2669. ParsedType T = getTypeAnnotation(Tok);
  2670. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
  2671. Tok.getAnnotationEndLoc(),
  2672. PrevSpec, DiagID, T, Policy);
  2673. if (isInvalid)
  2674. break;
  2675. }
  2676. else
  2677. DS.SetTypeSpecError();
  2678. DS.SetRangeEnd(Tok.getAnnotationEndLoc());
  2679. ConsumeAnnotationToken(); // The typename
  2680. }
  2681. if (Next.isNot(tok::identifier))
  2682. goto DoneWithDeclSpec;
  2683. // Check whether this is a constructor declaration. If we're in a
  2684. // context where the identifier could be a class name, and it has the
  2685. // shape of a constructor declaration, process it as one.
  2686. if ((DSContext == DSC_top_level || DSContext == DSC_class) &&
  2687. Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
  2688. &SS) &&
  2689. isConstructorDeclarator(/*Unqualified*/ false))
  2690. goto DoneWithDeclSpec;
  2691. ParsedType TypeRep =
  2692. Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(),
  2693. getCurScope(), &SS, false, false, nullptr,
  2694. /*IsCtorOrDtorName=*/false,
  2695. /*WantNonTrivialSourceInfo=*/true,
  2696. isClassTemplateDeductionContext(DSContext));
  2697. // If the referenced identifier is not a type, then this declspec is
  2698. // erroneous: We already checked about that it has no type specifier, and
  2699. // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
  2700. // typename.
  2701. if (!TypeRep) {
  2702. // Eat the scope spec so the identifier is current.
  2703. ConsumeAnnotationToken();
  2704. ParsedAttributesWithRange Attrs(AttrFactory);
  2705. if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) {
  2706. if (!Attrs.empty()) {
  2707. AttrsLastTime = true;
  2708. attrs.takeAllFrom(Attrs);
  2709. }
  2710. continue;
  2711. }
  2712. goto DoneWithDeclSpec;
  2713. }
  2714. DS.getTypeSpecScope() = SS;
  2715. ConsumeAnnotationToken(); // The C++ scope.
  2716. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2717. DiagID, TypeRep, Policy);
  2718. if (isInvalid)
  2719. break;
  2720. DS.SetRangeEnd(Tok.getLocation());
  2721. ConsumeToken(); // The typename.
  2722. continue;
  2723. }
  2724. case tok::annot_typename: {
  2725. // If we've previously seen a tag definition, we were almost surely
  2726. // missing a semicolon after it.
  2727. if (DS.hasTypeSpecifier() && DS.hasTagDefinition())
  2728. goto DoneWithDeclSpec;
  2729. if (Tok.getAnnotationValue()) {
  2730. ParsedType T = getTypeAnnotation(Tok);
  2731. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2732. DiagID, T, Policy);
  2733. } else
  2734. DS.SetTypeSpecError();
  2735. if (isInvalid)
  2736. break;
  2737. DS.SetRangeEnd(Tok.getAnnotationEndLoc());
  2738. ConsumeAnnotationToken(); // The typename
  2739. continue;
  2740. }
  2741. case tok::kw___is_signed:
  2742. // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
  2743. // typically treats it as a trait. If we see __is_signed as it appears
  2744. // in libstdc++, e.g.,
  2745. //
  2746. // static const bool __is_signed;
  2747. //
  2748. // then treat __is_signed as an identifier rather than as a keyword.
  2749. if (DS.getTypeSpecType() == TST_bool &&
  2750. DS.getTypeQualifiers() == DeclSpec::TQ_const &&
  2751. DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2752. TryKeywordIdentFallback(true);
  2753. // We're done with the declaration-specifiers.
  2754. goto DoneWithDeclSpec;
  2755. // typedef-name
  2756. case tok::kw___super:
  2757. case tok::kw_decltype:
  2758. case tok::identifier: {
  2759. // This identifier can only be a typedef name if we haven't already seen
  2760. // a type-specifier. Without this check we misparse:
  2761. // typedef int X; struct Y { short X; }; as 'short int'.
  2762. if (DS.hasTypeSpecifier())
  2763. goto DoneWithDeclSpec;
  2764. // If the token is an identifier named "__declspec" and Microsoft
  2765. // extensions are not enabled, it is likely that there will be cascading
  2766. // parse errors if this really is a __declspec attribute. Attempt to
  2767. // recognize that scenario and recover gracefully.
  2768. if (!getLangOpts().DeclSpecKeyword && Tok.is(tok::identifier) &&
  2769. Tok.getIdentifierInfo()->getName().equals("__declspec")) {
  2770. Diag(Loc, diag::err_ms_attributes_not_enabled);
  2771. // The next token should be an open paren. If it is, eat the entire
  2772. // attribute declaration and continue.
  2773. if (NextToken().is(tok::l_paren)) {
  2774. // Consume the __declspec identifier.
  2775. ConsumeToken();
  2776. // Eat the parens and everything between them.
  2777. BalancedDelimiterTracker T(*this, tok::l_paren);
  2778. if (T.consumeOpen()) {
  2779. assert(false && "Not a left paren?");
  2780. return;
  2781. }
  2782. T.skipToEnd();
  2783. continue;
  2784. }
  2785. }
  2786. // In C++, check to see if this is a scope specifier like foo::bar::, if
  2787. // so handle it as such. This is important for ctor parsing.
  2788. if (getLangOpts().CPlusPlus) {
  2789. if (TryAnnotateCXXScopeToken(EnteringContext)) {
  2790. DS.SetTypeSpecError();
  2791. goto DoneWithDeclSpec;
  2792. }
  2793. if (!Tok.is(tok::identifier))
  2794. continue;
  2795. }
  2796. // Check for need to substitute AltiVec keyword tokens.
  2797. if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
  2798. break;
  2799. // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
  2800. // allow the use of a typedef name as a type specifier.
  2801. if (DS.isTypeAltiVecVector())
  2802. goto DoneWithDeclSpec;
  2803. if (DSContext == DSC_objc_method_result && isObjCInstancetype()) {
  2804. ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc);
  2805. assert(TypeRep);
  2806. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2807. DiagID, TypeRep, Policy);
  2808. if (isInvalid)
  2809. break;
  2810. DS.SetRangeEnd(Loc);
  2811. ConsumeToken();
  2812. continue;
  2813. }
  2814. ParsedType TypeRep = Actions.getTypeName(
  2815. *Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), nullptr,
  2816. false, false, nullptr, false, false,
  2817. isClassTemplateDeductionContext(DSContext));
  2818. // If this is not a typedef name, don't parse it as part of the declspec,
  2819. // it must be an implicit int or an error.
  2820. if (!TypeRep) {
  2821. ParsedAttributesWithRange Attrs(AttrFactory);
  2822. if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) {
  2823. if (!Attrs.empty()) {
  2824. AttrsLastTime = true;
  2825. attrs.takeAllFrom(Attrs);
  2826. }
  2827. continue;
  2828. }
  2829. goto DoneWithDeclSpec;
  2830. }
  2831. // If we're in a context where the identifier could be a class name,
  2832. // check whether this is a constructor declaration.
  2833. if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
  2834. Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
  2835. isConstructorDeclarator(/*Unqualified*/true))
  2836. goto DoneWithDeclSpec;
  2837. // Likewise, if this is a context where the identifier could be a template
  2838. // name, check whether this is a deduction guide declaration.
  2839. if (getLangOpts().CPlusPlus1z &&
  2840. (DSContext == DSC_class || DSContext == DSC_top_level) &&
  2841. Actions.isDeductionGuideName(getCurScope(), *Tok.getIdentifierInfo(),
  2842. Tok.getLocation()) &&
  2843. isConstructorDeclarator(/*Unqualified*/ true,
  2844. /*DeductionGuide*/ true))
  2845. goto DoneWithDeclSpec;
  2846. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2847. DiagID, TypeRep, Policy);
  2848. if (isInvalid)
  2849. break;
  2850. DS.SetRangeEnd(Tok.getLocation());
  2851. ConsumeToken(); // The identifier
  2852. // Objective-C supports type arguments and protocol references
  2853. // following an Objective-C object or object pointer
  2854. // type. Handle either one of them.
  2855. if (Tok.is(tok::less) && getLangOpts().ObjC1) {
  2856. SourceLocation NewEndLoc;
  2857. TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers(
  2858. Loc, TypeRep, /*consumeLastToken=*/true,
  2859. NewEndLoc);
  2860. if (NewTypeRep.isUsable()) {
  2861. DS.UpdateTypeRep(NewTypeRep.get());
  2862. DS.SetRangeEnd(NewEndLoc);
  2863. }
  2864. }
  2865. // Need to support trailing type qualifiers (e.g. "id<p> const").
  2866. // If a type specifier follows, it will be diagnosed elsewhere.
  2867. continue;
  2868. }
  2869. // type-name
  2870. case tok::annot_template_id: {
  2871. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  2872. if (TemplateId->Kind != TNK_Type_template) {
  2873. // This template-id does not refer to a type name, so we're
  2874. // done with the type-specifiers.
  2875. goto DoneWithDeclSpec;
  2876. }
  2877. // If we're in a context where the template-id could be a
  2878. // constructor name or specialization, check whether this is a
  2879. // constructor declaration.
  2880. if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
  2881. Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
  2882. isConstructorDeclarator(TemplateId->SS.isEmpty()))
  2883. goto DoneWithDeclSpec;
  2884. // Turn the template-id annotation token into a type annotation
  2885. // token, then try again to parse it as a type-specifier.
  2886. AnnotateTemplateIdTokenAsType();
  2887. continue;
  2888. }
  2889. // GNU attributes support.
  2890. case tok::kw___attribute:
  2891. ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs);
  2892. continue;
  2893. // Microsoft declspec support.
  2894. case tok::kw___declspec:
  2895. ParseMicrosoftDeclSpecs(DS.getAttributes());
  2896. continue;
  2897. // Microsoft single token adornments.
  2898. case tok::kw___forceinline: {
  2899. isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID);
  2900. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  2901. SourceLocation AttrNameLoc = Tok.getLocation();
  2902. DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc,
  2903. nullptr, 0, AttributeList::AS_Keyword);
  2904. break;
  2905. }
  2906. case tok::kw___unaligned:
  2907. isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
  2908. getLangOpts());
  2909. break;
  2910. case tok::kw___sptr:
  2911. case tok::kw___uptr:
  2912. case tok::kw___ptr64:
  2913. case tok::kw___ptr32:
  2914. case tok::kw___w64:
  2915. case tok::kw___cdecl:
  2916. case tok::kw___stdcall:
  2917. case tok::kw___fastcall:
  2918. case tok::kw___thiscall:
  2919. case tok::kw___regcall:
  2920. case tok::kw___vectorcall:
  2921. ParseMicrosoftTypeAttributes(DS.getAttributes());
  2922. continue;
  2923. // Borland single token adornments.
  2924. case tok::kw___pascal:
  2925. ParseBorlandTypeAttributes(DS.getAttributes());
  2926. continue;
  2927. // OpenCL single token adornments.
  2928. case tok::kw___kernel:
  2929. ParseOpenCLKernelAttributes(DS.getAttributes());
  2930. continue;
  2931. // Nullability type specifiers.
  2932. case tok::kw__Nonnull:
  2933. case tok::kw__Nullable:
  2934. case tok::kw__Null_unspecified:
  2935. ParseNullabilityTypeSpecifiers(DS.getAttributes());
  2936. continue;
  2937. // Objective-C 'kindof' types.
  2938. case tok::kw___kindof:
  2939. DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
  2940. nullptr, 0, AttributeList::AS_Keyword);
  2941. (void)ConsumeToken();
  2942. continue;
  2943. // storage-class-specifier
  2944. case tok::kw_typedef:
  2945. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
  2946. PrevSpec, DiagID, Policy);
  2947. isStorageClass = true;
  2948. break;
  2949. case tok::kw_extern:
  2950. if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
  2951. Diag(Tok, diag::ext_thread_before) << "extern";
  2952. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
  2953. PrevSpec, DiagID, Policy);
  2954. isStorageClass = true;
  2955. break;
  2956. case tok::kw___private_extern__:
  2957. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
  2958. Loc, PrevSpec, DiagID, Policy);
  2959. isStorageClass = true;
  2960. break;
  2961. case tok::kw_static:
  2962. if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread)
  2963. Diag(Tok, diag::ext_thread_before) << "static";
  2964. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
  2965. PrevSpec, DiagID, Policy);
  2966. isStorageClass = true;
  2967. break;
  2968. case tok::kw_auto:
  2969. if (getLangOpts().CPlusPlus11) {
  2970. if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
  2971. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
  2972. PrevSpec, DiagID, Policy);
  2973. if (!isInvalid)
  2974. Diag(Tok, diag::ext_auto_storage_class)
  2975. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  2976. } else
  2977. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
  2978. DiagID, Policy);
  2979. } else
  2980. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
  2981. PrevSpec, DiagID, Policy);
  2982. isStorageClass = true;
  2983. break;
  2984. case tok::kw___auto_type:
  2985. Diag(Tok, diag::ext_auto_type);
  2986. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto_type, Loc, PrevSpec,
  2987. DiagID, Policy);
  2988. break;
  2989. case tok::kw_register:
  2990. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
  2991. PrevSpec, DiagID, Policy);
  2992. isStorageClass = true;
  2993. break;
  2994. case tok::kw_mutable:
  2995. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
  2996. PrevSpec, DiagID, Policy);
  2997. isStorageClass = true;
  2998. break;
  2999. case tok::kw___thread:
  3000. isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc,
  3001. PrevSpec, DiagID);
  3002. isStorageClass = true;
  3003. break;
  3004. case tok::kw_thread_local:
  3005. isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc,
  3006. PrevSpec, DiagID);
  3007. break;
  3008. case tok::kw__Thread_local:
  3009. isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local,
  3010. Loc, PrevSpec, DiagID);
  3011. isStorageClass = true;
  3012. break;
  3013. // function-specifier
  3014. case tok::kw_inline:
  3015. isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID);
  3016. break;
  3017. case tok::kw_virtual:
  3018. isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID);
  3019. break;
  3020. case tok::kw_explicit:
  3021. isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID);
  3022. break;
  3023. case tok::kw__Noreturn:
  3024. if (!getLangOpts().C11)
  3025. Diag(Loc, diag::ext_c11_noreturn);
  3026. isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID);
  3027. break;
  3028. // alignment-specifier
  3029. case tok::kw__Alignas:
  3030. if (!getLangOpts().C11)
  3031. Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
  3032. ParseAlignmentSpecifier(DS.getAttributes());
  3033. continue;
  3034. // friend
  3035. case tok::kw_friend:
  3036. if (DSContext == DSC_class)
  3037. isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
  3038. else {
  3039. PrevSpec = ""; // not actually used by the diagnostic
  3040. DiagID = diag::err_friend_invalid_in_context;
  3041. isInvalid = true;
  3042. }
  3043. break;
  3044. // Modules
  3045. case tok::kw___module_private__:
  3046. isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
  3047. break;
  3048. // constexpr
  3049. case tok::kw_constexpr:
  3050. isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
  3051. break;
  3052. // concept
  3053. case tok::kw_concept:
  3054. isInvalid = DS.SetConceptSpec(Loc, PrevSpec, DiagID);
  3055. break;
  3056. // type-specifier
  3057. case tok::kw_short:
  3058. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
  3059. DiagID, Policy);
  3060. break;
  3061. case tok::kw_long:
  3062. if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
  3063. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
  3064. DiagID, Policy);
  3065. else
  3066. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
  3067. DiagID, Policy);
  3068. break;
  3069. case tok::kw___int64:
  3070. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
  3071. DiagID, Policy);
  3072. break;
  3073. case tok::kw_signed:
  3074. isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
  3075. DiagID);
  3076. break;
  3077. case tok::kw_unsigned:
  3078. isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
  3079. DiagID);
  3080. break;
  3081. case tok::kw__Complex:
  3082. isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
  3083. DiagID);
  3084. break;
  3085. case tok::kw__Imaginary:
  3086. isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
  3087. DiagID);
  3088. break;
  3089. case tok::kw_void:
  3090. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
  3091. DiagID, Policy);
  3092. break;
  3093. case tok::kw_char:
  3094. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
  3095. DiagID, Policy);
  3096. break;
  3097. case tok::kw_int:
  3098. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
  3099. DiagID, Policy);
  3100. break;
  3101. case tok::kw___int128:
  3102. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
  3103. DiagID, Policy);
  3104. break;
  3105. case tok::kw_half:
  3106. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
  3107. DiagID, Policy);
  3108. break;
  3109. case tok::kw_float:
  3110. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
  3111. DiagID, Policy);
  3112. break;
  3113. case tok::kw_double:
  3114. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
  3115. DiagID, Policy);
  3116. break;
  3117. case tok::kw__Float16:
  3118. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec,
  3119. DiagID, Policy);
  3120. break;
  3121. case tok::kw___float128:
  3122. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec,
  3123. DiagID, Policy);
  3124. break;
  3125. case tok::kw_wchar_t:
  3126. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
  3127. DiagID, Policy);
  3128. break;
  3129. case tok::kw_char16_t:
  3130. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
  3131. DiagID, Policy);
  3132. break;
  3133. case tok::kw_char32_t:
  3134. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
  3135. DiagID, Policy);
  3136. break;
  3137. case tok::kw_bool:
  3138. case tok::kw__Bool:
  3139. if (Tok.is(tok::kw_bool) &&
  3140. DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
  3141. DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  3142. PrevSpec = ""; // Not used by the diagnostic.
  3143. DiagID = diag::err_bool_redeclaration;
  3144. // For better error recovery.
  3145. Tok.setKind(tok::identifier);
  3146. isInvalid = true;
  3147. } else {
  3148. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
  3149. DiagID, Policy);
  3150. }
  3151. break;
  3152. case tok::kw__Decimal32:
  3153. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
  3154. DiagID, Policy);
  3155. break;
  3156. case tok::kw__Decimal64:
  3157. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
  3158. DiagID, Policy);
  3159. break;
  3160. case tok::kw__Decimal128:
  3161. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
  3162. DiagID, Policy);
  3163. break;
  3164. case tok::kw___vector:
  3165. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
  3166. break;
  3167. case tok::kw___pixel:
  3168. isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
  3169. break;
  3170. case tok::kw___bool:
  3171. isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
  3172. break;
  3173. case tok::kw_pipe:
  3174. if (!getLangOpts().OpenCL || (getLangOpts().OpenCLVersion < 200)) {
  3175. // OpenCL 2.0 defined this keyword. OpenCL 1.2 and earlier should
  3176. // support the "pipe" word as identifier.
  3177. Tok.getIdentifierInfo()->revertTokenIDToIdentifier();
  3178. goto DoneWithDeclSpec;
  3179. }
  3180. isInvalid = DS.SetTypePipe(true, Loc, PrevSpec, DiagID, Policy);
  3181. break;
  3182. #define GENERIC_IMAGE_TYPE(ImgType, Id) \
  3183. case tok::kw_##ImgType##_t: \
  3184. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, \
  3185. DiagID, Policy); \
  3186. break;
  3187. #include "clang/Basic/OpenCLImageTypes.def"
  3188. case tok::kw___unknown_anytype:
  3189. isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
  3190. PrevSpec, DiagID, Policy);
  3191. break;
  3192. // class-specifier:
  3193. case tok::kw_class:
  3194. case tok::kw_struct:
  3195. case tok::kw___interface:
  3196. case tok::kw_union: {
  3197. tok::TokenKind Kind = Tok.getKind();
  3198. ConsumeToken();
  3199. // These are attributes following class specifiers.
  3200. // To produce better diagnostic, we parse them when
  3201. // parsing class specifier.
  3202. ParsedAttributesWithRange Attributes(AttrFactory);
  3203. ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
  3204. EnteringContext, DSContext, Attributes);
  3205. // If there are attributes following class specifier,
  3206. // take them over and handle them here.
  3207. if (!Attributes.empty()) {
  3208. AttrsLastTime = true;
  3209. attrs.takeAllFrom(Attributes);
  3210. }
  3211. continue;
  3212. }
  3213. // enum-specifier:
  3214. case tok::kw_enum:
  3215. ConsumeToken();
  3216. ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
  3217. continue;
  3218. // cv-qualifier:
  3219. case tok::kw_const:
  3220. isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
  3221. getLangOpts());
  3222. break;
  3223. case tok::kw_volatile:
  3224. isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
  3225. getLangOpts());
  3226. break;
  3227. case tok::kw_restrict:
  3228. isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
  3229. getLangOpts());
  3230. break;
  3231. // C++ typename-specifier:
  3232. case tok::kw_typename:
  3233. if (TryAnnotateTypeOrScopeToken()) {
  3234. DS.SetTypeSpecError();
  3235. goto DoneWithDeclSpec;
  3236. }
  3237. if (!Tok.is(tok::kw_typename))
  3238. continue;
  3239. break;
  3240. // GNU typeof support.
  3241. case tok::kw_typeof:
  3242. ParseTypeofSpecifier(DS);
  3243. continue;
  3244. case tok::annot_decltype:
  3245. ParseDecltypeSpecifier(DS);
  3246. continue;
  3247. case tok::annot_pragma_pack:
  3248. HandlePragmaPack();
  3249. continue;
  3250. case tok::annot_pragma_ms_pragma:
  3251. HandlePragmaMSPragma();
  3252. continue;
  3253. case tok::annot_pragma_ms_vtordisp:
  3254. HandlePragmaMSVtorDisp();
  3255. continue;
  3256. case tok::annot_pragma_ms_pointers_to_members:
  3257. HandlePragmaMSPointersToMembers();
  3258. continue;
  3259. case tok::kw___underlying_type:
  3260. ParseUnderlyingTypeSpecifier(DS);
  3261. continue;
  3262. case tok::kw__Atomic:
  3263. // C11 6.7.2.4/4:
  3264. // If the _Atomic keyword is immediately followed by a left parenthesis,
  3265. // it is interpreted as a type specifier (with a type name), not as a
  3266. // type qualifier.
  3267. if (NextToken().is(tok::l_paren)) {
  3268. ParseAtomicSpecifier(DS);
  3269. continue;
  3270. }
  3271. isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
  3272. getLangOpts());
  3273. break;
  3274. // OpenCL qualifiers:
  3275. case tok::kw___generic:
  3276. // generic address space is introduced only in OpenCL v2.0
  3277. // see OpenCL C Spec v2.0 s6.5.5
  3278. if (Actions.getLangOpts().OpenCLVersion < 200) {
  3279. DiagID = diag::err_opencl_unknown_type_specifier;
  3280. PrevSpec = Tok.getIdentifierInfo()->getNameStart();
  3281. isInvalid = true;
  3282. break;
  3283. };
  3284. LLVM_FALLTHROUGH;
  3285. case tok::kw___private:
  3286. case tok::kw___global:
  3287. case tok::kw___local:
  3288. case tok::kw___constant:
  3289. case tok::kw___read_only:
  3290. case tok::kw___write_only:
  3291. case tok::kw___read_write:
  3292. ParseOpenCLQualifiers(DS.getAttributes());
  3293. break;
  3294. case tok::less:
  3295. // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
  3296. // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
  3297. // but we support it.
  3298. if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
  3299. goto DoneWithDeclSpec;
  3300. SourceLocation StartLoc = Tok.getLocation();
  3301. SourceLocation EndLoc;
  3302. TypeResult Type = parseObjCProtocolQualifierType(EndLoc);
  3303. if (Type.isUsable()) {
  3304. if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc,
  3305. PrevSpec, DiagID, Type.get(),
  3306. Actions.getASTContext().getPrintingPolicy()))
  3307. Diag(StartLoc, DiagID) << PrevSpec;
  3308. DS.SetRangeEnd(EndLoc);
  3309. } else {
  3310. DS.SetTypeSpecError();
  3311. }
  3312. // Need to support trailing type qualifiers (e.g. "id<p> const").
  3313. // If a type specifier follows, it will be diagnosed elsewhere.
  3314. continue;
  3315. }
  3316. // If the specifier wasn't legal, issue a diagnostic.
  3317. if (isInvalid) {
  3318. assert(PrevSpec && "Method did not return previous specifier!");
  3319. assert(DiagID);
  3320. if (DiagID == diag::ext_duplicate_declspec)
  3321. Diag(Tok, DiagID)
  3322. << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
  3323. else if (DiagID == diag::err_opencl_unknown_type_specifier) {
  3324. const int OpenCLVer = getLangOpts().OpenCLVersion;
  3325. std::string VerSpec = llvm::to_string(OpenCLVer / 100) +
  3326. std::string (".") +
  3327. llvm::to_string((OpenCLVer % 100) / 10);
  3328. Diag(Tok, DiagID) << VerSpec << PrevSpec << isStorageClass;
  3329. } else
  3330. Diag(Tok, DiagID) << PrevSpec;
  3331. }
  3332. DS.SetRangeEnd(Tok.getLocation());
  3333. if (DiagID != diag::err_bool_redeclaration)
  3334. ConsumeToken();
  3335. AttrsLastTime = false;
  3336. }
  3337. }
  3338. /// ParseStructDeclaration - Parse a struct declaration without the terminating
  3339. /// semicolon.
  3340. ///
  3341. /// struct-declaration:
  3342. /// specifier-qualifier-list struct-declarator-list
  3343. /// [GNU] __extension__ struct-declaration
  3344. /// [GNU] specifier-qualifier-list
  3345. /// struct-declarator-list:
  3346. /// struct-declarator
  3347. /// struct-declarator-list ',' struct-declarator
  3348. /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
  3349. /// struct-declarator:
  3350. /// declarator
  3351. /// [GNU] declarator attributes[opt]
  3352. /// declarator[opt] ':' constant-expression
  3353. /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
  3354. ///
  3355. void Parser::ParseStructDeclaration(
  3356. ParsingDeclSpec &DS,
  3357. llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) {
  3358. if (Tok.is(tok::kw___extension__)) {
  3359. // __extension__ silences extension warnings in the subexpression.
  3360. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  3361. ConsumeToken();
  3362. return ParseStructDeclaration(DS, FieldsCallback);
  3363. }
  3364. // Parse the common specifier-qualifiers-list piece.
  3365. ParseSpecifierQualifierList(DS);
  3366. // If there are no declarators, this is a free-standing declaration
  3367. // specifier. Let the actions module cope with it.
  3368. if (Tok.is(tok::semi)) {
  3369. RecordDecl *AnonRecord = nullptr;
  3370. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
  3371. DS, AnonRecord);
  3372. assert(!AnonRecord && "Did not expect anonymous struct or union here");
  3373. DS.complete(TheDecl);
  3374. return;
  3375. }
  3376. // Read struct-declarators until we find the semicolon.
  3377. bool FirstDeclarator = true;
  3378. SourceLocation CommaLoc;
  3379. while (1) {
  3380. ParsingFieldDeclarator DeclaratorInfo(*this, DS);
  3381. DeclaratorInfo.D.setCommaLoc(CommaLoc);
  3382. // Attributes are only allowed here on successive declarators.
  3383. if (!FirstDeclarator)
  3384. MaybeParseGNUAttributes(DeclaratorInfo.D);
  3385. /// struct-declarator: declarator
  3386. /// struct-declarator: declarator[opt] ':' constant-expression
  3387. if (Tok.isNot(tok::colon)) {
  3388. // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
  3389. ColonProtectionRAIIObject X(*this);
  3390. ParseDeclarator(DeclaratorInfo.D);
  3391. } else
  3392. DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation());
  3393. if (TryConsumeToken(tok::colon)) {
  3394. ExprResult Res(ParseConstantExpression());
  3395. if (Res.isInvalid())
  3396. SkipUntil(tok::semi, StopBeforeMatch);
  3397. else
  3398. DeclaratorInfo.BitfieldSize = Res.get();
  3399. }
  3400. // If attributes exist after the declarator, parse them.
  3401. MaybeParseGNUAttributes(DeclaratorInfo.D);
  3402. // We're done with this declarator; invoke the callback.
  3403. FieldsCallback(DeclaratorInfo);
  3404. // If we don't have a comma, it is either the end of the list (a ';')
  3405. // or an error, bail out.
  3406. if (!TryConsumeToken(tok::comma, CommaLoc))
  3407. return;
  3408. FirstDeclarator = false;
  3409. }
  3410. }
  3411. /// ParseStructUnionBody
  3412. /// struct-contents:
  3413. /// struct-declaration-list
  3414. /// [EXT] empty
  3415. /// [GNU] "struct-declaration-list" without terminatoring ';'
  3416. /// struct-declaration-list:
  3417. /// struct-declaration
  3418. /// struct-declaration-list struct-declaration
  3419. /// [OBC] '@' 'defs' '(' class-name ')'
  3420. ///
  3421. void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
  3422. unsigned TagType, Decl *TagDecl) {
  3423. PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
  3424. "parsing struct/union body");
  3425. assert(!getLangOpts().CPlusPlus && "C++ declarations not supported");
  3426. BalancedDelimiterTracker T(*this, tok::l_brace);
  3427. if (T.consumeOpen())
  3428. return;
  3429. ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
  3430. Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
  3431. SmallVector<Decl *, 32> FieldDecls;
  3432. // While we still have something to read, read the declarations in the struct.
  3433. while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
  3434. Tok.isNot(tok::eof)) {
  3435. // Each iteration of this loop reads one struct-declaration.
  3436. // Check for extraneous top-level semicolon.
  3437. if (Tok.is(tok::semi)) {
  3438. ConsumeExtraSemi(InsideStruct, TagType);
  3439. continue;
  3440. }
  3441. // Parse _Static_assert declaration.
  3442. if (Tok.is(tok::kw__Static_assert)) {
  3443. SourceLocation DeclEnd;
  3444. ParseStaticAssertDeclaration(DeclEnd);
  3445. continue;
  3446. }
  3447. if (Tok.is(tok::annot_pragma_pack)) {
  3448. HandlePragmaPack();
  3449. continue;
  3450. }
  3451. if (Tok.is(tok::annot_pragma_align)) {
  3452. HandlePragmaAlign();
  3453. continue;
  3454. }
  3455. if (Tok.is(tok::annot_pragma_openmp)) {
  3456. // Result can be ignored, because it must be always empty.
  3457. AccessSpecifier AS = AS_none;
  3458. ParsedAttributesWithRange Attrs(AttrFactory);
  3459. (void)ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs);
  3460. continue;
  3461. }
  3462. if (!Tok.is(tok::at)) {
  3463. auto CFieldCallback = [&](ParsingFieldDeclarator &FD) {
  3464. // Install the declarator into the current TagDecl.
  3465. Decl *Field =
  3466. Actions.ActOnField(getCurScope(), TagDecl,
  3467. FD.D.getDeclSpec().getSourceRange().getBegin(),
  3468. FD.D, FD.BitfieldSize);
  3469. FieldDecls.push_back(Field);
  3470. FD.complete(Field);
  3471. };
  3472. // Parse all the comma separated declarators.
  3473. ParsingDeclSpec DS(*this);
  3474. ParseStructDeclaration(DS, CFieldCallback);
  3475. } else { // Handle @defs
  3476. ConsumeToken();
  3477. if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
  3478. Diag(Tok, diag::err_unexpected_at);
  3479. SkipUntil(tok::semi);
  3480. continue;
  3481. }
  3482. ConsumeToken();
  3483. ExpectAndConsume(tok::l_paren);
  3484. if (!Tok.is(tok::identifier)) {
  3485. Diag(Tok, diag::err_expected) << tok::identifier;
  3486. SkipUntil(tok::semi);
  3487. continue;
  3488. }
  3489. SmallVector<Decl *, 16> Fields;
  3490. Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
  3491. Tok.getIdentifierInfo(), Fields);
  3492. FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
  3493. ConsumeToken();
  3494. ExpectAndConsume(tok::r_paren);
  3495. }
  3496. if (TryConsumeToken(tok::semi))
  3497. continue;
  3498. if (Tok.is(tok::r_brace)) {
  3499. ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
  3500. break;
  3501. }
  3502. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
  3503. // Skip to end of block or statement to avoid ext-warning on extra ';'.
  3504. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  3505. // If we stopped at a ';', eat it.
  3506. TryConsumeToken(tok::semi);
  3507. }
  3508. T.consumeClose();
  3509. ParsedAttributes attrs(AttrFactory);
  3510. // If attributes exist after struct contents, parse them.
  3511. MaybeParseGNUAttributes(attrs);
  3512. Actions.ActOnFields(getCurScope(),
  3513. RecordLoc, TagDecl, FieldDecls,
  3514. T.getOpenLocation(), T.getCloseLocation(),
  3515. attrs.getList());
  3516. StructScope.Exit();
  3517. Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
  3518. }
  3519. /// ParseEnumSpecifier
  3520. /// enum-specifier: [C99 6.7.2.2]
  3521. /// 'enum' identifier[opt] '{' enumerator-list '}'
  3522. ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
  3523. /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
  3524. /// '}' attributes[opt]
  3525. /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
  3526. /// '}'
  3527. /// 'enum' identifier
  3528. /// [GNU] 'enum' attributes[opt] identifier
  3529. ///
  3530. /// [C++11] enum-head '{' enumerator-list[opt] '}'
  3531. /// [C++11] enum-head '{' enumerator-list ',' '}'
  3532. ///
  3533. /// enum-head: [C++11]
  3534. /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
  3535. /// enum-key attribute-specifier-seq[opt] nested-name-specifier
  3536. /// identifier enum-base[opt]
  3537. ///
  3538. /// enum-key: [C++11]
  3539. /// 'enum'
  3540. /// 'enum' 'class'
  3541. /// 'enum' 'struct'
  3542. ///
  3543. /// enum-base: [C++11]
  3544. /// ':' type-specifier-seq
  3545. ///
  3546. /// [C++] elaborated-type-specifier:
  3547. /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
  3548. ///
  3549. void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
  3550. const ParsedTemplateInfo &TemplateInfo,
  3551. AccessSpecifier AS, DeclSpecContext DSC) {
  3552. // Parse the tag portion of this.
  3553. if (Tok.is(tok::code_completion)) {
  3554. // Code completion for an enum name.
  3555. Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
  3556. return cutOffParsing();
  3557. }
  3558. // If attributes exist after tag, parse them.
  3559. ParsedAttributesWithRange attrs(AttrFactory);
  3560. MaybeParseGNUAttributes(attrs);
  3561. MaybeParseCXX11Attributes(attrs);
  3562. MaybeParseMicrosoftDeclSpecs(attrs);
  3563. SourceLocation ScopedEnumKWLoc;
  3564. bool IsScopedUsingClassTag = false;
  3565. // In C++11, recognize 'enum class' and 'enum struct'.
  3566. if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) {
  3567. Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum
  3568. : diag::ext_scoped_enum);
  3569. IsScopedUsingClassTag = Tok.is(tok::kw_class);
  3570. ScopedEnumKWLoc = ConsumeToken();
  3571. // Attributes are not allowed between these keywords. Diagnose,
  3572. // but then just treat them like they appeared in the right place.
  3573. ProhibitAttributes(attrs);
  3574. // They are allowed afterwards, though.
  3575. MaybeParseGNUAttributes(attrs);
  3576. MaybeParseCXX11Attributes(attrs);
  3577. MaybeParseMicrosoftDeclSpecs(attrs);
  3578. }
  3579. // C++11 [temp.explicit]p12:
  3580. // The usual access controls do not apply to names used to specify
  3581. // explicit instantiations.
  3582. // We extend this to also cover explicit specializations. Note that
  3583. // we don't suppress if this turns out to be an elaborated type
  3584. // specifier.
  3585. bool shouldDelayDiagsInTag =
  3586. (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
  3587. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
  3588. SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
  3589. // Enum definitions should not be parsed in a trailing-return-type.
  3590. bool AllowDeclaration = DSC != DSC_trailing;
  3591. bool AllowFixedUnderlyingType = AllowDeclaration &&
  3592. (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt ||
  3593. getLangOpts().ObjC2);
  3594. CXXScopeSpec &SS = DS.getTypeSpecScope();
  3595. if (getLangOpts().CPlusPlus) {
  3596. // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
  3597. // if a fixed underlying type is allowed.
  3598. ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
  3599. CXXScopeSpec Spec;
  3600. if (ParseOptionalCXXScopeSpecifier(Spec, nullptr,
  3601. /*EnteringContext=*/true))
  3602. return;
  3603. if (Spec.isSet() && Tok.isNot(tok::identifier)) {
  3604. Diag(Tok, diag::err_expected) << tok::identifier;
  3605. if (Tok.isNot(tok::l_brace)) {
  3606. // Has no name and is not a definition.
  3607. // Skip the rest of this declarator, up until the comma or semicolon.
  3608. SkipUntil(tok::comma, StopAtSemi);
  3609. return;
  3610. }
  3611. }
  3612. SS = Spec;
  3613. }
  3614. // Must have either 'enum name' or 'enum {...}'.
  3615. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
  3616. !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
  3617. Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
  3618. // Skip the rest of this declarator, up until the comma or semicolon.
  3619. SkipUntil(tok::comma, StopAtSemi);
  3620. return;
  3621. }
  3622. // If an identifier is present, consume and remember it.
  3623. IdentifierInfo *Name = nullptr;
  3624. SourceLocation NameLoc;
  3625. if (Tok.is(tok::identifier)) {
  3626. Name = Tok.getIdentifierInfo();
  3627. NameLoc = ConsumeToken();
  3628. }
  3629. if (!Name && ScopedEnumKWLoc.isValid()) {
  3630. // C++0x 7.2p2: The optional identifier shall not be omitted in the
  3631. // declaration of a scoped enumeration.
  3632. Diag(Tok, diag::err_scoped_enum_missing_identifier);
  3633. ScopedEnumKWLoc = SourceLocation();
  3634. IsScopedUsingClassTag = false;
  3635. }
  3636. // Okay, end the suppression area. We'll decide whether to emit the
  3637. // diagnostics in a second.
  3638. if (shouldDelayDiagsInTag)
  3639. diagsFromTag.done();
  3640. TypeResult BaseType;
  3641. // Parse the fixed underlying type.
  3642. bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
  3643. if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
  3644. bool PossibleBitfield = false;
  3645. if (CanBeBitfield) {
  3646. // If we're in class scope, this can either be an enum declaration with
  3647. // an underlying type, or a declaration of a bitfield member. We try to
  3648. // use a simple disambiguation scheme first to catch the common cases
  3649. // (integer literal, sizeof); if it's still ambiguous, we then consider
  3650. // anything that's a simple-type-specifier followed by '(' as an
  3651. // expression. This suffices because function types are not valid
  3652. // underlying types anyway.
  3653. EnterExpressionEvaluationContext Unevaluated(
  3654. Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  3655. TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
  3656. // If the next token starts an expression, we know we're parsing a
  3657. // bit-field. This is the common case.
  3658. if (TPR == TPResult::True)
  3659. PossibleBitfield = true;
  3660. // If the next token starts a type-specifier-seq, it may be either a
  3661. // a fixed underlying type or the start of a function-style cast in C++;
  3662. // lookahead one more token to see if it's obvious that we have a
  3663. // fixed underlying type.
  3664. else if (TPR == TPResult::False &&
  3665. GetLookAheadToken(2).getKind() == tok::semi) {
  3666. // Consume the ':'.
  3667. ConsumeToken();
  3668. } else {
  3669. // We have the start of a type-specifier-seq, so we have to perform
  3670. // tentative parsing to determine whether we have an expression or a
  3671. // type.
  3672. TentativeParsingAction TPA(*this);
  3673. // Consume the ':'.
  3674. ConsumeToken();
  3675. // If we see a type specifier followed by an open-brace, we have an
  3676. // ambiguity between an underlying type and a C++11 braced
  3677. // function-style cast. Resolve this by always treating it as an
  3678. // underlying type.
  3679. // FIXME: The standard is not entirely clear on how to disambiguate in
  3680. // this case.
  3681. if ((getLangOpts().CPlusPlus &&
  3682. isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) ||
  3683. (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
  3684. // We'll parse this as a bitfield later.
  3685. PossibleBitfield = true;
  3686. TPA.Revert();
  3687. } else {
  3688. // We have a type-specifier-seq.
  3689. TPA.Commit();
  3690. }
  3691. }
  3692. } else {
  3693. // Consume the ':'.
  3694. ConsumeToken();
  3695. }
  3696. if (!PossibleBitfield) {
  3697. SourceRange Range;
  3698. BaseType = ParseTypeName(&Range);
  3699. if (getLangOpts().CPlusPlus11) {
  3700. Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
  3701. } else if (!getLangOpts().ObjC2) {
  3702. if (getLangOpts().CPlusPlus)
  3703. Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range;
  3704. else
  3705. Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range;
  3706. }
  3707. }
  3708. }
  3709. // There are four options here. If we have 'friend enum foo;' then this is a
  3710. // friend declaration, and cannot have an accompanying definition. If we have
  3711. // 'enum foo;', then this is a forward declaration. If we have
  3712. // 'enum foo {...' then this is a definition. Otherwise we have something
  3713. // like 'enum foo xyz', a reference.
  3714. //
  3715. // This is needed to handle stuff like this right (C99 6.7.2.3p11):
  3716. // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
  3717. // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
  3718. //
  3719. Sema::TagUseKind TUK;
  3720. if (!AllowDeclaration) {
  3721. TUK = Sema::TUK_Reference;
  3722. } else if (Tok.is(tok::l_brace)) {
  3723. if (DS.isFriendSpecified()) {
  3724. Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
  3725. << SourceRange(DS.getFriendSpecLoc());
  3726. ConsumeBrace();
  3727. SkipUntil(tok::r_brace, StopAtSemi);
  3728. TUK = Sema::TUK_Friend;
  3729. } else {
  3730. TUK = Sema::TUK_Definition;
  3731. }
  3732. } else if (!isTypeSpecifier(DSC) &&
  3733. (Tok.is(tok::semi) ||
  3734. (Tok.isAtStartOfLine() &&
  3735. !isValidAfterTypeSpecifier(CanBeBitfield)))) {
  3736. TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
  3737. if (Tok.isNot(tok::semi)) {
  3738. // A semicolon was missing after this declaration. Diagnose and recover.
  3739. ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
  3740. PP.EnterToken(Tok);
  3741. Tok.setKind(tok::semi);
  3742. }
  3743. } else {
  3744. TUK = Sema::TUK_Reference;
  3745. }
  3746. // If this is an elaborated type specifier, and we delayed
  3747. // diagnostics before, just merge them into the current pool.
  3748. if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
  3749. diagsFromTag.redelay();
  3750. }
  3751. MultiTemplateParamsArg TParams;
  3752. if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
  3753. TUK != Sema::TUK_Reference) {
  3754. if (!getLangOpts().CPlusPlus11 || !SS.isSet()) {
  3755. // Skip the rest of this declarator, up until the comma or semicolon.
  3756. Diag(Tok, diag::err_enum_template);
  3757. SkipUntil(tok::comma, StopAtSemi);
  3758. return;
  3759. }
  3760. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  3761. // Enumerations can't be explicitly instantiated.
  3762. DS.SetTypeSpecError();
  3763. Diag(StartLoc, diag::err_explicit_instantiation_enum);
  3764. return;
  3765. }
  3766. assert(TemplateInfo.TemplateParams && "no template parameters");
  3767. TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
  3768. TemplateInfo.TemplateParams->size());
  3769. }
  3770. if (TUK == Sema::TUK_Reference)
  3771. ProhibitAttributes(attrs);
  3772. if (!Name && TUK != Sema::TUK_Definition) {
  3773. Diag(Tok, diag::err_enumerator_unnamed_no_def);
  3774. // Skip the rest of this declarator, up until the comma or semicolon.
  3775. SkipUntil(tok::comma, StopAtSemi);
  3776. return;
  3777. }
  3778. stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
  3779. Sema::SkipBodyInfo SkipBody;
  3780. if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) &&
  3781. NextToken().is(tok::identifier))
  3782. SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(),
  3783. NextToken().getIdentifierInfo(),
  3784. NextToken().getLocation());
  3785. bool Owned = false;
  3786. bool IsDependent = false;
  3787. const char *PrevSpec = nullptr;
  3788. unsigned DiagID;
  3789. Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
  3790. StartLoc, SS, Name, NameLoc, attrs.getList(),
  3791. AS, DS.getModulePrivateSpecLoc(), TParams,
  3792. Owned, IsDependent, ScopedEnumKWLoc,
  3793. IsScopedUsingClassTag, BaseType,
  3794. DSC == DSC_type_specifier,
  3795. DSC == DSC_template_param ||
  3796. DSC == DSC_template_type_arg, &SkipBody);
  3797. if (SkipBody.ShouldSkip) {
  3798. assert(TUK == Sema::TUK_Definition && "can only skip a definition");
  3799. BalancedDelimiterTracker T(*this, tok::l_brace);
  3800. T.consumeOpen();
  3801. T.skipToEnd();
  3802. if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
  3803. NameLoc.isValid() ? NameLoc : StartLoc,
  3804. PrevSpec, DiagID, TagDecl, Owned,
  3805. Actions.getASTContext().getPrintingPolicy()))
  3806. Diag(StartLoc, DiagID) << PrevSpec;
  3807. return;
  3808. }
  3809. if (IsDependent) {
  3810. // This enum has a dependent nested-name-specifier. Handle it as a
  3811. // dependent tag.
  3812. if (!Name) {
  3813. DS.SetTypeSpecError();
  3814. Diag(Tok, diag::err_expected_type_name_after_typename);
  3815. return;
  3816. }
  3817. TypeResult Type = Actions.ActOnDependentTag(
  3818. getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc);
  3819. if (Type.isInvalid()) {
  3820. DS.SetTypeSpecError();
  3821. return;
  3822. }
  3823. if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
  3824. NameLoc.isValid() ? NameLoc : StartLoc,
  3825. PrevSpec, DiagID, Type.get(),
  3826. Actions.getASTContext().getPrintingPolicy()))
  3827. Diag(StartLoc, DiagID) << PrevSpec;
  3828. return;
  3829. }
  3830. if (!TagDecl) {
  3831. // The action failed to produce an enumeration tag. If this is a
  3832. // definition, consume the entire definition.
  3833. if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
  3834. ConsumeBrace();
  3835. SkipUntil(tok::r_brace, StopAtSemi);
  3836. }
  3837. DS.SetTypeSpecError();
  3838. return;
  3839. }
  3840. if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
  3841. Decl *D = SkipBody.CheckSameAsPrevious ? SkipBody.New : TagDecl;
  3842. ParseEnumBody(StartLoc, D);
  3843. if (SkipBody.CheckSameAsPrevious &&
  3844. !Actions.ActOnDuplicateDefinition(DS, TagDecl, SkipBody)) {
  3845. DS.SetTypeSpecError();
  3846. return;
  3847. }
  3848. }
  3849. if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
  3850. NameLoc.isValid() ? NameLoc : StartLoc,
  3851. PrevSpec, DiagID, TagDecl, Owned,
  3852. Actions.getASTContext().getPrintingPolicy()))
  3853. Diag(StartLoc, DiagID) << PrevSpec;
  3854. }
  3855. /// ParseEnumBody - Parse a {} enclosed enumerator-list.
  3856. /// enumerator-list:
  3857. /// enumerator
  3858. /// enumerator-list ',' enumerator
  3859. /// enumerator:
  3860. /// enumeration-constant attributes[opt]
  3861. /// enumeration-constant attributes[opt] '=' constant-expression
  3862. /// enumeration-constant:
  3863. /// identifier
  3864. ///
  3865. void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
  3866. // Enter the scope of the enum body and start the definition.
  3867. ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope);
  3868. Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
  3869. BalancedDelimiterTracker T(*this, tok::l_brace);
  3870. T.consumeOpen();
  3871. // C does not allow an empty enumerator-list, C++ does [dcl.enum].
  3872. if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
  3873. Diag(Tok, diag::err_empty_enum);
  3874. SmallVector<Decl *, 32> EnumConstantDecls;
  3875. SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags;
  3876. Decl *LastEnumConstDecl = nullptr;
  3877. // Parse the enumerator-list.
  3878. while (Tok.isNot(tok::r_brace)) {
  3879. // Parse enumerator. If failed, try skipping till the start of the next
  3880. // enumerator definition.
  3881. if (Tok.isNot(tok::identifier)) {
  3882. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  3883. if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) &&
  3884. TryConsumeToken(tok::comma))
  3885. continue;
  3886. break;
  3887. }
  3888. IdentifierInfo *Ident = Tok.getIdentifierInfo();
  3889. SourceLocation IdentLoc = ConsumeToken();
  3890. // If attributes exist after the enumerator, parse them.
  3891. ParsedAttributesWithRange attrs(AttrFactory);
  3892. MaybeParseGNUAttributes(attrs);
  3893. ProhibitAttributes(attrs); // GNU-style attributes are prohibited.
  3894. if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
  3895. if (!getLangOpts().CPlusPlus1z)
  3896. Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute)
  3897. << 1 /*enumerator*/;
  3898. ParseCXX11Attributes(attrs);
  3899. }
  3900. SourceLocation EqualLoc;
  3901. ExprResult AssignedVal;
  3902. EnumAvailabilityDiags.emplace_back(*this);
  3903. if (TryConsumeToken(tok::equal, EqualLoc)) {
  3904. AssignedVal = ParseConstantExpression();
  3905. if (AssignedVal.isInvalid())
  3906. SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch);
  3907. }
  3908. // Install the enumerator constant into EnumDecl.
  3909. Decl *EnumConstDecl = Actions.ActOnEnumConstant(
  3910. getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident,
  3911. attrs.getList(), EqualLoc, AssignedVal.get());
  3912. EnumAvailabilityDiags.back().done();
  3913. EnumConstantDecls.push_back(EnumConstDecl);
  3914. LastEnumConstDecl = EnumConstDecl;
  3915. if (Tok.is(tok::identifier)) {
  3916. // We're missing a comma between enumerators.
  3917. SourceLocation Loc = getEndOfPreviousToken();
  3918. Diag(Loc, diag::err_enumerator_list_missing_comma)
  3919. << FixItHint::CreateInsertion(Loc, ", ");
  3920. continue;
  3921. }
  3922. // Emumerator definition must be finished, only comma or r_brace are
  3923. // allowed here.
  3924. SourceLocation CommaLoc;
  3925. if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) {
  3926. if (EqualLoc.isValid())
  3927. Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace
  3928. << tok::comma;
  3929. else
  3930. Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator);
  3931. if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) {
  3932. if (TryConsumeToken(tok::comma, CommaLoc))
  3933. continue;
  3934. } else {
  3935. break;
  3936. }
  3937. }
  3938. // If comma is followed by r_brace, emit appropriate warning.
  3939. if (Tok.is(tok::r_brace) && CommaLoc.isValid()) {
  3940. if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11)
  3941. Diag(CommaLoc, getLangOpts().CPlusPlus ?
  3942. diag::ext_enumerator_list_comma_cxx :
  3943. diag::ext_enumerator_list_comma_c)
  3944. << FixItHint::CreateRemoval(CommaLoc);
  3945. else if (getLangOpts().CPlusPlus11)
  3946. Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
  3947. << FixItHint::CreateRemoval(CommaLoc);
  3948. break;
  3949. }
  3950. }
  3951. // Eat the }.
  3952. T.consumeClose();
  3953. // If attributes exist after the identifier list, parse them.
  3954. ParsedAttributes attrs(AttrFactory);
  3955. MaybeParseGNUAttributes(attrs);
  3956. Actions.ActOnEnumBody(StartLoc, T.getRange(),
  3957. EnumDecl, EnumConstantDecls,
  3958. getCurScope(),
  3959. attrs.getList());
  3960. // Now handle enum constant availability diagnostics.
  3961. assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size());
  3962. for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) {
  3963. ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
  3964. EnumAvailabilityDiags[i].redelay();
  3965. PD.complete(EnumConstantDecls[i]);
  3966. }
  3967. EnumScope.Exit();
  3968. Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getRange());
  3969. // The next token must be valid after an enum definition. If not, a ';'
  3970. // was probably forgotten.
  3971. bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
  3972. if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
  3973. ExpectAndConsume(tok::semi, diag::err_expected_after, "enum");
  3974. // Push this token back into the preprocessor and change our current token
  3975. // to ';' so that the rest of the code recovers as though there were an
  3976. // ';' after the definition.
  3977. PP.EnterToken(Tok);
  3978. Tok.setKind(tok::semi);
  3979. }
  3980. }
  3981. /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
  3982. /// is definitely a type-specifier. Return false if it isn't part of a type
  3983. /// specifier or if we're not sure.
  3984. bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
  3985. switch (Tok.getKind()) {
  3986. default: return false;
  3987. // type-specifiers
  3988. case tok::kw_short:
  3989. case tok::kw_long:
  3990. case tok::kw___int64:
  3991. case tok::kw___int128:
  3992. case tok::kw_signed:
  3993. case tok::kw_unsigned:
  3994. case tok::kw__Complex:
  3995. case tok::kw__Imaginary:
  3996. case tok::kw_void:
  3997. case tok::kw_char:
  3998. case tok::kw_wchar_t:
  3999. case tok::kw_char16_t:
  4000. case tok::kw_char32_t:
  4001. case tok::kw_int:
  4002. case tok::kw_half:
  4003. case tok::kw_float:
  4004. case tok::kw_double:
  4005. case tok::kw__Float16:
  4006. case tok::kw___float128:
  4007. case tok::kw_bool:
  4008. case tok::kw__Bool:
  4009. case tok::kw__Decimal32:
  4010. case tok::kw__Decimal64:
  4011. case tok::kw__Decimal128:
  4012. case tok::kw___vector:
  4013. #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
  4014. #include "clang/Basic/OpenCLImageTypes.def"
  4015. // struct-or-union-specifier (C99) or class-specifier (C++)
  4016. case tok::kw_class:
  4017. case tok::kw_struct:
  4018. case tok::kw___interface:
  4019. case tok::kw_union:
  4020. // enum-specifier
  4021. case tok::kw_enum:
  4022. // typedef-name
  4023. case tok::annot_typename:
  4024. return true;
  4025. }
  4026. }
  4027. /// isTypeSpecifierQualifier - Return true if the current token could be the
  4028. /// start of a specifier-qualifier-list.
  4029. bool Parser::isTypeSpecifierQualifier() {
  4030. switch (Tok.getKind()) {
  4031. default: return false;
  4032. case tok::identifier: // foo::bar
  4033. if (TryAltiVecVectorToken())
  4034. return true;
  4035. // Fall through.
  4036. case tok::kw_typename: // typename T::type
  4037. // Annotate typenames and C++ scope specifiers. If we get one, just
  4038. // recurse to handle whatever we get.
  4039. if (TryAnnotateTypeOrScopeToken())
  4040. return true;
  4041. if (Tok.is(tok::identifier))
  4042. return false;
  4043. return isTypeSpecifierQualifier();
  4044. case tok::coloncolon: // ::foo::bar
  4045. if (NextToken().is(tok::kw_new) || // ::new
  4046. NextToken().is(tok::kw_delete)) // ::delete
  4047. return false;
  4048. if (TryAnnotateTypeOrScopeToken())
  4049. return true;
  4050. return isTypeSpecifierQualifier();
  4051. // GNU attributes support.
  4052. case tok::kw___attribute:
  4053. // GNU typeof support.
  4054. case tok::kw_typeof:
  4055. // type-specifiers
  4056. case tok::kw_short:
  4057. case tok::kw_long:
  4058. case tok::kw___int64:
  4059. case tok::kw___int128:
  4060. case tok::kw_signed:
  4061. case tok::kw_unsigned:
  4062. case tok::kw__Complex:
  4063. case tok::kw__Imaginary:
  4064. case tok::kw_void:
  4065. case tok::kw_char:
  4066. case tok::kw_wchar_t:
  4067. case tok::kw_char16_t:
  4068. case tok::kw_char32_t:
  4069. case tok::kw_int:
  4070. case tok::kw_half:
  4071. case tok::kw_float:
  4072. case tok::kw_double:
  4073. case tok::kw__Float16:
  4074. case tok::kw___float128:
  4075. case tok::kw_bool:
  4076. case tok::kw__Bool:
  4077. case tok::kw__Decimal32:
  4078. case tok::kw__Decimal64:
  4079. case tok::kw__Decimal128:
  4080. case tok::kw___vector:
  4081. #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
  4082. #include "clang/Basic/OpenCLImageTypes.def"
  4083. // struct-or-union-specifier (C99) or class-specifier (C++)
  4084. case tok::kw_class:
  4085. case tok::kw_struct:
  4086. case tok::kw___interface:
  4087. case tok::kw_union:
  4088. // enum-specifier
  4089. case tok::kw_enum:
  4090. // type-qualifier
  4091. case tok::kw_const:
  4092. case tok::kw_volatile:
  4093. case tok::kw_restrict:
  4094. // Debugger support.
  4095. case tok::kw___unknown_anytype:
  4096. // typedef-name
  4097. case tok::annot_typename:
  4098. return true;
  4099. // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
  4100. case tok::less:
  4101. return getLangOpts().ObjC1;
  4102. case tok::kw___cdecl:
  4103. case tok::kw___stdcall:
  4104. case tok::kw___fastcall:
  4105. case tok::kw___thiscall:
  4106. case tok::kw___regcall:
  4107. case tok::kw___vectorcall:
  4108. case tok::kw___w64:
  4109. case tok::kw___ptr64:
  4110. case tok::kw___ptr32:
  4111. case tok::kw___pascal:
  4112. case tok::kw___unaligned:
  4113. case tok::kw__Nonnull:
  4114. case tok::kw__Nullable:
  4115. case tok::kw__Null_unspecified:
  4116. case tok::kw___kindof:
  4117. case tok::kw___private:
  4118. case tok::kw___local:
  4119. case tok::kw___global:
  4120. case tok::kw___constant:
  4121. case tok::kw___generic:
  4122. case tok::kw___read_only:
  4123. case tok::kw___read_write:
  4124. case tok::kw___write_only:
  4125. return true;
  4126. // C11 _Atomic
  4127. case tok::kw__Atomic:
  4128. return true;
  4129. }
  4130. }
  4131. /// isDeclarationSpecifier() - Return true if the current token is part of a
  4132. /// declaration specifier.
  4133. ///
  4134. /// \param DisambiguatingWithExpression True to indicate that the purpose of
  4135. /// this check is to disambiguate between an expression and a declaration.
  4136. bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
  4137. switch (Tok.getKind()) {
  4138. default: return false;
  4139. case tok::kw_pipe:
  4140. return getLangOpts().OpenCL && (getLangOpts().OpenCLVersion >= 200);
  4141. case tok::identifier: // foo::bar
  4142. // Unfortunate hack to support "Class.factoryMethod" notation.
  4143. if (getLangOpts().ObjC1 && NextToken().is(tok::period))
  4144. return false;
  4145. if (TryAltiVecVectorToken())
  4146. return true;
  4147. // Fall through.
  4148. case tok::kw_decltype: // decltype(T())::type
  4149. case tok::kw_typename: // typename T::type
  4150. // Annotate typenames and C++ scope specifiers. If we get one, just
  4151. // recurse to handle whatever we get.
  4152. if (TryAnnotateTypeOrScopeToken())
  4153. return true;
  4154. if (Tok.is(tok::identifier))
  4155. return false;
  4156. // If we're in Objective-C and we have an Objective-C class type followed
  4157. // by an identifier and then either ':' or ']', in a place where an
  4158. // expression is permitted, then this is probably a class message send
  4159. // missing the initial '['. In this case, we won't consider this to be
  4160. // the start of a declaration.
  4161. if (DisambiguatingWithExpression &&
  4162. isStartOfObjCClassMessageMissingOpenBracket())
  4163. return false;
  4164. return isDeclarationSpecifier();
  4165. case tok::coloncolon: // ::foo::bar
  4166. if (NextToken().is(tok::kw_new) || // ::new
  4167. NextToken().is(tok::kw_delete)) // ::delete
  4168. return false;
  4169. // Annotate typenames and C++ scope specifiers. If we get one, just
  4170. // recurse to handle whatever we get.
  4171. if (TryAnnotateTypeOrScopeToken())
  4172. return true;
  4173. return isDeclarationSpecifier();
  4174. // storage-class-specifier
  4175. case tok::kw_typedef:
  4176. case tok::kw_extern:
  4177. case tok::kw___private_extern__:
  4178. case tok::kw_static:
  4179. case tok::kw_auto:
  4180. case tok::kw___auto_type:
  4181. case tok::kw_register:
  4182. case tok::kw___thread:
  4183. case tok::kw_thread_local:
  4184. case tok::kw__Thread_local:
  4185. // Modules
  4186. case tok::kw___module_private__:
  4187. // Debugger support
  4188. case tok::kw___unknown_anytype:
  4189. // type-specifiers
  4190. case tok::kw_short:
  4191. case tok::kw_long:
  4192. case tok::kw___int64:
  4193. case tok::kw___int128:
  4194. case tok::kw_signed:
  4195. case tok::kw_unsigned:
  4196. case tok::kw__Complex:
  4197. case tok::kw__Imaginary:
  4198. case tok::kw_void:
  4199. case tok::kw_char:
  4200. case tok::kw_wchar_t:
  4201. case tok::kw_char16_t:
  4202. case tok::kw_char32_t:
  4203. case tok::kw_int:
  4204. case tok::kw_half:
  4205. case tok::kw_float:
  4206. case tok::kw_double:
  4207. case tok::kw__Float16:
  4208. case tok::kw___float128:
  4209. case tok::kw_bool:
  4210. case tok::kw__Bool:
  4211. case tok::kw__Decimal32:
  4212. case tok::kw__Decimal64:
  4213. case tok::kw__Decimal128:
  4214. case tok::kw___vector:
  4215. // struct-or-union-specifier (C99) or class-specifier (C++)
  4216. case tok::kw_class:
  4217. case tok::kw_struct:
  4218. case tok::kw_union:
  4219. case tok::kw___interface:
  4220. // enum-specifier
  4221. case tok::kw_enum:
  4222. // type-qualifier
  4223. case tok::kw_const:
  4224. case tok::kw_volatile:
  4225. case tok::kw_restrict:
  4226. // function-specifier
  4227. case tok::kw_inline:
  4228. case tok::kw_virtual:
  4229. case tok::kw_explicit:
  4230. case tok::kw__Noreturn:
  4231. // alignment-specifier
  4232. case tok::kw__Alignas:
  4233. // friend keyword.
  4234. case tok::kw_friend:
  4235. // static_assert-declaration
  4236. case tok::kw__Static_assert:
  4237. // GNU typeof support.
  4238. case tok::kw_typeof:
  4239. // GNU attributes.
  4240. case tok::kw___attribute:
  4241. // C++11 decltype and constexpr.
  4242. case tok::annot_decltype:
  4243. case tok::kw_constexpr:
  4244. // C++ Concepts TS - concept
  4245. case tok::kw_concept:
  4246. // C11 _Atomic
  4247. case tok::kw__Atomic:
  4248. return true;
  4249. // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
  4250. case tok::less:
  4251. return getLangOpts().ObjC1;
  4252. // typedef-name
  4253. case tok::annot_typename:
  4254. return !DisambiguatingWithExpression ||
  4255. !isStartOfObjCClassMessageMissingOpenBracket();
  4256. case tok::kw___declspec:
  4257. case tok::kw___cdecl:
  4258. case tok::kw___stdcall:
  4259. case tok::kw___fastcall:
  4260. case tok::kw___thiscall:
  4261. case tok::kw___regcall:
  4262. case tok::kw___vectorcall:
  4263. case tok::kw___w64:
  4264. case tok::kw___sptr:
  4265. case tok::kw___uptr:
  4266. case tok::kw___ptr64:
  4267. case tok::kw___ptr32:
  4268. case tok::kw___forceinline:
  4269. case tok::kw___pascal:
  4270. case tok::kw___unaligned:
  4271. case tok::kw__Nonnull:
  4272. case tok::kw__Nullable:
  4273. case tok::kw__Null_unspecified:
  4274. case tok::kw___kindof:
  4275. case tok::kw___private:
  4276. case tok::kw___local:
  4277. case tok::kw___global:
  4278. case tok::kw___constant:
  4279. case tok::kw___generic:
  4280. case tok::kw___read_only:
  4281. case tok::kw___read_write:
  4282. case tok::kw___write_only:
  4283. #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
  4284. #include "clang/Basic/OpenCLImageTypes.def"
  4285. return true;
  4286. }
  4287. }
  4288. bool Parser::isConstructorDeclarator(bool IsUnqualified, bool DeductionGuide) {
  4289. TentativeParsingAction TPA(*this);
  4290. // Parse the C++ scope specifier.
  4291. CXXScopeSpec SS;
  4292. if (ParseOptionalCXXScopeSpecifier(SS, nullptr,
  4293. /*EnteringContext=*/true)) {
  4294. TPA.Revert();
  4295. return false;
  4296. }
  4297. // Parse the constructor name.
  4298. if (Tok.is(tok::identifier)) {
  4299. // We already know that we have a constructor name; just consume
  4300. // the token.
  4301. ConsumeToken();
  4302. } else if (Tok.is(tok::annot_template_id)) {
  4303. ConsumeAnnotationToken();
  4304. } else {
  4305. TPA.Revert();
  4306. return false;
  4307. }
  4308. // There may be attributes here, appertaining to the constructor name or type
  4309. // we just stepped past.
  4310. SkipCXX11Attributes();
  4311. // Current class name must be followed by a left parenthesis.
  4312. if (Tok.isNot(tok::l_paren)) {
  4313. TPA.Revert();
  4314. return false;
  4315. }
  4316. ConsumeParen();
  4317. // A right parenthesis, or ellipsis followed by a right parenthesis signals
  4318. // that we have a constructor.
  4319. if (Tok.is(tok::r_paren) ||
  4320. (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
  4321. TPA.Revert();
  4322. return true;
  4323. }
  4324. // A C++11 attribute here signals that we have a constructor, and is an
  4325. // attribute on the first constructor parameter.
  4326. if (getLangOpts().CPlusPlus11 &&
  4327. isCXX11AttributeSpecifier(/*Disambiguate*/ false,
  4328. /*OuterMightBeMessageSend*/ true)) {
  4329. TPA.Revert();
  4330. return true;
  4331. }
  4332. // If we need to, enter the specified scope.
  4333. DeclaratorScopeObj DeclScopeObj(*this, SS);
  4334. if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
  4335. DeclScopeObj.EnterDeclaratorScope();
  4336. // Optionally skip Microsoft attributes.
  4337. ParsedAttributes Attrs(AttrFactory);
  4338. MaybeParseMicrosoftAttributes(Attrs);
  4339. // Check whether the next token(s) are part of a declaration
  4340. // specifier, in which case we have the start of a parameter and,
  4341. // therefore, we know that this is a constructor.
  4342. bool IsConstructor = false;
  4343. if (isDeclarationSpecifier())
  4344. IsConstructor = true;
  4345. else if (Tok.is(tok::identifier) ||
  4346. (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
  4347. // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
  4348. // This might be a parenthesized member name, but is more likely to
  4349. // be a constructor declaration with an invalid argument type. Keep
  4350. // looking.
  4351. if (Tok.is(tok::annot_cxxscope))
  4352. ConsumeAnnotationToken();
  4353. ConsumeToken();
  4354. // If this is not a constructor, we must be parsing a declarator,
  4355. // which must have one of the following syntactic forms (see the
  4356. // grammar extract at the start of ParseDirectDeclarator):
  4357. switch (Tok.getKind()) {
  4358. case tok::l_paren:
  4359. // C(X ( int));
  4360. case tok::l_square:
  4361. // C(X [ 5]);
  4362. // C(X [ [attribute]]);
  4363. case tok::coloncolon:
  4364. // C(X :: Y);
  4365. // C(X :: *p);
  4366. // Assume this isn't a constructor, rather than assuming it's a
  4367. // constructor with an unnamed parameter of an ill-formed type.
  4368. break;
  4369. case tok::r_paren:
  4370. // C(X )
  4371. // Skip past the right-paren and any following attributes to get to
  4372. // the function body or trailing-return-type.
  4373. ConsumeParen();
  4374. SkipCXX11Attributes();
  4375. if (DeductionGuide) {
  4376. // C(X) -> ... is a deduction guide.
  4377. IsConstructor = Tok.is(tok::arrow);
  4378. break;
  4379. }
  4380. if (Tok.is(tok::colon) || Tok.is(tok::kw_try)) {
  4381. // Assume these were meant to be constructors:
  4382. // C(X) : (the name of a bit-field cannot be parenthesized).
  4383. // C(X) try (this is otherwise ill-formed).
  4384. IsConstructor = true;
  4385. }
  4386. if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) {
  4387. // If we have a constructor name within the class definition,
  4388. // assume these were meant to be constructors:
  4389. // C(X) {
  4390. // C(X) ;
  4391. // ... because otherwise we would be declaring a non-static data
  4392. // member that is ill-formed because it's of the same type as its
  4393. // surrounding class.
  4394. //
  4395. // FIXME: We can actually do this whether or not the name is qualified,
  4396. // because if it is qualified in this context it must be being used as
  4397. // a constructor name.
  4398. // currently, so we're somewhat conservative here.
  4399. IsConstructor = IsUnqualified;
  4400. }
  4401. break;
  4402. default:
  4403. IsConstructor = true;
  4404. break;
  4405. }
  4406. }
  4407. TPA.Revert();
  4408. return IsConstructor;
  4409. }
  4410. /// ParseTypeQualifierListOpt
  4411. /// type-qualifier-list: [C99 6.7.5]
  4412. /// type-qualifier
  4413. /// [vendor] attributes
  4414. /// [ only if AttrReqs & AR_VendorAttributesParsed ]
  4415. /// type-qualifier-list type-qualifier
  4416. /// [vendor] type-qualifier-list attributes
  4417. /// [ only if AttrReqs & AR_VendorAttributesParsed ]
  4418. /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
  4419. /// [ only if AttReqs & AR_CXX11AttributesParsed ]
  4420. /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via
  4421. /// AttrRequirements bitmask values.
  4422. void Parser::ParseTypeQualifierListOpt(
  4423. DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed,
  4424. bool IdentifierRequired,
  4425. Optional<llvm::function_ref<void()>> CodeCompletionHandler) {
  4426. if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) &&
  4427. isCXX11AttributeSpecifier()) {
  4428. ParsedAttributesWithRange attrs(AttrFactory);
  4429. ParseCXX11Attributes(attrs);
  4430. DS.takeAttributesFrom(attrs);
  4431. }
  4432. SourceLocation EndLoc;
  4433. while (1) {
  4434. bool isInvalid = false;
  4435. const char *PrevSpec = nullptr;
  4436. unsigned DiagID = 0;
  4437. SourceLocation Loc = Tok.getLocation();
  4438. switch (Tok.getKind()) {
  4439. case tok::code_completion:
  4440. if (CodeCompletionHandler)
  4441. (*CodeCompletionHandler)();
  4442. else
  4443. Actions.CodeCompleteTypeQualifiers(DS);
  4444. return cutOffParsing();
  4445. case tok::kw_const:
  4446. isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
  4447. getLangOpts());
  4448. break;
  4449. case tok::kw_volatile:
  4450. isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
  4451. getLangOpts());
  4452. break;
  4453. case tok::kw_restrict:
  4454. isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
  4455. getLangOpts());
  4456. break;
  4457. case tok::kw__Atomic:
  4458. if (!AtomicAllowed)
  4459. goto DoneWithTypeQuals;
  4460. isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID,
  4461. getLangOpts());
  4462. break;
  4463. // OpenCL qualifiers:
  4464. case tok::kw___private:
  4465. case tok::kw___global:
  4466. case tok::kw___local:
  4467. case tok::kw___constant:
  4468. case tok::kw___generic:
  4469. case tok::kw___read_only:
  4470. case tok::kw___write_only:
  4471. case tok::kw___read_write:
  4472. ParseOpenCLQualifiers(DS.getAttributes());
  4473. break;
  4474. case tok::kw___unaligned:
  4475. isInvalid = DS.SetTypeQual(DeclSpec::TQ_unaligned, Loc, PrevSpec, DiagID,
  4476. getLangOpts());
  4477. break;
  4478. case tok::kw___uptr:
  4479. // GNU libc headers in C mode use '__uptr' as an identifer which conflicts
  4480. // with the MS modifier keyword.
  4481. if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus &&
  4482. IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) {
  4483. if (TryKeywordIdentFallback(false))
  4484. continue;
  4485. }
  4486. LLVM_FALLTHROUGH;
  4487. case tok::kw___sptr:
  4488. case tok::kw___w64:
  4489. case tok::kw___ptr64:
  4490. case tok::kw___ptr32:
  4491. case tok::kw___cdecl:
  4492. case tok::kw___stdcall:
  4493. case tok::kw___fastcall:
  4494. case tok::kw___thiscall:
  4495. case tok::kw___regcall:
  4496. case tok::kw___vectorcall:
  4497. if (AttrReqs & AR_DeclspecAttributesParsed) {
  4498. ParseMicrosoftTypeAttributes(DS.getAttributes());
  4499. continue;
  4500. }
  4501. goto DoneWithTypeQuals;
  4502. case tok::kw___pascal:
  4503. if (AttrReqs & AR_VendorAttributesParsed) {
  4504. ParseBorlandTypeAttributes(DS.getAttributes());
  4505. continue;
  4506. }
  4507. goto DoneWithTypeQuals;
  4508. // Nullability type specifiers.
  4509. case tok::kw__Nonnull:
  4510. case tok::kw__Nullable:
  4511. case tok::kw__Null_unspecified:
  4512. ParseNullabilityTypeSpecifiers(DS.getAttributes());
  4513. continue;
  4514. // Objective-C 'kindof' types.
  4515. case tok::kw___kindof:
  4516. DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc,
  4517. nullptr, 0, AttributeList::AS_Keyword);
  4518. (void)ConsumeToken();
  4519. continue;
  4520. case tok::kw___attribute:
  4521. if (AttrReqs & AR_GNUAttributesParsedAndRejected)
  4522. // When GNU attributes are expressly forbidden, diagnose their usage.
  4523. Diag(Tok, diag::err_attributes_not_allowed);
  4524. // Parse the attributes even if they are rejected to ensure that error
  4525. // recovery is graceful.
  4526. if (AttrReqs & AR_GNUAttributesParsed ||
  4527. AttrReqs & AR_GNUAttributesParsedAndRejected) {
  4528. ParseGNUAttributes(DS.getAttributes());
  4529. continue; // do *not* consume the next token!
  4530. }
  4531. // otherwise, FALL THROUGH!
  4532. LLVM_FALLTHROUGH;
  4533. default:
  4534. DoneWithTypeQuals:
  4535. // If this is not a type-qualifier token, we're done reading type
  4536. // qualifiers. First verify that DeclSpec's are consistent.
  4537. DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
  4538. if (EndLoc.isValid())
  4539. DS.SetRangeEnd(EndLoc);
  4540. return;
  4541. }
  4542. // If the specifier combination wasn't legal, issue a diagnostic.
  4543. if (isInvalid) {
  4544. assert(PrevSpec && "Method did not return previous specifier!");
  4545. Diag(Tok, DiagID) << PrevSpec;
  4546. }
  4547. EndLoc = ConsumeToken();
  4548. }
  4549. }
  4550. /// ParseDeclarator - Parse and verify a newly-initialized declarator.
  4551. ///
  4552. void Parser::ParseDeclarator(Declarator &D) {
  4553. /// This implements the 'declarator' production in the C grammar, then checks
  4554. /// for well-formedness and issues diagnostics.
  4555. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
  4556. }
  4557. static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang,
  4558. unsigned TheContext) {
  4559. if (Kind == tok::star || Kind == tok::caret)
  4560. return true;
  4561. if ((Kind == tok::kw_pipe) && Lang.OpenCL && (Lang.OpenCLVersion >= 200))
  4562. return true;
  4563. if (!Lang.CPlusPlus)
  4564. return false;
  4565. if (Kind == tok::amp)
  4566. return true;
  4567. // We parse rvalue refs in C++03, because otherwise the errors are scary.
  4568. // But we must not parse them in conversion-type-ids and new-type-ids, since
  4569. // those can be legitimately followed by a && operator.
  4570. // (The same thing can in theory happen after a trailing-return-type, but
  4571. // since those are a C++11 feature, there is no rejects-valid issue there.)
  4572. if (Kind == tok::ampamp)
  4573. return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext &&
  4574. TheContext != Declarator::CXXNewContext);
  4575. return false;
  4576. }
  4577. // Indicates whether the given declarator is a pipe declarator.
  4578. static bool isPipeDeclerator(const Declarator &D) {
  4579. const unsigned NumTypes = D.getNumTypeObjects();
  4580. for (unsigned Idx = 0; Idx != NumTypes; ++Idx)
  4581. if (DeclaratorChunk::Pipe == D.getTypeObject(Idx).Kind)
  4582. return true;
  4583. return false;
  4584. }
  4585. /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
  4586. /// is parsed by the function passed to it. Pass null, and the direct-declarator
  4587. /// isn't parsed at all, making this function effectively parse the C++
  4588. /// ptr-operator production.
  4589. ///
  4590. /// If the grammar of this construct is extended, matching changes must also be
  4591. /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
  4592. /// isConstructorDeclarator.
  4593. ///
  4594. /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
  4595. /// [C] pointer[opt] direct-declarator
  4596. /// [C++] direct-declarator
  4597. /// [C++] ptr-operator declarator
  4598. ///
  4599. /// pointer: [C99 6.7.5]
  4600. /// '*' type-qualifier-list[opt]
  4601. /// '*' type-qualifier-list[opt] pointer
  4602. ///
  4603. /// ptr-operator:
  4604. /// '*' cv-qualifier-seq[opt]
  4605. /// '&'
  4606. /// [C++0x] '&&'
  4607. /// [GNU] '&' restrict[opt] attributes[opt]
  4608. /// [GNU?] '&&' restrict[opt] attributes[opt]
  4609. /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
  4610. void Parser::ParseDeclaratorInternal(Declarator &D,
  4611. DirectDeclParseFunction DirectDeclParser) {
  4612. if (Diags.hasAllExtensionsSilenced())
  4613. D.setExtension();
  4614. // C++ member pointers start with a '::' or a nested-name.
  4615. // Member pointers get special handling, since there's no place for the
  4616. // scope spec in the generic path below.
  4617. if (getLangOpts().CPlusPlus &&
  4618. (Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) ||
  4619. (Tok.is(tok::identifier) &&
  4620. (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) ||
  4621. Tok.is(tok::annot_cxxscope))) {
  4622. bool EnteringContext = D.getContext() == Declarator::FileContext ||
  4623. D.getContext() == Declarator::MemberContext;
  4624. CXXScopeSpec SS;
  4625. ParseOptionalCXXScopeSpecifier(SS, nullptr, EnteringContext);
  4626. if (SS.isNotEmpty()) {
  4627. if (Tok.isNot(tok::star)) {
  4628. // The scope spec really belongs to the direct-declarator.
  4629. if (D.mayHaveIdentifier())
  4630. D.getCXXScopeSpec() = SS;
  4631. else
  4632. AnnotateScopeToken(SS, true);
  4633. if (DirectDeclParser)
  4634. (this->*DirectDeclParser)(D);
  4635. return;
  4636. }
  4637. SourceLocation Loc = ConsumeToken();
  4638. D.SetRangeEnd(Loc);
  4639. DeclSpec DS(AttrFactory);
  4640. ParseTypeQualifierListOpt(DS);
  4641. D.ExtendWithDeclSpec(DS);
  4642. // Recurse to parse whatever is left.
  4643. ParseDeclaratorInternal(D, DirectDeclParser);
  4644. // Sema will have to catch (syntactically invalid) pointers into global
  4645. // scope. It has to catch pointers into namespace scope anyway.
  4646. D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
  4647. DS.getLocEnd()),
  4648. DS.getAttributes(),
  4649. /* Don't replace range end. */SourceLocation());
  4650. return;
  4651. }
  4652. }
  4653. tok::TokenKind Kind = Tok.getKind();
  4654. if (D.getDeclSpec().isTypeSpecPipe() && !isPipeDeclerator(D)) {
  4655. DeclSpec DS(AttrFactory);
  4656. ParseTypeQualifierListOpt(DS);
  4657. D.AddTypeInfo(
  4658. DeclaratorChunk::getPipe(DS.getTypeQualifiers(), DS.getPipeLoc()),
  4659. DS.getAttributes(), SourceLocation());
  4660. }
  4661. // Not a pointer, C++ reference, or block.
  4662. if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) {
  4663. if (DirectDeclParser)
  4664. (this->*DirectDeclParser)(D);
  4665. return;
  4666. }
  4667. // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
  4668. // '&&' -> rvalue reference
  4669. SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
  4670. D.SetRangeEnd(Loc);
  4671. if (Kind == tok::star || Kind == tok::caret) {
  4672. // Is a pointer.
  4673. DeclSpec DS(AttrFactory);
  4674. // GNU attributes are not allowed here in a new-type-id, but Declspec and
  4675. // C++11 attributes are allowed.
  4676. unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed |
  4677. ((D.getContext() != Declarator::CXXNewContext)
  4678. ? AR_GNUAttributesParsed
  4679. : AR_GNUAttributesParsedAndRejected);
  4680. ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier());
  4681. D.ExtendWithDeclSpec(DS);
  4682. // Recursively parse the declarator.
  4683. ParseDeclaratorInternal(D, DirectDeclParser);
  4684. if (Kind == tok::star)
  4685. // Remember that we parsed a pointer type, and remember the type-quals.
  4686. D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
  4687. DS.getConstSpecLoc(),
  4688. DS.getVolatileSpecLoc(),
  4689. DS.getRestrictSpecLoc(),
  4690. DS.getAtomicSpecLoc(),
  4691. DS.getUnalignedSpecLoc()),
  4692. DS.getAttributes(),
  4693. SourceLocation());
  4694. else
  4695. // Remember that we parsed a Block type, and remember the type-quals.
  4696. D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
  4697. Loc),
  4698. DS.getAttributes(),
  4699. SourceLocation());
  4700. } else {
  4701. // Is a reference
  4702. DeclSpec DS(AttrFactory);
  4703. // Complain about rvalue references in C++03, but then go on and build
  4704. // the declarator.
  4705. if (Kind == tok::ampamp)
  4706. Diag(Loc, getLangOpts().CPlusPlus11 ?
  4707. diag::warn_cxx98_compat_rvalue_reference :
  4708. diag::ext_rvalue_reference);
  4709. // GNU-style and C++11 attributes are allowed here, as is restrict.
  4710. ParseTypeQualifierListOpt(DS);
  4711. D.ExtendWithDeclSpec(DS);
  4712. // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
  4713. // cv-qualifiers are introduced through the use of a typedef or of a
  4714. // template type argument, in which case the cv-qualifiers are ignored.
  4715. if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
  4716. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4717. Diag(DS.getConstSpecLoc(),
  4718. diag::err_invalid_reference_qualifier_application) << "const";
  4719. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4720. Diag(DS.getVolatileSpecLoc(),
  4721. diag::err_invalid_reference_qualifier_application) << "volatile";
  4722. // 'restrict' is permitted as an extension.
  4723. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4724. Diag(DS.getAtomicSpecLoc(),
  4725. diag::err_invalid_reference_qualifier_application) << "_Atomic";
  4726. }
  4727. // Recursively parse the declarator.
  4728. ParseDeclaratorInternal(D, DirectDeclParser);
  4729. if (D.getNumTypeObjects() > 0) {
  4730. // C++ [dcl.ref]p4: There shall be no references to references.
  4731. DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
  4732. if (InnerChunk.Kind == DeclaratorChunk::Reference) {
  4733. if (const IdentifierInfo *II = D.getIdentifier())
  4734. Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
  4735. << II;
  4736. else
  4737. Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
  4738. << "type name";
  4739. // Once we've complained about the reference-to-reference, we
  4740. // can go ahead and build the (technically ill-formed)
  4741. // declarator: reference collapsing will take care of it.
  4742. }
  4743. }
  4744. // Remember that we parsed a reference type.
  4745. D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
  4746. Kind == tok::amp),
  4747. DS.getAttributes(),
  4748. SourceLocation());
  4749. }
  4750. }
  4751. // When correcting from misplaced brackets before the identifier, the location
  4752. // is saved inside the declarator so that other diagnostic messages can use
  4753. // them. This extracts and returns that location, or returns the provided
  4754. // location if a stored location does not exist.
  4755. static SourceLocation getMissingDeclaratorIdLoc(Declarator &D,
  4756. SourceLocation Loc) {
  4757. if (D.getName().StartLocation.isInvalid() &&
  4758. D.getName().EndLocation.isValid())
  4759. return D.getName().EndLocation;
  4760. return Loc;
  4761. }
  4762. /// ParseDirectDeclarator
  4763. /// direct-declarator: [C99 6.7.5]
  4764. /// [C99] identifier
  4765. /// '(' declarator ')'
  4766. /// [GNU] '(' attributes declarator ')'
  4767. /// [C90] direct-declarator '[' constant-expression[opt] ']'
  4768. /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
  4769. /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
  4770. /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
  4771. /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
  4772. /// [C++11] direct-declarator '[' constant-expression[opt] ']'
  4773. /// attribute-specifier-seq[opt]
  4774. /// direct-declarator '(' parameter-type-list ')'
  4775. /// direct-declarator '(' identifier-list[opt] ')'
  4776. /// [GNU] direct-declarator '(' parameter-forward-declarations
  4777. /// parameter-type-list[opt] ')'
  4778. /// [C++] direct-declarator '(' parameter-declaration-clause ')'
  4779. /// cv-qualifier-seq[opt] exception-specification[opt]
  4780. /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
  4781. /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
  4782. /// ref-qualifier[opt] exception-specification[opt]
  4783. /// [C++] declarator-id
  4784. /// [C++11] declarator-id attribute-specifier-seq[opt]
  4785. ///
  4786. /// declarator-id: [C++ 8]
  4787. /// '...'[opt] id-expression
  4788. /// '::'[opt] nested-name-specifier[opt] type-name
  4789. ///
  4790. /// id-expression: [C++ 5.1]
  4791. /// unqualified-id
  4792. /// qualified-id
  4793. ///
  4794. /// unqualified-id: [C++ 5.1]
  4795. /// identifier
  4796. /// operator-function-id
  4797. /// conversion-function-id
  4798. /// '~' class-name
  4799. /// template-id
  4800. ///
  4801. /// C++17 adds the following, which we also handle here:
  4802. ///
  4803. /// simple-declaration:
  4804. /// <decl-spec> '[' identifier-list ']' brace-or-equal-initializer ';'
  4805. ///
  4806. /// Note, any additional constructs added here may need corresponding changes
  4807. /// in isConstructorDeclarator.
  4808. void Parser::ParseDirectDeclarator(Declarator &D) {
  4809. DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
  4810. if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
  4811. // This might be a C++17 structured binding.
  4812. if (Tok.is(tok::l_square) && !D.mayOmitIdentifier() &&
  4813. D.getCXXScopeSpec().isEmpty())
  4814. return ParseDecompositionDeclarator(D);
  4815. // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in
  4816. // this context it is a bitfield. Also in range-based for statement colon
  4817. // may delimit for-range-declaration.
  4818. ColonProtectionRAIIObject X(*this,
  4819. D.getContext() == Declarator::MemberContext ||
  4820. (D.getContext() == Declarator::ForContext &&
  4821. getLangOpts().CPlusPlus11));
  4822. // ParseDeclaratorInternal might already have parsed the scope.
  4823. if (D.getCXXScopeSpec().isEmpty()) {
  4824. bool EnteringContext = D.getContext() == Declarator::FileContext ||
  4825. D.getContext() == Declarator::MemberContext;
  4826. ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), nullptr,
  4827. EnteringContext);
  4828. }
  4829. if (D.getCXXScopeSpec().isValid()) {
  4830. if (Actions.ShouldEnterDeclaratorScope(getCurScope(),
  4831. D.getCXXScopeSpec()))
  4832. // Change the declaration context for name lookup, until this function
  4833. // is exited (and the declarator has been parsed).
  4834. DeclScopeObj.EnterDeclaratorScope();
  4835. else if (getObjCDeclContext()) {
  4836. // Ensure that we don't interpret the next token as an identifier when
  4837. // dealing with declarations in an Objective-C container.
  4838. D.SetIdentifier(nullptr, Tok.getLocation());
  4839. D.setInvalidType(true);
  4840. ConsumeToken();
  4841. goto PastIdentifier;
  4842. }
  4843. }
  4844. // C++0x [dcl.fct]p14:
  4845. // There is a syntactic ambiguity when an ellipsis occurs at the end of a
  4846. // parameter-declaration-clause without a preceding comma. In this case,
  4847. // the ellipsis is parsed as part of the abstract-declarator if the type
  4848. // of the parameter either names a template parameter pack that has not
  4849. // been expanded or contains auto; otherwise, it is parsed as part of the
  4850. // parameter-declaration-clause.
  4851. if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
  4852. !((D.getContext() == Declarator::PrototypeContext ||
  4853. D.getContext() == Declarator::LambdaExprParameterContext ||
  4854. D.getContext() == Declarator::BlockLiteralContext) &&
  4855. NextToken().is(tok::r_paren) &&
  4856. !D.hasGroupingParens() &&
  4857. !Actions.containsUnexpandedParameterPacks(D) &&
  4858. D.getDeclSpec().getTypeSpecType() != TST_auto)) {
  4859. SourceLocation EllipsisLoc = ConsumeToken();
  4860. if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) {
  4861. // The ellipsis was put in the wrong place. Recover, and explain to
  4862. // the user what they should have done.
  4863. ParseDeclarator(D);
  4864. if (EllipsisLoc.isValid())
  4865. DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
  4866. return;
  4867. } else
  4868. D.setEllipsisLoc(EllipsisLoc);
  4869. // The ellipsis can't be followed by a parenthesized declarator. We
  4870. // check for that in ParseParenDeclarator, after we have disambiguated
  4871. // the l_paren token.
  4872. }
  4873. if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id,
  4874. tok::tilde)) {
  4875. // We found something that indicates the start of an unqualified-id.
  4876. // Parse that unqualified-id.
  4877. bool AllowConstructorName;
  4878. bool AllowDeductionGuide;
  4879. if (D.getDeclSpec().hasTypeSpecifier()) {
  4880. AllowConstructorName = false;
  4881. AllowDeductionGuide = false;
  4882. } else if (D.getCXXScopeSpec().isSet()) {
  4883. AllowConstructorName =
  4884. (D.getContext() == Declarator::FileContext ||
  4885. D.getContext() == Declarator::MemberContext);
  4886. AllowDeductionGuide = false;
  4887. } else {
  4888. AllowConstructorName = (D.getContext() == Declarator::MemberContext);
  4889. AllowDeductionGuide =
  4890. (D.getContext() == Declarator::FileContext ||
  4891. D.getContext() == Declarator::MemberContext);
  4892. }
  4893. SourceLocation TemplateKWLoc;
  4894. bool HadScope = D.getCXXScopeSpec().isValid();
  4895. if (ParseUnqualifiedId(D.getCXXScopeSpec(),
  4896. /*EnteringContext=*/true,
  4897. /*AllowDestructorName=*/true, AllowConstructorName,
  4898. AllowDeductionGuide, nullptr, TemplateKWLoc,
  4899. D.getName()) ||
  4900. // Once we're past the identifier, if the scope was bad, mark the
  4901. // whole declarator bad.
  4902. D.getCXXScopeSpec().isInvalid()) {
  4903. D.SetIdentifier(nullptr, Tok.getLocation());
  4904. D.setInvalidType(true);
  4905. } else {
  4906. // ParseUnqualifiedId might have parsed a scope specifier during error
  4907. // recovery. If it did so, enter that scope.
  4908. if (!HadScope && D.getCXXScopeSpec().isValid() &&
  4909. Actions.ShouldEnterDeclaratorScope(getCurScope(),
  4910. D.getCXXScopeSpec()))
  4911. DeclScopeObj.EnterDeclaratorScope();
  4912. // Parsed the unqualified-id; update range information and move along.
  4913. if (D.getSourceRange().getBegin().isInvalid())
  4914. D.SetRangeBegin(D.getName().getSourceRange().getBegin());
  4915. D.SetRangeEnd(D.getName().getSourceRange().getEnd());
  4916. }
  4917. goto PastIdentifier;
  4918. }
  4919. if (D.getCXXScopeSpec().isNotEmpty()) {
  4920. // We have a scope specifier but no following unqualified-id.
  4921. Diag(PP.getLocForEndOfToken(D.getCXXScopeSpec().getEndLoc()),
  4922. diag::err_expected_unqualified_id)
  4923. << /*C++*/1;
  4924. D.SetIdentifier(nullptr, Tok.getLocation());
  4925. goto PastIdentifier;
  4926. }
  4927. } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
  4928. assert(!getLangOpts().CPlusPlus &&
  4929. "There's a C++-specific check for tok::identifier above");
  4930. assert(Tok.getIdentifierInfo() && "Not an identifier?");
  4931. D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  4932. D.SetRangeEnd(Tok.getLocation());
  4933. ConsumeToken();
  4934. goto PastIdentifier;
  4935. } else if (Tok.is(tok::identifier) && !D.mayHaveIdentifier()) {
  4936. // We're not allowed an identifier here, but we got one. Try to figure out
  4937. // if the user was trying to attach a name to the type, or whether the name
  4938. // is some unrelated trailing syntax.
  4939. bool DiagnoseIdentifier = false;
  4940. if (D.hasGroupingParens())
  4941. // An identifier within parens is unlikely to be intended to be anything
  4942. // other than a name being "declared".
  4943. DiagnoseIdentifier = true;
  4944. else if (D.getContext() == Declarator::TemplateTypeArgContext)
  4945. // T<int N> is an accidental identifier; T<int N indicates a missing '>'.
  4946. DiagnoseIdentifier =
  4947. NextToken().isOneOf(tok::comma, tok::greater, tok::greatergreater);
  4948. else if (D.getContext() == Declarator::AliasDeclContext ||
  4949. D.getContext() == Declarator::AliasTemplateContext)
  4950. // The most likely error is that the ';' was forgotten.
  4951. DiagnoseIdentifier = NextToken().isOneOf(tok::comma, tok::semi);
  4952. else if (D.getContext() == Declarator::TrailingReturnContext &&
  4953. !isCXX11VirtSpecifier(Tok))
  4954. DiagnoseIdentifier = NextToken().isOneOf(
  4955. tok::comma, tok::semi, tok::equal, tok::l_brace, tok::kw_try);
  4956. if (DiagnoseIdentifier) {
  4957. Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id)
  4958. << FixItHint::CreateRemoval(Tok.getLocation());
  4959. D.SetIdentifier(nullptr, Tok.getLocation());
  4960. ConsumeToken();
  4961. goto PastIdentifier;
  4962. }
  4963. }
  4964. if (Tok.is(tok::l_paren)) {
  4965. // direct-declarator: '(' declarator ')'
  4966. // direct-declarator: '(' attributes declarator ')'
  4967. // Example: 'char (*X)' or 'int (*XX)(void)'
  4968. ParseParenDeclarator(D);
  4969. // If the declarator was parenthesized, we entered the declarator
  4970. // scope when parsing the parenthesized declarator, then exited
  4971. // the scope already. Re-enter the scope, if we need to.
  4972. if (D.getCXXScopeSpec().isSet()) {
  4973. // If there was an error parsing parenthesized declarator, declarator
  4974. // scope may have been entered before. Don't do it again.
  4975. if (!D.isInvalidType() &&
  4976. Actions.ShouldEnterDeclaratorScope(getCurScope(),
  4977. D.getCXXScopeSpec()))
  4978. // Change the declaration context for name lookup, until this function
  4979. // is exited (and the declarator has been parsed).
  4980. DeclScopeObj.EnterDeclaratorScope();
  4981. }
  4982. } else if (D.mayOmitIdentifier()) {
  4983. // This could be something simple like "int" (in which case the declarator
  4984. // portion is empty), if an abstract-declarator is allowed.
  4985. D.SetIdentifier(nullptr, Tok.getLocation());
  4986. // The grammar for abstract-pack-declarator does not allow grouping parens.
  4987. // FIXME: Revisit this once core issue 1488 is resolved.
  4988. if (D.hasEllipsis() && D.hasGroupingParens())
  4989. Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()),
  4990. diag::ext_abstract_pack_declarator_parens);
  4991. } else {
  4992. if (Tok.getKind() == tok::annot_pragma_parser_crash)
  4993. LLVM_BUILTIN_TRAP;
  4994. if (Tok.is(tok::l_square))
  4995. return ParseMisplacedBracketDeclarator(D);
  4996. if (D.getContext() == Declarator::MemberContext) {
  4997. // Objective-C++: Detect C++ keywords and try to prevent further errors by
  4998. // treating these keyword as valid member names.
  4999. if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus &&
  5000. Tok.getIdentifierInfo() &&
  5001. Tok.getIdentifierInfo()->isCPlusPlusKeyword(getLangOpts())) {
  5002. Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
  5003. diag::err_expected_member_name_or_semi_objcxx_keyword)
  5004. << Tok.getIdentifierInfo()
  5005. << (D.getDeclSpec().isEmpty() ? SourceRange()
  5006. : D.getDeclSpec().getSourceRange());
  5007. D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  5008. D.SetRangeEnd(Tok.getLocation());
  5009. ConsumeToken();
  5010. goto PastIdentifier;
  5011. }
  5012. Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
  5013. diag::err_expected_member_name_or_semi)
  5014. << (D.getDeclSpec().isEmpty() ? SourceRange()
  5015. : D.getDeclSpec().getSourceRange());
  5016. } else if (getLangOpts().CPlusPlus) {
  5017. if (Tok.isOneOf(tok::period, tok::arrow))
  5018. Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow);
  5019. else {
  5020. SourceLocation Loc = D.getCXXScopeSpec().getEndLoc();
  5021. if (Tok.isAtStartOfLine() && Loc.isValid())
  5022. Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id)
  5023. << getLangOpts().CPlusPlus;
  5024. else
  5025. Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
  5026. diag::err_expected_unqualified_id)
  5027. << getLangOpts().CPlusPlus;
  5028. }
  5029. } else {
  5030. Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()),
  5031. diag::err_expected_either)
  5032. << tok::identifier << tok::l_paren;
  5033. }
  5034. D.SetIdentifier(nullptr, Tok.getLocation());
  5035. D.setInvalidType(true);
  5036. }
  5037. PastIdentifier:
  5038. assert(D.isPastIdentifier() &&
  5039. "Haven't past the location of the identifier yet?");
  5040. // Don't parse attributes unless we have parsed an unparenthesized name.
  5041. if (D.hasName() && !D.getNumTypeObjects())
  5042. MaybeParseCXX11Attributes(D);
  5043. while (1) {
  5044. if (Tok.is(tok::l_paren)) {
  5045. // Enter function-declaration scope, limiting any declarators to the
  5046. // function prototype scope, including parameter declarators.
  5047. ParseScope PrototypeScope(this,
  5048. Scope::FunctionPrototypeScope|Scope::DeclScope|
  5049. (D.isFunctionDeclaratorAFunctionDeclaration()
  5050. ? Scope::FunctionDeclarationScope : 0));
  5051. // The paren may be part of a C++ direct initializer, eg. "int x(1);".
  5052. // In such a case, check if we actually have a function declarator; if it
  5053. // is not, the declarator has been fully parsed.
  5054. bool IsAmbiguous = false;
  5055. if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
  5056. // The name of the declarator, if any, is tentatively declared within
  5057. // a possible direct initializer.
  5058. TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
  5059. bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
  5060. TentativelyDeclaredIdentifiers.pop_back();
  5061. if (!IsFunctionDecl)
  5062. break;
  5063. }
  5064. ParsedAttributes attrs(AttrFactory);
  5065. BalancedDelimiterTracker T(*this, tok::l_paren);
  5066. T.consumeOpen();
  5067. ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
  5068. PrototypeScope.Exit();
  5069. } else if (Tok.is(tok::l_square)) {
  5070. ParseBracketDeclarator(D);
  5071. } else {
  5072. break;
  5073. }
  5074. }
  5075. }
  5076. void Parser::ParseDecompositionDeclarator(Declarator &D) {
  5077. assert(Tok.is(tok::l_square));
  5078. // If this doesn't look like a structured binding, maybe it's a misplaced
  5079. // array declarator.
  5080. // FIXME: Consume the l_square first so we don't need extra lookahead for
  5081. // this.
  5082. if (!(NextToken().is(tok::identifier) &&
  5083. GetLookAheadToken(2).isOneOf(tok::comma, tok::r_square)) &&
  5084. !(NextToken().is(tok::r_square) &&
  5085. GetLookAheadToken(2).isOneOf(tok::equal, tok::l_brace)))
  5086. return ParseMisplacedBracketDeclarator(D);
  5087. BalancedDelimiterTracker T(*this, tok::l_square);
  5088. T.consumeOpen();
  5089. SmallVector<DecompositionDeclarator::Binding, 32> Bindings;
  5090. while (Tok.isNot(tok::r_square)) {
  5091. if (!Bindings.empty()) {
  5092. if (Tok.is(tok::comma))
  5093. ConsumeToken();
  5094. else {
  5095. if (Tok.is(tok::identifier)) {
  5096. SourceLocation EndLoc = getEndOfPreviousToken();
  5097. Diag(EndLoc, diag::err_expected)
  5098. << tok::comma << FixItHint::CreateInsertion(EndLoc, ",");
  5099. } else {
  5100. Diag(Tok, diag::err_expected_comma_or_rsquare);
  5101. }
  5102. SkipUntil(tok::r_square, tok::comma, tok::identifier,
  5103. StopAtSemi | StopBeforeMatch);
  5104. if (Tok.is(tok::comma))
  5105. ConsumeToken();
  5106. else if (Tok.isNot(tok::identifier))
  5107. break;
  5108. }
  5109. }
  5110. if (Tok.isNot(tok::identifier)) {
  5111. Diag(Tok, diag::err_expected) << tok::identifier;
  5112. break;
  5113. }
  5114. Bindings.push_back({Tok.getIdentifierInfo(), Tok.getLocation()});
  5115. ConsumeToken();
  5116. }
  5117. if (Tok.isNot(tok::r_square))
  5118. // We've already diagnosed a problem here.
  5119. T.skipToEnd();
  5120. else {
  5121. // C++17 does not allow the identifier-list in a structured binding
  5122. // to be empty.
  5123. if (Bindings.empty())
  5124. Diag(Tok.getLocation(), diag::ext_decomp_decl_empty);
  5125. T.consumeClose();
  5126. }
  5127. return D.setDecompositionBindings(T.getOpenLocation(), Bindings,
  5128. T.getCloseLocation());
  5129. }
  5130. /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
  5131. /// only called before the identifier, so these are most likely just grouping
  5132. /// parens for precedence. If we find that these are actually function
  5133. /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
  5134. ///
  5135. /// direct-declarator:
  5136. /// '(' declarator ')'
  5137. /// [GNU] '(' attributes declarator ')'
  5138. /// direct-declarator '(' parameter-type-list ')'
  5139. /// direct-declarator '(' identifier-list[opt] ')'
  5140. /// [GNU] direct-declarator '(' parameter-forward-declarations
  5141. /// parameter-type-list[opt] ')'
  5142. ///
  5143. void Parser::ParseParenDeclarator(Declarator &D) {
  5144. BalancedDelimiterTracker T(*this, tok::l_paren);
  5145. T.consumeOpen();
  5146. assert(!D.isPastIdentifier() && "Should be called before passing identifier");
  5147. // Eat any attributes before we look at whether this is a grouping or function
  5148. // declarator paren. If this is a grouping paren, the attribute applies to
  5149. // the type being built up, for example:
  5150. // int (__attribute__(()) *x)(long y)
  5151. // If this ends up not being a grouping paren, the attribute applies to the
  5152. // first argument, for example:
  5153. // int (__attribute__(()) int x)
  5154. // In either case, we need to eat any attributes to be able to determine what
  5155. // sort of paren this is.
  5156. //
  5157. ParsedAttributes attrs(AttrFactory);
  5158. bool RequiresArg = false;
  5159. if (Tok.is(tok::kw___attribute)) {
  5160. ParseGNUAttributes(attrs);
  5161. // We require that the argument list (if this is a non-grouping paren) be
  5162. // present even if the attribute list was empty.
  5163. RequiresArg = true;
  5164. }
  5165. // Eat any Microsoft extensions.
  5166. ParseMicrosoftTypeAttributes(attrs);
  5167. // Eat any Borland extensions.
  5168. if (Tok.is(tok::kw___pascal))
  5169. ParseBorlandTypeAttributes(attrs);
  5170. // If we haven't past the identifier yet (or where the identifier would be
  5171. // stored, if this is an abstract declarator), then this is probably just
  5172. // grouping parens. However, if this could be an abstract-declarator, then
  5173. // this could also be the start of function arguments (consider 'void()').
  5174. bool isGrouping;
  5175. if (!D.mayOmitIdentifier()) {
  5176. // If this can't be an abstract-declarator, this *must* be a grouping
  5177. // paren, because we haven't seen the identifier yet.
  5178. isGrouping = true;
  5179. } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
  5180. (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
  5181. NextToken().is(tok::r_paren)) || // C++ int(...)
  5182. isDeclarationSpecifier() || // 'int(int)' is a function.
  5183. isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
  5184. // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
  5185. // considered to be a type, not a K&R identifier-list.
  5186. isGrouping = false;
  5187. } else {
  5188. // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
  5189. isGrouping = true;
  5190. }
  5191. // If this is a grouping paren, handle:
  5192. // direct-declarator: '(' declarator ')'
  5193. // direct-declarator: '(' attributes declarator ')'
  5194. if (isGrouping) {
  5195. SourceLocation EllipsisLoc = D.getEllipsisLoc();
  5196. D.setEllipsisLoc(SourceLocation());
  5197. bool hadGroupingParens = D.hasGroupingParens();
  5198. D.setGroupingParens(true);
  5199. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
  5200. // Match the ')'.
  5201. T.consumeClose();
  5202. D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
  5203. T.getCloseLocation()),
  5204. attrs, T.getCloseLocation());
  5205. D.setGroupingParens(hadGroupingParens);
  5206. // An ellipsis cannot be placed outside parentheses.
  5207. if (EllipsisLoc.isValid())
  5208. DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D);
  5209. return;
  5210. }
  5211. // Okay, if this wasn't a grouping paren, it must be the start of a function
  5212. // argument list. Recognize that this declarator will never have an
  5213. // identifier (and remember where it would have been), then call into
  5214. // ParseFunctionDeclarator to handle of argument list.
  5215. D.SetIdentifier(nullptr, Tok.getLocation());
  5216. // Enter function-declaration scope, limiting any declarators to the
  5217. // function prototype scope, including parameter declarators.
  5218. ParseScope PrototypeScope(this,
  5219. Scope::FunctionPrototypeScope | Scope::DeclScope |
  5220. (D.isFunctionDeclaratorAFunctionDeclaration()
  5221. ? Scope::FunctionDeclarationScope : 0));
  5222. ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
  5223. PrototypeScope.Exit();
  5224. }
  5225. /// ParseFunctionDeclarator - We are after the identifier and have parsed the
  5226. /// declarator D up to a paren, which indicates that we are parsing function
  5227. /// arguments.
  5228. ///
  5229. /// If FirstArgAttrs is non-null, then the caller parsed those arguments
  5230. /// immediately after the open paren - they should be considered to be the
  5231. /// first argument of a parameter.
  5232. ///
  5233. /// If RequiresArg is true, then the first argument of the function is required
  5234. /// to be present and required to not be an identifier list.
  5235. ///
  5236. /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
  5237. /// (C++11) ref-qualifier[opt], exception-specification[opt],
  5238. /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
  5239. ///
  5240. /// [C++11] exception-specification:
  5241. /// dynamic-exception-specification
  5242. /// noexcept-specification
  5243. ///
  5244. void Parser::ParseFunctionDeclarator(Declarator &D,
  5245. ParsedAttributes &FirstArgAttrs,
  5246. BalancedDelimiterTracker &Tracker,
  5247. bool IsAmbiguous,
  5248. bool RequiresArg) {
  5249. assert(getCurScope()->isFunctionPrototypeScope() &&
  5250. "Should call from a Function scope");
  5251. // lparen is already consumed!
  5252. assert(D.isPastIdentifier() && "Should not call before identifier!");
  5253. // This should be true when the function has typed arguments.
  5254. // Otherwise, it is treated as a K&R-style function.
  5255. bool HasProto = false;
  5256. // Build up an array of information about the parsed arguments.
  5257. SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
  5258. // Remember where we see an ellipsis, if any.
  5259. SourceLocation EllipsisLoc;
  5260. DeclSpec DS(AttrFactory);
  5261. bool RefQualifierIsLValueRef = true;
  5262. SourceLocation RefQualifierLoc;
  5263. SourceLocation ConstQualifierLoc;
  5264. SourceLocation VolatileQualifierLoc;
  5265. SourceLocation RestrictQualifierLoc;
  5266. ExceptionSpecificationType ESpecType = EST_None;
  5267. SourceRange ESpecRange;
  5268. SmallVector<ParsedType, 2> DynamicExceptions;
  5269. SmallVector<SourceRange, 2> DynamicExceptionRanges;
  5270. ExprResult NoexceptExpr;
  5271. CachedTokens *ExceptionSpecTokens = nullptr;
  5272. ParsedAttributes FnAttrs(AttrFactory);
  5273. TypeResult TrailingReturnType;
  5274. /* LocalEndLoc is the end location for the local FunctionTypeLoc.
  5275. EndLoc is the end location for the function declarator.
  5276. They differ for trailing return types. */
  5277. SourceLocation StartLoc, LocalEndLoc, EndLoc;
  5278. SourceLocation LParenLoc, RParenLoc;
  5279. LParenLoc = Tracker.getOpenLocation();
  5280. StartLoc = LParenLoc;
  5281. if (isFunctionDeclaratorIdentifierList()) {
  5282. if (RequiresArg)
  5283. Diag(Tok, diag::err_argument_required_after_attribute);
  5284. ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
  5285. Tracker.consumeClose();
  5286. RParenLoc = Tracker.getCloseLocation();
  5287. LocalEndLoc = RParenLoc;
  5288. EndLoc = RParenLoc;
  5289. } else {
  5290. if (Tok.isNot(tok::r_paren))
  5291. ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo,
  5292. EllipsisLoc);
  5293. else if (RequiresArg)
  5294. Diag(Tok, diag::err_argument_required_after_attribute);
  5295. HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
  5296. // If we have the closing ')', eat it.
  5297. Tracker.consumeClose();
  5298. RParenLoc = Tracker.getCloseLocation();
  5299. LocalEndLoc = RParenLoc;
  5300. EndLoc = RParenLoc;
  5301. if (getLangOpts().CPlusPlus) {
  5302. // FIXME: Accept these components in any order, and produce fixits to
  5303. // correct the order if the user gets it wrong. Ideally we should deal
  5304. // with the pure-specifier in the same way.
  5305. // Parse cv-qualifier-seq[opt].
  5306. ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed,
  5307. /*AtomicAllowed*/ false,
  5308. /*IdentifierRequired=*/false,
  5309. llvm::function_ref<void()>([&]() {
  5310. Actions.CodeCompleteFunctionQualifiers(DS, D);
  5311. }));
  5312. if (!DS.getSourceRange().getEnd().isInvalid()) {
  5313. EndLoc = DS.getSourceRange().getEnd();
  5314. ConstQualifierLoc = DS.getConstSpecLoc();
  5315. VolatileQualifierLoc = DS.getVolatileSpecLoc();
  5316. RestrictQualifierLoc = DS.getRestrictSpecLoc();
  5317. }
  5318. // Parse ref-qualifier[opt].
  5319. if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc))
  5320. EndLoc = RefQualifierLoc;
  5321. // C++11 [expr.prim.general]p3:
  5322. // If a declaration declares a member function or member function
  5323. // template of a class X, the expression this is a prvalue of type
  5324. // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
  5325. // and the end of the function-definition, member-declarator, or
  5326. // declarator.
  5327. // FIXME: currently, "static" case isn't handled correctly.
  5328. bool IsCXX11MemberFunction =
  5329. getLangOpts().CPlusPlus11 &&
  5330. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  5331. (D.getContext() == Declarator::MemberContext
  5332. ? !D.getDeclSpec().isFriendSpecified()
  5333. : D.getContext() == Declarator::FileContext &&
  5334. D.getCXXScopeSpec().isValid() &&
  5335. Actions.CurContext->isRecord());
  5336. Sema::CXXThisScopeRAII ThisScope(Actions,
  5337. dyn_cast<CXXRecordDecl>(Actions.CurContext),
  5338. DS.getTypeQualifiers() |
  5339. (D.getDeclSpec().isConstexprSpecified() &&
  5340. !getLangOpts().CPlusPlus14
  5341. ? Qualifiers::Const : 0),
  5342. IsCXX11MemberFunction);
  5343. // Parse exception-specification[opt].
  5344. bool Delayed = D.isFirstDeclarationOfMember() &&
  5345. D.isFunctionDeclaratorAFunctionDeclaration();
  5346. if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) &&
  5347. GetLookAheadToken(0).is(tok::kw_noexcept) &&
  5348. GetLookAheadToken(1).is(tok::l_paren) &&
  5349. GetLookAheadToken(2).is(tok::kw_noexcept) &&
  5350. GetLookAheadToken(3).is(tok::l_paren) &&
  5351. GetLookAheadToken(4).is(tok::identifier) &&
  5352. GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) {
  5353. // HACK: We've got an exception-specification
  5354. // noexcept(noexcept(swap(...)))
  5355. // or
  5356. // noexcept(noexcept(swap(...)) && noexcept(swap(...)))
  5357. // on a 'swap' member function. This is a libstdc++ bug; the lookup
  5358. // for 'swap' will only find the function we're currently declaring,
  5359. // whereas it expects to find a non-member swap through ADL. Turn off
  5360. // delayed parsing to give it a chance to find what it expects.
  5361. Delayed = false;
  5362. }
  5363. ESpecType = tryParseExceptionSpecification(Delayed,
  5364. ESpecRange,
  5365. DynamicExceptions,
  5366. DynamicExceptionRanges,
  5367. NoexceptExpr,
  5368. ExceptionSpecTokens);
  5369. if (ESpecType != EST_None)
  5370. EndLoc = ESpecRange.getEnd();
  5371. // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
  5372. // after the exception-specification.
  5373. MaybeParseCXX11Attributes(FnAttrs);
  5374. // Parse trailing-return-type[opt].
  5375. LocalEndLoc = EndLoc;
  5376. if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) {
  5377. Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
  5378. if (D.getDeclSpec().getTypeSpecType() == TST_auto)
  5379. StartLoc = D.getDeclSpec().getTypeSpecTypeLoc();
  5380. LocalEndLoc = Tok.getLocation();
  5381. SourceRange Range;
  5382. TrailingReturnType = ParseTrailingReturnType(Range);
  5383. EndLoc = Range.getEnd();
  5384. }
  5385. }
  5386. }
  5387. // Collect non-parameter declarations from the prototype if this is a function
  5388. // declaration. They will be moved into the scope of the function. Only do
  5389. // this in C and not C++, where the decls will continue to live in the
  5390. // surrounding context.
  5391. SmallVector<NamedDecl *, 0> DeclsInPrototype;
  5392. if (getCurScope()->getFlags() & Scope::FunctionDeclarationScope &&
  5393. !getLangOpts().CPlusPlus) {
  5394. for (Decl *D : getCurScope()->decls()) {
  5395. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  5396. if (!ND || isa<ParmVarDecl>(ND))
  5397. continue;
  5398. DeclsInPrototype.push_back(ND);
  5399. }
  5400. }
  5401. // Remember that we parsed a function type, and remember the attributes.
  5402. D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
  5403. IsAmbiguous,
  5404. LParenLoc,
  5405. ParamInfo.data(), ParamInfo.size(),
  5406. EllipsisLoc, RParenLoc,
  5407. DS.getTypeQualifiers(),
  5408. RefQualifierIsLValueRef,
  5409. RefQualifierLoc, ConstQualifierLoc,
  5410. VolatileQualifierLoc,
  5411. RestrictQualifierLoc,
  5412. /*MutableLoc=*/SourceLocation(),
  5413. ESpecType, ESpecRange,
  5414. DynamicExceptions.data(),
  5415. DynamicExceptionRanges.data(),
  5416. DynamicExceptions.size(),
  5417. NoexceptExpr.isUsable() ?
  5418. NoexceptExpr.get() : nullptr,
  5419. ExceptionSpecTokens,
  5420. DeclsInPrototype,
  5421. StartLoc, LocalEndLoc, D,
  5422. TrailingReturnType),
  5423. FnAttrs, EndLoc);
  5424. }
  5425. /// ParseRefQualifier - Parses a member function ref-qualifier. Returns
  5426. /// true if a ref-qualifier is found.
  5427. bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef,
  5428. SourceLocation &RefQualifierLoc) {
  5429. if (Tok.isOneOf(tok::amp, tok::ampamp)) {
  5430. Diag(Tok, getLangOpts().CPlusPlus11 ?
  5431. diag::warn_cxx98_compat_ref_qualifier :
  5432. diag::ext_ref_qualifier);
  5433. RefQualifierIsLValueRef = Tok.is(tok::amp);
  5434. RefQualifierLoc = ConsumeToken();
  5435. return true;
  5436. }
  5437. return false;
  5438. }
  5439. /// isFunctionDeclaratorIdentifierList - This parameter list may have an
  5440. /// identifier list form for a K&R-style function: void foo(a,b,c)
  5441. ///
  5442. /// Note that identifier-lists are only allowed for normal declarators, not for
  5443. /// abstract-declarators.
  5444. bool Parser::isFunctionDeclaratorIdentifierList() {
  5445. return !getLangOpts().CPlusPlus
  5446. && Tok.is(tok::identifier)
  5447. && !TryAltiVecVectorToken()
  5448. // K&R identifier lists can't have typedefs as identifiers, per C99
  5449. // 6.7.5.3p11.
  5450. && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
  5451. // Identifier lists follow a really simple grammar: the identifiers can
  5452. // be followed *only* by a ", identifier" or ")". However, K&R
  5453. // identifier lists are really rare in the brave new modern world, and
  5454. // it is very common for someone to typo a type in a non-K&R style
  5455. // list. If we are presented with something like: "void foo(intptr x,
  5456. // float y)", we don't want to start parsing the function declarator as
  5457. // though it is a K&R style declarator just because intptr is an
  5458. // invalid type.
  5459. //
  5460. // To handle this, we check to see if the token after the first
  5461. // identifier is a "," or ")". Only then do we parse it as an
  5462. // identifier list.
  5463. && (!Tok.is(tok::eof) &&
  5464. (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)));
  5465. }
  5466. /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
  5467. /// we found a K&R-style identifier list instead of a typed parameter list.
  5468. ///
  5469. /// After returning, ParamInfo will hold the parsed parameters.
  5470. ///
  5471. /// identifier-list: [C99 6.7.5]
  5472. /// identifier
  5473. /// identifier-list ',' identifier
  5474. ///
  5475. void Parser::ParseFunctionDeclaratorIdentifierList(
  5476. Declarator &D,
  5477. SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) {
  5478. // If there was no identifier specified for the declarator, either we are in
  5479. // an abstract-declarator, or we are in a parameter declarator which was found
  5480. // to be abstract. In abstract-declarators, identifier lists are not valid:
  5481. // diagnose this.
  5482. if (!D.getIdentifier())
  5483. Diag(Tok, diag::ext_ident_list_in_param);
  5484. // Maintain an efficient lookup of params we have seen so far.
  5485. llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
  5486. do {
  5487. // If this isn't an identifier, report the error and skip until ')'.
  5488. if (Tok.isNot(tok::identifier)) {
  5489. Diag(Tok, diag::err_expected) << tok::identifier;
  5490. SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
  5491. // Forget we parsed anything.
  5492. ParamInfo.clear();
  5493. return;
  5494. }
  5495. IdentifierInfo *ParmII = Tok.getIdentifierInfo();
  5496. // Reject 'typedef int y; int test(x, y)', but continue parsing.
  5497. if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
  5498. Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
  5499. // Verify that the argument identifier has not already been mentioned.
  5500. if (!ParamsSoFar.insert(ParmII).second) {
  5501. Diag(Tok, diag::err_param_redefinition) << ParmII;
  5502. } else {
  5503. // Remember this identifier in ParamInfo.
  5504. ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
  5505. Tok.getLocation(),
  5506. nullptr));
  5507. }
  5508. // Eat the identifier.
  5509. ConsumeToken();
  5510. // The list continues if we see a comma.
  5511. } while (TryConsumeToken(tok::comma));
  5512. }
  5513. /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
  5514. /// after the opening parenthesis. This function will not parse a K&R-style
  5515. /// identifier list.
  5516. ///
  5517. /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
  5518. /// caller parsed those arguments immediately after the open paren - they should
  5519. /// be considered to be part of the first parameter.
  5520. ///
  5521. /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
  5522. /// be the location of the ellipsis, if any was parsed.
  5523. ///
  5524. /// parameter-type-list: [C99 6.7.5]
  5525. /// parameter-list
  5526. /// parameter-list ',' '...'
  5527. /// [C++] parameter-list '...'
  5528. ///
  5529. /// parameter-list: [C99 6.7.5]
  5530. /// parameter-declaration
  5531. /// parameter-list ',' parameter-declaration
  5532. ///
  5533. /// parameter-declaration: [C99 6.7.5]
  5534. /// declaration-specifiers declarator
  5535. /// [C++] declaration-specifiers declarator '=' assignment-expression
  5536. /// [C++11] initializer-clause
  5537. /// [GNU] declaration-specifiers declarator attributes
  5538. /// declaration-specifiers abstract-declarator[opt]
  5539. /// [C++] declaration-specifiers abstract-declarator[opt]
  5540. /// '=' assignment-expression
  5541. /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
  5542. /// [C++11] attribute-specifier-seq parameter-declaration
  5543. ///
  5544. void Parser::ParseParameterDeclarationClause(
  5545. Declarator &D,
  5546. ParsedAttributes &FirstArgAttrs,
  5547. SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
  5548. SourceLocation &EllipsisLoc) {
  5549. do {
  5550. // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
  5551. // before deciding this was a parameter-declaration-clause.
  5552. if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
  5553. break;
  5554. // Parse the declaration-specifiers.
  5555. // Just use the ParsingDeclaration "scope" of the declarator.
  5556. DeclSpec DS(AttrFactory);
  5557. // Parse any C++11 attributes.
  5558. MaybeParseCXX11Attributes(DS.getAttributes());
  5559. // Skip any Microsoft attributes before a param.
  5560. MaybeParseMicrosoftAttributes(DS.getAttributes());
  5561. SourceLocation DSStart = Tok.getLocation();
  5562. // If the caller parsed attributes for the first argument, add them now.
  5563. // Take them so that we only apply the attributes to the first parameter.
  5564. // FIXME: If we can leave the attributes in the token stream somehow, we can
  5565. // get rid of a parameter (FirstArgAttrs) and this statement. It might be
  5566. // too much hassle.
  5567. DS.takeAttributesFrom(FirstArgAttrs);
  5568. ParseDeclarationSpecifiers(DS);
  5569. // Parse the declarator. This is "PrototypeContext" or
  5570. // "LambdaExprParameterContext", because we must accept either
  5571. // 'declarator' or 'abstract-declarator' here.
  5572. Declarator ParmDeclarator(DS,
  5573. D.getContext() == Declarator::LambdaExprContext ?
  5574. Declarator::LambdaExprParameterContext :
  5575. Declarator::PrototypeContext);
  5576. ParseDeclarator(ParmDeclarator);
  5577. // Parse GNU attributes, if present.
  5578. MaybeParseGNUAttributes(ParmDeclarator);
  5579. // Remember this parsed parameter in ParamInfo.
  5580. IdentifierInfo *ParmII = ParmDeclarator.getIdentifier();
  5581. // DefArgToks is used when the parsing of default arguments needs
  5582. // to be delayed.
  5583. std::unique_ptr<CachedTokens> DefArgToks;
  5584. // If no parameter was specified, verify that *something* was specified,
  5585. // otherwise we have a missing type and identifier.
  5586. if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr &&
  5587. ParmDeclarator.getNumTypeObjects() == 0) {
  5588. // Completely missing, emit error.
  5589. Diag(DSStart, diag::err_missing_param);
  5590. } else {
  5591. // Otherwise, we have something. Add it and let semantic analysis try
  5592. // to grok it and add the result to the ParamInfo we are building.
  5593. // Last chance to recover from a misplaced ellipsis in an attempted
  5594. // parameter pack declaration.
  5595. if (Tok.is(tok::ellipsis) &&
  5596. (NextToken().isNot(tok::r_paren) ||
  5597. (!ParmDeclarator.getEllipsisLoc().isValid() &&
  5598. !Actions.isUnexpandedParameterPackPermitted())) &&
  5599. Actions.containsUnexpandedParameterPacks(ParmDeclarator))
  5600. DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator);
  5601. // Inform the actions module about the parameter declarator, so it gets
  5602. // added to the current scope.
  5603. Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator);
  5604. // Parse the default argument, if any. We parse the default
  5605. // arguments in all dialects; the semantic analysis in
  5606. // ActOnParamDefaultArgument will reject the default argument in
  5607. // C.
  5608. if (Tok.is(tok::equal)) {
  5609. SourceLocation EqualLoc = Tok.getLocation();
  5610. // Parse the default argument
  5611. if (D.getContext() == Declarator::MemberContext) {
  5612. // If we're inside a class definition, cache the tokens
  5613. // corresponding to the default argument. We'll actually parse
  5614. // them when we see the end of the class definition.
  5615. DefArgToks.reset(new CachedTokens);
  5616. SourceLocation ArgStartLoc = NextToken().getLocation();
  5617. if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) {
  5618. DefArgToks.reset();
  5619. Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
  5620. } else {
  5621. Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
  5622. ArgStartLoc);
  5623. }
  5624. } else {
  5625. // Consume the '='.
  5626. ConsumeToken();
  5627. // The argument isn't actually potentially evaluated unless it is
  5628. // used.
  5629. EnterExpressionEvaluationContext Eval(
  5630. Actions,
  5631. Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed,
  5632. Param);
  5633. ExprResult DefArgResult;
  5634. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  5635. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  5636. DefArgResult = ParseBraceInitializer();
  5637. } else
  5638. DefArgResult = ParseAssignmentExpression();
  5639. DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult);
  5640. if (DefArgResult.isInvalid()) {
  5641. Actions.ActOnParamDefaultArgumentError(Param, EqualLoc);
  5642. SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch);
  5643. } else {
  5644. // Inform the actions module about the default argument
  5645. Actions.ActOnParamDefaultArgument(Param, EqualLoc,
  5646. DefArgResult.get());
  5647. }
  5648. }
  5649. }
  5650. ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
  5651. ParmDeclarator.getIdentifierLoc(),
  5652. Param, std::move(DefArgToks)));
  5653. }
  5654. if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
  5655. if (!getLangOpts().CPlusPlus) {
  5656. // We have ellipsis without a preceding ',', which is ill-formed
  5657. // in C. Complain and provide the fix.
  5658. Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
  5659. << FixItHint::CreateInsertion(EllipsisLoc, ", ");
  5660. } else if (ParmDeclarator.getEllipsisLoc().isValid() ||
  5661. Actions.containsUnexpandedParameterPacks(ParmDeclarator)) {
  5662. // It looks like this was supposed to be a parameter pack. Warn and
  5663. // point out where the ellipsis should have gone.
  5664. SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc();
  5665. Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg)
  5666. << ParmEllipsis.isValid() << ParmEllipsis;
  5667. if (ParmEllipsis.isValid()) {
  5668. Diag(ParmEllipsis,
  5669. diag::note_misplaced_ellipsis_vararg_existing_ellipsis);
  5670. } else {
  5671. Diag(ParmDeclarator.getIdentifierLoc(),
  5672. diag::note_misplaced_ellipsis_vararg_add_ellipsis)
  5673. << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(),
  5674. "...")
  5675. << !ParmDeclarator.hasName();
  5676. }
  5677. Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma)
  5678. << FixItHint::CreateInsertion(EllipsisLoc, ", ");
  5679. }
  5680. // We can't have any more parameters after an ellipsis.
  5681. break;
  5682. }
  5683. // If the next token is a comma, consume it and keep reading arguments.
  5684. } while (TryConsumeToken(tok::comma));
  5685. }
  5686. /// [C90] direct-declarator '[' constant-expression[opt] ']'
  5687. /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
  5688. /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
  5689. /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
  5690. /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
  5691. /// [C++11] direct-declarator '[' constant-expression[opt] ']'
  5692. /// attribute-specifier-seq[opt]
  5693. void Parser::ParseBracketDeclarator(Declarator &D) {
  5694. if (CheckProhibitedCXX11Attribute())
  5695. return;
  5696. BalancedDelimiterTracker T(*this, tok::l_square);
  5697. T.consumeOpen();
  5698. // C array syntax has many features, but by-far the most common is [] and [4].
  5699. // This code does a fast path to handle some of the most obvious cases.
  5700. if (Tok.getKind() == tok::r_square) {
  5701. T.consumeClose();
  5702. ParsedAttributes attrs(AttrFactory);
  5703. MaybeParseCXX11Attributes(attrs);
  5704. // Remember that we parsed the empty array type.
  5705. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr,
  5706. T.getOpenLocation(),
  5707. T.getCloseLocation()),
  5708. attrs, T.getCloseLocation());
  5709. return;
  5710. } else if (Tok.getKind() == tok::numeric_constant &&
  5711. GetLookAheadToken(1).is(tok::r_square)) {
  5712. // [4] is very common. Parse the numeric constant expression.
  5713. ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
  5714. ConsumeToken();
  5715. T.consumeClose();
  5716. ParsedAttributes attrs(AttrFactory);
  5717. MaybeParseCXX11Attributes(attrs);
  5718. // Remember that we parsed a array type, and remember its features.
  5719. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false,
  5720. ExprRes.get(),
  5721. T.getOpenLocation(),
  5722. T.getCloseLocation()),
  5723. attrs, T.getCloseLocation());
  5724. return;
  5725. } else if (Tok.getKind() == tok::code_completion) {
  5726. Actions.CodeCompleteBracketDeclarator(getCurScope());
  5727. return cutOffParsing();
  5728. }
  5729. // If valid, this location is the position where we read the 'static' keyword.
  5730. SourceLocation StaticLoc;
  5731. TryConsumeToken(tok::kw_static, StaticLoc);
  5732. // If there is a type-qualifier-list, read it now.
  5733. // Type qualifiers in an array subscript are a C99 feature.
  5734. DeclSpec DS(AttrFactory);
  5735. ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed);
  5736. // If we haven't already read 'static', check to see if there is one after the
  5737. // type-qualifier-list.
  5738. if (!StaticLoc.isValid())
  5739. TryConsumeToken(tok::kw_static, StaticLoc);
  5740. // Handle "direct-declarator [ type-qual-list[opt] * ]".
  5741. bool isStar = false;
  5742. ExprResult NumElements;
  5743. // Handle the case where we have '[*]' as the array size. However, a leading
  5744. // star could be the start of an expression, for example 'X[*p + 4]'. Verify
  5745. // the token after the star is a ']'. Since stars in arrays are
  5746. // infrequent, use of lookahead is not costly here.
  5747. if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
  5748. ConsumeToken(); // Eat the '*'.
  5749. if (StaticLoc.isValid()) {
  5750. Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
  5751. StaticLoc = SourceLocation(); // Drop the static.
  5752. }
  5753. isStar = true;
  5754. } else if (Tok.isNot(tok::r_square)) {
  5755. // Note, in C89, this production uses the constant-expr production instead
  5756. // of assignment-expr. The only difference is that assignment-expr allows
  5757. // things like '=' and '*='. Sema rejects these in C89 mode because they
  5758. // are not i-c-e's, so we don't need to distinguish between the two here.
  5759. // Parse the constant-expression or assignment-expression now (depending
  5760. // on dialect).
  5761. if (getLangOpts().CPlusPlus) {
  5762. NumElements = ParseConstantExpression();
  5763. } else {
  5764. EnterExpressionEvaluationContext Unevaluated(
  5765. Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  5766. NumElements =
  5767. Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
  5768. }
  5769. } else {
  5770. if (StaticLoc.isValid()) {
  5771. Diag(StaticLoc, diag::err_unspecified_size_with_static);
  5772. StaticLoc = SourceLocation(); // Drop the static.
  5773. }
  5774. }
  5775. // If there was an error parsing the assignment-expression, recover.
  5776. if (NumElements.isInvalid()) {
  5777. D.setInvalidType(true);
  5778. // If the expression was invalid, skip it.
  5779. SkipUntil(tok::r_square, StopAtSemi);
  5780. return;
  5781. }
  5782. T.consumeClose();
  5783. MaybeParseCXX11Attributes(DS.getAttributes());
  5784. // Remember that we parsed a array type, and remember its features.
  5785. D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
  5786. StaticLoc.isValid(), isStar,
  5787. NumElements.get(),
  5788. T.getOpenLocation(),
  5789. T.getCloseLocation()),
  5790. DS.getAttributes(), T.getCloseLocation());
  5791. }
  5792. /// Diagnose brackets before an identifier.
  5793. void Parser::ParseMisplacedBracketDeclarator(Declarator &D) {
  5794. assert(Tok.is(tok::l_square) && "Missing opening bracket");
  5795. assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier");
  5796. SourceLocation StartBracketLoc = Tok.getLocation();
  5797. Declarator TempDeclarator(D.getDeclSpec(), D.getContext());
  5798. while (Tok.is(tok::l_square)) {
  5799. ParseBracketDeclarator(TempDeclarator);
  5800. }
  5801. // Stuff the location of the start of the brackets into the Declarator.
  5802. // The diagnostics from ParseDirectDeclarator will make more sense if
  5803. // they use this location instead.
  5804. if (Tok.is(tok::semi))
  5805. D.getName().EndLocation = StartBracketLoc;
  5806. SourceLocation SuggestParenLoc = Tok.getLocation();
  5807. // Now that the brackets are removed, try parsing the declarator again.
  5808. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
  5809. // Something went wrong parsing the brackets, in which case,
  5810. // ParseBracketDeclarator has emitted an error, and we don't need to emit
  5811. // one here.
  5812. if (TempDeclarator.getNumTypeObjects() == 0)
  5813. return;
  5814. // Determine if parens will need to be suggested in the diagnostic.
  5815. bool NeedParens = false;
  5816. if (D.getNumTypeObjects() != 0) {
  5817. switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) {
  5818. case DeclaratorChunk::Pointer:
  5819. case DeclaratorChunk::Reference:
  5820. case DeclaratorChunk::BlockPointer:
  5821. case DeclaratorChunk::MemberPointer:
  5822. case DeclaratorChunk::Pipe:
  5823. NeedParens = true;
  5824. break;
  5825. case DeclaratorChunk::Array:
  5826. case DeclaratorChunk::Function:
  5827. case DeclaratorChunk::Paren:
  5828. break;
  5829. }
  5830. }
  5831. if (NeedParens) {
  5832. // Create a DeclaratorChunk for the inserted parens.
  5833. ParsedAttributes attrs(AttrFactory);
  5834. SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
  5835. D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs,
  5836. SourceLocation());
  5837. }
  5838. // Adding back the bracket info to the end of the Declarator.
  5839. for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) {
  5840. const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i);
  5841. ParsedAttributes attrs(AttrFactory);
  5842. attrs.set(Chunk.Common.AttrList);
  5843. D.AddTypeInfo(Chunk, attrs, SourceLocation());
  5844. }
  5845. // The missing identifier would have been diagnosed in ParseDirectDeclarator.
  5846. // If parentheses are required, always suggest them.
  5847. if (!D.getIdentifier() && !NeedParens)
  5848. return;
  5849. SourceLocation EndBracketLoc = TempDeclarator.getLocEnd();
  5850. // Generate the move bracket error message.
  5851. SourceRange BracketRange(StartBracketLoc, EndBracketLoc);
  5852. SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd());
  5853. if (NeedParens) {
  5854. Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
  5855. << getLangOpts().CPlusPlus
  5856. << FixItHint::CreateInsertion(SuggestParenLoc, "(")
  5857. << FixItHint::CreateInsertion(EndLoc, ")")
  5858. << FixItHint::CreateInsertionFromRange(
  5859. EndLoc, CharSourceRange(BracketRange, true))
  5860. << FixItHint::CreateRemoval(BracketRange);
  5861. } else {
  5862. Diag(EndLoc, diag::err_brackets_go_after_unqualified_id)
  5863. << getLangOpts().CPlusPlus
  5864. << FixItHint::CreateInsertionFromRange(
  5865. EndLoc, CharSourceRange(BracketRange, true))
  5866. << FixItHint::CreateRemoval(BracketRange);
  5867. }
  5868. }
  5869. /// [GNU] typeof-specifier:
  5870. /// typeof ( expressions )
  5871. /// typeof ( type-name )
  5872. /// [GNU/C++] typeof unary-expression
  5873. ///
  5874. void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
  5875. assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
  5876. Token OpTok = Tok;
  5877. SourceLocation StartLoc = ConsumeToken();
  5878. const bool hasParens = Tok.is(tok::l_paren);
  5879. EnterExpressionEvaluationContext Unevaluated(
  5880. Actions, Sema::ExpressionEvaluationContext::Unevaluated,
  5881. Sema::ReuseLambdaContextDecl);
  5882. bool isCastExpr;
  5883. ParsedType CastTy;
  5884. SourceRange CastRange;
  5885. ExprResult Operand = Actions.CorrectDelayedTyposInExpr(
  5886. ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange));
  5887. if (hasParens)
  5888. DS.setTypeofParensRange(CastRange);
  5889. if (CastRange.getEnd().isInvalid())
  5890. // FIXME: Not accurate, the range gets one token more than it should.
  5891. DS.SetRangeEnd(Tok.getLocation());
  5892. else
  5893. DS.SetRangeEnd(CastRange.getEnd());
  5894. if (isCastExpr) {
  5895. if (!CastTy) {
  5896. DS.SetTypeSpecError();
  5897. return;
  5898. }
  5899. const char *PrevSpec = nullptr;
  5900. unsigned DiagID;
  5901. // Check for duplicate type specifiers (e.g. "int typeof(int)").
  5902. if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
  5903. DiagID, CastTy,
  5904. Actions.getASTContext().getPrintingPolicy()))
  5905. Diag(StartLoc, DiagID) << PrevSpec;
  5906. return;
  5907. }
  5908. // If we get here, the operand to the typeof was an expression.
  5909. if (Operand.isInvalid()) {
  5910. DS.SetTypeSpecError();
  5911. return;
  5912. }
  5913. // We might need to transform the operand if it is potentially evaluated.
  5914. Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
  5915. if (Operand.isInvalid()) {
  5916. DS.SetTypeSpecError();
  5917. return;
  5918. }
  5919. const char *PrevSpec = nullptr;
  5920. unsigned DiagID;
  5921. // Check for duplicate type specifiers (e.g. "int typeof(int)").
  5922. if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
  5923. DiagID, Operand.get(),
  5924. Actions.getASTContext().getPrintingPolicy()))
  5925. Diag(StartLoc, DiagID) << PrevSpec;
  5926. }
  5927. /// [C11] atomic-specifier:
  5928. /// _Atomic ( type-name )
  5929. ///
  5930. void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
  5931. assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) &&
  5932. "Not an atomic specifier");
  5933. SourceLocation StartLoc = ConsumeToken();
  5934. BalancedDelimiterTracker T(*this, tok::l_paren);
  5935. if (T.consumeOpen())
  5936. return;
  5937. TypeResult Result = ParseTypeName();
  5938. if (Result.isInvalid()) {
  5939. SkipUntil(tok::r_paren, StopAtSemi);
  5940. return;
  5941. }
  5942. // Match the ')'
  5943. T.consumeClose();
  5944. if (T.getCloseLocation().isInvalid())
  5945. return;
  5946. DS.setTypeofParensRange(T.getRange());
  5947. DS.SetRangeEnd(T.getCloseLocation());
  5948. const char *PrevSpec = nullptr;
  5949. unsigned DiagID;
  5950. if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
  5951. DiagID, Result.get(),
  5952. Actions.getASTContext().getPrintingPolicy()))
  5953. Diag(StartLoc, DiagID) << PrevSpec;
  5954. }
  5955. /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
  5956. /// from TryAltiVecVectorToken.
  5957. bool Parser::TryAltiVecVectorTokenOutOfLine() {
  5958. Token Next = NextToken();
  5959. switch (Next.getKind()) {
  5960. default: return false;
  5961. case tok::kw_short:
  5962. case tok::kw_long:
  5963. case tok::kw_signed:
  5964. case tok::kw_unsigned:
  5965. case tok::kw_void:
  5966. case tok::kw_char:
  5967. case tok::kw_int:
  5968. case tok::kw_float:
  5969. case tok::kw_double:
  5970. case tok::kw_bool:
  5971. case tok::kw___bool:
  5972. case tok::kw___pixel:
  5973. Tok.setKind(tok::kw___vector);
  5974. return true;
  5975. case tok::identifier:
  5976. if (Next.getIdentifierInfo() == Ident_pixel) {
  5977. Tok.setKind(tok::kw___vector);
  5978. return true;
  5979. }
  5980. if (Next.getIdentifierInfo() == Ident_bool) {
  5981. Tok.setKind(tok::kw___vector);
  5982. return true;
  5983. }
  5984. return false;
  5985. }
  5986. }
  5987. bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
  5988. const char *&PrevSpec, unsigned &DiagID,
  5989. bool &isInvalid) {
  5990. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  5991. if (Tok.getIdentifierInfo() == Ident_vector) {
  5992. Token Next = NextToken();
  5993. switch (Next.getKind()) {
  5994. case tok::kw_short:
  5995. case tok::kw_long:
  5996. case tok::kw_signed:
  5997. case tok::kw_unsigned:
  5998. case tok::kw_void:
  5999. case tok::kw_char:
  6000. case tok::kw_int:
  6001. case tok::kw_float:
  6002. case tok::kw_double:
  6003. case tok::kw_bool:
  6004. case tok::kw___bool:
  6005. case tok::kw___pixel:
  6006. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy);
  6007. return true;
  6008. case tok::identifier:
  6009. if (Next.getIdentifierInfo() == Ident_pixel) {
  6010. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
  6011. return true;
  6012. }
  6013. if (Next.getIdentifierInfo() == Ident_bool) {
  6014. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy);
  6015. return true;
  6016. }
  6017. break;
  6018. default:
  6019. break;
  6020. }
  6021. } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
  6022. DS.isTypeAltiVecVector()) {
  6023. isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy);
  6024. return true;
  6025. } else if ((Tok.getIdentifierInfo() == Ident_bool) &&
  6026. DS.isTypeAltiVecVector()) {
  6027. isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy);
  6028. return true;
  6029. }
  6030. return false;
  6031. }