ParseDecl.cpp 236 KB

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