ParseDecl.cpp 232 KB

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