ParseDecl.cpp 269 KB

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