ParseDecl.cpp 269 KB

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