ParseDecl.cpp 288 KB

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