ParseDecl.cpp 263 KB

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