ParseDecl.cpp 258 KB

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