ParseDeclCXX.cpp 180 KB

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