ParseDecl.cpp 266 KB

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