ParseDecl.cpp 251 KB

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