ParseDecl.cpp 259 KB

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