ParseDecl.cpp 267 KB

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