ParseDecl.cpp 274 KB

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