ParseDeclCXX.cpp 177 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759
  1. //===--- ParseDeclCXX.cpp - C++ Declaration Parsing -------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the C++ Declaration portions of the Parser interfaces.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Parse/Parser.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/DeclTemplate.h"
  15. #include "clang/AST/PrettyDeclStackTrace.h"
  16. #include "clang/Basic/Attributes.h"
  17. #include "clang/Basic/CharInfo.h"
  18. #include "clang/Basic/OperatorKinds.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "clang/Parse/ParseDiagnostic.h"
  21. #include "clang/Parse/RAIIObjectsForParser.h"
  22. #include "clang/Sema/DeclSpec.h"
  23. #include "clang/Sema/ParsedTemplate.h"
  24. #include "clang/Sema/Scope.h"
  25. #include "llvm/ADT/SmallString.h"
  26. #include "llvm/Support/TimeProfiler.h"
  27. using namespace clang;
  28. /// ParseNamespace - We know that the current token is a namespace keyword. This
  29. /// may either be a top level namespace or a block-level namespace alias. If
  30. /// there was an inline keyword, it has already been parsed.
  31. ///
  32. /// namespace-definition: [C++: namespace.def]
  33. /// named-namespace-definition
  34. /// unnamed-namespace-definition
  35. /// nested-namespace-definition
  36. ///
  37. /// named-namespace-definition:
  38. /// 'inline'[opt] 'namespace' attributes[opt] identifier '{'
  39. /// namespace-body '}'
  40. ///
  41. /// unnamed-namespace-definition:
  42. /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}'
  43. ///
  44. /// nested-namespace-definition:
  45. /// 'namespace' enclosing-namespace-specifier '::' 'inline'[opt]
  46. /// identifier '{' namespace-body '}'
  47. ///
  48. /// enclosing-namespace-specifier:
  49. /// identifier
  50. /// enclosing-namespace-specifier '::' 'inline'[opt] identifier
  51. ///
  52. /// namespace-alias-definition: [C++ 7.3.2: namespace.alias]
  53. /// 'namespace' identifier '=' qualified-namespace-specifier ';'
  54. ///
  55. Parser::DeclGroupPtrTy Parser::ParseNamespace(DeclaratorContext Context,
  56. SourceLocation &DeclEnd,
  57. SourceLocation InlineLoc) {
  58. assert(Tok.is(tok::kw_namespace) && "Not a namespace!");
  59. SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'.
  60. ObjCDeclContextSwitch ObjCDC(*this);
  61. if (Tok.is(tok::code_completion)) {
  62. cutOffParsing();
  63. Actions.CodeCompleteNamespaceDecl(getCurScope());
  64. return nullptr;
  65. }
  66. SourceLocation IdentLoc;
  67. IdentifierInfo *Ident = nullptr;
  68. InnerNamespaceInfoList ExtraNSs;
  69. SourceLocation FirstNestedInlineLoc;
  70. ParsedAttributesWithRange attrs(AttrFactory);
  71. SourceLocation attrLoc;
  72. if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
  73. Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
  74. ? diag::warn_cxx14_compat_ns_enum_attribute
  75. : diag::ext_ns_enum_attribute)
  76. << 0 /*namespace*/;
  77. attrLoc = Tok.getLocation();
  78. ParseCXX11Attributes(attrs);
  79. }
  80. if (Tok.is(tok::identifier)) {
  81. Ident = Tok.getIdentifierInfo();
  82. IdentLoc = ConsumeToken(); // eat the identifier.
  83. while (Tok.is(tok::coloncolon) &&
  84. (NextToken().is(tok::identifier) ||
  85. (NextToken().is(tok::kw_inline) &&
  86. GetLookAheadToken(2).is(tok::identifier)))) {
  87. InnerNamespaceInfo Info;
  88. Info.NamespaceLoc = ConsumeToken();
  89. if (Tok.is(tok::kw_inline)) {
  90. Info.InlineLoc = ConsumeToken();
  91. if (FirstNestedInlineLoc.isInvalid())
  92. FirstNestedInlineLoc = Info.InlineLoc;
  93. }
  94. Info.Ident = Tok.getIdentifierInfo();
  95. Info.IdentLoc = ConsumeToken();
  96. ExtraNSs.push_back(Info);
  97. }
  98. }
  99. // A nested namespace definition cannot have attributes.
  100. if (!ExtraNSs.empty() && attrLoc.isValid())
  101. Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute);
  102. // Read label attributes, if present.
  103. if (Tok.is(tok::kw___attribute)) {
  104. attrLoc = Tok.getLocation();
  105. ParseGNUAttributes(attrs);
  106. }
  107. if (Tok.is(tok::equal)) {
  108. if (!Ident) {
  109. Diag(Tok, diag::err_expected) << tok::identifier;
  110. // Skip to end of the definition and eat the ';'.
  111. SkipUntil(tok::semi);
  112. return nullptr;
  113. }
  114. if (attrLoc.isValid())
  115. Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
  116. if (InlineLoc.isValid())
  117. Diag(InlineLoc, diag::err_inline_namespace_alias)
  118. << FixItHint::CreateRemoval(InlineLoc);
  119. Decl *NSAlias = ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd);
  120. return Actions.ConvertDeclToDeclGroup(NSAlias);
  121. }
  122. BalancedDelimiterTracker T(*this, tok::l_brace);
  123. if (T.consumeOpen()) {
  124. if (Ident)
  125. Diag(Tok, diag::err_expected) << tok::l_brace;
  126. else
  127. Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace;
  128. return nullptr;
  129. }
  130. if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() ||
  131. getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() ||
  132. getCurScope()->getFnParent()) {
  133. Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope);
  134. SkipUntil(tok::r_brace);
  135. return nullptr;
  136. }
  137. if (ExtraNSs.empty()) {
  138. // Normal namespace definition, not a nested-namespace-definition.
  139. } else if (InlineLoc.isValid()) {
  140. Diag(InlineLoc, diag::err_inline_nested_namespace_definition);
  141. } else if (getLangOpts().CPlusPlus20) {
  142. Diag(ExtraNSs[0].NamespaceLoc,
  143. diag::warn_cxx14_compat_nested_namespace_definition);
  144. if (FirstNestedInlineLoc.isValid())
  145. Diag(FirstNestedInlineLoc,
  146. diag::warn_cxx17_compat_inline_nested_namespace_definition);
  147. } else if (getLangOpts().CPlusPlus17) {
  148. Diag(ExtraNSs[0].NamespaceLoc,
  149. diag::warn_cxx14_compat_nested_namespace_definition);
  150. if (FirstNestedInlineLoc.isValid())
  151. Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
  152. } else {
  153. TentativeParsingAction TPA(*this);
  154. SkipUntil(tok::r_brace, StopBeforeMatch);
  155. Token rBraceToken = Tok;
  156. TPA.Revert();
  157. if (!rBraceToken.is(tok::r_brace)) {
  158. Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
  159. << SourceRange(ExtraNSs.front().NamespaceLoc,
  160. ExtraNSs.back().IdentLoc);
  161. } else {
  162. std::string NamespaceFix;
  163. for (const auto &ExtraNS : ExtraNSs) {
  164. NamespaceFix += " { ";
  165. if (ExtraNS.InlineLoc.isValid())
  166. NamespaceFix += "inline ";
  167. NamespaceFix += "namespace ";
  168. NamespaceFix += ExtraNS.Ident->getName();
  169. }
  170. std::string RBraces;
  171. for (unsigned i = 0, e = ExtraNSs.size(); i != e; ++i)
  172. RBraces += "} ";
  173. Diag(ExtraNSs[0].NamespaceLoc, diag::ext_nested_namespace_definition)
  174. << FixItHint::CreateReplacement(
  175. SourceRange(ExtraNSs.front().NamespaceLoc,
  176. ExtraNSs.back().IdentLoc),
  177. NamespaceFix)
  178. << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces);
  179. }
  180. // Warn about nested inline namespaces.
  181. if (FirstNestedInlineLoc.isValid())
  182. Diag(FirstNestedInlineLoc, diag::ext_inline_nested_namespace_definition);
  183. }
  184. // If we're still good, complain about inline namespaces in non-C++0x now.
  185. if (InlineLoc.isValid())
  186. Diag(InlineLoc, getLangOpts().CPlusPlus11 ?
  187. diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace);
  188. // Enter a scope for the namespace.
  189. ParseScope NamespaceScope(this, Scope::DeclScope);
  190. UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
  191. Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
  192. getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident,
  193. T.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
  194. PrettyDeclStackTraceEntry CrashInfo(Actions.Context, NamespcDecl,
  195. NamespaceLoc, "parsing namespace");
  196. // Parse the contents of the namespace. This includes parsing recovery on
  197. // any improperly nested namespaces.
  198. ParseInnerNamespace(ExtraNSs, 0, InlineLoc, attrs, T);
  199. // Leave the namespace scope.
  200. NamespaceScope.Exit();
  201. DeclEnd = T.getCloseLocation();
  202. Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd);
  203. return Actions.ConvertDeclToDeclGroup(NamespcDecl,
  204. ImplicitUsingDirectiveDecl);
  205. }
  206. /// ParseInnerNamespace - Parse the contents of a namespace.
  207. void Parser::ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs,
  208. unsigned int index, SourceLocation &InlineLoc,
  209. ParsedAttributes &attrs,
  210. BalancedDelimiterTracker &Tracker) {
  211. if (index == InnerNSs.size()) {
  212. while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
  213. Tok.isNot(tok::eof)) {
  214. ParsedAttributesWithRange attrs(AttrFactory);
  215. MaybeParseCXX11Attributes(attrs);
  216. ParseExternalDeclaration(attrs);
  217. }
  218. // The caller is what called check -- we are simply calling
  219. // the close for it.
  220. Tracker.consumeClose();
  221. return;
  222. }
  223. // Handle a nested namespace definition.
  224. // FIXME: Preserve the source information through to the AST rather than
  225. // desugaring it here.
  226. ParseScope NamespaceScope(this, Scope::DeclScope);
  227. UsingDirectiveDecl *ImplicitUsingDirectiveDecl = nullptr;
  228. Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(
  229. getCurScope(), InnerNSs[index].InlineLoc, InnerNSs[index].NamespaceLoc,
  230. InnerNSs[index].IdentLoc, InnerNSs[index].Ident,
  231. Tracker.getOpenLocation(), attrs, ImplicitUsingDirectiveDecl);
  232. assert(!ImplicitUsingDirectiveDecl &&
  233. "nested namespace definition cannot define anonymous namespace");
  234. ParseInnerNamespace(InnerNSs, ++index, InlineLoc, attrs, Tracker);
  235. NamespaceScope.Exit();
  236. Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation());
  237. }
  238. /// ParseNamespaceAlias - Parse the part after the '=' in a namespace
  239. /// alias definition.
  240. ///
  241. Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc,
  242. SourceLocation AliasLoc,
  243. IdentifierInfo *Alias,
  244. SourceLocation &DeclEnd) {
  245. assert(Tok.is(tok::equal) && "Not equal token");
  246. ConsumeToken(); // eat the '='.
  247. if (Tok.is(tok::code_completion)) {
  248. cutOffParsing();
  249. Actions.CodeCompleteNamespaceAliasDecl(getCurScope());
  250. return nullptr;
  251. }
  252. CXXScopeSpec SS;
  253. // Parse (optional) nested-name-specifier.
  254. ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
  255. /*ObjectHasErrors=*/false,
  256. /*EnteringContext=*/false,
  257. /*MayBePseudoDestructor=*/nullptr,
  258. /*IsTypename=*/false,
  259. /*LastII=*/nullptr,
  260. /*OnlyNamespace=*/true);
  261. if (Tok.isNot(tok::identifier)) {
  262. Diag(Tok, diag::err_expected_namespace_name);
  263. // Skip to end of the definition and eat the ';'.
  264. SkipUntil(tok::semi);
  265. return nullptr;
  266. }
  267. if (SS.isInvalid()) {
  268. // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
  269. // Skip to end of the definition and eat the ';'.
  270. SkipUntil(tok::semi);
  271. return nullptr;
  272. }
  273. // Parse identifier.
  274. IdentifierInfo *Ident = Tok.getIdentifierInfo();
  275. SourceLocation IdentLoc = ConsumeToken();
  276. // Eat the ';'.
  277. DeclEnd = Tok.getLocation();
  278. if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name))
  279. SkipUntil(tok::semi);
  280. return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc,
  281. Alias, SS, IdentLoc, Ident);
  282. }
  283. /// ParseLinkage - We know that the current token is a string_literal
  284. /// and just before that, that extern was seen.
  285. ///
  286. /// linkage-specification: [C++ 7.5p2: dcl.link]
  287. /// 'extern' string-literal '{' declaration-seq[opt] '}'
  288. /// 'extern' string-literal declaration
  289. ///
  290. Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context) {
  291. assert(isTokenStringLiteral() && "Not a string literal!");
  292. ExprResult Lang = ParseStringLiteralExpression(false);
  293. ParseScope LinkageScope(this, Scope::DeclScope);
  294. Decl *LinkageSpec =
  295. Lang.isInvalid()
  296. ? nullptr
  297. : Actions.ActOnStartLinkageSpecification(
  298. getCurScope(), DS.getSourceRange().getBegin(), Lang.get(),
  299. Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
  300. ParsedAttributesWithRange attrs(AttrFactory);
  301. MaybeParseCXX11Attributes(attrs);
  302. if (Tok.isNot(tok::l_brace)) {
  303. // Reset the source range in DS, as the leading "extern"
  304. // does not really belong to the inner declaration ...
  305. DS.SetRangeStart(SourceLocation());
  306. DS.SetRangeEnd(SourceLocation());
  307. // ... but anyway remember that such an "extern" was seen.
  308. DS.setExternInLinkageSpec(true);
  309. ParseExternalDeclaration(attrs, &DS);
  310. return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
  311. getCurScope(), LinkageSpec, SourceLocation())
  312. : nullptr;
  313. }
  314. DS.abort();
  315. ProhibitAttributes(attrs);
  316. BalancedDelimiterTracker T(*this, tok::l_brace);
  317. T.consumeOpen();
  318. unsigned NestedModules = 0;
  319. while (true) {
  320. switch (Tok.getKind()) {
  321. case tok::annot_module_begin:
  322. ++NestedModules;
  323. ParseTopLevelDecl();
  324. continue;
  325. case tok::annot_module_end:
  326. if (!NestedModules)
  327. break;
  328. --NestedModules;
  329. ParseTopLevelDecl();
  330. continue;
  331. case tok::annot_module_include:
  332. ParseTopLevelDecl();
  333. continue;
  334. case tok::eof:
  335. break;
  336. case tok::r_brace:
  337. if (!NestedModules)
  338. break;
  339. LLVM_FALLTHROUGH;
  340. default:
  341. ParsedAttributesWithRange attrs(AttrFactory);
  342. MaybeParseCXX11Attributes(attrs);
  343. ParseExternalDeclaration(attrs);
  344. continue;
  345. }
  346. break;
  347. }
  348. T.consumeClose();
  349. return LinkageSpec ? Actions.ActOnFinishLinkageSpecification(
  350. getCurScope(), LinkageSpec, T.getCloseLocation())
  351. : nullptr;
  352. }
  353. /// Parse a C++ Modules TS export-declaration.
  354. ///
  355. /// export-declaration:
  356. /// 'export' declaration
  357. /// 'export' '{' declaration-seq[opt] '}'
  358. ///
  359. Decl *Parser::ParseExportDeclaration() {
  360. assert(Tok.is(tok::kw_export));
  361. SourceLocation ExportLoc = ConsumeToken();
  362. ParseScope ExportScope(this, Scope::DeclScope);
  363. Decl *ExportDecl = Actions.ActOnStartExportDecl(
  364. getCurScope(), ExportLoc,
  365. Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation());
  366. if (Tok.isNot(tok::l_brace)) {
  367. // FIXME: Factor out a ParseExternalDeclarationWithAttrs.
  368. ParsedAttributesWithRange Attrs(AttrFactory);
  369. MaybeParseCXX11Attributes(Attrs);
  370. MaybeParseMicrosoftAttributes(Attrs);
  371. ParseExternalDeclaration(Attrs);
  372. return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
  373. SourceLocation());
  374. }
  375. BalancedDelimiterTracker T(*this, tok::l_brace);
  376. T.consumeOpen();
  377. // The Modules TS draft says "An export-declaration shall declare at least one
  378. // entity", but the intent is that it shall contain at least one declaration.
  379. if (Tok.is(tok::r_brace) && getLangOpts().ModulesTS) {
  380. Diag(ExportLoc, diag::err_export_empty)
  381. << SourceRange(ExportLoc, Tok.getLocation());
  382. }
  383. while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
  384. Tok.isNot(tok::eof)) {
  385. ParsedAttributesWithRange Attrs(AttrFactory);
  386. MaybeParseCXX11Attributes(Attrs);
  387. MaybeParseMicrosoftAttributes(Attrs);
  388. ParseExternalDeclaration(Attrs);
  389. }
  390. T.consumeClose();
  391. return Actions.ActOnFinishExportDecl(getCurScope(), ExportDecl,
  392. T.getCloseLocation());
  393. }
  394. /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or
  395. /// using-directive. Assumes that current token is 'using'.
  396. Parser::DeclGroupPtrTy
  397. Parser::ParseUsingDirectiveOrDeclaration(DeclaratorContext Context,
  398. const ParsedTemplateInfo &TemplateInfo,
  399. SourceLocation &DeclEnd,
  400. ParsedAttributesWithRange &attrs) {
  401. assert(Tok.is(tok::kw_using) && "Not using token");
  402. ObjCDeclContextSwitch ObjCDC(*this);
  403. // Eat 'using'.
  404. SourceLocation UsingLoc = ConsumeToken();
  405. if (Tok.is(tok::code_completion)) {
  406. cutOffParsing();
  407. Actions.CodeCompleteUsing(getCurScope());
  408. return nullptr;
  409. }
  410. // Consume unexpected 'template' keywords.
  411. while (Tok.is(tok::kw_template)) {
  412. SourceLocation TemplateLoc = ConsumeToken();
  413. Diag(TemplateLoc, diag::err_unexpected_template_after_using)
  414. << FixItHint::CreateRemoval(TemplateLoc);
  415. }
  416. // 'using namespace' means this is a using-directive.
  417. if (Tok.is(tok::kw_namespace)) {
  418. // Template parameters are always an error here.
  419. if (TemplateInfo.Kind) {
  420. SourceRange R = TemplateInfo.getSourceRange();
  421. Diag(UsingLoc, diag::err_templated_using_directive_declaration)
  422. << 0 /* directive */ << R << FixItHint::CreateRemoval(R);
  423. }
  424. Decl *UsingDir = ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs);
  425. return Actions.ConvertDeclToDeclGroup(UsingDir);
  426. }
  427. // Otherwise, it must be a using-declaration or an alias-declaration.
  428. return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd, attrs,
  429. AS_none);
  430. }
  431. /// ParseUsingDirective - Parse C++ using-directive, assumes
  432. /// that current token is 'namespace' and 'using' was already parsed.
  433. ///
  434. /// using-directive: [C++ 7.3.p4: namespace.udir]
  435. /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
  436. /// namespace-name ;
  437. /// [GNU] using-directive:
  438. /// 'using' 'namespace' ::[opt] nested-name-specifier[opt]
  439. /// namespace-name attributes[opt] ;
  440. ///
  441. Decl *Parser::ParseUsingDirective(DeclaratorContext Context,
  442. SourceLocation UsingLoc,
  443. SourceLocation &DeclEnd,
  444. ParsedAttributes &attrs) {
  445. assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token");
  446. // Eat 'namespace'.
  447. SourceLocation NamespcLoc = ConsumeToken();
  448. if (Tok.is(tok::code_completion)) {
  449. cutOffParsing();
  450. Actions.CodeCompleteUsingDirective(getCurScope());
  451. return nullptr;
  452. }
  453. CXXScopeSpec SS;
  454. // Parse (optional) nested-name-specifier.
  455. ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
  456. /*ObjectHasErrors=*/false,
  457. /*EnteringContext=*/false,
  458. /*MayBePseudoDestructor=*/nullptr,
  459. /*IsTypename=*/false,
  460. /*LastII=*/nullptr,
  461. /*OnlyNamespace=*/true);
  462. IdentifierInfo *NamespcName = nullptr;
  463. SourceLocation IdentLoc = SourceLocation();
  464. // Parse namespace-name.
  465. if (Tok.isNot(tok::identifier)) {
  466. Diag(Tok, diag::err_expected_namespace_name);
  467. // If there was invalid namespace name, skip to end of decl, and eat ';'.
  468. SkipUntil(tok::semi);
  469. // FIXME: Are there cases, when we would like to call ActOnUsingDirective?
  470. return nullptr;
  471. }
  472. if (SS.isInvalid()) {
  473. // Diagnostics have been emitted in ParseOptionalCXXScopeSpecifier.
  474. // Skip to end of the definition and eat the ';'.
  475. SkipUntil(tok::semi);
  476. return nullptr;
  477. }
  478. // Parse identifier.
  479. NamespcName = Tok.getIdentifierInfo();
  480. IdentLoc = ConsumeToken();
  481. // Parse (optional) attributes (most likely GNU strong-using extension).
  482. bool GNUAttr = false;
  483. if (Tok.is(tok::kw___attribute)) {
  484. GNUAttr = true;
  485. ParseGNUAttributes(attrs);
  486. }
  487. // Eat ';'.
  488. DeclEnd = Tok.getLocation();
  489. if (ExpectAndConsume(tok::semi,
  490. GNUAttr ? diag::err_expected_semi_after_attribute_list
  491. : diag::err_expected_semi_after_namespace_name))
  492. SkipUntil(tok::semi);
  493. return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS,
  494. IdentLoc, NamespcName, attrs);
  495. }
  496. /// Parse a using-declarator (or the identifier in a C++11 alias-declaration).
  497. ///
  498. /// using-declarator:
  499. /// 'typename'[opt] nested-name-specifier unqualified-id
  500. ///
  501. bool Parser::ParseUsingDeclarator(DeclaratorContext Context,
  502. UsingDeclarator &D) {
  503. D.clear();
  504. // Ignore optional 'typename'.
  505. // FIXME: This is wrong; we should parse this as a typename-specifier.
  506. TryConsumeToken(tok::kw_typename, D.TypenameLoc);
  507. if (Tok.is(tok::kw___super)) {
  508. Diag(Tok.getLocation(), diag::err_super_in_using_declaration);
  509. return true;
  510. }
  511. // Parse nested-name-specifier.
  512. IdentifierInfo *LastII = nullptr;
  513. if (ParseOptionalCXXScopeSpecifier(D.SS, /*ObjectType=*/nullptr,
  514. /*ObjectHasErrors=*/false,
  515. /*EnteringContext=*/false,
  516. /*MayBePseudoDtor=*/nullptr,
  517. /*IsTypename=*/false,
  518. /*LastII=*/&LastII,
  519. /*OnlyNamespace=*/false,
  520. /*InUsingDeclaration=*/true))
  521. return true;
  522. if (D.SS.isInvalid())
  523. return true;
  524. // Parse the unqualified-id. We allow parsing of both constructor and
  525. // destructor names and allow the action module to diagnose any semantic
  526. // errors.
  527. //
  528. // C++11 [class.qual]p2:
  529. // [...] in a using-declaration that is a member-declaration, if the name
  530. // specified after the nested-name-specifier is the same as the identifier
  531. // or the simple-template-id's template-name in the last component of the
  532. // nested-name-specifier, the name is [...] considered to name the
  533. // constructor.
  534. if (getLangOpts().CPlusPlus11 && Context == DeclaratorContext::Member &&
  535. Tok.is(tok::identifier) &&
  536. (NextToken().is(tok::semi) || NextToken().is(tok::comma) ||
  537. NextToken().is(tok::ellipsis) || NextToken().is(tok::l_square) ||
  538. NextToken().is(tok::kw___attribute)) &&
  539. D.SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() &&
  540. !D.SS.getScopeRep()->getAsNamespace() &&
  541. !D.SS.getScopeRep()->getAsNamespaceAlias()) {
  542. SourceLocation IdLoc = ConsumeToken();
  543. ParsedType Type =
  544. Actions.getInheritingConstructorName(D.SS, IdLoc, *LastII);
  545. D.Name.setConstructorName(Type, IdLoc, IdLoc);
  546. } else {
  547. if (ParseUnqualifiedId(
  548. D.SS, /*ObjectType=*/nullptr,
  549. /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
  550. /*AllowDestructorName=*/true,
  551. /*AllowConstructorName=*/
  552. !(Tok.is(tok::identifier) && NextToken().is(tok::equal)),
  553. /*AllowDeductionGuide=*/false, nullptr, D.Name))
  554. return true;
  555. }
  556. if (TryConsumeToken(tok::ellipsis, D.EllipsisLoc))
  557. Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
  558. diag::warn_cxx17_compat_using_declaration_pack :
  559. diag::ext_using_declaration_pack);
  560. return false;
  561. }
  562. /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration.
  563. /// Assumes that 'using' was already seen.
  564. ///
  565. /// using-declaration: [C++ 7.3.p3: namespace.udecl]
  566. /// 'using' using-declarator-list[opt] ;
  567. ///
  568. /// using-declarator-list: [C++1z]
  569. /// using-declarator '...'[opt]
  570. /// using-declarator-list ',' using-declarator '...'[opt]
  571. ///
  572. /// using-declarator-list: [C++98-14]
  573. /// using-declarator
  574. ///
  575. /// alias-declaration: C++11 [dcl.dcl]p1
  576. /// 'using' identifier attribute-specifier-seq[opt] = type-id ;
  577. ///
  578. /// using-enum-declaration: [C++20, dcl.enum]
  579. /// 'using' elaborated-enum-specifier ;
  580. ///
  581. /// elaborated-enum-specifier:
  582. /// 'enum' nested-name-specifier[opt] identifier
  583. Parser::DeclGroupPtrTy
  584. Parser::ParseUsingDeclaration(
  585. DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
  586. SourceLocation UsingLoc, SourceLocation &DeclEnd,
  587. ParsedAttributesWithRange &PrefixAttrs, AccessSpecifier AS) {
  588. SourceLocation UELoc;
  589. bool InInitStatement = Context == DeclaratorContext::SelectionInit ||
  590. Context == DeclaratorContext::ForInit;
  591. if (TryConsumeToken(tok::kw_enum, UELoc) && !InInitStatement) {
  592. // C++20 using-enum
  593. Diag(UELoc, getLangOpts().CPlusPlus20
  594. ? diag::warn_cxx17_compat_using_enum_declaration
  595. : diag::ext_using_enum_declaration);
  596. DiagnoseCXX11AttributeExtension(PrefixAttrs);
  597. DeclSpec DS(AttrFactory);
  598. ParseEnumSpecifier(UELoc, DS, TemplateInfo, AS,
  599. // DSC_trailing has the semantics we desire
  600. DeclSpecContext::DSC_trailing);
  601. if (TemplateInfo.Kind) {
  602. SourceRange R = TemplateInfo.getSourceRange();
  603. Diag(UsingLoc, diag::err_templated_using_directive_declaration)
  604. << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
  605. return nullptr;
  606. }
  607. Decl *UED = Actions.ActOnUsingEnumDeclaration(getCurScope(), AS, UsingLoc,
  608. UELoc, DS);
  609. DeclEnd = Tok.getLocation();
  610. if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  611. "using-enum declaration"))
  612. SkipUntil(tok::semi);
  613. return Actions.ConvertDeclToDeclGroup(UED);
  614. }
  615. // Check for misplaced attributes before the identifier in an
  616. // alias-declaration.
  617. ParsedAttributesWithRange MisplacedAttrs(AttrFactory);
  618. MaybeParseCXX11Attributes(MisplacedAttrs);
  619. if (InInitStatement && Tok.isNot(tok::identifier))
  620. return nullptr;
  621. UsingDeclarator D;
  622. bool InvalidDeclarator = ParseUsingDeclarator(Context, D);
  623. ParsedAttributesWithRange Attrs(AttrFactory);
  624. MaybeParseAttributes(PAKM_GNU | PAKM_CXX11, Attrs);
  625. // If we had any misplaced attributes from earlier, this is where they
  626. // should have been written.
  627. if (MisplacedAttrs.Range.isValid()) {
  628. Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed)
  629. << FixItHint::CreateInsertionFromRange(
  630. Tok.getLocation(),
  631. CharSourceRange::getTokenRange(MisplacedAttrs.Range))
  632. << FixItHint::CreateRemoval(MisplacedAttrs.Range);
  633. Attrs.takeAllFrom(MisplacedAttrs);
  634. }
  635. // Maybe this is an alias-declaration.
  636. if (Tok.is(tok::equal) || InInitStatement) {
  637. if (InvalidDeclarator) {
  638. SkipUntil(tok::semi);
  639. return nullptr;
  640. }
  641. ProhibitAttributes(PrefixAttrs);
  642. Decl *DeclFromDeclSpec = nullptr;
  643. Decl *AD = ParseAliasDeclarationAfterDeclarator(
  644. TemplateInfo, UsingLoc, D, DeclEnd, AS, Attrs, &DeclFromDeclSpec);
  645. return Actions.ConvertDeclToDeclGroup(AD, DeclFromDeclSpec);
  646. }
  647. DiagnoseCXX11AttributeExtension(PrefixAttrs);
  648. // Diagnose an attempt to declare a templated using-declaration.
  649. // In C++11, alias-declarations can be templates:
  650. // template <...> using id = type;
  651. if (TemplateInfo.Kind) {
  652. SourceRange R = TemplateInfo.getSourceRange();
  653. Diag(UsingLoc, diag::err_templated_using_directive_declaration)
  654. << 1 /* declaration */ << R << FixItHint::CreateRemoval(R);
  655. // Unfortunately, we have to bail out instead of recovering by
  656. // ignoring the parameters, just in case the nested name specifier
  657. // depends on the parameters.
  658. return nullptr;
  659. }
  660. SmallVector<Decl *, 8> DeclsInGroup;
  661. while (true) {
  662. // Parse (optional) attributes.
  663. MaybeParseAttributes(PAKM_GNU | PAKM_CXX11, Attrs);
  664. DiagnoseCXX11AttributeExtension(Attrs);
  665. Attrs.addAll(PrefixAttrs.begin(), PrefixAttrs.end());
  666. if (InvalidDeclarator)
  667. SkipUntil(tok::comma, tok::semi, StopBeforeMatch);
  668. else {
  669. // "typename" keyword is allowed for identifiers only,
  670. // because it may be a type definition.
  671. if (D.TypenameLoc.isValid() &&
  672. D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
  673. Diag(D.Name.getSourceRange().getBegin(),
  674. diag::err_typename_identifiers_only)
  675. << FixItHint::CreateRemoval(SourceRange(D.TypenameLoc));
  676. // Proceed parsing, but discard the typename keyword.
  677. D.TypenameLoc = SourceLocation();
  678. }
  679. Decl *UD = Actions.ActOnUsingDeclaration(getCurScope(), AS, UsingLoc,
  680. D.TypenameLoc, D.SS, D.Name,
  681. D.EllipsisLoc, Attrs);
  682. if (UD)
  683. DeclsInGroup.push_back(UD);
  684. }
  685. if (!TryConsumeToken(tok::comma))
  686. break;
  687. // Parse another using-declarator.
  688. Attrs.clear();
  689. InvalidDeclarator = ParseUsingDeclarator(Context, D);
  690. }
  691. if (DeclsInGroup.size() > 1)
  692. Diag(Tok.getLocation(), getLangOpts().CPlusPlus17 ?
  693. diag::warn_cxx17_compat_multi_using_declaration :
  694. diag::ext_multi_using_declaration);
  695. // Eat ';'.
  696. DeclEnd = Tok.getLocation();
  697. if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  698. !Attrs.empty() ? "attributes list"
  699. : UELoc.isValid() ? "using-enum declaration"
  700. : "using declaration"))
  701. SkipUntil(tok::semi);
  702. return Actions.BuildDeclaratorGroup(DeclsInGroup);
  703. }
  704. Decl *Parser::ParseAliasDeclarationAfterDeclarator(
  705. const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc,
  706. UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS,
  707. ParsedAttributes &Attrs, Decl **OwnedType) {
  708. if (ExpectAndConsume(tok::equal)) {
  709. SkipUntil(tok::semi);
  710. return nullptr;
  711. }
  712. Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ?
  713. diag::warn_cxx98_compat_alias_declaration :
  714. diag::ext_alias_declaration);
  715. // Type alias templates cannot be specialized.
  716. int SpecKind = -1;
  717. if (TemplateInfo.Kind == ParsedTemplateInfo::Template &&
  718. D.Name.getKind() == UnqualifiedIdKind::IK_TemplateId)
  719. SpecKind = 0;
  720. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization)
  721. SpecKind = 1;
  722. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
  723. SpecKind = 2;
  724. if (SpecKind != -1) {
  725. SourceRange Range;
  726. if (SpecKind == 0)
  727. Range = SourceRange(D.Name.TemplateId->LAngleLoc,
  728. D.Name.TemplateId->RAngleLoc);
  729. else
  730. Range = TemplateInfo.getSourceRange();
  731. Diag(Range.getBegin(), diag::err_alias_declaration_specialization)
  732. << SpecKind << Range;
  733. SkipUntil(tok::semi);
  734. return nullptr;
  735. }
  736. // Name must be an identifier.
  737. if (D.Name.getKind() != UnqualifiedIdKind::IK_Identifier) {
  738. Diag(D.Name.StartLocation, diag::err_alias_declaration_not_identifier);
  739. // No removal fixit: can't recover from this.
  740. SkipUntil(tok::semi);
  741. return nullptr;
  742. } else if (D.TypenameLoc.isValid())
  743. Diag(D.TypenameLoc, diag::err_alias_declaration_not_identifier)
  744. << FixItHint::CreateRemoval(SourceRange(
  745. D.TypenameLoc,
  746. D.SS.isNotEmpty() ? D.SS.getEndLoc() : D.TypenameLoc));
  747. else if (D.SS.isNotEmpty())
  748. Diag(D.SS.getBeginLoc(), diag::err_alias_declaration_not_identifier)
  749. << FixItHint::CreateRemoval(D.SS.getRange());
  750. if (D.EllipsisLoc.isValid())
  751. Diag(D.EllipsisLoc, diag::err_alias_declaration_pack_expansion)
  752. << FixItHint::CreateRemoval(SourceRange(D.EllipsisLoc));
  753. Decl *DeclFromDeclSpec = nullptr;
  754. TypeResult TypeAlias =
  755. ParseTypeName(nullptr,
  756. TemplateInfo.Kind ? DeclaratorContext::AliasTemplate
  757. : DeclaratorContext::AliasDecl,
  758. AS, &DeclFromDeclSpec, &Attrs);
  759. if (OwnedType)
  760. *OwnedType = DeclFromDeclSpec;
  761. // Eat ';'.
  762. DeclEnd = Tok.getLocation();
  763. if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  764. !Attrs.empty() ? "attributes list"
  765. : "alias declaration"))
  766. SkipUntil(tok::semi);
  767. TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
  768. MultiTemplateParamsArg TemplateParamsArg(
  769. TemplateParams ? TemplateParams->data() : nullptr,
  770. TemplateParams ? TemplateParams->size() : 0);
  771. return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg,
  772. UsingLoc, D.Name, Attrs, TypeAlias,
  773. DeclFromDeclSpec);
  774. }
  775. static FixItHint getStaticAssertNoMessageFixIt(const Expr *AssertExpr,
  776. SourceLocation EndExprLoc) {
  777. if (const auto *BO = dyn_cast_or_null<BinaryOperator>(AssertExpr)) {
  778. if (BO->getOpcode() == BO_LAnd &&
  779. isa<StringLiteral>(BO->getRHS()->IgnoreImpCasts()))
  780. return FixItHint::CreateReplacement(BO->getOperatorLoc(), ",");
  781. }
  782. return FixItHint::CreateInsertion(EndExprLoc, ", \"\"");
  783. }
  784. /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration.
  785. ///
  786. /// [C++0x] static_assert-declaration:
  787. /// static_assert ( constant-expression , string-literal ) ;
  788. ///
  789. /// [C11] static_assert-declaration:
  790. /// _Static_assert ( constant-expression , string-literal ) ;
  791. ///
  792. Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){
  793. assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) &&
  794. "Not a static_assert declaration");
  795. if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11)
  796. Diag(Tok, diag::ext_c11_feature) << Tok.getName();
  797. if (Tok.is(tok::kw_static_assert)) {
  798. if (!getLangOpts().CPlusPlus)
  799. Diag(Tok, diag::ext_ms_static_assert)
  800. << FixItHint::CreateReplacement(Tok.getLocation(), "_Static_assert");
  801. else
  802. Diag(Tok, diag::warn_cxx98_compat_static_assert);
  803. }
  804. SourceLocation StaticAssertLoc = ConsumeToken();
  805. BalancedDelimiterTracker T(*this, tok::l_paren);
  806. if (T.consumeOpen()) {
  807. Diag(Tok, diag::err_expected) << tok::l_paren;
  808. SkipMalformedDecl();
  809. return nullptr;
  810. }
  811. EnterExpressionEvaluationContext ConstantEvaluated(
  812. Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
  813. ExprResult AssertExpr(ParseConstantExpressionInExprEvalContext());
  814. if (AssertExpr.isInvalid()) {
  815. SkipMalformedDecl();
  816. return nullptr;
  817. }
  818. ExprResult AssertMessage;
  819. if (Tok.is(tok::r_paren)) {
  820. unsigned DiagVal;
  821. if (getLangOpts().CPlusPlus17)
  822. DiagVal = diag::warn_cxx14_compat_static_assert_no_message;
  823. else if (getLangOpts().CPlusPlus)
  824. DiagVal = diag::ext_cxx_static_assert_no_message;
  825. else if (getLangOpts().C2x)
  826. DiagVal = diag::warn_c17_compat_static_assert_no_message;
  827. else
  828. DiagVal = diag::ext_c_static_assert_no_message;
  829. Diag(Tok, DiagVal) << getStaticAssertNoMessageFixIt(AssertExpr.get(),
  830. Tok.getLocation());
  831. } else {
  832. if (ExpectAndConsume(tok::comma)) {
  833. SkipUntil(tok::semi);
  834. return nullptr;
  835. }
  836. if (!isTokenStringLiteral()) {
  837. Diag(Tok, diag::err_expected_string_literal)
  838. << /*Source='static_assert'*/1;
  839. SkipMalformedDecl();
  840. return nullptr;
  841. }
  842. AssertMessage = ParseStringLiteralExpression();
  843. if (AssertMessage.isInvalid()) {
  844. SkipMalformedDecl();
  845. return nullptr;
  846. }
  847. }
  848. T.consumeClose();
  849. DeclEnd = Tok.getLocation();
  850. ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert);
  851. return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc,
  852. AssertExpr.get(),
  853. AssertMessage.get(),
  854. T.getCloseLocation());
  855. }
  856. /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier.
  857. ///
  858. /// 'decltype' ( expression )
  859. /// 'decltype' ( 'auto' ) [C++1y]
  860. ///
  861. SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) {
  862. assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)
  863. && "Not a decltype specifier");
  864. ExprResult Result;
  865. SourceLocation StartLoc = Tok.getLocation();
  866. SourceLocation EndLoc;
  867. if (Tok.is(tok::annot_decltype)) {
  868. Result = getExprAnnotation(Tok);
  869. EndLoc = Tok.getAnnotationEndLoc();
  870. // Unfortunately, we don't know the LParen source location as the annotated
  871. // token doesn't have it.
  872. DS.setTypeofParensRange(SourceRange(SourceLocation(), EndLoc));
  873. ConsumeAnnotationToken();
  874. if (Result.isInvalid()) {
  875. DS.SetTypeSpecError();
  876. return EndLoc;
  877. }
  878. } else {
  879. if (Tok.getIdentifierInfo()->isStr("decltype"))
  880. Diag(Tok, diag::warn_cxx98_compat_decltype);
  881. ConsumeToken();
  882. BalancedDelimiterTracker T(*this, tok::l_paren);
  883. if (T.expectAndConsume(diag::err_expected_lparen_after,
  884. "decltype", tok::r_paren)) {
  885. DS.SetTypeSpecError();
  886. return T.getOpenLocation() == Tok.getLocation() ?
  887. StartLoc : T.getOpenLocation();
  888. }
  889. // Check for C++1y 'decltype(auto)'.
  890. if (Tok.is(tok::kw_auto)) {
  891. // No need to disambiguate here: an expression can't start with 'auto',
  892. // because the typename-specifier in a function-style cast operation can't
  893. // be 'auto'.
  894. Diag(Tok.getLocation(),
  895. getLangOpts().CPlusPlus14
  896. ? diag::warn_cxx11_compat_decltype_auto_type_specifier
  897. : diag::ext_decltype_auto_type_specifier);
  898. ConsumeToken();
  899. } else {
  900. // Parse the expression
  901. // C++11 [dcl.type.simple]p4:
  902. // The operand of the decltype specifier is an unevaluated operand.
  903. EnterExpressionEvaluationContext Unevaluated(
  904. Actions, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
  905. Sema::ExpressionEvaluationContextRecord::EK_Decltype);
  906. Result = Actions.CorrectDelayedTyposInExpr(
  907. ParseExpression(), /*InitDecl=*/nullptr,
  908. /*RecoverUncorrectedTypos=*/false,
  909. [](Expr *E) { return E->hasPlaceholderType() ? ExprError() : E; });
  910. if (Result.isInvalid()) {
  911. DS.SetTypeSpecError();
  912. if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) {
  913. EndLoc = ConsumeParen();
  914. } else {
  915. if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) {
  916. // Backtrack to get the location of the last token before the semi.
  917. PP.RevertCachedTokens(2);
  918. ConsumeToken(); // the semi.
  919. EndLoc = ConsumeAnyToken();
  920. assert(Tok.is(tok::semi));
  921. } else {
  922. EndLoc = Tok.getLocation();
  923. }
  924. }
  925. return EndLoc;
  926. }
  927. Result = Actions.ActOnDecltypeExpression(Result.get());
  928. }
  929. // Match the ')'
  930. T.consumeClose();
  931. DS.setTypeofParensRange(T.getRange());
  932. if (T.getCloseLocation().isInvalid()) {
  933. DS.SetTypeSpecError();
  934. // FIXME: this should return the location of the last token
  935. // that was consumed (by "consumeClose()")
  936. return T.getCloseLocation();
  937. }
  938. if (Result.isInvalid()) {
  939. DS.SetTypeSpecError();
  940. return T.getCloseLocation();
  941. }
  942. EndLoc = T.getCloseLocation();
  943. }
  944. assert(!Result.isInvalid());
  945. const char *PrevSpec = nullptr;
  946. unsigned DiagID;
  947. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  948. // Check for duplicate type specifiers (e.g. "int decltype(a)").
  949. if (Result.get()
  950. ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec,
  951. DiagID, Result.get(), Policy)
  952. : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec,
  953. DiagID, Policy)) {
  954. Diag(StartLoc, DiagID) << PrevSpec;
  955. DS.SetTypeSpecError();
  956. }
  957. return EndLoc;
  958. }
  959. void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS,
  960. SourceLocation StartLoc,
  961. SourceLocation EndLoc) {
  962. // make sure we have a token we can turn into an annotation token
  963. if (PP.isBacktrackEnabled()) {
  964. PP.RevertCachedTokens(1);
  965. if (DS.getTypeSpecType() == TST_error) {
  966. // We encountered an error in parsing 'decltype(...)' so lets annotate all
  967. // the tokens in the backtracking cache - that we likely had to skip over
  968. // to get to a token that allows us to resume parsing, such as a
  969. // semi-colon.
  970. EndLoc = PP.getLastCachedTokenLocation();
  971. }
  972. }
  973. else
  974. PP.EnterToken(Tok, /*IsReinject*/true);
  975. Tok.setKind(tok::annot_decltype);
  976. setExprAnnotation(Tok,
  977. DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() :
  978. DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() :
  979. ExprError());
  980. Tok.setAnnotationEndLoc(EndLoc);
  981. Tok.setLocation(StartLoc);
  982. PP.AnnotateCachedTokens(Tok);
  983. }
  984. void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) {
  985. assert(Tok.is(tok::kw___underlying_type) &&
  986. "Not an underlying type specifier");
  987. SourceLocation StartLoc = ConsumeToken();
  988. BalancedDelimiterTracker T(*this, tok::l_paren);
  989. if (T.expectAndConsume(diag::err_expected_lparen_after,
  990. "__underlying_type", tok::r_paren)) {
  991. return;
  992. }
  993. TypeResult Result = ParseTypeName();
  994. if (Result.isInvalid()) {
  995. SkipUntil(tok::r_paren, StopAtSemi);
  996. return;
  997. }
  998. // Match the ')'
  999. T.consumeClose();
  1000. if (T.getCloseLocation().isInvalid())
  1001. return;
  1002. const char *PrevSpec = nullptr;
  1003. unsigned DiagID;
  1004. if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec,
  1005. DiagID, Result.get(),
  1006. Actions.getASTContext().getPrintingPolicy()))
  1007. Diag(StartLoc, DiagID) << PrevSpec;
  1008. DS.setTypeofParensRange(T.getRange());
  1009. }
  1010. /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a
  1011. /// class name or decltype-specifier. Note that we only check that the result
  1012. /// names a type; semantic analysis will need to verify that the type names a
  1013. /// class. The result is either a type or null, depending on whether a type
  1014. /// name was found.
  1015. ///
  1016. /// base-type-specifier: [C++11 class.derived]
  1017. /// class-or-decltype
  1018. /// class-or-decltype: [C++11 class.derived]
  1019. /// nested-name-specifier[opt] class-name
  1020. /// decltype-specifier
  1021. /// class-name: [C++ class.name]
  1022. /// identifier
  1023. /// simple-template-id
  1024. ///
  1025. /// In C++98, instead of base-type-specifier, we have:
  1026. ///
  1027. /// ::[opt] nested-name-specifier[opt] class-name
  1028. TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
  1029. SourceLocation &EndLocation) {
  1030. // Ignore attempts to use typename
  1031. if (Tok.is(tok::kw_typename)) {
  1032. Diag(Tok, diag::err_expected_class_name_not_template)
  1033. << FixItHint::CreateRemoval(Tok.getLocation());
  1034. ConsumeToken();
  1035. }
  1036. // Parse optional nested-name-specifier
  1037. CXXScopeSpec SS;
  1038. if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
  1039. /*ObjectHasErrors=*/false,
  1040. /*EnteringContext=*/false))
  1041. return true;
  1042. BaseLoc = Tok.getLocation();
  1043. // Parse decltype-specifier
  1044. // tok == kw_decltype is just error recovery, it can only happen when SS
  1045. // isn't empty
  1046. if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
  1047. if (SS.isNotEmpty())
  1048. Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype)
  1049. << FixItHint::CreateRemoval(SS.getRange());
  1050. // Fake up a Declarator to use with ActOnTypeName.
  1051. DeclSpec DS(AttrFactory);
  1052. EndLocation = ParseDecltypeSpecifier(DS);
  1053. Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
  1054. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  1055. }
  1056. // Check whether we have a template-id that names a type.
  1057. if (Tok.is(tok::annot_template_id)) {
  1058. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1059. if (TemplateId->mightBeType()) {
  1060. AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
  1061. assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
  1062. TypeResult Type = getTypeAnnotation(Tok);
  1063. EndLocation = Tok.getAnnotationEndLoc();
  1064. ConsumeAnnotationToken();
  1065. return Type;
  1066. }
  1067. // Fall through to produce an error below.
  1068. }
  1069. if (Tok.isNot(tok::identifier)) {
  1070. Diag(Tok, diag::err_expected_class_name);
  1071. return true;
  1072. }
  1073. IdentifierInfo *Id = Tok.getIdentifierInfo();
  1074. SourceLocation IdLoc = ConsumeToken();
  1075. if (Tok.is(tok::less)) {
  1076. // It looks the user intended to write a template-id here, but the
  1077. // template-name was wrong. Try to fix that.
  1078. // FIXME: Invoke ParseOptionalCXXScopeSpecifier in a "'template' is neither
  1079. // required nor permitted" mode, and do this there.
  1080. TemplateNameKind TNK = TNK_Non_template;
  1081. TemplateTy Template;
  1082. if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(),
  1083. &SS, Template, TNK)) {
  1084. Diag(IdLoc, diag::err_unknown_template_name)
  1085. << Id;
  1086. }
  1087. // Form the template name
  1088. UnqualifiedId TemplateName;
  1089. TemplateName.setIdentifier(Id, IdLoc);
  1090. // Parse the full template-id, then turn it into a type.
  1091. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
  1092. TemplateName))
  1093. return true;
  1094. if (Tok.is(tok::annot_template_id) &&
  1095. takeTemplateIdAnnotation(Tok)->mightBeType())
  1096. AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
  1097. // If we didn't end up with a typename token, there's nothing more we
  1098. // can do.
  1099. if (Tok.isNot(tok::annot_typename))
  1100. return true;
  1101. // Retrieve the type from the annotation token, consume that token, and
  1102. // return.
  1103. EndLocation = Tok.getAnnotationEndLoc();
  1104. TypeResult Type = getTypeAnnotation(Tok);
  1105. ConsumeAnnotationToken();
  1106. return Type;
  1107. }
  1108. // We have an identifier; check whether it is actually a type.
  1109. IdentifierInfo *CorrectedII = nullptr;
  1110. ParsedType Type = Actions.getTypeName(
  1111. *Id, IdLoc, getCurScope(), &SS, /*isClassName=*/true, false, nullptr,
  1112. /*IsCtorOrDtorName=*/false,
  1113. /*WantNontrivialTypeSourceInfo=*/true,
  1114. /*IsClassTemplateDeductionContext*/ false, &CorrectedII);
  1115. if (!Type) {
  1116. Diag(IdLoc, diag::err_expected_class_name);
  1117. return true;
  1118. }
  1119. // Consume the identifier.
  1120. EndLocation = IdLoc;
  1121. // Fake up a Declarator to use with ActOnTypeName.
  1122. DeclSpec DS(AttrFactory);
  1123. DS.SetRangeStart(IdLoc);
  1124. DS.SetRangeEnd(EndLocation);
  1125. DS.getTypeSpecScope() = SS;
  1126. const char *PrevSpec = nullptr;
  1127. unsigned DiagID;
  1128. DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type,
  1129. Actions.getASTContext().getPrintingPolicy());
  1130. Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
  1131. return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  1132. }
  1133. void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) {
  1134. while (Tok.isOneOf(tok::kw___single_inheritance,
  1135. tok::kw___multiple_inheritance,
  1136. tok::kw___virtual_inheritance)) {
  1137. IdentifierInfo *AttrName = Tok.getIdentifierInfo();
  1138. SourceLocation AttrNameLoc = ConsumeToken();
  1139. attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
  1140. ParsedAttr::AS_Keyword);
  1141. }
  1142. }
  1143. /// Determine whether the following tokens are valid after a type-specifier
  1144. /// which could be a standalone declaration. This will conservatively return
  1145. /// true if there's any doubt, and is appropriate for insert-';' fixits.
  1146. bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) {
  1147. // This switch enumerates the valid "follow" set for type-specifiers.
  1148. switch (Tok.getKind()) {
  1149. default: break;
  1150. case tok::semi: // struct foo {...} ;
  1151. case tok::star: // struct foo {...} * P;
  1152. case tok::amp: // struct foo {...} & R = ...
  1153. case tok::ampamp: // struct foo {...} && R = ...
  1154. case tok::identifier: // struct foo {...} V ;
  1155. case tok::r_paren: //(struct foo {...} ) {4}
  1156. case tok::coloncolon: // struct foo {...} :: a::b;
  1157. case tok::annot_cxxscope: // struct foo {...} a:: b;
  1158. case tok::annot_typename: // struct foo {...} a ::b;
  1159. case tok::annot_template_id: // struct foo {...} a<int> ::b;
  1160. case tok::kw_decltype: // struct foo {...} decltype (a)::b;
  1161. case tok::l_paren: // struct foo {...} ( x);
  1162. case tok::comma: // __builtin_offsetof(struct foo{...} ,
  1163. case tok::kw_operator: // struct foo operator ++() {...}
  1164. case tok::kw___declspec: // struct foo {...} __declspec(...)
  1165. case tok::l_square: // void f(struct f [ 3])
  1166. case tok::ellipsis: // void f(struct f ... [Ns])
  1167. // FIXME: we should emit semantic diagnostic when declaration
  1168. // attribute is in type attribute position.
  1169. case tok::kw___attribute: // struct foo __attribute__((used)) x;
  1170. case tok::annot_pragma_pack: // struct foo {...} _Pragma(pack(pop));
  1171. // struct foo {...} _Pragma(section(...));
  1172. case tok::annot_pragma_ms_pragma:
  1173. // struct foo {...} _Pragma(vtordisp(pop));
  1174. case tok::annot_pragma_ms_vtordisp:
  1175. // struct foo {...} _Pragma(pointers_to_members(...));
  1176. case tok::annot_pragma_ms_pointers_to_members:
  1177. return true;
  1178. case tok::colon:
  1179. return CouldBeBitfield || // enum E { ... } : 2;
  1180. ColonIsSacred; // _Generic(..., enum E : 2);
  1181. // Microsoft compatibility
  1182. case tok::kw___cdecl: // struct foo {...} __cdecl x;
  1183. case tok::kw___fastcall: // struct foo {...} __fastcall x;
  1184. case tok::kw___stdcall: // struct foo {...} __stdcall x;
  1185. case tok::kw___thiscall: // struct foo {...} __thiscall x;
  1186. case tok::kw___vectorcall: // struct foo {...} __vectorcall x;
  1187. // We will diagnose these calling-convention specifiers on non-function
  1188. // declarations later, so claim they are valid after a type specifier.
  1189. return getLangOpts().MicrosoftExt;
  1190. // Type qualifiers
  1191. case tok::kw_const: // struct foo {...} const x;
  1192. case tok::kw_volatile: // struct foo {...} volatile x;
  1193. case tok::kw_restrict: // struct foo {...} restrict x;
  1194. case tok::kw__Atomic: // struct foo {...} _Atomic x;
  1195. case tok::kw___unaligned: // struct foo {...} __unaligned *x;
  1196. // Function specifiers
  1197. // Note, no 'explicit'. An explicit function must be either a conversion
  1198. // operator or a constructor. Either way, it can't have a return type.
  1199. case tok::kw_inline: // struct foo inline f();
  1200. case tok::kw_virtual: // struct foo virtual f();
  1201. case tok::kw_friend: // struct foo friend f();
  1202. // Storage-class specifiers
  1203. case tok::kw_static: // struct foo {...} static x;
  1204. case tok::kw_extern: // struct foo {...} extern x;
  1205. case tok::kw_typedef: // struct foo {...} typedef x;
  1206. case tok::kw_register: // struct foo {...} register x;
  1207. case tok::kw_auto: // struct foo {...} auto x;
  1208. case tok::kw_mutable: // struct foo {...} mutable x;
  1209. case tok::kw_thread_local: // struct foo {...} thread_local x;
  1210. case tok::kw_constexpr: // struct foo {...} constexpr x;
  1211. case tok::kw_consteval: // struct foo {...} consteval x;
  1212. case tok::kw_constinit: // struct foo {...} constinit x;
  1213. // As shown above, type qualifiers and storage class specifiers absolutely
  1214. // can occur after class specifiers according to the grammar. However,
  1215. // almost no one actually writes code like this. If we see one of these,
  1216. // it is much more likely that someone missed a semi colon and the
  1217. // type/storage class specifier we're seeing is part of the *next*
  1218. // intended declaration, as in:
  1219. //
  1220. // struct foo { ... }
  1221. // typedef int X;
  1222. //
  1223. // We'd really like to emit a missing semicolon error instead of emitting
  1224. // an error on the 'int' saying that you can't have two type specifiers in
  1225. // the same declaration of X. Because of this, we look ahead past this
  1226. // token to see if it's a type specifier. If so, we know the code is
  1227. // otherwise invalid, so we can produce the expected semi error.
  1228. if (!isKnownToBeTypeSpecifier(NextToken()))
  1229. return true;
  1230. break;
  1231. case tok::r_brace: // struct bar { struct foo {...} }
  1232. // Missing ';' at end of struct is accepted as an extension in C mode.
  1233. if (!getLangOpts().CPlusPlus)
  1234. return true;
  1235. break;
  1236. case tok::greater:
  1237. // template<class T = class X>
  1238. return getLangOpts().CPlusPlus;
  1239. }
  1240. return false;
  1241. }
  1242. /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
  1243. /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
  1244. /// until we reach the start of a definition or see a token that
  1245. /// cannot start a definition.
  1246. ///
  1247. /// class-specifier: [C++ class]
  1248. /// class-head '{' member-specification[opt] '}'
  1249. /// class-head '{' member-specification[opt] '}' attributes[opt]
  1250. /// class-head:
  1251. /// class-key identifier[opt] base-clause[opt]
  1252. /// class-key nested-name-specifier identifier base-clause[opt]
  1253. /// class-key nested-name-specifier[opt] simple-template-id
  1254. /// base-clause[opt]
  1255. /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
  1256. /// [GNU] class-key attributes[opt] nested-name-specifier
  1257. /// identifier base-clause[opt]
  1258. /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
  1259. /// simple-template-id base-clause[opt]
  1260. /// class-key:
  1261. /// 'class'
  1262. /// 'struct'
  1263. /// 'union'
  1264. ///
  1265. /// elaborated-type-specifier: [C++ dcl.type.elab]
  1266. /// class-key ::[opt] nested-name-specifier[opt] identifier
  1267. /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
  1268. /// simple-template-id
  1269. ///
  1270. /// Note that the C++ class-specifier and elaborated-type-specifier,
  1271. /// together, subsume the C99 struct-or-union-specifier:
  1272. ///
  1273. /// struct-or-union-specifier: [C99 6.7.2.1]
  1274. /// struct-or-union identifier[opt] '{' struct-contents '}'
  1275. /// struct-or-union identifier
  1276. /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
  1277. /// '}' attributes[opt]
  1278. /// [GNU] struct-or-union attributes[opt] identifier
  1279. /// struct-or-union:
  1280. /// 'struct'
  1281. /// 'union'
  1282. void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
  1283. SourceLocation StartLoc, DeclSpec &DS,
  1284. const ParsedTemplateInfo &TemplateInfo,
  1285. AccessSpecifier AS,
  1286. bool EnteringContext, DeclSpecContext DSC,
  1287. ParsedAttributesWithRange &Attributes) {
  1288. DeclSpec::TST TagType;
  1289. if (TagTokKind == tok::kw_struct)
  1290. TagType = DeclSpec::TST_struct;
  1291. else if (TagTokKind == tok::kw___interface)
  1292. TagType = DeclSpec::TST_interface;
  1293. else if (TagTokKind == tok::kw_class)
  1294. TagType = DeclSpec::TST_class;
  1295. else {
  1296. assert(TagTokKind == tok::kw_union && "Not a class specifier");
  1297. TagType = DeclSpec::TST_union;
  1298. }
  1299. if (Tok.is(tok::code_completion)) {
  1300. // Code completion for a struct, class, or union name.
  1301. cutOffParsing();
  1302. Actions.CodeCompleteTag(getCurScope(), TagType);
  1303. return;
  1304. }
  1305. // C++20 [temp.class.spec] 13.7.5/10
  1306. // The usual access checking rules do not apply to non-dependent names
  1307. // used to specify template arguments of the simple-template-id of the
  1308. // partial specialization.
  1309. // C++20 [temp.spec] 13.9/6:
  1310. // The usual access checking rules do not apply to names in a declaration
  1311. // of an explicit instantiation or explicit specialization...
  1312. const bool shouldDelayDiagsInTag =
  1313. (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate);
  1314. SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
  1315. ParsedAttributesWithRange attrs(AttrFactory);
  1316. // If attributes exist after tag, parse them.
  1317. MaybeParseAttributes(PAKM_CXX11 | PAKM_Declspec | PAKM_GNU, attrs);
  1318. // Parse inheritance specifiers.
  1319. if (Tok.isOneOf(tok::kw___single_inheritance,
  1320. tok::kw___multiple_inheritance,
  1321. tok::kw___virtual_inheritance))
  1322. ParseMicrosoftInheritanceClassAttributes(attrs);
  1323. // Allow attributes to precede or succeed the inheritance specifiers.
  1324. MaybeParseAttributes(PAKM_CXX11 | PAKM_Declspec | PAKM_GNU, attrs);
  1325. // Source location used by FIXIT to insert misplaced
  1326. // C++11 attributes
  1327. SourceLocation AttrFixitLoc = Tok.getLocation();
  1328. if (TagType == DeclSpec::TST_struct &&
  1329. Tok.isNot(tok::identifier) &&
  1330. !Tok.isAnnotation() &&
  1331. Tok.getIdentifierInfo() &&
  1332. Tok.isOneOf(tok::kw___is_abstract,
  1333. tok::kw___is_aggregate,
  1334. tok::kw___is_arithmetic,
  1335. tok::kw___is_array,
  1336. tok::kw___is_assignable,
  1337. tok::kw___is_base_of,
  1338. tok::kw___is_class,
  1339. tok::kw___is_complete_type,
  1340. tok::kw___is_compound,
  1341. tok::kw___is_const,
  1342. tok::kw___is_constructible,
  1343. tok::kw___is_convertible,
  1344. tok::kw___is_convertible_to,
  1345. tok::kw___is_destructible,
  1346. tok::kw___is_empty,
  1347. tok::kw___is_enum,
  1348. tok::kw___is_floating_point,
  1349. tok::kw___is_final,
  1350. tok::kw___is_function,
  1351. tok::kw___is_fundamental,
  1352. tok::kw___is_integral,
  1353. tok::kw___is_interface_class,
  1354. tok::kw___is_literal,
  1355. tok::kw___is_lvalue_expr,
  1356. tok::kw___is_lvalue_reference,
  1357. tok::kw___is_member_function_pointer,
  1358. tok::kw___is_member_object_pointer,
  1359. tok::kw___is_member_pointer,
  1360. tok::kw___is_nothrow_assignable,
  1361. tok::kw___is_nothrow_constructible,
  1362. tok::kw___is_nothrow_destructible,
  1363. tok::kw___is_object,
  1364. tok::kw___is_pod,
  1365. tok::kw___is_pointer,
  1366. tok::kw___is_polymorphic,
  1367. tok::kw___is_reference,
  1368. tok::kw___is_rvalue_expr,
  1369. tok::kw___is_rvalue_reference,
  1370. tok::kw___is_same,
  1371. tok::kw___is_scalar,
  1372. tok::kw___is_sealed,
  1373. tok::kw___is_signed,
  1374. tok::kw___is_standard_layout,
  1375. tok::kw___is_trivial,
  1376. tok::kw___is_trivially_assignable,
  1377. tok::kw___is_trivially_constructible,
  1378. tok::kw___is_trivially_copyable,
  1379. tok::kw___is_union,
  1380. tok::kw___is_unsigned,
  1381. tok::kw___is_void,
  1382. tok::kw___is_volatile))
  1383. // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
  1384. // name of struct templates, but some are keywords in GCC >= 4.3
  1385. // and Clang. Therefore, when we see the token sequence "struct
  1386. // X", make X into a normal identifier rather than a keyword, to
  1387. // allow libstdc++ 4.2 and libc++ to work properly.
  1388. TryKeywordIdentFallback(true);
  1389. struct PreserveAtomicIdentifierInfoRAII {
  1390. PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
  1391. : AtomicII(nullptr) {
  1392. if (!Enabled)
  1393. return;
  1394. assert(Tok.is(tok::kw__Atomic));
  1395. AtomicII = Tok.getIdentifierInfo();
  1396. AtomicII->revertTokenIDToIdentifier();
  1397. Tok.setKind(tok::identifier);
  1398. }
  1399. ~PreserveAtomicIdentifierInfoRAII() {
  1400. if (!AtomicII)
  1401. return;
  1402. AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
  1403. }
  1404. IdentifierInfo *AtomicII;
  1405. };
  1406. // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
  1407. // implementation for VS2013 uses _Atomic as an identifier for one of the
  1408. // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
  1409. // '_Atomic' to be a keyword. We are careful to undo this so that clang can
  1410. // use '_Atomic' in its own header files.
  1411. bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
  1412. Tok.is(tok::kw__Atomic) &&
  1413. TagType == DeclSpec::TST_struct;
  1414. PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
  1415. Tok, ShouldChangeAtomicToIdentifier);
  1416. // Parse the (optional) nested-name-specifier.
  1417. CXXScopeSpec &SS = DS.getTypeSpecScope();
  1418. if (getLangOpts().CPlusPlus) {
  1419. // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
  1420. // is a base-specifier-list.
  1421. ColonProtectionRAIIObject X(*this);
  1422. CXXScopeSpec Spec;
  1423. bool HasValidSpec = true;
  1424. if (ParseOptionalCXXScopeSpecifier(Spec, /*ObjectType=*/nullptr,
  1425. /*ObjectHasErrors=*/false,
  1426. EnteringContext)) {
  1427. DS.SetTypeSpecError();
  1428. HasValidSpec = false;
  1429. }
  1430. if (Spec.isSet())
  1431. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
  1432. Diag(Tok, diag::err_expected) << tok::identifier;
  1433. HasValidSpec = false;
  1434. }
  1435. if (HasValidSpec)
  1436. SS = Spec;
  1437. }
  1438. TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
  1439. auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
  1440. SourceLocation NameLoc,
  1441. SourceRange TemplateArgRange,
  1442. bool KnownUndeclared) {
  1443. Diag(NameLoc, diag::err_explicit_spec_non_template)
  1444. << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
  1445. << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
  1446. // Strip off the last template parameter list if it was empty, since
  1447. // we've removed its template argument list.
  1448. if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
  1449. if (TemplateParams->size() > 1) {
  1450. TemplateParams->pop_back();
  1451. } else {
  1452. TemplateParams = nullptr;
  1453. const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
  1454. ParsedTemplateInfo::NonTemplate;
  1455. }
  1456. } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1457. // Pretend this is just a forward declaration.
  1458. TemplateParams = nullptr;
  1459. const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
  1460. ParsedTemplateInfo::NonTemplate;
  1461. const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
  1462. SourceLocation();
  1463. const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
  1464. SourceLocation();
  1465. }
  1466. };
  1467. // Parse the (optional) class name or simple-template-id.
  1468. IdentifierInfo *Name = nullptr;
  1469. SourceLocation NameLoc;
  1470. TemplateIdAnnotation *TemplateId = nullptr;
  1471. if (Tok.is(tok::identifier)) {
  1472. Name = Tok.getIdentifierInfo();
  1473. NameLoc = ConsumeToken();
  1474. if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
  1475. // The name was supposed to refer to a template, but didn't.
  1476. // Eat the template argument list and try to continue parsing this as
  1477. // a class (or template thereof).
  1478. TemplateArgList TemplateArgs;
  1479. SourceLocation LAngleLoc, RAngleLoc;
  1480. if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
  1481. RAngleLoc)) {
  1482. // We couldn't parse the template argument list at all, so don't
  1483. // try to give any location information for the list.
  1484. LAngleLoc = RAngleLoc = SourceLocation();
  1485. }
  1486. RecoverFromUndeclaredTemplateName(
  1487. Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
  1488. }
  1489. } else if (Tok.is(tok::annot_template_id)) {
  1490. TemplateId = takeTemplateIdAnnotation(Tok);
  1491. NameLoc = ConsumeAnnotationToken();
  1492. if (TemplateId->Kind == TNK_Undeclared_template) {
  1493. // Try to resolve the template name to a type template. May update Kind.
  1494. Actions.ActOnUndeclaredTypeTemplateName(
  1495. getCurScope(), TemplateId->Template, TemplateId->Kind, NameLoc, Name);
  1496. if (TemplateId->Kind == TNK_Undeclared_template) {
  1497. RecoverFromUndeclaredTemplateName(
  1498. Name, NameLoc,
  1499. SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
  1500. TemplateId = nullptr;
  1501. }
  1502. }
  1503. if (TemplateId && !TemplateId->mightBeType()) {
  1504. // The template-name in the simple-template-id refers to
  1505. // something other than a type template. Give an appropriate
  1506. // error message and skip to the ';'.
  1507. SourceRange Range(NameLoc);
  1508. if (SS.isNotEmpty())
  1509. Range.setBegin(SS.getBeginLoc());
  1510. // FIXME: Name may be null here.
  1511. Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
  1512. << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
  1513. DS.SetTypeSpecError();
  1514. SkipUntil(tok::semi, StopBeforeMatch);
  1515. return;
  1516. }
  1517. }
  1518. // There are four options here.
  1519. // - If we are in a trailing return type, this is always just a reference,
  1520. // and we must not try to parse a definition. For instance,
  1521. // [] () -> struct S { };
  1522. // does not define a type.
  1523. // - If we have 'struct foo {...', 'struct foo :...',
  1524. // 'struct foo final :' or 'struct foo final {', then this is a definition.
  1525. // - If we have 'struct foo;', then this is either a forward declaration
  1526. // or a friend declaration, which have to be treated differently.
  1527. // - Otherwise we have something like 'struct foo xyz', a reference.
  1528. //
  1529. // We also detect these erroneous cases to provide better diagnostic for
  1530. // C++11 attributes parsing.
  1531. // - attributes follow class name:
  1532. // struct foo [[]] {};
  1533. // - attributes appear before or after 'final':
  1534. // struct foo [[]] final [[]] {};
  1535. //
  1536. // However, in type-specifier-seq's, things look like declarations but are
  1537. // just references, e.g.
  1538. // new struct s;
  1539. // or
  1540. // &T::operator struct s;
  1541. // For these, DSC is DeclSpecContext::DSC_type_specifier or
  1542. // DeclSpecContext::DSC_alias_declaration.
  1543. // If there are attributes after class name, parse them.
  1544. MaybeParseCXX11Attributes(Attributes);
  1545. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  1546. Sema::TagUseKind TUK;
  1547. if (isDefiningTypeSpecifierContext(DSC) == AllowDefiningTypeSpec::No ||
  1548. (getLangOpts().OpenMP && OpenMPDirectiveParsing))
  1549. TUK = Sema::TUK_Reference;
  1550. else if (Tok.is(tok::l_brace) ||
  1551. (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
  1552. (isClassCompatibleKeyword() &&
  1553. (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
  1554. if (DS.isFriendSpecified()) {
  1555. // C++ [class.friend]p2:
  1556. // A class shall not be defined in a friend declaration.
  1557. Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
  1558. << SourceRange(DS.getFriendSpecLoc());
  1559. // Skip everything up to the semicolon, so that this looks like a proper
  1560. // friend class (or template thereof) declaration.
  1561. SkipUntil(tok::semi, StopBeforeMatch);
  1562. TUK = Sema::TUK_Friend;
  1563. } else {
  1564. // Okay, this is a class definition.
  1565. TUK = Sema::TUK_Definition;
  1566. }
  1567. } else if (isClassCompatibleKeyword() &&
  1568. (NextToken().is(tok::l_square) ||
  1569. NextToken().is(tok::kw_alignas) ||
  1570. isCXX11VirtSpecifier(NextToken()) != VirtSpecifiers::VS_None)) {
  1571. // We can't tell if this is a definition or reference
  1572. // until we skipped the 'final' and C++11 attribute specifiers.
  1573. TentativeParsingAction PA(*this);
  1574. // Skip the 'final', abstract'... keywords.
  1575. while (isClassCompatibleKeyword()) {
  1576. ConsumeToken();
  1577. }
  1578. // Skip C++11 attribute specifiers.
  1579. while (true) {
  1580. if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
  1581. ConsumeBracket();
  1582. if (!SkipUntil(tok::r_square, StopAtSemi))
  1583. break;
  1584. } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
  1585. ConsumeToken();
  1586. ConsumeParen();
  1587. if (!SkipUntil(tok::r_paren, StopAtSemi))
  1588. break;
  1589. } else {
  1590. break;
  1591. }
  1592. }
  1593. if (Tok.isOneOf(tok::l_brace, tok::colon))
  1594. TUK = Sema::TUK_Definition;
  1595. else
  1596. TUK = Sema::TUK_Reference;
  1597. PA.Revert();
  1598. } else if (!isTypeSpecifier(DSC) &&
  1599. (Tok.is(tok::semi) ||
  1600. (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
  1601. TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
  1602. if (Tok.isNot(tok::semi)) {
  1603. const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
  1604. // A semicolon was missing after this declaration. Diagnose and recover.
  1605. ExpectAndConsume(tok::semi, diag::err_expected_after,
  1606. DeclSpec::getSpecifierName(TagType, PPol));
  1607. PP.EnterToken(Tok, /*IsReinject*/true);
  1608. Tok.setKind(tok::semi);
  1609. }
  1610. } else
  1611. TUK = Sema::TUK_Reference;
  1612. // Forbid misplaced attributes. In cases of a reference, we pass attributes
  1613. // to caller to handle.
  1614. if (TUK != Sema::TUK_Reference) {
  1615. // If this is not a reference, then the only possible
  1616. // valid place for C++11 attributes to appear here
  1617. // is between class-key and class-name. If there are
  1618. // any attributes after class-name, we try a fixit to move
  1619. // them to the right place.
  1620. SourceRange AttrRange = Attributes.Range;
  1621. if (AttrRange.isValid()) {
  1622. Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
  1623. << AttrRange
  1624. << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
  1625. CharSourceRange(AttrRange, true))
  1626. << FixItHint::CreateRemoval(AttrRange);
  1627. // Recover by adding misplaced attributes to the attribute list
  1628. // of the class so they can be applied on the class later.
  1629. attrs.takeAllFrom(Attributes);
  1630. }
  1631. }
  1632. if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
  1633. TUK != Sema::TUK_Definition)) {
  1634. if (DS.getTypeSpecType() != DeclSpec::TST_error) {
  1635. // We have a declaration or reference to an anonymous class.
  1636. Diag(StartLoc, diag::err_anon_type_definition)
  1637. << DeclSpec::getSpecifierName(TagType, Policy);
  1638. }
  1639. // If we are parsing a definition and stop at a base-clause, continue on
  1640. // until the semicolon. Continuing from the comma will just trick us into
  1641. // thinking we are seeing a variable declaration.
  1642. if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
  1643. SkipUntil(tok::semi, StopBeforeMatch);
  1644. else
  1645. SkipUntil(tok::comma, StopAtSemi);
  1646. return;
  1647. }
  1648. // Create the tag portion of the class or class template.
  1649. DeclResult TagOrTempResult = true; // invalid
  1650. TypeResult TypeResult = true; // invalid
  1651. bool Owned = false;
  1652. Sema::SkipBodyInfo SkipBody;
  1653. if (TemplateId) {
  1654. // Explicit specialization, class template partial specialization,
  1655. // or explicit instantiation.
  1656. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  1657. TemplateId->NumArgs);
  1658. if (TemplateId->isInvalid()) {
  1659. // Can't build the declaration.
  1660. } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1661. TUK == Sema::TUK_Declaration) {
  1662. // This is an explicit instantiation of a class template.
  1663. ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
  1664. /*DiagnoseEmptyAttrs=*/true);
  1665. TagOrTempResult = Actions.ActOnExplicitInstantiation(
  1666. getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
  1667. TagType, StartLoc, SS, TemplateId->Template,
  1668. TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
  1669. TemplateId->RAngleLoc, attrs);
  1670. // Friend template-ids are treated as references unless
  1671. // they have template headers, in which case they're ill-formed
  1672. // (FIXME: "template <class T> friend class A<T>::B<int>;").
  1673. // We diagnose this error in ActOnClassTemplateSpecialization.
  1674. } else if (TUK == Sema::TUK_Reference ||
  1675. (TUK == Sema::TUK_Friend &&
  1676. TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
  1677. ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
  1678. /*DiagnoseEmptyAttrs=*/true);
  1679. TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
  1680. SS,
  1681. TemplateId->TemplateKWLoc,
  1682. TemplateId->Template,
  1683. TemplateId->TemplateNameLoc,
  1684. TemplateId->LAngleLoc,
  1685. TemplateArgsPtr,
  1686. TemplateId->RAngleLoc);
  1687. } else {
  1688. // This is an explicit specialization or a class template
  1689. // partial specialization.
  1690. TemplateParameterLists FakedParamLists;
  1691. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1692. // This looks like an explicit instantiation, because we have
  1693. // something like
  1694. //
  1695. // template class Foo<X>
  1696. //
  1697. // but it actually has a definition. Most likely, this was
  1698. // meant to be an explicit specialization, but the user forgot
  1699. // the '<>' after 'template'.
  1700. // It this is friend declaration however, since it cannot have a
  1701. // template header, it is most likely that the user meant to
  1702. // remove the 'template' keyword.
  1703. assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
  1704. "Expected a definition here");
  1705. if (TUK == Sema::TUK_Friend) {
  1706. Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
  1707. TemplateParams = nullptr;
  1708. } else {
  1709. SourceLocation LAngleLoc =
  1710. PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
  1711. Diag(TemplateId->TemplateNameLoc,
  1712. diag::err_explicit_instantiation_with_definition)
  1713. << SourceRange(TemplateInfo.TemplateLoc)
  1714. << FixItHint::CreateInsertion(LAngleLoc, "<>");
  1715. // Create a fake template parameter list that contains only
  1716. // "template<>", so that we treat this construct as a class
  1717. // template specialization.
  1718. FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
  1719. 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
  1720. LAngleLoc, nullptr));
  1721. TemplateParams = &FakedParamLists;
  1722. }
  1723. }
  1724. // Build the class template specialization.
  1725. TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
  1726. getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
  1727. SS, *TemplateId, attrs,
  1728. MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
  1729. : nullptr,
  1730. TemplateParams ? TemplateParams->size() : 0),
  1731. &SkipBody);
  1732. }
  1733. } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1734. TUK == Sema::TUK_Declaration) {
  1735. // Explicit instantiation of a member of a class template
  1736. // specialization, e.g.,
  1737. //
  1738. // template struct Outer<int>::Inner;
  1739. //
  1740. ProhibitAttributes(attrs);
  1741. TagOrTempResult = Actions.ActOnExplicitInstantiation(
  1742. getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
  1743. TagType, StartLoc, SS, Name, NameLoc, attrs);
  1744. } else if (TUK == Sema::TUK_Friend &&
  1745. TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
  1746. ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
  1747. /*DiagnoseEmptyAttrs=*/true);
  1748. TagOrTempResult = Actions.ActOnTemplatedFriendTag(
  1749. getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
  1750. NameLoc, attrs,
  1751. MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
  1752. TemplateParams ? TemplateParams->size() : 0));
  1753. } else {
  1754. if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
  1755. ProhibitCXX11Attributes(attrs, diag::err_attributes_not_allowed,
  1756. /* DiagnoseEmptyAttrs=*/true);
  1757. if (TUK == Sema::TUK_Definition &&
  1758. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1759. // If the declarator-id is not a template-id, issue a diagnostic and
  1760. // recover by ignoring the 'template' keyword.
  1761. Diag(Tok, diag::err_template_defn_explicit_instantiation)
  1762. << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
  1763. TemplateParams = nullptr;
  1764. }
  1765. bool IsDependent = false;
  1766. // Don't pass down template parameter lists if this is just a tag
  1767. // reference. For example, we don't need the template parameters here:
  1768. // template <class T> class A *makeA(T t);
  1769. MultiTemplateParamsArg TParams;
  1770. if (TUK != Sema::TUK_Reference && TemplateParams)
  1771. TParams =
  1772. MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
  1773. stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
  1774. // Declaration or definition of a class type
  1775. TagOrTempResult = Actions.ActOnTag(
  1776. getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
  1777. DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
  1778. SourceLocation(), false, clang::TypeResult(),
  1779. DSC == DeclSpecContext::DSC_type_specifier,
  1780. DSC == DeclSpecContext::DSC_template_param ||
  1781. DSC == DeclSpecContext::DSC_template_type_arg,
  1782. &SkipBody);
  1783. // If ActOnTag said the type was dependent, try again with the
  1784. // less common call.
  1785. if (IsDependent) {
  1786. assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
  1787. TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
  1788. SS, Name, StartLoc, NameLoc);
  1789. }
  1790. }
  1791. // If this is an elaborated type specifier in function template,
  1792. // and we delayed diagnostics before,
  1793. // just merge them into the current pool.
  1794. if (shouldDelayDiagsInTag) {
  1795. diagsFromTag.done();
  1796. if (TUK == Sema::TUK_Reference &&
  1797. TemplateInfo.Kind == ParsedTemplateInfo::Template)
  1798. diagsFromTag.redelay();
  1799. }
  1800. // If there is a body, parse it and inform the actions module.
  1801. if (TUK == Sema::TUK_Definition) {
  1802. assert(Tok.is(tok::l_brace) ||
  1803. (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
  1804. isClassCompatibleKeyword());
  1805. if (SkipBody.ShouldSkip)
  1806. SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
  1807. TagOrTempResult.get());
  1808. else if (getLangOpts().CPlusPlus)
  1809. ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
  1810. TagOrTempResult.get());
  1811. else {
  1812. Decl *D =
  1813. SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
  1814. // Parse the definition body.
  1815. ParseStructUnionBody(StartLoc, TagType, cast<RecordDecl>(D));
  1816. if (SkipBody.CheckSameAsPrevious &&
  1817. !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
  1818. SkipBody)) {
  1819. DS.SetTypeSpecError();
  1820. return;
  1821. }
  1822. }
  1823. }
  1824. if (!TagOrTempResult.isInvalid())
  1825. // Delayed processing of attributes.
  1826. Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
  1827. const char *PrevSpec = nullptr;
  1828. unsigned DiagID;
  1829. bool Result;
  1830. if (!TypeResult.isInvalid()) {
  1831. Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
  1832. NameLoc.isValid() ? NameLoc : StartLoc,
  1833. PrevSpec, DiagID, TypeResult.get(), Policy);
  1834. } else if (!TagOrTempResult.isInvalid()) {
  1835. Result = DS.SetTypeSpecType(TagType, StartLoc,
  1836. NameLoc.isValid() ? NameLoc : StartLoc,
  1837. PrevSpec, DiagID, TagOrTempResult.get(), Owned,
  1838. Policy);
  1839. } else {
  1840. DS.SetTypeSpecError();
  1841. return;
  1842. }
  1843. if (Result)
  1844. Diag(StartLoc, DiagID) << PrevSpec;
  1845. // At this point, we've successfully parsed a class-specifier in 'definition'
  1846. // form (e.g. "struct foo { int x; }". While we could just return here, we're
  1847. // going to look at what comes after it to improve error recovery. If an
  1848. // impossible token occurs next, we assume that the programmer forgot a ; at
  1849. // the end of the declaration and recover that way.
  1850. //
  1851. // Also enforce C++ [temp]p3:
  1852. // In a template-declaration which defines a class, no declarator
  1853. // is permitted.
  1854. //
  1855. // After a type-specifier, we don't expect a semicolon. This only happens in
  1856. // C, since definitions are not permitted in this context in C++.
  1857. if (TUK == Sema::TUK_Definition &&
  1858. (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
  1859. (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
  1860. if (Tok.isNot(tok::semi)) {
  1861. const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
  1862. ExpectAndConsume(tok::semi, diag::err_expected_after,
  1863. DeclSpec::getSpecifierName(TagType, PPol));
  1864. // Push this token back into the preprocessor and change our current token
  1865. // to ';' so that the rest of the code recovers as though there were an
  1866. // ';' after the definition.
  1867. PP.EnterToken(Tok, /*IsReinject=*/true);
  1868. Tok.setKind(tok::semi);
  1869. }
  1870. }
  1871. }
  1872. /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
  1873. ///
  1874. /// base-clause : [C++ class.derived]
  1875. /// ':' base-specifier-list
  1876. /// base-specifier-list:
  1877. /// base-specifier '...'[opt]
  1878. /// base-specifier-list ',' base-specifier '...'[opt]
  1879. void Parser::ParseBaseClause(Decl *ClassDecl) {
  1880. assert(Tok.is(tok::colon) && "Not a base clause");
  1881. ConsumeToken();
  1882. // Build up an array of parsed base specifiers.
  1883. SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
  1884. while (true) {
  1885. // Parse a base-specifier.
  1886. BaseResult Result = ParseBaseSpecifier(ClassDecl);
  1887. if (Result.isInvalid()) {
  1888. // Skip the rest of this base specifier, up until the comma or
  1889. // opening brace.
  1890. SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
  1891. } else {
  1892. // Add this to our array of base specifiers.
  1893. BaseInfo.push_back(Result.get());
  1894. }
  1895. // If the next token is a comma, consume it and keep reading
  1896. // base-specifiers.
  1897. if (!TryConsumeToken(tok::comma))
  1898. break;
  1899. }
  1900. // Attach the base specifiers
  1901. Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
  1902. }
  1903. /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
  1904. /// one entry in the base class list of a class specifier, for example:
  1905. /// class foo : public bar, virtual private baz {
  1906. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  1907. ///
  1908. /// base-specifier: [C++ class.derived]
  1909. /// attribute-specifier-seq[opt] base-type-specifier
  1910. /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
  1911. /// base-type-specifier
  1912. /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
  1913. /// base-type-specifier
  1914. BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
  1915. bool IsVirtual = false;
  1916. SourceLocation StartLoc = Tok.getLocation();
  1917. ParsedAttributesWithRange Attributes(AttrFactory);
  1918. MaybeParseCXX11Attributes(Attributes);
  1919. // Parse the 'virtual' keyword.
  1920. if (TryConsumeToken(tok::kw_virtual))
  1921. IsVirtual = true;
  1922. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1923. // Parse an (optional) access specifier.
  1924. AccessSpecifier Access = getAccessSpecifierIfPresent();
  1925. if (Access != AS_none)
  1926. ConsumeToken();
  1927. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1928. // Parse the 'virtual' keyword (again!), in case it came after the
  1929. // access specifier.
  1930. if (Tok.is(tok::kw_virtual)) {
  1931. SourceLocation VirtualLoc = ConsumeToken();
  1932. if (IsVirtual) {
  1933. // Complain about duplicate 'virtual'
  1934. Diag(VirtualLoc, diag::err_dup_virtual)
  1935. << FixItHint::CreateRemoval(VirtualLoc);
  1936. }
  1937. IsVirtual = true;
  1938. }
  1939. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1940. // Parse the class-name.
  1941. // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
  1942. // implementation for VS2013 uses _Atomic as an identifier for one of the
  1943. // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
  1944. // parsing the class-name for a base specifier.
  1945. if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
  1946. NextToken().is(tok::less))
  1947. Tok.setKind(tok::identifier);
  1948. SourceLocation EndLocation;
  1949. SourceLocation BaseLoc;
  1950. TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
  1951. if (BaseType.isInvalid())
  1952. return true;
  1953. // Parse the optional ellipsis (for a pack expansion). The ellipsis is
  1954. // actually part of the base-specifier-list grammar productions, but we
  1955. // parse it here for convenience.
  1956. SourceLocation EllipsisLoc;
  1957. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  1958. // Find the complete source range for the base-specifier.
  1959. SourceRange Range(StartLoc, EndLocation);
  1960. // Notify semantic analysis that we have parsed a complete
  1961. // base-specifier.
  1962. return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
  1963. Access, BaseType.get(), BaseLoc,
  1964. EllipsisLoc);
  1965. }
  1966. /// getAccessSpecifierIfPresent - Determine whether the next token is
  1967. /// a C++ access-specifier.
  1968. ///
  1969. /// access-specifier: [C++ class.derived]
  1970. /// 'private'
  1971. /// 'protected'
  1972. /// 'public'
  1973. AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
  1974. switch (Tok.getKind()) {
  1975. default: return AS_none;
  1976. case tok::kw_private: return AS_private;
  1977. case tok::kw_protected: return AS_protected;
  1978. case tok::kw_public: return AS_public;
  1979. }
  1980. }
  1981. /// If the given declarator has any parts for which parsing has to be
  1982. /// delayed, e.g., default arguments or an exception-specification, create a
  1983. /// late-parsed method declaration record to handle the parsing at the end of
  1984. /// the class definition.
  1985. void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
  1986. Decl *ThisDecl) {
  1987. DeclaratorChunk::FunctionTypeInfo &FTI
  1988. = DeclaratorInfo.getFunctionTypeInfo();
  1989. // If there was a late-parsed exception-specification, we'll need a
  1990. // late parse
  1991. bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
  1992. if (!NeedLateParse) {
  1993. // Look ahead to see if there are any default args
  1994. for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
  1995. auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
  1996. if (Param->hasUnparsedDefaultArg()) {
  1997. NeedLateParse = true;
  1998. break;
  1999. }
  2000. }
  2001. }
  2002. if (NeedLateParse) {
  2003. // Push this method onto the stack of late-parsed method
  2004. // declarations.
  2005. auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
  2006. getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
  2007. // Push tokens for each parameter. Those that do not have defaults will be
  2008. // NULL. We need to track all the parameters so that we can push them into
  2009. // scope for later parameters and perhaps for the exception specification.
  2010. LateMethod->DefaultArgs.reserve(FTI.NumParams);
  2011. for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
  2012. LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
  2013. FTI.Params[ParamIdx].Param,
  2014. std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
  2015. // Stash the exception-specification tokens in the late-pased method.
  2016. if (FTI.getExceptionSpecType() == EST_Unparsed) {
  2017. LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
  2018. FTI.ExceptionSpecTokens = nullptr;
  2019. }
  2020. }
  2021. }
  2022. /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
  2023. /// virt-specifier.
  2024. ///
  2025. /// virt-specifier:
  2026. /// override
  2027. /// final
  2028. /// __final
  2029. VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
  2030. if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
  2031. return VirtSpecifiers::VS_None;
  2032. IdentifierInfo *II = Tok.getIdentifierInfo();
  2033. // Initialize the contextual keywords.
  2034. if (!Ident_final) {
  2035. Ident_final = &PP.getIdentifierTable().get("final");
  2036. if (getLangOpts().GNUKeywords)
  2037. Ident_GNU_final = &PP.getIdentifierTable().get("__final");
  2038. if (getLangOpts().MicrosoftExt) {
  2039. Ident_sealed = &PP.getIdentifierTable().get("sealed");
  2040. Ident_abstract = &PP.getIdentifierTable().get("abstract");
  2041. }
  2042. Ident_override = &PP.getIdentifierTable().get("override");
  2043. }
  2044. if (II == Ident_override)
  2045. return VirtSpecifiers::VS_Override;
  2046. if (II == Ident_sealed)
  2047. return VirtSpecifiers::VS_Sealed;
  2048. if (II == Ident_abstract)
  2049. return VirtSpecifiers::VS_Abstract;
  2050. if (II == Ident_final)
  2051. return VirtSpecifiers::VS_Final;
  2052. if (II == Ident_GNU_final)
  2053. return VirtSpecifiers::VS_GNU_Final;
  2054. return VirtSpecifiers::VS_None;
  2055. }
  2056. /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
  2057. ///
  2058. /// virt-specifier-seq:
  2059. /// virt-specifier
  2060. /// virt-specifier-seq virt-specifier
  2061. void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
  2062. bool IsInterface,
  2063. SourceLocation FriendLoc) {
  2064. while (true) {
  2065. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
  2066. if (Specifier == VirtSpecifiers::VS_None)
  2067. return;
  2068. if (FriendLoc.isValid()) {
  2069. Diag(Tok.getLocation(), diag::err_friend_decl_spec)
  2070. << VirtSpecifiers::getSpecifierName(Specifier)
  2071. << FixItHint::CreateRemoval(Tok.getLocation())
  2072. << SourceRange(FriendLoc, FriendLoc);
  2073. ConsumeToken();
  2074. continue;
  2075. }
  2076. // C++ [class.mem]p8:
  2077. // A virt-specifier-seq shall contain at most one of each virt-specifier.
  2078. const char *PrevSpec = nullptr;
  2079. if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
  2080. Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
  2081. << PrevSpec
  2082. << FixItHint::CreateRemoval(Tok.getLocation());
  2083. if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
  2084. Specifier == VirtSpecifiers::VS_Sealed)) {
  2085. Diag(Tok.getLocation(), diag::err_override_control_interface)
  2086. << VirtSpecifiers::getSpecifierName(Specifier);
  2087. } else if (Specifier == VirtSpecifiers::VS_Sealed) {
  2088. Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
  2089. } else if (Specifier == VirtSpecifiers::VS_Abstract) {
  2090. Diag(Tok.getLocation(), diag::ext_ms_abstract_keyword);
  2091. } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
  2092. Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
  2093. } else {
  2094. Diag(Tok.getLocation(),
  2095. getLangOpts().CPlusPlus11
  2096. ? diag::warn_cxx98_compat_override_control_keyword
  2097. : diag::ext_override_control_keyword)
  2098. << VirtSpecifiers::getSpecifierName(Specifier);
  2099. }
  2100. ConsumeToken();
  2101. }
  2102. }
  2103. /// isCXX11FinalKeyword - Determine whether the next token is a C++11
  2104. /// 'final' or Microsoft 'sealed' contextual keyword.
  2105. bool Parser::isCXX11FinalKeyword() const {
  2106. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
  2107. return Specifier == VirtSpecifiers::VS_Final ||
  2108. Specifier == VirtSpecifiers::VS_GNU_Final ||
  2109. Specifier == VirtSpecifiers::VS_Sealed;
  2110. }
  2111. /// isClassCompatibleKeyword - Determine whether the next token is a C++11
  2112. /// 'final' or Microsoft 'sealed' or 'abstract' contextual keywords.
  2113. bool Parser::isClassCompatibleKeyword() const {
  2114. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
  2115. return Specifier == VirtSpecifiers::VS_Final ||
  2116. Specifier == VirtSpecifiers::VS_GNU_Final ||
  2117. Specifier == VirtSpecifiers::VS_Sealed ||
  2118. Specifier == VirtSpecifiers::VS_Abstract;
  2119. }
  2120. /// Parse a C++ member-declarator up to, but not including, the optional
  2121. /// brace-or-equal-initializer or pure-specifier.
  2122. bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
  2123. Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
  2124. LateParsedAttrList &LateParsedAttrs) {
  2125. // member-declarator:
  2126. // declarator virt-specifier-seq[opt] pure-specifier[opt]
  2127. // declarator requires-clause
  2128. // declarator brace-or-equal-initializer[opt]
  2129. // identifier attribute-specifier-seq[opt] ':' constant-expression
  2130. // brace-or-equal-initializer[opt]
  2131. // ':' constant-expression
  2132. //
  2133. // NOTE: the latter two productions are a proposed bugfix rather than the
  2134. // current grammar rules as of C++20.
  2135. if (Tok.isNot(tok::colon))
  2136. ParseDeclarator(DeclaratorInfo);
  2137. else
  2138. DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
  2139. if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
  2140. assert(DeclaratorInfo.isPastIdentifier() &&
  2141. "don't know where identifier would go yet?");
  2142. BitfieldSize = ParseConstantExpression();
  2143. if (BitfieldSize.isInvalid())
  2144. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2145. } else if (Tok.is(tok::kw_requires)) {
  2146. ParseTrailingRequiresClause(DeclaratorInfo);
  2147. } else {
  2148. ParseOptionalCXX11VirtSpecifierSeq(
  2149. VS, getCurrentClass().IsInterface,
  2150. DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
  2151. if (!VS.isUnset())
  2152. MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
  2153. }
  2154. // If a simple-asm-expr is present, parse it.
  2155. if (Tok.is(tok::kw_asm)) {
  2156. SourceLocation Loc;
  2157. ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
  2158. if (AsmLabel.isInvalid())
  2159. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2160. DeclaratorInfo.setAsmLabel(AsmLabel.get());
  2161. DeclaratorInfo.SetRangeEnd(Loc);
  2162. }
  2163. // If attributes exist after the declarator, but before an '{', parse them.
  2164. // However, this does not apply for [[]] attributes (which could show up
  2165. // before or after the __attribute__ attributes).
  2166. DiagnoseAndSkipCXX11Attributes();
  2167. MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
  2168. DiagnoseAndSkipCXX11Attributes();
  2169. // For compatibility with code written to older Clang, also accept a
  2170. // virt-specifier *after* the GNU attributes.
  2171. if (BitfieldSize.isUnset() && VS.isUnset()) {
  2172. ParseOptionalCXX11VirtSpecifierSeq(
  2173. VS, getCurrentClass().IsInterface,
  2174. DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
  2175. if (!VS.isUnset()) {
  2176. // If we saw any GNU-style attributes that are known to GCC followed by a
  2177. // virt-specifier, issue a GCC-compat warning.
  2178. for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
  2179. if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
  2180. Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
  2181. MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
  2182. }
  2183. }
  2184. // If this has neither a name nor a bit width, something has gone seriously
  2185. // wrong. Skip until the semi-colon or }.
  2186. if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
  2187. // If so, skip until the semi-colon or a }.
  2188. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  2189. return true;
  2190. }
  2191. return false;
  2192. }
  2193. /// Look for declaration specifiers possibly occurring after C++11
  2194. /// virt-specifier-seq and diagnose them.
  2195. void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
  2196. Declarator &D,
  2197. VirtSpecifiers &VS) {
  2198. DeclSpec DS(AttrFactory);
  2199. // GNU-style and C++11 attributes are not allowed here, but they will be
  2200. // handled by the caller. Diagnose everything else.
  2201. ParseTypeQualifierListOpt(
  2202. DS, AR_NoAttributesParsed, false,
  2203. /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
  2204. Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
  2205. }));
  2206. D.ExtendWithDeclSpec(DS);
  2207. if (D.isFunctionDeclarator()) {
  2208. auto &Function = D.getFunctionTypeInfo();
  2209. if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
  2210. auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
  2211. SourceLocation SpecLoc) {
  2212. FixItHint Insertion;
  2213. auto &MQ = Function.getOrCreateMethodQualifiers();
  2214. if (!(MQ.getTypeQualifiers() & TypeQual)) {
  2215. std::string Name(FixItName.data());
  2216. Name += " ";
  2217. Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
  2218. MQ.SetTypeQual(TypeQual, SpecLoc);
  2219. }
  2220. Diag(SpecLoc, diag::err_declspec_after_virtspec)
  2221. << FixItName
  2222. << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
  2223. << FixItHint::CreateRemoval(SpecLoc) << Insertion;
  2224. };
  2225. DS.forEachQualifier(DeclSpecCheck);
  2226. }
  2227. // Parse ref-qualifiers.
  2228. bool RefQualifierIsLValueRef = true;
  2229. SourceLocation RefQualifierLoc;
  2230. if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
  2231. const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
  2232. FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
  2233. Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
  2234. Function.RefQualifierLoc = RefQualifierLoc;
  2235. Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
  2236. << (RefQualifierIsLValueRef ? "&" : "&&")
  2237. << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
  2238. << FixItHint::CreateRemoval(RefQualifierLoc)
  2239. << Insertion;
  2240. D.SetRangeEnd(RefQualifierLoc);
  2241. }
  2242. }
  2243. }
  2244. /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
  2245. ///
  2246. /// member-declaration:
  2247. /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
  2248. /// function-definition ';'[opt]
  2249. /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
  2250. /// using-declaration [TODO]
  2251. /// [C++0x] static_assert-declaration
  2252. /// template-declaration
  2253. /// [GNU] '__extension__' member-declaration
  2254. ///
  2255. /// member-declarator-list:
  2256. /// member-declarator
  2257. /// member-declarator-list ',' member-declarator
  2258. ///
  2259. /// member-declarator:
  2260. /// declarator virt-specifier-seq[opt] pure-specifier[opt]
  2261. /// [C++2a] declarator requires-clause
  2262. /// declarator constant-initializer[opt]
  2263. /// [C++11] declarator brace-or-equal-initializer[opt]
  2264. /// identifier[opt] ':' constant-expression
  2265. ///
  2266. /// virt-specifier-seq:
  2267. /// virt-specifier
  2268. /// virt-specifier-seq virt-specifier
  2269. ///
  2270. /// virt-specifier:
  2271. /// override
  2272. /// final
  2273. /// [MS] sealed
  2274. ///
  2275. /// pure-specifier:
  2276. /// '= 0'
  2277. ///
  2278. /// constant-initializer:
  2279. /// '=' constant-expression
  2280. ///
  2281. Parser::DeclGroupPtrTy
  2282. Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
  2283. ParsedAttributes &AccessAttrs,
  2284. const ParsedTemplateInfo &TemplateInfo,
  2285. ParsingDeclRAIIObject *TemplateDiags) {
  2286. if (Tok.is(tok::at)) {
  2287. if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
  2288. Diag(Tok, diag::err_at_defs_cxx);
  2289. else
  2290. Diag(Tok, diag::err_at_in_class);
  2291. ConsumeToken();
  2292. SkipUntil(tok::r_brace, StopAtSemi);
  2293. return nullptr;
  2294. }
  2295. // Turn on colon protection early, while parsing declspec, although there is
  2296. // nothing to protect there. It prevents from false errors if error recovery
  2297. // incorrectly determines where the declspec ends, as in the example:
  2298. // struct A { enum class B { C }; };
  2299. // const int C = 4;
  2300. // struct D { A::B : C; };
  2301. ColonProtectionRAIIObject X(*this);
  2302. // Access declarations.
  2303. bool MalformedTypeSpec = false;
  2304. if (!TemplateInfo.Kind &&
  2305. Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
  2306. if (TryAnnotateCXXScopeToken())
  2307. MalformedTypeSpec = true;
  2308. bool isAccessDecl;
  2309. if (Tok.isNot(tok::annot_cxxscope))
  2310. isAccessDecl = false;
  2311. else if (NextToken().is(tok::identifier))
  2312. isAccessDecl = GetLookAheadToken(2).is(tok::semi);
  2313. else
  2314. isAccessDecl = NextToken().is(tok::kw_operator);
  2315. if (isAccessDecl) {
  2316. // Collect the scope specifier token we annotated earlier.
  2317. CXXScopeSpec SS;
  2318. ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
  2319. /*ObjectHasErrors=*/false,
  2320. /*EnteringContext=*/false);
  2321. if (SS.isInvalid()) {
  2322. SkipUntil(tok::semi);
  2323. return nullptr;
  2324. }
  2325. // Try to parse an unqualified-id.
  2326. SourceLocation TemplateKWLoc;
  2327. UnqualifiedId Name;
  2328. if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
  2329. /*ObjectHadErrors=*/false, false, true, true,
  2330. false, &TemplateKWLoc, Name)) {
  2331. SkipUntil(tok::semi);
  2332. return nullptr;
  2333. }
  2334. // TODO: recover from mistakenly-qualified operator declarations.
  2335. if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  2336. "access declaration")) {
  2337. SkipUntil(tok::semi);
  2338. return nullptr;
  2339. }
  2340. // FIXME: We should do something with the 'template' keyword here.
  2341. return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
  2342. getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
  2343. /*TypenameLoc*/ SourceLocation(), SS, Name,
  2344. /*EllipsisLoc*/ SourceLocation(),
  2345. /*AttrList*/ ParsedAttributesView())));
  2346. }
  2347. }
  2348. // static_assert-declaration. A templated static_assert declaration is
  2349. // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
  2350. if (!TemplateInfo.Kind &&
  2351. Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
  2352. SourceLocation DeclEnd;
  2353. return DeclGroupPtrTy::make(
  2354. DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
  2355. }
  2356. if (Tok.is(tok::kw_template)) {
  2357. assert(!TemplateInfo.TemplateParams &&
  2358. "Nested template improperly parsed?");
  2359. ObjCDeclContextSwitch ObjCDC(*this);
  2360. SourceLocation DeclEnd;
  2361. return DeclGroupPtrTy::make(
  2362. DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
  2363. DeclaratorContext::Member, DeclEnd, AccessAttrs, AS)));
  2364. }
  2365. // Handle: member-declaration ::= '__extension__' member-declaration
  2366. if (Tok.is(tok::kw___extension__)) {
  2367. // __extension__ silences extension warnings in the subexpression.
  2368. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  2369. ConsumeToken();
  2370. return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
  2371. TemplateInfo, TemplateDiags);
  2372. }
  2373. ParsedAttributesWithRange attrs(AttrFactory);
  2374. ParsedAttributesViewWithRange FnAttrs;
  2375. // Optional C++11 attribute-specifier
  2376. MaybeParseCXX11Attributes(attrs);
  2377. // The next token may be an OpenMP pragma annotation token. That would
  2378. // normally be handled from ParseCXXClassMemberDeclarationWithPragmas, but in
  2379. // this case, it came from an *attribute* rather than a pragma. Handle it now.
  2380. if (Tok.is(tok::annot_attr_openmp))
  2381. return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, attrs);
  2382. // We need to keep these attributes for future diagnostic
  2383. // before they are taken over by declaration specifier.
  2384. FnAttrs.addAll(attrs.begin(), attrs.end());
  2385. FnAttrs.Range = attrs.Range;
  2386. MaybeParseMicrosoftAttributes(attrs);
  2387. if (Tok.is(tok::kw_using)) {
  2388. // Eat 'using'.
  2389. SourceLocation UsingLoc = ConsumeToken();
  2390. // Consume unexpected 'template' keywords.
  2391. while (Tok.is(tok::kw_template)) {
  2392. SourceLocation TemplateLoc = ConsumeToken();
  2393. Diag(TemplateLoc, diag::err_unexpected_template_after_using)
  2394. << FixItHint::CreateRemoval(TemplateLoc);
  2395. }
  2396. if (Tok.is(tok::kw_namespace)) {
  2397. Diag(UsingLoc, diag::err_using_namespace_in_class);
  2398. SkipUntil(tok::semi, StopBeforeMatch);
  2399. return nullptr;
  2400. }
  2401. SourceLocation DeclEnd;
  2402. // Otherwise, it must be a using-declaration or an alias-declaration.
  2403. return ParseUsingDeclaration(DeclaratorContext::Member, TemplateInfo,
  2404. UsingLoc, DeclEnd, attrs, AS);
  2405. }
  2406. // Hold late-parsed attributes so we can attach a Decl to them later.
  2407. LateParsedAttrList CommonLateParsedAttrs;
  2408. // decl-specifier-seq:
  2409. // Parse the common declaration-specifiers piece.
  2410. ParsingDeclSpec DS(*this, TemplateDiags);
  2411. DS.takeAttributesFrom(attrs);
  2412. if (MalformedTypeSpec)
  2413. DS.SetTypeSpecError();
  2414. // Turn off usual access checking for templates explicit specialization
  2415. // and instantiation.
  2416. // C++20 [temp.spec] 13.9/6.
  2417. // This disables the access checking rules for member function template
  2418. // explicit instantiation and explicit specialization.
  2419. bool IsTemplateSpecOrInst =
  2420. (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
  2421. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
  2422. SuppressAccessChecks diagsFromTag(*this, IsTemplateSpecOrInst);
  2423. ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
  2424. &CommonLateParsedAttrs);
  2425. if (IsTemplateSpecOrInst)
  2426. diagsFromTag.done();
  2427. // Turn off colon protection that was set for declspec.
  2428. X.restore();
  2429. // If we had a free-standing type definition with a missing semicolon, we
  2430. // may get this far before the problem becomes obvious.
  2431. if (DS.hasTagDefinition() &&
  2432. TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
  2433. DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
  2434. &CommonLateParsedAttrs))
  2435. return nullptr;
  2436. MultiTemplateParamsArg TemplateParams(
  2437. TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
  2438. : nullptr,
  2439. TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
  2440. if (TryConsumeToken(tok::semi)) {
  2441. if (DS.isFriendSpecified())
  2442. ProhibitAttributes(FnAttrs);
  2443. RecordDecl *AnonRecord = nullptr;
  2444. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
  2445. getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
  2446. DS.complete(TheDecl);
  2447. if (AnonRecord) {
  2448. Decl* decls[] = {AnonRecord, TheDecl};
  2449. return Actions.BuildDeclaratorGroup(decls);
  2450. }
  2451. return Actions.ConvertDeclToDeclGroup(TheDecl);
  2452. }
  2453. ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::Member);
  2454. if (TemplateInfo.TemplateParams)
  2455. DeclaratorInfo.setTemplateParameterLists(TemplateParams);
  2456. VirtSpecifiers VS;
  2457. // Hold late-parsed attributes so we can attach a Decl to them later.
  2458. LateParsedAttrList LateParsedAttrs;
  2459. SourceLocation EqualLoc;
  2460. SourceLocation PureSpecLoc;
  2461. auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
  2462. if (Tok.isNot(tok::equal))
  2463. return false;
  2464. auto &Zero = NextToken();
  2465. SmallString<8> Buffer;
  2466. if (Zero.isNot(tok::numeric_constant) ||
  2467. PP.getSpelling(Zero, Buffer) != "0")
  2468. return false;
  2469. auto &After = GetLookAheadToken(2);
  2470. if (!After.isOneOf(tok::semi, tok::comma) &&
  2471. !(AllowDefinition &&
  2472. After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
  2473. return false;
  2474. EqualLoc = ConsumeToken();
  2475. PureSpecLoc = ConsumeToken();
  2476. return true;
  2477. };
  2478. SmallVector<Decl *, 8> DeclsInGroup;
  2479. ExprResult BitfieldSize;
  2480. ExprResult TrailingRequiresClause;
  2481. bool ExpectSemi = true;
  2482. // C++20 [temp.spec] 13.9/6.
  2483. // This disables the access checking rules for member function template
  2484. // explicit instantiation and explicit specialization.
  2485. SuppressAccessChecks SAC(*this, IsTemplateSpecOrInst);
  2486. // Parse the first declarator.
  2487. if (ParseCXXMemberDeclaratorBeforeInitializer(
  2488. DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
  2489. TryConsumeToken(tok::semi);
  2490. return nullptr;
  2491. }
  2492. if (IsTemplateSpecOrInst)
  2493. SAC.done();
  2494. // Check for a member function definition.
  2495. if (BitfieldSize.isUnset()) {
  2496. // MSVC permits pure specifier on inline functions defined at class scope.
  2497. // Hence check for =0 before checking for function definition.
  2498. if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
  2499. TryConsumePureSpecifier(/*AllowDefinition*/ true);
  2500. FunctionDefinitionKind DefinitionKind = FunctionDefinitionKind::Declaration;
  2501. // function-definition:
  2502. //
  2503. // In C++11, a non-function declarator followed by an open brace is a
  2504. // braced-init-list for an in-class member initialization, not an
  2505. // erroneous function definition.
  2506. if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
  2507. DefinitionKind = FunctionDefinitionKind::Definition;
  2508. } else if (DeclaratorInfo.isFunctionDeclarator()) {
  2509. if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
  2510. DefinitionKind = FunctionDefinitionKind::Definition;
  2511. } else if (Tok.is(tok::equal)) {
  2512. const Token &KW = NextToken();
  2513. if (KW.is(tok::kw_default))
  2514. DefinitionKind = FunctionDefinitionKind::Defaulted;
  2515. else if (KW.is(tok::kw_delete))
  2516. DefinitionKind = FunctionDefinitionKind::Deleted;
  2517. else if (KW.is(tok::code_completion)) {
  2518. cutOffParsing();
  2519. Actions.CodeCompleteAfterFunctionEquals(DeclaratorInfo);
  2520. return nullptr;
  2521. }
  2522. }
  2523. }
  2524. DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
  2525. // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
  2526. // to a friend declaration, that declaration shall be a definition.
  2527. if (DeclaratorInfo.isFunctionDeclarator() &&
  2528. DefinitionKind == FunctionDefinitionKind::Declaration &&
  2529. DS.isFriendSpecified()) {
  2530. // Diagnose attributes that appear before decl specifier:
  2531. // [[]] friend int foo();
  2532. ProhibitAttributes(FnAttrs);
  2533. }
  2534. if (DefinitionKind != FunctionDefinitionKind::Declaration) {
  2535. if (!DeclaratorInfo.isFunctionDeclarator()) {
  2536. Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
  2537. ConsumeBrace();
  2538. SkipUntil(tok::r_brace);
  2539. // Consume the optional ';'
  2540. TryConsumeToken(tok::semi);
  2541. return nullptr;
  2542. }
  2543. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  2544. Diag(DeclaratorInfo.getIdentifierLoc(),
  2545. diag::err_function_declared_typedef);
  2546. // Recover by treating the 'typedef' as spurious.
  2547. DS.ClearStorageClassSpecs();
  2548. }
  2549. Decl *FunDecl =
  2550. ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
  2551. VS, PureSpecLoc);
  2552. if (FunDecl) {
  2553. for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
  2554. CommonLateParsedAttrs[i]->addDecl(FunDecl);
  2555. }
  2556. for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
  2557. LateParsedAttrs[i]->addDecl(FunDecl);
  2558. }
  2559. }
  2560. LateParsedAttrs.clear();
  2561. // Consume the ';' - it's optional unless we have a delete or default
  2562. if (Tok.is(tok::semi))
  2563. ConsumeExtraSemi(AfterMemberFunctionDefinition);
  2564. return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
  2565. }
  2566. }
  2567. // member-declarator-list:
  2568. // member-declarator
  2569. // member-declarator-list ',' member-declarator
  2570. while (true) {
  2571. InClassInitStyle HasInClassInit = ICIS_NoInit;
  2572. bool HasStaticInitializer = false;
  2573. if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
  2574. // DRXXXX: Anonymous bit-fields cannot have a brace-or-equal-initializer.
  2575. if (BitfieldSize.isUsable() && !DeclaratorInfo.hasName()) {
  2576. // Diagnose the error and pretend there is no in-class initializer.
  2577. Diag(Tok, diag::err_anon_bitfield_member_init);
  2578. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2579. } else if (DeclaratorInfo.isDeclarationOfFunction()) {
  2580. // It's a pure-specifier.
  2581. if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
  2582. // Parse it as an expression so that Sema can diagnose it.
  2583. HasStaticInitializer = true;
  2584. } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2585. DeclSpec::SCS_static &&
  2586. DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2587. DeclSpec::SCS_typedef &&
  2588. !DS.isFriendSpecified()) {
  2589. // It's a default member initializer.
  2590. if (BitfieldSize.get())
  2591. Diag(Tok, getLangOpts().CPlusPlus20
  2592. ? diag::warn_cxx17_compat_bitfield_member_init
  2593. : diag::ext_bitfield_member_init);
  2594. HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
  2595. } else {
  2596. HasStaticInitializer = true;
  2597. }
  2598. }
  2599. // NOTE: If Sema is the Action module and declarator is an instance field,
  2600. // this call will *not* return the created decl; It will return null.
  2601. // See Sema::ActOnCXXMemberDeclarator for details.
  2602. NamedDecl *ThisDecl = nullptr;
  2603. if (DS.isFriendSpecified()) {
  2604. // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
  2605. // to a friend declaration, that declaration shall be a definition.
  2606. //
  2607. // Diagnose attributes that appear in a friend member function declarator:
  2608. // friend int foo [[]] ();
  2609. SmallVector<SourceRange, 4> Ranges;
  2610. DeclaratorInfo.getCXX11AttributeRanges(Ranges);
  2611. for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
  2612. E = Ranges.end(); I != E; ++I)
  2613. Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
  2614. ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
  2615. TemplateParams);
  2616. } else {
  2617. ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
  2618. DeclaratorInfo,
  2619. TemplateParams,
  2620. BitfieldSize.get(),
  2621. VS, HasInClassInit);
  2622. if (VarTemplateDecl *VT =
  2623. ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
  2624. // Re-direct this decl to refer to the templated decl so that we can
  2625. // initialize it.
  2626. ThisDecl = VT->getTemplatedDecl();
  2627. if (ThisDecl)
  2628. Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
  2629. }
  2630. // Error recovery might have converted a non-static member into a static
  2631. // member.
  2632. if (HasInClassInit != ICIS_NoInit &&
  2633. DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
  2634. DeclSpec::SCS_static) {
  2635. HasInClassInit = ICIS_NoInit;
  2636. HasStaticInitializer = true;
  2637. }
  2638. if (PureSpecLoc.isValid() && VS.getAbstractLoc().isValid()) {
  2639. Diag(PureSpecLoc, diag::err_duplicate_virt_specifier) << "abstract";
  2640. }
  2641. if (ThisDecl && PureSpecLoc.isValid())
  2642. Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
  2643. else if (ThisDecl && VS.getAbstractLoc().isValid())
  2644. Actions.ActOnPureSpecifier(ThisDecl, VS.getAbstractLoc());
  2645. // Handle the initializer.
  2646. if (HasInClassInit != ICIS_NoInit) {
  2647. // The initializer was deferred; parse it and cache the tokens.
  2648. Diag(Tok, getLangOpts().CPlusPlus11
  2649. ? diag::warn_cxx98_compat_nonstatic_member_init
  2650. : diag::ext_nonstatic_member_init);
  2651. if (DeclaratorInfo.isArrayOfUnknownBound()) {
  2652. // C++11 [dcl.array]p3: An array bound may also be omitted when the
  2653. // declarator is followed by an initializer.
  2654. //
  2655. // A brace-or-equal-initializer for a member-declarator is not an
  2656. // initializer in the grammar, so this is ill-formed.
  2657. Diag(Tok, diag::err_incomplete_array_member_init);
  2658. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2659. // Avoid later warnings about a class member of incomplete type.
  2660. if (ThisDecl)
  2661. ThisDecl->setInvalidDecl();
  2662. } else
  2663. ParseCXXNonStaticMemberInitializer(ThisDecl);
  2664. } else if (HasStaticInitializer) {
  2665. // Normal initializer.
  2666. ExprResult Init = ParseCXXMemberInitializer(
  2667. ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
  2668. if (Init.isInvalid()) {
  2669. if (ThisDecl)
  2670. Actions.ActOnUninitializedDecl(ThisDecl);
  2671. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2672. } else if (ThisDecl)
  2673. Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
  2674. } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2675. // No initializer.
  2676. Actions.ActOnUninitializedDecl(ThisDecl);
  2677. if (ThisDecl) {
  2678. if (!ThisDecl->isInvalidDecl()) {
  2679. // Set the Decl for any late parsed attributes
  2680. for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
  2681. CommonLateParsedAttrs[i]->addDecl(ThisDecl);
  2682. for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
  2683. LateParsedAttrs[i]->addDecl(ThisDecl);
  2684. }
  2685. Actions.FinalizeDeclaration(ThisDecl);
  2686. DeclsInGroup.push_back(ThisDecl);
  2687. if (DeclaratorInfo.isFunctionDeclarator() &&
  2688. DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2689. DeclSpec::SCS_typedef)
  2690. HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
  2691. }
  2692. LateParsedAttrs.clear();
  2693. DeclaratorInfo.complete(ThisDecl);
  2694. // If we don't have a comma, it is either the end of the list (a ';')
  2695. // or an error, bail out.
  2696. SourceLocation CommaLoc;
  2697. if (!TryConsumeToken(tok::comma, CommaLoc))
  2698. break;
  2699. if (Tok.isAtStartOfLine() &&
  2700. !MightBeDeclarator(DeclaratorContext::Member)) {
  2701. // This comma was followed by a line-break and something which can't be
  2702. // the start of a declarator. The comma was probably a typo for a
  2703. // semicolon.
  2704. Diag(CommaLoc, diag::err_expected_semi_declaration)
  2705. << FixItHint::CreateReplacement(CommaLoc, ";");
  2706. ExpectSemi = false;
  2707. break;
  2708. }
  2709. // Parse the next declarator.
  2710. DeclaratorInfo.clear();
  2711. VS.clear();
  2712. BitfieldSize = ExprResult(/*Invalid=*/false);
  2713. EqualLoc = PureSpecLoc = SourceLocation();
  2714. DeclaratorInfo.setCommaLoc(CommaLoc);
  2715. // GNU attributes are allowed before the second and subsequent declarator.
  2716. // However, this does not apply for [[]] attributes (which could show up
  2717. // before or after the __attribute__ attributes).
  2718. DiagnoseAndSkipCXX11Attributes();
  2719. MaybeParseGNUAttributes(DeclaratorInfo);
  2720. DiagnoseAndSkipCXX11Attributes();
  2721. if (ParseCXXMemberDeclaratorBeforeInitializer(
  2722. DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
  2723. break;
  2724. }
  2725. if (ExpectSemi &&
  2726. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
  2727. // Skip to end of block or statement.
  2728. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  2729. // If we stopped at a ';', eat it.
  2730. TryConsumeToken(tok::semi);
  2731. return nullptr;
  2732. }
  2733. return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
  2734. }
  2735. /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
  2736. /// Also detect and reject any attempted defaulted/deleted function definition.
  2737. /// The location of the '=', if any, will be placed in EqualLoc.
  2738. ///
  2739. /// This does not check for a pure-specifier; that's handled elsewhere.
  2740. ///
  2741. /// brace-or-equal-initializer:
  2742. /// '=' initializer-expression
  2743. /// braced-init-list
  2744. ///
  2745. /// initializer-clause:
  2746. /// assignment-expression
  2747. /// braced-init-list
  2748. ///
  2749. /// defaulted/deleted function-definition:
  2750. /// '=' 'default'
  2751. /// '=' 'delete'
  2752. ///
  2753. /// Prior to C++0x, the assignment-expression in an initializer-clause must
  2754. /// be a constant-expression.
  2755. ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
  2756. SourceLocation &EqualLoc) {
  2757. assert(Tok.isOneOf(tok::equal, tok::l_brace)
  2758. && "Data member initializer not starting with '=' or '{'");
  2759. EnterExpressionEvaluationContext Context(
  2760. Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
  2761. if (TryConsumeToken(tok::equal, EqualLoc)) {
  2762. if (Tok.is(tok::kw_delete)) {
  2763. // In principle, an initializer of '= delete p;' is legal, but it will
  2764. // never type-check. It's better to diagnose it as an ill-formed expression
  2765. // than as an ill-formed deleted non-function member.
  2766. // An initializer of '= delete p, foo' will never be parsed, because
  2767. // a top-level comma always ends the initializer expression.
  2768. const Token &Next = NextToken();
  2769. if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
  2770. if (IsFunction)
  2771. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  2772. << 1 /* delete */;
  2773. else
  2774. Diag(ConsumeToken(), diag::err_deleted_non_function);
  2775. return ExprError();
  2776. }
  2777. } else if (Tok.is(tok::kw_default)) {
  2778. if (IsFunction)
  2779. Diag(Tok, diag::err_default_delete_in_multiple_declaration)
  2780. << 0 /* default */;
  2781. else
  2782. Diag(ConsumeToken(), diag::err_default_special_members)
  2783. << getLangOpts().CPlusPlus20;
  2784. return ExprError();
  2785. }
  2786. }
  2787. if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
  2788. Diag(Tok, diag::err_ms_property_initializer) << PD;
  2789. return ExprError();
  2790. }
  2791. return ParseInitializer();
  2792. }
  2793. void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
  2794. SourceLocation AttrFixitLoc,
  2795. unsigned TagType, Decl *TagDecl) {
  2796. // Skip the optional 'final' keyword.
  2797. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
  2798. assert(isCXX11FinalKeyword() && "not a class definition");
  2799. ConsumeToken();
  2800. // Diagnose any C++11 attributes after 'final' keyword.
  2801. // We deliberately discard these attributes.
  2802. ParsedAttributesWithRange Attrs(AttrFactory);
  2803. CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
  2804. // This can only happen if we had malformed misplaced attributes;
  2805. // we only get called if there is a colon or left-brace after the
  2806. // attributes.
  2807. if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
  2808. return;
  2809. }
  2810. // Skip the base clauses. This requires actually parsing them, because
  2811. // otherwise we can't be sure where they end (a left brace may appear
  2812. // within a template argument).
  2813. if (Tok.is(tok::colon)) {
  2814. // Enter the scope of the class so that we can correctly parse its bases.
  2815. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
  2816. ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
  2817. TagType == DeclSpec::TST_interface);
  2818. auto OldContext =
  2819. Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
  2820. // Parse the bases but don't attach them to the class.
  2821. ParseBaseClause(nullptr);
  2822. Actions.ActOnTagFinishSkippedDefinition(OldContext);
  2823. if (!Tok.is(tok::l_brace)) {
  2824. Diag(PP.getLocForEndOfToken(PrevTokLocation),
  2825. diag::err_expected_lbrace_after_base_specifiers);
  2826. return;
  2827. }
  2828. }
  2829. // Skip the body.
  2830. assert(Tok.is(tok::l_brace));
  2831. BalancedDelimiterTracker T(*this, tok::l_brace);
  2832. T.consumeOpen();
  2833. T.skipToEnd();
  2834. // Parse and discard any trailing attributes.
  2835. ParsedAttributes Attrs(AttrFactory);
  2836. if (Tok.is(tok::kw___attribute))
  2837. MaybeParseGNUAttributes(Attrs);
  2838. }
  2839. Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
  2840. AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
  2841. DeclSpec::TST TagType, Decl *TagDecl) {
  2842. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  2843. switch (Tok.getKind()) {
  2844. case tok::kw___if_exists:
  2845. case tok::kw___if_not_exists:
  2846. ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
  2847. return nullptr;
  2848. case tok::semi:
  2849. // Check for extraneous top-level semicolon.
  2850. ConsumeExtraSemi(InsideStruct, TagType);
  2851. return nullptr;
  2852. // Handle pragmas that can appear as member declarations.
  2853. case tok::annot_pragma_vis:
  2854. HandlePragmaVisibility();
  2855. return nullptr;
  2856. case tok::annot_pragma_pack:
  2857. HandlePragmaPack();
  2858. return nullptr;
  2859. case tok::annot_pragma_align:
  2860. HandlePragmaAlign();
  2861. return nullptr;
  2862. case tok::annot_pragma_ms_pointers_to_members:
  2863. HandlePragmaMSPointersToMembers();
  2864. return nullptr;
  2865. case tok::annot_pragma_ms_pragma:
  2866. HandlePragmaMSPragma();
  2867. return nullptr;
  2868. case tok::annot_pragma_ms_vtordisp:
  2869. HandlePragmaMSVtorDisp();
  2870. return nullptr;
  2871. case tok::annot_pragma_dump:
  2872. HandlePragmaDump();
  2873. return nullptr;
  2874. case tok::kw_namespace:
  2875. // If we see a namespace here, a close brace was missing somewhere.
  2876. DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
  2877. return nullptr;
  2878. case tok::kw_private:
  2879. // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
  2880. // yet.
  2881. if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
  2882. return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
  2883. LLVM_FALLTHROUGH;
  2884. case tok::kw_public:
  2885. case tok::kw_protected: {
  2886. AccessSpecifier NewAS = getAccessSpecifierIfPresent();
  2887. assert(NewAS != AS_none);
  2888. // Current token is a C++ access specifier.
  2889. AS = NewAS;
  2890. SourceLocation ASLoc = Tok.getLocation();
  2891. unsigned TokLength = Tok.getLength();
  2892. ConsumeToken();
  2893. AccessAttrs.clear();
  2894. MaybeParseGNUAttributes(AccessAttrs);
  2895. SourceLocation EndLoc;
  2896. if (TryConsumeToken(tok::colon, EndLoc)) {
  2897. } else if (TryConsumeToken(tok::semi, EndLoc)) {
  2898. Diag(EndLoc, diag::err_expected)
  2899. << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
  2900. } else {
  2901. EndLoc = ASLoc.getLocWithOffset(TokLength);
  2902. Diag(EndLoc, diag::err_expected)
  2903. << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
  2904. }
  2905. // The Microsoft extension __interface does not permit non-public
  2906. // access specifiers.
  2907. if (TagType == DeclSpec::TST_interface && AS != AS_public) {
  2908. Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
  2909. }
  2910. if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
  2911. // found another attribute than only annotations
  2912. AccessAttrs.clear();
  2913. }
  2914. return nullptr;
  2915. }
  2916. case tok::annot_attr_openmp:
  2917. case tok::annot_pragma_openmp:
  2918. return ParseOpenMPDeclarativeDirectiveWithExtDecl(
  2919. AS, AccessAttrs, /*Delayed=*/true, TagType, TagDecl);
  2920. default:
  2921. if (tok::isPragmaAnnotation(Tok.getKind())) {
  2922. Diag(Tok.getLocation(), diag::err_pragma_misplaced_in_decl)
  2923. << DeclSpec::getSpecifierName(TagType,
  2924. Actions.getASTContext().getPrintingPolicy());
  2925. ConsumeAnnotationToken();
  2926. return nullptr;
  2927. }
  2928. return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
  2929. }
  2930. }
  2931. /// ParseCXXMemberSpecification - Parse the class definition.
  2932. ///
  2933. /// member-specification:
  2934. /// member-declaration member-specification[opt]
  2935. /// access-specifier ':' member-specification[opt]
  2936. ///
  2937. void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
  2938. SourceLocation AttrFixitLoc,
  2939. ParsedAttributesWithRange &Attrs,
  2940. unsigned TagType, Decl *TagDecl) {
  2941. assert((TagType == DeclSpec::TST_struct ||
  2942. TagType == DeclSpec::TST_interface ||
  2943. TagType == DeclSpec::TST_union ||
  2944. TagType == DeclSpec::TST_class) && "Invalid TagType!");
  2945. llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
  2946. if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
  2947. return TD->getQualifiedNameAsString();
  2948. return std::string("<anonymous>");
  2949. });
  2950. PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
  2951. "parsing struct/union/class body");
  2952. // Determine whether this is a non-nested class. Note that local
  2953. // classes are *not* considered to be nested classes.
  2954. bool NonNestedClass = true;
  2955. if (!ClassStack.empty()) {
  2956. for (const Scope *S = getCurScope(); S; S = S->getParent()) {
  2957. if (S->isClassScope()) {
  2958. // We're inside a class scope, so this is a nested class.
  2959. NonNestedClass = false;
  2960. // The Microsoft extension __interface does not permit nested classes.
  2961. if (getCurrentClass().IsInterface) {
  2962. Diag(RecordLoc, diag::err_invalid_member_in_interface)
  2963. << /*ErrorType=*/6
  2964. << (isa<NamedDecl>(TagDecl)
  2965. ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
  2966. : "(anonymous)");
  2967. }
  2968. break;
  2969. }
  2970. if ((S->getFlags() & Scope::FnScope))
  2971. // If we're in a function or function template then this is a local
  2972. // class rather than a nested class.
  2973. break;
  2974. }
  2975. }
  2976. // Enter a scope for the class.
  2977. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
  2978. // Note that we are parsing a new (potentially-nested) class definition.
  2979. ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
  2980. TagType == DeclSpec::TST_interface);
  2981. if (TagDecl)
  2982. Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
  2983. SourceLocation FinalLoc;
  2984. SourceLocation AbstractLoc;
  2985. bool IsFinalSpelledSealed = false;
  2986. bool IsAbstract = false;
  2987. // Parse the optional 'final' keyword.
  2988. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
  2989. while (true) {
  2990. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
  2991. if (Specifier == VirtSpecifiers::VS_None)
  2992. break;
  2993. if (isCXX11FinalKeyword()) {
  2994. if (FinalLoc.isValid()) {
  2995. auto Skipped = ConsumeToken();
  2996. Diag(Skipped, diag::err_duplicate_class_virt_specifier)
  2997. << VirtSpecifiers::getSpecifierName(Specifier);
  2998. } else {
  2999. FinalLoc = ConsumeToken();
  3000. if (Specifier == VirtSpecifiers::VS_Sealed)
  3001. IsFinalSpelledSealed = true;
  3002. }
  3003. } else {
  3004. if (AbstractLoc.isValid()) {
  3005. auto Skipped = ConsumeToken();
  3006. Diag(Skipped, diag::err_duplicate_class_virt_specifier)
  3007. << VirtSpecifiers::getSpecifierName(Specifier);
  3008. } else {
  3009. AbstractLoc = ConsumeToken();
  3010. IsAbstract = true;
  3011. }
  3012. }
  3013. if (TagType == DeclSpec::TST_interface)
  3014. Diag(FinalLoc, diag::err_override_control_interface)
  3015. << VirtSpecifiers::getSpecifierName(Specifier);
  3016. else if (Specifier == VirtSpecifiers::VS_Final)
  3017. Diag(FinalLoc, getLangOpts().CPlusPlus11
  3018. ? diag::warn_cxx98_compat_override_control_keyword
  3019. : diag::ext_override_control_keyword)
  3020. << VirtSpecifiers::getSpecifierName(Specifier);
  3021. else if (Specifier == VirtSpecifiers::VS_Sealed)
  3022. Diag(FinalLoc, diag::ext_ms_sealed_keyword);
  3023. else if (Specifier == VirtSpecifiers::VS_Abstract)
  3024. Diag(AbstractLoc, diag::ext_ms_abstract_keyword);
  3025. else if (Specifier == VirtSpecifiers::VS_GNU_Final)
  3026. Diag(FinalLoc, diag::ext_warn_gnu_final);
  3027. }
  3028. assert((FinalLoc.isValid() || AbstractLoc.isValid()) &&
  3029. "not a class definition");
  3030. // Parse any C++11 attributes after 'final' keyword.
  3031. // These attributes are not allowed to appear here,
  3032. // and the only possible place for them to appertain
  3033. // to the class would be between class-key and class-name.
  3034. CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
  3035. // ParseClassSpecifier() does only a superficial check for attributes before
  3036. // deciding to call this method. For example, for
  3037. // `class C final alignas ([l) {` it will decide that this looks like a
  3038. // misplaced attribute since it sees `alignas '(' ')'`. But the actual
  3039. // attribute parsing code will try to parse the '[' as a constexpr lambda
  3040. // and consume enough tokens that the alignas parsing code will eat the
  3041. // opening '{'. So bail out if the next token isn't one we expect.
  3042. if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
  3043. if (TagDecl)
  3044. Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
  3045. return;
  3046. }
  3047. }
  3048. if (Tok.is(tok::colon)) {
  3049. ParseScope InheritanceScope(this, getCurScope()->getFlags() |
  3050. Scope::ClassInheritanceScope);
  3051. ParseBaseClause(TagDecl);
  3052. if (!Tok.is(tok::l_brace)) {
  3053. bool SuggestFixIt = false;
  3054. SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
  3055. if (Tok.isAtStartOfLine()) {
  3056. switch (Tok.getKind()) {
  3057. case tok::kw_private:
  3058. case tok::kw_protected:
  3059. case tok::kw_public:
  3060. SuggestFixIt = NextToken().getKind() == tok::colon;
  3061. break;
  3062. case tok::kw_static_assert:
  3063. case tok::r_brace:
  3064. case tok::kw_using:
  3065. // base-clause can have simple-template-id; 'template' can't be there
  3066. case tok::kw_template:
  3067. SuggestFixIt = true;
  3068. break;
  3069. case tok::identifier:
  3070. SuggestFixIt = isConstructorDeclarator(true);
  3071. break;
  3072. default:
  3073. SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
  3074. break;
  3075. }
  3076. }
  3077. DiagnosticBuilder LBraceDiag =
  3078. Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
  3079. if (SuggestFixIt) {
  3080. LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
  3081. // Try recovering from missing { after base-clause.
  3082. PP.EnterToken(Tok, /*IsReinject*/true);
  3083. Tok.setKind(tok::l_brace);
  3084. } else {
  3085. if (TagDecl)
  3086. Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
  3087. return;
  3088. }
  3089. }
  3090. }
  3091. assert(Tok.is(tok::l_brace));
  3092. BalancedDelimiterTracker T(*this, tok::l_brace);
  3093. T.consumeOpen();
  3094. if (TagDecl)
  3095. Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
  3096. IsFinalSpelledSealed, IsAbstract,
  3097. T.getOpenLocation());
  3098. // C++ 11p3: Members of a class defined with the keyword class are private
  3099. // by default. Members of a class defined with the keywords struct or union
  3100. // are public by default.
  3101. AccessSpecifier CurAS;
  3102. if (TagType == DeclSpec::TST_class)
  3103. CurAS = AS_private;
  3104. else
  3105. CurAS = AS_public;
  3106. ParsedAttributesWithRange AccessAttrs(AttrFactory);
  3107. if (TagDecl) {
  3108. // While we still have something to read, read the member-declarations.
  3109. while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
  3110. Tok.isNot(tok::eof)) {
  3111. // Each iteration of this loop reads one member-declaration.
  3112. ParseCXXClassMemberDeclarationWithPragmas(
  3113. CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
  3114. MaybeDestroyTemplateIds();
  3115. }
  3116. T.consumeClose();
  3117. } else {
  3118. SkipUntil(tok::r_brace);
  3119. }
  3120. // If attributes exist after class contents, parse them.
  3121. ParsedAttributes attrs(AttrFactory);
  3122. MaybeParseGNUAttributes(attrs);
  3123. if (TagDecl)
  3124. Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
  3125. T.getOpenLocation(),
  3126. T.getCloseLocation(), attrs);
  3127. // C++11 [class.mem]p2:
  3128. // Within the class member-specification, the class is regarded as complete
  3129. // within function bodies, default arguments, exception-specifications, and
  3130. // brace-or-equal-initializers for non-static data members (including such
  3131. // things in nested classes).
  3132. if (TagDecl && NonNestedClass) {
  3133. // We are not inside a nested class. This class and its nested classes
  3134. // are complete and we can parse the delayed portions of method
  3135. // declarations and the lexed inline method definitions, along with any
  3136. // delayed attributes.
  3137. SourceLocation SavedPrevTokLocation = PrevTokLocation;
  3138. ParseLexedPragmas(getCurrentClass());
  3139. ParseLexedAttributes(getCurrentClass());
  3140. ParseLexedMethodDeclarations(getCurrentClass());
  3141. // We've finished with all pending member declarations.
  3142. Actions.ActOnFinishCXXMemberDecls();
  3143. ParseLexedMemberInitializers(getCurrentClass());
  3144. ParseLexedMethodDefs(getCurrentClass());
  3145. PrevTokLocation = SavedPrevTokLocation;
  3146. // We've finished parsing everything, including default argument
  3147. // initializers.
  3148. Actions.ActOnFinishCXXNonNestedClass();
  3149. }
  3150. if (TagDecl)
  3151. Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
  3152. // Leave the class scope.
  3153. ParsingDef.Pop();
  3154. ClassScope.Exit();
  3155. }
  3156. void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
  3157. assert(Tok.is(tok::kw_namespace));
  3158. // FIXME: Suggest where the close brace should have gone by looking
  3159. // at indentation changes within the definition body.
  3160. Diag(D->getLocation(),
  3161. diag::err_missing_end_of_definition) << D;
  3162. Diag(Tok.getLocation(),
  3163. diag::note_missing_end_of_definition_before) << D;
  3164. // Push '};' onto the token stream to recover.
  3165. PP.EnterToken(Tok, /*IsReinject*/ true);
  3166. Tok.startToken();
  3167. Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
  3168. Tok.setKind(tok::semi);
  3169. PP.EnterToken(Tok, /*IsReinject*/ true);
  3170. Tok.setKind(tok::r_brace);
  3171. }
  3172. /// ParseConstructorInitializer - Parse a C++ constructor initializer,
  3173. /// which explicitly initializes the members or base classes of a
  3174. /// class (C++ [class.base.init]). For example, the three initializers
  3175. /// after the ':' in the Derived constructor below:
  3176. ///
  3177. /// @code
  3178. /// class Base { };
  3179. /// class Derived : Base {
  3180. /// int x;
  3181. /// float f;
  3182. /// public:
  3183. /// Derived(float f) : Base(), x(17), f(f) { }
  3184. /// };
  3185. /// @endcode
  3186. ///
  3187. /// [C++] ctor-initializer:
  3188. /// ':' mem-initializer-list
  3189. ///
  3190. /// [C++] mem-initializer-list:
  3191. /// mem-initializer ...[opt]
  3192. /// mem-initializer ...[opt] , mem-initializer-list
  3193. void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
  3194. assert(Tok.is(tok::colon) &&
  3195. "Constructor initializer always starts with ':'");
  3196. // Poison the SEH identifiers so they are flagged as illegal in constructor
  3197. // initializers.
  3198. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
  3199. SourceLocation ColonLoc = ConsumeToken();
  3200. SmallVector<CXXCtorInitializer*, 4> MemInitializers;
  3201. bool AnyErrors = false;
  3202. do {
  3203. if (Tok.is(tok::code_completion)) {
  3204. cutOffParsing();
  3205. Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
  3206. MemInitializers);
  3207. return;
  3208. }
  3209. MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
  3210. if (!MemInit.isInvalid())
  3211. MemInitializers.push_back(MemInit.get());
  3212. else
  3213. AnyErrors = true;
  3214. if (Tok.is(tok::comma))
  3215. ConsumeToken();
  3216. else if (Tok.is(tok::l_brace))
  3217. break;
  3218. // If the previous initializer was valid and the next token looks like a
  3219. // base or member initializer, assume that we're just missing a comma.
  3220. else if (!MemInit.isInvalid() &&
  3221. Tok.isOneOf(tok::identifier, tok::coloncolon)) {
  3222. SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
  3223. Diag(Loc, diag::err_ctor_init_missing_comma)
  3224. << FixItHint::CreateInsertion(Loc, ", ");
  3225. } else {
  3226. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  3227. if (!MemInit.isInvalid())
  3228. Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
  3229. << tok::comma;
  3230. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
  3231. break;
  3232. }
  3233. } while (true);
  3234. Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
  3235. AnyErrors);
  3236. }
  3237. /// ParseMemInitializer - Parse a C++ member initializer, which is
  3238. /// part of a constructor initializer that explicitly initializes one
  3239. /// member or base class (C++ [class.base.init]). See
  3240. /// ParseConstructorInitializer for an example.
  3241. ///
  3242. /// [C++] mem-initializer:
  3243. /// mem-initializer-id '(' expression-list[opt] ')'
  3244. /// [C++0x] mem-initializer-id braced-init-list
  3245. ///
  3246. /// [C++] mem-initializer-id:
  3247. /// '::'[opt] nested-name-specifier[opt] class-name
  3248. /// identifier
  3249. MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
  3250. // parse '::'[opt] nested-name-specifier[opt]
  3251. CXXScopeSpec SS;
  3252. if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
  3253. /*ObjectHasErrors=*/false,
  3254. /*EnteringContext=*/false))
  3255. return true;
  3256. // : identifier
  3257. IdentifierInfo *II = nullptr;
  3258. SourceLocation IdLoc = Tok.getLocation();
  3259. // : declype(...)
  3260. DeclSpec DS(AttrFactory);
  3261. // : template_name<...>
  3262. TypeResult TemplateTypeTy;
  3263. if (Tok.is(tok::identifier)) {
  3264. // Get the identifier. This may be a member name or a class name,
  3265. // but we'll let the semantic analysis determine which it is.
  3266. II = Tok.getIdentifierInfo();
  3267. ConsumeToken();
  3268. } else if (Tok.is(tok::annot_decltype)) {
  3269. // Get the decltype expression, if there is one.
  3270. // Uses of decltype will already have been converted to annot_decltype by
  3271. // ParseOptionalCXXScopeSpecifier at this point.
  3272. // FIXME: Can we get here with a scope specifier?
  3273. ParseDecltypeSpecifier(DS);
  3274. } else {
  3275. TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
  3276. ? takeTemplateIdAnnotation(Tok)
  3277. : nullptr;
  3278. if (TemplateId && TemplateId->mightBeType()) {
  3279. AnnotateTemplateIdTokenAsType(SS, /*IsClassName*/true);
  3280. assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
  3281. TemplateTypeTy = getTypeAnnotation(Tok);
  3282. ConsumeAnnotationToken();
  3283. } else {
  3284. Diag(Tok, diag::err_expected_member_or_base_name);
  3285. return true;
  3286. }
  3287. }
  3288. // Parse the '('.
  3289. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  3290. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  3291. // FIXME: Add support for signature help inside initializer lists.
  3292. ExprResult InitList = ParseBraceInitializer();
  3293. if (InitList.isInvalid())
  3294. return true;
  3295. SourceLocation EllipsisLoc;
  3296. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  3297. if (TemplateTypeTy.isInvalid())
  3298. return true;
  3299. return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
  3300. TemplateTypeTy.get(), DS, IdLoc,
  3301. InitList.get(), EllipsisLoc);
  3302. } else if(Tok.is(tok::l_paren)) {
  3303. BalancedDelimiterTracker T(*this, tok::l_paren);
  3304. T.consumeOpen();
  3305. // Parse the optional expression-list.
  3306. ExprVector ArgExprs;
  3307. CommaLocsTy CommaLocs;
  3308. auto RunSignatureHelp = [&] {
  3309. if (TemplateTypeTy.isInvalid())
  3310. return QualType();
  3311. QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
  3312. ConstructorDecl, SS, TemplateTypeTy.get(), ArgExprs, II,
  3313. T.getOpenLocation(), /*Braced=*/false);
  3314. CalledSignatureHelp = true;
  3315. return PreferredType;
  3316. };
  3317. if (Tok.isNot(tok::r_paren) &&
  3318. ParseExpressionList(ArgExprs, CommaLocs, [&] {
  3319. PreferredType.enterFunctionArgument(Tok.getLocation(),
  3320. RunSignatureHelp);
  3321. })) {
  3322. if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
  3323. RunSignatureHelp();
  3324. SkipUntil(tok::r_paren, StopAtSemi);
  3325. return true;
  3326. }
  3327. T.consumeClose();
  3328. SourceLocation EllipsisLoc;
  3329. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  3330. if (TemplateTypeTy.isInvalid())
  3331. return true;
  3332. return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
  3333. TemplateTypeTy.get(), DS, IdLoc,
  3334. T.getOpenLocation(), ArgExprs,
  3335. T.getCloseLocation(), EllipsisLoc);
  3336. }
  3337. if (TemplateTypeTy.isInvalid())
  3338. return true;
  3339. if (getLangOpts().CPlusPlus11)
  3340. return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
  3341. else
  3342. return Diag(Tok, diag::err_expected) << tok::l_paren;
  3343. }
  3344. /// Parse a C++ exception-specification if present (C++0x [except.spec]).
  3345. ///
  3346. /// exception-specification:
  3347. /// dynamic-exception-specification
  3348. /// noexcept-specification
  3349. ///
  3350. /// noexcept-specification:
  3351. /// 'noexcept'
  3352. /// 'noexcept' '(' constant-expression ')'
  3353. ExceptionSpecificationType
  3354. Parser::tryParseExceptionSpecification(bool Delayed,
  3355. SourceRange &SpecificationRange,
  3356. SmallVectorImpl<ParsedType> &DynamicExceptions,
  3357. SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
  3358. ExprResult &NoexceptExpr,
  3359. CachedTokens *&ExceptionSpecTokens) {
  3360. ExceptionSpecificationType Result = EST_None;
  3361. ExceptionSpecTokens = nullptr;
  3362. // Handle delayed parsing of exception-specifications.
  3363. if (Delayed) {
  3364. if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
  3365. return EST_None;
  3366. // Consume and cache the starting token.
  3367. bool IsNoexcept = Tok.is(tok::kw_noexcept);
  3368. Token StartTok = Tok;
  3369. SpecificationRange = SourceRange(ConsumeToken());
  3370. // Check for a '('.
  3371. if (!Tok.is(tok::l_paren)) {
  3372. // If this is a bare 'noexcept', we're done.
  3373. if (IsNoexcept) {
  3374. Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
  3375. NoexceptExpr = nullptr;
  3376. return EST_BasicNoexcept;
  3377. }
  3378. Diag(Tok, diag::err_expected_lparen_after) << "throw";
  3379. return EST_DynamicNone;
  3380. }
  3381. // Cache the tokens for the exception-specification.
  3382. ExceptionSpecTokens = new CachedTokens;
  3383. ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
  3384. ExceptionSpecTokens->push_back(Tok); // '('
  3385. SpecificationRange.setEnd(ConsumeParen()); // '('
  3386. ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
  3387. /*StopAtSemi=*/true,
  3388. /*ConsumeFinalToken=*/true);
  3389. SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
  3390. return EST_Unparsed;
  3391. }
  3392. // See if there's a dynamic specification.
  3393. if (Tok.is(tok::kw_throw)) {
  3394. Result = ParseDynamicExceptionSpecification(SpecificationRange,
  3395. DynamicExceptions,
  3396. DynamicExceptionRanges);
  3397. assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
  3398. "Produced different number of exception types and ranges.");
  3399. }
  3400. // If there's no noexcept specification, we're done.
  3401. if (Tok.isNot(tok::kw_noexcept))
  3402. return Result;
  3403. Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
  3404. // If we already had a dynamic specification, parse the noexcept for,
  3405. // recovery, but emit a diagnostic and don't store the results.
  3406. SourceRange NoexceptRange;
  3407. ExceptionSpecificationType NoexceptType = EST_None;
  3408. SourceLocation KeywordLoc = ConsumeToken();
  3409. if (Tok.is(tok::l_paren)) {
  3410. // There is an argument.
  3411. BalancedDelimiterTracker T(*this, tok::l_paren);
  3412. T.consumeOpen();
  3413. NoexceptExpr = ParseConstantExpression();
  3414. T.consumeClose();
  3415. if (!NoexceptExpr.isInvalid()) {
  3416. NoexceptExpr = Actions.ActOnNoexceptSpec(NoexceptExpr.get(),
  3417. NoexceptType);
  3418. NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
  3419. } else {
  3420. NoexceptType = EST_BasicNoexcept;
  3421. }
  3422. } else {
  3423. // There is no argument.
  3424. NoexceptType = EST_BasicNoexcept;
  3425. NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
  3426. }
  3427. if (Result == EST_None) {
  3428. SpecificationRange = NoexceptRange;
  3429. Result = NoexceptType;
  3430. // If there's a dynamic specification after a noexcept specification,
  3431. // parse that and ignore the results.
  3432. if (Tok.is(tok::kw_throw)) {
  3433. Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
  3434. ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
  3435. DynamicExceptionRanges);
  3436. }
  3437. } else {
  3438. Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
  3439. }
  3440. return Result;
  3441. }
  3442. static void diagnoseDynamicExceptionSpecification(
  3443. Parser &P, SourceRange Range, bool IsNoexcept) {
  3444. if (P.getLangOpts().CPlusPlus11) {
  3445. const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
  3446. P.Diag(Range.getBegin(),
  3447. P.getLangOpts().CPlusPlus17 && !IsNoexcept
  3448. ? diag::ext_dynamic_exception_spec
  3449. : diag::warn_exception_spec_deprecated)
  3450. << Range;
  3451. P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
  3452. << Replacement << FixItHint::CreateReplacement(Range, Replacement);
  3453. }
  3454. }
  3455. /// ParseDynamicExceptionSpecification - Parse a C++
  3456. /// dynamic-exception-specification (C++ [except.spec]).
  3457. ///
  3458. /// dynamic-exception-specification:
  3459. /// 'throw' '(' type-id-list [opt] ')'
  3460. /// [MS] 'throw' '(' '...' ')'
  3461. ///
  3462. /// type-id-list:
  3463. /// type-id ... [opt]
  3464. /// type-id-list ',' type-id ... [opt]
  3465. ///
  3466. ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
  3467. SourceRange &SpecificationRange,
  3468. SmallVectorImpl<ParsedType> &Exceptions,
  3469. SmallVectorImpl<SourceRange> &Ranges) {
  3470. assert(Tok.is(tok::kw_throw) && "expected throw");
  3471. SpecificationRange.setBegin(ConsumeToken());
  3472. BalancedDelimiterTracker T(*this, tok::l_paren);
  3473. if (T.consumeOpen()) {
  3474. Diag(Tok, diag::err_expected_lparen_after) << "throw";
  3475. SpecificationRange.setEnd(SpecificationRange.getBegin());
  3476. return EST_DynamicNone;
  3477. }
  3478. // Parse throw(...), a Microsoft extension that means "this function
  3479. // can throw anything".
  3480. if (Tok.is(tok::ellipsis)) {
  3481. SourceLocation EllipsisLoc = ConsumeToken();
  3482. if (!getLangOpts().MicrosoftExt)
  3483. Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
  3484. T.consumeClose();
  3485. SpecificationRange.setEnd(T.getCloseLocation());
  3486. diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
  3487. return EST_MSAny;
  3488. }
  3489. // Parse the sequence of type-ids.
  3490. SourceRange Range;
  3491. while (Tok.isNot(tok::r_paren)) {
  3492. TypeResult Res(ParseTypeName(&Range));
  3493. if (Tok.is(tok::ellipsis)) {
  3494. // C++0x [temp.variadic]p5:
  3495. // - In a dynamic-exception-specification (15.4); the pattern is a
  3496. // type-id.
  3497. SourceLocation Ellipsis = ConsumeToken();
  3498. Range.setEnd(Ellipsis);
  3499. if (!Res.isInvalid())
  3500. Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
  3501. }
  3502. if (!Res.isInvalid()) {
  3503. Exceptions.push_back(Res.get());
  3504. Ranges.push_back(Range);
  3505. }
  3506. if (!TryConsumeToken(tok::comma))
  3507. break;
  3508. }
  3509. T.consumeClose();
  3510. SpecificationRange.setEnd(T.getCloseLocation());
  3511. diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
  3512. Exceptions.empty());
  3513. return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
  3514. }
  3515. /// ParseTrailingReturnType - Parse a trailing return type on a new-style
  3516. /// function declaration.
  3517. TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
  3518. bool MayBeFollowedByDirectInit) {
  3519. assert(Tok.is(tok::arrow) && "expected arrow");
  3520. ConsumeToken();
  3521. return ParseTypeName(&Range, MayBeFollowedByDirectInit
  3522. ? DeclaratorContext::TrailingReturnVar
  3523. : DeclaratorContext::TrailingReturn);
  3524. }
  3525. /// Parse a requires-clause as part of a function declaration.
  3526. void Parser::ParseTrailingRequiresClause(Declarator &D) {
  3527. assert(Tok.is(tok::kw_requires) && "expected requires");
  3528. SourceLocation RequiresKWLoc = ConsumeToken();
  3529. ExprResult TrailingRequiresClause;
  3530. ParseScope ParamScope(this,
  3531. Scope::DeclScope |
  3532. Scope::FunctionDeclarationScope |
  3533. Scope::FunctionPrototypeScope);
  3534. Actions.ActOnStartTrailingRequiresClause(getCurScope(), D);
  3535. llvm::Optional<Sema::CXXThisScopeRAII> ThisScope;
  3536. InitCXXThisScopeForDeclaratorIfRelevant(D, D.getDeclSpec(), ThisScope);
  3537. TrailingRequiresClause =
  3538. ParseConstraintLogicalOrExpression(/*IsTrailingRequiresClause=*/true);
  3539. TrailingRequiresClause =
  3540. Actions.ActOnFinishTrailingRequiresClause(TrailingRequiresClause);
  3541. if (!D.isDeclarationOfFunction()) {
  3542. Diag(RequiresKWLoc,
  3543. diag::err_requires_clause_on_declarator_not_declaring_a_function);
  3544. return;
  3545. }
  3546. if (TrailingRequiresClause.isInvalid())
  3547. SkipUntil({tok::l_brace, tok::arrow, tok::kw_try, tok::comma, tok::colon},
  3548. StopAtSemi | StopBeforeMatch);
  3549. else
  3550. D.setTrailingRequiresClause(TrailingRequiresClause.get());
  3551. // Did the user swap the trailing return type and requires clause?
  3552. if (D.isFunctionDeclarator() && Tok.is(tok::arrow) &&
  3553. D.getDeclSpec().getTypeSpecType() == TST_auto) {
  3554. SourceLocation ArrowLoc = Tok.getLocation();
  3555. SourceRange Range;
  3556. TypeResult TrailingReturnType =
  3557. ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit=*/false);
  3558. if (!TrailingReturnType.isInvalid()) {
  3559. Diag(ArrowLoc,
  3560. diag::err_requires_clause_must_appear_after_trailing_return)
  3561. << Range;
  3562. auto &FunctionChunk = D.getFunctionTypeInfo();
  3563. FunctionChunk.HasTrailingReturnType = TrailingReturnType.isUsable();
  3564. FunctionChunk.TrailingReturnType = TrailingReturnType.get();
  3565. FunctionChunk.TrailingReturnTypeLoc = Range.getBegin();
  3566. } else
  3567. SkipUntil({tok::equal, tok::l_brace, tok::arrow, tok::kw_try, tok::comma},
  3568. StopAtSemi | StopBeforeMatch);
  3569. }
  3570. }
  3571. /// We have just started parsing the definition of a new class,
  3572. /// so push that class onto our stack of classes that is currently
  3573. /// being parsed.
  3574. Sema::ParsingClassState
  3575. Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
  3576. bool IsInterface) {
  3577. assert((NonNestedClass || !ClassStack.empty()) &&
  3578. "Nested class without outer class");
  3579. ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
  3580. return Actions.PushParsingClass();
  3581. }
  3582. /// Deallocate the given parsed class and all of its nested
  3583. /// classes.
  3584. void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
  3585. for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
  3586. delete Class->LateParsedDeclarations[I];
  3587. delete Class;
  3588. }
  3589. /// Pop the top class of the stack of classes that are
  3590. /// currently being parsed.
  3591. ///
  3592. /// This routine should be called when we have finished parsing the
  3593. /// definition of a class, but have not yet popped the Scope
  3594. /// associated with the class's definition.
  3595. void Parser::PopParsingClass(Sema::ParsingClassState state) {
  3596. assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
  3597. Actions.PopParsingClass(state);
  3598. ParsingClass *Victim = ClassStack.top();
  3599. ClassStack.pop();
  3600. if (Victim->TopLevelClass) {
  3601. // Deallocate all of the nested classes of this class,
  3602. // recursively: we don't need to keep any of this information.
  3603. DeallocateParsedClasses(Victim);
  3604. return;
  3605. }
  3606. assert(!ClassStack.empty() && "Missing top-level class?");
  3607. if (Victim->LateParsedDeclarations.empty()) {
  3608. // The victim is a nested class, but we will not need to perform
  3609. // any processing after the definition of this class since it has
  3610. // no members whose handling was delayed. Therefore, we can just
  3611. // remove this nested class.
  3612. DeallocateParsedClasses(Victim);
  3613. return;
  3614. }
  3615. // This nested class has some members that will need to be processed
  3616. // after the top-level class is completely defined. Therefore, add
  3617. // it to the list of nested classes within its parent.
  3618. assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
  3619. ClassStack.top()->LateParsedDeclarations.push_back(
  3620. new LateParsedClass(this, Victim));
  3621. }
  3622. /// Try to parse an 'identifier' which appears within an attribute-token.
  3623. ///
  3624. /// \return the parsed identifier on success, and 0 if the next token is not an
  3625. /// attribute-token.
  3626. ///
  3627. /// C++11 [dcl.attr.grammar]p3:
  3628. /// If a keyword or an alternative token that satisfies the syntactic
  3629. /// requirements of an identifier is contained in an attribute-token,
  3630. /// it is considered an identifier.
  3631. IdentifierInfo *
  3632. Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc,
  3633. Sema::AttributeCompletion Completion,
  3634. const IdentifierInfo *Scope) {
  3635. switch (Tok.getKind()) {
  3636. default:
  3637. // Identifiers and keywords have identifier info attached.
  3638. if (!Tok.isAnnotation()) {
  3639. if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  3640. Loc = ConsumeToken();
  3641. return II;
  3642. }
  3643. }
  3644. return nullptr;
  3645. case tok::code_completion:
  3646. cutOffParsing();
  3647. Actions.CodeCompleteAttribute(getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11
  3648. : ParsedAttr::AS_C2x,
  3649. Completion, Scope);
  3650. return nullptr;
  3651. case tok::numeric_constant: {
  3652. // If we got a numeric constant, check to see if it comes from a macro that
  3653. // corresponds to the predefined __clang__ macro. If it does, warn the user
  3654. // and recover by pretending they said _Clang instead.
  3655. if (Tok.getLocation().isMacroID()) {
  3656. SmallString<8> ExpansionBuf;
  3657. SourceLocation ExpansionLoc =
  3658. PP.getSourceManager().getExpansionLoc(Tok.getLocation());
  3659. StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
  3660. if (Spelling == "__clang__") {
  3661. SourceRange TokRange(
  3662. ExpansionLoc,
  3663. PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
  3664. Diag(Tok, diag::warn_wrong_clang_attr_namespace)
  3665. << FixItHint::CreateReplacement(TokRange, "_Clang");
  3666. Loc = ConsumeToken();
  3667. return &PP.getIdentifierTable().get("_Clang");
  3668. }
  3669. }
  3670. return nullptr;
  3671. }
  3672. case tok::ampamp: // 'and'
  3673. case tok::pipe: // 'bitor'
  3674. case tok::pipepipe: // 'or'
  3675. case tok::caret: // 'xor'
  3676. case tok::tilde: // 'compl'
  3677. case tok::amp: // 'bitand'
  3678. case tok::ampequal: // 'and_eq'
  3679. case tok::pipeequal: // 'or_eq'
  3680. case tok::caretequal: // 'xor_eq'
  3681. case tok::exclaim: // 'not'
  3682. case tok::exclaimequal: // 'not_eq'
  3683. // Alternative tokens do not have identifier info, but their spelling
  3684. // starts with an alphabetical character.
  3685. SmallString<8> SpellingBuf;
  3686. SourceLocation SpellingLoc =
  3687. PP.getSourceManager().getSpellingLoc(Tok.getLocation());
  3688. StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
  3689. if (isLetter(Spelling[0])) {
  3690. Loc = ConsumeToken();
  3691. return &PP.getIdentifierTable().get(Spelling);
  3692. }
  3693. return nullptr;
  3694. }
  3695. }
  3696. void Parser::ParseOpenMPAttributeArgs(IdentifierInfo *AttrName,
  3697. CachedTokens &OpenMPTokens) {
  3698. // Both 'sequence' and 'directive' attributes require arguments, so parse the
  3699. // open paren for the argument list.
  3700. BalancedDelimiterTracker T(*this, tok::l_paren);
  3701. if (T.consumeOpen()) {
  3702. Diag(Tok, diag::err_expected) << tok::l_paren;
  3703. return;
  3704. }
  3705. if (AttrName->isStr("directive")) {
  3706. // If the attribute is named `directive`, we can consume its argument list
  3707. // and push the tokens from it into the cached token stream for a new OpenMP
  3708. // pragma directive.
  3709. Token OMPBeginTok;
  3710. OMPBeginTok.startToken();
  3711. OMPBeginTok.setKind(tok::annot_attr_openmp);
  3712. OMPBeginTok.setLocation(Tok.getLocation());
  3713. OpenMPTokens.push_back(OMPBeginTok);
  3714. ConsumeAndStoreUntil(tok::r_paren, OpenMPTokens, /*StopAtSemi=*/false,
  3715. /*ConsumeFinalToken*/ false);
  3716. Token OMPEndTok;
  3717. OMPEndTok.startToken();
  3718. OMPEndTok.setKind(tok::annot_pragma_openmp_end);
  3719. OMPEndTok.setLocation(Tok.getLocation());
  3720. OpenMPTokens.push_back(OMPEndTok);
  3721. } else {
  3722. assert(AttrName->isStr("sequence") &&
  3723. "Expected either 'directive' or 'sequence'");
  3724. // If the attribute is named 'sequence', its argument is a list of one or
  3725. // more OpenMP attributes (either 'omp::directive' or 'omp::sequence',
  3726. // where the 'omp::' is optional).
  3727. do {
  3728. // We expect to see one of the following:
  3729. // * An identifier (omp) for the attribute namespace followed by ::
  3730. // * An identifier (directive) or an identifier (sequence).
  3731. SourceLocation IdentLoc;
  3732. IdentifierInfo *Ident = TryParseCXX11AttributeIdentifier(IdentLoc);
  3733. // If there is an identifier and it is 'omp', a double colon is required
  3734. // followed by the actual identifier we're after.
  3735. if (Ident && Ident->isStr("omp") && !ExpectAndConsume(tok::coloncolon))
  3736. Ident = TryParseCXX11AttributeIdentifier(IdentLoc);
  3737. // If we failed to find an identifier (scoped or otherwise), or we found
  3738. // an unexpected identifier, diagnose.
  3739. if (!Ident || (!Ident->isStr("directive") && !Ident->isStr("sequence"))) {
  3740. Diag(Tok.getLocation(), diag::err_expected_sequence_or_directive);
  3741. SkipUntil(tok::r_paren, StopBeforeMatch);
  3742. continue;
  3743. }
  3744. // We read an identifier. If the identifier is one of the ones we
  3745. // expected, we can recurse to parse the args.
  3746. ParseOpenMPAttributeArgs(Ident, OpenMPTokens);
  3747. // There may be a comma to signal that we expect another directive in the
  3748. // sequence.
  3749. } while (TryConsumeToken(tok::comma));
  3750. }
  3751. // Parse the closing paren for the argument list.
  3752. T.consumeClose();
  3753. }
  3754. static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
  3755. IdentifierInfo *ScopeName) {
  3756. switch (
  3757. ParsedAttr::getParsedKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
  3758. case ParsedAttr::AT_CarriesDependency:
  3759. case ParsedAttr::AT_Deprecated:
  3760. case ParsedAttr::AT_FallThrough:
  3761. case ParsedAttr::AT_CXX11NoReturn:
  3762. case ParsedAttr::AT_NoUniqueAddress:
  3763. case ParsedAttr::AT_Likely:
  3764. case ParsedAttr::AT_Unlikely:
  3765. return true;
  3766. case ParsedAttr::AT_WarnUnusedResult:
  3767. return !ScopeName && AttrName->getName().equals("nodiscard");
  3768. case ParsedAttr::AT_Unused:
  3769. return !ScopeName && AttrName->getName().equals("maybe_unused");
  3770. default:
  3771. return false;
  3772. }
  3773. }
  3774. /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
  3775. ///
  3776. /// [C++11] attribute-argument-clause:
  3777. /// '(' balanced-token-seq ')'
  3778. ///
  3779. /// [C++11] balanced-token-seq:
  3780. /// balanced-token
  3781. /// balanced-token-seq balanced-token
  3782. ///
  3783. /// [C++11] balanced-token:
  3784. /// '(' balanced-token-seq ')'
  3785. /// '[' balanced-token-seq ']'
  3786. /// '{' balanced-token-seq '}'
  3787. /// any token but '(', ')', '[', ']', '{', or '}'
  3788. bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
  3789. SourceLocation AttrNameLoc,
  3790. ParsedAttributes &Attrs,
  3791. SourceLocation *EndLoc,
  3792. IdentifierInfo *ScopeName,
  3793. SourceLocation ScopeLoc,
  3794. CachedTokens &OpenMPTokens) {
  3795. assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
  3796. SourceLocation LParenLoc = Tok.getLocation();
  3797. const LangOptions &LO = getLangOpts();
  3798. ParsedAttr::Syntax Syntax =
  3799. LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
  3800. // If the attribute isn't known, we will not attempt to parse any
  3801. // arguments.
  3802. if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
  3803. AttrName, getTargetInfo(), getLangOpts())) {
  3804. // Eat the left paren, then skip to the ending right paren.
  3805. ConsumeParen();
  3806. SkipUntil(tok::r_paren);
  3807. return false;
  3808. }
  3809. if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
  3810. // GNU-scoped attributes have some special cases to handle GNU-specific
  3811. // behaviors.
  3812. ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
  3813. ScopeLoc, Syntax, nullptr);
  3814. return true;
  3815. }
  3816. if (ScopeName && ScopeName->isStr("omp")) {
  3817. Diag(AttrNameLoc, getLangOpts().OpenMP >= 51
  3818. ? diag::warn_omp51_compat_attributes
  3819. : diag::ext_omp_attributes);
  3820. ParseOpenMPAttributeArgs(AttrName, OpenMPTokens);
  3821. // We claim that an attribute was parsed and added so that one is not
  3822. // created for us by the caller.
  3823. return true;
  3824. }
  3825. unsigned NumArgs;
  3826. // Some Clang-scoped attributes have some special parsing behavior.
  3827. if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
  3828. NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
  3829. ScopeName, ScopeLoc, Syntax);
  3830. else
  3831. NumArgs =
  3832. ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
  3833. ScopeName, ScopeLoc, Syntax);
  3834. if (!Attrs.empty() &&
  3835. IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
  3836. ParsedAttr &Attr = Attrs.back();
  3837. // If the attribute is a standard or built-in attribute and we are
  3838. // parsing an argument list, we need to determine whether this attribute
  3839. // was allowed to have an argument list (such as [[deprecated]]), and how
  3840. // many arguments were parsed (so we can diagnose on [[deprecated()]]).
  3841. if (Attr.getMaxArgs() && !NumArgs) {
  3842. // The attribute was allowed to have arguments, but none were provided
  3843. // even though the attribute parsed successfully. This is an error.
  3844. Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
  3845. Attr.setInvalid(true);
  3846. } else if (!Attr.getMaxArgs()) {
  3847. // The attribute parsed successfully, but was not allowed to have any
  3848. // arguments. It doesn't matter whether any were provided -- the
  3849. // presence of the argument list (even if empty) is diagnosed.
  3850. Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
  3851. << AttrName
  3852. << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
  3853. Attr.setInvalid(true);
  3854. }
  3855. }
  3856. return true;
  3857. }
  3858. /// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
  3859. ///
  3860. /// [C++11] attribute-specifier:
  3861. /// '[' '[' attribute-list ']' ']'
  3862. /// alignment-specifier
  3863. ///
  3864. /// [C++11] attribute-list:
  3865. /// attribute[opt]
  3866. /// attribute-list ',' attribute[opt]
  3867. /// attribute '...'
  3868. /// attribute-list ',' attribute '...'
  3869. ///
  3870. /// [C++11] attribute:
  3871. /// attribute-token attribute-argument-clause[opt]
  3872. ///
  3873. /// [C++11] attribute-token:
  3874. /// identifier
  3875. /// attribute-scoped-token
  3876. ///
  3877. /// [C++11] attribute-scoped-token:
  3878. /// attribute-namespace '::' identifier
  3879. ///
  3880. /// [C++11] attribute-namespace:
  3881. /// identifier
  3882. void Parser::ParseCXX11AttributeSpecifierInternal(ParsedAttributes &Attrs,
  3883. CachedTokens &OpenMPTokens,
  3884. SourceLocation *EndLoc) {
  3885. if (Tok.is(tok::kw_alignas)) {
  3886. Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
  3887. ParseAlignmentSpecifier(Attrs, EndLoc);
  3888. return;
  3889. }
  3890. assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
  3891. "Not a double square bracket attribute list");
  3892. SourceLocation OpenLoc = Tok.getLocation();
  3893. Diag(OpenLoc, diag::warn_cxx98_compat_attribute);
  3894. ConsumeBracket();
  3895. checkCompoundToken(OpenLoc, tok::l_square, CompoundToken::AttrBegin);
  3896. ConsumeBracket();
  3897. SourceLocation CommonScopeLoc;
  3898. IdentifierInfo *CommonScopeName = nullptr;
  3899. if (Tok.is(tok::kw_using)) {
  3900. Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
  3901. ? diag::warn_cxx14_compat_using_attribute_ns
  3902. : diag::ext_using_attribute_ns);
  3903. ConsumeToken();
  3904. CommonScopeName = TryParseCXX11AttributeIdentifier(
  3905. CommonScopeLoc, Sema::AttributeCompletion::Scope);
  3906. if (!CommonScopeName) {
  3907. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  3908. SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
  3909. }
  3910. if (!TryConsumeToken(tok::colon) && CommonScopeName)
  3911. Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
  3912. }
  3913. llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
  3914. bool AttrParsed = false;
  3915. while (!Tok.isOneOf(tok::r_square, tok::semi, tok::eof)) {
  3916. if (AttrParsed) {
  3917. // If we parsed an attribute, a comma is required before parsing any
  3918. // additional attributes.
  3919. if (ExpectAndConsume(tok::comma)) {
  3920. SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch);
  3921. continue;
  3922. }
  3923. AttrParsed = false;
  3924. }
  3925. // Eat all remaining superfluous commas before parsing the next attribute.
  3926. while (TryConsumeToken(tok::comma))
  3927. ;
  3928. SourceLocation ScopeLoc, AttrLoc;
  3929. IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
  3930. AttrName = TryParseCXX11AttributeIdentifier(
  3931. AttrLoc, Sema::AttributeCompletion::Attribute, CommonScopeName);
  3932. if (!AttrName)
  3933. // Break out to the "expected ']'" diagnostic.
  3934. break;
  3935. // scoped attribute
  3936. if (TryConsumeToken(tok::coloncolon)) {
  3937. ScopeName = AttrName;
  3938. ScopeLoc = AttrLoc;
  3939. AttrName = TryParseCXX11AttributeIdentifier(
  3940. AttrLoc, Sema::AttributeCompletion::Attribute, ScopeName);
  3941. if (!AttrName) {
  3942. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  3943. SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
  3944. continue;
  3945. }
  3946. }
  3947. if (CommonScopeName) {
  3948. if (ScopeName) {
  3949. Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
  3950. << SourceRange(CommonScopeLoc);
  3951. } else {
  3952. ScopeName = CommonScopeName;
  3953. ScopeLoc = CommonScopeLoc;
  3954. }
  3955. }
  3956. // Parse attribute arguments
  3957. if (Tok.is(tok::l_paren))
  3958. AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, Attrs, EndLoc,
  3959. ScopeName, ScopeLoc, OpenMPTokens);
  3960. if (!AttrParsed) {
  3961. Attrs.addNew(
  3962. AttrName,
  3963. SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
  3964. ScopeName, ScopeLoc, nullptr, 0,
  3965. getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
  3966. AttrParsed = true;
  3967. }
  3968. if (TryConsumeToken(tok::ellipsis))
  3969. Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
  3970. << AttrName;
  3971. }
  3972. // If we hit an error and recovered by parsing up to a semicolon, eat the
  3973. // semicolon and don't issue further diagnostics about missing brackets.
  3974. if (Tok.is(tok::semi)) {
  3975. ConsumeToken();
  3976. return;
  3977. }
  3978. SourceLocation CloseLoc = Tok.getLocation();
  3979. if (ExpectAndConsume(tok::r_square))
  3980. SkipUntil(tok::r_square);
  3981. else if (Tok.is(tok::r_square))
  3982. checkCompoundToken(CloseLoc, tok::r_square, CompoundToken::AttrEnd);
  3983. if (EndLoc)
  3984. *EndLoc = Tok.getLocation();
  3985. if (ExpectAndConsume(tok::r_square))
  3986. SkipUntil(tok::r_square);
  3987. }
  3988. /// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
  3989. ///
  3990. /// attribute-specifier-seq:
  3991. /// attribute-specifier-seq[opt] attribute-specifier
  3992. void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
  3993. SourceLocation *endLoc) {
  3994. assert(standardAttributesAllowed());
  3995. SourceLocation StartLoc = Tok.getLocation(), Loc;
  3996. if (!endLoc)
  3997. endLoc = &Loc;
  3998. do {
  3999. ParseCXX11AttributeSpecifier(attrs, endLoc);
  4000. } while (isCXX11AttributeSpecifier());
  4001. attrs.Range = SourceRange(StartLoc, *endLoc);
  4002. }
  4003. void Parser::DiagnoseAndSkipCXX11Attributes() {
  4004. // Start and end location of an attribute or an attribute list.
  4005. SourceLocation StartLoc = Tok.getLocation();
  4006. SourceLocation EndLoc = SkipCXX11Attributes();
  4007. if (EndLoc.isValid()) {
  4008. SourceRange Range(StartLoc, EndLoc);
  4009. Diag(StartLoc, diag::err_attributes_not_allowed)
  4010. << Range;
  4011. }
  4012. }
  4013. SourceLocation Parser::SkipCXX11Attributes() {
  4014. SourceLocation EndLoc;
  4015. if (!isCXX11AttributeSpecifier())
  4016. return EndLoc;
  4017. do {
  4018. if (Tok.is(tok::l_square)) {
  4019. BalancedDelimiterTracker T(*this, tok::l_square);
  4020. T.consumeOpen();
  4021. T.skipToEnd();
  4022. EndLoc = T.getCloseLocation();
  4023. } else {
  4024. assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
  4025. ConsumeToken();
  4026. BalancedDelimiterTracker T(*this, tok::l_paren);
  4027. if (!T.consumeOpen())
  4028. T.skipToEnd();
  4029. EndLoc = T.getCloseLocation();
  4030. }
  4031. } while (isCXX11AttributeSpecifier());
  4032. return EndLoc;
  4033. }
  4034. /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
  4035. void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
  4036. assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
  4037. IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
  4038. assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
  4039. SourceLocation UuidLoc = Tok.getLocation();
  4040. ConsumeToken();
  4041. // Ignore the left paren location for now.
  4042. BalancedDelimiterTracker T(*this, tok::l_paren);
  4043. if (T.consumeOpen()) {
  4044. Diag(Tok, diag::err_expected) << tok::l_paren;
  4045. return;
  4046. }
  4047. ArgsVector ArgExprs;
  4048. if (Tok.is(tok::string_literal)) {
  4049. // Easy case: uuid("...") -- quoted string.
  4050. ExprResult StringResult = ParseStringLiteralExpression();
  4051. if (StringResult.isInvalid())
  4052. return;
  4053. ArgExprs.push_back(StringResult.get());
  4054. } else {
  4055. // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
  4056. // quotes in the parens. Just append the spelling of all tokens encountered
  4057. // until the closing paren.
  4058. SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
  4059. StrBuffer += "\"";
  4060. // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
  4061. // tok::r_brace, tok::minus, tok::identifier (think C000) and
  4062. // tok::numeric_constant (0000) should be enough. But the spelling of the
  4063. // uuid argument is checked later anyways, so there's no harm in accepting
  4064. // almost anything here.
  4065. // cl is very strict about whitespace in this form and errors out if any
  4066. // is present, so check the space flags on the tokens.
  4067. SourceLocation StartLoc = Tok.getLocation();
  4068. while (Tok.isNot(tok::r_paren)) {
  4069. if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
  4070. Diag(Tok, diag::err_attribute_uuid_malformed_guid);
  4071. SkipUntil(tok::r_paren, StopAtSemi);
  4072. return;
  4073. }
  4074. SmallString<16> SpellingBuffer;
  4075. SpellingBuffer.resize(Tok.getLength() + 1);
  4076. bool Invalid = false;
  4077. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  4078. if (Invalid) {
  4079. SkipUntil(tok::r_paren, StopAtSemi);
  4080. return;
  4081. }
  4082. StrBuffer += TokSpelling;
  4083. ConsumeAnyToken();
  4084. }
  4085. StrBuffer += "\"";
  4086. if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
  4087. Diag(Tok, diag::err_attribute_uuid_malformed_guid);
  4088. ConsumeParen();
  4089. return;
  4090. }
  4091. // Pretend the user wrote the appropriate string literal here.
  4092. // ActOnStringLiteral() copies the string data into the literal, so it's
  4093. // ok that the Token points to StrBuffer.
  4094. Token Toks[1];
  4095. Toks[0].startToken();
  4096. Toks[0].setKind(tok::string_literal);
  4097. Toks[0].setLocation(StartLoc);
  4098. Toks[0].setLiteralData(StrBuffer.data());
  4099. Toks[0].setLength(StrBuffer.size());
  4100. StringLiteral *UuidString =
  4101. cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
  4102. ArgExprs.push_back(UuidString);
  4103. }
  4104. if (!T.consumeClose()) {
  4105. Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
  4106. SourceLocation(), ArgExprs.data(), ArgExprs.size(),
  4107. ParsedAttr::AS_Microsoft);
  4108. }
  4109. }
  4110. /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
  4111. ///
  4112. /// [MS] ms-attribute:
  4113. /// '[' token-seq ']'
  4114. ///
  4115. /// [MS] ms-attribute-seq:
  4116. /// ms-attribute[opt]
  4117. /// ms-attribute ms-attribute-seq
  4118. void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
  4119. SourceLocation *endLoc) {
  4120. assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
  4121. do {
  4122. // FIXME: If this is actually a C++11 attribute, parse it as one.
  4123. BalancedDelimiterTracker T(*this, tok::l_square);
  4124. T.consumeOpen();
  4125. // Skip most ms attributes except for a specific list.
  4126. while (true) {
  4127. SkipUntil(tok::r_square, tok::identifier,
  4128. StopAtSemi | StopBeforeMatch | StopAtCodeCompletion);
  4129. if (Tok.is(tok::code_completion)) {
  4130. cutOffParsing();
  4131. Actions.CodeCompleteAttribute(AttributeCommonInfo::AS_Microsoft,
  4132. Sema::AttributeCompletion::Attribute,
  4133. /*Scope=*/nullptr);
  4134. break;
  4135. }
  4136. if (Tok.isNot(tok::identifier)) // ']', but also eof
  4137. break;
  4138. if (Tok.getIdentifierInfo()->getName() == "uuid")
  4139. ParseMicrosoftUuidAttributeArgs(attrs);
  4140. else
  4141. ConsumeToken();
  4142. }
  4143. T.consumeClose();
  4144. if (endLoc)
  4145. *endLoc = T.getCloseLocation();
  4146. } while (Tok.is(tok::l_square));
  4147. }
  4148. void Parser::ParseMicrosoftIfExistsClassDeclaration(
  4149. DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
  4150. AccessSpecifier &CurAS) {
  4151. IfExistsCondition Result;
  4152. if (ParseMicrosoftIfExistsCondition(Result))
  4153. return;
  4154. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  4155. if (Braces.consumeOpen()) {
  4156. Diag(Tok, diag::err_expected) << tok::l_brace;
  4157. return;
  4158. }
  4159. switch (Result.Behavior) {
  4160. case IEB_Parse:
  4161. // Parse the declarations below.
  4162. break;
  4163. case IEB_Dependent:
  4164. Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
  4165. << Result.IsIfExists;
  4166. // Fall through to skip.
  4167. LLVM_FALLTHROUGH;
  4168. case IEB_Skip:
  4169. Braces.skipToEnd();
  4170. return;
  4171. }
  4172. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  4173. // __if_exists, __if_not_exists can nest.
  4174. if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
  4175. ParseMicrosoftIfExistsClassDeclaration(TagType,
  4176. AccessAttrs, CurAS);
  4177. continue;
  4178. }
  4179. // Check for extraneous top-level semicolon.
  4180. if (Tok.is(tok::semi)) {
  4181. ConsumeExtraSemi(InsideStruct, TagType);
  4182. continue;
  4183. }
  4184. AccessSpecifier AS = getAccessSpecifierIfPresent();
  4185. if (AS != AS_none) {
  4186. // Current token is a C++ access specifier.
  4187. CurAS = AS;
  4188. SourceLocation ASLoc = Tok.getLocation();
  4189. ConsumeToken();
  4190. if (Tok.is(tok::colon))
  4191. Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
  4192. ParsedAttributesView{});
  4193. else
  4194. Diag(Tok, diag::err_expected) << tok::colon;
  4195. ConsumeToken();
  4196. continue;
  4197. }
  4198. // Parse all the comma separated declarators.
  4199. ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
  4200. }
  4201. Braces.consumeClose();
  4202. }