ParseDecl.cpp 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224
  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 "clang/Parse/ParseDiagnostic.h"
  15. #include "clang/Basic/OpenCL.h"
  16. #include "clang/Sema/Lookup.h"
  17. #include "clang/Sema/Scope.h"
  18. #include "clang/Sema/ParsedTemplate.h"
  19. #include "clang/Sema/PrettyDeclStackTrace.h"
  20. #include "RAIIObjectsForParser.h"
  21. #include "llvm/ADT/SmallSet.h"
  22. #include "llvm/ADT/SmallString.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. using namespace clang;
  25. //===----------------------------------------------------------------------===//
  26. // C99 6.7: Declarations.
  27. //===----------------------------------------------------------------------===//
  28. /// ParseTypeName
  29. /// type-name: [C99 6.7.6]
  30. /// specifier-qualifier-list abstract-declarator[opt]
  31. ///
  32. /// Called type-id in C++.
  33. TypeResult Parser::ParseTypeName(SourceRange *Range,
  34. Declarator::TheContext Context,
  35. AccessSpecifier AS,
  36. Decl **OwnedType) {
  37. DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context);
  38. if (DSC == DSC_normal)
  39. DSC = DSC_type_specifier;
  40. // Parse the common declaration-specifiers piece.
  41. DeclSpec DS(AttrFactory);
  42. ParseSpecifierQualifierList(DS, AS, DSC);
  43. if (OwnedType)
  44. *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : 0;
  45. // Parse the abstract-declarator, if present.
  46. Declarator DeclaratorInfo(DS, Context);
  47. ParseDeclarator(DeclaratorInfo);
  48. if (Range)
  49. *Range = DeclaratorInfo.getSourceRange();
  50. if (DeclaratorInfo.isInvalidType())
  51. return true;
  52. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  53. }
  54. /// isAttributeLateParsed - Return true if the attribute has arguments that
  55. /// require late parsing.
  56. static bool isAttributeLateParsed(const IdentifierInfo &II) {
  57. return llvm::StringSwitch<bool>(II.getName())
  58. #include "clang/Parse/AttrLateParsed.inc"
  59. .Default(false);
  60. }
  61. /// ParseGNUAttributes - Parse a non-empty attributes list.
  62. ///
  63. /// [GNU] attributes:
  64. /// attribute
  65. /// attributes attribute
  66. ///
  67. /// [GNU] attribute:
  68. /// '__attribute__' '(' '(' attribute-list ')' ')'
  69. ///
  70. /// [GNU] attribute-list:
  71. /// attrib
  72. /// attribute_list ',' attrib
  73. ///
  74. /// [GNU] attrib:
  75. /// empty
  76. /// attrib-name
  77. /// attrib-name '(' identifier ')'
  78. /// attrib-name '(' identifier ',' nonempty-expr-list ')'
  79. /// attrib-name '(' argument-expression-list [C99 6.5.2] ')'
  80. ///
  81. /// [GNU] attrib-name:
  82. /// identifier
  83. /// typespec
  84. /// typequal
  85. /// storageclass
  86. ///
  87. /// FIXME: The GCC grammar/code for this construct implies we need two
  88. /// token lookahead. Comment from gcc: "If they start with an identifier
  89. /// which is followed by a comma or close parenthesis, then the arguments
  90. /// start with that identifier; otherwise they are an expression list."
  91. ///
  92. /// GCC does not require the ',' between attribs in an attribute-list.
  93. ///
  94. /// At the moment, I am not doing 2 token lookahead. I am also unaware of
  95. /// any attributes that don't work (based on my limited testing). Most
  96. /// attributes are very simple in practice. Until we find a bug, I don't see
  97. /// a pressing need to implement the 2 token lookahead.
  98. void Parser::ParseGNUAttributes(ParsedAttributes &attrs,
  99. SourceLocation *endLoc,
  100. LateParsedAttrList *LateAttrs) {
  101. assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!");
  102. while (Tok.is(tok::kw___attribute)) {
  103. ConsumeToken();
  104. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
  105. "attribute")) {
  106. SkipUntil(tok::r_paren, true); // skip until ) or ;
  107. return;
  108. }
  109. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) {
  110. SkipUntil(tok::r_paren, true); // skip until ) or ;
  111. return;
  112. }
  113. // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") ))
  114. while (Tok.is(tok::identifier) || isDeclarationSpecifier() ||
  115. Tok.is(tok::comma)) {
  116. if (Tok.is(tok::comma)) {
  117. // allows for empty/non-empty attributes. ((__vector_size__(16),,,,))
  118. ConsumeToken();
  119. continue;
  120. }
  121. // we have an identifier or declaration specifier (const, int, etc.)
  122. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  123. SourceLocation AttrNameLoc = ConsumeToken();
  124. if (Tok.is(tok::l_paren)) {
  125. // handle "parameterized" attributes
  126. if (LateAttrs && isAttributeLateParsed(*AttrName)) {
  127. LateParsedAttribute *LA =
  128. new LateParsedAttribute(this, *AttrName, AttrNameLoc);
  129. LateAttrs->push_back(LA);
  130. // Attributes in a class are parsed at the end of the class, along
  131. // with other late-parsed declarations.
  132. if (!ClassStack.empty())
  133. getCurrentClass().LateParsedDeclarations.push_back(LA);
  134. // consume everything up to and including the matching right parens
  135. ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false);
  136. Token Eof;
  137. Eof.startToken();
  138. Eof.setLocation(Tok.getLocation());
  139. LA->Toks.push_back(Eof);
  140. } else {
  141. ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc);
  142. }
  143. } else {
  144. attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc,
  145. 0, SourceLocation(), 0, 0, AttributeList::AS_GNU);
  146. }
  147. }
  148. if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen))
  149. SkipUntil(tok::r_paren, false);
  150. SourceLocation Loc = Tok.getLocation();
  151. if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
  152. SkipUntil(tok::r_paren, false);
  153. }
  154. if (endLoc)
  155. *endLoc = Loc;
  156. }
  157. }
  158. /// Parse the arguments to a parameterized GNU attribute
  159. void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName,
  160. SourceLocation AttrNameLoc,
  161. ParsedAttributes &Attrs,
  162. SourceLocation *EndLoc) {
  163. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  164. // Availability attributes have their own grammar.
  165. if (AttrName->isStr("availability")) {
  166. ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
  167. return;
  168. }
  169. // Thread safety attributes fit into the FIXME case above, so we
  170. // just parse the arguments as a list of expressions
  171. if (IsThreadSafetyAttribute(AttrName->getName())) {
  172. ParseThreadSafetyAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
  173. return;
  174. }
  175. // Type safety attributes have their own grammar.
  176. if (AttrName->isStr("type_tag_for_datatype")) {
  177. ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc);
  178. return;
  179. }
  180. ConsumeParen(); // ignore the left paren loc for now
  181. IdentifierInfo *ParmName = 0;
  182. SourceLocation ParmLoc;
  183. bool BuiltinType = false;
  184. switch (Tok.getKind()) {
  185. case tok::kw_char:
  186. case tok::kw_wchar_t:
  187. case tok::kw_char16_t:
  188. case tok::kw_char32_t:
  189. case tok::kw_bool:
  190. case tok::kw_short:
  191. case tok::kw_int:
  192. case tok::kw_long:
  193. case tok::kw___int64:
  194. case tok::kw___int128:
  195. case tok::kw_signed:
  196. case tok::kw_unsigned:
  197. case tok::kw_float:
  198. case tok::kw_double:
  199. case tok::kw_void:
  200. case tok::kw_typeof:
  201. // __attribute__(( vec_type_hint(char) ))
  202. // FIXME: Don't just discard the builtin type token.
  203. ConsumeToken();
  204. BuiltinType = true;
  205. break;
  206. case tok::identifier:
  207. ParmName = Tok.getIdentifierInfo();
  208. ParmLoc = ConsumeToken();
  209. break;
  210. default:
  211. break;
  212. }
  213. ExprVector ArgExprs(Actions);
  214. if (!BuiltinType &&
  215. (ParmLoc.isValid() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren))) {
  216. // Eat the comma.
  217. if (ParmLoc.isValid())
  218. ConsumeToken();
  219. // Parse the non-empty comma-separated list of expressions.
  220. while (1) {
  221. ExprResult ArgExpr(ParseAssignmentExpression());
  222. if (ArgExpr.isInvalid()) {
  223. SkipUntil(tok::r_paren);
  224. return;
  225. }
  226. ArgExprs.push_back(ArgExpr.release());
  227. if (Tok.isNot(tok::comma))
  228. break;
  229. ConsumeToken(); // Eat the comma, move to the next argument
  230. }
  231. }
  232. else if (Tok.is(tok::less) && AttrName->isStr("iboutletcollection")) {
  233. if (!ExpectAndConsume(tok::less, diag::err_expected_less_after, "<",
  234. tok::greater)) {
  235. while (Tok.is(tok::identifier)) {
  236. ConsumeToken();
  237. if (Tok.is(tok::greater))
  238. break;
  239. if (Tok.is(tok::comma)) {
  240. ConsumeToken();
  241. continue;
  242. }
  243. }
  244. if (Tok.isNot(tok::greater))
  245. Diag(Tok, diag::err_iboutletcollection_with_protocol);
  246. SkipUntil(tok::r_paren, false, true); // skip until ')'
  247. }
  248. }
  249. SourceLocation RParen = Tok.getLocation();
  250. if (!ExpectAndConsume(tok::r_paren, diag::err_expected_rparen)) {
  251. AttributeList *attr =
  252. Attrs.addNew(AttrName, SourceRange(AttrNameLoc, RParen), 0, AttrNameLoc,
  253. ParmName, ParmLoc, ArgExprs.take(), ArgExprs.size(),
  254. AttributeList::AS_GNU);
  255. if (BuiltinType && attr->getKind() == AttributeList::AT_IBOutletCollection)
  256. Diag(Tok, diag::err_iboutletcollection_builtintype);
  257. }
  258. }
  259. /// \brief Parses a single argument for a declspec, including the
  260. /// surrounding parens.
  261. void Parser::ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
  262. SourceLocation AttrNameLoc,
  263. ParsedAttributes &Attrs)
  264. {
  265. BalancedDelimiterTracker T(*this, tok::l_paren);
  266. if (T.expectAndConsume(diag::err_expected_lparen_after,
  267. AttrName->getNameStart(), tok::r_paren))
  268. return;
  269. ExprResult ArgExpr(ParseConstantExpression());
  270. if (ArgExpr.isInvalid()) {
  271. T.skipToEnd();
  272. return;
  273. }
  274. Expr *ExprList = ArgExpr.take();
  275. Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
  276. &ExprList, 1, AttributeList::AS_Declspec);
  277. T.consumeClose();
  278. }
  279. /// \brief Determines whether a declspec is a "simple" one requiring no
  280. /// arguments.
  281. bool Parser::IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident) {
  282. return llvm::StringSwitch<bool>(Ident->getName())
  283. .Case("dllimport", true)
  284. .Case("dllexport", true)
  285. .Case("noreturn", true)
  286. .Case("nothrow", true)
  287. .Case("noinline", true)
  288. .Case("naked", true)
  289. .Case("appdomain", true)
  290. .Case("process", true)
  291. .Case("jitintrinsic", true)
  292. .Case("noalias", true)
  293. .Case("restrict", true)
  294. .Case("novtable", true)
  295. .Case("selectany", true)
  296. .Case("thread", true)
  297. .Default(false);
  298. }
  299. /// \brief Attempts to parse a declspec which is not simple (one that takes
  300. /// parameters). Will return false if we properly handled the declspec, or
  301. /// true if it is an unknown declspec.
  302. void Parser::ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
  303. SourceLocation Loc,
  304. ParsedAttributes &Attrs) {
  305. // Try to handle the easy case first -- these declspecs all take a single
  306. // parameter as their argument.
  307. if (llvm::StringSwitch<bool>(Ident->getName())
  308. .Case("uuid", true)
  309. .Case("align", true)
  310. .Case("allocate", true)
  311. .Default(false)) {
  312. ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
  313. } else if (Ident->getName() == "deprecated") {
  314. // The deprecated declspec has an optional single argument, so we will
  315. // check for a l-paren to decide whether we should parse an argument or
  316. // not.
  317. if (Tok.getKind() == tok::l_paren)
  318. ParseMicrosoftDeclSpecWithSingleArg(Ident, Loc, Attrs);
  319. else
  320. Attrs.addNew(Ident, Loc, 0, Loc, 0, SourceLocation(), 0, 0,
  321. AttributeList::AS_Declspec);
  322. } else if (Ident->getName() == "property") {
  323. // The property declspec is more complex in that it can take one or two
  324. // assignment expressions as a parameter, but the lhs of the assignment
  325. // must be named get or put.
  326. //
  327. // For right now, we will just skip to the closing right paren of the
  328. // property expression.
  329. //
  330. // FIXME: we should deal with __declspec(property) at some point because it
  331. // is used in the platform SDK headers for the Parallel Patterns Library
  332. // and ATL.
  333. BalancedDelimiterTracker T(*this, tok::l_paren);
  334. if (T.expectAndConsume(diag::err_expected_lparen_after,
  335. Ident->getNameStart(), tok::r_paren))
  336. return;
  337. T.skipToEnd();
  338. } else {
  339. // We don't recognize this as a valid declspec, but instead of creating the
  340. // attribute and allowing sema to warn about it, we will warn here instead.
  341. // This is because some attributes have multiple spellings, but we need to
  342. // disallow that for declspecs (such as align vs aligned). If we made the
  343. // attribute, we'd have to split the valid declspec spelling logic into
  344. // both locations.
  345. Diag(Loc, diag::warn_ms_declspec_unknown) << Ident;
  346. // If there's an open paren, we should eat the open and close parens under
  347. // the assumption that this unknown declspec has parameters.
  348. BalancedDelimiterTracker T(*this, tok::l_paren);
  349. if (!T.consumeOpen())
  350. T.skipToEnd();
  351. }
  352. }
  353. /// [MS] decl-specifier:
  354. /// __declspec ( extended-decl-modifier-seq )
  355. ///
  356. /// [MS] extended-decl-modifier-seq:
  357. /// extended-decl-modifier[opt]
  358. /// extended-decl-modifier extended-decl-modifier-seq
  359. void Parser::ParseMicrosoftDeclSpec(ParsedAttributes &Attrs) {
  360. assert(Tok.is(tok::kw___declspec) && "Not a declspec!");
  361. ConsumeToken();
  362. BalancedDelimiterTracker T(*this, tok::l_paren);
  363. if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec",
  364. tok::r_paren))
  365. return;
  366. // An empty declspec is perfectly legal and should not warn. Additionally,
  367. // you can specify multiple attributes per declspec.
  368. while (Tok.getKind() != tok::r_paren) {
  369. // We expect either a well-known identifier or a generic string. Anything
  370. // else is a malformed declspec.
  371. bool IsString = Tok.getKind() == tok::string_literal ? true : false;
  372. if (!IsString && Tok.getKind() != tok::identifier &&
  373. Tok.getKind() != tok::kw_restrict) {
  374. Diag(Tok, diag::err_ms_declspec_type);
  375. T.skipToEnd();
  376. return;
  377. }
  378. IdentifierInfo *AttrName;
  379. SourceLocation AttrNameLoc;
  380. if (IsString) {
  381. SmallString<8> StrBuffer;
  382. bool Invalid = false;
  383. StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid);
  384. if (Invalid) {
  385. T.skipToEnd();
  386. return;
  387. }
  388. AttrName = PP.getIdentifierInfo(Str);
  389. AttrNameLoc = ConsumeStringToken();
  390. } else {
  391. AttrName = Tok.getIdentifierInfo();
  392. AttrNameLoc = ConsumeToken();
  393. }
  394. if (IsString || IsSimpleMicrosoftDeclSpec(AttrName))
  395. // If we have a generic string, we will allow it because there is no
  396. // documented list of allowable string declspecs, but we know they exist
  397. // (for instance, SAL declspecs in older versions of MSVC).
  398. //
  399. // Alternatively, if the identifier is a simple one, then it requires no
  400. // arguments and can be turned into an attribute directly.
  401. Attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
  402. 0, 0, AttributeList::AS_Declspec);
  403. else
  404. ParseComplexMicrosoftDeclSpec(AttrName, AttrNameLoc, Attrs);
  405. }
  406. T.consumeClose();
  407. }
  408. void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) {
  409. // Treat these like attributes
  410. while (Tok.is(tok::kw___fastcall) || Tok.is(tok::kw___stdcall) ||
  411. Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___cdecl) ||
  412. Tok.is(tok::kw___ptr64) || Tok.is(tok::kw___w64) ||
  413. Tok.is(tok::kw___ptr32) ||
  414. Tok.is(tok::kw___unaligned)) {
  415. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  416. SourceLocation AttrNameLoc = ConsumeToken();
  417. attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
  418. SourceLocation(), 0, 0, AttributeList::AS_MSTypespec);
  419. }
  420. }
  421. void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) {
  422. // Treat these like attributes
  423. while (Tok.is(tok::kw___pascal)) {
  424. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  425. SourceLocation AttrNameLoc = ConsumeToken();
  426. attrs.addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
  427. SourceLocation(), 0, 0, AttributeList::AS_MSTypespec);
  428. }
  429. }
  430. void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) {
  431. // Treat these like attributes
  432. while (Tok.is(tok::kw___kernel)) {
  433. SourceLocation AttrNameLoc = ConsumeToken();
  434. attrs.addNew(PP.getIdentifierInfo("opencl_kernel_function"),
  435. AttrNameLoc, 0, AttrNameLoc, 0,
  436. SourceLocation(), 0, 0, AttributeList::AS_GNU);
  437. }
  438. }
  439. void Parser::ParseOpenCLQualifiers(DeclSpec &DS) {
  440. SourceLocation Loc = Tok.getLocation();
  441. switch(Tok.getKind()) {
  442. // OpenCL qualifiers:
  443. case tok::kw___private:
  444. case tok::kw_private:
  445. DS.getAttributes().addNewInteger(
  446. Actions.getASTContext(),
  447. PP.getIdentifierInfo("address_space"), Loc, 0);
  448. break;
  449. case tok::kw___global:
  450. DS.getAttributes().addNewInteger(
  451. Actions.getASTContext(),
  452. PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_global);
  453. break;
  454. case tok::kw___local:
  455. DS.getAttributes().addNewInteger(
  456. Actions.getASTContext(),
  457. PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_local);
  458. break;
  459. case tok::kw___constant:
  460. DS.getAttributes().addNewInteger(
  461. Actions.getASTContext(),
  462. PP.getIdentifierInfo("address_space"), Loc, LangAS::opencl_constant);
  463. break;
  464. case tok::kw___read_only:
  465. DS.getAttributes().addNewInteger(
  466. Actions.getASTContext(),
  467. PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_only);
  468. break;
  469. case tok::kw___write_only:
  470. DS.getAttributes().addNewInteger(
  471. Actions.getASTContext(),
  472. PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_write_only);
  473. break;
  474. case tok::kw___read_write:
  475. DS.getAttributes().addNewInteger(
  476. Actions.getASTContext(),
  477. PP.getIdentifierInfo("opencl_image_access"), Loc, CLIA_read_write);
  478. break;
  479. default: break;
  480. }
  481. }
  482. /// \brief Parse a version number.
  483. ///
  484. /// version:
  485. /// simple-integer
  486. /// simple-integer ',' simple-integer
  487. /// simple-integer ',' simple-integer ',' simple-integer
  488. VersionTuple Parser::ParseVersionTuple(SourceRange &Range) {
  489. Range = Tok.getLocation();
  490. if (!Tok.is(tok::numeric_constant)) {
  491. Diag(Tok, diag::err_expected_version);
  492. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  493. return VersionTuple();
  494. }
  495. // Parse the major (and possibly minor and subminor) versions, which
  496. // are stored in the numeric constant. We utilize a quirk of the
  497. // lexer, which is that it handles something like 1.2.3 as a single
  498. // numeric constant, rather than two separate tokens.
  499. SmallString<512> Buffer;
  500. Buffer.resize(Tok.getLength()+1);
  501. const char *ThisTokBegin = &Buffer[0];
  502. // Get the spelling of the token, which eliminates trigraphs, etc.
  503. bool Invalid = false;
  504. unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
  505. if (Invalid)
  506. return VersionTuple();
  507. // Parse the major version.
  508. unsigned AfterMajor = 0;
  509. unsigned Major = 0;
  510. while (AfterMajor < ActualLength && isdigit(ThisTokBegin[AfterMajor])) {
  511. Major = Major * 10 + ThisTokBegin[AfterMajor] - '0';
  512. ++AfterMajor;
  513. }
  514. if (AfterMajor == 0) {
  515. Diag(Tok, diag::err_expected_version);
  516. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  517. return VersionTuple();
  518. }
  519. if (AfterMajor == ActualLength) {
  520. ConsumeToken();
  521. // We only had a single version component.
  522. if (Major == 0) {
  523. Diag(Tok, diag::err_zero_version);
  524. return VersionTuple();
  525. }
  526. return VersionTuple(Major);
  527. }
  528. if (ThisTokBegin[AfterMajor] != '.' || (AfterMajor + 1 == ActualLength)) {
  529. Diag(Tok, diag::err_expected_version);
  530. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  531. return VersionTuple();
  532. }
  533. // Parse the minor version.
  534. unsigned AfterMinor = AfterMajor + 1;
  535. unsigned Minor = 0;
  536. while (AfterMinor < ActualLength && isdigit(ThisTokBegin[AfterMinor])) {
  537. Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0';
  538. ++AfterMinor;
  539. }
  540. if (AfterMinor == ActualLength) {
  541. ConsumeToken();
  542. // We had major.minor.
  543. if (Major == 0 && Minor == 0) {
  544. Diag(Tok, diag::err_zero_version);
  545. return VersionTuple();
  546. }
  547. return VersionTuple(Major, Minor);
  548. }
  549. // If what follows is not a '.', we have a problem.
  550. if (ThisTokBegin[AfterMinor] != '.') {
  551. Diag(Tok, diag::err_expected_version);
  552. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  553. return VersionTuple();
  554. }
  555. // Parse the subminor version.
  556. unsigned AfterSubminor = AfterMinor + 1;
  557. unsigned Subminor = 0;
  558. while (AfterSubminor < ActualLength && isdigit(ThisTokBegin[AfterSubminor])) {
  559. Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0';
  560. ++AfterSubminor;
  561. }
  562. if (AfterSubminor != ActualLength) {
  563. Diag(Tok, diag::err_expected_version);
  564. SkipUntil(tok::comma, tok::r_paren, true, true, true);
  565. return VersionTuple();
  566. }
  567. ConsumeToken();
  568. return VersionTuple(Major, Minor, Subminor);
  569. }
  570. /// \brief Parse the contents of the "availability" attribute.
  571. ///
  572. /// availability-attribute:
  573. /// 'availability' '(' platform ',' version-arg-list, opt-message')'
  574. ///
  575. /// platform:
  576. /// identifier
  577. ///
  578. /// version-arg-list:
  579. /// version-arg
  580. /// version-arg ',' version-arg-list
  581. ///
  582. /// version-arg:
  583. /// 'introduced' '=' version
  584. /// 'deprecated' '=' version
  585. /// 'obsoleted' = version
  586. /// 'unavailable'
  587. /// opt-message:
  588. /// 'message' '=' <string>
  589. void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability,
  590. SourceLocation AvailabilityLoc,
  591. ParsedAttributes &attrs,
  592. SourceLocation *endLoc) {
  593. SourceLocation PlatformLoc;
  594. IdentifierInfo *Platform = 0;
  595. enum { Introduced, Deprecated, Obsoleted, Unknown };
  596. AvailabilityChange Changes[Unknown];
  597. ExprResult MessageExpr;
  598. // Opening '('.
  599. BalancedDelimiterTracker T(*this, tok::l_paren);
  600. if (T.consumeOpen()) {
  601. Diag(Tok, diag::err_expected_lparen);
  602. return;
  603. }
  604. // Parse the platform name,
  605. if (Tok.isNot(tok::identifier)) {
  606. Diag(Tok, diag::err_availability_expected_platform);
  607. SkipUntil(tok::r_paren);
  608. return;
  609. }
  610. Platform = Tok.getIdentifierInfo();
  611. PlatformLoc = ConsumeToken();
  612. // Parse the ',' following the platform name.
  613. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::r_paren))
  614. return;
  615. // If we haven't grabbed the pointers for the identifiers
  616. // "introduced", "deprecated", and "obsoleted", do so now.
  617. if (!Ident_introduced) {
  618. Ident_introduced = PP.getIdentifierInfo("introduced");
  619. Ident_deprecated = PP.getIdentifierInfo("deprecated");
  620. Ident_obsoleted = PP.getIdentifierInfo("obsoleted");
  621. Ident_unavailable = PP.getIdentifierInfo("unavailable");
  622. Ident_message = PP.getIdentifierInfo("message");
  623. }
  624. // Parse the set of introductions/deprecations/removals.
  625. SourceLocation UnavailableLoc;
  626. do {
  627. if (Tok.isNot(tok::identifier)) {
  628. Diag(Tok, diag::err_availability_expected_change);
  629. SkipUntil(tok::r_paren);
  630. return;
  631. }
  632. IdentifierInfo *Keyword = Tok.getIdentifierInfo();
  633. SourceLocation KeywordLoc = ConsumeToken();
  634. if (Keyword == Ident_unavailable) {
  635. if (UnavailableLoc.isValid()) {
  636. Diag(KeywordLoc, diag::err_availability_redundant)
  637. << Keyword << SourceRange(UnavailableLoc);
  638. }
  639. UnavailableLoc = KeywordLoc;
  640. if (Tok.isNot(tok::comma))
  641. break;
  642. ConsumeToken();
  643. continue;
  644. }
  645. if (Tok.isNot(tok::equal)) {
  646. Diag(Tok, diag::err_expected_equal_after)
  647. << Keyword;
  648. SkipUntil(tok::r_paren);
  649. return;
  650. }
  651. ConsumeToken();
  652. if (Keyword == Ident_message) {
  653. if (!isTokenStringLiteral()) {
  654. Diag(Tok, diag::err_expected_string_literal);
  655. SkipUntil(tok::r_paren);
  656. return;
  657. }
  658. MessageExpr = ParseStringLiteralExpression();
  659. break;
  660. }
  661. SourceRange VersionRange;
  662. VersionTuple Version = ParseVersionTuple(VersionRange);
  663. if (Version.empty()) {
  664. SkipUntil(tok::r_paren);
  665. return;
  666. }
  667. unsigned Index;
  668. if (Keyword == Ident_introduced)
  669. Index = Introduced;
  670. else if (Keyword == Ident_deprecated)
  671. Index = Deprecated;
  672. else if (Keyword == Ident_obsoleted)
  673. Index = Obsoleted;
  674. else
  675. Index = Unknown;
  676. if (Index < Unknown) {
  677. if (!Changes[Index].KeywordLoc.isInvalid()) {
  678. Diag(KeywordLoc, diag::err_availability_redundant)
  679. << Keyword
  680. << SourceRange(Changes[Index].KeywordLoc,
  681. Changes[Index].VersionRange.getEnd());
  682. }
  683. Changes[Index].KeywordLoc = KeywordLoc;
  684. Changes[Index].Version = Version;
  685. Changes[Index].VersionRange = VersionRange;
  686. } else {
  687. Diag(KeywordLoc, diag::err_availability_unknown_change)
  688. << Keyword << VersionRange;
  689. }
  690. if (Tok.isNot(tok::comma))
  691. break;
  692. ConsumeToken();
  693. } while (true);
  694. // Closing ')'.
  695. if (T.consumeClose())
  696. return;
  697. if (endLoc)
  698. *endLoc = T.getCloseLocation();
  699. // The 'unavailable' availability cannot be combined with any other
  700. // availability changes. Make sure that hasn't happened.
  701. if (UnavailableLoc.isValid()) {
  702. bool Complained = false;
  703. for (unsigned Index = Introduced; Index != Unknown; ++Index) {
  704. if (Changes[Index].KeywordLoc.isValid()) {
  705. if (!Complained) {
  706. Diag(UnavailableLoc, diag::warn_availability_and_unavailable)
  707. << SourceRange(Changes[Index].KeywordLoc,
  708. Changes[Index].VersionRange.getEnd());
  709. Complained = true;
  710. }
  711. // Clear out the availability.
  712. Changes[Index] = AvailabilityChange();
  713. }
  714. }
  715. }
  716. // Record this attribute
  717. attrs.addNew(&Availability,
  718. SourceRange(AvailabilityLoc, T.getCloseLocation()),
  719. 0, AvailabilityLoc,
  720. Platform, PlatformLoc,
  721. Changes[Introduced],
  722. Changes[Deprecated],
  723. Changes[Obsoleted],
  724. UnavailableLoc, MessageExpr.take(),
  725. AttributeList::AS_GNU);
  726. }
  727. // Late Parsed Attributes:
  728. // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods
  729. void Parser::LateParsedDeclaration::ParseLexedAttributes() {}
  730. void Parser::LateParsedClass::ParseLexedAttributes() {
  731. Self->ParseLexedAttributes(*Class);
  732. }
  733. void Parser::LateParsedAttribute::ParseLexedAttributes() {
  734. Self->ParseLexedAttribute(*this, true, false);
  735. }
  736. /// Wrapper class which calls ParseLexedAttribute, after setting up the
  737. /// scope appropriately.
  738. void Parser::ParseLexedAttributes(ParsingClass &Class) {
  739. // Deal with templates
  740. // FIXME: Test cases to make sure this does the right thing for templates.
  741. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope;
  742. ParseScope ClassTemplateScope(this, Scope::TemplateParamScope,
  743. HasTemplateScope);
  744. if (HasTemplateScope)
  745. Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate);
  746. // Set or update the scope flags.
  747. bool AlreadyHasClassScope = Class.TopLevelClass;
  748. unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope;
  749. ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope);
  750. ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope);
  751. // Enter the scope of nested classes
  752. if (!AlreadyHasClassScope)
  753. Actions.ActOnStartDelayedMemberDeclarations(getCurScope(),
  754. Class.TagOrTemplate);
  755. if (!Class.LateParsedDeclarations.empty()) {
  756. for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){
  757. Class.LateParsedDeclarations[i]->ParseLexedAttributes();
  758. }
  759. }
  760. if (!AlreadyHasClassScope)
  761. Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(),
  762. Class.TagOrTemplate);
  763. }
  764. /// \brief Parse all attributes in LAs, and attach them to Decl D.
  765. void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
  766. bool EnterScope, bool OnDefinition) {
  767. for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) {
  768. if (D)
  769. LAs[i]->addDecl(D);
  770. ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition);
  771. delete LAs[i];
  772. }
  773. LAs.clear();
  774. }
  775. /// \brief Finish parsing an attribute for which parsing was delayed.
  776. /// This will be called at the end of parsing a class declaration
  777. /// for each LateParsedAttribute. We consume the saved tokens and
  778. /// create an attribute with the arguments filled in. We add this
  779. /// to the Attribute list for the decl.
  780. void Parser::ParseLexedAttribute(LateParsedAttribute &LA,
  781. bool EnterScope, bool OnDefinition) {
  782. // Save the current token position.
  783. SourceLocation OrigLoc = Tok.getLocation();
  784. // Append the current token at the end of the new token stream so that it
  785. // doesn't get lost.
  786. LA.Toks.push_back(Tok);
  787. PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false);
  788. // Consume the previously pushed token.
  789. ConsumeAnyToken();
  790. if (OnDefinition && !IsThreadSafetyAttribute(LA.AttrName.getName())) {
  791. Diag(Tok, diag::warn_attribute_on_function_definition)
  792. << LA.AttrName.getName();
  793. }
  794. ParsedAttributes Attrs(AttrFactory);
  795. SourceLocation endLoc;
  796. if (LA.Decls.size() > 0) {
  797. Decl *D = LA.Decls[0];
  798. NamedDecl *ND = dyn_cast<NamedDecl>(D);
  799. RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
  800. // Allow 'this' within late-parsed attributes.
  801. Sema::CXXThisScopeRAII ThisScope(Actions, RD,
  802. /*TypeQuals=*/0,
  803. ND && RD && ND->isCXXInstanceMember());
  804. if (LA.Decls.size() == 1) {
  805. // If the Decl is templatized, add template parameters to scope.
  806. bool HasTemplateScope = EnterScope && D->isTemplateDecl();
  807. ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope);
  808. if (HasTemplateScope)
  809. Actions.ActOnReenterTemplateScope(Actions.CurScope, D);
  810. // If the Decl is on a function, add function parameters to the scope.
  811. bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate();
  812. ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope);
  813. if (HasFunScope)
  814. Actions.ActOnReenterFunctionContext(Actions.CurScope, D);
  815. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
  816. if (HasFunScope) {
  817. Actions.ActOnExitFunctionContext();
  818. FnScope.Exit(); // Pop scope, and remove Decls from IdResolver
  819. }
  820. if (HasTemplateScope) {
  821. TempScope.Exit();
  822. }
  823. } else {
  824. // If there are multiple decls, then the decl cannot be within the
  825. // function scope.
  826. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc);
  827. }
  828. } else {
  829. Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName();
  830. }
  831. for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) {
  832. Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs);
  833. }
  834. if (Tok.getLocation() != OrigLoc) {
  835. // Due to a parsing error, we either went over the cached tokens or
  836. // there are still cached tokens left, so we skip the leftover tokens.
  837. // Since this is an uncommon situation that should be avoided, use the
  838. // expensive isBeforeInTranslationUnit call.
  839. if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(),
  840. OrigLoc))
  841. while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof))
  842. ConsumeAnyToken();
  843. }
  844. }
  845. /// \brief Wrapper around a case statement checking if AttrName is
  846. /// one of the thread safety attributes
  847. bool Parser::IsThreadSafetyAttribute(llvm::StringRef AttrName){
  848. return llvm::StringSwitch<bool>(AttrName)
  849. .Case("guarded_by", true)
  850. .Case("guarded_var", true)
  851. .Case("pt_guarded_by", true)
  852. .Case("pt_guarded_var", true)
  853. .Case("lockable", true)
  854. .Case("scoped_lockable", true)
  855. .Case("no_thread_safety_analysis", true)
  856. .Case("acquired_after", true)
  857. .Case("acquired_before", true)
  858. .Case("exclusive_lock_function", true)
  859. .Case("shared_lock_function", true)
  860. .Case("exclusive_trylock_function", true)
  861. .Case("shared_trylock_function", true)
  862. .Case("unlock_function", true)
  863. .Case("lock_returned", true)
  864. .Case("locks_excluded", true)
  865. .Case("exclusive_locks_required", true)
  866. .Case("shared_locks_required", true)
  867. .Default(false);
  868. }
  869. /// \brief Parse the contents of thread safety attributes. These
  870. /// should always be parsed as an expression list.
  871. ///
  872. /// We need to special case the parsing due to the fact that if the first token
  873. /// of the first argument is an identifier, the main parse loop will store
  874. /// that token as a "parameter" and the rest of
  875. /// the arguments will be added to a list of "arguments". However,
  876. /// subsequent tokens in the first argument are lost. We instead parse each
  877. /// argument as an expression and add all arguments to the list of "arguments".
  878. /// In future, we will take advantage of this special case to also
  879. /// deal with some argument scoping issues here (for example, referring to a
  880. /// function parameter in the attribute on that function).
  881. void Parser::ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
  882. SourceLocation AttrNameLoc,
  883. ParsedAttributes &Attrs,
  884. SourceLocation *EndLoc) {
  885. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  886. BalancedDelimiterTracker T(*this, tok::l_paren);
  887. T.consumeOpen();
  888. ExprVector ArgExprs(Actions);
  889. bool ArgExprsOk = true;
  890. // now parse the list of expressions
  891. while (Tok.isNot(tok::r_paren)) {
  892. ExprResult ArgExpr(ParseAssignmentExpression());
  893. if (ArgExpr.isInvalid()) {
  894. ArgExprsOk = false;
  895. T.consumeClose();
  896. break;
  897. } else {
  898. ArgExprs.push_back(ArgExpr.release());
  899. }
  900. if (Tok.isNot(tok::comma))
  901. break;
  902. ConsumeToken(); // Eat the comma, move to the next argument
  903. }
  904. // Match the ')'.
  905. if (ArgExprsOk && !T.consumeClose()) {
  906. Attrs.addNew(&AttrName, AttrNameLoc, 0, AttrNameLoc, 0, SourceLocation(),
  907. ArgExprs.take(), ArgExprs.size(), AttributeList::AS_GNU);
  908. }
  909. if (EndLoc)
  910. *EndLoc = T.getCloseLocation();
  911. }
  912. void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
  913. SourceLocation AttrNameLoc,
  914. ParsedAttributes &Attrs,
  915. SourceLocation *EndLoc) {
  916. assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('");
  917. BalancedDelimiterTracker T(*this, tok::l_paren);
  918. T.consumeOpen();
  919. if (Tok.isNot(tok::identifier)) {
  920. Diag(Tok, diag::err_expected_ident);
  921. T.skipToEnd();
  922. return;
  923. }
  924. IdentifierInfo *ArgumentKind = Tok.getIdentifierInfo();
  925. SourceLocation ArgumentKindLoc = ConsumeToken();
  926. if (Tok.isNot(tok::comma)) {
  927. Diag(Tok, diag::err_expected_comma);
  928. T.skipToEnd();
  929. return;
  930. }
  931. ConsumeToken();
  932. SourceRange MatchingCTypeRange;
  933. TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange);
  934. if (MatchingCType.isInvalid()) {
  935. T.skipToEnd();
  936. return;
  937. }
  938. bool LayoutCompatible = false;
  939. bool MustBeNull = false;
  940. while (Tok.is(tok::comma)) {
  941. ConsumeToken();
  942. if (Tok.isNot(tok::identifier)) {
  943. Diag(Tok, diag::err_expected_ident);
  944. T.skipToEnd();
  945. return;
  946. }
  947. IdentifierInfo *Flag = Tok.getIdentifierInfo();
  948. if (Flag->isStr("layout_compatible"))
  949. LayoutCompatible = true;
  950. else if (Flag->isStr("must_be_null"))
  951. MustBeNull = true;
  952. else {
  953. Diag(Tok, diag::err_type_safety_unknown_flag) << Flag;
  954. T.skipToEnd();
  955. return;
  956. }
  957. ConsumeToken(); // consume flag
  958. }
  959. if (!T.consumeClose()) {
  960. Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, 0, AttrNameLoc,
  961. ArgumentKind, ArgumentKindLoc,
  962. MatchingCType.release(), LayoutCompatible,
  963. MustBeNull, AttributeList::AS_GNU);
  964. }
  965. if (EndLoc)
  966. *EndLoc = T.getCloseLocation();
  967. }
  968. /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets
  969. /// of a C++11 attribute-specifier in a location where an attribute is not
  970. /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this
  971. /// situation.
  972. ///
  973. /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if
  974. /// this doesn't appear to actually be an attribute-specifier, and the caller
  975. /// should try to parse it.
  976. bool Parser::DiagnoseProhibitedCXX11Attribute() {
  977. assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square));
  978. switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) {
  979. case CAK_NotAttributeSpecifier:
  980. // No diagnostic: we're in Obj-C++11 and this is not actually an attribute.
  981. return false;
  982. case CAK_InvalidAttributeSpecifier:
  983. Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute);
  984. return false;
  985. case CAK_AttributeSpecifier:
  986. // Parse and discard the attributes.
  987. SourceLocation BeginLoc = ConsumeBracket();
  988. ConsumeBracket();
  989. SkipUntil(tok::r_square, /*StopAtSemi*/ false);
  990. assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied");
  991. SourceLocation EndLoc = ConsumeBracket();
  992. Diag(BeginLoc, diag::err_attributes_not_allowed)
  993. << SourceRange(BeginLoc, EndLoc);
  994. return true;
  995. }
  996. llvm_unreachable("All cases handled above.");
  997. }
  998. void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) {
  999. Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed)
  1000. << attrs.Range;
  1001. }
  1002. /// ParseDeclaration - Parse a full 'declaration', which consists of
  1003. /// declaration-specifiers, some number of declarators, and a semicolon.
  1004. /// 'Context' should be a Declarator::TheContext value. This returns the
  1005. /// location of the semicolon in DeclEnd.
  1006. ///
  1007. /// declaration: [C99 6.7]
  1008. /// block-declaration ->
  1009. /// simple-declaration
  1010. /// others [FIXME]
  1011. /// [C++] template-declaration
  1012. /// [C++] namespace-definition
  1013. /// [C++] using-directive
  1014. /// [C++] using-declaration
  1015. /// [C++11/C11] static_assert-declaration
  1016. /// others... [FIXME]
  1017. ///
  1018. Parser::DeclGroupPtrTy Parser::ParseDeclaration(StmtVector &Stmts,
  1019. unsigned Context,
  1020. SourceLocation &DeclEnd,
  1021. ParsedAttributesWithRange &attrs) {
  1022. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  1023. // Must temporarily exit the objective-c container scope for
  1024. // parsing c none objective-c decls.
  1025. ObjCDeclContextSwitch ObjCDC(*this);
  1026. Decl *SingleDecl = 0;
  1027. Decl *OwnedType = 0;
  1028. switch (Tok.getKind()) {
  1029. case tok::kw_template:
  1030. case tok::kw_export:
  1031. ProhibitAttributes(attrs);
  1032. SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd);
  1033. break;
  1034. case tok::kw_inline:
  1035. // Could be the start of an inline namespace. Allowed as an ext in C++03.
  1036. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace)) {
  1037. ProhibitAttributes(attrs);
  1038. SourceLocation InlineLoc = ConsumeToken();
  1039. SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc);
  1040. break;
  1041. }
  1042. return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs,
  1043. true);
  1044. case tok::kw_namespace:
  1045. ProhibitAttributes(attrs);
  1046. SingleDecl = ParseNamespace(Context, DeclEnd);
  1047. break;
  1048. case tok::kw_using:
  1049. SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(),
  1050. DeclEnd, attrs, &OwnedType);
  1051. break;
  1052. case tok::kw_static_assert:
  1053. case tok::kw__Static_assert:
  1054. ProhibitAttributes(attrs);
  1055. SingleDecl = ParseStaticAssertDeclaration(DeclEnd);
  1056. break;
  1057. default:
  1058. return ParseSimpleDeclaration(Stmts, Context, DeclEnd, attrs, true);
  1059. }
  1060. // This routine returns a DeclGroup, if the thing we parsed only contains a
  1061. // single decl, convert it now. Alias declarations can also declare a type;
  1062. // include that too if it is present.
  1063. return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType);
  1064. }
  1065. /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl]
  1066. /// declaration-specifiers init-declarator-list[opt] ';'
  1067. /// [C++11] attribute-specifier-seq decl-specifier-seq[opt]
  1068. /// init-declarator-list ';'
  1069. ///[C90/C++]init-declarator-list ';' [TODO]
  1070. /// [OMP] threadprivate-directive [TODO]
  1071. ///
  1072. /// for-range-declaration: [C++11 6.5p1: stmt.ranged]
  1073. /// attribute-specifier-seq[opt] type-specifier-seq declarator
  1074. ///
  1075. /// If RequireSemi is false, this does not check for a ';' at the end of the
  1076. /// declaration. If it is true, it checks for and eats it.
  1077. ///
  1078. /// If FRI is non-null, we might be parsing a for-range-declaration instead
  1079. /// of a simple-declaration. If we find that we are, we also parse the
  1080. /// for-range-initializer, and place it here.
  1081. Parser::DeclGroupPtrTy
  1082. Parser::ParseSimpleDeclaration(StmtVector &Stmts, unsigned Context,
  1083. SourceLocation &DeclEnd,
  1084. ParsedAttributesWithRange &attrs,
  1085. bool RequireSemi, ForRangeInit *FRI) {
  1086. // Parse the common declaration-specifiers piece.
  1087. ParsingDeclSpec DS(*this);
  1088. DS.takeAttributesFrom(attrs);
  1089. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
  1090. getDeclSpecContextFromDeclaratorContext(Context));
  1091. // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };"
  1092. // declaration-specifiers init-declarator-list[opt] ';'
  1093. if (Tok.is(tok::semi)) {
  1094. DeclEnd = Tok.getLocation();
  1095. if (RequireSemi) ConsumeToken();
  1096. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
  1097. DS);
  1098. DS.complete(TheDecl);
  1099. return Actions.ConvertDeclToDeclGroup(TheDecl);
  1100. }
  1101. return ParseDeclGroup(DS, Context, /*FunctionDefs=*/ false, &DeclEnd, FRI);
  1102. }
  1103. /// Returns true if this might be the start of a declarator, or a common typo
  1104. /// for a declarator.
  1105. bool Parser::MightBeDeclarator(unsigned Context) {
  1106. switch (Tok.getKind()) {
  1107. case tok::annot_cxxscope:
  1108. case tok::annot_template_id:
  1109. case tok::caret:
  1110. case tok::code_completion:
  1111. case tok::coloncolon:
  1112. case tok::ellipsis:
  1113. case tok::kw___attribute:
  1114. case tok::kw_operator:
  1115. case tok::l_paren:
  1116. case tok::star:
  1117. return true;
  1118. case tok::amp:
  1119. case tok::ampamp:
  1120. return getLangOpts().CPlusPlus;
  1121. case tok::l_square: // Might be an attribute on an unnamed bit-field.
  1122. return Context == Declarator::MemberContext && getLangOpts().CPlusPlus0x &&
  1123. NextToken().is(tok::l_square);
  1124. case tok::colon: // Might be a typo for '::' or an unnamed bit-field.
  1125. return Context == Declarator::MemberContext || getLangOpts().CPlusPlus;
  1126. case tok::identifier:
  1127. switch (NextToken().getKind()) {
  1128. case tok::code_completion:
  1129. case tok::coloncolon:
  1130. case tok::comma:
  1131. case tok::equal:
  1132. case tok::equalequal: // Might be a typo for '='.
  1133. case tok::kw_alignas:
  1134. case tok::kw_asm:
  1135. case tok::kw___attribute:
  1136. case tok::l_brace:
  1137. case tok::l_paren:
  1138. case tok::l_square:
  1139. case tok::less:
  1140. case tok::r_brace:
  1141. case tok::r_paren:
  1142. case tok::r_square:
  1143. case tok::semi:
  1144. return true;
  1145. case tok::colon:
  1146. // At namespace scope, 'identifier:' is probably a typo for 'identifier::'
  1147. // and in block scope it's probably a label. Inside a class definition,
  1148. // this is a bit-field.
  1149. return Context == Declarator::MemberContext ||
  1150. (getLangOpts().CPlusPlus && Context == Declarator::FileContext);
  1151. case tok::identifier: // Possible virt-specifier.
  1152. return getLangOpts().CPlusPlus0x && isCXX0XVirtSpecifier(NextToken());
  1153. default:
  1154. return false;
  1155. }
  1156. default:
  1157. return false;
  1158. }
  1159. }
  1160. /// Skip until we reach something which seems like a sensible place to pick
  1161. /// up parsing after a malformed declaration. This will sometimes stop sooner
  1162. /// than SkipUntil(tok::r_brace) would, but will never stop later.
  1163. void Parser::SkipMalformedDecl() {
  1164. while (true) {
  1165. switch (Tok.getKind()) {
  1166. case tok::l_brace:
  1167. // Skip until matching }, then stop. We've probably skipped over
  1168. // a malformed class or function definition or similar.
  1169. ConsumeBrace();
  1170. SkipUntil(tok::r_brace, /*StopAtSemi*/false);
  1171. if (Tok.is(tok::comma) || Tok.is(tok::l_brace) || Tok.is(tok::kw_try)) {
  1172. // This declaration isn't over yet. Keep skipping.
  1173. continue;
  1174. }
  1175. if (Tok.is(tok::semi))
  1176. ConsumeToken();
  1177. return;
  1178. case tok::l_square:
  1179. ConsumeBracket();
  1180. SkipUntil(tok::r_square, /*StopAtSemi*/false);
  1181. continue;
  1182. case tok::l_paren:
  1183. ConsumeParen();
  1184. SkipUntil(tok::r_paren, /*StopAtSemi*/false);
  1185. continue;
  1186. case tok::r_brace:
  1187. return;
  1188. case tok::semi:
  1189. ConsumeToken();
  1190. return;
  1191. case tok::kw_inline:
  1192. // 'inline namespace' at the start of a line is almost certainly
  1193. // a good place to pick back up parsing, except in an Objective-C
  1194. // @interface context.
  1195. if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) &&
  1196. (!ParsingInObjCContainer || CurParsedObjCImpl))
  1197. return;
  1198. break;
  1199. case tok::kw_namespace:
  1200. // 'namespace' at the start of a line is almost certainly a good
  1201. // place to pick back up parsing, except in an Objective-C
  1202. // @interface context.
  1203. if (Tok.isAtStartOfLine() &&
  1204. (!ParsingInObjCContainer || CurParsedObjCImpl))
  1205. return;
  1206. break;
  1207. case tok::at:
  1208. // @end is very much like } in Objective-C contexts.
  1209. if (NextToken().isObjCAtKeyword(tok::objc_end) &&
  1210. ParsingInObjCContainer)
  1211. return;
  1212. break;
  1213. case tok::minus:
  1214. case tok::plus:
  1215. // - and + probably start new method declarations in Objective-C contexts.
  1216. if (Tok.isAtStartOfLine() && ParsingInObjCContainer)
  1217. return;
  1218. break;
  1219. case tok::eof:
  1220. return;
  1221. default:
  1222. break;
  1223. }
  1224. ConsumeAnyToken();
  1225. }
  1226. }
  1227. /// ParseDeclGroup - Having concluded that this is either a function
  1228. /// definition or a group of object declarations, actually parse the
  1229. /// result.
  1230. Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS,
  1231. unsigned Context,
  1232. bool AllowFunctionDefinitions,
  1233. SourceLocation *DeclEnd,
  1234. ForRangeInit *FRI) {
  1235. // Parse the first declarator.
  1236. ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context));
  1237. ParseDeclarator(D);
  1238. // Bail out if the first declarator didn't seem well-formed.
  1239. if (!D.hasName() && !D.mayOmitIdentifier()) {
  1240. SkipMalformedDecl();
  1241. return DeclGroupPtrTy();
  1242. }
  1243. // Save late-parsed attributes for now; they need to be parsed in the
  1244. // appropriate function scope after the function Decl has been constructed.
  1245. LateParsedAttrList LateParsedAttrs;
  1246. if (D.isFunctionDeclarator())
  1247. MaybeParseGNUAttributes(D, &LateParsedAttrs);
  1248. // Check to see if we have a function *definition* which must have a body.
  1249. if (AllowFunctionDefinitions && D.isFunctionDeclarator() &&
  1250. // Look at the next token to make sure that this isn't a function
  1251. // declaration. We have to check this because __attribute__ might be the
  1252. // start of a function definition in GCC-extended K&R C.
  1253. !isDeclarationAfterDeclarator()) {
  1254. if (isStartOfFunctionDefinition(D)) {
  1255. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  1256. Diag(Tok, diag::err_function_declared_typedef);
  1257. // Recover by treating the 'typedef' as spurious.
  1258. DS.ClearStorageClassSpecs();
  1259. }
  1260. Decl *TheDecl =
  1261. ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs);
  1262. return Actions.ConvertDeclToDeclGroup(TheDecl);
  1263. }
  1264. if (isDeclarationSpecifier()) {
  1265. // If there is an invalid declaration specifier right after the function
  1266. // prototype, then we must be in a missing semicolon case where this isn't
  1267. // actually a body. Just fall through into the code that handles it as a
  1268. // prototype, and let the top-level code handle the erroneous declspec
  1269. // where it would otherwise expect a comma or semicolon.
  1270. } else {
  1271. Diag(Tok, diag::err_expected_fn_body);
  1272. SkipUntil(tok::semi);
  1273. return DeclGroupPtrTy();
  1274. }
  1275. }
  1276. if (ParseAsmAttributesAfterDeclarator(D))
  1277. return DeclGroupPtrTy();
  1278. // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we
  1279. // must parse and analyze the for-range-initializer before the declaration is
  1280. // analyzed.
  1281. if (FRI && Tok.is(tok::colon)) {
  1282. FRI->ColonLoc = ConsumeToken();
  1283. if (Tok.is(tok::l_brace))
  1284. FRI->RangeExpr = ParseBraceInitializer();
  1285. else
  1286. FRI->RangeExpr = ParseExpression();
  1287. Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
  1288. Actions.ActOnCXXForRangeDecl(ThisDecl);
  1289. Actions.FinalizeDeclaration(ThisDecl);
  1290. D.complete(ThisDecl);
  1291. return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, &ThisDecl, 1);
  1292. }
  1293. SmallVector<Decl *, 8> DeclsInGroup;
  1294. Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes(D);
  1295. if (LateParsedAttrs.size() > 0)
  1296. ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false);
  1297. D.complete(FirstDecl);
  1298. if (FirstDecl)
  1299. DeclsInGroup.push_back(FirstDecl);
  1300. bool ExpectSemi = Context != Declarator::ForContext;
  1301. // If we don't have a comma, it is either the end of the list (a ';') or an
  1302. // error, bail out.
  1303. while (Tok.is(tok::comma)) {
  1304. SourceLocation CommaLoc = ConsumeToken();
  1305. if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) {
  1306. // This comma was followed by a line-break and something which can't be
  1307. // the start of a declarator. The comma was probably a typo for a
  1308. // semicolon.
  1309. Diag(CommaLoc, diag::err_expected_semi_declaration)
  1310. << FixItHint::CreateReplacement(CommaLoc, ";");
  1311. ExpectSemi = false;
  1312. break;
  1313. }
  1314. // Parse the next declarator.
  1315. D.clear();
  1316. D.setCommaLoc(CommaLoc);
  1317. // Accept attributes in an init-declarator. In the first declarator in a
  1318. // declaration, these would be part of the declspec. In subsequent
  1319. // declarators, they become part of the declarator itself, so that they
  1320. // don't apply to declarators after *this* one. Examples:
  1321. // short __attribute__((common)) var; -> declspec
  1322. // short var __attribute__((common)); -> declarator
  1323. // short x, __attribute__((common)) var; -> declarator
  1324. MaybeParseGNUAttributes(D);
  1325. ParseDeclarator(D);
  1326. if (!D.isInvalidType()) {
  1327. Decl *ThisDecl = ParseDeclarationAfterDeclarator(D);
  1328. D.complete(ThisDecl);
  1329. if (ThisDecl)
  1330. DeclsInGroup.push_back(ThisDecl);
  1331. }
  1332. }
  1333. if (DeclEnd)
  1334. *DeclEnd = Tok.getLocation();
  1335. if (ExpectSemi &&
  1336. ExpectAndConsumeSemi(Context == Declarator::FileContext
  1337. ? diag::err_invalid_token_after_toplevel_declarator
  1338. : diag::err_expected_semi_declaration)) {
  1339. // Okay, there was no semicolon and one was expected. If we see a
  1340. // declaration specifier, just assume it was missing and continue parsing.
  1341. // Otherwise things are very confused and we skip to recover.
  1342. if (!isDeclarationSpecifier()) {
  1343. SkipUntil(tok::r_brace, true, true);
  1344. if (Tok.is(tok::semi))
  1345. ConsumeToken();
  1346. }
  1347. }
  1348. return Actions.FinalizeDeclaratorGroup(getCurScope(), DS,
  1349. DeclsInGroup.data(),
  1350. DeclsInGroup.size());
  1351. }
  1352. /// Parse an optional simple-asm-expr and attributes, and attach them to a
  1353. /// declarator. Returns true on an error.
  1354. bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) {
  1355. // If a simple-asm-expr is present, parse it.
  1356. if (Tok.is(tok::kw_asm)) {
  1357. SourceLocation Loc;
  1358. ExprResult AsmLabel(ParseSimpleAsm(&Loc));
  1359. if (AsmLabel.isInvalid()) {
  1360. SkipUntil(tok::semi, true, true);
  1361. return true;
  1362. }
  1363. D.setAsmLabel(AsmLabel.release());
  1364. D.SetRangeEnd(Loc);
  1365. }
  1366. MaybeParseGNUAttributes(D);
  1367. return false;
  1368. }
  1369. /// \brief Parse 'declaration' after parsing 'declaration-specifiers
  1370. /// declarator'. This method parses the remainder of the declaration
  1371. /// (including any attributes or initializer, among other things) and
  1372. /// finalizes the declaration.
  1373. ///
  1374. /// init-declarator: [C99 6.7]
  1375. /// declarator
  1376. /// declarator '=' initializer
  1377. /// [GNU] declarator simple-asm-expr[opt] attributes[opt]
  1378. /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer
  1379. /// [C++] declarator initializer[opt]
  1380. ///
  1381. /// [C++] initializer:
  1382. /// [C++] '=' initializer-clause
  1383. /// [C++] '(' expression-list ')'
  1384. /// [C++0x] '=' 'default' [TODO]
  1385. /// [C++0x] '=' 'delete'
  1386. /// [C++0x] braced-init-list
  1387. ///
  1388. /// According to the standard grammar, =default and =delete are function
  1389. /// definitions, but that definitely doesn't fit with the parser here.
  1390. ///
  1391. Decl *Parser::ParseDeclarationAfterDeclarator(Declarator &D,
  1392. const ParsedTemplateInfo &TemplateInfo) {
  1393. if (ParseAsmAttributesAfterDeclarator(D))
  1394. return 0;
  1395. return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
  1396. }
  1397. Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
  1398. const ParsedTemplateInfo &TemplateInfo) {
  1399. // Inform the current actions module that we just parsed this declarator.
  1400. Decl *ThisDecl = 0;
  1401. switch (TemplateInfo.Kind) {
  1402. case ParsedTemplateInfo::NonTemplate:
  1403. ThisDecl = Actions.ActOnDeclarator(getCurScope(), D);
  1404. break;
  1405. case ParsedTemplateInfo::Template:
  1406. case ParsedTemplateInfo::ExplicitSpecialization:
  1407. ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(),
  1408. MultiTemplateParamsArg(Actions,
  1409. TemplateInfo.TemplateParams->data(),
  1410. TemplateInfo.TemplateParams->size()),
  1411. D);
  1412. break;
  1413. case ParsedTemplateInfo::ExplicitInstantiation: {
  1414. DeclResult ThisRes
  1415. = Actions.ActOnExplicitInstantiation(getCurScope(),
  1416. TemplateInfo.ExternLoc,
  1417. TemplateInfo.TemplateLoc,
  1418. D);
  1419. if (ThisRes.isInvalid()) {
  1420. SkipUntil(tok::semi, true, true);
  1421. return 0;
  1422. }
  1423. ThisDecl = ThisRes.get();
  1424. break;
  1425. }
  1426. }
  1427. bool TypeContainsAuto =
  1428. D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
  1429. // Parse declarator '=' initializer.
  1430. // If a '==' or '+=' is found, suggest a fixit to '='.
  1431. if (isTokenEqualOrEqualTypo()) {
  1432. ConsumeToken();
  1433. if (Tok.is(tok::kw_delete)) {
  1434. if (D.isFunctionDeclarator())
  1435. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  1436. << 1 /* delete */;
  1437. else
  1438. Diag(ConsumeToken(), diag::err_deleted_non_function);
  1439. } else if (Tok.is(tok::kw_default)) {
  1440. if (D.isFunctionDeclarator())
  1441. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  1442. << 0 /* default */;
  1443. else
  1444. Diag(ConsumeToken(), diag::err_default_special_members);
  1445. } else {
  1446. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1447. EnterScope(0);
  1448. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  1449. }
  1450. if (Tok.is(tok::code_completion)) {
  1451. Actions.CodeCompleteInitializer(getCurScope(), ThisDecl);
  1452. Actions.FinalizeDeclaration(ThisDecl);
  1453. cutOffParsing();
  1454. return 0;
  1455. }
  1456. ExprResult Init(ParseInitializer());
  1457. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1458. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1459. ExitScope();
  1460. }
  1461. if (Init.isInvalid()) {
  1462. SkipUntil(tok::comma, true, true);
  1463. Actions.ActOnInitializerError(ThisDecl);
  1464. } else
  1465. Actions.AddInitializerToDecl(ThisDecl, Init.take(),
  1466. /*DirectInit=*/false, TypeContainsAuto);
  1467. }
  1468. } else if (Tok.is(tok::l_paren)) {
  1469. // Parse C++ direct initializer: '(' expression-list ')'
  1470. BalancedDelimiterTracker T(*this, tok::l_paren);
  1471. T.consumeOpen();
  1472. ExprVector Exprs(Actions);
  1473. CommaLocsTy CommaLocs;
  1474. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1475. EnterScope(0);
  1476. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  1477. }
  1478. if (ParseExpressionList(Exprs, CommaLocs)) {
  1479. SkipUntil(tok::r_paren);
  1480. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1481. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1482. ExitScope();
  1483. }
  1484. } else {
  1485. // Match the ')'.
  1486. T.consumeClose();
  1487. assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() &&
  1488. "Unexpected number of commas!");
  1489. if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) {
  1490. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1491. ExitScope();
  1492. }
  1493. ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(),
  1494. T.getCloseLocation(),
  1495. Exprs);
  1496. Actions.AddInitializerToDecl(ThisDecl, Initializer.take(),
  1497. /*DirectInit=*/true, TypeContainsAuto);
  1498. }
  1499. } else if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace) &&
  1500. (!CurParsedObjCImpl || !D.isFunctionDeclarator())) {
  1501. // Parse C++0x braced-init-list.
  1502. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  1503. if (D.getCXXScopeSpec().isSet()) {
  1504. EnterScope(0);
  1505. Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl);
  1506. }
  1507. ExprResult Init(ParseBraceInitializer());
  1508. if (D.getCXXScopeSpec().isSet()) {
  1509. Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl);
  1510. ExitScope();
  1511. }
  1512. if (Init.isInvalid()) {
  1513. Actions.ActOnInitializerError(ThisDecl);
  1514. } else
  1515. Actions.AddInitializerToDecl(ThisDecl, Init.take(),
  1516. /*DirectInit=*/true, TypeContainsAuto);
  1517. } else {
  1518. Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto);
  1519. }
  1520. Actions.FinalizeDeclaration(ThisDecl);
  1521. return ThisDecl;
  1522. }
  1523. /// ParseSpecifierQualifierList
  1524. /// specifier-qualifier-list:
  1525. /// type-specifier specifier-qualifier-list[opt]
  1526. /// type-qualifier specifier-qualifier-list[opt]
  1527. /// [GNU] attributes specifier-qualifier-list[opt]
  1528. ///
  1529. void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS,
  1530. DeclSpecContext DSC) {
  1531. /// specifier-qualifier-list is a subset of declaration-specifiers. Just
  1532. /// parse declaration-specifiers and complain about extra stuff.
  1533. /// TODO: diagnose attribute-specifiers and alignment-specifiers.
  1534. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC);
  1535. // Validate declspec for type-name.
  1536. unsigned Specs = DS.getParsedSpecifiers();
  1537. if ((DSC == DSC_type_specifier || DSC == DSC_trailing) &&
  1538. !DS.hasTypeSpecifier()) {
  1539. Diag(Tok, diag::err_expected_type);
  1540. DS.SetTypeSpecError();
  1541. } else if (Specs == DeclSpec::PQ_None && !DS.getNumProtocolQualifiers() &&
  1542. !DS.hasAttributes()) {
  1543. Diag(Tok, diag::err_typename_requires_specqual);
  1544. if (!DS.hasTypeSpecifier())
  1545. DS.SetTypeSpecError();
  1546. }
  1547. // Issue diagnostic and remove storage class if present.
  1548. if (Specs & DeclSpec::PQ_StorageClassSpecifier) {
  1549. if (DS.getStorageClassSpecLoc().isValid())
  1550. Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass);
  1551. else
  1552. Diag(DS.getThreadSpecLoc(), diag::err_typename_invalid_storageclass);
  1553. DS.ClearStorageClassSpecs();
  1554. }
  1555. // Issue diagnostic and remove function specfier if present.
  1556. if (Specs & DeclSpec::PQ_FunctionSpecifier) {
  1557. if (DS.isInlineSpecified())
  1558. Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec);
  1559. if (DS.isVirtualSpecified())
  1560. Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec);
  1561. if (DS.isExplicitSpecified())
  1562. Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec);
  1563. DS.ClearFunctionSpecs();
  1564. }
  1565. // Issue diagnostic and remove constexpr specfier if present.
  1566. if (DS.isConstexprSpecified()) {
  1567. Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr);
  1568. DS.ClearConstexprSpec();
  1569. }
  1570. }
  1571. /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the
  1572. /// specified token is valid after the identifier in a declarator which
  1573. /// immediately follows the declspec. For example, these things are valid:
  1574. ///
  1575. /// int x [ 4]; // direct-declarator
  1576. /// int x ( int y); // direct-declarator
  1577. /// int(int x ) // direct-declarator
  1578. /// int x ; // simple-declaration
  1579. /// int x = 17; // init-declarator-list
  1580. /// int x , y; // init-declarator-list
  1581. /// int x __asm__ ("foo"); // init-declarator-list
  1582. /// int x : 4; // struct-declarator
  1583. /// int x { 5}; // C++'0x unified initializers
  1584. ///
  1585. /// This is not, because 'x' does not immediately follow the declspec (though
  1586. /// ')' happens to be valid anyway).
  1587. /// int (x)
  1588. ///
  1589. static bool isValidAfterIdentifierInDeclarator(const Token &T) {
  1590. return T.is(tok::l_square) || T.is(tok::l_paren) || T.is(tok::r_paren) ||
  1591. T.is(tok::semi) || T.is(tok::comma) || T.is(tok::equal) ||
  1592. T.is(tok::kw_asm) || T.is(tok::l_brace) || T.is(tok::colon);
  1593. }
  1594. /// ParseImplicitInt - This method is called when we have an non-typename
  1595. /// identifier in a declspec (which normally terminates the decl spec) when
  1596. /// the declspec has no type specifier. In this case, the declspec is either
  1597. /// malformed or is "implicit int" (in K&R and C89).
  1598. ///
  1599. /// This method handles diagnosing this prettily and returns false if the
  1600. /// declspec is done being processed. If it recovers and thinks there may be
  1601. /// other pieces of declspec after it, it returns true.
  1602. ///
  1603. bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
  1604. const ParsedTemplateInfo &TemplateInfo,
  1605. AccessSpecifier AS, DeclSpecContext DSC) {
  1606. assert(Tok.is(tok::identifier) && "should have identifier");
  1607. SourceLocation Loc = Tok.getLocation();
  1608. // If we see an identifier that is not a type name, we normally would
  1609. // parse it as the identifer being declared. However, when a typename
  1610. // is typo'd or the definition is not included, this will incorrectly
  1611. // parse the typename as the identifier name and fall over misparsing
  1612. // later parts of the diagnostic.
  1613. //
  1614. // As such, we try to do some look-ahead in cases where this would
  1615. // otherwise be an "implicit-int" case to see if this is invalid. For
  1616. // example: "static foo_t x = 4;" In this case, if we parsed foo_t as
  1617. // an identifier with implicit int, we'd get a parse error because the
  1618. // next token is obviously invalid for a type. Parse these as a case
  1619. // with an invalid type specifier.
  1620. assert(!DS.hasTypeSpecifier() && "Type specifier checked above");
  1621. // Since we know that this either implicit int (which is rare) or an
  1622. // error, do lookahead to try to do better recovery. This never applies
  1623. // within a type specifier. Outside of C++, we allow this even if the
  1624. // language doesn't "officially" support implicit int -- we support
  1625. // implicit int as an extension in C99 and C11. Allegedly, MS also
  1626. // supports implicit int in C++ mode.
  1627. if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
  1628. (!getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt) &&
  1629. isValidAfterIdentifierInDeclarator(NextToken())) {
  1630. // If this token is valid for implicit int, e.g. "static x = 4", then
  1631. // we just avoid eating the identifier, so it will be parsed as the
  1632. // identifier in the declarator.
  1633. return false;
  1634. }
  1635. if (getLangOpts().CPlusPlus &&
  1636. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  1637. // Don't require a type specifier if we have the 'auto' storage class
  1638. // specifier in C++98 -- we'll promote it to a type specifier.
  1639. return false;
  1640. }
  1641. // Otherwise, if we don't consume this token, we are going to emit an
  1642. // error anyway. Try to recover from various common problems. Check
  1643. // to see if this was a reference to a tag name without a tag specified.
  1644. // This is a common problem in C (saying 'foo' instead of 'struct foo').
  1645. //
  1646. // C++ doesn't need this, and isTagName doesn't take SS.
  1647. if (SS == 0) {
  1648. const char *TagName = 0, *FixitTagName = 0;
  1649. tok::TokenKind TagKind = tok::unknown;
  1650. switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) {
  1651. default: break;
  1652. case DeclSpec::TST_enum:
  1653. TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break;
  1654. case DeclSpec::TST_union:
  1655. TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break;
  1656. case DeclSpec::TST_struct:
  1657. TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break;
  1658. case DeclSpec::TST_class:
  1659. TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break;
  1660. }
  1661. if (TagName) {
  1662. IdentifierInfo *TokenName = Tok.getIdentifierInfo();
  1663. LookupResult R(Actions, TokenName, SourceLocation(),
  1664. Sema::LookupOrdinaryName);
  1665. Diag(Loc, diag::err_use_of_tag_name_without_tag)
  1666. << TokenName << TagName << getLangOpts().CPlusPlus
  1667. << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName);
  1668. if (Actions.LookupParsedName(R, getCurScope(), SS)) {
  1669. for (LookupResult::iterator I = R.begin(), IEnd = R.end();
  1670. I != IEnd; ++I)
  1671. Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  1672. << TokenName << TagName;
  1673. }
  1674. // Parse this as a tag as if the missing tag were present.
  1675. if (TagKind == tok::kw_enum)
  1676. ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal);
  1677. else
  1678. ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS,
  1679. /*EnteringContext*/ false, DSC_normal);
  1680. return true;
  1681. }
  1682. }
  1683. // Determine whether this identifier could plausibly be the name of something
  1684. // being declared (with a missing type).
  1685. if (DSC != DSC_type_specifier && DSC != DSC_trailing &&
  1686. (!SS || DSC == DSC_top_level || DSC == DSC_class)) {
  1687. // Look ahead to the next token to try to figure out what this declaration
  1688. // was supposed to be.
  1689. switch (NextToken().getKind()) {
  1690. case tok::comma:
  1691. case tok::equal:
  1692. case tok::kw_asm:
  1693. case tok::l_brace:
  1694. case tok::l_square:
  1695. case tok::semi:
  1696. // This looks like a variable declaration. The type is probably missing.
  1697. // We're done parsing decl-specifiers.
  1698. return false;
  1699. case tok::l_paren: {
  1700. // static x(4); // 'x' is not a type
  1701. // x(int n); // 'x' is not a type
  1702. // x (*p)[]; // 'x' is a type
  1703. //
  1704. // Since we're in an error case (or the rare 'implicit int in C++' MS
  1705. // extension), we can afford to perform a tentative parse to determine
  1706. // which case we're in.
  1707. TentativeParsingAction PA(*this);
  1708. ConsumeToken();
  1709. TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false);
  1710. PA.Revert();
  1711. if (TPR == TPResult::False())
  1712. return false;
  1713. // The identifier is followed by a parenthesized declarator.
  1714. // It's supposed to be a type.
  1715. break;
  1716. }
  1717. default:
  1718. // This is probably supposed to be a type. This includes cases like:
  1719. // int f(itn);
  1720. // struct S { unsinged : 4; };
  1721. break;
  1722. }
  1723. }
  1724. // This is almost certainly an invalid type name. Let the action emit a
  1725. // diagnostic and attempt to recover.
  1726. ParsedType T;
  1727. IdentifierInfo *II = Tok.getIdentifierInfo();
  1728. if (Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T)) {
  1729. // The action emitted a diagnostic, so we don't have to.
  1730. if (T) {
  1731. // The action has suggested that the type T could be used. Set that as
  1732. // the type in the declaration specifiers, consume the would-be type
  1733. // name token, and we're done.
  1734. const char *PrevSpec;
  1735. unsigned DiagID;
  1736. DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T);
  1737. DS.SetRangeEnd(Tok.getLocation());
  1738. ConsumeToken();
  1739. // There may be other declaration specifiers after this.
  1740. return true;
  1741. } else if (II != Tok.getIdentifierInfo()) {
  1742. // If no type was suggested, the correction is to a keyword
  1743. Tok.setKind(II->getTokenID());
  1744. // There may be other declaration specifiers after this.
  1745. return true;
  1746. }
  1747. // Fall through; the action had no suggestion for us.
  1748. } else {
  1749. // The action did not emit a diagnostic, so emit one now.
  1750. SourceRange R;
  1751. if (SS) R = SS->getRange();
  1752. Diag(Loc, diag::err_unknown_typename) << Tok.getIdentifierInfo() << R;
  1753. }
  1754. // Mark this as an error.
  1755. DS.SetTypeSpecError();
  1756. DS.SetRangeEnd(Tok.getLocation());
  1757. ConsumeToken();
  1758. // TODO: Could inject an invalid typedef decl in an enclosing scope to
  1759. // avoid rippling error messages on subsequent uses of the same type,
  1760. // could be useful if #include was forgotten.
  1761. return false;
  1762. }
  1763. /// \brief Determine the declaration specifier context from the declarator
  1764. /// context.
  1765. ///
  1766. /// \param Context the declarator context, which is one of the
  1767. /// Declarator::TheContext enumerator values.
  1768. Parser::DeclSpecContext
  1769. Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) {
  1770. if (Context == Declarator::MemberContext)
  1771. return DSC_class;
  1772. if (Context == Declarator::FileContext)
  1773. return DSC_top_level;
  1774. if (Context == Declarator::TrailingReturnContext)
  1775. return DSC_trailing;
  1776. return DSC_normal;
  1777. }
  1778. /// ParseAlignArgument - Parse the argument to an alignment-specifier.
  1779. ///
  1780. /// FIXME: Simply returns an alignof() expression if the argument is a
  1781. /// type. Ideally, the type should be propagated directly into Sema.
  1782. ///
  1783. /// [C11] type-id
  1784. /// [C11] constant-expression
  1785. /// [C++0x] type-id ...[opt]
  1786. /// [C++0x] assignment-expression ...[opt]
  1787. ExprResult Parser::ParseAlignArgument(SourceLocation Start,
  1788. SourceLocation &EllipsisLoc) {
  1789. ExprResult ER;
  1790. if (isTypeIdInParens()) {
  1791. SourceLocation TypeLoc = Tok.getLocation();
  1792. ParsedType Ty = ParseTypeName().get();
  1793. SourceRange TypeRange(Start, Tok.getLocation());
  1794. ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true,
  1795. Ty.getAsOpaquePtr(), TypeRange);
  1796. } else
  1797. ER = ParseConstantExpression();
  1798. if (getLangOpts().CPlusPlus0x && Tok.is(tok::ellipsis))
  1799. EllipsisLoc = ConsumeToken();
  1800. return ER;
  1801. }
  1802. /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the
  1803. /// attribute to Attrs.
  1804. ///
  1805. /// alignment-specifier:
  1806. /// [C11] '_Alignas' '(' type-id ')'
  1807. /// [C11] '_Alignas' '(' constant-expression ')'
  1808. /// [C++0x] 'alignas' '(' type-id ...[opt] ')'
  1809. /// [C++0x] 'alignas' '(' assignment-expression ...[opt] ')'
  1810. void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs,
  1811. SourceLocation *endLoc) {
  1812. assert((Tok.is(tok::kw_alignas) || Tok.is(tok::kw__Alignas)) &&
  1813. "Not an alignment-specifier!");
  1814. SourceLocation KWLoc = Tok.getLocation();
  1815. ConsumeToken();
  1816. BalancedDelimiterTracker T(*this, tok::l_paren);
  1817. if (T.expectAndConsume(diag::err_expected_lparen))
  1818. return;
  1819. SourceLocation EllipsisLoc;
  1820. ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc);
  1821. if (ArgExpr.isInvalid()) {
  1822. SkipUntil(tok::r_paren);
  1823. return;
  1824. }
  1825. T.consumeClose();
  1826. if (endLoc)
  1827. *endLoc = T.getCloseLocation();
  1828. // FIXME: Handle pack-expansions here.
  1829. if (EllipsisLoc.isValid()) {
  1830. Diag(EllipsisLoc, diag::err_alignas_pack_exp_unsupported);
  1831. return;
  1832. }
  1833. ExprVector ArgExprs(Actions);
  1834. ArgExprs.push_back(ArgExpr.release());
  1835. // FIXME: This should not be GNU, but we since the attribute used is
  1836. // based on the spelling, and there is no true spelling for
  1837. // C++11 attributes, this isn't accepted.
  1838. Attrs.addNew(PP.getIdentifierInfo("aligned"), KWLoc, 0, KWLoc,
  1839. 0, T.getOpenLocation(), ArgExprs.take(), 1,
  1840. AttributeList::AS_GNU);
  1841. }
  1842. /// ParseDeclarationSpecifiers
  1843. /// declaration-specifiers: [C99 6.7]
  1844. /// storage-class-specifier declaration-specifiers[opt]
  1845. /// type-specifier declaration-specifiers[opt]
  1846. /// [C99] function-specifier declaration-specifiers[opt]
  1847. /// [C11] alignment-specifier declaration-specifiers[opt]
  1848. /// [GNU] attributes declaration-specifiers[opt]
  1849. /// [Clang] '__module_private__' declaration-specifiers[opt]
  1850. ///
  1851. /// storage-class-specifier: [C99 6.7.1]
  1852. /// 'typedef'
  1853. /// 'extern'
  1854. /// 'static'
  1855. /// 'auto'
  1856. /// 'register'
  1857. /// [C++] 'mutable'
  1858. /// [GNU] '__thread'
  1859. /// function-specifier: [C99 6.7.4]
  1860. /// [C99] 'inline'
  1861. /// [C++] 'virtual'
  1862. /// [C++] 'explicit'
  1863. /// [OpenCL] '__kernel'
  1864. /// 'friend': [C++ dcl.friend]
  1865. /// 'constexpr': [C++0x dcl.constexpr]
  1866. ///
  1867. void Parser::ParseDeclarationSpecifiers(DeclSpec &DS,
  1868. const ParsedTemplateInfo &TemplateInfo,
  1869. AccessSpecifier AS,
  1870. DeclSpecContext DSContext,
  1871. LateParsedAttrList *LateAttrs) {
  1872. if (DS.getSourceRange().isInvalid()) {
  1873. DS.SetRangeStart(Tok.getLocation());
  1874. DS.SetRangeEnd(Tok.getLocation());
  1875. }
  1876. bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level);
  1877. bool AttrsLastTime = false;
  1878. ParsedAttributesWithRange attrs(AttrFactory);
  1879. while (1) {
  1880. bool isInvalid = false;
  1881. const char *PrevSpec = 0;
  1882. unsigned DiagID = 0;
  1883. SourceLocation Loc = Tok.getLocation();
  1884. switch (Tok.getKind()) {
  1885. default:
  1886. DoneWithDeclSpec:
  1887. if (!AttrsLastTime)
  1888. ProhibitAttributes(attrs);
  1889. else
  1890. DS.takeAttributesFrom(attrs);
  1891. // If this is not a declaration specifier token, we're done reading decl
  1892. // specifiers. First verify that DeclSpec's are consistent.
  1893. DS.Finish(Diags, PP);
  1894. return;
  1895. case tok::l_square:
  1896. case tok::kw_alignas:
  1897. if (!isCXX11AttributeSpecifier())
  1898. goto DoneWithDeclSpec;
  1899. ProhibitAttributes(attrs);
  1900. // FIXME: It would be good to recover by accepting the attributes,
  1901. // but attempting to do that now would cause serious
  1902. // madness in terms of diagnostics.
  1903. attrs.clear();
  1904. attrs.Range = SourceRange();
  1905. ParseCXX11Attributes(attrs);
  1906. AttrsLastTime = true;
  1907. continue;
  1908. case tok::code_completion: {
  1909. Sema::ParserCompletionContext CCC = Sema::PCC_Namespace;
  1910. if (DS.hasTypeSpecifier()) {
  1911. bool AllowNonIdentifiers
  1912. = (getCurScope()->getFlags() & (Scope::ControlScope |
  1913. Scope::BlockScope |
  1914. Scope::TemplateParamScope |
  1915. Scope::FunctionPrototypeScope |
  1916. Scope::AtCatchScope)) == 0;
  1917. bool AllowNestedNameSpecifiers
  1918. = DSContext == DSC_top_level ||
  1919. (DSContext == DSC_class && DS.isFriendSpecified());
  1920. Actions.CodeCompleteDeclSpec(getCurScope(), DS,
  1921. AllowNonIdentifiers,
  1922. AllowNestedNameSpecifiers);
  1923. return cutOffParsing();
  1924. }
  1925. if (getCurScope()->getFnParent() || getCurScope()->getBlockParent())
  1926. CCC = Sema::PCC_LocalDeclarationSpecifiers;
  1927. else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate)
  1928. CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate
  1929. : Sema::PCC_Template;
  1930. else if (DSContext == DSC_class)
  1931. CCC = Sema::PCC_Class;
  1932. else if (CurParsedObjCImpl)
  1933. CCC = Sema::PCC_ObjCImplementation;
  1934. Actions.CodeCompleteOrdinaryName(getCurScope(), CCC);
  1935. return cutOffParsing();
  1936. }
  1937. case tok::coloncolon: // ::foo::bar
  1938. // C++ scope specifier. Annotate and loop, or bail out on error.
  1939. if (TryAnnotateCXXScopeToken(true)) {
  1940. if (!DS.hasTypeSpecifier())
  1941. DS.SetTypeSpecError();
  1942. goto DoneWithDeclSpec;
  1943. }
  1944. if (Tok.is(tok::coloncolon)) // ::new or ::delete
  1945. goto DoneWithDeclSpec;
  1946. continue;
  1947. case tok::annot_cxxscope: {
  1948. if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector())
  1949. goto DoneWithDeclSpec;
  1950. CXXScopeSpec SS;
  1951. Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
  1952. Tok.getAnnotationRange(),
  1953. SS);
  1954. // We are looking for a qualified typename.
  1955. Token Next = NextToken();
  1956. if (Next.is(tok::annot_template_id) &&
  1957. static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue())
  1958. ->Kind == TNK_Type_template) {
  1959. // We have a qualified template-id, e.g., N::A<int>
  1960. // C++ [class.qual]p2:
  1961. // In a lookup in which the constructor is an acceptable lookup
  1962. // result and the nested-name-specifier nominates a class C:
  1963. //
  1964. // - if the name specified after the
  1965. // nested-name-specifier, when looked up in C, is the
  1966. // injected-class-name of C (Clause 9), or
  1967. //
  1968. // - if the name specified after the nested-name-specifier
  1969. // is the same as the identifier or the
  1970. // simple-template-id's template-name in the last
  1971. // component of the nested-name-specifier,
  1972. //
  1973. // the name is instead considered to name the constructor of
  1974. // class C.
  1975. //
  1976. // Thus, if the template-name is actually the constructor
  1977. // name, then the code is ill-formed; this interpretation is
  1978. // reinforced by the NAD status of core issue 635.
  1979. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
  1980. if ((DSContext == DSC_top_level ||
  1981. (DSContext == DSC_class && DS.isFriendSpecified())) &&
  1982. TemplateId->Name &&
  1983. Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
  1984. if (isConstructorDeclarator()) {
  1985. // The user meant this to be an out-of-line constructor
  1986. // definition, but template arguments are not allowed
  1987. // there. Just allow this as a constructor; we'll
  1988. // complain about it later.
  1989. goto DoneWithDeclSpec;
  1990. }
  1991. // The user meant this to name a type, but it actually names
  1992. // a constructor with some extraneous template
  1993. // arguments. Complain, then parse it as a type as the user
  1994. // intended.
  1995. Diag(TemplateId->TemplateNameLoc,
  1996. diag::err_out_of_line_template_id_names_constructor)
  1997. << TemplateId->Name;
  1998. }
  1999. DS.getTypeSpecScope() = SS;
  2000. ConsumeToken(); // The C++ scope.
  2001. assert(Tok.is(tok::annot_template_id) &&
  2002. "ParseOptionalCXXScopeSpecifier not working");
  2003. AnnotateTemplateIdTokenAsType();
  2004. continue;
  2005. }
  2006. if (Next.is(tok::annot_typename)) {
  2007. DS.getTypeSpecScope() = SS;
  2008. ConsumeToken(); // The C++ scope.
  2009. if (Tok.getAnnotationValue()) {
  2010. ParsedType T = getTypeAnnotation(Tok);
  2011. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename,
  2012. Tok.getAnnotationEndLoc(),
  2013. PrevSpec, DiagID, T);
  2014. }
  2015. else
  2016. DS.SetTypeSpecError();
  2017. DS.SetRangeEnd(Tok.getAnnotationEndLoc());
  2018. ConsumeToken(); // The typename
  2019. }
  2020. if (Next.isNot(tok::identifier))
  2021. goto DoneWithDeclSpec;
  2022. // If we're in a context where the identifier could be a class name,
  2023. // check whether this is a constructor declaration.
  2024. if ((DSContext == DSC_top_level ||
  2025. (DSContext == DSC_class && DS.isFriendSpecified())) &&
  2026. Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(),
  2027. &SS)) {
  2028. if (isConstructorDeclarator())
  2029. goto DoneWithDeclSpec;
  2030. // As noted in C++ [class.qual]p2 (cited above), when the name
  2031. // of the class is qualified in a context where it could name
  2032. // a constructor, its a constructor name. However, we've
  2033. // looked at the declarator, and the user probably meant this
  2034. // to be a type. Complain that it isn't supposed to be treated
  2035. // as a type, then proceed to parse it as a type.
  2036. Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor)
  2037. << Next.getIdentifierInfo();
  2038. }
  2039. ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(),
  2040. Next.getLocation(),
  2041. getCurScope(), &SS,
  2042. false, false, ParsedType(),
  2043. /*IsCtorOrDtorName=*/false,
  2044. /*NonTrivialSourceInfo=*/true);
  2045. // If the referenced identifier is not a type, then this declspec is
  2046. // erroneous: We already checked about that it has no type specifier, and
  2047. // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the
  2048. // typename.
  2049. if (TypeRep == 0) {
  2050. ConsumeToken(); // Eat the scope spec so the identifier is current.
  2051. if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext)) continue;
  2052. goto DoneWithDeclSpec;
  2053. }
  2054. DS.getTypeSpecScope() = SS;
  2055. ConsumeToken(); // The C++ scope.
  2056. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2057. DiagID, TypeRep);
  2058. if (isInvalid)
  2059. break;
  2060. DS.SetRangeEnd(Tok.getLocation());
  2061. ConsumeToken(); // The typename.
  2062. continue;
  2063. }
  2064. case tok::annot_typename: {
  2065. if (Tok.getAnnotationValue()) {
  2066. ParsedType T = getTypeAnnotation(Tok);
  2067. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2068. DiagID, T);
  2069. } else
  2070. DS.SetTypeSpecError();
  2071. if (isInvalid)
  2072. break;
  2073. DS.SetRangeEnd(Tok.getAnnotationEndLoc());
  2074. ConsumeToken(); // The typename
  2075. // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
  2076. // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
  2077. // Objective-C interface.
  2078. if (Tok.is(tok::less) && getLangOpts().ObjC1)
  2079. ParseObjCProtocolQualifiers(DS);
  2080. continue;
  2081. }
  2082. case tok::kw___is_signed:
  2083. // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang
  2084. // typically treats it as a trait. If we see __is_signed as it appears
  2085. // in libstdc++, e.g.,
  2086. //
  2087. // static const bool __is_signed;
  2088. //
  2089. // then treat __is_signed as an identifier rather than as a keyword.
  2090. if (DS.getTypeSpecType() == TST_bool &&
  2091. DS.getTypeQualifiers() == DeclSpec::TQ_const &&
  2092. DS.getStorageClassSpec() == DeclSpec::SCS_static) {
  2093. Tok.getIdentifierInfo()->RevertTokenIDToIdentifier();
  2094. Tok.setKind(tok::identifier);
  2095. }
  2096. // We're done with the declaration-specifiers.
  2097. goto DoneWithDeclSpec;
  2098. // typedef-name
  2099. case tok::kw_decltype:
  2100. case tok::identifier: {
  2101. // In C++, check to see if this is a scope specifier like foo::bar::, if
  2102. // so handle it as such. This is important for ctor parsing.
  2103. if (getLangOpts().CPlusPlus) {
  2104. if (TryAnnotateCXXScopeToken(true)) {
  2105. if (!DS.hasTypeSpecifier())
  2106. DS.SetTypeSpecError();
  2107. goto DoneWithDeclSpec;
  2108. }
  2109. if (!Tok.is(tok::identifier))
  2110. continue;
  2111. }
  2112. // This identifier can only be a typedef name if we haven't already seen
  2113. // a type-specifier. Without this check we misparse:
  2114. // typedef int X; struct Y { short X; }; as 'short int'.
  2115. if (DS.hasTypeSpecifier())
  2116. goto DoneWithDeclSpec;
  2117. // Check for need to substitute AltiVec keyword tokens.
  2118. if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid))
  2119. break;
  2120. // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not
  2121. // allow the use of a typedef name as a type specifier.
  2122. if (DS.isTypeAltiVecVector())
  2123. goto DoneWithDeclSpec;
  2124. ParsedType TypeRep =
  2125. Actions.getTypeName(*Tok.getIdentifierInfo(),
  2126. Tok.getLocation(), getCurScope());
  2127. // If this is not a typedef name, don't parse it as part of the declspec,
  2128. // it must be an implicit int or an error.
  2129. if (!TypeRep) {
  2130. if (ParseImplicitInt(DS, 0, TemplateInfo, AS, DSContext)) continue;
  2131. goto DoneWithDeclSpec;
  2132. }
  2133. // If we're in a context where the identifier could be a class name,
  2134. // check whether this is a constructor declaration.
  2135. if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
  2136. Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) &&
  2137. isConstructorDeclarator())
  2138. goto DoneWithDeclSpec;
  2139. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec,
  2140. DiagID, TypeRep);
  2141. if (isInvalid)
  2142. break;
  2143. DS.SetRangeEnd(Tok.getLocation());
  2144. ConsumeToken(); // The identifier
  2145. // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
  2146. // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
  2147. // Objective-C interface.
  2148. if (Tok.is(tok::less) && getLangOpts().ObjC1)
  2149. ParseObjCProtocolQualifiers(DS);
  2150. // Need to support trailing type qualifiers (e.g. "id<p> const").
  2151. // If a type specifier follows, it will be diagnosed elsewhere.
  2152. continue;
  2153. }
  2154. // type-name
  2155. case tok::annot_template_id: {
  2156. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  2157. if (TemplateId->Kind != TNK_Type_template) {
  2158. // This template-id does not refer to a type name, so we're
  2159. // done with the type-specifiers.
  2160. goto DoneWithDeclSpec;
  2161. }
  2162. // If we're in a context where the template-id could be a
  2163. // constructor name or specialization, check whether this is a
  2164. // constructor declaration.
  2165. if (getLangOpts().CPlusPlus && DSContext == DSC_class &&
  2166. Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) &&
  2167. isConstructorDeclarator())
  2168. goto DoneWithDeclSpec;
  2169. // Turn the template-id annotation token into a type annotation
  2170. // token, then try again to parse it as a type-specifier.
  2171. AnnotateTemplateIdTokenAsType();
  2172. continue;
  2173. }
  2174. // GNU attributes support.
  2175. case tok::kw___attribute:
  2176. ParseGNUAttributes(DS.getAttributes(), 0, LateAttrs);
  2177. continue;
  2178. // Microsoft declspec support.
  2179. case tok::kw___declspec:
  2180. ParseMicrosoftDeclSpec(DS.getAttributes());
  2181. continue;
  2182. // Microsoft single token adornments.
  2183. case tok::kw___forceinline: {
  2184. isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
  2185. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  2186. SourceLocation AttrNameLoc = ConsumeToken();
  2187. // FIXME: This does not work correctly if it is set to be a declspec
  2188. // attribute, and a GNU attribute is simply incorrect.
  2189. DS.getAttributes().addNew(AttrName, AttrNameLoc, 0, AttrNameLoc, 0,
  2190. SourceLocation(), 0, 0, AttributeList::AS_GNU);
  2191. continue;
  2192. }
  2193. case tok::kw___ptr64:
  2194. case tok::kw___ptr32:
  2195. case tok::kw___w64:
  2196. case tok::kw___cdecl:
  2197. case tok::kw___stdcall:
  2198. case tok::kw___fastcall:
  2199. case tok::kw___thiscall:
  2200. case tok::kw___unaligned:
  2201. ParseMicrosoftTypeAttributes(DS.getAttributes());
  2202. continue;
  2203. // Borland single token adornments.
  2204. case tok::kw___pascal:
  2205. ParseBorlandTypeAttributes(DS.getAttributes());
  2206. continue;
  2207. // OpenCL single token adornments.
  2208. case tok::kw___kernel:
  2209. ParseOpenCLAttributes(DS.getAttributes());
  2210. continue;
  2211. // storage-class-specifier
  2212. case tok::kw_typedef:
  2213. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc,
  2214. PrevSpec, DiagID);
  2215. break;
  2216. case tok::kw_extern:
  2217. if (DS.isThreadSpecified())
  2218. Diag(Tok, diag::ext_thread_before) << "extern";
  2219. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc,
  2220. PrevSpec, DiagID);
  2221. break;
  2222. case tok::kw___private_extern__:
  2223. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern,
  2224. Loc, PrevSpec, DiagID);
  2225. break;
  2226. case tok::kw_static:
  2227. if (DS.isThreadSpecified())
  2228. Diag(Tok, diag::ext_thread_before) << "static";
  2229. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc,
  2230. PrevSpec, DiagID);
  2231. break;
  2232. case tok::kw_auto:
  2233. if (getLangOpts().CPlusPlus0x) {
  2234. if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) {
  2235. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
  2236. PrevSpec, DiagID);
  2237. if (!isInvalid)
  2238. Diag(Tok, diag::ext_auto_storage_class)
  2239. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  2240. } else
  2241. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec,
  2242. DiagID);
  2243. } else
  2244. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc,
  2245. PrevSpec, DiagID);
  2246. break;
  2247. case tok::kw_register:
  2248. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc,
  2249. PrevSpec, DiagID);
  2250. break;
  2251. case tok::kw_mutable:
  2252. isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc,
  2253. PrevSpec, DiagID);
  2254. break;
  2255. case tok::kw___thread:
  2256. isInvalid = DS.SetStorageClassSpecThread(Loc, PrevSpec, DiagID);
  2257. break;
  2258. // function-specifier
  2259. case tok::kw_inline:
  2260. isInvalid = DS.SetFunctionSpecInline(Loc, PrevSpec, DiagID);
  2261. break;
  2262. case tok::kw_virtual:
  2263. isInvalid = DS.SetFunctionSpecVirtual(Loc, PrevSpec, DiagID);
  2264. break;
  2265. case tok::kw_explicit:
  2266. isInvalid = DS.SetFunctionSpecExplicit(Loc, PrevSpec, DiagID);
  2267. break;
  2268. // alignment-specifier
  2269. case tok::kw__Alignas:
  2270. if (!getLangOpts().C11)
  2271. Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
  2272. ParseAlignmentSpecifier(DS.getAttributes());
  2273. continue;
  2274. // friend
  2275. case tok::kw_friend:
  2276. if (DSContext == DSC_class)
  2277. isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
  2278. else {
  2279. PrevSpec = ""; // not actually used by the diagnostic
  2280. DiagID = diag::err_friend_invalid_in_context;
  2281. isInvalid = true;
  2282. }
  2283. break;
  2284. // Modules
  2285. case tok::kw___module_private__:
  2286. isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID);
  2287. break;
  2288. // constexpr
  2289. case tok::kw_constexpr:
  2290. isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID);
  2291. break;
  2292. // type-specifier
  2293. case tok::kw_short:
  2294. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec,
  2295. DiagID);
  2296. break;
  2297. case tok::kw_long:
  2298. if (DS.getTypeSpecWidth() != DeclSpec::TSW_long)
  2299. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec,
  2300. DiagID);
  2301. else
  2302. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
  2303. DiagID);
  2304. break;
  2305. case tok::kw___int64:
  2306. isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec,
  2307. DiagID);
  2308. break;
  2309. case tok::kw_signed:
  2310. isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec,
  2311. DiagID);
  2312. break;
  2313. case tok::kw_unsigned:
  2314. isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec,
  2315. DiagID);
  2316. break;
  2317. case tok::kw__Complex:
  2318. isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec,
  2319. DiagID);
  2320. break;
  2321. case tok::kw__Imaginary:
  2322. isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec,
  2323. DiagID);
  2324. break;
  2325. case tok::kw_void:
  2326. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec,
  2327. DiagID);
  2328. break;
  2329. case tok::kw_char:
  2330. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec,
  2331. DiagID);
  2332. break;
  2333. case tok::kw_int:
  2334. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec,
  2335. DiagID);
  2336. break;
  2337. case tok::kw___int128:
  2338. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec,
  2339. DiagID);
  2340. break;
  2341. case tok::kw_half:
  2342. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec,
  2343. DiagID);
  2344. break;
  2345. case tok::kw_float:
  2346. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec,
  2347. DiagID);
  2348. break;
  2349. case tok::kw_double:
  2350. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec,
  2351. DiagID);
  2352. break;
  2353. case tok::kw_wchar_t:
  2354. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec,
  2355. DiagID);
  2356. break;
  2357. case tok::kw_char16_t:
  2358. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec,
  2359. DiagID);
  2360. break;
  2361. case tok::kw_char32_t:
  2362. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec,
  2363. DiagID);
  2364. break;
  2365. case tok::kw_bool:
  2366. case tok::kw__Bool:
  2367. if (Tok.is(tok::kw_bool) &&
  2368. DS.getTypeSpecType() != DeclSpec::TST_unspecified &&
  2369. DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  2370. PrevSpec = ""; // Not used by the diagnostic.
  2371. DiagID = diag::err_bool_redeclaration;
  2372. // For better error recovery.
  2373. Tok.setKind(tok::identifier);
  2374. isInvalid = true;
  2375. } else {
  2376. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec,
  2377. DiagID);
  2378. }
  2379. break;
  2380. case tok::kw__Decimal32:
  2381. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec,
  2382. DiagID);
  2383. break;
  2384. case tok::kw__Decimal64:
  2385. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec,
  2386. DiagID);
  2387. break;
  2388. case tok::kw__Decimal128:
  2389. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec,
  2390. DiagID);
  2391. break;
  2392. case tok::kw___vector:
  2393. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
  2394. break;
  2395. case tok::kw___pixel:
  2396. isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
  2397. break;
  2398. case tok::kw___unknown_anytype:
  2399. isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc,
  2400. PrevSpec, DiagID);
  2401. break;
  2402. // class-specifier:
  2403. case tok::kw_class:
  2404. case tok::kw_struct:
  2405. case tok::kw_union: {
  2406. tok::TokenKind Kind = Tok.getKind();
  2407. ConsumeToken();
  2408. ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS,
  2409. EnteringContext, DSContext);
  2410. continue;
  2411. }
  2412. // enum-specifier:
  2413. case tok::kw_enum:
  2414. ConsumeToken();
  2415. ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext);
  2416. continue;
  2417. // cv-qualifier:
  2418. case tok::kw_const:
  2419. isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID,
  2420. getLangOpts(), /*IsTypeSpec*/true);
  2421. break;
  2422. case tok::kw_volatile:
  2423. isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
  2424. getLangOpts(), /*IsTypeSpec*/true);
  2425. break;
  2426. case tok::kw_restrict:
  2427. isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
  2428. getLangOpts(), /*IsTypeSpec*/true);
  2429. break;
  2430. // C++ typename-specifier:
  2431. case tok::kw_typename:
  2432. if (TryAnnotateTypeOrScopeToken()) {
  2433. DS.SetTypeSpecError();
  2434. goto DoneWithDeclSpec;
  2435. }
  2436. if (!Tok.is(tok::kw_typename))
  2437. continue;
  2438. break;
  2439. // GNU typeof support.
  2440. case tok::kw_typeof:
  2441. ParseTypeofSpecifier(DS);
  2442. continue;
  2443. case tok::annot_decltype:
  2444. ParseDecltypeSpecifier(DS);
  2445. continue;
  2446. case tok::kw___underlying_type:
  2447. ParseUnderlyingTypeSpecifier(DS);
  2448. continue;
  2449. case tok::kw__Atomic:
  2450. ParseAtomicSpecifier(DS);
  2451. continue;
  2452. // OpenCL qualifiers:
  2453. case tok::kw_private:
  2454. if (!getLangOpts().OpenCL)
  2455. goto DoneWithDeclSpec;
  2456. case tok::kw___private:
  2457. case tok::kw___global:
  2458. case tok::kw___local:
  2459. case tok::kw___constant:
  2460. case tok::kw___read_only:
  2461. case tok::kw___write_only:
  2462. case tok::kw___read_write:
  2463. ParseOpenCLQualifiers(DS);
  2464. break;
  2465. case tok::less:
  2466. // GCC ObjC supports types like "<SomeProtocol>" as a synonym for
  2467. // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous,
  2468. // but we support it.
  2469. if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1)
  2470. goto DoneWithDeclSpec;
  2471. if (!ParseObjCProtocolQualifiers(DS))
  2472. Diag(Loc, diag::warn_objc_protocol_qualifier_missing_id)
  2473. << FixItHint::CreateInsertion(Loc, "id")
  2474. << SourceRange(Loc, DS.getSourceRange().getEnd());
  2475. // Need to support trailing type qualifiers (e.g. "id<p> const").
  2476. // If a type specifier follows, it will be diagnosed elsewhere.
  2477. continue;
  2478. }
  2479. // If the specifier wasn't legal, issue a diagnostic.
  2480. if (isInvalid) {
  2481. assert(PrevSpec && "Method did not return previous specifier!");
  2482. assert(DiagID);
  2483. if (DiagID == diag::ext_duplicate_declspec)
  2484. Diag(Tok, DiagID)
  2485. << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation());
  2486. else
  2487. Diag(Tok, DiagID) << PrevSpec;
  2488. }
  2489. DS.SetRangeEnd(Tok.getLocation());
  2490. if (DiagID != diag::err_bool_redeclaration)
  2491. ConsumeToken();
  2492. AttrsLastTime = false;
  2493. }
  2494. }
  2495. /// ParseStructDeclaration - Parse a struct declaration without the terminating
  2496. /// semicolon.
  2497. ///
  2498. /// struct-declaration:
  2499. /// specifier-qualifier-list struct-declarator-list
  2500. /// [GNU] __extension__ struct-declaration
  2501. /// [GNU] specifier-qualifier-list
  2502. /// struct-declarator-list:
  2503. /// struct-declarator
  2504. /// struct-declarator-list ',' struct-declarator
  2505. /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator
  2506. /// struct-declarator:
  2507. /// declarator
  2508. /// [GNU] declarator attributes[opt]
  2509. /// declarator[opt] ':' constant-expression
  2510. /// [GNU] declarator[opt] ':' constant-expression attributes[opt]
  2511. ///
  2512. void Parser::
  2513. ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Fields) {
  2514. if (Tok.is(tok::kw___extension__)) {
  2515. // __extension__ silences extension warnings in the subexpression.
  2516. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  2517. ConsumeToken();
  2518. return ParseStructDeclaration(DS, Fields);
  2519. }
  2520. // Parse the common specifier-qualifiers-list piece.
  2521. ParseSpecifierQualifierList(DS);
  2522. // If there are no declarators, this is a free-standing declaration
  2523. // specifier. Let the actions module cope with it.
  2524. if (Tok.is(tok::semi)) {
  2525. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none,
  2526. DS);
  2527. DS.complete(TheDecl);
  2528. return;
  2529. }
  2530. // Read struct-declarators until we find the semicolon.
  2531. bool FirstDeclarator = true;
  2532. SourceLocation CommaLoc;
  2533. while (1) {
  2534. ParsingFieldDeclarator DeclaratorInfo(*this, DS);
  2535. DeclaratorInfo.D.setCommaLoc(CommaLoc);
  2536. // Attributes are only allowed here on successive declarators.
  2537. if (!FirstDeclarator)
  2538. MaybeParseGNUAttributes(DeclaratorInfo.D);
  2539. /// struct-declarator: declarator
  2540. /// struct-declarator: declarator[opt] ':' constant-expression
  2541. if (Tok.isNot(tok::colon)) {
  2542. // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
  2543. ColonProtectionRAIIObject X(*this);
  2544. ParseDeclarator(DeclaratorInfo.D);
  2545. }
  2546. if (Tok.is(tok::colon)) {
  2547. ConsumeToken();
  2548. ExprResult Res(ParseConstantExpression());
  2549. if (Res.isInvalid())
  2550. SkipUntil(tok::semi, true, true);
  2551. else
  2552. DeclaratorInfo.BitfieldSize = Res.release();
  2553. }
  2554. // If attributes exist after the declarator, parse them.
  2555. MaybeParseGNUAttributes(DeclaratorInfo.D);
  2556. // We're done with this declarator; invoke the callback.
  2557. Fields.invoke(DeclaratorInfo);
  2558. // If we don't have a comma, it is either the end of the list (a ';')
  2559. // or an error, bail out.
  2560. if (Tok.isNot(tok::comma))
  2561. return;
  2562. // Consume the comma.
  2563. CommaLoc = ConsumeToken();
  2564. FirstDeclarator = false;
  2565. }
  2566. }
  2567. /// ParseStructUnionBody
  2568. /// struct-contents:
  2569. /// struct-declaration-list
  2570. /// [EXT] empty
  2571. /// [GNU] "struct-declaration-list" without terminatoring ';'
  2572. /// struct-declaration-list:
  2573. /// struct-declaration
  2574. /// struct-declaration-list struct-declaration
  2575. /// [OBC] '@' 'defs' '(' class-name ')'
  2576. ///
  2577. void Parser::ParseStructUnionBody(SourceLocation RecordLoc,
  2578. unsigned TagType, Decl *TagDecl) {
  2579. PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc,
  2580. "parsing struct/union body");
  2581. BalancedDelimiterTracker T(*this, tok::l_brace);
  2582. if (T.consumeOpen())
  2583. return;
  2584. ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope);
  2585. Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
  2586. // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
  2587. // C++.
  2588. if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) {
  2589. Diag(Tok, diag::ext_empty_struct_union) << (TagType == TST_union);
  2590. Diag(Tok, diag::warn_empty_struct_union_compat) << (TagType == TST_union);
  2591. }
  2592. SmallVector<Decl *, 32> FieldDecls;
  2593. // While we still have something to read, read the declarations in the struct.
  2594. while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) {
  2595. // Each iteration of this loop reads one struct-declaration.
  2596. // Check for extraneous top-level semicolon.
  2597. if (Tok.is(tok::semi)) {
  2598. ConsumeExtraSemi(InsideStruct, TagType);
  2599. continue;
  2600. }
  2601. if (!Tok.is(tok::at)) {
  2602. struct CFieldCallback : FieldCallback {
  2603. Parser &P;
  2604. Decl *TagDecl;
  2605. SmallVectorImpl<Decl *> &FieldDecls;
  2606. CFieldCallback(Parser &P, Decl *TagDecl,
  2607. SmallVectorImpl<Decl *> &FieldDecls) :
  2608. P(P), TagDecl(TagDecl), FieldDecls(FieldDecls) {}
  2609. void invoke(ParsingFieldDeclarator &FD) {
  2610. // Install the declarator into the current TagDecl.
  2611. Decl *Field = P.Actions.ActOnField(P.getCurScope(), TagDecl,
  2612. FD.D.getDeclSpec().getSourceRange().getBegin(),
  2613. FD.D, FD.BitfieldSize);
  2614. FieldDecls.push_back(Field);
  2615. FD.complete(Field);
  2616. }
  2617. } Callback(*this, TagDecl, FieldDecls);
  2618. // Parse all the comma separated declarators.
  2619. ParsingDeclSpec DS(*this);
  2620. ParseStructDeclaration(DS, Callback);
  2621. } else { // Handle @defs
  2622. ConsumeToken();
  2623. if (!Tok.isObjCAtKeyword(tok::objc_defs)) {
  2624. Diag(Tok, diag::err_unexpected_at);
  2625. SkipUntil(tok::semi, true);
  2626. continue;
  2627. }
  2628. ConsumeToken();
  2629. ExpectAndConsume(tok::l_paren, diag::err_expected_lparen);
  2630. if (!Tok.is(tok::identifier)) {
  2631. Diag(Tok, diag::err_expected_ident);
  2632. SkipUntil(tok::semi, true);
  2633. continue;
  2634. }
  2635. SmallVector<Decl *, 16> Fields;
  2636. Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(),
  2637. Tok.getIdentifierInfo(), Fields);
  2638. FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end());
  2639. ConsumeToken();
  2640. ExpectAndConsume(tok::r_paren, diag::err_expected_rparen);
  2641. }
  2642. if (Tok.is(tok::semi)) {
  2643. ConsumeToken();
  2644. } else if (Tok.is(tok::r_brace)) {
  2645. ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list);
  2646. break;
  2647. } else {
  2648. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list);
  2649. // Skip to end of block or statement to avoid ext-warning on extra ';'.
  2650. SkipUntil(tok::r_brace, true, true);
  2651. // If we stopped at a ';', eat it.
  2652. if (Tok.is(tok::semi)) ConsumeToken();
  2653. }
  2654. }
  2655. T.consumeClose();
  2656. ParsedAttributes attrs(AttrFactory);
  2657. // If attributes exist after struct contents, parse them.
  2658. MaybeParseGNUAttributes(attrs);
  2659. Actions.ActOnFields(getCurScope(),
  2660. RecordLoc, TagDecl, FieldDecls,
  2661. T.getOpenLocation(), T.getCloseLocation(),
  2662. attrs.getList());
  2663. StructScope.Exit();
  2664. Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl,
  2665. T.getCloseLocation());
  2666. }
  2667. /// ParseEnumSpecifier
  2668. /// enum-specifier: [C99 6.7.2.2]
  2669. /// 'enum' identifier[opt] '{' enumerator-list '}'
  2670. ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}'
  2671. /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt]
  2672. /// '}' attributes[opt]
  2673. /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt]
  2674. /// '}'
  2675. /// 'enum' identifier
  2676. /// [GNU] 'enum' attributes[opt] identifier
  2677. ///
  2678. /// [C++11] enum-head '{' enumerator-list[opt] '}'
  2679. /// [C++11] enum-head '{' enumerator-list ',' '}'
  2680. ///
  2681. /// enum-head: [C++11]
  2682. /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt]
  2683. /// enum-key attribute-specifier-seq[opt] nested-name-specifier
  2684. /// identifier enum-base[opt]
  2685. ///
  2686. /// enum-key: [C++11]
  2687. /// 'enum'
  2688. /// 'enum' 'class'
  2689. /// 'enum' 'struct'
  2690. ///
  2691. /// enum-base: [C++11]
  2692. /// ':' type-specifier-seq
  2693. ///
  2694. /// [C++] elaborated-type-specifier:
  2695. /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier
  2696. ///
  2697. void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS,
  2698. const ParsedTemplateInfo &TemplateInfo,
  2699. AccessSpecifier AS, DeclSpecContext DSC) {
  2700. // Parse the tag portion of this.
  2701. if (Tok.is(tok::code_completion)) {
  2702. // Code completion for an enum name.
  2703. Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum);
  2704. return cutOffParsing();
  2705. }
  2706. // If attributes exist after tag, parse them.
  2707. ParsedAttributesWithRange attrs(AttrFactory);
  2708. MaybeParseGNUAttributes(attrs);
  2709. MaybeParseCXX0XAttributes(attrs);
  2710. // If declspecs exist after tag, parse them.
  2711. while (Tok.is(tok::kw___declspec))
  2712. ParseMicrosoftDeclSpec(attrs);
  2713. SourceLocation ScopedEnumKWLoc;
  2714. bool IsScopedUsingClassTag = false;
  2715. // In C++11, recognize 'enum class' and 'enum struct'.
  2716. if (getLangOpts().CPlusPlus0x &&
  2717. (Tok.is(tok::kw_class) || Tok.is(tok::kw_struct))) {
  2718. Diag(Tok, diag::warn_cxx98_compat_scoped_enum);
  2719. IsScopedUsingClassTag = Tok.is(tok::kw_class);
  2720. ScopedEnumKWLoc = ConsumeToken();
  2721. // Attributes are not allowed between these keywords. Diagnose,
  2722. // but then just treat them like they appeared in the right place.
  2723. ProhibitAttributes(attrs);
  2724. // They are allowed afterwards, though.
  2725. MaybeParseGNUAttributes(attrs);
  2726. MaybeParseCXX0XAttributes(attrs);
  2727. while (Tok.is(tok::kw___declspec))
  2728. ParseMicrosoftDeclSpec(attrs);
  2729. }
  2730. // C++11 [temp.explicit]p12:
  2731. // The usual access controls do not apply to names used to specify
  2732. // explicit instantiations.
  2733. // We extend this to also cover explicit specializations. Note that
  2734. // we don't suppress if this turns out to be an elaborated type
  2735. // specifier.
  2736. bool shouldDelayDiagsInTag =
  2737. (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
  2738. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
  2739. SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
  2740. // Enum definitions should not be parsed in a trailing-return-type.
  2741. bool AllowDeclaration = DSC != DSC_trailing;
  2742. bool AllowFixedUnderlyingType = AllowDeclaration &&
  2743. (getLangOpts().CPlusPlus0x || getLangOpts().MicrosoftExt ||
  2744. getLangOpts().ObjC2);
  2745. CXXScopeSpec &SS = DS.getTypeSpecScope();
  2746. if (getLangOpts().CPlusPlus) {
  2747. // "enum foo : bar;" is not a potential typo for "enum foo::bar;"
  2748. // if a fixed underlying type is allowed.
  2749. ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType);
  2750. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  2751. /*EnteringContext=*/false))
  2752. return;
  2753. if (SS.isSet() && Tok.isNot(tok::identifier)) {
  2754. Diag(Tok, diag::err_expected_ident);
  2755. if (Tok.isNot(tok::l_brace)) {
  2756. // Has no name and is not a definition.
  2757. // Skip the rest of this declarator, up until the comma or semicolon.
  2758. SkipUntil(tok::comma, true);
  2759. return;
  2760. }
  2761. }
  2762. }
  2763. // Must have either 'enum name' or 'enum {...}'.
  2764. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) &&
  2765. !(AllowFixedUnderlyingType && Tok.is(tok::colon))) {
  2766. Diag(Tok, diag::err_expected_ident_lbrace);
  2767. // Skip the rest of this declarator, up until the comma or semicolon.
  2768. SkipUntil(tok::comma, true);
  2769. return;
  2770. }
  2771. // If an identifier is present, consume and remember it.
  2772. IdentifierInfo *Name = 0;
  2773. SourceLocation NameLoc;
  2774. if (Tok.is(tok::identifier)) {
  2775. Name = Tok.getIdentifierInfo();
  2776. NameLoc = ConsumeToken();
  2777. }
  2778. if (!Name && ScopedEnumKWLoc.isValid()) {
  2779. // C++0x 7.2p2: The optional identifier shall not be omitted in the
  2780. // declaration of a scoped enumeration.
  2781. Diag(Tok, diag::err_scoped_enum_missing_identifier);
  2782. ScopedEnumKWLoc = SourceLocation();
  2783. IsScopedUsingClassTag = false;
  2784. }
  2785. // Okay, end the suppression area. We'll decide whether to emit the
  2786. // diagnostics in a second.
  2787. if (shouldDelayDiagsInTag)
  2788. diagsFromTag.done();
  2789. TypeResult BaseType;
  2790. // Parse the fixed underlying type.
  2791. bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
  2792. if (AllowFixedUnderlyingType && Tok.is(tok::colon)) {
  2793. bool PossibleBitfield = false;
  2794. if (CanBeBitfield) {
  2795. // If we're in class scope, this can either be an enum declaration with
  2796. // an underlying type, or a declaration of a bitfield member. We try to
  2797. // use a simple disambiguation scheme first to catch the common cases
  2798. // (integer literal, sizeof); if it's still ambiguous, we then consider
  2799. // anything that's a simple-type-specifier followed by '(' as an
  2800. // expression. This suffices because function types are not valid
  2801. // underlying types anyway.
  2802. EnterExpressionEvaluationContext Unevaluated(Actions,
  2803. Sema::ConstantEvaluated);
  2804. TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind());
  2805. // If the next token starts an expression, we know we're parsing a
  2806. // bit-field. This is the common case.
  2807. if (TPR == TPResult::True())
  2808. PossibleBitfield = true;
  2809. // If the next token starts a type-specifier-seq, it may be either a
  2810. // a fixed underlying type or the start of a function-style cast in C++;
  2811. // lookahead one more token to see if it's obvious that we have a
  2812. // fixed underlying type.
  2813. else if (TPR == TPResult::False() &&
  2814. GetLookAheadToken(2).getKind() == tok::semi) {
  2815. // Consume the ':'.
  2816. ConsumeToken();
  2817. } else {
  2818. // We have the start of a type-specifier-seq, so we have to perform
  2819. // tentative parsing to determine whether we have an expression or a
  2820. // type.
  2821. TentativeParsingAction TPA(*this);
  2822. // Consume the ':'.
  2823. ConsumeToken();
  2824. // If we see a type specifier followed by an open-brace, we have an
  2825. // ambiguity between an underlying type and a C++11 braced
  2826. // function-style cast. Resolve this by always treating it as an
  2827. // underlying type.
  2828. // FIXME: The standard is not entirely clear on how to disambiguate in
  2829. // this case.
  2830. if ((getLangOpts().CPlusPlus &&
  2831. isCXXDeclarationSpecifier(TPResult::True()) != TPResult::True()) ||
  2832. (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) {
  2833. // We'll parse this as a bitfield later.
  2834. PossibleBitfield = true;
  2835. TPA.Revert();
  2836. } else {
  2837. // We have a type-specifier-seq.
  2838. TPA.Commit();
  2839. }
  2840. }
  2841. } else {
  2842. // Consume the ':'.
  2843. ConsumeToken();
  2844. }
  2845. if (!PossibleBitfield) {
  2846. SourceRange Range;
  2847. BaseType = ParseTypeName(&Range);
  2848. if (!getLangOpts().CPlusPlus0x && !getLangOpts().ObjC2)
  2849. Diag(StartLoc, diag::ext_ms_enum_fixed_underlying_type)
  2850. << Range;
  2851. if (getLangOpts().CPlusPlus0x)
  2852. Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type);
  2853. }
  2854. }
  2855. // There are four options here. If we have 'friend enum foo;' then this is a
  2856. // friend declaration, and cannot have an accompanying definition. If we have
  2857. // 'enum foo;', then this is a forward declaration. If we have
  2858. // 'enum foo {...' then this is a definition. Otherwise we have something
  2859. // like 'enum foo xyz', a reference.
  2860. //
  2861. // This is needed to handle stuff like this right (C99 6.7.2.3p11):
  2862. // enum foo {..}; void bar() { enum foo; } <- new foo in bar.
  2863. // enum foo {..}; void bar() { enum foo x; } <- use of old foo.
  2864. //
  2865. Sema::TagUseKind TUK;
  2866. if (!AllowDeclaration) {
  2867. TUK = Sema::TUK_Reference;
  2868. } else if (Tok.is(tok::l_brace)) {
  2869. if (DS.isFriendSpecified()) {
  2870. Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
  2871. << SourceRange(DS.getFriendSpecLoc());
  2872. ConsumeBrace();
  2873. SkipUntil(tok::r_brace);
  2874. TUK = Sema::TUK_Friend;
  2875. } else {
  2876. TUK = Sema::TUK_Definition;
  2877. }
  2878. } else if (DSC != DSC_type_specifier &&
  2879. (Tok.is(tok::semi) ||
  2880. (Tok.isAtStartOfLine() &&
  2881. !isValidAfterTypeSpecifier(CanBeBitfield)))) {
  2882. TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
  2883. if (Tok.isNot(tok::semi)) {
  2884. // A semicolon was missing after this declaration. Diagnose and recover.
  2885. ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl,
  2886. "enum");
  2887. PP.EnterToken(Tok);
  2888. Tok.setKind(tok::semi);
  2889. }
  2890. } else {
  2891. TUK = Sema::TUK_Reference;
  2892. }
  2893. // If this is an elaborated type specifier, and we delayed
  2894. // diagnostics before, just merge them into the current pool.
  2895. if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) {
  2896. diagsFromTag.redelay();
  2897. }
  2898. MultiTemplateParamsArg TParams;
  2899. if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
  2900. TUK != Sema::TUK_Reference) {
  2901. if (!getLangOpts().CPlusPlus0x || !SS.isSet()) {
  2902. // Skip the rest of this declarator, up until the comma or semicolon.
  2903. Diag(Tok, diag::err_enum_template);
  2904. SkipUntil(tok::comma, true);
  2905. return;
  2906. }
  2907. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  2908. // Enumerations can't be explicitly instantiated.
  2909. DS.SetTypeSpecError();
  2910. Diag(StartLoc, diag::err_explicit_instantiation_enum);
  2911. return;
  2912. }
  2913. assert(TemplateInfo.TemplateParams && "no template parameters");
  2914. TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(),
  2915. TemplateInfo.TemplateParams->size());
  2916. }
  2917. if (TUK == Sema::TUK_Reference)
  2918. ProhibitAttributes(attrs);
  2919. if (!Name && TUK != Sema::TUK_Definition) {
  2920. Diag(Tok, diag::err_enumerator_unnamed_no_def);
  2921. // Skip the rest of this declarator, up until the comma or semicolon.
  2922. SkipUntil(tok::comma, true);
  2923. return;
  2924. }
  2925. bool Owned = false;
  2926. bool IsDependent = false;
  2927. const char *PrevSpec = 0;
  2928. unsigned DiagID;
  2929. Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK,
  2930. StartLoc, SS, Name, NameLoc, attrs.getList(),
  2931. AS, DS.getModulePrivateSpecLoc(), TParams,
  2932. Owned, IsDependent, ScopedEnumKWLoc,
  2933. IsScopedUsingClassTag, BaseType);
  2934. if (IsDependent) {
  2935. // This enum has a dependent nested-name-specifier. Handle it as a
  2936. // dependent tag.
  2937. if (!Name) {
  2938. DS.SetTypeSpecError();
  2939. Diag(Tok, diag::err_expected_type_name_after_typename);
  2940. return;
  2941. }
  2942. TypeResult Type = Actions.ActOnDependentTag(getCurScope(), DeclSpec::TST_enum,
  2943. TUK, SS, Name, StartLoc,
  2944. NameLoc);
  2945. if (Type.isInvalid()) {
  2946. DS.SetTypeSpecError();
  2947. return;
  2948. }
  2949. if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
  2950. NameLoc.isValid() ? NameLoc : StartLoc,
  2951. PrevSpec, DiagID, Type.get()))
  2952. Diag(StartLoc, DiagID) << PrevSpec;
  2953. return;
  2954. }
  2955. if (!TagDecl) {
  2956. // The action failed to produce an enumeration tag. If this is a
  2957. // definition, consume the entire definition.
  2958. if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) {
  2959. ConsumeBrace();
  2960. SkipUntil(tok::r_brace);
  2961. }
  2962. DS.SetTypeSpecError();
  2963. return;
  2964. }
  2965. if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference)
  2966. ParseEnumBody(StartLoc, TagDecl);
  2967. if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc,
  2968. NameLoc.isValid() ? NameLoc : StartLoc,
  2969. PrevSpec, DiagID, TagDecl, Owned))
  2970. Diag(StartLoc, DiagID) << PrevSpec;
  2971. }
  2972. /// ParseEnumBody - Parse a {} enclosed enumerator-list.
  2973. /// enumerator-list:
  2974. /// enumerator
  2975. /// enumerator-list ',' enumerator
  2976. /// enumerator:
  2977. /// enumeration-constant
  2978. /// enumeration-constant '=' constant-expression
  2979. /// enumeration-constant:
  2980. /// identifier
  2981. ///
  2982. void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) {
  2983. // Enter the scope of the enum body and start the definition.
  2984. ParseScope EnumScope(this, Scope::DeclScope);
  2985. Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl);
  2986. BalancedDelimiterTracker T(*this, tok::l_brace);
  2987. T.consumeOpen();
  2988. // C does not allow an empty enumerator-list, C++ does [dcl.enum].
  2989. if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus)
  2990. Diag(Tok, diag::error_empty_enum);
  2991. SmallVector<Decl *, 32> EnumConstantDecls;
  2992. Decl *LastEnumConstDecl = 0;
  2993. // Parse the enumerator-list.
  2994. while (Tok.is(tok::identifier)) {
  2995. IdentifierInfo *Ident = Tok.getIdentifierInfo();
  2996. SourceLocation IdentLoc = ConsumeToken();
  2997. // If attributes exist after the enumerator, parse them.
  2998. ParsedAttributesWithRange attrs(AttrFactory);
  2999. MaybeParseGNUAttributes(attrs);
  3000. MaybeParseCXX0XAttributes(attrs);
  3001. ProhibitAttributes(attrs);
  3002. SourceLocation EqualLoc;
  3003. ExprResult AssignedVal;
  3004. ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent);
  3005. if (Tok.is(tok::equal)) {
  3006. EqualLoc = ConsumeToken();
  3007. AssignedVal = ParseConstantExpression();
  3008. if (AssignedVal.isInvalid())
  3009. SkipUntil(tok::comma, tok::r_brace, true, true);
  3010. }
  3011. // Install the enumerator constant into EnumDecl.
  3012. Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl,
  3013. LastEnumConstDecl,
  3014. IdentLoc, Ident,
  3015. attrs.getList(), EqualLoc,
  3016. AssignedVal.release());
  3017. PD.complete(EnumConstDecl);
  3018. EnumConstantDecls.push_back(EnumConstDecl);
  3019. LastEnumConstDecl = EnumConstDecl;
  3020. if (Tok.is(tok::identifier)) {
  3021. // We're missing a comma between enumerators.
  3022. SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
  3023. Diag(Loc, diag::err_enumerator_list_missing_comma)
  3024. << FixItHint::CreateInsertion(Loc, ", ");
  3025. continue;
  3026. }
  3027. if (Tok.isNot(tok::comma))
  3028. break;
  3029. SourceLocation CommaLoc = ConsumeToken();
  3030. if (Tok.isNot(tok::identifier)) {
  3031. if (!getLangOpts().C99 && !getLangOpts().CPlusPlus0x)
  3032. Diag(CommaLoc, getLangOpts().CPlusPlus ?
  3033. diag::ext_enumerator_list_comma_cxx :
  3034. diag::ext_enumerator_list_comma_c)
  3035. << FixItHint::CreateRemoval(CommaLoc);
  3036. else if (getLangOpts().CPlusPlus0x)
  3037. Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma)
  3038. << FixItHint::CreateRemoval(CommaLoc);
  3039. }
  3040. }
  3041. // Eat the }.
  3042. T.consumeClose();
  3043. // If attributes exist after the identifier list, parse them.
  3044. ParsedAttributes attrs(AttrFactory);
  3045. MaybeParseGNUAttributes(attrs);
  3046. Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(),
  3047. EnumDecl, EnumConstantDecls.data(),
  3048. EnumConstantDecls.size(), getCurScope(),
  3049. attrs.getList());
  3050. EnumScope.Exit();
  3051. Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl,
  3052. T.getCloseLocation());
  3053. // The next token must be valid after an enum definition. If not, a ';'
  3054. // was probably forgotten.
  3055. bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope;
  3056. if (!isValidAfterTypeSpecifier(CanBeBitfield)) {
  3057. ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, "enum");
  3058. // Push this token back into the preprocessor and change our current token
  3059. // to ';' so that the rest of the code recovers as though there were an
  3060. // ';' after the definition.
  3061. PP.EnterToken(Tok);
  3062. Tok.setKind(tok::semi);
  3063. }
  3064. }
  3065. /// isTypeSpecifierQualifier - Return true if the current token could be the
  3066. /// start of a type-qualifier-list.
  3067. bool Parser::isTypeQualifier() const {
  3068. switch (Tok.getKind()) {
  3069. default: return false;
  3070. // type-qualifier only in OpenCL
  3071. case tok::kw_private:
  3072. return getLangOpts().OpenCL;
  3073. // type-qualifier
  3074. case tok::kw_const:
  3075. case tok::kw_volatile:
  3076. case tok::kw_restrict:
  3077. case tok::kw___private:
  3078. case tok::kw___local:
  3079. case tok::kw___global:
  3080. case tok::kw___constant:
  3081. case tok::kw___read_only:
  3082. case tok::kw___read_write:
  3083. case tok::kw___write_only:
  3084. return true;
  3085. }
  3086. }
  3087. /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
  3088. /// is definitely a type-specifier. Return false if it isn't part of a type
  3089. /// specifier or if we're not sure.
  3090. bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const {
  3091. switch (Tok.getKind()) {
  3092. default: return false;
  3093. // type-specifiers
  3094. case tok::kw_short:
  3095. case tok::kw_long:
  3096. case tok::kw___int64:
  3097. case tok::kw___int128:
  3098. case tok::kw_signed:
  3099. case tok::kw_unsigned:
  3100. case tok::kw__Complex:
  3101. case tok::kw__Imaginary:
  3102. case tok::kw_void:
  3103. case tok::kw_char:
  3104. case tok::kw_wchar_t:
  3105. case tok::kw_char16_t:
  3106. case tok::kw_char32_t:
  3107. case tok::kw_int:
  3108. case tok::kw_half:
  3109. case tok::kw_float:
  3110. case tok::kw_double:
  3111. case tok::kw_bool:
  3112. case tok::kw__Bool:
  3113. case tok::kw__Decimal32:
  3114. case tok::kw__Decimal64:
  3115. case tok::kw__Decimal128:
  3116. case tok::kw___vector:
  3117. // struct-or-union-specifier (C99) or class-specifier (C++)
  3118. case tok::kw_class:
  3119. case tok::kw_struct:
  3120. case tok::kw_union:
  3121. // enum-specifier
  3122. case tok::kw_enum:
  3123. // typedef-name
  3124. case tok::annot_typename:
  3125. return true;
  3126. }
  3127. }
  3128. /// isTypeSpecifierQualifier - Return true if the current token could be the
  3129. /// start of a specifier-qualifier-list.
  3130. bool Parser::isTypeSpecifierQualifier() {
  3131. switch (Tok.getKind()) {
  3132. default: return false;
  3133. case tok::identifier: // foo::bar
  3134. if (TryAltiVecVectorToken())
  3135. return true;
  3136. // Fall through.
  3137. case tok::kw_typename: // typename T::type
  3138. // Annotate typenames and C++ scope specifiers. If we get one, just
  3139. // recurse to handle whatever we get.
  3140. if (TryAnnotateTypeOrScopeToken())
  3141. return true;
  3142. if (Tok.is(tok::identifier))
  3143. return false;
  3144. return isTypeSpecifierQualifier();
  3145. case tok::coloncolon: // ::foo::bar
  3146. if (NextToken().is(tok::kw_new) || // ::new
  3147. NextToken().is(tok::kw_delete)) // ::delete
  3148. return false;
  3149. if (TryAnnotateTypeOrScopeToken())
  3150. return true;
  3151. return isTypeSpecifierQualifier();
  3152. // GNU attributes support.
  3153. case tok::kw___attribute:
  3154. // GNU typeof support.
  3155. case tok::kw_typeof:
  3156. // type-specifiers
  3157. case tok::kw_short:
  3158. case tok::kw_long:
  3159. case tok::kw___int64:
  3160. case tok::kw___int128:
  3161. case tok::kw_signed:
  3162. case tok::kw_unsigned:
  3163. case tok::kw__Complex:
  3164. case tok::kw__Imaginary:
  3165. case tok::kw_void:
  3166. case tok::kw_char:
  3167. case tok::kw_wchar_t:
  3168. case tok::kw_char16_t:
  3169. case tok::kw_char32_t:
  3170. case tok::kw_int:
  3171. case tok::kw_half:
  3172. case tok::kw_float:
  3173. case tok::kw_double:
  3174. case tok::kw_bool:
  3175. case tok::kw__Bool:
  3176. case tok::kw__Decimal32:
  3177. case tok::kw__Decimal64:
  3178. case tok::kw__Decimal128:
  3179. case tok::kw___vector:
  3180. // struct-or-union-specifier (C99) or class-specifier (C++)
  3181. case tok::kw_class:
  3182. case tok::kw_struct:
  3183. case tok::kw_union:
  3184. // enum-specifier
  3185. case tok::kw_enum:
  3186. // type-qualifier
  3187. case tok::kw_const:
  3188. case tok::kw_volatile:
  3189. case tok::kw_restrict:
  3190. // typedef-name
  3191. case tok::annot_typename:
  3192. return true;
  3193. // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
  3194. case tok::less:
  3195. return getLangOpts().ObjC1;
  3196. case tok::kw___cdecl:
  3197. case tok::kw___stdcall:
  3198. case tok::kw___fastcall:
  3199. case tok::kw___thiscall:
  3200. case tok::kw___w64:
  3201. case tok::kw___ptr64:
  3202. case tok::kw___ptr32:
  3203. case tok::kw___pascal:
  3204. case tok::kw___unaligned:
  3205. case tok::kw___private:
  3206. case tok::kw___local:
  3207. case tok::kw___global:
  3208. case tok::kw___constant:
  3209. case tok::kw___read_only:
  3210. case tok::kw___read_write:
  3211. case tok::kw___write_only:
  3212. return true;
  3213. case tok::kw_private:
  3214. return getLangOpts().OpenCL;
  3215. // C11 _Atomic()
  3216. case tok::kw__Atomic:
  3217. return true;
  3218. }
  3219. }
  3220. /// isDeclarationSpecifier() - Return true if the current token is part of a
  3221. /// declaration specifier.
  3222. ///
  3223. /// \param DisambiguatingWithExpression True to indicate that the purpose of
  3224. /// this check is to disambiguate between an expression and a declaration.
  3225. bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) {
  3226. switch (Tok.getKind()) {
  3227. default: return false;
  3228. case tok::kw_private:
  3229. return getLangOpts().OpenCL;
  3230. case tok::identifier: // foo::bar
  3231. // Unfortunate hack to support "Class.factoryMethod" notation.
  3232. if (getLangOpts().ObjC1 && NextToken().is(tok::period))
  3233. return false;
  3234. if (TryAltiVecVectorToken())
  3235. return true;
  3236. // Fall through.
  3237. case tok::kw_decltype: // decltype(T())::type
  3238. case tok::kw_typename: // typename T::type
  3239. // Annotate typenames and C++ scope specifiers. If we get one, just
  3240. // recurse to handle whatever we get.
  3241. if (TryAnnotateTypeOrScopeToken())
  3242. return true;
  3243. if (Tok.is(tok::identifier))
  3244. return false;
  3245. // If we're in Objective-C and we have an Objective-C class type followed
  3246. // by an identifier and then either ':' or ']', in a place where an
  3247. // expression is permitted, then this is probably a class message send
  3248. // missing the initial '['. In this case, we won't consider this to be
  3249. // the start of a declaration.
  3250. if (DisambiguatingWithExpression &&
  3251. isStartOfObjCClassMessageMissingOpenBracket())
  3252. return false;
  3253. return isDeclarationSpecifier();
  3254. case tok::coloncolon: // ::foo::bar
  3255. if (NextToken().is(tok::kw_new) || // ::new
  3256. NextToken().is(tok::kw_delete)) // ::delete
  3257. return false;
  3258. // Annotate typenames and C++ scope specifiers. If we get one, just
  3259. // recurse to handle whatever we get.
  3260. if (TryAnnotateTypeOrScopeToken())
  3261. return true;
  3262. return isDeclarationSpecifier();
  3263. // storage-class-specifier
  3264. case tok::kw_typedef:
  3265. case tok::kw_extern:
  3266. case tok::kw___private_extern__:
  3267. case tok::kw_static:
  3268. case tok::kw_auto:
  3269. case tok::kw_register:
  3270. case tok::kw___thread:
  3271. // Modules
  3272. case tok::kw___module_private__:
  3273. // type-specifiers
  3274. case tok::kw_short:
  3275. case tok::kw_long:
  3276. case tok::kw___int64:
  3277. case tok::kw___int128:
  3278. case tok::kw_signed:
  3279. case tok::kw_unsigned:
  3280. case tok::kw__Complex:
  3281. case tok::kw__Imaginary:
  3282. case tok::kw_void:
  3283. case tok::kw_char:
  3284. case tok::kw_wchar_t:
  3285. case tok::kw_char16_t:
  3286. case tok::kw_char32_t:
  3287. case tok::kw_int:
  3288. case tok::kw_half:
  3289. case tok::kw_float:
  3290. case tok::kw_double:
  3291. case tok::kw_bool:
  3292. case tok::kw__Bool:
  3293. case tok::kw__Decimal32:
  3294. case tok::kw__Decimal64:
  3295. case tok::kw__Decimal128:
  3296. case tok::kw___vector:
  3297. // struct-or-union-specifier (C99) or class-specifier (C++)
  3298. case tok::kw_class:
  3299. case tok::kw_struct:
  3300. case tok::kw_union:
  3301. // enum-specifier
  3302. case tok::kw_enum:
  3303. // type-qualifier
  3304. case tok::kw_const:
  3305. case tok::kw_volatile:
  3306. case tok::kw_restrict:
  3307. // function-specifier
  3308. case tok::kw_inline:
  3309. case tok::kw_virtual:
  3310. case tok::kw_explicit:
  3311. // static_assert-declaration
  3312. case tok::kw__Static_assert:
  3313. // GNU typeof support.
  3314. case tok::kw_typeof:
  3315. // GNU attributes.
  3316. case tok::kw___attribute:
  3317. return true;
  3318. // C++0x decltype.
  3319. case tok::annot_decltype:
  3320. return true;
  3321. // C11 _Atomic()
  3322. case tok::kw__Atomic:
  3323. return true;
  3324. // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'.
  3325. case tok::less:
  3326. return getLangOpts().ObjC1;
  3327. // typedef-name
  3328. case tok::annot_typename:
  3329. return !DisambiguatingWithExpression ||
  3330. !isStartOfObjCClassMessageMissingOpenBracket();
  3331. case tok::kw___declspec:
  3332. case tok::kw___cdecl:
  3333. case tok::kw___stdcall:
  3334. case tok::kw___fastcall:
  3335. case tok::kw___thiscall:
  3336. case tok::kw___w64:
  3337. case tok::kw___ptr64:
  3338. case tok::kw___ptr32:
  3339. case tok::kw___forceinline:
  3340. case tok::kw___pascal:
  3341. case tok::kw___unaligned:
  3342. case tok::kw___private:
  3343. case tok::kw___local:
  3344. case tok::kw___global:
  3345. case tok::kw___constant:
  3346. case tok::kw___read_only:
  3347. case tok::kw___read_write:
  3348. case tok::kw___write_only:
  3349. return true;
  3350. }
  3351. }
  3352. bool Parser::isConstructorDeclarator() {
  3353. TentativeParsingAction TPA(*this);
  3354. // Parse the C++ scope specifier.
  3355. CXXScopeSpec SS;
  3356. if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  3357. /*EnteringContext=*/true)) {
  3358. TPA.Revert();
  3359. return false;
  3360. }
  3361. // Parse the constructor name.
  3362. if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id)) {
  3363. // We already know that we have a constructor name; just consume
  3364. // the token.
  3365. ConsumeToken();
  3366. } else {
  3367. TPA.Revert();
  3368. return false;
  3369. }
  3370. // Current class name must be followed by a left parenthesis.
  3371. if (Tok.isNot(tok::l_paren)) {
  3372. TPA.Revert();
  3373. return false;
  3374. }
  3375. ConsumeParen();
  3376. // A right parenthesis, or ellipsis followed by a right parenthesis signals
  3377. // that we have a constructor.
  3378. if (Tok.is(tok::r_paren) ||
  3379. (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) {
  3380. TPA.Revert();
  3381. return true;
  3382. }
  3383. // If we need to, enter the specified scope.
  3384. DeclaratorScopeObj DeclScopeObj(*this, SS);
  3385. if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
  3386. DeclScopeObj.EnterDeclaratorScope();
  3387. // Optionally skip Microsoft attributes.
  3388. ParsedAttributes Attrs(AttrFactory);
  3389. MaybeParseMicrosoftAttributes(Attrs);
  3390. // Check whether the next token(s) are part of a declaration
  3391. // specifier, in which case we have the start of a parameter and,
  3392. // therefore, we know that this is a constructor.
  3393. bool IsConstructor = false;
  3394. if (isDeclarationSpecifier())
  3395. IsConstructor = true;
  3396. else if (Tok.is(tok::identifier) ||
  3397. (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) {
  3398. // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type.
  3399. // This might be a parenthesized member name, but is more likely to
  3400. // be a constructor declaration with an invalid argument type. Keep
  3401. // looking.
  3402. if (Tok.is(tok::annot_cxxscope))
  3403. ConsumeToken();
  3404. ConsumeToken();
  3405. // If this is not a constructor, we must be parsing a declarator,
  3406. // which must have one of the following syntactic forms (see the
  3407. // grammar extract at the start of ParseDirectDeclarator):
  3408. switch (Tok.getKind()) {
  3409. case tok::l_paren:
  3410. // C(X ( int));
  3411. case tok::l_square:
  3412. // C(X [ 5]);
  3413. // C(X [ [attribute]]);
  3414. case tok::coloncolon:
  3415. // C(X :: Y);
  3416. // C(X :: *p);
  3417. case tok::r_paren:
  3418. // C(X )
  3419. // Assume this isn't a constructor, rather than assuming it's a
  3420. // constructor with an unnamed parameter of an ill-formed type.
  3421. break;
  3422. default:
  3423. IsConstructor = true;
  3424. break;
  3425. }
  3426. }
  3427. TPA.Revert();
  3428. return IsConstructor;
  3429. }
  3430. /// ParseTypeQualifierListOpt
  3431. /// type-qualifier-list: [C99 6.7.5]
  3432. /// type-qualifier
  3433. /// [vendor] attributes
  3434. /// [ only if VendorAttributesAllowed=true ]
  3435. /// type-qualifier-list type-qualifier
  3436. /// [vendor] type-qualifier-list attributes
  3437. /// [ only if VendorAttributesAllowed=true ]
  3438. /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq
  3439. /// [ only if CXX0XAttributesAllowed=true ]
  3440. /// Note: vendor can be GNU, MS, etc.
  3441. ///
  3442. void Parser::ParseTypeQualifierListOpt(DeclSpec &DS,
  3443. bool VendorAttributesAllowed,
  3444. bool CXX11AttributesAllowed) {
  3445. if (getLangOpts().CPlusPlus0x && CXX11AttributesAllowed &&
  3446. isCXX11AttributeSpecifier()) {
  3447. ParsedAttributesWithRange attrs(AttrFactory);
  3448. ParseCXX11Attributes(attrs);
  3449. DS.takeAttributesFrom(attrs);
  3450. }
  3451. SourceLocation EndLoc;
  3452. while (1) {
  3453. bool isInvalid = false;
  3454. const char *PrevSpec = 0;
  3455. unsigned DiagID = 0;
  3456. SourceLocation Loc = Tok.getLocation();
  3457. switch (Tok.getKind()) {
  3458. case tok::code_completion:
  3459. Actions.CodeCompleteTypeQualifiers(DS);
  3460. return cutOffParsing();
  3461. case tok::kw_const:
  3462. isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID,
  3463. getLangOpts(), /*IsTypeSpec*/false);
  3464. break;
  3465. case tok::kw_volatile:
  3466. isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID,
  3467. getLangOpts(), /*IsTypeSpec*/false);
  3468. break;
  3469. case tok::kw_restrict:
  3470. isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID,
  3471. getLangOpts(), /*IsTypeSpec*/false);
  3472. break;
  3473. // OpenCL qualifiers:
  3474. case tok::kw_private:
  3475. if (!getLangOpts().OpenCL)
  3476. goto DoneWithTypeQuals;
  3477. case tok::kw___private:
  3478. case tok::kw___global:
  3479. case tok::kw___local:
  3480. case tok::kw___constant:
  3481. case tok::kw___read_only:
  3482. case tok::kw___write_only:
  3483. case tok::kw___read_write:
  3484. ParseOpenCLQualifiers(DS);
  3485. break;
  3486. case tok::kw___w64:
  3487. case tok::kw___ptr64:
  3488. case tok::kw___ptr32:
  3489. case tok::kw___cdecl:
  3490. case tok::kw___stdcall:
  3491. case tok::kw___fastcall:
  3492. case tok::kw___thiscall:
  3493. case tok::kw___unaligned:
  3494. if (VendorAttributesAllowed) {
  3495. ParseMicrosoftTypeAttributes(DS.getAttributes());
  3496. continue;
  3497. }
  3498. goto DoneWithTypeQuals;
  3499. case tok::kw___pascal:
  3500. if (VendorAttributesAllowed) {
  3501. ParseBorlandTypeAttributes(DS.getAttributes());
  3502. continue;
  3503. }
  3504. goto DoneWithTypeQuals;
  3505. case tok::kw___attribute:
  3506. if (VendorAttributesAllowed) {
  3507. ParseGNUAttributes(DS.getAttributes());
  3508. continue; // do *not* consume the next token!
  3509. }
  3510. // otherwise, FALL THROUGH!
  3511. default:
  3512. DoneWithTypeQuals:
  3513. // If this is not a type-qualifier token, we're done reading type
  3514. // qualifiers. First verify that DeclSpec's are consistent.
  3515. DS.Finish(Diags, PP);
  3516. if (EndLoc.isValid())
  3517. DS.SetRangeEnd(EndLoc);
  3518. return;
  3519. }
  3520. // If the specifier combination wasn't legal, issue a diagnostic.
  3521. if (isInvalid) {
  3522. assert(PrevSpec && "Method did not return previous specifier!");
  3523. Diag(Tok, DiagID) << PrevSpec;
  3524. }
  3525. EndLoc = ConsumeToken();
  3526. }
  3527. }
  3528. /// ParseDeclarator - Parse and verify a newly-initialized declarator.
  3529. ///
  3530. void Parser::ParseDeclarator(Declarator &D) {
  3531. /// This implements the 'declarator' production in the C grammar, then checks
  3532. /// for well-formedness and issues diagnostics.
  3533. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
  3534. }
  3535. static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang) {
  3536. if (Kind == tok::star || Kind == tok::caret)
  3537. return true;
  3538. // We parse rvalue refs in C++03, because otherwise the errors are scary.
  3539. if (!Lang.CPlusPlus)
  3540. return false;
  3541. return Kind == tok::amp || Kind == tok::ampamp;
  3542. }
  3543. /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator
  3544. /// is parsed by the function passed to it. Pass null, and the direct-declarator
  3545. /// isn't parsed at all, making this function effectively parse the C++
  3546. /// ptr-operator production.
  3547. ///
  3548. /// If the grammar of this construct is extended, matching changes must also be
  3549. /// made to TryParseDeclarator and MightBeDeclarator, and possibly to
  3550. /// isConstructorDeclarator.
  3551. ///
  3552. /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl]
  3553. /// [C] pointer[opt] direct-declarator
  3554. /// [C++] direct-declarator
  3555. /// [C++] ptr-operator declarator
  3556. ///
  3557. /// pointer: [C99 6.7.5]
  3558. /// '*' type-qualifier-list[opt]
  3559. /// '*' type-qualifier-list[opt] pointer
  3560. ///
  3561. /// ptr-operator:
  3562. /// '*' cv-qualifier-seq[opt]
  3563. /// '&'
  3564. /// [C++0x] '&&'
  3565. /// [GNU] '&' restrict[opt] attributes[opt]
  3566. /// [GNU?] '&&' restrict[opt] attributes[opt]
  3567. /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt]
  3568. void Parser::ParseDeclaratorInternal(Declarator &D,
  3569. DirectDeclParseFunction DirectDeclParser) {
  3570. if (Diags.hasAllExtensionsSilenced())
  3571. D.setExtension();
  3572. // C++ member pointers start with a '::' or a nested-name.
  3573. // Member pointers get special handling, since there's no place for the
  3574. // scope spec in the generic path below.
  3575. if (getLangOpts().CPlusPlus &&
  3576. (Tok.is(tok::coloncolon) || Tok.is(tok::identifier) ||
  3577. Tok.is(tok::annot_cxxscope))) {
  3578. bool EnteringContext = D.getContext() == Declarator::FileContext ||
  3579. D.getContext() == Declarator::MemberContext;
  3580. CXXScopeSpec SS;
  3581. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext);
  3582. if (SS.isNotEmpty()) {
  3583. if (Tok.isNot(tok::star)) {
  3584. // The scope spec really belongs to the direct-declarator.
  3585. D.getCXXScopeSpec() = SS;
  3586. if (DirectDeclParser)
  3587. (this->*DirectDeclParser)(D);
  3588. return;
  3589. }
  3590. SourceLocation Loc = ConsumeToken();
  3591. D.SetRangeEnd(Loc);
  3592. DeclSpec DS(AttrFactory);
  3593. ParseTypeQualifierListOpt(DS);
  3594. D.ExtendWithDeclSpec(DS);
  3595. // Recurse to parse whatever is left.
  3596. ParseDeclaratorInternal(D, DirectDeclParser);
  3597. // Sema will have to catch (syntactically invalid) pointers into global
  3598. // scope. It has to catch pointers into namespace scope anyway.
  3599. D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(),
  3600. Loc),
  3601. DS.getAttributes(),
  3602. /* Don't replace range end. */SourceLocation());
  3603. return;
  3604. }
  3605. }
  3606. tok::TokenKind Kind = Tok.getKind();
  3607. // Not a pointer, C++ reference, or block.
  3608. if (!isPtrOperatorToken(Kind, getLangOpts())) {
  3609. if (DirectDeclParser)
  3610. (this->*DirectDeclParser)(D);
  3611. return;
  3612. }
  3613. // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference,
  3614. // '&&' -> rvalue reference
  3615. SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&.
  3616. D.SetRangeEnd(Loc);
  3617. if (Kind == tok::star || Kind == tok::caret) {
  3618. // Is a pointer.
  3619. DeclSpec DS(AttrFactory);
  3620. // FIXME: GNU attributes are not allowed here in a new-type-id.
  3621. ParseTypeQualifierListOpt(DS);
  3622. D.ExtendWithDeclSpec(DS);
  3623. // Recursively parse the declarator.
  3624. ParseDeclaratorInternal(D, DirectDeclParser);
  3625. if (Kind == tok::star)
  3626. // Remember that we parsed a pointer type, and remember the type-quals.
  3627. D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc,
  3628. DS.getConstSpecLoc(),
  3629. DS.getVolatileSpecLoc(),
  3630. DS.getRestrictSpecLoc()),
  3631. DS.getAttributes(),
  3632. SourceLocation());
  3633. else
  3634. // Remember that we parsed a Block type, and remember the type-quals.
  3635. D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(),
  3636. Loc),
  3637. DS.getAttributes(),
  3638. SourceLocation());
  3639. } else {
  3640. // Is a reference
  3641. DeclSpec DS(AttrFactory);
  3642. // Complain about rvalue references in C++03, but then go on and build
  3643. // the declarator.
  3644. if (Kind == tok::ampamp)
  3645. Diag(Loc, getLangOpts().CPlusPlus0x ?
  3646. diag::warn_cxx98_compat_rvalue_reference :
  3647. diag::ext_rvalue_reference);
  3648. // GNU-style and C++11 attributes are allowed here, as is restrict.
  3649. ParseTypeQualifierListOpt(DS);
  3650. D.ExtendWithDeclSpec(DS);
  3651. // C++ 8.3.2p1: cv-qualified references are ill-formed except when the
  3652. // cv-qualifiers are introduced through the use of a typedef or of a
  3653. // template type argument, in which case the cv-qualifiers are ignored.
  3654. if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
  3655. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3656. Diag(DS.getConstSpecLoc(),
  3657. diag::err_invalid_reference_qualifier_application) << "const";
  3658. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3659. Diag(DS.getVolatileSpecLoc(),
  3660. diag::err_invalid_reference_qualifier_application) << "volatile";
  3661. }
  3662. // Recursively parse the declarator.
  3663. ParseDeclaratorInternal(D, DirectDeclParser);
  3664. if (D.getNumTypeObjects() > 0) {
  3665. // C++ [dcl.ref]p4: There shall be no references to references.
  3666. DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1);
  3667. if (InnerChunk.Kind == DeclaratorChunk::Reference) {
  3668. if (const IdentifierInfo *II = D.getIdentifier())
  3669. Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
  3670. << II;
  3671. else
  3672. Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference)
  3673. << "type name";
  3674. // Once we've complained about the reference-to-reference, we
  3675. // can go ahead and build the (technically ill-formed)
  3676. // declarator: reference collapsing will take care of it.
  3677. }
  3678. }
  3679. // Remember that we parsed a reference type. It doesn't have type-quals.
  3680. D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc,
  3681. Kind == tok::amp),
  3682. DS.getAttributes(),
  3683. SourceLocation());
  3684. }
  3685. }
  3686. static void diagnoseMisplacedEllipsis(Parser &P, Declarator &D,
  3687. SourceLocation EllipsisLoc) {
  3688. if (EllipsisLoc.isValid()) {
  3689. FixItHint Insertion;
  3690. if (!D.getEllipsisLoc().isValid()) {
  3691. Insertion = FixItHint::CreateInsertion(D.getIdentifierLoc(), "...");
  3692. D.setEllipsisLoc(EllipsisLoc);
  3693. }
  3694. P.Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
  3695. << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !D.hasName();
  3696. }
  3697. }
  3698. /// ParseDirectDeclarator
  3699. /// direct-declarator: [C99 6.7.5]
  3700. /// [C99] identifier
  3701. /// '(' declarator ')'
  3702. /// [GNU] '(' attributes declarator ')'
  3703. /// [C90] direct-declarator '[' constant-expression[opt] ']'
  3704. /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
  3705. /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
  3706. /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
  3707. /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
  3708. /// [C++11] direct-declarator '[' constant-expression[opt] ']'
  3709. /// attribute-specifier-seq[opt]
  3710. /// direct-declarator '(' parameter-type-list ')'
  3711. /// direct-declarator '(' identifier-list[opt] ')'
  3712. /// [GNU] direct-declarator '(' parameter-forward-declarations
  3713. /// parameter-type-list[opt] ')'
  3714. /// [C++] direct-declarator '(' parameter-declaration-clause ')'
  3715. /// cv-qualifier-seq[opt] exception-specification[opt]
  3716. /// [C++11] direct-declarator '(' parameter-declaration-clause ')'
  3717. /// attribute-specifier-seq[opt] cv-qualifier-seq[opt]
  3718. /// ref-qualifier[opt] exception-specification[opt]
  3719. /// [C++] declarator-id
  3720. /// [C++11] declarator-id attribute-specifier-seq[opt]
  3721. ///
  3722. /// declarator-id: [C++ 8]
  3723. /// '...'[opt] id-expression
  3724. /// '::'[opt] nested-name-specifier[opt] type-name
  3725. ///
  3726. /// id-expression: [C++ 5.1]
  3727. /// unqualified-id
  3728. /// qualified-id
  3729. ///
  3730. /// unqualified-id: [C++ 5.1]
  3731. /// identifier
  3732. /// operator-function-id
  3733. /// conversion-function-id
  3734. /// '~' class-name
  3735. /// template-id
  3736. ///
  3737. /// Note, any additional constructs added here may need corresponding changes
  3738. /// in isConstructorDeclarator.
  3739. void Parser::ParseDirectDeclarator(Declarator &D) {
  3740. DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec());
  3741. if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) {
  3742. // ParseDeclaratorInternal might already have parsed the scope.
  3743. if (D.getCXXScopeSpec().isEmpty()) {
  3744. bool EnteringContext = D.getContext() == Declarator::FileContext ||
  3745. D.getContext() == Declarator::MemberContext;
  3746. ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(),
  3747. EnteringContext);
  3748. }
  3749. if (D.getCXXScopeSpec().isValid()) {
  3750. if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
  3751. // Change the declaration context for name lookup, until this function
  3752. // is exited (and the declarator has been parsed).
  3753. DeclScopeObj.EnterDeclaratorScope();
  3754. }
  3755. // C++0x [dcl.fct]p14:
  3756. // There is a syntactic ambiguity when an ellipsis occurs at the end
  3757. // of a parameter-declaration-clause without a preceding comma. In
  3758. // this case, the ellipsis is parsed as part of the
  3759. // abstract-declarator if the type of the parameter names a template
  3760. // parameter pack that has not been expanded; otherwise, it is parsed
  3761. // as part of the parameter-declaration-clause.
  3762. if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() &&
  3763. !((D.getContext() == Declarator::PrototypeContext ||
  3764. D.getContext() == Declarator::BlockLiteralContext) &&
  3765. NextToken().is(tok::r_paren) &&
  3766. !Actions.containsUnexpandedParameterPacks(D))) {
  3767. SourceLocation EllipsisLoc = ConsumeToken();
  3768. if (isPtrOperatorToken(Tok.getKind(), getLangOpts())) {
  3769. // The ellipsis was put in the wrong place. Recover, and explain to
  3770. // the user what they should have done.
  3771. ParseDeclarator(D);
  3772. diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
  3773. return;
  3774. } else
  3775. D.setEllipsisLoc(EllipsisLoc);
  3776. // The ellipsis can't be followed by a parenthesized declarator. We
  3777. // check for that in ParseParenDeclarator, after we have disambiguated
  3778. // the l_paren token.
  3779. }
  3780. if (Tok.is(tok::identifier) || Tok.is(tok::kw_operator) ||
  3781. Tok.is(tok::annot_template_id) || Tok.is(tok::tilde)) {
  3782. // We found something that indicates the start of an unqualified-id.
  3783. // Parse that unqualified-id.
  3784. bool AllowConstructorName;
  3785. if (D.getDeclSpec().hasTypeSpecifier())
  3786. AllowConstructorName = false;
  3787. else if (D.getCXXScopeSpec().isSet())
  3788. AllowConstructorName =
  3789. (D.getContext() == Declarator::FileContext ||
  3790. (D.getContext() == Declarator::MemberContext &&
  3791. D.getDeclSpec().isFriendSpecified()));
  3792. else
  3793. AllowConstructorName = (D.getContext() == Declarator::MemberContext);
  3794. SourceLocation TemplateKWLoc;
  3795. if (ParseUnqualifiedId(D.getCXXScopeSpec(),
  3796. /*EnteringContext=*/true,
  3797. /*AllowDestructorName=*/true,
  3798. AllowConstructorName,
  3799. ParsedType(),
  3800. TemplateKWLoc,
  3801. D.getName()) ||
  3802. // Once we're past the identifier, if the scope was bad, mark the
  3803. // whole declarator bad.
  3804. D.getCXXScopeSpec().isInvalid()) {
  3805. D.SetIdentifier(0, Tok.getLocation());
  3806. D.setInvalidType(true);
  3807. } else {
  3808. // Parsed the unqualified-id; update range information and move along.
  3809. if (D.getSourceRange().getBegin().isInvalid())
  3810. D.SetRangeBegin(D.getName().getSourceRange().getBegin());
  3811. D.SetRangeEnd(D.getName().getSourceRange().getEnd());
  3812. }
  3813. goto PastIdentifier;
  3814. }
  3815. } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) {
  3816. assert(!getLangOpts().CPlusPlus &&
  3817. "There's a C++-specific check for tok::identifier above");
  3818. assert(Tok.getIdentifierInfo() && "Not an identifier?");
  3819. D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  3820. ConsumeToken();
  3821. goto PastIdentifier;
  3822. }
  3823. if (Tok.is(tok::l_paren)) {
  3824. // direct-declarator: '(' declarator ')'
  3825. // direct-declarator: '(' attributes declarator ')'
  3826. // Example: 'char (*X)' or 'int (*XX)(void)'
  3827. ParseParenDeclarator(D);
  3828. // If the declarator was parenthesized, we entered the declarator
  3829. // scope when parsing the parenthesized declarator, then exited
  3830. // the scope already. Re-enter the scope, if we need to.
  3831. if (D.getCXXScopeSpec().isSet()) {
  3832. // If there was an error parsing parenthesized declarator, declarator
  3833. // scope may have been entered before. Don't do it again.
  3834. if (!D.isInvalidType() &&
  3835. Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec()))
  3836. // Change the declaration context for name lookup, until this function
  3837. // is exited (and the declarator has been parsed).
  3838. DeclScopeObj.EnterDeclaratorScope();
  3839. }
  3840. } else if (D.mayOmitIdentifier()) {
  3841. // This could be something simple like "int" (in which case the declarator
  3842. // portion is empty), if an abstract-declarator is allowed.
  3843. D.SetIdentifier(0, Tok.getLocation());
  3844. } else {
  3845. if (Tok.getKind() == tok::annot_pragma_parser_crash)
  3846. LLVM_BUILTIN_TRAP;
  3847. if (D.getContext() == Declarator::MemberContext)
  3848. Diag(Tok, diag::err_expected_member_name_or_semi)
  3849. << D.getDeclSpec().getSourceRange();
  3850. else if (getLangOpts().CPlusPlus)
  3851. Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
  3852. else
  3853. Diag(Tok, diag::err_expected_ident_lparen);
  3854. D.SetIdentifier(0, Tok.getLocation());
  3855. D.setInvalidType(true);
  3856. }
  3857. PastIdentifier:
  3858. assert(D.isPastIdentifier() &&
  3859. "Haven't past the location of the identifier yet?");
  3860. // Don't parse attributes unless we have parsed an unparenthesized name.
  3861. if (D.hasName() && !D.getNumTypeObjects())
  3862. MaybeParseCXX0XAttributes(D);
  3863. while (1) {
  3864. if (Tok.is(tok::l_paren)) {
  3865. // Enter function-declaration scope, limiting any declarators to the
  3866. // function prototype scope, including parameter declarators.
  3867. ParseScope PrototypeScope(this,
  3868. Scope::FunctionPrototypeScope|Scope::DeclScope);
  3869. // The paren may be part of a C++ direct initializer, eg. "int x(1);".
  3870. // In such a case, check if we actually have a function declarator; if it
  3871. // is not, the declarator has been fully parsed.
  3872. bool IsAmbiguous = false;
  3873. if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit()) {
  3874. // The name of the declarator, if any, is tentatively declared within
  3875. // a possible direct initializer.
  3876. TentativelyDeclaredIdentifiers.push_back(D.getIdentifier());
  3877. bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous);
  3878. TentativelyDeclaredIdentifiers.pop_back();
  3879. if (!IsFunctionDecl)
  3880. break;
  3881. }
  3882. ParsedAttributes attrs(AttrFactory);
  3883. BalancedDelimiterTracker T(*this, tok::l_paren);
  3884. T.consumeOpen();
  3885. ParseFunctionDeclarator(D, attrs, T, IsAmbiguous);
  3886. PrototypeScope.Exit();
  3887. } else if (Tok.is(tok::l_square)) {
  3888. ParseBracketDeclarator(D);
  3889. } else {
  3890. break;
  3891. }
  3892. }
  3893. }
  3894. /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is
  3895. /// only called before the identifier, so these are most likely just grouping
  3896. /// parens for precedence. If we find that these are actually function
  3897. /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator.
  3898. ///
  3899. /// direct-declarator:
  3900. /// '(' declarator ')'
  3901. /// [GNU] '(' attributes declarator ')'
  3902. /// direct-declarator '(' parameter-type-list ')'
  3903. /// direct-declarator '(' identifier-list[opt] ')'
  3904. /// [GNU] direct-declarator '(' parameter-forward-declarations
  3905. /// parameter-type-list[opt] ')'
  3906. ///
  3907. void Parser::ParseParenDeclarator(Declarator &D) {
  3908. BalancedDelimiterTracker T(*this, tok::l_paren);
  3909. T.consumeOpen();
  3910. assert(!D.isPastIdentifier() && "Should be called before passing identifier");
  3911. // Eat any attributes before we look at whether this is a grouping or function
  3912. // declarator paren. If this is a grouping paren, the attribute applies to
  3913. // the type being built up, for example:
  3914. // int (__attribute__(()) *x)(long y)
  3915. // If this ends up not being a grouping paren, the attribute applies to the
  3916. // first argument, for example:
  3917. // int (__attribute__(()) int x)
  3918. // In either case, we need to eat any attributes to be able to determine what
  3919. // sort of paren this is.
  3920. //
  3921. ParsedAttributes attrs(AttrFactory);
  3922. bool RequiresArg = false;
  3923. if (Tok.is(tok::kw___attribute)) {
  3924. ParseGNUAttributes(attrs);
  3925. // We require that the argument list (if this is a non-grouping paren) be
  3926. // present even if the attribute list was empty.
  3927. RequiresArg = true;
  3928. }
  3929. // Eat any Microsoft extensions.
  3930. if (Tok.is(tok::kw___cdecl) || Tok.is(tok::kw___stdcall) ||
  3931. Tok.is(tok::kw___thiscall) || Tok.is(tok::kw___fastcall) ||
  3932. Tok.is(tok::kw___w64) || Tok.is(tok::kw___ptr64) ||
  3933. Tok.is(tok::kw___ptr32) || Tok.is(tok::kw___unaligned)) {
  3934. ParseMicrosoftTypeAttributes(attrs);
  3935. }
  3936. // Eat any Borland extensions.
  3937. if (Tok.is(tok::kw___pascal))
  3938. ParseBorlandTypeAttributes(attrs);
  3939. // If we haven't past the identifier yet (or where the identifier would be
  3940. // stored, if this is an abstract declarator), then this is probably just
  3941. // grouping parens. However, if this could be an abstract-declarator, then
  3942. // this could also be the start of function arguments (consider 'void()').
  3943. bool isGrouping;
  3944. if (!D.mayOmitIdentifier()) {
  3945. // If this can't be an abstract-declarator, this *must* be a grouping
  3946. // paren, because we haven't seen the identifier yet.
  3947. isGrouping = true;
  3948. } else if (Tok.is(tok::r_paren) || // 'int()' is a function.
  3949. (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) &&
  3950. NextToken().is(tok::r_paren)) || // C++ int(...)
  3951. isDeclarationSpecifier() || // 'int(int)' is a function.
  3952. isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function.
  3953. // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is
  3954. // considered to be a type, not a K&R identifier-list.
  3955. isGrouping = false;
  3956. } else {
  3957. // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'.
  3958. isGrouping = true;
  3959. }
  3960. // If this is a grouping paren, handle:
  3961. // direct-declarator: '(' declarator ')'
  3962. // direct-declarator: '(' attributes declarator ')'
  3963. if (isGrouping) {
  3964. SourceLocation EllipsisLoc = D.getEllipsisLoc();
  3965. D.setEllipsisLoc(SourceLocation());
  3966. bool hadGroupingParens = D.hasGroupingParens();
  3967. D.setGroupingParens(true);
  3968. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator);
  3969. // Match the ')'.
  3970. T.consumeClose();
  3971. D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(),
  3972. T.getCloseLocation()),
  3973. attrs, T.getCloseLocation());
  3974. D.setGroupingParens(hadGroupingParens);
  3975. // An ellipsis cannot be placed outside parentheses.
  3976. if (EllipsisLoc.isValid())
  3977. diagnoseMisplacedEllipsis(*this, D, EllipsisLoc);
  3978. return;
  3979. }
  3980. // Okay, if this wasn't a grouping paren, it must be the start of a function
  3981. // argument list. Recognize that this declarator will never have an
  3982. // identifier (and remember where it would have been), then call into
  3983. // ParseFunctionDeclarator to handle of argument list.
  3984. D.SetIdentifier(0, Tok.getLocation());
  3985. // Enter function-declaration scope, limiting any declarators to the
  3986. // function prototype scope, including parameter declarators.
  3987. ParseScope PrototypeScope(this,
  3988. Scope::FunctionPrototypeScope|Scope::DeclScope);
  3989. ParseFunctionDeclarator(D, attrs, T, false, RequiresArg);
  3990. PrototypeScope.Exit();
  3991. }
  3992. /// ParseFunctionDeclarator - We are after the identifier and have parsed the
  3993. /// declarator D up to a paren, which indicates that we are parsing function
  3994. /// arguments.
  3995. ///
  3996. /// If FirstArgAttrs is non-null, then the caller parsed those arguments
  3997. /// immediately after the open paren - they should be considered to be the
  3998. /// first argument of a parameter.
  3999. ///
  4000. /// If RequiresArg is true, then the first argument of the function is required
  4001. /// to be present and required to not be an identifier list.
  4002. ///
  4003. /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt],
  4004. /// (C++11) ref-qualifier[opt], exception-specification[opt],
  4005. /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt].
  4006. ///
  4007. /// [C++11] exception-specification:
  4008. /// dynamic-exception-specification
  4009. /// noexcept-specification
  4010. ///
  4011. void Parser::ParseFunctionDeclarator(Declarator &D,
  4012. ParsedAttributes &FirstArgAttrs,
  4013. BalancedDelimiterTracker &Tracker,
  4014. bool IsAmbiguous,
  4015. bool RequiresArg) {
  4016. assert(getCurScope()->isFunctionPrototypeScope() &&
  4017. "Should call from a Function scope");
  4018. // lparen is already consumed!
  4019. assert(D.isPastIdentifier() && "Should not call before identifier!");
  4020. // This should be true when the function has typed arguments.
  4021. // Otherwise, it is treated as a K&R-style function.
  4022. bool HasProto = false;
  4023. // Build up an array of information about the parsed arguments.
  4024. SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
  4025. // Remember where we see an ellipsis, if any.
  4026. SourceLocation EllipsisLoc;
  4027. DeclSpec DS(AttrFactory);
  4028. bool RefQualifierIsLValueRef = true;
  4029. SourceLocation RefQualifierLoc;
  4030. SourceLocation ConstQualifierLoc;
  4031. SourceLocation VolatileQualifierLoc;
  4032. ExceptionSpecificationType ESpecType = EST_None;
  4033. SourceRange ESpecRange;
  4034. SmallVector<ParsedType, 2> DynamicExceptions;
  4035. SmallVector<SourceRange, 2> DynamicExceptionRanges;
  4036. ExprResult NoexceptExpr;
  4037. ParsedAttributes FnAttrs(AttrFactory);
  4038. TypeResult TrailingReturnType;
  4039. Actions.ActOnStartFunctionDeclarator();
  4040. SourceLocation EndLoc;
  4041. if (isFunctionDeclaratorIdentifierList()) {
  4042. if (RequiresArg)
  4043. Diag(Tok, diag::err_argument_required_after_attribute);
  4044. ParseFunctionDeclaratorIdentifierList(D, ParamInfo);
  4045. Tracker.consumeClose();
  4046. EndLoc = Tracker.getCloseLocation();
  4047. } else {
  4048. if (Tok.isNot(tok::r_paren))
  4049. ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc);
  4050. else if (RequiresArg)
  4051. Diag(Tok, diag::err_argument_required_after_attribute);
  4052. HasProto = ParamInfo.size() || getLangOpts().CPlusPlus;
  4053. // If we have the closing ')', eat it.
  4054. Tracker.consumeClose();
  4055. EndLoc = Tracker.getCloseLocation();
  4056. if (getLangOpts().CPlusPlus) {
  4057. // FIXME: Accept these components in any order, and produce fixits to
  4058. // correct the order if the user gets it wrong. Ideally we should deal
  4059. // with the virt-specifier-seq and pure-specifier in the same way.
  4060. // Parse cv-qualifier-seq[opt].
  4061. ParseTypeQualifierListOpt(DS, false /*no attributes*/, false);
  4062. if (!DS.getSourceRange().getEnd().isInvalid()) {
  4063. EndLoc = DS.getSourceRange().getEnd();
  4064. ConstQualifierLoc = DS.getConstSpecLoc();
  4065. VolatileQualifierLoc = DS.getVolatileSpecLoc();
  4066. }
  4067. // Parse ref-qualifier[opt].
  4068. if (Tok.is(tok::amp) || Tok.is(tok::ampamp)) {
  4069. Diag(Tok, getLangOpts().CPlusPlus0x ?
  4070. diag::warn_cxx98_compat_ref_qualifier :
  4071. diag::ext_ref_qualifier);
  4072. RefQualifierIsLValueRef = Tok.is(tok::amp);
  4073. RefQualifierLoc = ConsumeToken();
  4074. EndLoc = RefQualifierLoc;
  4075. }
  4076. // C++11 [expr.prim.general]p3:
  4077. // If a declaration declares a member function or member function
  4078. // template of a class X, the expression this is a prvalue of type
  4079. // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
  4080. // and the end of the function-definition, member-declarator, or
  4081. // declarator.
  4082. bool IsCXX11MemberFunction =
  4083. getLangOpts().CPlusPlus0x &&
  4084. (D.getContext() == Declarator::MemberContext ||
  4085. (D.getContext() == Declarator::FileContext &&
  4086. D.getCXXScopeSpec().isValid() &&
  4087. Actions.CurContext->isRecord()));
  4088. Sema::CXXThisScopeRAII ThisScope(Actions,
  4089. dyn_cast<CXXRecordDecl>(Actions.CurContext),
  4090. DS.getTypeQualifiers(),
  4091. IsCXX11MemberFunction);
  4092. // Parse exception-specification[opt].
  4093. ESpecType = tryParseExceptionSpecification(ESpecRange,
  4094. DynamicExceptions,
  4095. DynamicExceptionRanges,
  4096. NoexceptExpr);
  4097. if (ESpecType != EST_None)
  4098. EndLoc = ESpecRange.getEnd();
  4099. // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes
  4100. // after the exception-specification.
  4101. MaybeParseCXX0XAttributes(FnAttrs);
  4102. // Parse trailing-return-type[opt].
  4103. if (getLangOpts().CPlusPlus0x && Tok.is(tok::arrow)) {
  4104. Diag(Tok, diag::warn_cxx98_compat_trailing_return_type);
  4105. SourceRange Range;
  4106. TrailingReturnType = ParseTrailingReturnType(Range);
  4107. if (Range.getEnd().isValid())
  4108. EndLoc = Range.getEnd();
  4109. }
  4110. }
  4111. }
  4112. // Remember that we parsed a function type, and remember the attributes.
  4113. D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto,
  4114. /*isVariadic=*/EllipsisLoc.isValid(),
  4115. IsAmbiguous, EllipsisLoc,
  4116. ParamInfo.data(), ParamInfo.size(),
  4117. DS.getTypeQualifiers(),
  4118. RefQualifierIsLValueRef,
  4119. RefQualifierLoc, ConstQualifierLoc,
  4120. VolatileQualifierLoc,
  4121. /*MutableLoc=*/SourceLocation(),
  4122. ESpecType, ESpecRange.getBegin(),
  4123. DynamicExceptions.data(),
  4124. DynamicExceptionRanges.data(),
  4125. DynamicExceptions.size(),
  4126. NoexceptExpr.isUsable() ?
  4127. NoexceptExpr.get() : 0,
  4128. Tracker.getOpenLocation(),
  4129. EndLoc, D,
  4130. TrailingReturnType),
  4131. FnAttrs, EndLoc);
  4132. Actions.ActOnEndFunctionDeclarator();
  4133. }
  4134. /// isFunctionDeclaratorIdentifierList - This parameter list may have an
  4135. /// identifier list form for a K&R-style function: void foo(a,b,c)
  4136. ///
  4137. /// Note that identifier-lists are only allowed for normal declarators, not for
  4138. /// abstract-declarators.
  4139. bool Parser::isFunctionDeclaratorIdentifierList() {
  4140. return !getLangOpts().CPlusPlus
  4141. && Tok.is(tok::identifier)
  4142. && !TryAltiVecVectorToken()
  4143. // K&R identifier lists can't have typedefs as identifiers, per C99
  4144. // 6.7.5.3p11.
  4145. && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename))
  4146. // Identifier lists follow a really simple grammar: the identifiers can
  4147. // be followed *only* by a ", identifier" or ")". However, K&R
  4148. // identifier lists are really rare in the brave new modern world, and
  4149. // it is very common for someone to typo a type in a non-K&R style
  4150. // list. If we are presented with something like: "void foo(intptr x,
  4151. // float y)", we don't want to start parsing the function declarator as
  4152. // though it is a K&R style declarator just because intptr is an
  4153. // invalid type.
  4154. //
  4155. // To handle this, we check to see if the token after the first
  4156. // identifier is a "," or ")". Only then do we parse it as an
  4157. // identifier list.
  4158. && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren));
  4159. }
  4160. /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator
  4161. /// we found a K&R-style identifier list instead of a typed parameter list.
  4162. ///
  4163. /// After returning, ParamInfo will hold the parsed parameters.
  4164. ///
  4165. /// identifier-list: [C99 6.7.5]
  4166. /// identifier
  4167. /// identifier-list ',' identifier
  4168. ///
  4169. void Parser::ParseFunctionDeclaratorIdentifierList(
  4170. Declarator &D,
  4171. SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo) {
  4172. // If there was no identifier specified for the declarator, either we are in
  4173. // an abstract-declarator, or we are in a parameter declarator which was found
  4174. // to be abstract. In abstract-declarators, identifier lists are not valid:
  4175. // diagnose this.
  4176. if (!D.getIdentifier())
  4177. Diag(Tok, diag::ext_ident_list_in_param);
  4178. // Maintain an efficient lookup of params we have seen so far.
  4179. llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar;
  4180. while (1) {
  4181. // If this isn't an identifier, report the error and skip until ')'.
  4182. if (Tok.isNot(tok::identifier)) {
  4183. Diag(Tok, diag::err_expected_ident);
  4184. SkipUntil(tok::r_paren, /*StopAtSemi=*/true, /*DontConsume=*/true);
  4185. // Forget we parsed anything.
  4186. ParamInfo.clear();
  4187. return;
  4188. }
  4189. IdentifierInfo *ParmII = Tok.getIdentifierInfo();
  4190. // Reject 'typedef int y; int test(x, y)', but continue parsing.
  4191. if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope()))
  4192. Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII;
  4193. // Verify that the argument identifier has not already been mentioned.
  4194. if (!ParamsSoFar.insert(ParmII)) {
  4195. Diag(Tok, diag::err_param_redefinition) << ParmII;
  4196. } else {
  4197. // Remember this identifier in ParamInfo.
  4198. ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
  4199. Tok.getLocation(),
  4200. 0));
  4201. }
  4202. // Eat the identifier.
  4203. ConsumeToken();
  4204. // The list continues if we see a comma.
  4205. if (Tok.isNot(tok::comma))
  4206. break;
  4207. ConsumeToken();
  4208. }
  4209. }
  4210. /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list
  4211. /// after the opening parenthesis. This function will not parse a K&R-style
  4212. /// identifier list.
  4213. ///
  4214. /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the
  4215. /// caller parsed those arguments immediately after the open paren - they should
  4216. /// be considered to be part of the first parameter.
  4217. ///
  4218. /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will
  4219. /// be the location of the ellipsis, if any was parsed.
  4220. ///
  4221. /// parameter-type-list: [C99 6.7.5]
  4222. /// parameter-list
  4223. /// parameter-list ',' '...'
  4224. /// [C++] parameter-list '...'
  4225. ///
  4226. /// parameter-list: [C99 6.7.5]
  4227. /// parameter-declaration
  4228. /// parameter-list ',' parameter-declaration
  4229. ///
  4230. /// parameter-declaration: [C99 6.7.5]
  4231. /// declaration-specifiers declarator
  4232. /// [C++] declaration-specifiers declarator '=' assignment-expression
  4233. /// [C++11] initializer-clause
  4234. /// [GNU] declaration-specifiers declarator attributes
  4235. /// declaration-specifiers abstract-declarator[opt]
  4236. /// [C++] declaration-specifiers abstract-declarator[opt]
  4237. /// '=' assignment-expression
  4238. /// [GNU] declaration-specifiers abstract-declarator[opt] attributes
  4239. /// [C++11] attribute-specifier-seq parameter-declaration
  4240. ///
  4241. void Parser::ParseParameterDeclarationClause(
  4242. Declarator &D,
  4243. ParsedAttributes &FirstArgAttrs,
  4244. SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
  4245. SourceLocation &EllipsisLoc) {
  4246. while (1) {
  4247. if (Tok.is(tok::ellipsis)) {
  4248. // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq
  4249. // before deciding this was a parameter-declaration-clause.
  4250. EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
  4251. break;
  4252. }
  4253. // Parse the declaration-specifiers.
  4254. // Just use the ParsingDeclaration "scope" of the declarator.
  4255. DeclSpec DS(AttrFactory);
  4256. // Parse any C++11 attributes.
  4257. MaybeParseCXX0XAttributes(DS.getAttributes());
  4258. // Skip any Microsoft attributes before a param.
  4259. if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
  4260. ParseMicrosoftAttributes(DS.getAttributes());
  4261. SourceLocation DSStart = Tok.getLocation();
  4262. // If the caller parsed attributes for the first argument, add them now.
  4263. // Take them so that we only apply the attributes to the first parameter.
  4264. // FIXME: If we can leave the attributes in the token stream somehow, we can
  4265. // get rid of a parameter (FirstArgAttrs) and this statement. It might be
  4266. // too much hassle.
  4267. DS.takeAttributesFrom(FirstArgAttrs);
  4268. ParseDeclarationSpecifiers(DS);
  4269. // Parse the declarator. This is "PrototypeContext", because we must
  4270. // accept either 'declarator' or 'abstract-declarator' here.
  4271. Declarator ParmDecl(DS, Declarator::PrototypeContext);
  4272. ParseDeclarator(ParmDecl);
  4273. // Parse GNU attributes, if present.
  4274. MaybeParseGNUAttributes(ParmDecl);
  4275. // Remember this parsed parameter in ParamInfo.
  4276. IdentifierInfo *ParmII = ParmDecl.getIdentifier();
  4277. // DefArgToks is used when the parsing of default arguments needs
  4278. // to be delayed.
  4279. CachedTokens *DefArgToks = 0;
  4280. // If no parameter was specified, verify that *something* was specified,
  4281. // otherwise we have a missing type and identifier.
  4282. if (DS.isEmpty() && ParmDecl.getIdentifier() == 0 &&
  4283. ParmDecl.getNumTypeObjects() == 0) {
  4284. // Completely missing, emit error.
  4285. Diag(DSStart, diag::err_missing_param);
  4286. } else {
  4287. // Otherwise, we have something. Add it and let semantic analysis try
  4288. // to grok it and add the result to the ParamInfo we are building.
  4289. // Inform the actions module about the parameter declarator, so it gets
  4290. // added to the current scope.
  4291. Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl);
  4292. // Parse the default argument, if any. We parse the default
  4293. // arguments in all dialects; the semantic analysis in
  4294. // ActOnParamDefaultArgument will reject the default argument in
  4295. // C.
  4296. if (Tok.is(tok::equal)) {
  4297. SourceLocation EqualLoc = Tok.getLocation();
  4298. // Parse the default argument
  4299. if (D.getContext() == Declarator::MemberContext) {
  4300. // If we're inside a class definition, cache the tokens
  4301. // corresponding to the default argument. We'll actually parse
  4302. // them when we see the end of the class definition.
  4303. // FIXME: Can we use a smart pointer for Toks?
  4304. DefArgToks = new CachedTokens;
  4305. if (!ConsumeAndStoreUntil(tok::comma, tok::r_paren, *DefArgToks,
  4306. /*StopAtSemi=*/true,
  4307. /*ConsumeFinalToken=*/false)) {
  4308. delete DefArgToks;
  4309. DefArgToks = 0;
  4310. Actions.ActOnParamDefaultArgumentError(Param);
  4311. } else {
  4312. // Mark the end of the default argument so that we know when to
  4313. // stop when we parse it later on.
  4314. Token DefArgEnd;
  4315. DefArgEnd.startToken();
  4316. DefArgEnd.setKind(tok::cxx_defaultarg_end);
  4317. DefArgEnd.setLocation(Tok.getLocation());
  4318. DefArgToks->push_back(DefArgEnd);
  4319. Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc,
  4320. (*DefArgToks)[1].getLocation());
  4321. }
  4322. } else {
  4323. // Consume the '='.
  4324. ConsumeToken();
  4325. // The argument isn't actually potentially evaluated unless it is
  4326. // used.
  4327. EnterExpressionEvaluationContext Eval(Actions,
  4328. Sema::PotentiallyEvaluatedIfUsed,
  4329. Param);
  4330. ExprResult DefArgResult;
  4331. if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
  4332. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  4333. DefArgResult = ParseBraceInitializer();
  4334. } else
  4335. DefArgResult = ParseAssignmentExpression();
  4336. if (DefArgResult.isInvalid()) {
  4337. Actions.ActOnParamDefaultArgumentError(Param);
  4338. SkipUntil(tok::comma, tok::r_paren, true, true);
  4339. } else {
  4340. // Inform the actions module about the default argument
  4341. Actions.ActOnParamDefaultArgument(Param, EqualLoc,
  4342. DefArgResult.take());
  4343. }
  4344. }
  4345. }
  4346. ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII,
  4347. ParmDecl.getIdentifierLoc(), Param,
  4348. DefArgToks));
  4349. }
  4350. // If the next token is a comma, consume it and keep reading arguments.
  4351. if (Tok.isNot(tok::comma)) {
  4352. if (Tok.is(tok::ellipsis)) {
  4353. EllipsisLoc = ConsumeToken(); // Consume the ellipsis.
  4354. if (!getLangOpts().CPlusPlus) {
  4355. // We have ellipsis without a preceding ',', which is ill-formed
  4356. // in C. Complain and provide the fix.
  4357. Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis)
  4358. << FixItHint::CreateInsertion(EllipsisLoc, ", ");
  4359. }
  4360. }
  4361. break;
  4362. }
  4363. // Consume the comma.
  4364. ConsumeToken();
  4365. }
  4366. }
  4367. /// [C90] direct-declarator '[' constant-expression[opt] ']'
  4368. /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']'
  4369. /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']'
  4370. /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']'
  4371. /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']'
  4372. /// [C++11] direct-declarator '[' constant-expression[opt] ']'
  4373. /// attribute-specifier-seq[opt]
  4374. void Parser::ParseBracketDeclarator(Declarator &D) {
  4375. if (CheckProhibitedCXX11Attribute())
  4376. return;
  4377. BalancedDelimiterTracker T(*this, tok::l_square);
  4378. T.consumeOpen();
  4379. // C array syntax has many features, but by-far the most common is [] and [4].
  4380. // This code does a fast path to handle some of the most obvious cases.
  4381. if (Tok.getKind() == tok::r_square) {
  4382. T.consumeClose();
  4383. ParsedAttributes attrs(AttrFactory);
  4384. MaybeParseCXX0XAttributes(attrs);
  4385. // Remember that we parsed the empty array type.
  4386. ExprResult NumElements;
  4387. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, 0,
  4388. T.getOpenLocation(),
  4389. T.getCloseLocation()),
  4390. attrs, T.getCloseLocation());
  4391. return;
  4392. } else if (Tok.getKind() == tok::numeric_constant &&
  4393. GetLookAheadToken(1).is(tok::r_square)) {
  4394. // [4] is very common. Parse the numeric constant expression.
  4395. ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope()));
  4396. ConsumeToken();
  4397. T.consumeClose();
  4398. ParsedAttributes attrs(AttrFactory);
  4399. MaybeParseCXX0XAttributes(attrs);
  4400. // Remember that we parsed a array type, and remember its features.
  4401. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, 0,
  4402. ExprRes.release(),
  4403. T.getOpenLocation(),
  4404. T.getCloseLocation()),
  4405. attrs, T.getCloseLocation());
  4406. return;
  4407. }
  4408. // If valid, this location is the position where we read the 'static' keyword.
  4409. SourceLocation StaticLoc;
  4410. if (Tok.is(tok::kw_static))
  4411. StaticLoc = ConsumeToken();
  4412. // If there is a type-qualifier-list, read it now.
  4413. // Type qualifiers in an array subscript are a C99 feature.
  4414. DeclSpec DS(AttrFactory);
  4415. ParseTypeQualifierListOpt(DS, false /*no attributes*/);
  4416. // If we haven't already read 'static', check to see if there is one after the
  4417. // type-qualifier-list.
  4418. if (!StaticLoc.isValid() && Tok.is(tok::kw_static))
  4419. StaticLoc = ConsumeToken();
  4420. // Handle "direct-declarator [ type-qual-list[opt] * ]".
  4421. bool isStar = false;
  4422. ExprResult NumElements;
  4423. // Handle the case where we have '[*]' as the array size. However, a leading
  4424. // star could be the start of an expression, for example 'X[*p + 4]'. Verify
  4425. // the token after the star is a ']'. Since stars in arrays are
  4426. // infrequent, use of lookahead is not costly here.
  4427. if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) {
  4428. ConsumeToken(); // Eat the '*'.
  4429. if (StaticLoc.isValid()) {
  4430. Diag(StaticLoc, diag::err_unspecified_vla_size_with_static);
  4431. StaticLoc = SourceLocation(); // Drop the static.
  4432. }
  4433. isStar = true;
  4434. } else if (Tok.isNot(tok::r_square)) {
  4435. // Note, in C89, this production uses the constant-expr production instead
  4436. // of assignment-expr. The only difference is that assignment-expr allows
  4437. // things like '=' and '*='. Sema rejects these in C89 mode because they
  4438. // are not i-c-e's, so we don't need to distinguish between the two here.
  4439. // Parse the constant-expression or assignment-expression now (depending
  4440. // on dialect).
  4441. if (getLangOpts().CPlusPlus) {
  4442. NumElements = ParseConstantExpression();
  4443. } else {
  4444. EnterExpressionEvaluationContext Unevaluated(Actions,
  4445. Sema::ConstantEvaluated);
  4446. NumElements = ParseAssignmentExpression();
  4447. }
  4448. }
  4449. // If there was an error parsing the assignment-expression, recover.
  4450. if (NumElements.isInvalid()) {
  4451. D.setInvalidType(true);
  4452. // If the expression was invalid, skip it.
  4453. SkipUntil(tok::r_square);
  4454. return;
  4455. }
  4456. T.consumeClose();
  4457. ParsedAttributes attrs(AttrFactory);
  4458. MaybeParseCXX0XAttributes(attrs);
  4459. // Remember that we parsed a array type, and remember its features.
  4460. D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(),
  4461. StaticLoc.isValid(), isStar,
  4462. NumElements.release(),
  4463. T.getOpenLocation(),
  4464. T.getCloseLocation()),
  4465. attrs, T.getCloseLocation());
  4466. }
  4467. /// [GNU] typeof-specifier:
  4468. /// typeof ( expressions )
  4469. /// typeof ( type-name )
  4470. /// [GNU/C++] typeof unary-expression
  4471. ///
  4472. void Parser::ParseTypeofSpecifier(DeclSpec &DS) {
  4473. assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier");
  4474. Token OpTok = Tok;
  4475. SourceLocation StartLoc = ConsumeToken();
  4476. const bool hasParens = Tok.is(tok::l_paren);
  4477. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  4478. bool isCastExpr;
  4479. ParsedType CastTy;
  4480. SourceRange CastRange;
  4481. ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr,
  4482. CastTy, CastRange);
  4483. if (hasParens)
  4484. DS.setTypeofParensRange(CastRange);
  4485. if (CastRange.getEnd().isInvalid())
  4486. // FIXME: Not accurate, the range gets one token more than it should.
  4487. DS.SetRangeEnd(Tok.getLocation());
  4488. else
  4489. DS.SetRangeEnd(CastRange.getEnd());
  4490. if (isCastExpr) {
  4491. if (!CastTy) {
  4492. DS.SetTypeSpecError();
  4493. return;
  4494. }
  4495. const char *PrevSpec = 0;
  4496. unsigned DiagID;
  4497. // Check for duplicate type specifiers (e.g. "int typeof(int)").
  4498. if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec,
  4499. DiagID, CastTy))
  4500. Diag(StartLoc, DiagID) << PrevSpec;
  4501. return;
  4502. }
  4503. // If we get here, the operand to the typeof was an expresion.
  4504. if (Operand.isInvalid()) {
  4505. DS.SetTypeSpecError();
  4506. return;
  4507. }
  4508. // We might need to transform the operand if it is potentially evaluated.
  4509. Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get());
  4510. if (Operand.isInvalid()) {
  4511. DS.SetTypeSpecError();
  4512. return;
  4513. }
  4514. const char *PrevSpec = 0;
  4515. unsigned DiagID;
  4516. // Check for duplicate type specifiers (e.g. "int typeof(int)").
  4517. if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec,
  4518. DiagID, Operand.get()))
  4519. Diag(StartLoc, DiagID) << PrevSpec;
  4520. }
  4521. /// [C11] atomic-specifier:
  4522. /// _Atomic ( type-name )
  4523. ///
  4524. void Parser::ParseAtomicSpecifier(DeclSpec &DS) {
  4525. assert(Tok.is(tok::kw__Atomic) && "Not an atomic specifier");
  4526. SourceLocation StartLoc = ConsumeToken();
  4527. BalancedDelimiterTracker T(*this, tok::l_paren);
  4528. if (T.expectAndConsume(diag::err_expected_lparen_after, "_Atomic")) {
  4529. SkipUntil(tok::r_paren);
  4530. return;
  4531. }
  4532. TypeResult Result = ParseTypeName();
  4533. if (Result.isInvalid()) {
  4534. SkipUntil(tok::r_paren);
  4535. return;
  4536. }
  4537. // Match the ')'
  4538. T.consumeClose();
  4539. if (T.getCloseLocation().isInvalid())
  4540. return;
  4541. DS.setTypeofParensRange(T.getRange());
  4542. DS.SetRangeEnd(T.getCloseLocation());
  4543. const char *PrevSpec = 0;
  4544. unsigned DiagID;
  4545. if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec,
  4546. DiagID, Result.release()))
  4547. Diag(StartLoc, DiagID) << PrevSpec;
  4548. }
  4549. /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called
  4550. /// from TryAltiVecVectorToken.
  4551. bool Parser::TryAltiVecVectorTokenOutOfLine() {
  4552. Token Next = NextToken();
  4553. switch (Next.getKind()) {
  4554. default: return false;
  4555. case tok::kw_short:
  4556. case tok::kw_long:
  4557. case tok::kw_signed:
  4558. case tok::kw_unsigned:
  4559. case tok::kw_void:
  4560. case tok::kw_char:
  4561. case tok::kw_int:
  4562. case tok::kw_float:
  4563. case tok::kw_double:
  4564. case tok::kw_bool:
  4565. case tok::kw___pixel:
  4566. Tok.setKind(tok::kw___vector);
  4567. return true;
  4568. case tok::identifier:
  4569. if (Next.getIdentifierInfo() == Ident_pixel) {
  4570. Tok.setKind(tok::kw___vector);
  4571. return true;
  4572. }
  4573. return false;
  4574. }
  4575. }
  4576. bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
  4577. const char *&PrevSpec, unsigned &DiagID,
  4578. bool &isInvalid) {
  4579. if (Tok.getIdentifierInfo() == Ident_vector) {
  4580. Token Next = NextToken();
  4581. switch (Next.getKind()) {
  4582. case tok::kw_short:
  4583. case tok::kw_long:
  4584. case tok::kw_signed:
  4585. case tok::kw_unsigned:
  4586. case tok::kw_void:
  4587. case tok::kw_char:
  4588. case tok::kw_int:
  4589. case tok::kw_float:
  4590. case tok::kw_double:
  4591. case tok::kw_bool:
  4592. case tok::kw___pixel:
  4593. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
  4594. return true;
  4595. case tok::identifier:
  4596. if (Next.getIdentifierInfo() == Ident_pixel) {
  4597. isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID);
  4598. return true;
  4599. }
  4600. break;
  4601. default:
  4602. break;
  4603. }
  4604. } else if ((Tok.getIdentifierInfo() == Ident_pixel) &&
  4605. DS.isTypeAltiVecVector()) {
  4606. isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID);
  4607. return true;
  4608. }
  4609. return false;
  4610. }