ParseDecl.cpp 251 KB

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