ParseDeclCXX.cpp 161 KB

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