ParseDeclCXX.cpp 160 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371
  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_static_assert);
  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. /*NonTrivialTypeSourceInfo=*/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. // As shown above, type qualifiers and storage class specifiers absolutely
  1146. // can occur after class specifiers according to the grammar. However,
  1147. // almost no one actually writes code like this. If we see one of these,
  1148. // it is much more likely that someone missed a semi colon and the
  1149. // type/storage class specifier we're seeing is part of the *next*
  1150. // intended declaration, as in:
  1151. //
  1152. // struct foo { ... }
  1153. // typedef int X;
  1154. //
  1155. // We'd really like to emit a missing semicolon error instead of emitting
  1156. // an error on the 'int' saying that you can't have two type specifiers in
  1157. // the same declaration of X. Because of this, we look ahead past this
  1158. // token to see if it's a type specifier. If so, we know the code is
  1159. // otherwise invalid, so we can produce the expected semi error.
  1160. if (!isKnownToBeTypeSpecifier(NextToken()))
  1161. return true;
  1162. break;
  1163. case tok::r_brace: // struct bar { struct foo {...} }
  1164. // Missing ';' at end of struct is accepted as an extension in C mode.
  1165. if (!getLangOpts().CPlusPlus)
  1166. return true;
  1167. break;
  1168. case tok::greater:
  1169. // template<class T = class X>
  1170. return getLangOpts().CPlusPlus;
  1171. }
  1172. return false;
  1173. }
  1174. /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or
  1175. /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which
  1176. /// until we reach the start of a definition or see a token that
  1177. /// cannot start a definition.
  1178. ///
  1179. /// class-specifier: [C++ class]
  1180. /// class-head '{' member-specification[opt] '}'
  1181. /// class-head '{' member-specification[opt] '}' attributes[opt]
  1182. /// class-head:
  1183. /// class-key identifier[opt] base-clause[opt]
  1184. /// class-key nested-name-specifier identifier base-clause[opt]
  1185. /// class-key nested-name-specifier[opt] simple-template-id
  1186. /// base-clause[opt]
  1187. /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt]
  1188. /// [GNU] class-key attributes[opt] nested-name-specifier
  1189. /// identifier base-clause[opt]
  1190. /// [GNU] class-key attributes[opt] nested-name-specifier[opt]
  1191. /// simple-template-id base-clause[opt]
  1192. /// class-key:
  1193. /// 'class'
  1194. /// 'struct'
  1195. /// 'union'
  1196. ///
  1197. /// elaborated-type-specifier: [C++ dcl.type.elab]
  1198. /// class-key ::[opt] nested-name-specifier[opt] identifier
  1199. /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt]
  1200. /// simple-template-id
  1201. ///
  1202. /// Note that the C++ class-specifier and elaborated-type-specifier,
  1203. /// together, subsume the C99 struct-or-union-specifier:
  1204. ///
  1205. /// struct-or-union-specifier: [C99 6.7.2.1]
  1206. /// struct-or-union identifier[opt] '{' struct-contents '}'
  1207. /// struct-or-union identifier
  1208. /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents
  1209. /// '}' attributes[opt]
  1210. /// [GNU] struct-or-union attributes[opt] identifier
  1211. /// struct-or-union:
  1212. /// 'struct'
  1213. /// 'union'
  1214. void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
  1215. SourceLocation StartLoc, DeclSpec &DS,
  1216. const ParsedTemplateInfo &TemplateInfo,
  1217. AccessSpecifier AS,
  1218. bool EnteringContext, DeclSpecContext DSC,
  1219. ParsedAttributesWithRange &Attributes) {
  1220. DeclSpec::TST TagType;
  1221. if (TagTokKind == tok::kw_struct)
  1222. TagType = DeclSpec::TST_struct;
  1223. else if (TagTokKind == tok::kw___interface)
  1224. TagType = DeclSpec::TST_interface;
  1225. else if (TagTokKind == tok::kw_class)
  1226. TagType = DeclSpec::TST_class;
  1227. else {
  1228. assert(TagTokKind == tok::kw_union && "Not a class specifier");
  1229. TagType = DeclSpec::TST_union;
  1230. }
  1231. if (Tok.is(tok::code_completion)) {
  1232. // Code completion for a struct, class, or union name.
  1233. Actions.CodeCompleteTag(getCurScope(), TagType);
  1234. return cutOffParsing();
  1235. }
  1236. // C++03 [temp.explicit] 14.7.2/8:
  1237. // The usual access checking rules do not apply to names used to specify
  1238. // explicit instantiations.
  1239. //
  1240. // As an extension we do not perform access checking on the names used to
  1241. // specify explicit specializations either. This is important to allow
  1242. // specializing traits classes for private types.
  1243. //
  1244. // Note that we don't suppress if this turns out to be an elaborated
  1245. // type specifier.
  1246. bool shouldDelayDiagsInTag =
  1247. (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation ||
  1248. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization);
  1249. SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag);
  1250. ParsedAttributesWithRange attrs(AttrFactory);
  1251. // If attributes exist after tag, parse them.
  1252. MaybeParseGNUAttributes(attrs);
  1253. MaybeParseMicrosoftDeclSpecs(attrs);
  1254. // Parse inheritance specifiers.
  1255. if (Tok.isOneOf(tok::kw___single_inheritance,
  1256. tok::kw___multiple_inheritance,
  1257. tok::kw___virtual_inheritance))
  1258. ParseMicrosoftInheritanceClassAttributes(attrs);
  1259. // If C++0x attributes exist here, parse them.
  1260. // FIXME: Are we consistent with the ordering of parsing of different
  1261. // styles of attributes?
  1262. MaybeParseCXX11Attributes(attrs);
  1263. // Source location used by FIXIT to insert misplaced
  1264. // C++11 attributes
  1265. SourceLocation AttrFixitLoc = Tok.getLocation();
  1266. if (TagType == DeclSpec::TST_struct &&
  1267. Tok.isNot(tok::identifier) &&
  1268. !Tok.isAnnotation() &&
  1269. Tok.getIdentifierInfo() &&
  1270. Tok.isOneOf(tok::kw___is_abstract,
  1271. tok::kw___is_aggregate,
  1272. tok::kw___is_arithmetic,
  1273. tok::kw___is_array,
  1274. tok::kw___is_assignable,
  1275. tok::kw___is_base_of,
  1276. tok::kw___is_class,
  1277. tok::kw___is_complete_type,
  1278. tok::kw___is_compound,
  1279. tok::kw___is_const,
  1280. tok::kw___is_constructible,
  1281. tok::kw___is_convertible,
  1282. tok::kw___is_convertible_to,
  1283. tok::kw___is_destructible,
  1284. tok::kw___is_empty,
  1285. tok::kw___is_enum,
  1286. tok::kw___is_floating_point,
  1287. tok::kw___is_final,
  1288. tok::kw___is_function,
  1289. tok::kw___is_fundamental,
  1290. tok::kw___is_integral,
  1291. tok::kw___is_interface_class,
  1292. tok::kw___is_literal,
  1293. tok::kw___is_lvalue_expr,
  1294. tok::kw___is_lvalue_reference,
  1295. tok::kw___is_member_function_pointer,
  1296. tok::kw___is_member_object_pointer,
  1297. tok::kw___is_member_pointer,
  1298. tok::kw___is_nothrow_assignable,
  1299. tok::kw___is_nothrow_constructible,
  1300. tok::kw___is_nothrow_destructible,
  1301. tok::kw___is_object,
  1302. tok::kw___is_pod,
  1303. tok::kw___is_pointer,
  1304. tok::kw___is_polymorphic,
  1305. tok::kw___is_reference,
  1306. tok::kw___is_rvalue_expr,
  1307. tok::kw___is_rvalue_reference,
  1308. tok::kw___is_same,
  1309. tok::kw___is_scalar,
  1310. tok::kw___is_sealed,
  1311. tok::kw___is_signed,
  1312. tok::kw___is_standard_layout,
  1313. tok::kw___is_trivial,
  1314. tok::kw___is_trivially_assignable,
  1315. tok::kw___is_trivially_constructible,
  1316. tok::kw___is_trivially_copyable,
  1317. tok::kw___is_union,
  1318. tok::kw___is_unsigned,
  1319. tok::kw___is_void,
  1320. tok::kw___is_volatile))
  1321. // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the
  1322. // name of struct templates, but some are keywords in GCC >= 4.3
  1323. // and Clang. Therefore, when we see the token sequence "struct
  1324. // X", make X into a normal identifier rather than a keyword, to
  1325. // allow libstdc++ 4.2 and libc++ to work properly.
  1326. TryKeywordIdentFallback(true);
  1327. struct PreserveAtomicIdentifierInfoRAII {
  1328. PreserveAtomicIdentifierInfoRAII(Token &Tok, bool Enabled)
  1329. : AtomicII(nullptr) {
  1330. if (!Enabled)
  1331. return;
  1332. assert(Tok.is(tok::kw__Atomic));
  1333. AtomicII = Tok.getIdentifierInfo();
  1334. AtomicII->revertTokenIDToIdentifier();
  1335. Tok.setKind(tok::identifier);
  1336. }
  1337. ~PreserveAtomicIdentifierInfoRAII() {
  1338. if (!AtomicII)
  1339. return;
  1340. AtomicII->revertIdentifierToTokenID(tok::kw__Atomic);
  1341. }
  1342. IdentifierInfo *AtomicII;
  1343. };
  1344. // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
  1345. // implementation for VS2013 uses _Atomic as an identifier for one of the
  1346. // classes in <atomic>. When we are parsing 'struct _Atomic', don't consider
  1347. // '_Atomic' to be a keyword. We are careful to undo this so that clang can
  1348. // use '_Atomic' in its own header files.
  1349. bool ShouldChangeAtomicToIdentifier = getLangOpts().MSVCCompat &&
  1350. Tok.is(tok::kw__Atomic) &&
  1351. TagType == DeclSpec::TST_struct;
  1352. PreserveAtomicIdentifierInfoRAII AtomicTokenGuard(
  1353. Tok, ShouldChangeAtomicToIdentifier);
  1354. // Parse the (optional) nested-name-specifier.
  1355. CXXScopeSpec &SS = DS.getTypeSpecScope();
  1356. if (getLangOpts().CPlusPlus) {
  1357. // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it
  1358. // is a base-specifier-list.
  1359. ColonProtectionRAIIObject X(*this);
  1360. CXXScopeSpec Spec;
  1361. bool HasValidSpec = true;
  1362. if (ParseOptionalCXXScopeSpecifier(Spec, nullptr, EnteringContext)) {
  1363. DS.SetTypeSpecError();
  1364. HasValidSpec = false;
  1365. }
  1366. if (Spec.isSet())
  1367. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) {
  1368. Diag(Tok, diag::err_expected) << tok::identifier;
  1369. HasValidSpec = false;
  1370. }
  1371. if (HasValidSpec)
  1372. SS = Spec;
  1373. }
  1374. TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams;
  1375. auto RecoverFromUndeclaredTemplateName = [&](IdentifierInfo *Name,
  1376. SourceLocation NameLoc,
  1377. SourceRange TemplateArgRange,
  1378. bool KnownUndeclared) {
  1379. Diag(NameLoc, diag::err_explicit_spec_non_template)
  1380. << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
  1381. << TagTokKind << Name << TemplateArgRange << KnownUndeclared;
  1382. // Strip off the last template parameter list if it was empty, since
  1383. // we've removed its template argument list.
  1384. if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) {
  1385. if (TemplateParams->size() > 1) {
  1386. TemplateParams->pop_back();
  1387. } else {
  1388. TemplateParams = nullptr;
  1389. const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
  1390. ParsedTemplateInfo::NonTemplate;
  1391. }
  1392. } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1393. // Pretend this is just a forward declaration.
  1394. TemplateParams = nullptr;
  1395. const_cast<ParsedTemplateInfo &>(TemplateInfo).Kind =
  1396. ParsedTemplateInfo::NonTemplate;
  1397. const_cast<ParsedTemplateInfo &>(TemplateInfo).TemplateLoc =
  1398. SourceLocation();
  1399. const_cast<ParsedTemplateInfo &>(TemplateInfo).ExternLoc =
  1400. SourceLocation();
  1401. }
  1402. };
  1403. // Parse the (optional) class name or simple-template-id.
  1404. IdentifierInfo *Name = nullptr;
  1405. SourceLocation NameLoc;
  1406. TemplateIdAnnotation *TemplateId = nullptr;
  1407. if (Tok.is(tok::identifier)) {
  1408. Name = Tok.getIdentifierInfo();
  1409. NameLoc = ConsumeToken();
  1410. if (Tok.is(tok::less) && getLangOpts().CPlusPlus) {
  1411. // The name was supposed to refer to a template, but didn't.
  1412. // Eat the template argument list and try to continue parsing this as
  1413. // a class (or template thereof).
  1414. TemplateArgList TemplateArgs;
  1415. SourceLocation LAngleLoc, RAngleLoc;
  1416. if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
  1417. RAngleLoc)) {
  1418. // We couldn't parse the template argument list at all, so don't
  1419. // try to give any location information for the list.
  1420. LAngleLoc = RAngleLoc = SourceLocation();
  1421. }
  1422. RecoverFromUndeclaredTemplateName(
  1423. Name, NameLoc, SourceRange(LAngleLoc, RAngleLoc), false);
  1424. }
  1425. } else if (Tok.is(tok::annot_template_id)) {
  1426. TemplateId = takeTemplateIdAnnotation(Tok);
  1427. NameLoc = ConsumeAnnotationToken();
  1428. if (TemplateId->Kind == TNK_Undeclared_template) {
  1429. // Try to resolve the template name to a type template.
  1430. Actions.ActOnUndeclaredTypeTemplateName(getCurScope(), TemplateId->Template,
  1431. TemplateId->Kind, NameLoc, Name);
  1432. if (TemplateId->Kind == TNK_Undeclared_template) {
  1433. RecoverFromUndeclaredTemplateName(
  1434. Name, NameLoc,
  1435. SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc), true);
  1436. TemplateId = nullptr;
  1437. }
  1438. }
  1439. if (TemplateId && TemplateId->Kind != TNK_Type_template &&
  1440. TemplateId->Kind != TNK_Dependent_template_name) {
  1441. // The template-name in the simple-template-id refers to
  1442. // something other than a class template. Give an appropriate
  1443. // error message and skip to the ';'.
  1444. SourceRange Range(NameLoc);
  1445. if (SS.isNotEmpty())
  1446. Range.setBegin(SS.getBeginLoc());
  1447. // FIXME: Name may be null here.
  1448. Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template)
  1449. << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range;
  1450. DS.SetTypeSpecError();
  1451. SkipUntil(tok::semi, StopBeforeMatch);
  1452. return;
  1453. }
  1454. }
  1455. // There are four options here.
  1456. // - If we are in a trailing return type, this is always just a reference,
  1457. // and we must not try to parse a definition. For instance,
  1458. // [] () -> struct S { };
  1459. // does not define a type.
  1460. // - If we have 'struct foo {...', 'struct foo :...',
  1461. // 'struct foo final :' or 'struct foo final {', then this is a definition.
  1462. // - If we have 'struct foo;', then this is either a forward declaration
  1463. // or a friend declaration, which have to be treated differently.
  1464. // - Otherwise we have something like 'struct foo xyz', a reference.
  1465. //
  1466. // We also detect these erroneous cases to provide better diagnostic for
  1467. // C++11 attributes parsing.
  1468. // - attributes follow class name:
  1469. // struct foo [[]] {};
  1470. // - attributes appear before or after 'final':
  1471. // struct foo [[]] final [[]] {};
  1472. //
  1473. // However, in type-specifier-seq's, things look like declarations but are
  1474. // just references, e.g.
  1475. // new struct s;
  1476. // or
  1477. // &T::operator struct s;
  1478. // For these, DSC is DeclSpecContext::DSC_type_specifier or
  1479. // DeclSpecContext::DSC_alias_declaration.
  1480. // If there are attributes after class name, parse them.
  1481. MaybeParseCXX11Attributes(Attributes);
  1482. const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy();
  1483. Sema::TagUseKind TUK;
  1484. if (DSC == DeclSpecContext::DSC_trailing)
  1485. TUK = Sema::TUK_Reference;
  1486. else if (Tok.is(tok::l_brace) ||
  1487. (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
  1488. (isCXX11FinalKeyword() &&
  1489. (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) {
  1490. if (DS.isFriendSpecified()) {
  1491. // C++ [class.friend]p2:
  1492. // A class shall not be defined in a friend declaration.
  1493. Diag(Tok.getLocation(), diag::err_friend_decl_defines_type)
  1494. << SourceRange(DS.getFriendSpecLoc());
  1495. // Skip everything up to the semicolon, so that this looks like a proper
  1496. // friend class (or template thereof) declaration.
  1497. SkipUntil(tok::semi, StopBeforeMatch);
  1498. TUK = Sema::TUK_Friend;
  1499. } else {
  1500. // Okay, this is a class definition.
  1501. TUK = Sema::TUK_Definition;
  1502. }
  1503. } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) ||
  1504. NextToken().is(tok::kw_alignas))) {
  1505. // We can't tell if this is a definition or reference
  1506. // until we skipped the 'final' and C++11 attribute specifiers.
  1507. TentativeParsingAction PA(*this);
  1508. // Skip the 'final' keyword.
  1509. ConsumeToken();
  1510. // Skip C++11 attribute specifiers.
  1511. while (true) {
  1512. if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
  1513. ConsumeBracket();
  1514. if (!SkipUntil(tok::r_square, StopAtSemi))
  1515. break;
  1516. } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) {
  1517. ConsumeToken();
  1518. ConsumeParen();
  1519. if (!SkipUntil(tok::r_paren, StopAtSemi))
  1520. break;
  1521. } else {
  1522. break;
  1523. }
  1524. }
  1525. if (Tok.isOneOf(tok::l_brace, tok::colon))
  1526. TUK = Sema::TUK_Definition;
  1527. else
  1528. TUK = Sema::TUK_Reference;
  1529. PA.Revert();
  1530. } else if (!isTypeSpecifier(DSC) &&
  1531. (Tok.is(tok::semi) ||
  1532. (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) {
  1533. TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration;
  1534. if (Tok.isNot(tok::semi)) {
  1535. const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
  1536. // A semicolon was missing after this declaration. Diagnose and recover.
  1537. ExpectAndConsume(tok::semi, diag::err_expected_after,
  1538. DeclSpec::getSpecifierName(TagType, PPol));
  1539. PP.EnterToken(Tok, /*IsReinject*/true);
  1540. Tok.setKind(tok::semi);
  1541. }
  1542. } else
  1543. TUK = Sema::TUK_Reference;
  1544. // Forbid misplaced attributes. In cases of a reference, we pass attributes
  1545. // to caller to handle.
  1546. if (TUK != Sema::TUK_Reference) {
  1547. // If this is not a reference, then the only possible
  1548. // valid place for C++11 attributes to appear here
  1549. // is between class-key and class-name. If there are
  1550. // any attributes after class-name, we try a fixit to move
  1551. // them to the right place.
  1552. SourceRange AttrRange = Attributes.Range;
  1553. if (AttrRange.isValid()) {
  1554. Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed)
  1555. << AttrRange
  1556. << FixItHint::CreateInsertionFromRange(AttrFixitLoc,
  1557. CharSourceRange(AttrRange, true))
  1558. << FixItHint::CreateRemoval(AttrRange);
  1559. // Recover by adding misplaced attributes to the attribute list
  1560. // of the class so they can be applied on the class later.
  1561. attrs.takeAllFrom(Attributes);
  1562. }
  1563. }
  1564. // If this is an elaborated type specifier, and we delayed
  1565. // diagnostics before, just merge them into the current pool.
  1566. if (shouldDelayDiagsInTag) {
  1567. diagsFromTag.done();
  1568. if (TUK == Sema::TUK_Reference)
  1569. diagsFromTag.redelay();
  1570. }
  1571. if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error ||
  1572. TUK != Sema::TUK_Definition)) {
  1573. if (DS.getTypeSpecType() != DeclSpec::TST_error) {
  1574. // We have a declaration or reference to an anonymous class.
  1575. Diag(StartLoc, diag::err_anon_type_definition)
  1576. << DeclSpec::getSpecifierName(TagType, Policy);
  1577. }
  1578. // If we are parsing a definition and stop at a base-clause, continue on
  1579. // until the semicolon. Continuing from the comma will just trick us into
  1580. // thinking we are seeing a variable declaration.
  1581. if (TUK == Sema::TUK_Definition && Tok.is(tok::colon))
  1582. SkipUntil(tok::semi, StopBeforeMatch);
  1583. else
  1584. SkipUntil(tok::comma, StopAtSemi);
  1585. return;
  1586. }
  1587. // Create the tag portion of the class or class template.
  1588. DeclResult TagOrTempResult = true; // invalid
  1589. TypeResult TypeResult = true; // invalid
  1590. bool Owned = false;
  1591. Sema::SkipBodyInfo SkipBody;
  1592. if (TemplateId) {
  1593. // Explicit specialization, class template partial specialization,
  1594. // or explicit instantiation.
  1595. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  1596. TemplateId->NumArgs);
  1597. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1598. TUK == Sema::TUK_Declaration) {
  1599. // This is an explicit instantiation of a class template.
  1600. ProhibitAttributes(attrs);
  1601. TagOrTempResult = Actions.ActOnExplicitInstantiation(
  1602. getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
  1603. TagType, StartLoc, SS, TemplateId->Template,
  1604. TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
  1605. TemplateId->RAngleLoc, attrs);
  1606. // Friend template-ids are treated as references unless
  1607. // they have template headers, in which case they're ill-formed
  1608. // (FIXME: "template <class T> friend class A<T>::B<int>;").
  1609. // We diagnose this error in ActOnClassTemplateSpecialization.
  1610. } else if (TUK == Sema::TUK_Reference ||
  1611. (TUK == Sema::TUK_Friend &&
  1612. TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) {
  1613. ProhibitAttributes(attrs);
  1614. TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc,
  1615. TemplateId->SS,
  1616. TemplateId->TemplateKWLoc,
  1617. TemplateId->Template,
  1618. TemplateId->TemplateNameLoc,
  1619. TemplateId->LAngleLoc,
  1620. TemplateArgsPtr,
  1621. TemplateId->RAngleLoc);
  1622. } else {
  1623. // This is an explicit specialization or a class template
  1624. // partial specialization.
  1625. TemplateParameterLists FakedParamLists;
  1626. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1627. // This looks like an explicit instantiation, because we have
  1628. // something like
  1629. //
  1630. // template class Foo<X>
  1631. //
  1632. // but it actually has a definition. Most likely, this was
  1633. // meant to be an explicit specialization, but the user forgot
  1634. // the '<>' after 'template'.
  1635. // It this is friend declaration however, since it cannot have a
  1636. // template header, it is most likely that the user meant to
  1637. // remove the 'template' keyword.
  1638. assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) &&
  1639. "Expected a definition here");
  1640. if (TUK == Sema::TUK_Friend) {
  1641. Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation);
  1642. TemplateParams = nullptr;
  1643. } else {
  1644. SourceLocation LAngleLoc =
  1645. PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
  1646. Diag(TemplateId->TemplateNameLoc,
  1647. diag::err_explicit_instantiation_with_definition)
  1648. << SourceRange(TemplateInfo.TemplateLoc)
  1649. << FixItHint::CreateInsertion(LAngleLoc, "<>");
  1650. // Create a fake template parameter list that contains only
  1651. // "template<>", so that we treat this construct as a class
  1652. // template specialization.
  1653. FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
  1654. 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
  1655. LAngleLoc, nullptr));
  1656. TemplateParams = &FakedParamLists;
  1657. }
  1658. }
  1659. // Build the class template specialization.
  1660. TagOrTempResult = Actions.ActOnClassTemplateSpecialization(
  1661. getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(),
  1662. *TemplateId, attrs,
  1663. MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0]
  1664. : nullptr,
  1665. TemplateParams ? TemplateParams->size() : 0),
  1666. &SkipBody);
  1667. }
  1668. } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation &&
  1669. TUK == Sema::TUK_Declaration) {
  1670. // Explicit instantiation of a member of a class template
  1671. // specialization, e.g.,
  1672. //
  1673. // template struct Outer<int>::Inner;
  1674. //
  1675. ProhibitAttributes(attrs);
  1676. TagOrTempResult = Actions.ActOnExplicitInstantiation(
  1677. getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc,
  1678. TagType, StartLoc, SS, Name, NameLoc, attrs);
  1679. } else if (TUK == Sema::TUK_Friend &&
  1680. TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
  1681. ProhibitAttributes(attrs);
  1682. TagOrTempResult = Actions.ActOnTemplatedFriendTag(
  1683. getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name,
  1684. NameLoc, attrs,
  1685. MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr,
  1686. TemplateParams ? TemplateParams->size() : 0));
  1687. } else {
  1688. if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition)
  1689. ProhibitAttributes(attrs);
  1690. if (TUK == Sema::TUK_Definition &&
  1691. TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
  1692. // If the declarator-id is not a template-id, issue a diagnostic and
  1693. // recover by ignoring the 'template' keyword.
  1694. Diag(Tok, diag::err_template_defn_explicit_instantiation)
  1695. << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc);
  1696. TemplateParams = nullptr;
  1697. }
  1698. bool IsDependent = false;
  1699. // Don't pass down template parameter lists if this is just a tag
  1700. // reference. For example, we don't need the template parameters here:
  1701. // template <class T> class A *makeA(T t);
  1702. MultiTemplateParamsArg TParams;
  1703. if (TUK != Sema::TUK_Reference && TemplateParams)
  1704. TParams =
  1705. MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
  1706. stripTypeAttributesOffDeclSpec(attrs, DS, TUK);
  1707. // Declaration or definition of a class type
  1708. TagOrTempResult = Actions.ActOnTag(
  1709. getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs, AS,
  1710. DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent,
  1711. SourceLocation(), false, clang::TypeResult(),
  1712. DSC == DeclSpecContext::DSC_type_specifier,
  1713. DSC == DeclSpecContext::DSC_template_param ||
  1714. DSC == DeclSpecContext::DSC_template_type_arg,
  1715. &SkipBody);
  1716. // If ActOnTag said the type was dependent, try again with the
  1717. // less common call.
  1718. if (IsDependent) {
  1719. assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend);
  1720. TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK,
  1721. SS, Name, StartLoc, NameLoc);
  1722. }
  1723. }
  1724. // If there is a body, parse it and inform the actions module.
  1725. if (TUK == Sema::TUK_Definition) {
  1726. assert(Tok.is(tok::l_brace) ||
  1727. (getLangOpts().CPlusPlus && Tok.is(tok::colon)) ||
  1728. isCXX11FinalKeyword());
  1729. if (SkipBody.ShouldSkip)
  1730. SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType,
  1731. TagOrTempResult.get());
  1732. else if (getLangOpts().CPlusPlus)
  1733. ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType,
  1734. TagOrTempResult.get());
  1735. else {
  1736. Decl *D =
  1737. SkipBody.CheckSameAsPrevious ? SkipBody.New : TagOrTempResult.get();
  1738. // Parse the definition body.
  1739. ParseStructUnionBody(StartLoc, TagType, D);
  1740. if (SkipBody.CheckSameAsPrevious &&
  1741. !Actions.ActOnDuplicateDefinition(DS, TagOrTempResult.get(),
  1742. SkipBody)) {
  1743. DS.SetTypeSpecError();
  1744. return;
  1745. }
  1746. }
  1747. }
  1748. if (!TagOrTempResult.isInvalid())
  1749. // Delayed processing of attributes.
  1750. Actions.ProcessDeclAttributeDelayed(TagOrTempResult.get(), attrs);
  1751. const char *PrevSpec = nullptr;
  1752. unsigned DiagID;
  1753. bool Result;
  1754. if (!TypeResult.isInvalid()) {
  1755. Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc,
  1756. NameLoc.isValid() ? NameLoc : StartLoc,
  1757. PrevSpec, DiagID, TypeResult.get(), Policy);
  1758. } else if (!TagOrTempResult.isInvalid()) {
  1759. Result = DS.SetTypeSpecType(TagType, StartLoc,
  1760. NameLoc.isValid() ? NameLoc : StartLoc,
  1761. PrevSpec, DiagID, TagOrTempResult.get(), Owned,
  1762. Policy);
  1763. } else {
  1764. DS.SetTypeSpecError();
  1765. return;
  1766. }
  1767. if (Result)
  1768. Diag(StartLoc, DiagID) << PrevSpec;
  1769. // At this point, we've successfully parsed a class-specifier in 'definition'
  1770. // form (e.g. "struct foo { int x; }". While we could just return here, we're
  1771. // going to look at what comes after it to improve error recovery. If an
  1772. // impossible token occurs next, we assume that the programmer forgot a ; at
  1773. // the end of the declaration and recover that way.
  1774. //
  1775. // Also enforce C++ [temp]p3:
  1776. // In a template-declaration which defines a class, no declarator
  1777. // is permitted.
  1778. //
  1779. // After a type-specifier, we don't expect a semicolon. This only happens in
  1780. // C, since definitions are not permitted in this context in C++.
  1781. if (TUK == Sema::TUK_Definition &&
  1782. (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
  1783. (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) {
  1784. if (Tok.isNot(tok::semi)) {
  1785. const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
  1786. ExpectAndConsume(tok::semi, diag::err_expected_after,
  1787. DeclSpec::getSpecifierName(TagType, PPol));
  1788. // Push this token back into the preprocessor and change our current token
  1789. // to ';' so that the rest of the code recovers as though there were an
  1790. // ';' after the definition.
  1791. PP.EnterToken(Tok, /*IsReinject=*/true);
  1792. Tok.setKind(tok::semi);
  1793. }
  1794. }
  1795. }
  1796. /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived].
  1797. ///
  1798. /// base-clause : [C++ class.derived]
  1799. /// ':' base-specifier-list
  1800. /// base-specifier-list:
  1801. /// base-specifier '...'[opt]
  1802. /// base-specifier-list ',' base-specifier '...'[opt]
  1803. void Parser::ParseBaseClause(Decl *ClassDecl) {
  1804. assert(Tok.is(tok::colon) && "Not a base clause");
  1805. ConsumeToken();
  1806. // Build up an array of parsed base specifiers.
  1807. SmallVector<CXXBaseSpecifier *, 8> BaseInfo;
  1808. while (true) {
  1809. // Parse a base-specifier.
  1810. BaseResult Result = ParseBaseSpecifier(ClassDecl);
  1811. if (Result.isInvalid()) {
  1812. // Skip the rest of this base specifier, up until the comma or
  1813. // opening brace.
  1814. SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch);
  1815. } else {
  1816. // Add this to our array of base specifiers.
  1817. BaseInfo.push_back(Result.get());
  1818. }
  1819. // If the next token is a comma, consume it and keep reading
  1820. // base-specifiers.
  1821. if (!TryConsumeToken(tok::comma))
  1822. break;
  1823. }
  1824. // Attach the base specifiers
  1825. Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo);
  1826. }
  1827. /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is
  1828. /// one entry in the base class list of a class specifier, for example:
  1829. /// class foo : public bar, virtual private baz {
  1830. /// 'public bar' and 'virtual private baz' are each base-specifiers.
  1831. ///
  1832. /// base-specifier: [C++ class.derived]
  1833. /// attribute-specifier-seq[opt] base-type-specifier
  1834. /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt]
  1835. /// base-type-specifier
  1836. /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt]
  1837. /// base-type-specifier
  1838. BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) {
  1839. bool IsVirtual = false;
  1840. SourceLocation StartLoc = Tok.getLocation();
  1841. ParsedAttributesWithRange Attributes(AttrFactory);
  1842. MaybeParseCXX11Attributes(Attributes);
  1843. // Parse the 'virtual' keyword.
  1844. if (TryConsumeToken(tok::kw_virtual))
  1845. IsVirtual = true;
  1846. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1847. // Parse an (optional) access specifier.
  1848. AccessSpecifier Access = getAccessSpecifierIfPresent();
  1849. if (Access != AS_none)
  1850. ConsumeToken();
  1851. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1852. // Parse the 'virtual' keyword (again!), in case it came after the
  1853. // access specifier.
  1854. if (Tok.is(tok::kw_virtual)) {
  1855. SourceLocation VirtualLoc = ConsumeToken();
  1856. if (IsVirtual) {
  1857. // Complain about duplicate 'virtual'
  1858. Diag(VirtualLoc, diag::err_dup_virtual)
  1859. << FixItHint::CreateRemoval(VirtualLoc);
  1860. }
  1861. IsVirtual = true;
  1862. }
  1863. CheckMisplacedCXX11Attribute(Attributes, StartLoc);
  1864. // Parse the class-name.
  1865. // HACK: MSVC doesn't consider _Atomic to be a keyword and its STL
  1866. // implementation for VS2013 uses _Atomic as an identifier for one of the
  1867. // classes in <atomic>. Treat '_Atomic' to be an identifier when we are
  1868. // parsing the class-name for a base specifier.
  1869. if (getLangOpts().MSVCCompat && Tok.is(tok::kw__Atomic) &&
  1870. NextToken().is(tok::less))
  1871. Tok.setKind(tok::identifier);
  1872. SourceLocation EndLocation;
  1873. SourceLocation BaseLoc;
  1874. TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation);
  1875. if (BaseType.isInvalid())
  1876. return true;
  1877. // Parse the optional ellipsis (for a pack expansion). The ellipsis is
  1878. // actually part of the base-specifier-list grammar productions, but we
  1879. // parse it here for convenience.
  1880. SourceLocation EllipsisLoc;
  1881. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  1882. // Find the complete source range for the base-specifier.
  1883. SourceRange Range(StartLoc, EndLocation);
  1884. // Notify semantic analysis that we have parsed a complete
  1885. // base-specifier.
  1886. return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual,
  1887. Access, BaseType.get(), BaseLoc,
  1888. EllipsisLoc);
  1889. }
  1890. /// getAccessSpecifierIfPresent - Determine whether the next token is
  1891. /// a C++ access-specifier.
  1892. ///
  1893. /// access-specifier: [C++ class.derived]
  1894. /// 'private'
  1895. /// 'protected'
  1896. /// 'public'
  1897. AccessSpecifier Parser::getAccessSpecifierIfPresent() const {
  1898. switch (Tok.getKind()) {
  1899. default: return AS_none;
  1900. case tok::kw_private: return AS_private;
  1901. case tok::kw_protected: return AS_protected;
  1902. case tok::kw_public: return AS_public;
  1903. }
  1904. }
  1905. /// If the given declarator has any parts for which parsing has to be
  1906. /// delayed, e.g., default arguments or an exception-specification, create a
  1907. /// late-parsed method declaration record to handle the parsing at the end of
  1908. /// the class definition.
  1909. void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
  1910. Decl *ThisDecl) {
  1911. DeclaratorChunk::FunctionTypeInfo &FTI
  1912. = DeclaratorInfo.getFunctionTypeInfo();
  1913. // If there was a late-parsed exception-specification, we'll need a
  1914. // late parse
  1915. bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed;
  1916. if (!NeedLateParse) {
  1917. // Look ahead to see if there are any default args
  1918. for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) {
  1919. auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param);
  1920. if (Param->hasUnparsedDefaultArg()) {
  1921. NeedLateParse = true;
  1922. break;
  1923. }
  1924. }
  1925. }
  1926. if (NeedLateParse) {
  1927. // Push this method onto the stack of late-parsed method
  1928. // declarations.
  1929. auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl);
  1930. getCurrentClass().LateParsedDeclarations.push_back(LateMethod);
  1931. LateMethod->TemplateScope = getCurScope()->isTemplateParamScope();
  1932. // Stash the exception-specification tokens in the late-pased method.
  1933. LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens;
  1934. FTI.ExceptionSpecTokens = nullptr;
  1935. // Push tokens for each parameter. Those that do not have
  1936. // defaults will be NULL.
  1937. LateMethod->DefaultArgs.reserve(FTI.NumParams);
  1938. for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx)
  1939. LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument(
  1940. FTI.Params[ParamIdx].Param,
  1941. std::move(FTI.Params[ParamIdx].DefaultArgTokens)));
  1942. }
  1943. }
  1944. /// isCXX11VirtSpecifier - Determine whether the given token is a C++11
  1945. /// virt-specifier.
  1946. ///
  1947. /// virt-specifier:
  1948. /// override
  1949. /// final
  1950. /// __final
  1951. VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const {
  1952. if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier))
  1953. return VirtSpecifiers::VS_None;
  1954. IdentifierInfo *II = Tok.getIdentifierInfo();
  1955. // Initialize the contextual keywords.
  1956. if (!Ident_final) {
  1957. Ident_final = &PP.getIdentifierTable().get("final");
  1958. if (getLangOpts().GNUKeywords)
  1959. Ident_GNU_final = &PP.getIdentifierTable().get("__final");
  1960. if (getLangOpts().MicrosoftExt)
  1961. Ident_sealed = &PP.getIdentifierTable().get("sealed");
  1962. Ident_override = &PP.getIdentifierTable().get("override");
  1963. }
  1964. if (II == Ident_override)
  1965. return VirtSpecifiers::VS_Override;
  1966. if (II == Ident_sealed)
  1967. return VirtSpecifiers::VS_Sealed;
  1968. if (II == Ident_final)
  1969. return VirtSpecifiers::VS_Final;
  1970. if (II == Ident_GNU_final)
  1971. return VirtSpecifiers::VS_GNU_Final;
  1972. return VirtSpecifiers::VS_None;
  1973. }
  1974. /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq.
  1975. ///
  1976. /// virt-specifier-seq:
  1977. /// virt-specifier
  1978. /// virt-specifier-seq virt-specifier
  1979. void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS,
  1980. bool IsInterface,
  1981. SourceLocation FriendLoc) {
  1982. while (true) {
  1983. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
  1984. if (Specifier == VirtSpecifiers::VS_None)
  1985. return;
  1986. if (FriendLoc.isValid()) {
  1987. Diag(Tok.getLocation(), diag::err_friend_decl_spec)
  1988. << VirtSpecifiers::getSpecifierName(Specifier)
  1989. << FixItHint::CreateRemoval(Tok.getLocation())
  1990. << SourceRange(FriendLoc, FriendLoc);
  1991. ConsumeToken();
  1992. continue;
  1993. }
  1994. // C++ [class.mem]p8:
  1995. // A virt-specifier-seq shall contain at most one of each virt-specifier.
  1996. const char *PrevSpec = nullptr;
  1997. if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec))
  1998. Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier)
  1999. << PrevSpec
  2000. << FixItHint::CreateRemoval(Tok.getLocation());
  2001. if (IsInterface && (Specifier == VirtSpecifiers::VS_Final ||
  2002. Specifier == VirtSpecifiers::VS_Sealed)) {
  2003. Diag(Tok.getLocation(), diag::err_override_control_interface)
  2004. << VirtSpecifiers::getSpecifierName(Specifier);
  2005. } else if (Specifier == VirtSpecifiers::VS_Sealed) {
  2006. Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword);
  2007. } else if (Specifier == VirtSpecifiers::VS_GNU_Final) {
  2008. Diag(Tok.getLocation(), diag::ext_warn_gnu_final);
  2009. } else {
  2010. Diag(Tok.getLocation(),
  2011. getLangOpts().CPlusPlus11
  2012. ? diag::warn_cxx98_compat_override_control_keyword
  2013. : diag::ext_override_control_keyword)
  2014. << VirtSpecifiers::getSpecifierName(Specifier);
  2015. }
  2016. ConsumeToken();
  2017. }
  2018. }
  2019. /// isCXX11FinalKeyword - Determine whether the next token is a C++11
  2020. /// 'final' or Microsoft 'sealed' contextual keyword.
  2021. bool Parser::isCXX11FinalKeyword() const {
  2022. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier();
  2023. return Specifier == VirtSpecifiers::VS_Final ||
  2024. Specifier == VirtSpecifiers::VS_GNU_Final ||
  2025. Specifier == VirtSpecifiers::VS_Sealed;
  2026. }
  2027. /// Parse a C++ member-declarator up to, but not including, the optional
  2028. /// brace-or-equal-initializer or pure-specifier.
  2029. bool Parser::ParseCXXMemberDeclaratorBeforeInitializer(
  2030. Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize,
  2031. LateParsedAttrList &LateParsedAttrs) {
  2032. // member-declarator:
  2033. // declarator pure-specifier[opt]
  2034. // declarator brace-or-equal-initializer[opt]
  2035. // identifier[opt] ':' constant-expression
  2036. if (Tok.isNot(tok::colon))
  2037. ParseDeclarator(DeclaratorInfo);
  2038. else
  2039. DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation());
  2040. if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) {
  2041. assert(DeclaratorInfo.isPastIdentifier() &&
  2042. "don't know where identifier would go yet?");
  2043. BitfieldSize = ParseConstantExpression();
  2044. if (BitfieldSize.isInvalid())
  2045. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2046. } else {
  2047. ParseOptionalCXX11VirtSpecifierSeq(
  2048. VS, getCurrentClass().IsInterface,
  2049. DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
  2050. if (!VS.isUnset())
  2051. MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
  2052. }
  2053. // If a simple-asm-expr is present, parse it.
  2054. if (Tok.is(tok::kw_asm)) {
  2055. SourceLocation Loc;
  2056. ExprResult AsmLabel(ParseSimpleAsm(&Loc));
  2057. if (AsmLabel.isInvalid())
  2058. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2059. DeclaratorInfo.setAsmLabel(AsmLabel.get());
  2060. DeclaratorInfo.SetRangeEnd(Loc);
  2061. }
  2062. // If attributes exist after the declarator, but before an '{', parse them.
  2063. MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
  2064. // For compatibility with code written to older Clang, also accept a
  2065. // virt-specifier *after* the GNU attributes.
  2066. if (BitfieldSize.isUnset() && VS.isUnset()) {
  2067. ParseOptionalCXX11VirtSpecifierSeq(
  2068. VS, getCurrentClass().IsInterface,
  2069. DeclaratorInfo.getDeclSpec().getFriendSpecLoc());
  2070. if (!VS.isUnset()) {
  2071. // If we saw any GNU-style attributes that are known to GCC followed by a
  2072. // virt-specifier, issue a GCC-compat warning.
  2073. for (const ParsedAttr &AL : DeclaratorInfo.getAttributes())
  2074. if (AL.isKnownToGCC() && !AL.isCXX11Attribute())
  2075. Diag(AL.getLoc(), diag::warn_gcc_attribute_location);
  2076. MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS);
  2077. }
  2078. }
  2079. // If this has neither a name nor a bit width, something has gone seriously
  2080. // wrong. Skip until the semi-colon or }.
  2081. if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) {
  2082. // If so, skip until the semi-colon or a }.
  2083. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  2084. return true;
  2085. }
  2086. return false;
  2087. }
  2088. /// Look for declaration specifiers possibly occurring after C++11
  2089. /// virt-specifier-seq and diagnose them.
  2090. void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(
  2091. Declarator &D,
  2092. VirtSpecifiers &VS) {
  2093. DeclSpec DS(AttrFactory);
  2094. // GNU-style and C++11 attributes are not allowed here, but they will be
  2095. // handled by the caller. Diagnose everything else.
  2096. ParseTypeQualifierListOpt(
  2097. DS, AR_NoAttributesParsed, false,
  2098. /*IdentifierRequired=*/false, llvm::function_ref<void()>([&]() {
  2099. Actions.CodeCompleteFunctionQualifiers(DS, D, &VS);
  2100. }));
  2101. D.ExtendWithDeclSpec(DS);
  2102. if (D.isFunctionDeclarator()) {
  2103. auto &Function = D.getFunctionTypeInfo();
  2104. if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) {
  2105. auto DeclSpecCheck = [&](DeclSpec::TQ TypeQual, StringRef FixItName,
  2106. SourceLocation SpecLoc) {
  2107. FixItHint Insertion;
  2108. auto &MQ = Function.getOrCreateMethodQualifiers();
  2109. if (!(MQ.getTypeQualifiers() & TypeQual)) {
  2110. std::string Name(FixItName.data());
  2111. Name += " ";
  2112. Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
  2113. MQ.SetTypeQual(TypeQual, SpecLoc);
  2114. }
  2115. Diag(SpecLoc, diag::err_declspec_after_virtspec)
  2116. << FixItName
  2117. << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
  2118. << FixItHint::CreateRemoval(SpecLoc) << Insertion;
  2119. };
  2120. DS.forEachQualifier(DeclSpecCheck);
  2121. }
  2122. // Parse ref-qualifiers.
  2123. bool RefQualifierIsLValueRef = true;
  2124. SourceLocation RefQualifierLoc;
  2125. if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) {
  2126. const char *Name = (RefQualifierIsLValueRef ? "& " : "&& ");
  2127. FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name);
  2128. Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef;
  2129. Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding();
  2130. Diag(RefQualifierLoc, diag::err_declspec_after_virtspec)
  2131. << (RefQualifierIsLValueRef ? "&" : "&&")
  2132. << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier())
  2133. << FixItHint::CreateRemoval(RefQualifierLoc)
  2134. << Insertion;
  2135. D.SetRangeEnd(RefQualifierLoc);
  2136. }
  2137. }
  2138. }
  2139. /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration.
  2140. ///
  2141. /// member-declaration:
  2142. /// decl-specifier-seq[opt] member-declarator-list[opt] ';'
  2143. /// function-definition ';'[opt]
  2144. /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO]
  2145. /// using-declaration [TODO]
  2146. /// [C++0x] static_assert-declaration
  2147. /// template-declaration
  2148. /// [GNU] '__extension__' member-declaration
  2149. ///
  2150. /// member-declarator-list:
  2151. /// member-declarator
  2152. /// member-declarator-list ',' member-declarator
  2153. ///
  2154. /// member-declarator:
  2155. /// declarator virt-specifier-seq[opt] pure-specifier[opt]
  2156. /// declarator constant-initializer[opt]
  2157. /// [C++11] declarator brace-or-equal-initializer[opt]
  2158. /// identifier[opt] ':' constant-expression
  2159. ///
  2160. /// virt-specifier-seq:
  2161. /// virt-specifier
  2162. /// virt-specifier-seq virt-specifier
  2163. ///
  2164. /// virt-specifier:
  2165. /// override
  2166. /// final
  2167. /// [MS] sealed
  2168. ///
  2169. /// pure-specifier:
  2170. /// '= 0'
  2171. ///
  2172. /// constant-initializer:
  2173. /// '=' constant-expression
  2174. ///
  2175. Parser::DeclGroupPtrTy
  2176. Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
  2177. ParsedAttributes &AccessAttrs,
  2178. const ParsedTemplateInfo &TemplateInfo,
  2179. ParsingDeclRAIIObject *TemplateDiags) {
  2180. if (Tok.is(tok::at)) {
  2181. if (getLangOpts().ObjC && NextToken().isObjCAtKeyword(tok::objc_defs))
  2182. Diag(Tok, diag::err_at_defs_cxx);
  2183. else
  2184. Diag(Tok, diag::err_at_in_class);
  2185. ConsumeToken();
  2186. SkipUntil(tok::r_brace, StopAtSemi);
  2187. return nullptr;
  2188. }
  2189. // Turn on colon protection early, while parsing declspec, although there is
  2190. // nothing to protect there. It prevents from false errors if error recovery
  2191. // incorrectly determines where the declspec ends, as in the example:
  2192. // struct A { enum class B { C }; };
  2193. // const int C = 4;
  2194. // struct D { A::B : C; };
  2195. ColonProtectionRAIIObject X(*this);
  2196. // Access declarations.
  2197. bool MalformedTypeSpec = false;
  2198. if (!TemplateInfo.Kind &&
  2199. Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) {
  2200. if (TryAnnotateCXXScopeToken())
  2201. MalformedTypeSpec = true;
  2202. bool isAccessDecl;
  2203. if (Tok.isNot(tok::annot_cxxscope))
  2204. isAccessDecl = false;
  2205. else if (NextToken().is(tok::identifier))
  2206. isAccessDecl = GetLookAheadToken(2).is(tok::semi);
  2207. else
  2208. isAccessDecl = NextToken().is(tok::kw_operator);
  2209. if (isAccessDecl) {
  2210. // Collect the scope specifier token we annotated earlier.
  2211. CXXScopeSpec SS;
  2212. ParseOptionalCXXScopeSpecifier(SS, nullptr,
  2213. /*EnteringContext=*/false);
  2214. if (SS.isInvalid()) {
  2215. SkipUntil(tok::semi);
  2216. return nullptr;
  2217. }
  2218. // Try to parse an unqualified-id.
  2219. SourceLocation TemplateKWLoc;
  2220. UnqualifiedId Name;
  2221. if (ParseUnqualifiedId(SS, false, true, true, false, nullptr,
  2222. &TemplateKWLoc, Name)) {
  2223. SkipUntil(tok::semi);
  2224. return nullptr;
  2225. }
  2226. // TODO: recover from mistakenly-qualified operator declarations.
  2227. if (ExpectAndConsume(tok::semi, diag::err_expected_after,
  2228. "access declaration")) {
  2229. SkipUntil(tok::semi);
  2230. return nullptr;
  2231. }
  2232. // FIXME: We should do something with the 'template' keyword here.
  2233. return DeclGroupPtrTy::make(DeclGroupRef(Actions.ActOnUsingDeclaration(
  2234. getCurScope(), AS, /*UsingLoc*/ SourceLocation(),
  2235. /*TypenameLoc*/ SourceLocation(), SS, Name,
  2236. /*EllipsisLoc*/ SourceLocation(),
  2237. /*AttrList*/ ParsedAttributesView())));
  2238. }
  2239. }
  2240. // static_assert-declaration. A templated static_assert declaration is
  2241. // diagnosed in Parser::ParseSingleDeclarationAfterTemplate.
  2242. if (!TemplateInfo.Kind &&
  2243. Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) {
  2244. SourceLocation DeclEnd;
  2245. return DeclGroupPtrTy::make(
  2246. DeclGroupRef(ParseStaticAssertDeclaration(DeclEnd)));
  2247. }
  2248. if (Tok.is(tok::kw_template)) {
  2249. assert(!TemplateInfo.TemplateParams &&
  2250. "Nested template improperly parsed?");
  2251. ObjCDeclContextSwitch ObjCDC(*this);
  2252. SourceLocation DeclEnd;
  2253. return DeclGroupPtrTy::make(
  2254. DeclGroupRef(ParseTemplateDeclarationOrSpecialization(
  2255. DeclaratorContext::MemberContext, DeclEnd, AccessAttrs, AS)));
  2256. }
  2257. // Handle: member-declaration ::= '__extension__' member-declaration
  2258. if (Tok.is(tok::kw___extension__)) {
  2259. // __extension__ silences extension warnings in the subexpression.
  2260. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  2261. ConsumeToken();
  2262. return ParseCXXClassMemberDeclaration(AS, AccessAttrs,
  2263. TemplateInfo, TemplateDiags);
  2264. }
  2265. ParsedAttributesWithRange attrs(AttrFactory);
  2266. ParsedAttributesViewWithRange FnAttrs;
  2267. // Optional C++11 attribute-specifier
  2268. MaybeParseCXX11Attributes(attrs);
  2269. // We need to keep these attributes for future diagnostic
  2270. // before they are taken over by declaration specifier.
  2271. FnAttrs.addAll(attrs.begin(), attrs.end());
  2272. FnAttrs.Range = attrs.Range;
  2273. MaybeParseMicrosoftAttributes(attrs);
  2274. if (Tok.is(tok::kw_using)) {
  2275. ProhibitAttributes(attrs);
  2276. // Eat 'using'.
  2277. SourceLocation UsingLoc = ConsumeToken();
  2278. // Consume unexpected 'template' keywords.
  2279. while (Tok.is(tok::kw_template)) {
  2280. SourceLocation TemplateLoc = ConsumeToken();
  2281. Diag(TemplateLoc, diag::err_unexpected_template_after_using)
  2282. << FixItHint::CreateRemoval(TemplateLoc);
  2283. }
  2284. if (Tok.is(tok::kw_namespace)) {
  2285. Diag(UsingLoc, diag::err_using_namespace_in_class);
  2286. SkipUntil(tok::semi, StopBeforeMatch);
  2287. return nullptr;
  2288. }
  2289. SourceLocation DeclEnd;
  2290. // Otherwise, it must be a using-declaration or an alias-declaration.
  2291. return ParseUsingDeclaration(DeclaratorContext::MemberContext, TemplateInfo,
  2292. UsingLoc, DeclEnd, AS);
  2293. }
  2294. // Hold late-parsed attributes so we can attach a Decl to them later.
  2295. LateParsedAttrList CommonLateParsedAttrs;
  2296. // decl-specifier-seq:
  2297. // Parse the common declaration-specifiers piece.
  2298. ParsingDeclSpec DS(*this, TemplateDiags);
  2299. DS.takeAttributesFrom(attrs);
  2300. if (MalformedTypeSpec)
  2301. DS.SetTypeSpecError();
  2302. ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DeclSpecContext::DSC_class,
  2303. &CommonLateParsedAttrs);
  2304. // Turn off colon protection that was set for declspec.
  2305. X.restore();
  2306. // If we had a free-standing type definition with a missing semicolon, we
  2307. // may get this far before the problem becomes obvious.
  2308. if (DS.hasTagDefinition() &&
  2309. TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate &&
  2310. DiagnoseMissingSemiAfterTagDefinition(DS, AS, DeclSpecContext::DSC_class,
  2311. &CommonLateParsedAttrs))
  2312. return nullptr;
  2313. MultiTemplateParamsArg TemplateParams(
  2314. TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data()
  2315. : nullptr,
  2316. TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0);
  2317. if (TryConsumeToken(tok::semi)) {
  2318. if (DS.isFriendSpecified())
  2319. ProhibitAttributes(FnAttrs);
  2320. RecordDecl *AnonRecord = nullptr;
  2321. Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(
  2322. getCurScope(), AS, DS, TemplateParams, false, AnonRecord);
  2323. DS.complete(TheDecl);
  2324. if (AnonRecord) {
  2325. Decl* decls[] = {AnonRecord, TheDecl};
  2326. return Actions.BuildDeclaratorGroup(decls);
  2327. }
  2328. return Actions.ConvertDeclToDeclGroup(TheDecl);
  2329. }
  2330. ParsingDeclarator DeclaratorInfo(*this, DS, DeclaratorContext::MemberContext);
  2331. VirtSpecifiers VS;
  2332. // Hold late-parsed attributes so we can attach a Decl to them later.
  2333. LateParsedAttrList LateParsedAttrs;
  2334. SourceLocation EqualLoc;
  2335. SourceLocation PureSpecLoc;
  2336. auto TryConsumePureSpecifier = [&] (bool AllowDefinition) {
  2337. if (Tok.isNot(tok::equal))
  2338. return false;
  2339. auto &Zero = NextToken();
  2340. SmallString<8> Buffer;
  2341. if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 ||
  2342. PP.getSpelling(Zero, Buffer) != "0")
  2343. return false;
  2344. auto &After = GetLookAheadToken(2);
  2345. if (!After.isOneOf(tok::semi, tok::comma) &&
  2346. !(AllowDefinition &&
  2347. After.isOneOf(tok::l_brace, tok::colon, tok::kw_try)))
  2348. return false;
  2349. EqualLoc = ConsumeToken();
  2350. PureSpecLoc = ConsumeToken();
  2351. return true;
  2352. };
  2353. SmallVector<Decl *, 8> DeclsInGroup;
  2354. ExprResult BitfieldSize;
  2355. bool ExpectSemi = true;
  2356. // Parse the first declarator.
  2357. if (ParseCXXMemberDeclaratorBeforeInitializer(
  2358. DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) {
  2359. TryConsumeToken(tok::semi);
  2360. return nullptr;
  2361. }
  2362. // Check for a member function definition.
  2363. if (BitfieldSize.isUnset()) {
  2364. // MSVC permits pure specifier on inline functions defined at class scope.
  2365. // Hence check for =0 before checking for function definition.
  2366. if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction())
  2367. TryConsumePureSpecifier(/*AllowDefinition*/ true);
  2368. FunctionDefinitionKind DefinitionKind = FDK_Declaration;
  2369. // function-definition:
  2370. //
  2371. // In C++11, a non-function declarator followed by an open brace is a
  2372. // braced-init-list for an in-class member initialization, not an
  2373. // erroneous function definition.
  2374. if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) {
  2375. DefinitionKind = FDK_Definition;
  2376. } else if (DeclaratorInfo.isFunctionDeclarator()) {
  2377. if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) {
  2378. DefinitionKind = FDK_Definition;
  2379. } else if (Tok.is(tok::equal)) {
  2380. const Token &KW = NextToken();
  2381. if (KW.is(tok::kw_default))
  2382. DefinitionKind = FDK_Defaulted;
  2383. else if (KW.is(tok::kw_delete))
  2384. DefinitionKind = FDK_Deleted;
  2385. }
  2386. }
  2387. DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind);
  2388. // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
  2389. // to a friend declaration, that declaration shall be a definition.
  2390. if (DeclaratorInfo.isFunctionDeclarator() &&
  2391. DefinitionKind != FDK_Definition && DS.isFriendSpecified()) {
  2392. // Diagnose attributes that appear before decl specifier:
  2393. // [[]] friend int foo();
  2394. ProhibitAttributes(FnAttrs);
  2395. }
  2396. if (DefinitionKind != FDK_Declaration) {
  2397. if (!DeclaratorInfo.isFunctionDeclarator()) {
  2398. Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params);
  2399. ConsumeBrace();
  2400. SkipUntil(tok::r_brace);
  2401. // Consume the optional ';'
  2402. TryConsumeToken(tok::semi);
  2403. return nullptr;
  2404. }
  2405. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
  2406. Diag(DeclaratorInfo.getIdentifierLoc(),
  2407. diag::err_function_declared_typedef);
  2408. // Recover by treating the 'typedef' as spurious.
  2409. DS.ClearStorageClassSpecs();
  2410. }
  2411. Decl *FunDecl =
  2412. ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo,
  2413. VS, PureSpecLoc);
  2414. if (FunDecl) {
  2415. for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) {
  2416. CommonLateParsedAttrs[i]->addDecl(FunDecl);
  2417. }
  2418. for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) {
  2419. LateParsedAttrs[i]->addDecl(FunDecl);
  2420. }
  2421. }
  2422. LateParsedAttrs.clear();
  2423. // Consume the ';' - it's optional unless we have a delete or default
  2424. if (Tok.is(tok::semi))
  2425. ConsumeExtraSemi(AfterMemberFunctionDefinition);
  2426. return DeclGroupPtrTy::make(DeclGroupRef(FunDecl));
  2427. }
  2428. }
  2429. // member-declarator-list:
  2430. // member-declarator
  2431. // member-declarator-list ',' member-declarator
  2432. while (1) {
  2433. InClassInitStyle HasInClassInit = ICIS_NoInit;
  2434. bool HasStaticInitializer = false;
  2435. if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) {
  2436. if (DeclaratorInfo.isDeclarationOfFunction()) {
  2437. // It's a pure-specifier.
  2438. if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false))
  2439. // Parse it as an expression so that Sema can diagnose it.
  2440. HasStaticInitializer = true;
  2441. } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2442. DeclSpec::SCS_static &&
  2443. DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2444. DeclSpec::SCS_typedef &&
  2445. !DS.isFriendSpecified()) {
  2446. // It's a default member initializer.
  2447. if (BitfieldSize.get())
  2448. Diag(Tok, getLangOpts().CPlusPlus2a
  2449. ? diag::warn_cxx17_compat_bitfield_member_init
  2450. : diag::ext_bitfield_member_init);
  2451. HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit;
  2452. } else {
  2453. HasStaticInitializer = true;
  2454. }
  2455. }
  2456. // NOTE: If Sema is the Action module and declarator is an instance field,
  2457. // this call will *not* return the created decl; It will return null.
  2458. // See Sema::ActOnCXXMemberDeclarator for details.
  2459. NamedDecl *ThisDecl = nullptr;
  2460. if (DS.isFriendSpecified()) {
  2461. // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains
  2462. // to a friend declaration, that declaration shall be a definition.
  2463. //
  2464. // Diagnose attributes that appear in a friend member function declarator:
  2465. // friend int foo [[]] ();
  2466. SmallVector<SourceRange, 4> Ranges;
  2467. DeclaratorInfo.getCXX11AttributeRanges(Ranges);
  2468. for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
  2469. E = Ranges.end(); I != E; ++I)
  2470. Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I;
  2471. ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo,
  2472. TemplateParams);
  2473. } else {
  2474. ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS,
  2475. DeclaratorInfo,
  2476. TemplateParams,
  2477. BitfieldSize.get(),
  2478. VS, HasInClassInit);
  2479. if (VarTemplateDecl *VT =
  2480. ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr)
  2481. // Re-direct this decl to refer to the templated decl so that we can
  2482. // initialize it.
  2483. ThisDecl = VT->getTemplatedDecl();
  2484. if (ThisDecl)
  2485. Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs);
  2486. }
  2487. // Error recovery might have converted a non-static member into a static
  2488. // member.
  2489. if (HasInClassInit != ICIS_NoInit &&
  2490. DeclaratorInfo.getDeclSpec().getStorageClassSpec() ==
  2491. DeclSpec::SCS_static) {
  2492. HasInClassInit = ICIS_NoInit;
  2493. HasStaticInitializer = true;
  2494. }
  2495. if (ThisDecl && PureSpecLoc.isValid())
  2496. Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc);
  2497. // Handle the initializer.
  2498. if (HasInClassInit != ICIS_NoInit) {
  2499. // The initializer was deferred; parse it and cache the tokens.
  2500. Diag(Tok, getLangOpts().CPlusPlus11
  2501. ? diag::warn_cxx98_compat_nonstatic_member_init
  2502. : diag::ext_nonstatic_member_init);
  2503. if (DeclaratorInfo.isArrayOfUnknownBound()) {
  2504. // C++11 [dcl.array]p3: An array bound may also be omitted when the
  2505. // declarator is followed by an initializer.
  2506. //
  2507. // A brace-or-equal-initializer for a member-declarator is not an
  2508. // initializer in the grammar, so this is ill-formed.
  2509. Diag(Tok, diag::err_incomplete_array_member_init);
  2510. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2511. // Avoid later warnings about a class member of incomplete type.
  2512. if (ThisDecl)
  2513. ThisDecl->setInvalidDecl();
  2514. } else
  2515. ParseCXXNonStaticMemberInitializer(ThisDecl);
  2516. } else if (HasStaticInitializer) {
  2517. // Normal initializer.
  2518. ExprResult Init = ParseCXXMemberInitializer(
  2519. ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc);
  2520. if (Init.isInvalid())
  2521. SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch);
  2522. else if (ThisDecl)
  2523. Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid());
  2524. } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static)
  2525. // No initializer.
  2526. Actions.ActOnUninitializedDecl(ThisDecl);
  2527. if (ThisDecl) {
  2528. if (!ThisDecl->isInvalidDecl()) {
  2529. // Set the Decl for any late parsed attributes
  2530. for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i)
  2531. CommonLateParsedAttrs[i]->addDecl(ThisDecl);
  2532. for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i)
  2533. LateParsedAttrs[i]->addDecl(ThisDecl);
  2534. }
  2535. Actions.FinalizeDeclaration(ThisDecl);
  2536. DeclsInGroup.push_back(ThisDecl);
  2537. if (DeclaratorInfo.isFunctionDeclarator() &&
  2538. DeclaratorInfo.getDeclSpec().getStorageClassSpec() !=
  2539. DeclSpec::SCS_typedef)
  2540. HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl);
  2541. }
  2542. LateParsedAttrs.clear();
  2543. DeclaratorInfo.complete(ThisDecl);
  2544. // If we don't have a comma, it is either the end of the list (a ';')
  2545. // or an error, bail out.
  2546. SourceLocation CommaLoc;
  2547. if (!TryConsumeToken(tok::comma, CommaLoc))
  2548. break;
  2549. if (Tok.isAtStartOfLine() &&
  2550. !MightBeDeclarator(DeclaratorContext::MemberContext)) {
  2551. // This comma was followed by a line-break and something which can't be
  2552. // the start of a declarator. The comma was probably a typo for a
  2553. // semicolon.
  2554. Diag(CommaLoc, diag::err_expected_semi_declaration)
  2555. << FixItHint::CreateReplacement(CommaLoc, ";");
  2556. ExpectSemi = false;
  2557. break;
  2558. }
  2559. // Parse the next declarator.
  2560. DeclaratorInfo.clear();
  2561. VS.clear();
  2562. BitfieldSize = ExprResult(/*Invalid=*/false);
  2563. EqualLoc = PureSpecLoc = SourceLocation();
  2564. DeclaratorInfo.setCommaLoc(CommaLoc);
  2565. // GNU attributes are allowed before the second and subsequent declarator.
  2566. MaybeParseGNUAttributes(DeclaratorInfo);
  2567. if (ParseCXXMemberDeclaratorBeforeInitializer(
  2568. DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs))
  2569. break;
  2570. }
  2571. if (ExpectSemi &&
  2572. ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) {
  2573. // Skip to end of block or statement.
  2574. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
  2575. // If we stopped at a ';', eat it.
  2576. TryConsumeToken(tok::semi);
  2577. return nullptr;
  2578. }
  2579. return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
  2580. }
  2581. /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer.
  2582. /// Also detect and reject any attempted defaulted/deleted function definition.
  2583. /// The location of the '=', if any, will be placed in EqualLoc.
  2584. ///
  2585. /// This does not check for a pure-specifier; that's handled elsewhere.
  2586. ///
  2587. /// brace-or-equal-initializer:
  2588. /// '=' initializer-expression
  2589. /// braced-init-list
  2590. ///
  2591. /// initializer-clause:
  2592. /// assignment-expression
  2593. /// braced-init-list
  2594. ///
  2595. /// defaulted/deleted function-definition:
  2596. /// '=' 'default'
  2597. /// '=' 'delete'
  2598. ///
  2599. /// Prior to C++0x, the assignment-expression in an initializer-clause must
  2600. /// be a constant-expression.
  2601. ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction,
  2602. SourceLocation &EqualLoc) {
  2603. assert(Tok.isOneOf(tok::equal, tok::l_brace)
  2604. && "Data member initializer not starting with '=' or '{'");
  2605. EnterExpressionEvaluationContext Context(
  2606. Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, D);
  2607. if (TryConsumeToken(tok::equal, EqualLoc)) {
  2608. if (Tok.is(tok::kw_delete)) {
  2609. // In principle, an initializer of '= delete p;' is legal, but it will
  2610. // never type-check. It's better to diagnose it as an ill-formed expression
  2611. // than as an ill-formed deleted non-function member.
  2612. // An initializer of '= delete p, foo' will never be parsed, because
  2613. // a top-level comma always ends the initializer expression.
  2614. const Token &Next = NextToken();
  2615. if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) {
  2616. if (IsFunction)
  2617. Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration)
  2618. << 1 /* delete */;
  2619. else
  2620. Diag(ConsumeToken(), diag::err_deleted_non_function);
  2621. return ExprError();
  2622. }
  2623. } else if (Tok.is(tok::kw_default)) {
  2624. if (IsFunction)
  2625. Diag(Tok, diag::err_default_delete_in_multiple_declaration)
  2626. << 0 /* default */;
  2627. else
  2628. Diag(ConsumeToken(), diag::err_default_special_members);
  2629. return ExprError();
  2630. }
  2631. }
  2632. if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) {
  2633. Diag(Tok, diag::err_ms_property_initializer) << PD;
  2634. return ExprError();
  2635. }
  2636. return ParseInitializer();
  2637. }
  2638. void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc,
  2639. SourceLocation AttrFixitLoc,
  2640. unsigned TagType, Decl *TagDecl) {
  2641. // Skip the optional 'final' keyword.
  2642. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
  2643. assert(isCXX11FinalKeyword() && "not a class definition");
  2644. ConsumeToken();
  2645. // Diagnose any C++11 attributes after 'final' keyword.
  2646. // We deliberately discard these attributes.
  2647. ParsedAttributesWithRange Attrs(AttrFactory);
  2648. CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
  2649. // This can only happen if we had malformed misplaced attributes;
  2650. // we only get called if there is a colon or left-brace after the
  2651. // attributes.
  2652. if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace))
  2653. return;
  2654. }
  2655. // Skip the base clauses. This requires actually parsing them, because
  2656. // otherwise we can't be sure where they end (a left brace may appear
  2657. // within a template argument).
  2658. if (Tok.is(tok::colon)) {
  2659. // Enter the scope of the class so that we can correctly parse its bases.
  2660. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
  2661. ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true,
  2662. TagType == DeclSpec::TST_interface);
  2663. auto OldContext =
  2664. Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl);
  2665. // Parse the bases but don't attach them to the class.
  2666. ParseBaseClause(nullptr);
  2667. Actions.ActOnTagFinishSkippedDefinition(OldContext);
  2668. if (!Tok.is(tok::l_brace)) {
  2669. Diag(PP.getLocForEndOfToken(PrevTokLocation),
  2670. diag::err_expected_lbrace_after_base_specifiers);
  2671. return;
  2672. }
  2673. }
  2674. // Skip the body.
  2675. assert(Tok.is(tok::l_brace));
  2676. BalancedDelimiterTracker T(*this, tok::l_brace);
  2677. T.consumeOpen();
  2678. T.skipToEnd();
  2679. // Parse and discard any trailing attributes.
  2680. ParsedAttributes Attrs(AttrFactory);
  2681. if (Tok.is(tok::kw___attribute))
  2682. MaybeParseGNUAttributes(Attrs);
  2683. }
  2684. Parser::DeclGroupPtrTy Parser::ParseCXXClassMemberDeclarationWithPragmas(
  2685. AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs,
  2686. DeclSpec::TST TagType, Decl *TagDecl) {
  2687. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  2688. switch (Tok.getKind()) {
  2689. case tok::kw___if_exists:
  2690. case tok::kw___if_not_exists:
  2691. ParseMicrosoftIfExistsClassDeclaration(TagType, AccessAttrs, AS);
  2692. return nullptr;
  2693. case tok::semi:
  2694. // Check for extraneous top-level semicolon.
  2695. ConsumeExtraSemi(InsideStruct, TagType);
  2696. return nullptr;
  2697. // Handle pragmas that can appear as member declarations.
  2698. case tok::annot_pragma_vis:
  2699. HandlePragmaVisibility();
  2700. return nullptr;
  2701. case tok::annot_pragma_pack:
  2702. HandlePragmaPack();
  2703. return nullptr;
  2704. case tok::annot_pragma_align:
  2705. HandlePragmaAlign();
  2706. return nullptr;
  2707. case tok::annot_pragma_ms_pointers_to_members:
  2708. HandlePragmaMSPointersToMembers();
  2709. return nullptr;
  2710. case tok::annot_pragma_ms_pragma:
  2711. HandlePragmaMSPragma();
  2712. return nullptr;
  2713. case tok::annot_pragma_ms_vtordisp:
  2714. HandlePragmaMSVtorDisp();
  2715. return nullptr;
  2716. case tok::annot_pragma_dump:
  2717. HandlePragmaDump();
  2718. return nullptr;
  2719. case tok::kw_namespace:
  2720. // If we see a namespace here, a close brace was missing somewhere.
  2721. DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl));
  2722. return nullptr;
  2723. case tok::kw_private:
  2724. // FIXME: We don't accept GNU attributes on access specifiers in OpenCL mode
  2725. // yet.
  2726. if (getLangOpts().OpenCL && !NextToken().is(tok::colon))
  2727. return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
  2728. LLVM_FALLTHROUGH;
  2729. case tok::kw_public:
  2730. case tok::kw_protected: {
  2731. AccessSpecifier NewAS = getAccessSpecifierIfPresent();
  2732. assert(NewAS != AS_none);
  2733. // Current token is a C++ access specifier.
  2734. AS = NewAS;
  2735. SourceLocation ASLoc = Tok.getLocation();
  2736. unsigned TokLength = Tok.getLength();
  2737. ConsumeToken();
  2738. AccessAttrs.clear();
  2739. MaybeParseGNUAttributes(AccessAttrs);
  2740. SourceLocation EndLoc;
  2741. if (TryConsumeToken(tok::colon, EndLoc)) {
  2742. } else if (TryConsumeToken(tok::semi, EndLoc)) {
  2743. Diag(EndLoc, diag::err_expected)
  2744. << tok::colon << FixItHint::CreateReplacement(EndLoc, ":");
  2745. } else {
  2746. EndLoc = ASLoc.getLocWithOffset(TokLength);
  2747. Diag(EndLoc, diag::err_expected)
  2748. << tok::colon << FixItHint::CreateInsertion(EndLoc, ":");
  2749. }
  2750. // The Microsoft extension __interface does not permit non-public
  2751. // access specifiers.
  2752. if (TagType == DeclSpec::TST_interface && AS != AS_public) {
  2753. Diag(ASLoc, diag::err_access_specifier_interface) << (AS == AS_protected);
  2754. }
  2755. if (Actions.ActOnAccessSpecifier(NewAS, ASLoc, EndLoc, AccessAttrs)) {
  2756. // found another attribute than only annotations
  2757. AccessAttrs.clear();
  2758. }
  2759. return nullptr;
  2760. }
  2761. case tok::annot_pragma_openmp:
  2762. return ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, AccessAttrs, TagType,
  2763. TagDecl);
  2764. default:
  2765. return ParseCXXClassMemberDeclaration(AS, AccessAttrs);
  2766. }
  2767. }
  2768. /// ParseCXXMemberSpecification - Parse the class definition.
  2769. ///
  2770. /// member-specification:
  2771. /// member-declaration member-specification[opt]
  2772. /// access-specifier ':' member-specification[opt]
  2773. ///
  2774. void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc,
  2775. SourceLocation AttrFixitLoc,
  2776. ParsedAttributesWithRange &Attrs,
  2777. unsigned TagType, Decl *TagDecl) {
  2778. assert((TagType == DeclSpec::TST_struct ||
  2779. TagType == DeclSpec::TST_interface ||
  2780. TagType == DeclSpec::TST_union ||
  2781. TagType == DeclSpec::TST_class) && "Invalid TagType!");
  2782. llvm::TimeTraceScope TimeScope("ParseClass", [&]() {
  2783. if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl))
  2784. return TD->getQualifiedNameAsString();
  2785. return std::string("<anonymous>");
  2786. });
  2787. PrettyDeclStackTraceEntry CrashInfo(Actions.Context, TagDecl, RecordLoc,
  2788. "parsing struct/union/class body");
  2789. // Determine whether this is a non-nested class. Note that local
  2790. // classes are *not* considered to be nested classes.
  2791. bool NonNestedClass = true;
  2792. if (!ClassStack.empty()) {
  2793. for (const Scope *S = getCurScope(); S; S = S->getParent()) {
  2794. if (S->isClassScope()) {
  2795. // We're inside a class scope, so this is a nested class.
  2796. NonNestedClass = false;
  2797. // The Microsoft extension __interface does not permit nested classes.
  2798. if (getCurrentClass().IsInterface) {
  2799. Diag(RecordLoc, diag::err_invalid_member_in_interface)
  2800. << /*ErrorType=*/6
  2801. << (isa<NamedDecl>(TagDecl)
  2802. ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString()
  2803. : "(anonymous)");
  2804. }
  2805. break;
  2806. }
  2807. if ((S->getFlags() & Scope::FnScope))
  2808. // If we're in a function or function template then this is a local
  2809. // class rather than a nested class.
  2810. break;
  2811. }
  2812. }
  2813. // Enter a scope for the class.
  2814. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope);
  2815. // Note that we are parsing a new (potentially-nested) class definition.
  2816. ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass,
  2817. TagType == DeclSpec::TST_interface);
  2818. if (TagDecl)
  2819. Actions.ActOnTagStartDefinition(getCurScope(), TagDecl);
  2820. SourceLocation FinalLoc;
  2821. bool IsFinalSpelledSealed = false;
  2822. // Parse the optional 'final' keyword.
  2823. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) {
  2824. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok);
  2825. assert((Specifier == VirtSpecifiers::VS_Final ||
  2826. Specifier == VirtSpecifiers::VS_GNU_Final ||
  2827. Specifier == VirtSpecifiers::VS_Sealed) &&
  2828. "not a class definition");
  2829. FinalLoc = ConsumeToken();
  2830. IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed;
  2831. if (TagType == DeclSpec::TST_interface)
  2832. Diag(FinalLoc, diag::err_override_control_interface)
  2833. << VirtSpecifiers::getSpecifierName(Specifier);
  2834. else if (Specifier == VirtSpecifiers::VS_Final)
  2835. Diag(FinalLoc, getLangOpts().CPlusPlus11
  2836. ? diag::warn_cxx98_compat_override_control_keyword
  2837. : diag::ext_override_control_keyword)
  2838. << VirtSpecifiers::getSpecifierName(Specifier);
  2839. else if (Specifier == VirtSpecifiers::VS_Sealed)
  2840. Diag(FinalLoc, diag::ext_ms_sealed_keyword);
  2841. else if (Specifier == VirtSpecifiers::VS_GNU_Final)
  2842. Diag(FinalLoc, diag::ext_warn_gnu_final);
  2843. // Parse any C++11 attributes after 'final' keyword.
  2844. // These attributes are not allowed to appear here,
  2845. // and the only possible place for them to appertain
  2846. // to the class would be between class-key and class-name.
  2847. CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc);
  2848. // ParseClassSpecifier() does only a superficial check for attributes before
  2849. // deciding to call this method. For example, for
  2850. // `class C final alignas ([l) {` it will decide that this looks like a
  2851. // misplaced attribute since it sees `alignas '(' ')'`. But the actual
  2852. // attribute parsing code will try to parse the '[' as a constexpr lambda
  2853. // and consume enough tokens that the alignas parsing code will eat the
  2854. // opening '{'. So bail out if the next token isn't one we expect.
  2855. if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) {
  2856. if (TagDecl)
  2857. Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
  2858. return;
  2859. }
  2860. }
  2861. if (Tok.is(tok::colon)) {
  2862. ParseScope InheritanceScope(this, getCurScope()->getFlags() |
  2863. Scope::ClassInheritanceScope);
  2864. ParseBaseClause(TagDecl);
  2865. if (!Tok.is(tok::l_brace)) {
  2866. bool SuggestFixIt = false;
  2867. SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation);
  2868. if (Tok.isAtStartOfLine()) {
  2869. switch (Tok.getKind()) {
  2870. case tok::kw_private:
  2871. case tok::kw_protected:
  2872. case tok::kw_public:
  2873. SuggestFixIt = NextToken().getKind() == tok::colon;
  2874. break;
  2875. case tok::kw_static_assert:
  2876. case tok::r_brace:
  2877. case tok::kw_using:
  2878. // base-clause can have simple-template-id; 'template' can't be there
  2879. case tok::kw_template:
  2880. SuggestFixIt = true;
  2881. break;
  2882. case tok::identifier:
  2883. SuggestFixIt = isConstructorDeclarator(true);
  2884. break;
  2885. default:
  2886. SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false);
  2887. break;
  2888. }
  2889. }
  2890. DiagnosticBuilder LBraceDiag =
  2891. Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers);
  2892. if (SuggestFixIt) {
  2893. LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {");
  2894. // Try recovering from missing { after base-clause.
  2895. PP.EnterToken(Tok, /*IsReinject*/true);
  2896. Tok.setKind(tok::l_brace);
  2897. } else {
  2898. if (TagDecl)
  2899. Actions.ActOnTagDefinitionError(getCurScope(), TagDecl);
  2900. return;
  2901. }
  2902. }
  2903. }
  2904. assert(Tok.is(tok::l_brace));
  2905. BalancedDelimiterTracker T(*this, tok::l_brace);
  2906. T.consumeOpen();
  2907. if (TagDecl)
  2908. Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc,
  2909. IsFinalSpelledSealed,
  2910. T.getOpenLocation());
  2911. // C++ 11p3: Members of a class defined with the keyword class are private
  2912. // by default. Members of a class defined with the keywords struct or union
  2913. // are public by default.
  2914. AccessSpecifier CurAS;
  2915. if (TagType == DeclSpec::TST_class)
  2916. CurAS = AS_private;
  2917. else
  2918. CurAS = AS_public;
  2919. ParsedAttributesWithRange AccessAttrs(AttrFactory);
  2920. if (TagDecl) {
  2921. // While we still have something to read, read the member-declarations.
  2922. while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
  2923. Tok.isNot(tok::eof)) {
  2924. // Each iteration of this loop reads one member-declaration.
  2925. ParseCXXClassMemberDeclarationWithPragmas(
  2926. CurAS, AccessAttrs, static_cast<DeclSpec::TST>(TagType), TagDecl);
  2927. }
  2928. T.consumeClose();
  2929. } else {
  2930. SkipUntil(tok::r_brace);
  2931. }
  2932. // If attributes exist after class contents, parse them.
  2933. ParsedAttributes attrs(AttrFactory);
  2934. MaybeParseGNUAttributes(attrs);
  2935. if (TagDecl)
  2936. Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl,
  2937. T.getOpenLocation(),
  2938. T.getCloseLocation(), attrs);
  2939. // C++11 [class.mem]p2:
  2940. // Within the class member-specification, the class is regarded as complete
  2941. // within function bodies, default arguments, exception-specifications, and
  2942. // brace-or-equal-initializers for non-static data members (including such
  2943. // things in nested classes).
  2944. if (TagDecl && NonNestedClass) {
  2945. // We are not inside a nested class. This class and its nested classes
  2946. // are complete and we can parse the delayed portions of method
  2947. // declarations and the lexed inline method definitions, along with any
  2948. // delayed attributes.
  2949. SourceLocation SavedPrevTokLocation = PrevTokLocation;
  2950. ParseLexedAttributes(getCurrentClass());
  2951. ParseLexedMethodDeclarations(getCurrentClass());
  2952. // We've finished with all pending member declarations.
  2953. Actions.ActOnFinishCXXMemberDecls();
  2954. ParseLexedMemberInitializers(getCurrentClass());
  2955. ParseLexedMethodDefs(getCurrentClass());
  2956. PrevTokLocation = SavedPrevTokLocation;
  2957. // We've finished parsing everything, including default argument
  2958. // initializers.
  2959. Actions.ActOnFinishCXXNonNestedClass(TagDecl);
  2960. }
  2961. if (TagDecl)
  2962. Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getRange());
  2963. // Leave the class scope.
  2964. ParsingDef.Pop();
  2965. ClassScope.Exit();
  2966. }
  2967. void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) {
  2968. assert(Tok.is(tok::kw_namespace));
  2969. // FIXME: Suggest where the close brace should have gone by looking
  2970. // at indentation changes within the definition body.
  2971. Diag(D->getLocation(),
  2972. diag::err_missing_end_of_definition) << D;
  2973. Diag(Tok.getLocation(),
  2974. diag::note_missing_end_of_definition_before) << D;
  2975. // Push '};' onto the token stream to recover.
  2976. PP.EnterToken(Tok, /*IsReinject*/ true);
  2977. Tok.startToken();
  2978. Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation));
  2979. Tok.setKind(tok::semi);
  2980. PP.EnterToken(Tok, /*IsReinject*/ true);
  2981. Tok.setKind(tok::r_brace);
  2982. }
  2983. /// ParseConstructorInitializer - Parse a C++ constructor initializer,
  2984. /// which explicitly initializes the members or base classes of a
  2985. /// class (C++ [class.base.init]). For example, the three initializers
  2986. /// after the ':' in the Derived constructor below:
  2987. ///
  2988. /// @code
  2989. /// class Base { };
  2990. /// class Derived : Base {
  2991. /// int x;
  2992. /// float f;
  2993. /// public:
  2994. /// Derived(float f) : Base(), x(17), f(f) { }
  2995. /// };
  2996. /// @endcode
  2997. ///
  2998. /// [C++] ctor-initializer:
  2999. /// ':' mem-initializer-list
  3000. ///
  3001. /// [C++] mem-initializer-list:
  3002. /// mem-initializer ...[opt]
  3003. /// mem-initializer ...[opt] , mem-initializer-list
  3004. void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) {
  3005. assert(Tok.is(tok::colon) &&
  3006. "Constructor initializer always starts with ':'");
  3007. // Poison the SEH identifiers so they are flagged as illegal in constructor
  3008. // initializers.
  3009. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true);
  3010. SourceLocation ColonLoc = ConsumeToken();
  3011. SmallVector<CXXCtorInitializer*, 4> MemInitializers;
  3012. bool AnyErrors = false;
  3013. do {
  3014. if (Tok.is(tok::code_completion)) {
  3015. Actions.CodeCompleteConstructorInitializer(ConstructorDecl,
  3016. MemInitializers);
  3017. return cutOffParsing();
  3018. }
  3019. MemInitResult MemInit = ParseMemInitializer(ConstructorDecl);
  3020. if (!MemInit.isInvalid())
  3021. MemInitializers.push_back(MemInit.get());
  3022. else
  3023. AnyErrors = true;
  3024. if (Tok.is(tok::comma))
  3025. ConsumeToken();
  3026. else if (Tok.is(tok::l_brace))
  3027. break;
  3028. // If the previous initializer was valid and the next token looks like a
  3029. // base or member initializer, assume that we're just missing a comma.
  3030. else if (!MemInit.isInvalid() &&
  3031. Tok.isOneOf(tok::identifier, tok::coloncolon)) {
  3032. SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation);
  3033. Diag(Loc, diag::err_ctor_init_missing_comma)
  3034. << FixItHint::CreateInsertion(Loc, ", ");
  3035. } else {
  3036. // Skip over garbage, until we get to '{'. Don't eat the '{'.
  3037. if (!MemInit.isInvalid())
  3038. Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace
  3039. << tok::comma;
  3040. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch);
  3041. break;
  3042. }
  3043. } while (true);
  3044. Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers,
  3045. AnyErrors);
  3046. }
  3047. /// ParseMemInitializer - Parse a C++ member initializer, which is
  3048. /// part of a constructor initializer that explicitly initializes one
  3049. /// member or base class (C++ [class.base.init]). See
  3050. /// ParseConstructorInitializer for an example.
  3051. ///
  3052. /// [C++] mem-initializer:
  3053. /// mem-initializer-id '(' expression-list[opt] ')'
  3054. /// [C++0x] mem-initializer-id braced-init-list
  3055. ///
  3056. /// [C++] mem-initializer-id:
  3057. /// '::'[opt] nested-name-specifier[opt] class-name
  3058. /// identifier
  3059. MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) {
  3060. // parse '::'[opt] nested-name-specifier[opt]
  3061. CXXScopeSpec SS;
  3062. if (ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false))
  3063. return true;
  3064. // : identifier
  3065. IdentifierInfo *II = nullptr;
  3066. SourceLocation IdLoc = Tok.getLocation();
  3067. // : declype(...)
  3068. DeclSpec DS(AttrFactory);
  3069. // : template_name<...>
  3070. ParsedType TemplateTypeTy;
  3071. if (Tok.is(tok::identifier)) {
  3072. // Get the identifier. This may be a member name or a class name,
  3073. // but we'll let the semantic analysis determine which it is.
  3074. II = Tok.getIdentifierInfo();
  3075. ConsumeToken();
  3076. } else if (Tok.is(tok::annot_decltype)) {
  3077. // Get the decltype expression, if there is one.
  3078. // Uses of decltype will already have been converted to annot_decltype by
  3079. // ParseOptionalCXXScopeSpecifier at this point.
  3080. // FIXME: Can we get here with a scope specifier?
  3081. ParseDecltypeSpecifier(DS);
  3082. } else {
  3083. TemplateIdAnnotation *TemplateId = Tok.is(tok::annot_template_id)
  3084. ? takeTemplateIdAnnotation(Tok)
  3085. : nullptr;
  3086. if (TemplateId && (TemplateId->Kind == TNK_Type_template ||
  3087. TemplateId->Kind == TNK_Dependent_template_name ||
  3088. TemplateId->Kind == TNK_Undeclared_template)) {
  3089. AnnotateTemplateIdTokenAsType(/*IsClassName*/true);
  3090. assert(Tok.is(tok::annot_typename) && "template-id -> type failed");
  3091. TemplateTypeTy = getTypeAnnotation(Tok);
  3092. ConsumeAnnotationToken();
  3093. if (!TemplateTypeTy)
  3094. return true;
  3095. } else {
  3096. Diag(Tok, diag::err_expected_member_or_base_name);
  3097. return true;
  3098. }
  3099. }
  3100. // Parse the '('.
  3101. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  3102. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  3103. // FIXME: Add support for signature help inside initializer lists.
  3104. ExprResult InitList = ParseBraceInitializer();
  3105. if (InitList.isInvalid())
  3106. return true;
  3107. SourceLocation EllipsisLoc;
  3108. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  3109. return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
  3110. TemplateTypeTy, DS, IdLoc,
  3111. InitList.get(), EllipsisLoc);
  3112. } else if(Tok.is(tok::l_paren)) {
  3113. BalancedDelimiterTracker T(*this, tok::l_paren);
  3114. T.consumeOpen();
  3115. // Parse the optional expression-list.
  3116. ExprVector ArgExprs;
  3117. CommaLocsTy CommaLocs;
  3118. auto RunSignatureHelp = [&] {
  3119. QualType PreferredType = Actions.ProduceCtorInitMemberSignatureHelp(
  3120. getCurScope(), ConstructorDecl, SS, TemplateTypeTy, ArgExprs, II,
  3121. T.getOpenLocation());
  3122. CalledSignatureHelp = true;
  3123. return PreferredType;
  3124. };
  3125. if (Tok.isNot(tok::r_paren) &&
  3126. ParseExpressionList(ArgExprs, CommaLocs, [&] {
  3127. PreferredType.enterFunctionArgument(Tok.getLocation(),
  3128. RunSignatureHelp);
  3129. })) {
  3130. if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
  3131. RunSignatureHelp();
  3132. SkipUntil(tok::r_paren, StopAtSemi);
  3133. return true;
  3134. }
  3135. T.consumeClose();
  3136. SourceLocation EllipsisLoc;
  3137. TryConsumeToken(tok::ellipsis, EllipsisLoc);
  3138. return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II,
  3139. TemplateTypeTy, DS, IdLoc,
  3140. T.getOpenLocation(), ArgExprs,
  3141. T.getCloseLocation(), EllipsisLoc);
  3142. }
  3143. if (getLangOpts().CPlusPlus11)
  3144. return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace;
  3145. else
  3146. return Diag(Tok, diag::err_expected) << tok::l_paren;
  3147. }
  3148. /// Parse a C++ exception-specification if present (C++0x [except.spec]).
  3149. ///
  3150. /// exception-specification:
  3151. /// dynamic-exception-specification
  3152. /// noexcept-specification
  3153. ///
  3154. /// noexcept-specification:
  3155. /// 'noexcept'
  3156. /// 'noexcept' '(' constant-expression ')'
  3157. ExceptionSpecificationType
  3158. Parser::tryParseExceptionSpecification(bool Delayed,
  3159. SourceRange &SpecificationRange,
  3160. SmallVectorImpl<ParsedType> &DynamicExceptions,
  3161. SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
  3162. ExprResult &NoexceptExpr,
  3163. CachedTokens *&ExceptionSpecTokens) {
  3164. ExceptionSpecificationType Result = EST_None;
  3165. ExceptionSpecTokens = nullptr;
  3166. // Handle delayed parsing of exception-specifications.
  3167. if (Delayed) {
  3168. if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept))
  3169. return EST_None;
  3170. // Consume and cache the starting token.
  3171. bool IsNoexcept = Tok.is(tok::kw_noexcept);
  3172. Token StartTok = Tok;
  3173. SpecificationRange = SourceRange(ConsumeToken());
  3174. // Check for a '('.
  3175. if (!Tok.is(tok::l_paren)) {
  3176. // If this is a bare 'noexcept', we're done.
  3177. if (IsNoexcept) {
  3178. Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
  3179. NoexceptExpr = nullptr;
  3180. return EST_BasicNoexcept;
  3181. }
  3182. Diag(Tok, diag::err_expected_lparen_after) << "throw";
  3183. return EST_DynamicNone;
  3184. }
  3185. // Cache the tokens for the exception-specification.
  3186. ExceptionSpecTokens = new CachedTokens;
  3187. ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept'
  3188. ExceptionSpecTokens->push_back(Tok); // '('
  3189. SpecificationRange.setEnd(ConsumeParen()); // '('
  3190. ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens,
  3191. /*StopAtSemi=*/true,
  3192. /*ConsumeFinalToken=*/true);
  3193. SpecificationRange.setEnd(ExceptionSpecTokens->back().getLocation());
  3194. return EST_Unparsed;
  3195. }
  3196. // See if there's a dynamic specification.
  3197. if (Tok.is(tok::kw_throw)) {
  3198. Result = ParseDynamicExceptionSpecification(SpecificationRange,
  3199. DynamicExceptions,
  3200. DynamicExceptionRanges);
  3201. assert(DynamicExceptions.size() == DynamicExceptionRanges.size() &&
  3202. "Produced different number of exception types and ranges.");
  3203. }
  3204. // If there's no noexcept specification, we're done.
  3205. if (Tok.isNot(tok::kw_noexcept))
  3206. return Result;
  3207. Diag(Tok, diag::warn_cxx98_compat_noexcept_decl);
  3208. // If we already had a dynamic specification, parse the noexcept for,
  3209. // recovery, but emit a diagnostic and don't store the results.
  3210. SourceRange NoexceptRange;
  3211. ExceptionSpecificationType NoexceptType = EST_None;
  3212. SourceLocation KeywordLoc = ConsumeToken();
  3213. if (Tok.is(tok::l_paren)) {
  3214. // There is an argument.
  3215. BalancedDelimiterTracker T(*this, tok::l_paren);
  3216. T.consumeOpen();
  3217. NoexceptExpr = ParseConstantExpression();
  3218. T.consumeClose();
  3219. if (!NoexceptExpr.isInvalid()) {
  3220. NoexceptExpr = Actions.ActOnNoexceptSpec(KeywordLoc, NoexceptExpr.get(),
  3221. NoexceptType);
  3222. NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation());
  3223. } else {
  3224. NoexceptType = EST_BasicNoexcept;
  3225. }
  3226. } else {
  3227. // There is no argument.
  3228. NoexceptType = EST_BasicNoexcept;
  3229. NoexceptRange = SourceRange(KeywordLoc, KeywordLoc);
  3230. }
  3231. if (Result == EST_None) {
  3232. SpecificationRange = NoexceptRange;
  3233. Result = NoexceptType;
  3234. // If there's a dynamic specification after a noexcept specification,
  3235. // parse that and ignore the results.
  3236. if (Tok.is(tok::kw_throw)) {
  3237. Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
  3238. ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions,
  3239. DynamicExceptionRanges);
  3240. }
  3241. } else {
  3242. Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification);
  3243. }
  3244. return Result;
  3245. }
  3246. static void diagnoseDynamicExceptionSpecification(
  3247. Parser &P, SourceRange Range, bool IsNoexcept) {
  3248. if (P.getLangOpts().CPlusPlus11) {
  3249. const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)";
  3250. P.Diag(Range.getBegin(),
  3251. P.getLangOpts().CPlusPlus17 && !IsNoexcept
  3252. ? diag::ext_dynamic_exception_spec
  3253. : diag::warn_exception_spec_deprecated)
  3254. << Range;
  3255. P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated)
  3256. << Replacement << FixItHint::CreateReplacement(Range, Replacement);
  3257. }
  3258. }
  3259. /// ParseDynamicExceptionSpecification - Parse a C++
  3260. /// dynamic-exception-specification (C++ [except.spec]).
  3261. ///
  3262. /// dynamic-exception-specification:
  3263. /// 'throw' '(' type-id-list [opt] ')'
  3264. /// [MS] 'throw' '(' '...' ')'
  3265. ///
  3266. /// type-id-list:
  3267. /// type-id ... [opt]
  3268. /// type-id-list ',' type-id ... [opt]
  3269. ///
  3270. ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification(
  3271. SourceRange &SpecificationRange,
  3272. SmallVectorImpl<ParsedType> &Exceptions,
  3273. SmallVectorImpl<SourceRange> &Ranges) {
  3274. assert(Tok.is(tok::kw_throw) && "expected throw");
  3275. SpecificationRange.setBegin(ConsumeToken());
  3276. BalancedDelimiterTracker T(*this, tok::l_paren);
  3277. if (T.consumeOpen()) {
  3278. Diag(Tok, diag::err_expected_lparen_after) << "throw";
  3279. SpecificationRange.setEnd(SpecificationRange.getBegin());
  3280. return EST_DynamicNone;
  3281. }
  3282. // Parse throw(...), a Microsoft extension that means "this function
  3283. // can throw anything".
  3284. if (Tok.is(tok::ellipsis)) {
  3285. SourceLocation EllipsisLoc = ConsumeToken();
  3286. if (!getLangOpts().MicrosoftExt)
  3287. Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec);
  3288. T.consumeClose();
  3289. SpecificationRange.setEnd(T.getCloseLocation());
  3290. diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false);
  3291. return EST_MSAny;
  3292. }
  3293. // Parse the sequence of type-ids.
  3294. SourceRange Range;
  3295. while (Tok.isNot(tok::r_paren)) {
  3296. TypeResult Res(ParseTypeName(&Range));
  3297. if (Tok.is(tok::ellipsis)) {
  3298. // C++0x [temp.variadic]p5:
  3299. // - In a dynamic-exception-specification (15.4); the pattern is a
  3300. // type-id.
  3301. SourceLocation Ellipsis = ConsumeToken();
  3302. Range.setEnd(Ellipsis);
  3303. if (!Res.isInvalid())
  3304. Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis);
  3305. }
  3306. if (!Res.isInvalid()) {
  3307. Exceptions.push_back(Res.get());
  3308. Ranges.push_back(Range);
  3309. }
  3310. if (!TryConsumeToken(tok::comma))
  3311. break;
  3312. }
  3313. T.consumeClose();
  3314. SpecificationRange.setEnd(T.getCloseLocation());
  3315. diagnoseDynamicExceptionSpecification(*this, SpecificationRange,
  3316. Exceptions.empty());
  3317. return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic;
  3318. }
  3319. /// ParseTrailingReturnType - Parse a trailing return type on a new-style
  3320. /// function declaration.
  3321. TypeResult Parser::ParseTrailingReturnType(SourceRange &Range,
  3322. bool MayBeFollowedByDirectInit) {
  3323. assert(Tok.is(tok::arrow) && "expected arrow");
  3324. ConsumeToken();
  3325. return ParseTypeName(&Range, MayBeFollowedByDirectInit
  3326. ? DeclaratorContext::TrailingReturnVarContext
  3327. : DeclaratorContext::TrailingReturnContext);
  3328. }
  3329. /// We have just started parsing the definition of a new class,
  3330. /// so push that class onto our stack of classes that is currently
  3331. /// being parsed.
  3332. Sema::ParsingClassState
  3333. Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass,
  3334. bool IsInterface) {
  3335. assert((NonNestedClass || !ClassStack.empty()) &&
  3336. "Nested class without outer class");
  3337. ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface));
  3338. return Actions.PushParsingClass();
  3339. }
  3340. /// Deallocate the given parsed class and all of its nested
  3341. /// classes.
  3342. void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) {
  3343. for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I)
  3344. delete Class->LateParsedDeclarations[I];
  3345. delete Class;
  3346. }
  3347. /// Pop the top class of the stack of classes that are
  3348. /// currently being parsed.
  3349. ///
  3350. /// This routine should be called when we have finished parsing the
  3351. /// definition of a class, but have not yet popped the Scope
  3352. /// associated with the class's definition.
  3353. void Parser::PopParsingClass(Sema::ParsingClassState state) {
  3354. assert(!ClassStack.empty() && "Mismatched push/pop for class parsing");
  3355. Actions.PopParsingClass(state);
  3356. ParsingClass *Victim = ClassStack.top();
  3357. ClassStack.pop();
  3358. if (Victim->TopLevelClass) {
  3359. // Deallocate all of the nested classes of this class,
  3360. // recursively: we don't need to keep any of this information.
  3361. DeallocateParsedClasses(Victim);
  3362. return;
  3363. }
  3364. assert(!ClassStack.empty() && "Missing top-level class?");
  3365. if (Victim->LateParsedDeclarations.empty()) {
  3366. // The victim is a nested class, but we will not need to perform
  3367. // any processing after the definition of this class since it has
  3368. // no members whose handling was delayed. Therefore, we can just
  3369. // remove this nested class.
  3370. DeallocateParsedClasses(Victim);
  3371. return;
  3372. }
  3373. // This nested class has some members that will need to be processed
  3374. // after the top-level class is completely defined. Therefore, add
  3375. // it to the list of nested classes within its parent.
  3376. assert(getCurScope()->isClassScope() && "Nested class outside of class scope?");
  3377. ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim));
  3378. Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope();
  3379. }
  3380. /// Try to parse an 'identifier' which appears within an attribute-token.
  3381. ///
  3382. /// \return the parsed identifier on success, and 0 if the next token is not an
  3383. /// attribute-token.
  3384. ///
  3385. /// C++11 [dcl.attr.grammar]p3:
  3386. /// If a keyword or an alternative token that satisfies the syntactic
  3387. /// requirements of an identifier is contained in an attribute-token,
  3388. /// it is considered an identifier.
  3389. IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) {
  3390. switch (Tok.getKind()) {
  3391. default:
  3392. // Identifiers and keywords have identifier info attached.
  3393. if (!Tok.isAnnotation()) {
  3394. if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
  3395. Loc = ConsumeToken();
  3396. return II;
  3397. }
  3398. }
  3399. return nullptr;
  3400. case tok::numeric_constant: {
  3401. // If we got a numeric constant, check to see if it comes from a macro that
  3402. // corresponds to the predefined __clang__ macro. If it does, warn the user
  3403. // and recover by pretending they said _Clang instead.
  3404. if (Tok.getLocation().isMacroID()) {
  3405. SmallString<8> ExpansionBuf;
  3406. SourceLocation ExpansionLoc =
  3407. PP.getSourceManager().getExpansionLoc(Tok.getLocation());
  3408. StringRef Spelling = PP.getSpelling(ExpansionLoc, ExpansionBuf);
  3409. if (Spelling == "__clang__") {
  3410. SourceRange TokRange(
  3411. ExpansionLoc,
  3412. PP.getSourceManager().getExpansionLoc(Tok.getEndLoc()));
  3413. Diag(Tok, diag::warn_wrong_clang_attr_namespace)
  3414. << FixItHint::CreateReplacement(TokRange, "_Clang");
  3415. Loc = ConsumeToken();
  3416. return &PP.getIdentifierTable().get("_Clang");
  3417. }
  3418. }
  3419. return nullptr;
  3420. }
  3421. case tok::ampamp: // 'and'
  3422. case tok::pipe: // 'bitor'
  3423. case tok::pipepipe: // 'or'
  3424. case tok::caret: // 'xor'
  3425. case tok::tilde: // 'compl'
  3426. case tok::amp: // 'bitand'
  3427. case tok::ampequal: // 'and_eq'
  3428. case tok::pipeequal: // 'or_eq'
  3429. case tok::caretequal: // 'xor_eq'
  3430. case tok::exclaim: // 'not'
  3431. case tok::exclaimequal: // 'not_eq'
  3432. // Alternative tokens do not have identifier info, but their spelling
  3433. // starts with an alphabetical character.
  3434. SmallString<8> SpellingBuf;
  3435. SourceLocation SpellingLoc =
  3436. PP.getSourceManager().getSpellingLoc(Tok.getLocation());
  3437. StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf);
  3438. if (isLetter(Spelling[0])) {
  3439. Loc = ConsumeToken();
  3440. return &PP.getIdentifierTable().get(Spelling);
  3441. }
  3442. return nullptr;
  3443. }
  3444. }
  3445. static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName,
  3446. IdentifierInfo *ScopeName) {
  3447. switch (ParsedAttr::getKind(AttrName, ScopeName, ParsedAttr::AS_CXX11)) {
  3448. case ParsedAttr::AT_CarriesDependency:
  3449. case ParsedAttr::AT_Deprecated:
  3450. case ParsedAttr::AT_FallThrough:
  3451. case ParsedAttr::AT_CXX11NoReturn:
  3452. case ParsedAttr::AT_NoUniqueAddress:
  3453. return true;
  3454. case ParsedAttr::AT_WarnUnusedResult:
  3455. return !ScopeName && AttrName->getName().equals("nodiscard");
  3456. case ParsedAttr::AT_Unused:
  3457. return !ScopeName && AttrName->getName().equals("maybe_unused");
  3458. default:
  3459. return false;
  3460. }
  3461. }
  3462. /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause.
  3463. ///
  3464. /// [C++11] attribute-argument-clause:
  3465. /// '(' balanced-token-seq ')'
  3466. ///
  3467. /// [C++11] balanced-token-seq:
  3468. /// balanced-token
  3469. /// balanced-token-seq balanced-token
  3470. ///
  3471. /// [C++11] balanced-token:
  3472. /// '(' balanced-token-seq ')'
  3473. /// '[' balanced-token-seq ']'
  3474. /// '{' balanced-token-seq '}'
  3475. /// any token but '(', ')', '[', ']', '{', or '}'
  3476. bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
  3477. SourceLocation AttrNameLoc,
  3478. ParsedAttributes &Attrs,
  3479. SourceLocation *EndLoc,
  3480. IdentifierInfo *ScopeName,
  3481. SourceLocation ScopeLoc) {
  3482. assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list");
  3483. SourceLocation LParenLoc = Tok.getLocation();
  3484. const LangOptions &LO = getLangOpts();
  3485. ParsedAttr::Syntax Syntax =
  3486. LO.CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x;
  3487. // If the attribute isn't known, we will not attempt to parse any
  3488. // arguments.
  3489. if (!hasAttribute(LO.CPlusPlus ? AttrSyntax::CXX : AttrSyntax::C, ScopeName,
  3490. AttrName, getTargetInfo(), getLangOpts())) {
  3491. // Eat the left paren, then skip to the ending right paren.
  3492. ConsumeParen();
  3493. SkipUntil(tok::r_paren);
  3494. return false;
  3495. }
  3496. if (ScopeName && (ScopeName->isStr("gnu") || ScopeName->isStr("__gnu__"))) {
  3497. // GNU-scoped attributes have some special cases to handle GNU-specific
  3498. // behaviors.
  3499. ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName,
  3500. ScopeLoc, Syntax, nullptr);
  3501. return true;
  3502. }
  3503. unsigned NumArgs;
  3504. // Some Clang-scoped attributes have some special parsing behavior.
  3505. if (ScopeName && (ScopeName->isStr("clang") || ScopeName->isStr("_Clang")))
  3506. NumArgs = ParseClangAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc,
  3507. ScopeName, ScopeLoc, Syntax);
  3508. else
  3509. NumArgs =
  3510. ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc,
  3511. ScopeName, ScopeLoc, Syntax);
  3512. if (!Attrs.empty() &&
  3513. IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) {
  3514. ParsedAttr &Attr = Attrs.back();
  3515. // If the attribute is a standard or built-in attribute and we are
  3516. // parsing an argument list, we need to determine whether this attribute
  3517. // was allowed to have an argument list (such as [[deprecated]]), and how
  3518. // many arguments were parsed (so we can diagnose on [[deprecated()]]).
  3519. if (Attr.getMaxArgs() && !NumArgs) {
  3520. // The attribute was allowed to have arguments, but none were provided
  3521. // even though the attribute parsed successfully. This is an error.
  3522. Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName;
  3523. Attr.setInvalid(true);
  3524. } else if (!Attr.getMaxArgs()) {
  3525. // The attribute parsed successfully, but was not allowed to have any
  3526. // arguments. It doesn't matter whether any were provided -- the
  3527. // presence of the argument list (even if empty) is diagnosed.
  3528. Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments)
  3529. << AttrName
  3530. << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc));
  3531. Attr.setInvalid(true);
  3532. }
  3533. }
  3534. return true;
  3535. }
  3536. /// ParseCXX11AttributeSpecifier - Parse a C++11 or C2x attribute-specifier.
  3537. ///
  3538. /// [C++11] attribute-specifier:
  3539. /// '[' '[' attribute-list ']' ']'
  3540. /// alignment-specifier
  3541. ///
  3542. /// [C++11] attribute-list:
  3543. /// attribute[opt]
  3544. /// attribute-list ',' attribute[opt]
  3545. /// attribute '...'
  3546. /// attribute-list ',' attribute '...'
  3547. ///
  3548. /// [C++11] attribute:
  3549. /// attribute-token attribute-argument-clause[opt]
  3550. ///
  3551. /// [C++11] attribute-token:
  3552. /// identifier
  3553. /// attribute-scoped-token
  3554. ///
  3555. /// [C++11] attribute-scoped-token:
  3556. /// attribute-namespace '::' identifier
  3557. ///
  3558. /// [C++11] attribute-namespace:
  3559. /// identifier
  3560. void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
  3561. SourceLocation *endLoc) {
  3562. if (Tok.is(tok::kw_alignas)) {
  3563. Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas);
  3564. ParseAlignmentSpecifier(attrs, endLoc);
  3565. return;
  3566. }
  3567. assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) &&
  3568. "Not a double square bracket attribute list");
  3569. Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute);
  3570. ConsumeBracket();
  3571. ConsumeBracket();
  3572. SourceLocation CommonScopeLoc;
  3573. IdentifierInfo *CommonScopeName = nullptr;
  3574. if (Tok.is(tok::kw_using)) {
  3575. Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
  3576. ? diag::warn_cxx14_compat_using_attribute_ns
  3577. : diag::ext_using_attribute_ns);
  3578. ConsumeToken();
  3579. CommonScopeName = TryParseCXX11AttributeIdentifier(CommonScopeLoc);
  3580. if (!CommonScopeName) {
  3581. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  3582. SkipUntil(tok::r_square, tok::colon, StopBeforeMatch);
  3583. }
  3584. if (!TryConsumeToken(tok::colon) && CommonScopeName)
  3585. Diag(Tok.getLocation(), diag::err_expected) << tok::colon;
  3586. }
  3587. llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs;
  3588. while (Tok.isNot(tok::r_square)) {
  3589. // attribute not present
  3590. if (TryConsumeToken(tok::comma))
  3591. continue;
  3592. SourceLocation ScopeLoc, AttrLoc;
  3593. IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr;
  3594. AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
  3595. if (!AttrName)
  3596. // Break out to the "expected ']'" diagnostic.
  3597. break;
  3598. // scoped attribute
  3599. if (TryConsumeToken(tok::coloncolon)) {
  3600. ScopeName = AttrName;
  3601. ScopeLoc = AttrLoc;
  3602. AttrName = TryParseCXX11AttributeIdentifier(AttrLoc);
  3603. if (!AttrName) {
  3604. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  3605. SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch);
  3606. continue;
  3607. }
  3608. }
  3609. if (CommonScopeName) {
  3610. if (ScopeName) {
  3611. Diag(ScopeLoc, diag::err_using_attribute_ns_conflict)
  3612. << SourceRange(CommonScopeLoc);
  3613. } else {
  3614. ScopeName = CommonScopeName;
  3615. ScopeLoc = CommonScopeLoc;
  3616. }
  3617. }
  3618. bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName);
  3619. bool AttrParsed = false;
  3620. if (StandardAttr &&
  3621. !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second)
  3622. Diag(AttrLoc, diag::err_cxx11_attribute_repeated)
  3623. << AttrName << SourceRange(SeenAttrs[AttrName]);
  3624. // Parse attribute arguments
  3625. if (Tok.is(tok::l_paren))
  3626. AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc,
  3627. ScopeName, ScopeLoc);
  3628. if (!AttrParsed)
  3629. attrs.addNew(
  3630. AttrName,
  3631. SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc),
  3632. ScopeName, ScopeLoc, nullptr, 0,
  3633. getLangOpts().CPlusPlus ? ParsedAttr::AS_CXX11 : ParsedAttr::AS_C2x);
  3634. if (TryConsumeToken(tok::ellipsis))
  3635. Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis)
  3636. << AttrName;
  3637. }
  3638. if (ExpectAndConsume(tok::r_square))
  3639. SkipUntil(tok::r_square);
  3640. if (endLoc)
  3641. *endLoc = Tok.getLocation();
  3642. if (ExpectAndConsume(tok::r_square))
  3643. SkipUntil(tok::r_square);
  3644. }
  3645. /// ParseCXX11Attributes - Parse a C++11 or C2x attribute-specifier-seq.
  3646. ///
  3647. /// attribute-specifier-seq:
  3648. /// attribute-specifier-seq[opt] attribute-specifier
  3649. void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
  3650. SourceLocation *endLoc) {
  3651. assert(standardAttributesAllowed());
  3652. SourceLocation StartLoc = Tok.getLocation(), Loc;
  3653. if (!endLoc)
  3654. endLoc = &Loc;
  3655. do {
  3656. ParseCXX11AttributeSpecifier(attrs, endLoc);
  3657. } while (isCXX11AttributeSpecifier());
  3658. attrs.Range = SourceRange(StartLoc, *endLoc);
  3659. }
  3660. void Parser::DiagnoseAndSkipCXX11Attributes() {
  3661. // Start and end location of an attribute or an attribute list.
  3662. SourceLocation StartLoc = Tok.getLocation();
  3663. SourceLocation EndLoc = SkipCXX11Attributes();
  3664. if (EndLoc.isValid()) {
  3665. SourceRange Range(StartLoc, EndLoc);
  3666. Diag(StartLoc, diag::err_attributes_not_allowed)
  3667. << Range;
  3668. }
  3669. }
  3670. SourceLocation Parser::SkipCXX11Attributes() {
  3671. SourceLocation EndLoc;
  3672. if (!isCXX11AttributeSpecifier())
  3673. return EndLoc;
  3674. do {
  3675. if (Tok.is(tok::l_square)) {
  3676. BalancedDelimiterTracker T(*this, tok::l_square);
  3677. T.consumeOpen();
  3678. T.skipToEnd();
  3679. EndLoc = T.getCloseLocation();
  3680. } else {
  3681. assert(Tok.is(tok::kw_alignas) && "not an attribute specifier");
  3682. ConsumeToken();
  3683. BalancedDelimiterTracker T(*this, tok::l_paren);
  3684. if (!T.consumeOpen())
  3685. T.skipToEnd();
  3686. EndLoc = T.getCloseLocation();
  3687. }
  3688. } while (isCXX11AttributeSpecifier());
  3689. return EndLoc;
  3690. }
  3691. /// Parse uuid() attribute when it appears in a [] Microsoft attribute.
  3692. void Parser::ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs) {
  3693. assert(Tok.is(tok::identifier) && "Not a Microsoft attribute list");
  3694. IdentifierInfo *UuidIdent = Tok.getIdentifierInfo();
  3695. assert(UuidIdent->getName() == "uuid" && "Not a Microsoft attribute list");
  3696. SourceLocation UuidLoc = Tok.getLocation();
  3697. ConsumeToken();
  3698. // Ignore the left paren location for now.
  3699. BalancedDelimiterTracker T(*this, tok::l_paren);
  3700. if (T.consumeOpen()) {
  3701. Diag(Tok, diag::err_expected) << tok::l_paren;
  3702. return;
  3703. }
  3704. ArgsVector ArgExprs;
  3705. if (Tok.is(tok::string_literal)) {
  3706. // Easy case: uuid("...") -- quoted string.
  3707. ExprResult StringResult = ParseStringLiteralExpression();
  3708. if (StringResult.isInvalid())
  3709. return;
  3710. ArgExprs.push_back(StringResult.get());
  3711. } else {
  3712. // something like uuid({000000A0-0000-0000-C000-000000000049}) -- no
  3713. // quotes in the parens. Just append the spelling of all tokens encountered
  3714. // until the closing paren.
  3715. SmallString<42> StrBuffer; // 2 "", 36 bytes UUID, 2 optional {}, 1 nul
  3716. StrBuffer += "\"";
  3717. // Since none of C++'s keywords match [a-f]+, accepting just tok::l_brace,
  3718. // tok::r_brace, tok::minus, tok::identifier (think C000) and
  3719. // tok::numeric_constant (0000) should be enough. But the spelling of the
  3720. // uuid argument is checked later anyways, so there's no harm in accepting
  3721. // almost anything here.
  3722. // cl is very strict about whitespace in this form and errors out if any
  3723. // is present, so check the space flags on the tokens.
  3724. SourceLocation StartLoc = Tok.getLocation();
  3725. while (Tok.isNot(tok::r_paren)) {
  3726. if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
  3727. Diag(Tok, diag::err_attribute_uuid_malformed_guid);
  3728. SkipUntil(tok::r_paren, StopAtSemi);
  3729. return;
  3730. }
  3731. SmallString<16> SpellingBuffer;
  3732. SpellingBuffer.resize(Tok.getLength() + 1);
  3733. bool Invalid = false;
  3734. StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
  3735. if (Invalid) {
  3736. SkipUntil(tok::r_paren, StopAtSemi);
  3737. return;
  3738. }
  3739. StrBuffer += TokSpelling;
  3740. ConsumeAnyToken();
  3741. }
  3742. StrBuffer += "\"";
  3743. if (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()) {
  3744. Diag(Tok, diag::err_attribute_uuid_malformed_guid);
  3745. ConsumeParen();
  3746. return;
  3747. }
  3748. // Pretend the user wrote the appropriate string literal here.
  3749. // ActOnStringLiteral() copies the string data into the literal, so it's
  3750. // ok that the Token points to StrBuffer.
  3751. Token Toks[1];
  3752. Toks[0].startToken();
  3753. Toks[0].setKind(tok::string_literal);
  3754. Toks[0].setLocation(StartLoc);
  3755. Toks[0].setLiteralData(StrBuffer.data());
  3756. Toks[0].setLength(StrBuffer.size());
  3757. StringLiteral *UuidString =
  3758. cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
  3759. ArgExprs.push_back(UuidString);
  3760. }
  3761. if (!T.consumeClose()) {
  3762. Attrs.addNew(UuidIdent, SourceRange(UuidLoc, T.getCloseLocation()), nullptr,
  3763. SourceLocation(), ArgExprs.data(), ArgExprs.size(),
  3764. ParsedAttr::AS_Microsoft);
  3765. }
  3766. }
  3767. /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr]
  3768. ///
  3769. /// [MS] ms-attribute:
  3770. /// '[' token-seq ']'
  3771. ///
  3772. /// [MS] ms-attribute-seq:
  3773. /// ms-attribute[opt]
  3774. /// ms-attribute ms-attribute-seq
  3775. void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs,
  3776. SourceLocation *endLoc) {
  3777. assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list");
  3778. do {
  3779. // FIXME: If this is actually a C++11 attribute, parse it as one.
  3780. BalancedDelimiterTracker T(*this, tok::l_square);
  3781. T.consumeOpen();
  3782. // Skip most ms attributes except for a whitelist.
  3783. while (true) {
  3784. SkipUntil(tok::r_square, tok::identifier, StopAtSemi | StopBeforeMatch);
  3785. if (Tok.isNot(tok::identifier)) // ']', but also eof
  3786. break;
  3787. if (Tok.getIdentifierInfo()->getName() == "uuid")
  3788. ParseMicrosoftUuidAttributeArgs(attrs);
  3789. else
  3790. ConsumeToken();
  3791. }
  3792. T.consumeClose();
  3793. if (endLoc)
  3794. *endLoc = T.getCloseLocation();
  3795. } while (Tok.is(tok::l_square));
  3796. }
  3797. void Parser::ParseMicrosoftIfExistsClassDeclaration(
  3798. DeclSpec::TST TagType, ParsedAttributes &AccessAttrs,
  3799. AccessSpecifier &CurAS) {
  3800. IfExistsCondition Result;
  3801. if (ParseMicrosoftIfExistsCondition(Result))
  3802. return;
  3803. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  3804. if (Braces.consumeOpen()) {
  3805. Diag(Tok, diag::err_expected) << tok::l_brace;
  3806. return;
  3807. }
  3808. switch (Result.Behavior) {
  3809. case IEB_Parse:
  3810. // Parse the declarations below.
  3811. break;
  3812. case IEB_Dependent:
  3813. Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists)
  3814. << Result.IsIfExists;
  3815. // Fall through to skip.
  3816. LLVM_FALLTHROUGH;
  3817. case IEB_Skip:
  3818. Braces.skipToEnd();
  3819. return;
  3820. }
  3821. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
  3822. // __if_exists, __if_not_exists can nest.
  3823. if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) {
  3824. ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType,
  3825. AccessAttrs, CurAS);
  3826. continue;
  3827. }
  3828. // Check for extraneous top-level semicolon.
  3829. if (Tok.is(tok::semi)) {
  3830. ConsumeExtraSemi(InsideStruct, TagType);
  3831. continue;
  3832. }
  3833. AccessSpecifier AS = getAccessSpecifierIfPresent();
  3834. if (AS != AS_none) {
  3835. // Current token is a C++ access specifier.
  3836. CurAS = AS;
  3837. SourceLocation ASLoc = Tok.getLocation();
  3838. ConsumeToken();
  3839. if (Tok.is(tok::colon))
  3840. Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation(),
  3841. ParsedAttributesView{});
  3842. else
  3843. Diag(Tok, diag::err_expected) << tok::colon;
  3844. ConsumeToken();
  3845. continue;
  3846. }
  3847. // Parse all the comma separated declarators.
  3848. ParseCXXClassMemberDeclaration(CurAS, AccessAttrs);
  3849. }
  3850. Braces.consumeClose();
  3851. }