ParseExprCXX.cpp 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041
  1. //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
  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 Expression parsing implementation for C++.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/DeclTemplate.h"
  15. #include "clang/AST/ExprCXX.h"
  16. #include "clang/Basic/PrettyStackTrace.h"
  17. #include "clang/Lex/LiteralSupport.h"
  18. #include "clang/Parse/ParseDiagnostic.h"
  19. #include "clang/Parse/Parser.h"
  20. #include "clang/Parse/RAIIObjectsForParser.h"
  21. #include "clang/Sema/DeclSpec.h"
  22. #include "clang/Sema/ParsedTemplate.h"
  23. #include "clang/Sema/Scope.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include <numeric>
  26. using namespace clang;
  27. static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
  28. switch (Kind) {
  29. // template name
  30. case tok::unknown: return 0;
  31. // casts
  32. case tok::kw_addrspace_cast: return 1;
  33. case tok::kw_const_cast: return 2;
  34. case tok::kw_dynamic_cast: return 3;
  35. case tok::kw_reinterpret_cast: return 4;
  36. case tok::kw_static_cast: return 5;
  37. default:
  38. llvm_unreachable("Unknown type for digraph error message.");
  39. }
  40. }
  41. // Are the two tokens adjacent in the same source file?
  42. bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
  43. SourceManager &SM = PP.getSourceManager();
  44. SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
  45. SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
  46. return FirstEnd == SM.getSpellingLoc(Second.getLocation());
  47. }
  48. // Suggest fixit for "<::" after a cast.
  49. static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
  50. Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
  51. // Pull '<:' and ':' off token stream.
  52. if (!AtDigraph)
  53. PP.Lex(DigraphToken);
  54. PP.Lex(ColonToken);
  55. SourceRange Range;
  56. Range.setBegin(DigraphToken.getLocation());
  57. Range.setEnd(ColonToken.getLocation());
  58. P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
  59. << SelectDigraphErrorMessage(Kind)
  60. << FixItHint::CreateReplacement(Range, "< ::");
  61. // Update token information to reflect their change in token type.
  62. ColonToken.setKind(tok::coloncolon);
  63. ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
  64. ColonToken.setLength(2);
  65. DigraphToken.setKind(tok::less);
  66. DigraphToken.setLength(1);
  67. // Push new tokens back to token stream.
  68. PP.EnterToken(ColonToken, /*IsReinject*/ true);
  69. if (!AtDigraph)
  70. PP.EnterToken(DigraphToken, /*IsReinject*/ true);
  71. }
  72. // Check for '<::' which should be '< ::' instead of '[:' when following
  73. // a template name.
  74. void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
  75. bool EnteringContext,
  76. IdentifierInfo &II, CXXScopeSpec &SS) {
  77. if (!Next.is(tok::l_square) || Next.getLength() != 2)
  78. return;
  79. Token SecondToken = GetLookAheadToken(2);
  80. if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
  81. return;
  82. TemplateTy Template;
  83. UnqualifiedId TemplateName;
  84. TemplateName.setIdentifier(&II, Tok.getLocation());
  85. bool MemberOfUnknownSpecialization;
  86. if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
  87. TemplateName, ObjectType, EnteringContext,
  88. Template, MemberOfUnknownSpecialization))
  89. return;
  90. FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
  91. /*AtDigraph*/false);
  92. }
  93. /// Parse global scope or nested-name-specifier if present.
  94. ///
  95. /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
  96. /// may be preceded by '::'). Note that this routine will not parse ::new or
  97. /// ::delete; it will just leave them in the token stream.
  98. ///
  99. /// '::'[opt] nested-name-specifier
  100. /// '::'
  101. ///
  102. /// nested-name-specifier:
  103. /// type-name '::'
  104. /// namespace-name '::'
  105. /// nested-name-specifier identifier '::'
  106. /// nested-name-specifier 'template'[opt] simple-template-id '::'
  107. ///
  108. ///
  109. /// \param SS the scope specifier that will be set to the parsed
  110. /// nested-name-specifier (or empty)
  111. ///
  112. /// \param ObjectType if this nested-name-specifier is being parsed following
  113. /// the "." or "->" of a member access expression, this parameter provides the
  114. /// type of the object whose members are being accessed.
  115. ///
  116. /// \param ObjectHadErrors if this unqualified-id occurs within a member access
  117. /// expression, indicates whether the original subexpressions had any errors.
  118. /// When true, diagnostics for missing 'template' keyword will be supressed.
  119. ///
  120. /// \param EnteringContext whether we will be entering into the context of
  121. /// the nested-name-specifier after parsing it.
  122. ///
  123. /// \param MayBePseudoDestructor When non-NULL, points to a flag that
  124. /// indicates whether this nested-name-specifier may be part of a
  125. /// pseudo-destructor name. In this case, the flag will be set false
  126. /// if we don't actually end up parsing a destructor name. Moreover,
  127. /// if we do end up determining that we are parsing a destructor name,
  128. /// the last component of the nested-name-specifier is not parsed as
  129. /// part of the scope specifier.
  130. ///
  131. /// \param IsTypename If \c true, this nested-name-specifier is known to be
  132. /// part of a type name. This is used to improve error recovery.
  133. ///
  134. /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
  135. /// filled in with the leading identifier in the last component of the
  136. /// nested-name-specifier, if any.
  137. ///
  138. /// \param OnlyNamespace If true, only considers namespaces in lookup.
  139. ///
  140. ///
  141. /// \returns true if there was an error parsing a scope specifier
  142. bool Parser::ParseOptionalCXXScopeSpecifier(
  143. CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
  144. bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename,
  145. IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration) {
  146. assert(getLangOpts().CPlusPlus &&
  147. "Call sites of this function should be guarded by checking for C++");
  148. if (Tok.is(tok::annot_cxxscope)) {
  149. assert(!LastII && "want last identifier but have already annotated scope");
  150. assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
  151. Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
  152. Tok.getAnnotationRange(),
  153. SS);
  154. ConsumeAnnotationToken();
  155. return false;
  156. }
  157. // Has to happen before any "return false"s in this function.
  158. bool CheckForDestructor = false;
  159. if (MayBePseudoDestructor && *MayBePseudoDestructor) {
  160. CheckForDestructor = true;
  161. *MayBePseudoDestructor = false;
  162. }
  163. if (LastII)
  164. *LastII = nullptr;
  165. bool HasScopeSpecifier = false;
  166. if (Tok.is(tok::coloncolon)) {
  167. // ::new and ::delete aren't nested-name-specifiers.
  168. tok::TokenKind NextKind = NextToken().getKind();
  169. if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
  170. return false;
  171. if (NextKind == tok::l_brace) {
  172. // It is invalid to have :: {, consume the scope qualifier and pretend
  173. // like we never saw it.
  174. Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
  175. } else {
  176. // '::' - Global scope qualifier.
  177. if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
  178. return true;
  179. HasScopeSpecifier = true;
  180. }
  181. }
  182. if (Tok.is(tok::kw___super)) {
  183. SourceLocation SuperLoc = ConsumeToken();
  184. if (!Tok.is(tok::coloncolon)) {
  185. Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
  186. return true;
  187. }
  188. return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
  189. }
  190. if (!HasScopeSpecifier &&
  191. Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
  192. DeclSpec DS(AttrFactory);
  193. SourceLocation DeclLoc = Tok.getLocation();
  194. SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
  195. SourceLocation CCLoc;
  196. // Work around a standard defect: 'decltype(auto)::' is not a
  197. // nested-name-specifier.
  198. if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
  199. !TryConsumeToken(tok::coloncolon, CCLoc)) {
  200. AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
  201. return false;
  202. }
  203. if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
  204. SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
  205. HasScopeSpecifier = true;
  206. }
  207. // Preferred type might change when parsing qualifiers, we need the original.
  208. auto SavedType = PreferredType;
  209. while (true) {
  210. if (HasScopeSpecifier) {
  211. if (Tok.is(tok::code_completion)) {
  212. cutOffParsing();
  213. // Code completion for a nested-name-specifier, where the code
  214. // completion token follows the '::'.
  215. Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
  216. InUsingDeclaration, ObjectType.get(),
  217. SavedType.get(SS.getBeginLoc()));
  218. // Include code completion token into the range of the scope otherwise
  219. // when we try to annotate the scope tokens the dangling code completion
  220. // token will cause assertion in
  221. // Preprocessor::AnnotatePreviousCachedTokens.
  222. SS.setEndLoc(Tok.getLocation());
  223. return true;
  224. }
  225. // C++ [basic.lookup.classref]p5:
  226. // If the qualified-id has the form
  227. //
  228. // ::class-name-or-namespace-name::...
  229. //
  230. // the class-name-or-namespace-name is looked up in global scope as a
  231. // class-name or namespace-name.
  232. //
  233. // To implement this, we clear out the object type as soon as we've
  234. // seen a leading '::' or part of a nested-name-specifier.
  235. ObjectType = nullptr;
  236. }
  237. // nested-name-specifier:
  238. // nested-name-specifier 'template'[opt] simple-template-id '::'
  239. // Parse the optional 'template' keyword, then make sure we have
  240. // 'identifier <' after it.
  241. if (Tok.is(tok::kw_template)) {
  242. // If we don't have a scope specifier or an object type, this isn't a
  243. // nested-name-specifier, since they aren't allowed to start with
  244. // 'template'.
  245. if (!HasScopeSpecifier && !ObjectType)
  246. break;
  247. TentativeParsingAction TPA(*this);
  248. SourceLocation TemplateKWLoc = ConsumeToken();
  249. UnqualifiedId TemplateName;
  250. if (Tok.is(tok::identifier)) {
  251. // Consume the identifier.
  252. TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  253. ConsumeToken();
  254. } else if (Tok.is(tok::kw_operator)) {
  255. // We don't need to actually parse the unqualified-id in this case,
  256. // because a simple-template-id cannot start with 'operator', but
  257. // go ahead and parse it anyway for consistency with the case where
  258. // we already annotated the template-id.
  259. if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
  260. TemplateName)) {
  261. TPA.Commit();
  262. break;
  263. }
  264. if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
  265. TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
  266. Diag(TemplateName.getSourceRange().getBegin(),
  267. diag::err_id_after_template_in_nested_name_spec)
  268. << TemplateName.getSourceRange();
  269. TPA.Commit();
  270. break;
  271. }
  272. } else {
  273. TPA.Revert();
  274. break;
  275. }
  276. // If the next token is not '<', we have a qualified-id that refers
  277. // to a template name, such as T::template apply, but is not a
  278. // template-id.
  279. if (Tok.isNot(tok::less)) {
  280. TPA.Revert();
  281. break;
  282. }
  283. // Commit to parsing the template-id.
  284. TPA.Commit();
  285. TemplateTy Template;
  286. TemplateNameKind TNK = Actions.ActOnTemplateName(
  287. getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
  288. EnteringContext, Template, /*AllowInjectedClassName*/ true);
  289. if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
  290. TemplateName, false))
  291. return true;
  292. continue;
  293. }
  294. if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
  295. // We have
  296. //
  297. // template-id '::'
  298. //
  299. // So we need to check whether the template-id is a simple-template-id of
  300. // the right kind (it should name a type or be dependent), and then
  301. // convert it into a type within the nested-name-specifier.
  302. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  303. if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
  304. *MayBePseudoDestructor = true;
  305. return false;
  306. }
  307. if (LastII)
  308. *LastII = TemplateId->Name;
  309. // Consume the template-id token.
  310. ConsumeAnnotationToken();
  311. assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
  312. SourceLocation CCLoc = ConsumeToken();
  313. HasScopeSpecifier = true;
  314. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  315. TemplateId->NumArgs);
  316. if (TemplateId->isInvalid() ||
  317. Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
  318. SS,
  319. TemplateId->TemplateKWLoc,
  320. TemplateId->Template,
  321. TemplateId->TemplateNameLoc,
  322. TemplateId->LAngleLoc,
  323. TemplateArgsPtr,
  324. TemplateId->RAngleLoc,
  325. CCLoc,
  326. EnteringContext)) {
  327. SourceLocation StartLoc
  328. = SS.getBeginLoc().isValid()? SS.getBeginLoc()
  329. : TemplateId->TemplateNameLoc;
  330. SS.SetInvalid(SourceRange(StartLoc, CCLoc));
  331. }
  332. continue;
  333. }
  334. // The rest of the nested-name-specifier possibilities start with
  335. // tok::identifier.
  336. if (Tok.isNot(tok::identifier))
  337. break;
  338. IdentifierInfo &II = *Tok.getIdentifierInfo();
  339. // nested-name-specifier:
  340. // type-name '::'
  341. // namespace-name '::'
  342. // nested-name-specifier identifier '::'
  343. Token Next = NextToken();
  344. Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
  345. ObjectType);
  346. // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
  347. // and emit a fixit hint for it.
  348. if (Next.is(tok::colon) && !ColonIsSacred) {
  349. if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
  350. EnteringContext) &&
  351. // If the token after the colon isn't an identifier, it's still an
  352. // error, but they probably meant something else strange so don't
  353. // recover like this.
  354. PP.LookAhead(1).is(tok::identifier)) {
  355. Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
  356. << FixItHint::CreateReplacement(Next.getLocation(), "::");
  357. // Recover as if the user wrote '::'.
  358. Next.setKind(tok::coloncolon);
  359. }
  360. }
  361. if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
  362. // It is invalid to have :: {, consume the scope qualifier and pretend
  363. // like we never saw it.
  364. Token Identifier = Tok; // Stash away the identifier.
  365. ConsumeToken(); // Eat the identifier, current token is now '::'.
  366. Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
  367. << tok::identifier;
  368. UnconsumeToken(Identifier); // Stick the identifier back.
  369. Next = NextToken(); // Point Next at the '{' token.
  370. }
  371. if (Next.is(tok::coloncolon)) {
  372. if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
  373. *MayBePseudoDestructor = true;
  374. return false;
  375. }
  376. if (ColonIsSacred) {
  377. const Token &Next2 = GetLookAheadToken(2);
  378. if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
  379. Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
  380. Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
  381. << Next2.getName()
  382. << FixItHint::CreateReplacement(Next.getLocation(), ":");
  383. Token ColonColon;
  384. PP.Lex(ColonColon);
  385. ColonColon.setKind(tok::colon);
  386. PP.EnterToken(ColonColon, /*IsReinject*/ true);
  387. break;
  388. }
  389. }
  390. if (LastII)
  391. *LastII = &II;
  392. // We have an identifier followed by a '::'. Lookup this name
  393. // as the name in a nested-name-specifier.
  394. Token Identifier = Tok;
  395. SourceLocation IdLoc = ConsumeToken();
  396. assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
  397. "NextToken() not working properly!");
  398. Token ColonColon = Tok;
  399. SourceLocation CCLoc = ConsumeToken();
  400. bool IsCorrectedToColon = false;
  401. bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
  402. if (Actions.ActOnCXXNestedNameSpecifier(
  403. getCurScope(), IdInfo, EnteringContext, SS, false,
  404. CorrectionFlagPtr, OnlyNamespace)) {
  405. // Identifier is not recognized as a nested name, but we can have
  406. // mistyped '::' instead of ':'.
  407. if (CorrectionFlagPtr && IsCorrectedToColon) {
  408. ColonColon.setKind(tok::colon);
  409. PP.EnterToken(Tok, /*IsReinject*/ true);
  410. PP.EnterToken(ColonColon, /*IsReinject*/ true);
  411. Tok = Identifier;
  412. break;
  413. }
  414. SS.SetInvalid(SourceRange(IdLoc, CCLoc));
  415. }
  416. HasScopeSpecifier = true;
  417. continue;
  418. }
  419. CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
  420. // nested-name-specifier:
  421. // type-name '<'
  422. if (Next.is(tok::less)) {
  423. TemplateTy Template;
  424. UnqualifiedId TemplateName;
  425. TemplateName.setIdentifier(&II, Tok.getLocation());
  426. bool MemberOfUnknownSpecialization;
  427. if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
  428. /*hasTemplateKeyword=*/false,
  429. TemplateName,
  430. ObjectType,
  431. EnteringContext,
  432. Template,
  433. MemberOfUnknownSpecialization)) {
  434. // If lookup didn't find anything, we treat the name as a template-name
  435. // anyway. C++20 requires this, and in prior language modes it improves
  436. // error recovery. But before we commit to this, check that we actually
  437. // have something that looks like a template-argument-list next.
  438. if (!IsTypename && TNK == TNK_Undeclared_template &&
  439. isTemplateArgumentList(1) == TPResult::False)
  440. break;
  441. // We have found a template name, so annotate this token
  442. // with a template-id annotation. We do not permit the
  443. // template-id to be translated into a type annotation,
  444. // because some clients (e.g., the parsing of class template
  445. // specializations) still want to see the original template-id
  446. // token, and it might not be a type at all (e.g. a concept name in a
  447. // type-constraint).
  448. ConsumeToken();
  449. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
  450. TemplateName, false))
  451. return true;
  452. continue;
  453. }
  454. if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
  455. (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
  456. // If we had errors before, ObjectType can be dependent even without any
  457. // templates. Do not report missing template keyword in that case.
  458. if (!ObjectHadErrors) {
  459. // We have something like t::getAs<T>, where getAs is a
  460. // member of an unknown specialization. However, this will only
  461. // parse correctly as a template, so suggest the keyword 'template'
  462. // before 'getAs' and treat this as a dependent template name.
  463. unsigned DiagID = diag::err_missing_dependent_template_keyword;
  464. if (getLangOpts().MicrosoftExt)
  465. DiagID = diag::warn_missing_dependent_template_keyword;
  466. Diag(Tok.getLocation(), DiagID)
  467. << II.getName()
  468. << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
  469. }
  470. SourceLocation TemplateNameLoc = ConsumeToken();
  471. TemplateNameKind TNK = Actions.ActOnTemplateName(
  472. getCurScope(), SS, TemplateNameLoc, TemplateName, ObjectType,
  473. EnteringContext, Template, /*AllowInjectedClassName*/ true);
  474. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
  475. TemplateName, false))
  476. return true;
  477. continue;
  478. }
  479. }
  480. // We don't have any tokens that form the beginning of a
  481. // nested-name-specifier, so we're done.
  482. break;
  483. }
  484. // Even if we didn't see any pieces of a nested-name-specifier, we
  485. // still check whether there is a tilde in this position, which
  486. // indicates a potential pseudo-destructor.
  487. if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde))
  488. *MayBePseudoDestructor = true;
  489. return false;
  490. }
  491. ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
  492. bool isAddressOfOperand,
  493. Token &Replacement) {
  494. ExprResult E;
  495. // We may have already annotated this id-expression.
  496. switch (Tok.getKind()) {
  497. case tok::annot_non_type: {
  498. NamedDecl *ND = getNonTypeAnnotation(Tok);
  499. SourceLocation Loc = ConsumeAnnotationToken();
  500. E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
  501. break;
  502. }
  503. case tok::annot_non_type_dependent: {
  504. IdentifierInfo *II = getIdentifierAnnotation(Tok);
  505. SourceLocation Loc = ConsumeAnnotationToken();
  506. // This is only the direct operand of an & operator if it is not
  507. // followed by a postfix-expression suffix.
  508. if (isAddressOfOperand && isPostfixExpressionSuffixStart())
  509. isAddressOfOperand = false;
  510. E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
  511. isAddressOfOperand);
  512. break;
  513. }
  514. case tok::annot_non_type_undeclared: {
  515. assert(SS.isEmpty() &&
  516. "undeclared non-type annotation should be unqualified");
  517. IdentifierInfo *II = getIdentifierAnnotation(Tok);
  518. SourceLocation Loc = ConsumeAnnotationToken();
  519. E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
  520. break;
  521. }
  522. default:
  523. SourceLocation TemplateKWLoc;
  524. UnqualifiedId Name;
  525. if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
  526. /*ObjectHadErrors=*/false,
  527. /*EnteringContext=*/false,
  528. /*AllowDestructorName=*/false,
  529. /*AllowConstructorName=*/false,
  530. /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name))
  531. return ExprError();
  532. // This is only the direct operand of an & operator if it is not
  533. // followed by a postfix-expression suffix.
  534. if (isAddressOfOperand && isPostfixExpressionSuffixStart())
  535. isAddressOfOperand = false;
  536. E = Actions.ActOnIdExpression(
  537. getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
  538. isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
  539. &Replacement);
  540. break;
  541. }
  542. if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
  543. checkPotentialAngleBracket(E);
  544. return E;
  545. }
  546. /// ParseCXXIdExpression - Handle id-expression.
  547. ///
  548. /// id-expression:
  549. /// unqualified-id
  550. /// qualified-id
  551. ///
  552. /// qualified-id:
  553. /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
  554. /// '::' identifier
  555. /// '::' operator-function-id
  556. /// '::' template-id
  557. ///
  558. /// NOTE: The standard specifies that, for qualified-id, the parser does not
  559. /// expect:
  560. ///
  561. /// '::' conversion-function-id
  562. /// '::' '~' class-name
  563. ///
  564. /// This may cause a slight inconsistency on diagnostics:
  565. ///
  566. /// class C {};
  567. /// namespace A {}
  568. /// void f() {
  569. /// :: A :: ~ C(); // Some Sema error about using destructor with a
  570. /// // namespace.
  571. /// :: ~ C(); // Some Parser error like 'unexpected ~'.
  572. /// }
  573. ///
  574. /// We simplify the parser a bit and make it work like:
  575. ///
  576. /// qualified-id:
  577. /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
  578. /// '::' unqualified-id
  579. ///
  580. /// That way Sema can handle and report similar errors for namespaces and the
  581. /// global scope.
  582. ///
  583. /// The isAddressOfOperand parameter indicates that this id-expression is a
  584. /// direct operand of the address-of operator. This is, besides member contexts,
  585. /// the only place where a qualified-id naming a non-static class member may
  586. /// appear.
  587. ///
  588. ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
  589. // qualified-id:
  590. // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
  591. // '::' unqualified-id
  592. //
  593. CXXScopeSpec SS;
  594. ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
  595. /*ObjectHasErrors=*/false,
  596. /*EnteringContext=*/false);
  597. Token Replacement;
  598. ExprResult Result =
  599. tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
  600. if (Result.isUnset()) {
  601. // If the ExprResult is valid but null, then typo correction suggested a
  602. // keyword replacement that needs to be reparsed.
  603. UnconsumeToken(Replacement);
  604. Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
  605. }
  606. assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
  607. "for a previous keyword suggestion");
  608. return Result;
  609. }
  610. /// ParseLambdaExpression - Parse a C++11 lambda expression.
  611. ///
  612. /// lambda-expression:
  613. /// lambda-introducer lambda-declarator compound-statement
  614. /// lambda-introducer '<' template-parameter-list '>'
  615. /// requires-clause[opt] lambda-declarator compound-statement
  616. ///
  617. /// lambda-introducer:
  618. /// '[' lambda-capture[opt] ']'
  619. ///
  620. /// lambda-capture:
  621. /// capture-default
  622. /// capture-list
  623. /// capture-default ',' capture-list
  624. ///
  625. /// capture-default:
  626. /// '&'
  627. /// '='
  628. ///
  629. /// capture-list:
  630. /// capture
  631. /// capture-list ',' capture
  632. ///
  633. /// capture:
  634. /// simple-capture
  635. /// init-capture [C++1y]
  636. ///
  637. /// simple-capture:
  638. /// identifier
  639. /// '&' identifier
  640. /// 'this'
  641. ///
  642. /// init-capture: [C++1y]
  643. /// identifier initializer
  644. /// '&' identifier initializer
  645. ///
  646. /// lambda-declarator:
  647. /// lambda-specifiers [C++2b]
  648. /// '(' parameter-declaration-clause ')' lambda-specifiers
  649. /// requires-clause[opt]
  650. ///
  651. /// lambda-specifiers:
  652. /// decl-specifier-seq[opt] noexcept-specifier[opt]
  653. /// attribute-specifier-seq[opt] trailing-return-type[opt]
  654. ///
  655. ExprResult Parser::ParseLambdaExpression() {
  656. // Parse lambda-introducer.
  657. LambdaIntroducer Intro;
  658. if (ParseLambdaIntroducer(Intro)) {
  659. SkipUntil(tok::r_square, StopAtSemi);
  660. SkipUntil(tok::l_brace, StopAtSemi);
  661. SkipUntil(tok::r_brace, StopAtSemi);
  662. return ExprError();
  663. }
  664. return ParseLambdaExpressionAfterIntroducer(Intro);
  665. }
  666. /// Use lookahead and potentially tentative parsing to determine if we are
  667. /// looking at a C++11 lambda expression, and parse it if we are.
  668. ///
  669. /// If we are not looking at a lambda expression, returns ExprError().
  670. ExprResult Parser::TryParseLambdaExpression() {
  671. assert(getLangOpts().CPlusPlus11
  672. && Tok.is(tok::l_square)
  673. && "Not at the start of a possible lambda expression.");
  674. const Token Next = NextToken();
  675. if (Next.is(tok::eof)) // Nothing else to lookup here...
  676. return ExprEmpty();
  677. const Token After = GetLookAheadToken(2);
  678. // If lookahead indicates this is a lambda...
  679. if (Next.is(tok::r_square) || // []
  680. Next.is(tok::equal) || // [=
  681. (Next.is(tok::amp) && // [&] or [&,
  682. After.isOneOf(tok::r_square, tok::comma)) ||
  683. (Next.is(tok::identifier) && // [identifier]
  684. After.is(tok::r_square)) ||
  685. Next.is(tok::ellipsis)) { // [...
  686. return ParseLambdaExpression();
  687. }
  688. // If lookahead indicates an ObjC message send...
  689. // [identifier identifier
  690. if (Next.is(tok::identifier) && After.is(tok::identifier))
  691. return ExprEmpty();
  692. // Here, we're stuck: lambda introducers and Objective-C message sends are
  693. // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
  694. // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
  695. // writing two routines to parse a lambda introducer, just try to parse
  696. // a lambda introducer first, and fall back if that fails.
  697. LambdaIntroducer Intro;
  698. {
  699. TentativeParsingAction TPA(*this);
  700. LambdaIntroducerTentativeParse Tentative;
  701. if (ParseLambdaIntroducer(Intro, &Tentative)) {
  702. TPA.Commit();
  703. return ExprError();
  704. }
  705. switch (Tentative) {
  706. case LambdaIntroducerTentativeParse::Success:
  707. TPA.Commit();
  708. break;
  709. case LambdaIntroducerTentativeParse::Incomplete:
  710. // Didn't fully parse the lambda-introducer, try again with a
  711. // non-tentative parse.
  712. TPA.Revert();
  713. Intro = LambdaIntroducer();
  714. if (ParseLambdaIntroducer(Intro))
  715. return ExprError();
  716. break;
  717. case LambdaIntroducerTentativeParse::MessageSend:
  718. case LambdaIntroducerTentativeParse::Invalid:
  719. // Not a lambda-introducer, might be a message send.
  720. TPA.Revert();
  721. return ExprEmpty();
  722. }
  723. }
  724. return ParseLambdaExpressionAfterIntroducer(Intro);
  725. }
  726. /// Parse a lambda introducer.
  727. /// \param Intro A LambdaIntroducer filled in with information about the
  728. /// contents of the lambda-introducer.
  729. /// \param Tentative If non-null, we are disambiguating between a
  730. /// lambda-introducer and some other construct. In this mode, we do not
  731. /// produce any diagnostics or take any other irreversible action unless
  732. /// we're sure that this is a lambda-expression.
  733. /// \return \c true if parsing (or disambiguation) failed with a diagnostic and
  734. /// the caller should bail out / recover.
  735. bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
  736. LambdaIntroducerTentativeParse *Tentative) {
  737. if (Tentative)
  738. *Tentative = LambdaIntroducerTentativeParse::Success;
  739. assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
  740. BalancedDelimiterTracker T(*this, tok::l_square);
  741. T.consumeOpen();
  742. Intro.Range.setBegin(T.getOpenLocation());
  743. bool First = true;
  744. // Produce a diagnostic if we're not tentatively parsing; otherwise track
  745. // that our parse has failed.
  746. auto Invalid = [&](llvm::function_ref<void()> Action) {
  747. if (Tentative) {
  748. *Tentative = LambdaIntroducerTentativeParse::Invalid;
  749. return false;
  750. }
  751. Action();
  752. return true;
  753. };
  754. // Perform some irreversible action if this is a non-tentative parse;
  755. // otherwise note that our actions were incomplete.
  756. auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
  757. if (Tentative)
  758. *Tentative = LambdaIntroducerTentativeParse::Incomplete;
  759. else
  760. Action();
  761. };
  762. // Parse capture-default.
  763. if (Tok.is(tok::amp) &&
  764. (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
  765. Intro.Default = LCD_ByRef;
  766. Intro.DefaultLoc = ConsumeToken();
  767. First = false;
  768. if (!Tok.getIdentifierInfo()) {
  769. // This can only be a lambda; no need for tentative parsing any more.
  770. // '[[and]]' can still be an attribute, though.
  771. Tentative = nullptr;
  772. }
  773. } else if (Tok.is(tok::equal)) {
  774. Intro.Default = LCD_ByCopy;
  775. Intro.DefaultLoc = ConsumeToken();
  776. First = false;
  777. Tentative = nullptr;
  778. }
  779. while (Tok.isNot(tok::r_square)) {
  780. if (!First) {
  781. if (Tok.isNot(tok::comma)) {
  782. // Provide a completion for a lambda introducer here. Except
  783. // in Objective-C, where this is Almost Surely meant to be a message
  784. // send. In that case, fail here and let the ObjC message
  785. // expression parser perform the completion.
  786. if (Tok.is(tok::code_completion) &&
  787. !(getLangOpts().ObjC && Tentative)) {
  788. cutOffParsing();
  789. Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
  790. /*AfterAmpersand=*/false);
  791. break;
  792. }
  793. return Invalid([&] {
  794. Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
  795. });
  796. }
  797. ConsumeToken();
  798. }
  799. if (Tok.is(tok::code_completion)) {
  800. cutOffParsing();
  801. // If we're in Objective-C++ and we have a bare '[', then this is more
  802. // likely to be a message receiver.
  803. if (getLangOpts().ObjC && Tentative && First)
  804. Actions.CodeCompleteObjCMessageReceiver(getCurScope());
  805. else
  806. Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
  807. /*AfterAmpersand=*/false);
  808. break;
  809. }
  810. First = false;
  811. // Parse capture.
  812. LambdaCaptureKind Kind = LCK_ByCopy;
  813. LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
  814. SourceLocation Loc;
  815. IdentifierInfo *Id = nullptr;
  816. SourceLocation EllipsisLocs[4];
  817. ExprResult Init;
  818. SourceLocation LocStart = Tok.getLocation();
  819. if (Tok.is(tok::star)) {
  820. Loc = ConsumeToken();
  821. if (Tok.is(tok::kw_this)) {
  822. ConsumeToken();
  823. Kind = LCK_StarThis;
  824. } else {
  825. return Invalid([&] {
  826. Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
  827. });
  828. }
  829. } else if (Tok.is(tok::kw_this)) {
  830. Kind = LCK_This;
  831. Loc = ConsumeToken();
  832. } else if (Tok.isOneOf(tok::amp, tok::equal) &&
  833. NextToken().isOneOf(tok::comma, tok::r_square) &&
  834. Intro.Default == LCD_None) {
  835. // We have a lone "&" or "=" which is either a misplaced capture-default
  836. // or the start of a capture (in the "&" case) with the rest of the
  837. // capture missing. Both are an error but a misplaced capture-default
  838. // is more likely if we don't already have a capture default.
  839. return Invalid(
  840. [&] { Diag(Tok.getLocation(), diag::err_capture_default_first); });
  841. } else {
  842. TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
  843. if (Tok.is(tok::amp)) {
  844. Kind = LCK_ByRef;
  845. ConsumeToken();
  846. if (Tok.is(tok::code_completion)) {
  847. cutOffParsing();
  848. Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
  849. /*AfterAmpersand=*/true);
  850. break;
  851. }
  852. }
  853. TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
  854. if (Tok.is(tok::identifier)) {
  855. Id = Tok.getIdentifierInfo();
  856. Loc = ConsumeToken();
  857. } else if (Tok.is(tok::kw_this)) {
  858. return Invalid([&] {
  859. // FIXME: Suggest a fixit here.
  860. Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
  861. });
  862. } else {
  863. return Invalid([&] {
  864. Diag(Tok.getLocation(), diag::err_expected_capture);
  865. });
  866. }
  867. TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
  868. if (Tok.is(tok::l_paren)) {
  869. BalancedDelimiterTracker Parens(*this, tok::l_paren);
  870. Parens.consumeOpen();
  871. InitKind = LambdaCaptureInitKind::DirectInit;
  872. ExprVector Exprs;
  873. CommaLocsTy Commas;
  874. if (Tentative) {
  875. Parens.skipToEnd();
  876. *Tentative = LambdaIntroducerTentativeParse::Incomplete;
  877. } else if (ParseExpressionList(Exprs, Commas)) {
  878. Parens.skipToEnd();
  879. Init = ExprError();
  880. } else {
  881. Parens.consumeClose();
  882. Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
  883. Parens.getCloseLocation(),
  884. Exprs);
  885. }
  886. } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
  887. // Each lambda init-capture forms its own full expression, which clears
  888. // Actions.MaybeODRUseExprs. So create an expression evaluation context
  889. // to save the necessary state, and restore it later.
  890. EnterExpressionEvaluationContext EC(
  891. Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
  892. if (TryConsumeToken(tok::equal))
  893. InitKind = LambdaCaptureInitKind::CopyInit;
  894. else
  895. InitKind = LambdaCaptureInitKind::ListInit;
  896. if (!Tentative) {
  897. Init = ParseInitializer();
  898. } else if (Tok.is(tok::l_brace)) {
  899. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  900. Braces.consumeOpen();
  901. Braces.skipToEnd();
  902. *Tentative = LambdaIntroducerTentativeParse::Incomplete;
  903. } else {
  904. // We're disambiguating this:
  905. //
  906. // [..., x = expr
  907. //
  908. // We need to find the end of the following expression in order to
  909. // determine whether this is an Obj-C message send's receiver, a
  910. // C99 designator, or a lambda init-capture.
  911. //
  912. // Parse the expression to find where it ends, and annotate it back
  913. // onto the tokens. We would have parsed this expression the same way
  914. // in either case: both the RHS of an init-capture and the RHS of an
  915. // assignment expression are parsed as an initializer-clause, and in
  916. // neither case can anything be added to the scope between the '[' and
  917. // here.
  918. //
  919. // FIXME: This is horrible. Adding a mechanism to skip an expression
  920. // would be much cleaner.
  921. // FIXME: If there is a ',' before the next ']' or ':', we can skip to
  922. // that instead. (And if we see a ':' with no matching '?', we can
  923. // classify this as an Obj-C message send.)
  924. SourceLocation StartLoc = Tok.getLocation();
  925. InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
  926. Init = ParseInitializer();
  927. if (!Init.isInvalid())
  928. Init = Actions.CorrectDelayedTyposInExpr(Init.get());
  929. if (Tok.getLocation() != StartLoc) {
  930. // Back out the lexing of the token after the initializer.
  931. PP.RevertCachedTokens(1);
  932. // Replace the consumed tokens with an appropriate annotation.
  933. Tok.setLocation(StartLoc);
  934. Tok.setKind(tok::annot_primary_expr);
  935. setExprAnnotation(Tok, Init);
  936. Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
  937. PP.AnnotateCachedTokens(Tok);
  938. // Consume the annotated initializer.
  939. ConsumeAnnotationToken();
  940. }
  941. }
  942. }
  943. TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
  944. }
  945. // Check if this is a message send before we act on a possible init-capture.
  946. if (Tentative && Tok.is(tok::identifier) &&
  947. NextToken().isOneOf(tok::colon, tok::r_square)) {
  948. // This can only be a message send. We're done with disambiguation.
  949. *Tentative = LambdaIntroducerTentativeParse::MessageSend;
  950. return false;
  951. }
  952. // Ensure that any ellipsis was in the right place.
  953. SourceLocation EllipsisLoc;
  954. if (llvm::any_of(EllipsisLocs,
  955. [](SourceLocation Loc) { return Loc.isValid(); })) {
  956. // The '...' should appear before the identifier in an init-capture, and
  957. // after the identifier otherwise.
  958. bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
  959. SourceLocation *ExpectedEllipsisLoc =
  960. !InitCapture ? &EllipsisLocs[2] :
  961. Kind == LCK_ByRef ? &EllipsisLocs[1] :
  962. &EllipsisLocs[0];
  963. EllipsisLoc = *ExpectedEllipsisLoc;
  964. unsigned DiagID = 0;
  965. if (EllipsisLoc.isInvalid()) {
  966. DiagID = diag::err_lambda_capture_misplaced_ellipsis;
  967. for (SourceLocation Loc : EllipsisLocs) {
  968. if (Loc.isValid())
  969. EllipsisLoc = Loc;
  970. }
  971. } else {
  972. unsigned NumEllipses = std::accumulate(
  973. std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
  974. [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
  975. if (NumEllipses > 1)
  976. DiagID = diag::err_lambda_capture_multiple_ellipses;
  977. }
  978. if (DiagID) {
  979. NonTentativeAction([&] {
  980. // Point the diagnostic at the first misplaced ellipsis.
  981. SourceLocation DiagLoc;
  982. for (SourceLocation &Loc : EllipsisLocs) {
  983. if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
  984. DiagLoc = Loc;
  985. break;
  986. }
  987. }
  988. assert(DiagLoc.isValid() && "no location for diagnostic");
  989. // Issue the diagnostic and produce fixits showing where the ellipsis
  990. // should have been written.
  991. auto &&D = Diag(DiagLoc, DiagID);
  992. if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
  993. SourceLocation ExpectedLoc =
  994. InitCapture ? Loc
  995. : Lexer::getLocForEndOfToken(
  996. Loc, 0, PP.getSourceManager(), getLangOpts());
  997. D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
  998. }
  999. for (SourceLocation &Loc : EllipsisLocs) {
  1000. if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
  1001. D << FixItHint::CreateRemoval(Loc);
  1002. }
  1003. });
  1004. }
  1005. }
  1006. // Process the init-capture initializers now rather than delaying until we
  1007. // form the lambda-expression so that they can be handled in the context
  1008. // enclosing the lambda-expression, rather than in the context of the
  1009. // lambda-expression itself.
  1010. ParsedType InitCaptureType;
  1011. if (Init.isUsable())
  1012. Init = Actions.CorrectDelayedTyposInExpr(Init.get());
  1013. if (Init.isUsable()) {
  1014. NonTentativeAction([&] {
  1015. // Get the pointer and store it in an lvalue, so we can use it as an
  1016. // out argument.
  1017. Expr *InitExpr = Init.get();
  1018. // This performs any lvalue-to-rvalue conversions if necessary, which
  1019. // can affect what gets captured in the containing decl-context.
  1020. InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
  1021. Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
  1022. Init = InitExpr;
  1023. });
  1024. }
  1025. SourceLocation LocEnd = PrevTokLocation;
  1026. Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
  1027. InitCaptureType, SourceRange(LocStart, LocEnd));
  1028. }
  1029. T.consumeClose();
  1030. Intro.Range.setEnd(T.getCloseLocation());
  1031. return false;
  1032. }
  1033. static void tryConsumeLambdaSpecifierToken(Parser &P,
  1034. SourceLocation &MutableLoc,
  1035. SourceLocation &ConstexprLoc,
  1036. SourceLocation &ConstevalLoc,
  1037. SourceLocation &DeclEndLoc) {
  1038. assert(MutableLoc.isInvalid());
  1039. assert(ConstexprLoc.isInvalid());
  1040. // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
  1041. // to the final of those locations. Emit an error if we have multiple
  1042. // copies of those keywords and recover.
  1043. while (true) {
  1044. switch (P.getCurToken().getKind()) {
  1045. case tok::kw_mutable: {
  1046. if (MutableLoc.isValid()) {
  1047. P.Diag(P.getCurToken().getLocation(),
  1048. diag::err_lambda_decl_specifier_repeated)
  1049. << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
  1050. }
  1051. MutableLoc = P.ConsumeToken();
  1052. DeclEndLoc = MutableLoc;
  1053. break /*switch*/;
  1054. }
  1055. case tok::kw_constexpr:
  1056. if (ConstexprLoc.isValid()) {
  1057. P.Diag(P.getCurToken().getLocation(),
  1058. diag::err_lambda_decl_specifier_repeated)
  1059. << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
  1060. }
  1061. ConstexprLoc = P.ConsumeToken();
  1062. DeclEndLoc = ConstexprLoc;
  1063. break /*switch*/;
  1064. case tok::kw_consteval:
  1065. if (ConstevalLoc.isValid()) {
  1066. P.Diag(P.getCurToken().getLocation(),
  1067. diag::err_lambda_decl_specifier_repeated)
  1068. << 2 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
  1069. }
  1070. ConstevalLoc = P.ConsumeToken();
  1071. DeclEndLoc = ConstevalLoc;
  1072. break /*switch*/;
  1073. default:
  1074. return;
  1075. }
  1076. }
  1077. }
  1078. static void
  1079. addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
  1080. DeclSpec &DS) {
  1081. if (ConstexprLoc.isValid()) {
  1082. P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
  1083. ? diag::ext_constexpr_on_lambda_cxx17
  1084. : diag::warn_cxx14_compat_constexpr_on_lambda);
  1085. const char *PrevSpec = nullptr;
  1086. unsigned DiagID = 0;
  1087. DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, ConstexprLoc, PrevSpec,
  1088. DiagID);
  1089. assert(PrevSpec == nullptr && DiagID == 0 &&
  1090. "Constexpr cannot have been set previously!");
  1091. }
  1092. }
  1093. static void addConstevalToLambdaDeclSpecifier(Parser &P,
  1094. SourceLocation ConstevalLoc,
  1095. DeclSpec &DS) {
  1096. if (ConstevalLoc.isValid()) {
  1097. P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
  1098. const char *PrevSpec = nullptr;
  1099. unsigned DiagID = 0;
  1100. DS.SetConstexprSpec(ConstexprSpecKind::Consteval, ConstevalLoc, PrevSpec,
  1101. DiagID);
  1102. if (DiagID != 0)
  1103. P.Diag(ConstevalLoc, DiagID) << PrevSpec;
  1104. }
  1105. }
  1106. /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
  1107. /// expression.
  1108. ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
  1109. LambdaIntroducer &Intro) {
  1110. SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
  1111. Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
  1112. PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
  1113. "lambda expression parsing");
  1114. // FIXME: Call into Actions to add any init-capture declarations to the
  1115. // scope while parsing the lambda-declarator and compound-statement.
  1116. // Parse lambda-declarator[opt].
  1117. DeclSpec DS(AttrFactory);
  1118. Declarator D(DS, DeclaratorContext::LambdaExpr);
  1119. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
  1120. Actions.PushLambdaScope();
  1121. ParsedAttributes Attr(AttrFactory);
  1122. if (getLangOpts().CUDA) {
  1123. // In CUDA code, GNU attributes are allowed to appear immediately after the
  1124. // "[...]", even if there is no "(...)" before the lambda body.
  1125. MaybeParseGNUAttributes(D);
  1126. }
  1127. // Helper to emit a warning if we see a CUDA host/device/global attribute
  1128. // after '(...)'. nvcc doesn't accept this.
  1129. auto WarnIfHasCUDATargetAttr = [&] {
  1130. if (getLangOpts().CUDA)
  1131. for (const ParsedAttr &A : Attr)
  1132. if (A.getKind() == ParsedAttr::AT_CUDADevice ||
  1133. A.getKind() == ParsedAttr::AT_CUDAHost ||
  1134. A.getKind() == ParsedAttr::AT_CUDAGlobal)
  1135. Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
  1136. << A.getAttrName()->getName();
  1137. };
  1138. MultiParseScope TemplateParamScope(*this);
  1139. if (Tok.is(tok::less)) {
  1140. Diag(Tok, getLangOpts().CPlusPlus20
  1141. ? diag::warn_cxx17_compat_lambda_template_parameter_list
  1142. : diag::ext_lambda_template_parameter_list);
  1143. SmallVector<NamedDecl*, 4> TemplateParams;
  1144. SourceLocation LAngleLoc, RAngleLoc;
  1145. if (ParseTemplateParameters(TemplateParamScope,
  1146. CurTemplateDepthTracker.getDepth(),
  1147. TemplateParams, LAngleLoc, RAngleLoc)) {
  1148. Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
  1149. return ExprError();
  1150. }
  1151. if (TemplateParams.empty()) {
  1152. Diag(RAngleLoc,
  1153. diag::err_lambda_template_parameter_list_empty);
  1154. } else {
  1155. ExprResult RequiresClause;
  1156. if (TryConsumeToken(tok::kw_requires)) {
  1157. RequiresClause =
  1158. Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
  1159. /*IsTrailingRequiresClause=*/false));
  1160. if (RequiresClause.isInvalid())
  1161. SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch);
  1162. }
  1163. Actions.ActOnLambdaExplicitTemplateParameterList(
  1164. LAngleLoc, TemplateParams, RAngleLoc, RequiresClause);
  1165. ++CurTemplateDepthTracker;
  1166. }
  1167. }
  1168. // Implement WG21 P2173, which allows attributes immediately before the
  1169. // lambda declarator and applies them to the corresponding function operator
  1170. // or operator template declaration. We accept this as a conforming extension
  1171. // in all language modes that support lambdas.
  1172. if (isCXX11AttributeSpecifier()) {
  1173. Diag(Tok, getLangOpts().CPlusPlus2b
  1174. ? diag::warn_cxx20_compat_decl_attrs_on_lambda
  1175. : diag::ext_decl_attrs_on_lambda);
  1176. MaybeParseCXX11Attributes(D);
  1177. }
  1178. TypeResult TrailingReturnType;
  1179. SourceLocation TrailingReturnTypeLoc;
  1180. auto ParseLambdaSpecifiers =
  1181. [&](SourceLocation LParenLoc, SourceLocation RParenLoc,
  1182. MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo,
  1183. SourceLocation EllipsisLoc) {
  1184. SourceLocation DeclEndLoc = RParenLoc;
  1185. // GNU-style attributes must be parsed before the mutable specifier to
  1186. // be compatible with GCC. MSVC-style attributes must be parsed before
  1187. // the mutable specifier to be compatible with MSVC.
  1188. MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attr);
  1189. // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update
  1190. // the DeclEndLoc.
  1191. SourceLocation MutableLoc;
  1192. SourceLocation ConstexprLoc;
  1193. SourceLocation ConstevalLoc;
  1194. tryConsumeLambdaSpecifierToken(*this, MutableLoc, ConstexprLoc,
  1195. ConstevalLoc, DeclEndLoc);
  1196. addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
  1197. addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
  1198. // Parse exception-specification[opt].
  1199. ExceptionSpecificationType ESpecType = EST_None;
  1200. SourceRange ESpecRange;
  1201. SmallVector<ParsedType, 2> DynamicExceptions;
  1202. SmallVector<SourceRange, 2> DynamicExceptionRanges;
  1203. ExprResult NoexceptExpr;
  1204. CachedTokens *ExceptionSpecTokens;
  1205. ESpecType = tryParseExceptionSpecification(
  1206. /*Delayed=*/false, ESpecRange, DynamicExceptions,
  1207. DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens);
  1208. if (ESpecType != EST_None)
  1209. DeclEndLoc = ESpecRange.getEnd();
  1210. // Parse attribute-specifier[opt].
  1211. MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
  1212. // Parse OpenCL addr space attribute.
  1213. if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
  1214. tok::kw___constant, tok::kw___generic)) {
  1215. ParseOpenCLQualifiers(DS.getAttributes());
  1216. ConsumeToken();
  1217. }
  1218. SourceLocation FunLocalRangeEnd = DeclEndLoc;
  1219. // Parse trailing-return-type[opt].
  1220. if (Tok.is(tok::arrow)) {
  1221. FunLocalRangeEnd = Tok.getLocation();
  1222. SourceRange Range;
  1223. TrailingReturnType = ParseTrailingReturnType(
  1224. Range, /*MayBeFollowedByDirectInit*/ false);
  1225. TrailingReturnTypeLoc = Range.getBegin();
  1226. if (Range.getEnd().isValid())
  1227. DeclEndLoc = Range.getEnd();
  1228. }
  1229. SourceLocation NoLoc;
  1230. D.AddTypeInfo(
  1231. DeclaratorChunk::getFunction(
  1232. /*HasProto=*/true,
  1233. /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
  1234. ParamInfo.size(), EllipsisLoc, RParenLoc,
  1235. /*RefQualifierIsLvalueRef=*/true,
  1236. /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType, ESpecRange,
  1237. DynamicExceptions.data(), DynamicExceptionRanges.data(),
  1238. DynamicExceptions.size(),
  1239. NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
  1240. /*ExceptionSpecTokens*/ nullptr,
  1241. /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
  1242. TrailingReturnType, TrailingReturnTypeLoc, &DS),
  1243. std::move(Attr), DeclEndLoc);
  1244. };
  1245. if (Tok.is(tok::l_paren)) {
  1246. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
  1247. Scope::FunctionDeclarationScope |
  1248. Scope::DeclScope);
  1249. BalancedDelimiterTracker T(*this, tok::l_paren);
  1250. T.consumeOpen();
  1251. SourceLocation LParenLoc = T.getOpenLocation();
  1252. // Parse parameter-declaration-clause.
  1253. SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
  1254. SourceLocation EllipsisLoc;
  1255. if (Tok.isNot(tok::r_paren)) {
  1256. Actions.RecordParsingTemplateParameterDepth(
  1257. CurTemplateDepthTracker.getOriginalDepth());
  1258. ParseParameterDeclarationClause(D.getContext(), Attr, ParamInfo,
  1259. EllipsisLoc);
  1260. // For a generic lambda, each 'auto' within the parameter declaration
  1261. // clause creates a template type parameter, so increment the depth.
  1262. // If we've parsed any explicit template parameters, then the depth will
  1263. // have already been incremented. So we make sure that at most a single
  1264. // depth level is added.
  1265. if (Actions.getCurGenericLambda())
  1266. CurTemplateDepthTracker.setAddedDepth(1);
  1267. }
  1268. T.consumeClose();
  1269. // Parse lambda-specifiers.
  1270. ParseLambdaSpecifiers(LParenLoc, /*DeclEndLoc=*/T.getCloseLocation(),
  1271. ParamInfo, EllipsisLoc);
  1272. // Parse requires-clause[opt].
  1273. if (Tok.is(tok::kw_requires))
  1274. ParseTrailingRequiresClause(D);
  1275. } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
  1276. tok::kw_constexpr, tok::kw_consteval,
  1277. tok::kw___private, tok::kw___global, tok::kw___local,
  1278. tok::kw___constant, tok::kw___generic,
  1279. tok::kw_requires, tok::kw_noexcept) ||
  1280. (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
  1281. if (!getLangOpts().CPlusPlus2b)
  1282. // It's common to forget that one needs '()' before 'mutable', an
  1283. // attribute specifier, the result type, or the requires clause. Deal with
  1284. // this.
  1285. Diag(Tok, diag::ext_lambda_missing_parens)
  1286. << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
  1287. SourceLocation NoLoc;
  1288. // Parse lambda-specifiers.
  1289. std::vector<DeclaratorChunk::ParamInfo> EmptyParamInfo;
  1290. ParseLambdaSpecifiers(/*LParenLoc=*/NoLoc, /*RParenLoc=*/NoLoc,
  1291. EmptyParamInfo, /*EllipsisLoc=*/NoLoc);
  1292. }
  1293. WarnIfHasCUDATargetAttr();
  1294. // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
  1295. // it.
  1296. unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
  1297. Scope::CompoundStmtScope;
  1298. ParseScope BodyScope(this, ScopeFlags);
  1299. Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
  1300. // Parse compound-statement.
  1301. if (!Tok.is(tok::l_brace)) {
  1302. Diag(Tok, diag::err_expected_lambda_body);
  1303. Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
  1304. return ExprError();
  1305. }
  1306. StmtResult Stmt(ParseCompoundStatementBody());
  1307. BodyScope.Exit();
  1308. TemplateParamScope.Exit();
  1309. if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
  1310. return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
  1311. Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
  1312. return ExprError();
  1313. }
  1314. /// ParseCXXCasts - This handles the various ways to cast expressions to another
  1315. /// type.
  1316. ///
  1317. /// postfix-expression: [C++ 5.2p1]
  1318. /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
  1319. /// 'static_cast' '<' type-name '>' '(' expression ')'
  1320. /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
  1321. /// 'const_cast' '<' type-name '>' '(' expression ')'
  1322. ///
  1323. /// C++ for OpenCL s2.3.1 adds:
  1324. /// 'addrspace_cast' '<' type-name '>' '(' expression ')'
  1325. ExprResult Parser::ParseCXXCasts() {
  1326. tok::TokenKind Kind = Tok.getKind();
  1327. const char *CastName = nullptr; // For error messages
  1328. switch (Kind) {
  1329. default: llvm_unreachable("Unknown C++ cast!");
  1330. case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break;
  1331. case tok::kw_const_cast: CastName = "const_cast"; break;
  1332. case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
  1333. case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
  1334. case tok::kw_static_cast: CastName = "static_cast"; break;
  1335. }
  1336. SourceLocation OpLoc = ConsumeToken();
  1337. SourceLocation LAngleBracketLoc = Tok.getLocation();
  1338. // Check for "<::" which is parsed as "[:". If found, fix token stream,
  1339. // diagnose error, suggest fix, and recover parsing.
  1340. if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
  1341. Token Next = NextToken();
  1342. if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
  1343. FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
  1344. }
  1345. if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
  1346. return ExprError();
  1347. // Parse the common declaration-specifiers piece.
  1348. DeclSpec DS(AttrFactory);
  1349. ParseSpecifierQualifierList(DS);
  1350. // Parse the abstract-declarator, if present.
  1351. Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
  1352. ParseDeclarator(DeclaratorInfo);
  1353. SourceLocation RAngleBracketLoc = Tok.getLocation();
  1354. if (ExpectAndConsume(tok::greater))
  1355. return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
  1356. BalancedDelimiterTracker T(*this, tok::l_paren);
  1357. if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
  1358. return ExprError();
  1359. ExprResult Result = ParseExpression();
  1360. // Match the ')'.
  1361. T.consumeClose();
  1362. if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
  1363. Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
  1364. LAngleBracketLoc, DeclaratorInfo,
  1365. RAngleBracketLoc,
  1366. T.getOpenLocation(), Result.get(),
  1367. T.getCloseLocation());
  1368. return Result;
  1369. }
  1370. /// ParseCXXTypeid - This handles the C++ typeid expression.
  1371. ///
  1372. /// postfix-expression: [C++ 5.2p1]
  1373. /// 'typeid' '(' expression ')'
  1374. /// 'typeid' '(' type-id ')'
  1375. ///
  1376. ExprResult Parser::ParseCXXTypeid() {
  1377. assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
  1378. SourceLocation OpLoc = ConsumeToken();
  1379. SourceLocation LParenLoc, RParenLoc;
  1380. BalancedDelimiterTracker T(*this, tok::l_paren);
  1381. // typeid expressions are always parenthesized.
  1382. if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
  1383. return ExprError();
  1384. LParenLoc = T.getOpenLocation();
  1385. ExprResult Result;
  1386. // C++0x [expr.typeid]p3:
  1387. // When typeid is applied to an expression other than an lvalue of a
  1388. // polymorphic class type [...] The expression is an unevaluated
  1389. // operand (Clause 5).
  1390. //
  1391. // Note that we can't tell whether the expression is an lvalue of a
  1392. // polymorphic class type until after we've parsed the expression; we
  1393. // speculatively assume the subexpression is unevaluated, and fix it up
  1394. // later.
  1395. //
  1396. // We enter the unevaluated context before trying to determine whether we
  1397. // have a type-id, because the tentative parse logic will try to resolve
  1398. // names, and must treat them as unevaluated.
  1399. EnterExpressionEvaluationContext Unevaluated(
  1400. Actions, Sema::ExpressionEvaluationContext::Unevaluated,
  1401. Sema::ReuseLambdaContextDecl);
  1402. if (isTypeIdInParens()) {
  1403. TypeResult Ty = ParseTypeName();
  1404. // Match the ')'.
  1405. T.consumeClose();
  1406. RParenLoc = T.getCloseLocation();
  1407. if (Ty.isInvalid() || RParenLoc.isInvalid())
  1408. return ExprError();
  1409. Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
  1410. Ty.get().getAsOpaquePtr(), RParenLoc);
  1411. } else {
  1412. Result = ParseExpression();
  1413. // Match the ')'.
  1414. if (Result.isInvalid())
  1415. SkipUntil(tok::r_paren, StopAtSemi);
  1416. else {
  1417. T.consumeClose();
  1418. RParenLoc = T.getCloseLocation();
  1419. if (RParenLoc.isInvalid())
  1420. return ExprError();
  1421. Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
  1422. Result.get(), RParenLoc);
  1423. }
  1424. }
  1425. return Result;
  1426. }
  1427. /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
  1428. ///
  1429. /// '__uuidof' '(' expression ')'
  1430. /// '__uuidof' '(' type-id ')'
  1431. ///
  1432. ExprResult Parser::ParseCXXUuidof() {
  1433. assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
  1434. SourceLocation OpLoc = ConsumeToken();
  1435. BalancedDelimiterTracker T(*this, tok::l_paren);
  1436. // __uuidof expressions are always parenthesized.
  1437. if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
  1438. return ExprError();
  1439. ExprResult Result;
  1440. if (isTypeIdInParens()) {
  1441. TypeResult Ty = ParseTypeName();
  1442. // Match the ')'.
  1443. T.consumeClose();
  1444. if (Ty.isInvalid())
  1445. return ExprError();
  1446. Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
  1447. Ty.get().getAsOpaquePtr(),
  1448. T.getCloseLocation());
  1449. } else {
  1450. EnterExpressionEvaluationContext Unevaluated(
  1451. Actions, Sema::ExpressionEvaluationContext::Unevaluated);
  1452. Result = ParseExpression();
  1453. // Match the ')'.
  1454. if (Result.isInvalid())
  1455. SkipUntil(tok::r_paren, StopAtSemi);
  1456. else {
  1457. T.consumeClose();
  1458. Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
  1459. /*isType=*/false,
  1460. Result.get(), T.getCloseLocation());
  1461. }
  1462. }
  1463. return Result;
  1464. }
  1465. /// Parse a C++ pseudo-destructor expression after the base,
  1466. /// . or -> operator, and nested-name-specifier have already been
  1467. /// parsed. We're handling this fragment of the grammar:
  1468. ///
  1469. /// postfix-expression: [C++2a expr.post]
  1470. /// postfix-expression . template[opt] id-expression
  1471. /// postfix-expression -> template[opt] id-expression
  1472. ///
  1473. /// id-expression:
  1474. /// qualified-id
  1475. /// unqualified-id
  1476. ///
  1477. /// qualified-id:
  1478. /// nested-name-specifier template[opt] unqualified-id
  1479. ///
  1480. /// nested-name-specifier:
  1481. /// type-name ::
  1482. /// decltype-specifier :: FIXME: not implemented, but probably only
  1483. /// allowed in C++ grammar by accident
  1484. /// nested-name-specifier identifier ::
  1485. /// nested-name-specifier template[opt] simple-template-id ::
  1486. /// [...]
  1487. ///
  1488. /// unqualified-id:
  1489. /// ~ type-name
  1490. /// ~ decltype-specifier
  1491. /// [...]
  1492. ///
  1493. /// ... where the all but the last component of the nested-name-specifier
  1494. /// has already been parsed, and the base expression is not of a non-dependent
  1495. /// class type.
  1496. ExprResult
  1497. Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
  1498. tok::TokenKind OpKind,
  1499. CXXScopeSpec &SS,
  1500. ParsedType ObjectType) {
  1501. // If the last component of the (optional) nested-name-specifier is
  1502. // template[opt] simple-template-id, it has already been annotated.
  1503. UnqualifiedId FirstTypeName;
  1504. SourceLocation CCLoc;
  1505. if (Tok.is(tok::identifier)) {
  1506. FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
  1507. ConsumeToken();
  1508. assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
  1509. CCLoc = ConsumeToken();
  1510. } else if (Tok.is(tok::annot_template_id)) {
  1511. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1512. // FIXME: Carry on and build an AST representation for tooling.
  1513. if (TemplateId->isInvalid())
  1514. return ExprError();
  1515. FirstTypeName.setTemplateId(TemplateId);
  1516. ConsumeAnnotationToken();
  1517. assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
  1518. CCLoc = ConsumeToken();
  1519. } else {
  1520. assert(SS.isEmpty() && "missing last component of nested name specifier");
  1521. FirstTypeName.setIdentifier(nullptr, SourceLocation());
  1522. }
  1523. // Parse the tilde.
  1524. assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
  1525. SourceLocation TildeLoc = ConsumeToken();
  1526. if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
  1527. DeclSpec DS(AttrFactory);
  1528. ParseDecltypeSpecifier(DS);
  1529. if (DS.getTypeSpecType() == TST_error)
  1530. return ExprError();
  1531. return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
  1532. TildeLoc, DS);
  1533. }
  1534. if (!Tok.is(tok::identifier)) {
  1535. Diag(Tok, diag::err_destructor_tilde_identifier);
  1536. return ExprError();
  1537. }
  1538. // Parse the second type.
  1539. UnqualifiedId SecondTypeName;
  1540. IdentifierInfo *Name = Tok.getIdentifierInfo();
  1541. SourceLocation NameLoc = ConsumeToken();
  1542. SecondTypeName.setIdentifier(Name, NameLoc);
  1543. // If there is a '<', the second type name is a template-id. Parse
  1544. // it as such.
  1545. //
  1546. // FIXME: This is not a context in which a '<' is assumed to start a template
  1547. // argument list. This affects examples such as
  1548. // void f(auto *p) { p->~X<int>(); }
  1549. // ... but there's no ambiguity, and nowhere to write 'template' in such an
  1550. // example, so we accept it anyway.
  1551. if (Tok.is(tok::less) &&
  1552. ParseUnqualifiedIdTemplateId(
  1553. SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
  1554. Name, NameLoc, false, SecondTypeName,
  1555. /*AssumeTemplateId=*/true))
  1556. return ExprError();
  1557. return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
  1558. SS, FirstTypeName, CCLoc, TildeLoc,
  1559. SecondTypeName);
  1560. }
  1561. /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
  1562. ///
  1563. /// boolean-literal: [C++ 2.13.5]
  1564. /// 'true'
  1565. /// 'false'
  1566. ExprResult Parser::ParseCXXBoolLiteral() {
  1567. tok::TokenKind Kind = Tok.getKind();
  1568. return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
  1569. }
  1570. /// ParseThrowExpression - This handles the C++ throw expression.
  1571. ///
  1572. /// throw-expression: [C++ 15]
  1573. /// 'throw' assignment-expression[opt]
  1574. ExprResult Parser::ParseThrowExpression() {
  1575. assert(Tok.is(tok::kw_throw) && "Not throw!");
  1576. SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
  1577. // If the current token isn't the start of an assignment-expression,
  1578. // then the expression is not present. This handles things like:
  1579. // "C ? throw : (void)42", which is crazy but legal.
  1580. switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
  1581. case tok::semi:
  1582. case tok::r_paren:
  1583. case tok::r_square:
  1584. case tok::r_brace:
  1585. case tok::colon:
  1586. case tok::comma:
  1587. return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
  1588. default:
  1589. ExprResult Expr(ParseAssignmentExpression());
  1590. if (Expr.isInvalid()) return Expr;
  1591. return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
  1592. }
  1593. }
  1594. /// Parse the C++ Coroutines co_yield expression.
  1595. ///
  1596. /// co_yield-expression:
  1597. /// 'co_yield' assignment-expression[opt]
  1598. ExprResult Parser::ParseCoyieldExpression() {
  1599. assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
  1600. SourceLocation Loc = ConsumeToken();
  1601. ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
  1602. : ParseAssignmentExpression();
  1603. if (!Expr.isInvalid())
  1604. Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
  1605. return Expr;
  1606. }
  1607. /// ParseCXXThis - This handles the C++ 'this' pointer.
  1608. ///
  1609. /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
  1610. /// a non-lvalue expression whose value is the address of the object for which
  1611. /// the function is called.
  1612. ExprResult Parser::ParseCXXThis() {
  1613. assert(Tok.is(tok::kw_this) && "Not 'this'!");
  1614. SourceLocation ThisLoc = ConsumeToken();
  1615. return Actions.ActOnCXXThis(ThisLoc);
  1616. }
  1617. /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
  1618. /// Can be interpreted either as function-style casting ("int(x)")
  1619. /// or class type construction ("ClassType(x,y,z)")
  1620. /// or creation of a value-initialized type ("int()").
  1621. /// See [C++ 5.2.3].
  1622. ///
  1623. /// postfix-expression: [C++ 5.2p1]
  1624. /// simple-type-specifier '(' expression-list[opt] ')'
  1625. /// [C++0x] simple-type-specifier braced-init-list
  1626. /// typename-specifier '(' expression-list[opt] ')'
  1627. /// [C++0x] typename-specifier braced-init-list
  1628. ///
  1629. /// In C++1z onwards, the type specifier can also be a template-name.
  1630. ExprResult
  1631. Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
  1632. Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCast);
  1633. ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
  1634. assert((Tok.is(tok::l_paren) ||
  1635. (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
  1636. && "Expected '(' or '{'!");
  1637. if (Tok.is(tok::l_brace)) {
  1638. PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
  1639. ExprResult Init = ParseBraceInitializer();
  1640. if (Init.isInvalid())
  1641. return Init;
  1642. Expr *InitList = Init.get();
  1643. return Actions.ActOnCXXTypeConstructExpr(
  1644. TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
  1645. InitList->getEndLoc(), /*ListInitialization=*/true);
  1646. } else {
  1647. BalancedDelimiterTracker T(*this, tok::l_paren);
  1648. T.consumeOpen();
  1649. PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
  1650. ExprVector Exprs;
  1651. CommaLocsTy CommaLocs;
  1652. auto RunSignatureHelp = [&]() {
  1653. QualType PreferredType;
  1654. if (TypeRep)
  1655. PreferredType = Actions.ProduceConstructorSignatureHelp(
  1656. TypeRep.get()->getCanonicalTypeInternal(), DS.getEndLoc(), Exprs,
  1657. T.getOpenLocation(), /*Braced=*/false);
  1658. CalledSignatureHelp = true;
  1659. return PreferredType;
  1660. };
  1661. if (Tok.isNot(tok::r_paren)) {
  1662. if (ParseExpressionList(Exprs, CommaLocs, [&] {
  1663. PreferredType.enterFunctionArgument(Tok.getLocation(),
  1664. RunSignatureHelp);
  1665. })) {
  1666. if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
  1667. RunSignatureHelp();
  1668. SkipUntil(tok::r_paren, StopAtSemi);
  1669. return ExprError();
  1670. }
  1671. }
  1672. // Match the ')'.
  1673. T.consumeClose();
  1674. // TypeRep could be null, if it references an invalid typedef.
  1675. if (!TypeRep)
  1676. return ExprError();
  1677. assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
  1678. "Unexpected number of commas!");
  1679. return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
  1680. Exprs, T.getCloseLocation(),
  1681. /*ListInitialization=*/false);
  1682. }
  1683. }
  1684. Parser::DeclGroupPtrTy
  1685. Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
  1686. ParsedAttributesWithRange &Attrs) {
  1687. assert(Tok.is(tok::kw_using) && "Expected using");
  1688. assert((Context == DeclaratorContext::ForInit ||
  1689. Context == DeclaratorContext::SelectionInit) &&
  1690. "Unexpected Declarator Context");
  1691. DeclGroupPtrTy DG;
  1692. SourceLocation DeclStart = ConsumeToken(), DeclEnd;
  1693. DG = ParseUsingDeclaration(Context, {}, DeclStart, DeclEnd, Attrs, AS_none);
  1694. if (!DG)
  1695. return DG;
  1696. Diag(DeclStart, !getLangOpts().CPlusPlus2b
  1697. ? diag::ext_alias_in_init_statement
  1698. : diag::warn_cxx20_alias_in_init_statement)
  1699. << SourceRange(DeclStart, DeclEnd);
  1700. return DG;
  1701. }
  1702. /// ParseCXXCondition - if/switch/while condition expression.
  1703. ///
  1704. /// condition:
  1705. /// expression
  1706. /// type-specifier-seq declarator '=' assignment-expression
  1707. /// [C++11] type-specifier-seq declarator '=' initializer-clause
  1708. /// [C++11] type-specifier-seq declarator braced-init-list
  1709. /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
  1710. /// brace-or-equal-initializer
  1711. /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
  1712. /// '=' assignment-expression
  1713. ///
  1714. /// In C++1z, a condition may in some contexts be preceded by an
  1715. /// optional init-statement. This function will parse that too.
  1716. ///
  1717. /// \param InitStmt If non-null, an init-statement is permitted, and if present
  1718. /// will be parsed and stored here.
  1719. ///
  1720. /// \param Loc The location of the start of the statement that requires this
  1721. /// condition, e.g., the "for" in a for loop.
  1722. ///
  1723. /// \param MissingOK Whether an empty condition is acceptable here. Otherwise
  1724. /// it is considered an error to be recovered from.
  1725. ///
  1726. /// \param FRI If non-null, a for range declaration is permitted, and if
  1727. /// present will be parsed and stored here, and a null result will be returned.
  1728. ///
  1729. /// \param EnterForConditionScope If true, enter a continue/break scope at the
  1730. /// appropriate moment for a 'for' loop.
  1731. ///
  1732. /// \returns The parsed condition.
  1733. Sema::ConditionResult
  1734. Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc,
  1735. Sema::ConditionKind CK, bool MissingOK,
  1736. ForRangeInfo *FRI, bool EnterForConditionScope) {
  1737. // Helper to ensure we always enter a continue/break scope if requested.
  1738. struct ForConditionScopeRAII {
  1739. Scope *S;
  1740. void enter(bool IsConditionVariable) {
  1741. if (S) {
  1742. S->AddFlags(Scope::BreakScope | Scope::ContinueScope);
  1743. S->setIsConditionVarScope(IsConditionVariable);
  1744. }
  1745. }
  1746. ~ForConditionScopeRAII() {
  1747. if (S)
  1748. S->setIsConditionVarScope(false);
  1749. }
  1750. } ForConditionScope{EnterForConditionScope ? getCurScope() : nullptr};
  1751. ParenBraceBracketBalancer BalancerRAIIObj(*this);
  1752. PreferredType.enterCondition(Actions, Tok.getLocation());
  1753. if (Tok.is(tok::code_completion)) {
  1754. cutOffParsing();
  1755. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
  1756. return Sema::ConditionError();
  1757. }
  1758. ParsedAttributesWithRange attrs(AttrFactory);
  1759. MaybeParseCXX11Attributes(attrs);
  1760. const auto WarnOnInit = [this, &CK] {
  1761. Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
  1762. ? diag::warn_cxx14_compat_init_statement
  1763. : diag::ext_init_statement)
  1764. << (CK == Sema::ConditionKind::Switch);
  1765. };
  1766. // Determine what kind of thing we have.
  1767. switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
  1768. case ConditionOrInitStatement::Expression: {
  1769. // If this is a for loop, we're entering its condition.
  1770. ForConditionScope.enter(/*IsConditionVariable=*/false);
  1771. ProhibitAttributes(attrs);
  1772. // We can have an empty expression here.
  1773. // if (; true);
  1774. if (InitStmt && Tok.is(tok::semi)) {
  1775. WarnOnInit();
  1776. SourceLocation SemiLoc = Tok.getLocation();
  1777. if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
  1778. Diag(SemiLoc, diag::warn_empty_init_statement)
  1779. << (CK == Sema::ConditionKind::Switch)
  1780. << FixItHint::CreateRemoval(SemiLoc);
  1781. }
  1782. ConsumeToken();
  1783. *InitStmt = Actions.ActOnNullStmt(SemiLoc);
  1784. return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
  1785. }
  1786. // Parse the expression.
  1787. ExprResult Expr = ParseExpression(); // expression
  1788. if (Expr.isInvalid())
  1789. return Sema::ConditionError();
  1790. if (InitStmt && Tok.is(tok::semi)) {
  1791. WarnOnInit();
  1792. *InitStmt = Actions.ActOnExprStmt(Expr.get());
  1793. ConsumeToken();
  1794. return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
  1795. }
  1796. return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK,
  1797. MissingOK);
  1798. }
  1799. case ConditionOrInitStatement::InitStmtDecl: {
  1800. WarnOnInit();
  1801. DeclGroupPtrTy DG;
  1802. SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
  1803. if (Tok.is(tok::kw_using))
  1804. DG = ParseAliasDeclarationInInitStatement(
  1805. DeclaratorContext::SelectionInit, attrs);
  1806. else
  1807. DG = ParseSimpleDeclaration(DeclaratorContext::SelectionInit, DeclEnd,
  1808. attrs, /*RequireSemi=*/true);
  1809. *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
  1810. return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
  1811. }
  1812. case ConditionOrInitStatement::ForRangeDecl: {
  1813. // This is 'for (init-stmt; for-range-decl : range-expr)'.
  1814. // We're not actually in a for loop yet, so 'break' and 'continue' aren't
  1815. // permitted here.
  1816. assert(FRI && "should not parse a for range declaration here");
  1817. SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
  1818. DeclGroupPtrTy DG = ParseSimpleDeclaration(DeclaratorContext::ForInit,
  1819. DeclEnd, attrs, false, FRI);
  1820. FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
  1821. assert((FRI->ColonLoc.isValid() || !DG) &&
  1822. "cannot find for range declaration");
  1823. return Sema::ConditionResult();
  1824. }
  1825. case ConditionOrInitStatement::ConditionDecl:
  1826. case ConditionOrInitStatement::Error:
  1827. break;
  1828. }
  1829. // If this is a for loop, we're entering its condition.
  1830. ForConditionScope.enter(/*IsConditionVariable=*/true);
  1831. // type-specifier-seq
  1832. DeclSpec DS(AttrFactory);
  1833. DS.takeAttributesFrom(attrs);
  1834. ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
  1835. // declarator
  1836. Declarator DeclaratorInfo(DS, DeclaratorContext::Condition);
  1837. ParseDeclarator(DeclaratorInfo);
  1838. // simple-asm-expr[opt]
  1839. if (Tok.is(tok::kw_asm)) {
  1840. SourceLocation Loc;
  1841. ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
  1842. if (AsmLabel.isInvalid()) {
  1843. SkipUntil(tok::semi, StopAtSemi);
  1844. return Sema::ConditionError();
  1845. }
  1846. DeclaratorInfo.setAsmLabel(AsmLabel.get());
  1847. DeclaratorInfo.SetRangeEnd(Loc);
  1848. }
  1849. // If attributes are present, parse them.
  1850. MaybeParseGNUAttributes(DeclaratorInfo);
  1851. // Type-check the declaration itself.
  1852. DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
  1853. DeclaratorInfo);
  1854. if (Dcl.isInvalid())
  1855. return Sema::ConditionError();
  1856. Decl *DeclOut = Dcl.get();
  1857. // '=' assignment-expression
  1858. // If a '==' or '+=' is found, suggest a fixit to '='.
  1859. bool CopyInitialization = isTokenEqualOrEqualTypo();
  1860. if (CopyInitialization)
  1861. ConsumeToken();
  1862. ExprResult InitExpr = ExprError();
  1863. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  1864. Diag(Tok.getLocation(),
  1865. diag::warn_cxx98_compat_generalized_initializer_lists);
  1866. InitExpr = ParseBraceInitializer();
  1867. } else if (CopyInitialization) {
  1868. PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
  1869. InitExpr = ParseAssignmentExpression();
  1870. } else if (Tok.is(tok::l_paren)) {
  1871. // This was probably an attempt to initialize the variable.
  1872. SourceLocation LParen = ConsumeParen(), RParen = LParen;
  1873. if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
  1874. RParen = ConsumeParen();
  1875. Diag(DeclOut->getLocation(),
  1876. diag::err_expected_init_in_condition_lparen)
  1877. << SourceRange(LParen, RParen);
  1878. } else {
  1879. Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
  1880. }
  1881. if (!InitExpr.isInvalid())
  1882. Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
  1883. else
  1884. Actions.ActOnInitializerError(DeclOut);
  1885. Actions.FinalizeDeclaration(DeclOut);
  1886. return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
  1887. }
  1888. /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
  1889. /// This should only be called when the current token is known to be part of
  1890. /// simple-type-specifier.
  1891. ///
  1892. /// simple-type-specifier:
  1893. /// '::'[opt] nested-name-specifier[opt] type-name
  1894. /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
  1895. /// char
  1896. /// wchar_t
  1897. /// bool
  1898. /// short
  1899. /// int
  1900. /// long
  1901. /// signed
  1902. /// unsigned
  1903. /// float
  1904. /// double
  1905. /// void
  1906. /// [GNU] typeof-specifier
  1907. /// [C++0x] auto [TODO]
  1908. ///
  1909. /// type-name:
  1910. /// class-name
  1911. /// enum-name
  1912. /// typedef-name
  1913. ///
  1914. void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
  1915. DS.SetRangeStart(Tok.getLocation());
  1916. const char *PrevSpec;
  1917. unsigned DiagID;
  1918. SourceLocation Loc = Tok.getLocation();
  1919. const clang::PrintingPolicy &Policy =
  1920. Actions.getASTContext().getPrintingPolicy();
  1921. switch (Tok.getKind()) {
  1922. case tok::identifier: // foo::bar
  1923. case tok::coloncolon: // ::foo::bar
  1924. llvm_unreachable("Annotation token should already be formed!");
  1925. default:
  1926. llvm_unreachable("Not a simple-type-specifier token!");
  1927. // type-name
  1928. case tok::annot_typename: {
  1929. DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
  1930. getTypeAnnotation(Tok), Policy);
  1931. DS.SetRangeEnd(Tok.getAnnotationEndLoc());
  1932. ConsumeAnnotationToken();
  1933. DS.Finish(Actions, Policy);
  1934. return;
  1935. }
  1936. case tok::kw__ExtInt:
  1937. case tok::kw__BitInt: {
  1938. DiagnoseBitIntUse(Tok);
  1939. ExprResult ER = ParseExtIntegerArgument();
  1940. if (ER.isInvalid())
  1941. DS.SetTypeSpecError();
  1942. else
  1943. DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
  1944. // Do this here because we have already consumed the close paren.
  1945. DS.SetRangeEnd(PrevTokLocation);
  1946. DS.Finish(Actions, Policy);
  1947. return;
  1948. }
  1949. // builtin types
  1950. case tok::kw_short:
  1951. DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
  1952. Policy);
  1953. break;
  1954. case tok::kw_long:
  1955. DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
  1956. Policy);
  1957. break;
  1958. case tok::kw___int64:
  1959. DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID,
  1960. Policy);
  1961. break;
  1962. case tok::kw_signed:
  1963. DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
  1964. break;
  1965. case tok::kw_unsigned:
  1966. DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
  1967. break;
  1968. case tok::kw_void:
  1969. DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
  1970. break;
  1971. case tok::kw_char:
  1972. DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
  1973. break;
  1974. case tok::kw_int:
  1975. DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
  1976. break;
  1977. case tok::kw___int128:
  1978. DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
  1979. break;
  1980. case tok::kw___bf16:
  1981. DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
  1982. break;
  1983. case tok::kw_half:
  1984. DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
  1985. break;
  1986. case tok::kw_float:
  1987. DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
  1988. break;
  1989. case tok::kw_double:
  1990. DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
  1991. break;
  1992. case tok::kw__Float16:
  1993. DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
  1994. break;
  1995. case tok::kw___float128:
  1996. DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
  1997. break;
  1998. case tok::kw___ibm128:
  1999. DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy);
  2000. break;
  2001. case tok::kw_wchar_t:
  2002. DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
  2003. break;
  2004. case tok::kw_char8_t:
  2005. DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
  2006. break;
  2007. case tok::kw_char16_t:
  2008. DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
  2009. break;
  2010. case tok::kw_char32_t:
  2011. DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
  2012. break;
  2013. case tok::kw_bool:
  2014. DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
  2015. break;
  2016. #define GENERIC_IMAGE_TYPE(ImgType, Id) \
  2017. case tok::kw_##ImgType##_t: \
  2018. DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
  2019. Policy); \
  2020. break;
  2021. #include "clang/Basic/OpenCLImageTypes.def"
  2022. case tok::annot_decltype:
  2023. case tok::kw_decltype:
  2024. DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
  2025. return DS.Finish(Actions, Policy);
  2026. // GNU typeof support.
  2027. case tok::kw_typeof:
  2028. ParseTypeofSpecifier(DS);
  2029. DS.Finish(Actions, Policy);
  2030. return;
  2031. }
  2032. ConsumeAnyToken();
  2033. DS.SetRangeEnd(PrevTokLocation);
  2034. DS.Finish(Actions, Policy);
  2035. }
  2036. /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
  2037. /// [dcl.name]), which is a non-empty sequence of type-specifiers,
  2038. /// e.g., "const short int". Note that the DeclSpec is *not* finished
  2039. /// by parsing the type-specifier-seq, because these sequences are
  2040. /// typically followed by some form of declarator. Returns true and
  2041. /// emits diagnostics if this is not a type-specifier-seq, false
  2042. /// otherwise.
  2043. ///
  2044. /// type-specifier-seq: [C++ 8.1]
  2045. /// type-specifier type-specifier-seq[opt]
  2046. ///
  2047. bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
  2048. ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
  2049. DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
  2050. return false;
  2051. }
  2052. /// Finish parsing a C++ unqualified-id that is a template-id of
  2053. /// some form.
  2054. ///
  2055. /// This routine is invoked when a '<' is encountered after an identifier or
  2056. /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
  2057. /// whether the unqualified-id is actually a template-id. This routine will
  2058. /// then parse the template arguments and form the appropriate template-id to
  2059. /// return to the caller.
  2060. ///
  2061. /// \param SS the nested-name-specifier that precedes this template-id, if
  2062. /// we're actually parsing a qualified-id.
  2063. ///
  2064. /// \param ObjectType if this unqualified-id occurs within a member access
  2065. /// expression, the type of the base object whose member is being accessed.
  2066. ///
  2067. /// \param ObjectHadErrors this unqualified-id occurs within a member access
  2068. /// expression, indicates whether the original subexpressions had any errors.
  2069. ///
  2070. /// \param Name for constructor and destructor names, this is the actual
  2071. /// identifier that may be a template-name.
  2072. ///
  2073. /// \param NameLoc the location of the class-name in a constructor or
  2074. /// destructor.
  2075. ///
  2076. /// \param EnteringContext whether we're entering the scope of the
  2077. /// nested-name-specifier.
  2078. ///
  2079. /// \param Id as input, describes the template-name or operator-function-id
  2080. /// that precedes the '<'. If template arguments were parsed successfully,
  2081. /// will be updated with the template-id.
  2082. ///
  2083. /// \param AssumeTemplateId When true, this routine will assume that the name
  2084. /// refers to a template without performing name lookup to verify.
  2085. ///
  2086. /// \returns true if a parse error occurred, false otherwise.
  2087. bool Parser::ParseUnqualifiedIdTemplateId(
  2088. CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
  2089. SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
  2090. bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
  2091. assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
  2092. TemplateTy Template;
  2093. TemplateNameKind TNK = TNK_Non_template;
  2094. switch (Id.getKind()) {
  2095. case UnqualifiedIdKind::IK_Identifier:
  2096. case UnqualifiedIdKind::IK_OperatorFunctionId:
  2097. case UnqualifiedIdKind::IK_LiteralOperatorId:
  2098. if (AssumeTemplateId) {
  2099. // We defer the injected-class-name checks until we've found whether
  2100. // this template-id is used to form a nested-name-specifier or not.
  2101. TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
  2102. ObjectType, EnteringContext, Template,
  2103. /*AllowInjectedClassName*/ true);
  2104. } else {
  2105. bool MemberOfUnknownSpecialization;
  2106. TNK = Actions.isTemplateName(getCurScope(), SS,
  2107. TemplateKWLoc.isValid(), Id,
  2108. ObjectType, EnteringContext, Template,
  2109. MemberOfUnknownSpecialization);
  2110. // If lookup found nothing but we're assuming that this is a template
  2111. // name, double-check that makes sense syntactically before committing
  2112. // to it.
  2113. if (TNK == TNK_Undeclared_template &&
  2114. isTemplateArgumentList(0) == TPResult::False)
  2115. return false;
  2116. if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
  2117. ObjectType && isTemplateArgumentList(0) == TPResult::True) {
  2118. // If we had errors before, ObjectType can be dependent even without any
  2119. // templates, do not report missing template keyword in that case.
  2120. if (!ObjectHadErrors) {
  2121. // We have something like t->getAs<T>(), where getAs is a
  2122. // member of an unknown specialization. However, this will only
  2123. // parse correctly as a template, so suggest the keyword 'template'
  2124. // before 'getAs' and treat this as a dependent template name.
  2125. std::string Name;
  2126. if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
  2127. Name = std::string(Id.Identifier->getName());
  2128. else {
  2129. Name = "operator ";
  2130. if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
  2131. Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
  2132. else
  2133. Name += Id.Identifier->getName();
  2134. }
  2135. Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
  2136. << Name
  2137. << FixItHint::CreateInsertion(Id.StartLocation, "template ");
  2138. }
  2139. TNK = Actions.ActOnTemplateName(
  2140. getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
  2141. Template, /*AllowInjectedClassName*/ true);
  2142. } else if (TNK == TNK_Non_template) {
  2143. return false;
  2144. }
  2145. }
  2146. break;
  2147. case UnqualifiedIdKind::IK_ConstructorName: {
  2148. UnqualifiedId TemplateName;
  2149. bool MemberOfUnknownSpecialization;
  2150. TemplateName.setIdentifier(Name, NameLoc);
  2151. TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
  2152. TemplateName, ObjectType,
  2153. EnteringContext, Template,
  2154. MemberOfUnknownSpecialization);
  2155. if (TNK == TNK_Non_template)
  2156. return false;
  2157. break;
  2158. }
  2159. case UnqualifiedIdKind::IK_DestructorName: {
  2160. UnqualifiedId TemplateName;
  2161. bool MemberOfUnknownSpecialization;
  2162. TemplateName.setIdentifier(Name, NameLoc);
  2163. if (ObjectType) {
  2164. TNK = Actions.ActOnTemplateName(
  2165. getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
  2166. EnteringContext, Template, /*AllowInjectedClassName*/ true);
  2167. } else {
  2168. TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
  2169. TemplateName, ObjectType,
  2170. EnteringContext, Template,
  2171. MemberOfUnknownSpecialization);
  2172. if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
  2173. Diag(NameLoc, diag::err_destructor_template_id)
  2174. << Name << SS.getRange();
  2175. // Carry on to parse the template arguments before bailing out.
  2176. }
  2177. }
  2178. break;
  2179. }
  2180. default:
  2181. return false;
  2182. }
  2183. // Parse the enclosed template argument list.
  2184. SourceLocation LAngleLoc, RAngleLoc;
  2185. TemplateArgList TemplateArgs;
  2186. if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, RAngleLoc,
  2187. Template))
  2188. return true;
  2189. // If this is a non-template, we already issued a diagnostic.
  2190. if (TNK == TNK_Non_template)
  2191. return true;
  2192. if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
  2193. Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
  2194. Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
  2195. // Form a parsed representation of the template-id to be stored in the
  2196. // UnqualifiedId.
  2197. // FIXME: Store name for literal operator too.
  2198. IdentifierInfo *TemplateII =
  2199. Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
  2200. : nullptr;
  2201. OverloadedOperatorKind OpKind =
  2202. Id.getKind() == UnqualifiedIdKind::IK_Identifier
  2203. ? OO_None
  2204. : Id.OperatorFunctionId.Operator;
  2205. TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
  2206. TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
  2207. LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
  2208. Id.setTemplateId(TemplateId);
  2209. return false;
  2210. }
  2211. // Bundle the template arguments together.
  2212. ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
  2213. // Constructor and destructor names.
  2214. TypeResult Type = Actions.ActOnTemplateIdType(
  2215. getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
  2216. TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
  2217. if (Type.isInvalid())
  2218. return true;
  2219. if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
  2220. Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
  2221. else
  2222. Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
  2223. return false;
  2224. }
  2225. /// Parse an operator-function-id or conversion-function-id as part
  2226. /// of a C++ unqualified-id.
  2227. ///
  2228. /// This routine is responsible only for parsing the operator-function-id or
  2229. /// conversion-function-id; it does not handle template arguments in any way.
  2230. ///
  2231. /// \code
  2232. /// operator-function-id: [C++ 13.5]
  2233. /// 'operator' operator
  2234. ///
  2235. /// operator: one of
  2236. /// new delete new[] delete[]
  2237. /// + - * / % ^ & | ~
  2238. /// ! = < > += -= *= /= %=
  2239. /// ^= &= |= << >> >>= <<= == !=
  2240. /// <= >= && || ++ -- , ->* ->
  2241. /// () [] <=>
  2242. ///
  2243. /// conversion-function-id: [C++ 12.3.2]
  2244. /// operator conversion-type-id
  2245. ///
  2246. /// conversion-type-id:
  2247. /// type-specifier-seq conversion-declarator[opt]
  2248. ///
  2249. /// conversion-declarator:
  2250. /// ptr-operator conversion-declarator[opt]
  2251. /// \endcode
  2252. ///
  2253. /// \param SS The nested-name-specifier that preceded this unqualified-id. If
  2254. /// non-empty, then we are parsing the unqualified-id of a qualified-id.
  2255. ///
  2256. /// \param EnteringContext whether we are entering the scope of the
  2257. /// nested-name-specifier.
  2258. ///
  2259. /// \param ObjectType if this unqualified-id occurs within a member access
  2260. /// expression, the type of the base object whose member is being accessed.
  2261. ///
  2262. /// \param Result on a successful parse, contains the parsed unqualified-id.
  2263. ///
  2264. /// \returns true if parsing fails, false otherwise.
  2265. bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
  2266. ParsedType ObjectType,
  2267. UnqualifiedId &Result) {
  2268. assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
  2269. // Consume the 'operator' keyword.
  2270. SourceLocation KeywordLoc = ConsumeToken();
  2271. // Determine what kind of operator name we have.
  2272. unsigned SymbolIdx = 0;
  2273. SourceLocation SymbolLocations[3];
  2274. OverloadedOperatorKind Op = OO_None;
  2275. switch (Tok.getKind()) {
  2276. case tok::kw_new:
  2277. case tok::kw_delete: {
  2278. bool isNew = Tok.getKind() == tok::kw_new;
  2279. // Consume the 'new' or 'delete'.
  2280. SymbolLocations[SymbolIdx++] = ConsumeToken();
  2281. // Check for array new/delete.
  2282. if (Tok.is(tok::l_square) &&
  2283. (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
  2284. // Consume the '[' and ']'.
  2285. BalancedDelimiterTracker T(*this, tok::l_square);
  2286. T.consumeOpen();
  2287. T.consumeClose();
  2288. if (T.getCloseLocation().isInvalid())
  2289. return true;
  2290. SymbolLocations[SymbolIdx++] = T.getOpenLocation();
  2291. SymbolLocations[SymbolIdx++] = T.getCloseLocation();
  2292. Op = isNew? OO_Array_New : OO_Array_Delete;
  2293. } else {
  2294. Op = isNew? OO_New : OO_Delete;
  2295. }
  2296. break;
  2297. }
  2298. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  2299. case tok::Token: \
  2300. SymbolLocations[SymbolIdx++] = ConsumeToken(); \
  2301. Op = OO_##Name; \
  2302. break;
  2303. #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
  2304. #include "clang/Basic/OperatorKinds.def"
  2305. case tok::l_paren: {
  2306. // Consume the '(' and ')'.
  2307. BalancedDelimiterTracker T(*this, tok::l_paren);
  2308. T.consumeOpen();
  2309. T.consumeClose();
  2310. if (T.getCloseLocation().isInvalid())
  2311. return true;
  2312. SymbolLocations[SymbolIdx++] = T.getOpenLocation();
  2313. SymbolLocations[SymbolIdx++] = T.getCloseLocation();
  2314. Op = OO_Call;
  2315. break;
  2316. }
  2317. case tok::l_square: {
  2318. // Consume the '[' and ']'.
  2319. BalancedDelimiterTracker T(*this, tok::l_square);
  2320. T.consumeOpen();
  2321. T.consumeClose();
  2322. if (T.getCloseLocation().isInvalid())
  2323. return true;
  2324. SymbolLocations[SymbolIdx++] = T.getOpenLocation();
  2325. SymbolLocations[SymbolIdx++] = T.getCloseLocation();
  2326. Op = OO_Subscript;
  2327. break;
  2328. }
  2329. case tok::code_completion: {
  2330. // Don't try to parse any further.
  2331. cutOffParsing();
  2332. // Code completion for the operator name.
  2333. Actions.CodeCompleteOperatorName(getCurScope());
  2334. return true;
  2335. }
  2336. default:
  2337. break;
  2338. }
  2339. if (Op != OO_None) {
  2340. // We have parsed an operator-function-id.
  2341. Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
  2342. return false;
  2343. }
  2344. // Parse a literal-operator-id.
  2345. //
  2346. // literal-operator-id: C++11 [over.literal]
  2347. // operator string-literal identifier
  2348. // operator user-defined-string-literal
  2349. if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
  2350. Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
  2351. SourceLocation DiagLoc;
  2352. unsigned DiagId = 0;
  2353. // We're past translation phase 6, so perform string literal concatenation
  2354. // before checking for "".
  2355. SmallVector<Token, 4> Toks;
  2356. SmallVector<SourceLocation, 4> TokLocs;
  2357. while (isTokenStringLiteral()) {
  2358. if (!Tok.is(tok::string_literal) && !DiagId) {
  2359. // C++11 [over.literal]p1:
  2360. // The string-literal or user-defined-string-literal in a
  2361. // literal-operator-id shall have no encoding-prefix [...].
  2362. DiagLoc = Tok.getLocation();
  2363. DiagId = diag::err_literal_operator_string_prefix;
  2364. }
  2365. Toks.push_back(Tok);
  2366. TokLocs.push_back(ConsumeStringToken());
  2367. }
  2368. StringLiteralParser Literal(Toks, PP);
  2369. if (Literal.hadError)
  2370. return true;
  2371. // Grab the literal operator's suffix, which will be either the next token
  2372. // or a ud-suffix from the string literal.
  2373. bool IsUDSuffix = !Literal.getUDSuffix().empty();
  2374. IdentifierInfo *II = nullptr;
  2375. SourceLocation SuffixLoc;
  2376. if (IsUDSuffix) {
  2377. II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
  2378. SuffixLoc =
  2379. Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
  2380. Literal.getUDSuffixOffset(),
  2381. PP.getSourceManager(), getLangOpts());
  2382. } else if (Tok.is(tok::identifier)) {
  2383. II = Tok.getIdentifierInfo();
  2384. SuffixLoc = ConsumeToken();
  2385. TokLocs.push_back(SuffixLoc);
  2386. } else {
  2387. Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
  2388. return true;
  2389. }
  2390. // The string literal must be empty.
  2391. if (!Literal.GetString().empty() || Literal.Pascal) {
  2392. // C++11 [over.literal]p1:
  2393. // The string-literal or user-defined-string-literal in a
  2394. // literal-operator-id shall [...] contain no characters
  2395. // other than the implicit terminating '\0'.
  2396. DiagLoc = TokLocs.front();
  2397. DiagId = diag::err_literal_operator_string_not_empty;
  2398. }
  2399. if (DiagId) {
  2400. // This isn't a valid literal-operator-id, but we think we know
  2401. // what the user meant. Tell them what they should have written.
  2402. SmallString<32> Str;
  2403. Str += "\"\"";
  2404. Str += II->getName();
  2405. Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
  2406. SourceRange(TokLocs.front(), TokLocs.back()), Str);
  2407. }
  2408. Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
  2409. return Actions.checkLiteralOperatorId(SS, Result, IsUDSuffix);
  2410. }
  2411. // Parse a conversion-function-id.
  2412. //
  2413. // conversion-function-id: [C++ 12.3.2]
  2414. // operator conversion-type-id
  2415. //
  2416. // conversion-type-id:
  2417. // type-specifier-seq conversion-declarator[opt]
  2418. //
  2419. // conversion-declarator:
  2420. // ptr-operator conversion-declarator[opt]
  2421. // Parse the type-specifier-seq.
  2422. DeclSpec DS(AttrFactory);
  2423. if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
  2424. return true;
  2425. // Parse the conversion-declarator, which is merely a sequence of
  2426. // ptr-operators.
  2427. Declarator D(DS, DeclaratorContext::ConversionId);
  2428. ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
  2429. // Finish up the type.
  2430. TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
  2431. if (Ty.isInvalid())
  2432. return true;
  2433. // Note that this is a conversion-function-id.
  2434. Result.setConversionFunctionId(KeywordLoc, Ty.get(),
  2435. D.getSourceRange().getEnd());
  2436. return false;
  2437. }
  2438. /// Parse a C++ unqualified-id (or a C identifier), which describes the
  2439. /// name of an entity.
  2440. ///
  2441. /// \code
  2442. /// unqualified-id: [C++ expr.prim.general]
  2443. /// identifier
  2444. /// operator-function-id
  2445. /// conversion-function-id
  2446. /// [C++0x] literal-operator-id [TODO]
  2447. /// ~ class-name
  2448. /// template-id
  2449. ///
  2450. /// \endcode
  2451. ///
  2452. /// \param SS The nested-name-specifier that preceded this unqualified-id. If
  2453. /// non-empty, then we are parsing the unqualified-id of a qualified-id.
  2454. ///
  2455. /// \param ObjectType if this unqualified-id occurs within a member access
  2456. /// expression, the type of the base object whose member is being accessed.
  2457. ///
  2458. /// \param ObjectHadErrors if this unqualified-id occurs within a member access
  2459. /// expression, indicates whether the original subexpressions had any errors.
  2460. /// When true, diagnostics for missing 'template' keyword will be supressed.
  2461. ///
  2462. /// \param EnteringContext whether we are entering the scope of the
  2463. /// nested-name-specifier.
  2464. ///
  2465. /// \param AllowDestructorName whether we allow parsing of a destructor name.
  2466. ///
  2467. /// \param AllowConstructorName whether we allow parsing a constructor name.
  2468. ///
  2469. /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
  2470. ///
  2471. /// \param Result on a successful parse, contains the parsed unqualified-id.
  2472. ///
  2473. /// \returns true if parsing fails, false otherwise.
  2474. bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
  2475. bool ObjectHadErrors, bool EnteringContext,
  2476. bool AllowDestructorName,
  2477. bool AllowConstructorName,
  2478. bool AllowDeductionGuide,
  2479. SourceLocation *TemplateKWLoc,
  2480. UnqualifiedId &Result) {
  2481. if (TemplateKWLoc)
  2482. *TemplateKWLoc = SourceLocation();
  2483. // Handle 'A::template B'. This is for template-ids which have not
  2484. // already been annotated by ParseOptionalCXXScopeSpecifier().
  2485. bool TemplateSpecified = false;
  2486. if (Tok.is(tok::kw_template)) {
  2487. if (TemplateKWLoc && (ObjectType || SS.isSet())) {
  2488. TemplateSpecified = true;
  2489. *TemplateKWLoc = ConsumeToken();
  2490. } else {
  2491. SourceLocation TemplateLoc = ConsumeToken();
  2492. Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
  2493. << FixItHint::CreateRemoval(TemplateLoc);
  2494. }
  2495. }
  2496. // unqualified-id:
  2497. // identifier
  2498. // template-id (when it hasn't already been annotated)
  2499. if (Tok.is(tok::identifier)) {
  2500. // Consume the identifier.
  2501. IdentifierInfo *Id = Tok.getIdentifierInfo();
  2502. SourceLocation IdLoc = ConsumeToken();
  2503. if (!getLangOpts().CPlusPlus) {
  2504. // If we're not in C++, only identifiers matter. Record the
  2505. // identifier and return.
  2506. Result.setIdentifier(Id, IdLoc);
  2507. return false;
  2508. }
  2509. ParsedTemplateTy TemplateName;
  2510. if (AllowConstructorName &&
  2511. Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
  2512. // We have parsed a constructor name.
  2513. ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
  2514. EnteringContext);
  2515. if (!Ty)
  2516. return true;
  2517. Result.setConstructorName(Ty, IdLoc, IdLoc);
  2518. } else if (getLangOpts().CPlusPlus17 &&
  2519. AllowDeductionGuide && SS.isEmpty() &&
  2520. Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
  2521. &TemplateName)) {
  2522. // We have parsed a template-name naming a deduction guide.
  2523. Result.setDeductionGuideName(TemplateName, IdLoc);
  2524. } else {
  2525. // We have parsed an identifier.
  2526. Result.setIdentifier(Id, IdLoc);
  2527. }
  2528. // If the next token is a '<', we may have a template.
  2529. TemplateTy Template;
  2530. if (Tok.is(tok::less))
  2531. return ParseUnqualifiedIdTemplateId(
  2532. SS, ObjectType, ObjectHadErrors,
  2533. TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
  2534. EnteringContext, Result, TemplateSpecified);
  2535. else if (TemplateSpecified &&
  2536. Actions.ActOnTemplateName(
  2537. getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
  2538. EnteringContext, Template,
  2539. /*AllowInjectedClassName*/ true) == TNK_Non_template)
  2540. return true;
  2541. return false;
  2542. }
  2543. // unqualified-id:
  2544. // template-id (already parsed and annotated)
  2545. if (Tok.is(tok::annot_template_id)) {
  2546. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  2547. // FIXME: Consider passing invalid template-ids on to callers; they may
  2548. // be able to recover better than we can.
  2549. if (TemplateId->isInvalid()) {
  2550. ConsumeAnnotationToken();
  2551. return true;
  2552. }
  2553. // If the template-name names the current class, then this is a constructor
  2554. if (AllowConstructorName && TemplateId->Name &&
  2555. Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
  2556. if (SS.isSet()) {
  2557. // C++ [class.qual]p2 specifies that a qualified template-name
  2558. // is taken as the constructor name where a constructor can be
  2559. // declared. Thus, the template arguments are extraneous, so
  2560. // complain about them and remove them entirely.
  2561. Diag(TemplateId->TemplateNameLoc,
  2562. diag::err_out_of_line_constructor_template_id)
  2563. << TemplateId->Name
  2564. << FixItHint::CreateRemoval(
  2565. SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
  2566. ParsedType Ty = Actions.getConstructorName(
  2567. *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
  2568. EnteringContext);
  2569. if (!Ty)
  2570. return true;
  2571. Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
  2572. TemplateId->RAngleLoc);
  2573. ConsumeAnnotationToken();
  2574. return false;
  2575. }
  2576. Result.setConstructorTemplateId(TemplateId);
  2577. ConsumeAnnotationToken();
  2578. return false;
  2579. }
  2580. // We have already parsed a template-id; consume the annotation token as
  2581. // our unqualified-id.
  2582. Result.setTemplateId(TemplateId);
  2583. SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
  2584. if (TemplateLoc.isValid()) {
  2585. if (TemplateKWLoc && (ObjectType || SS.isSet()))
  2586. *TemplateKWLoc = TemplateLoc;
  2587. else
  2588. Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
  2589. << FixItHint::CreateRemoval(TemplateLoc);
  2590. }
  2591. ConsumeAnnotationToken();
  2592. return false;
  2593. }
  2594. // unqualified-id:
  2595. // operator-function-id
  2596. // conversion-function-id
  2597. if (Tok.is(tok::kw_operator)) {
  2598. if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
  2599. return true;
  2600. // If we have an operator-function-id or a literal-operator-id and the next
  2601. // token is a '<', we may have a
  2602. //
  2603. // template-id:
  2604. // operator-function-id < template-argument-list[opt] >
  2605. TemplateTy Template;
  2606. if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
  2607. Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
  2608. Tok.is(tok::less))
  2609. return ParseUnqualifiedIdTemplateId(
  2610. SS, ObjectType, ObjectHadErrors,
  2611. TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
  2612. SourceLocation(), EnteringContext, Result, TemplateSpecified);
  2613. else if (TemplateSpecified &&
  2614. Actions.ActOnTemplateName(
  2615. getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
  2616. EnteringContext, Template,
  2617. /*AllowInjectedClassName*/ true) == TNK_Non_template)
  2618. return true;
  2619. return false;
  2620. }
  2621. if (getLangOpts().CPlusPlus &&
  2622. (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
  2623. // C++ [expr.unary.op]p10:
  2624. // There is an ambiguity in the unary-expression ~X(), where X is a
  2625. // class-name. The ambiguity is resolved in favor of treating ~ as a
  2626. // unary complement rather than treating ~X as referring to a destructor.
  2627. // Parse the '~'.
  2628. SourceLocation TildeLoc = ConsumeToken();
  2629. if (TemplateSpecified) {
  2630. // C++ [temp.names]p3:
  2631. // A name prefixed by the keyword template shall be a template-id [...]
  2632. //
  2633. // A template-id cannot begin with a '~' token. This would never work
  2634. // anyway: x.~A<int>() would specify that the destructor is a template,
  2635. // not that 'A' is a template.
  2636. //
  2637. // FIXME: Suggest replacing the attempted destructor name with a correct
  2638. // destructor name and recover. (This is not trivial if this would become
  2639. // a pseudo-destructor name).
  2640. Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
  2641. << Tok.getLocation();
  2642. return true;
  2643. }
  2644. if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
  2645. DeclSpec DS(AttrFactory);
  2646. SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
  2647. if (ParsedType Type =
  2648. Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
  2649. Result.setDestructorName(TildeLoc, Type, EndLoc);
  2650. return false;
  2651. }
  2652. return true;
  2653. }
  2654. // Parse the class-name.
  2655. if (Tok.isNot(tok::identifier)) {
  2656. Diag(Tok, diag::err_destructor_tilde_identifier);
  2657. return true;
  2658. }
  2659. // If the user wrote ~T::T, correct it to T::~T.
  2660. DeclaratorScopeObj DeclScopeObj(*this, SS);
  2661. if (NextToken().is(tok::coloncolon)) {
  2662. // Don't let ParseOptionalCXXScopeSpecifier() "correct"
  2663. // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
  2664. // it will confuse this recovery logic.
  2665. ColonProtectionRAIIObject ColonRAII(*this, false);
  2666. if (SS.isSet()) {
  2667. AnnotateScopeToken(SS, /*NewAnnotation*/true);
  2668. SS.clear();
  2669. }
  2670. if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
  2671. EnteringContext))
  2672. return true;
  2673. if (SS.isNotEmpty())
  2674. ObjectType = nullptr;
  2675. if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
  2676. !SS.isSet()) {
  2677. Diag(TildeLoc, diag::err_destructor_tilde_scope);
  2678. return true;
  2679. }
  2680. // Recover as if the tilde had been written before the identifier.
  2681. Diag(TildeLoc, diag::err_destructor_tilde_scope)
  2682. << FixItHint::CreateRemoval(TildeLoc)
  2683. << FixItHint::CreateInsertion(Tok.getLocation(), "~");
  2684. // Temporarily enter the scope for the rest of this function.
  2685. if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
  2686. DeclScopeObj.EnterDeclaratorScope();
  2687. }
  2688. // Parse the class-name (or template-name in a simple-template-id).
  2689. IdentifierInfo *ClassName = Tok.getIdentifierInfo();
  2690. SourceLocation ClassNameLoc = ConsumeToken();
  2691. if (Tok.is(tok::less)) {
  2692. Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
  2693. return ParseUnqualifiedIdTemplateId(
  2694. SS, ObjectType, ObjectHadErrors,
  2695. TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
  2696. ClassNameLoc, EnteringContext, Result, TemplateSpecified);
  2697. }
  2698. // Note that this is a destructor name.
  2699. ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
  2700. ClassNameLoc, getCurScope(),
  2701. SS, ObjectType,
  2702. EnteringContext);
  2703. if (!Ty)
  2704. return true;
  2705. Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
  2706. return false;
  2707. }
  2708. Diag(Tok, diag::err_expected_unqualified_id)
  2709. << getLangOpts().CPlusPlus;
  2710. return true;
  2711. }
  2712. /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
  2713. /// memory in a typesafe manner and call constructors.
  2714. ///
  2715. /// This method is called to parse the new expression after the optional :: has
  2716. /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
  2717. /// is its location. Otherwise, "Start" is the location of the 'new' token.
  2718. ///
  2719. /// new-expression:
  2720. /// '::'[opt] 'new' new-placement[opt] new-type-id
  2721. /// new-initializer[opt]
  2722. /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
  2723. /// new-initializer[opt]
  2724. ///
  2725. /// new-placement:
  2726. /// '(' expression-list ')'
  2727. ///
  2728. /// new-type-id:
  2729. /// type-specifier-seq new-declarator[opt]
  2730. /// [GNU] attributes type-specifier-seq new-declarator[opt]
  2731. ///
  2732. /// new-declarator:
  2733. /// ptr-operator new-declarator[opt]
  2734. /// direct-new-declarator
  2735. ///
  2736. /// new-initializer:
  2737. /// '(' expression-list[opt] ')'
  2738. /// [C++0x] braced-init-list
  2739. ///
  2740. ExprResult
  2741. Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
  2742. assert(Tok.is(tok::kw_new) && "expected 'new' token");
  2743. ConsumeToken(); // Consume 'new'
  2744. // A '(' now can be a new-placement or the '(' wrapping the type-id in the
  2745. // second form of new-expression. It can't be a new-type-id.
  2746. ExprVector PlacementArgs;
  2747. SourceLocation PlacementLParen, PlacementRParen;
  2748. SourceRange TypeIdParens;
  2749. DeclSpec DS(AttrFactory);
  2750. Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNew);
  2751. if (Tok.is(tok::l_paren)) {
  2752. // If it turns out to be a placement, we change the type location.
  2753. BalancedDelimiterTracker T(*this, tok::l_paren);
  2754. T.consumeOpen();
  2755. PlacementLParen = T.getOpenLocation();
  2756. if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
  2757. SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
  2758. return ExprError();
  2759. }
  2760. T.consumeClose();
  2761. PlacementRParen = T.getCloseLocation();
  2762. if (PlacementRParen.isInvalid()) {
  2763. SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
  2764. return ExprError();
  2765. }
  2766. if (PlacementArgs.empty()) {
  2767. // Reset the placement locations. There was no placement.
  2768. TypeIdParens = T.getRange();
  2769. PlacementLParen = PlacementRParen = SourceLocation();
  2770. } else {
  2771. // We still need the type.
  2772. if (Tok.is(tok::l_paren)) {
  2773. BalancedDelimiterTracker T(*this, tok::l_paren);
  2774. T.consumeOpen();
  2775. MaybeParseGNUAttributes(DeclaratorInfo);
  2776. ParseSpecifierQualifierList(DS);
  2777. DeclaratorInfo.SetSourceRange(DS.getSourceRange());
  2778. ParseDeclarator(DeclaratorInfo);
  2779. T.consumeClose();
  2780. TypeIdParens = T.getRange();
  2781. } else {
  2782. MaybeParseGNUAttributes(DeclaratorInfo);
  2783. if (ParseCXXTypeSpecifierSeq(DS))
  2784. DeclaratorInfo.setInvalidType(true);
  2785. else {
  2786. DeclaratorInfo.SetSourceRange(DS.getSourceRange());
  2787. ParseDeclaratorInternal(DeclaratorInfo,
  2788. &Parser::ParseDirectNewDeclarator);
  2789. }
  2790. }
  2791. }
  2792. } else {
  2793. // A new-type-id is a simplified type-id, where essentially the
  2794. // direct-declarator is replaced by a direct-new-declarator.
  2795. MaybeParseGNUAttributes(DeclaratorInfo);
  2796. if (ParseCXXTypeSpecifierSeq(DS))
  2797. DeclaratorInfo.setInvalidType(true);
  2798. else {
  2799. DeclaratorInfo.SetSourceRange(DS.getSourceRange());
  2800. ParseDeclaratorInternal(DeclaratorInfo,
  2801. &Parser::ParseDirectNewDeclarator);
  2802. }
  2803. }
  2804. if (DeclaratorInfo.isInvalidType()) {
  2805. SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
  2806. return ExprError();
  2807. }
  2808. ExprResult Initializer;
  2809. if (Tok.is(tok::l_paren)) {
  2810. SourceLocation ConstructorLParen, ConstructorRParen;
  2811. ExprVector ConstructorArgs;
  2812. BalancedDelimiterTracker T(*this, tok::l_paren);
  2813. T.consumeOpen();
  2814. ConstructorLParen = T.getOpenLocation();
  2815. if (Tok.isNot(tok::r_paren)) {
  2816. CommaLocsTy CommaLocs;
  2817. auto RunSignatureHelp = [&]() {
  2818. ParsedType TypeRep =
  2819. Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
  2820. QualType PreferredType;
  2821. // ActOnTypeName might adjust DeclaratorInfo and return a null type even
  2822. // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
  2823. // `new decltype(invalid) (^)`.
  2824. if (TypeRep)
  2825. PreferredType = Actions.ProduceConstructorSignatureHelp(
  2826. TypeRep.get()->getCanonicalTypeInternal(),
  2827. DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen,
  2828. /*Braced=*/false);
  2829. CalledSignatureHelp = true;
  2830. return PreferredType;
  2831. };
  2832. if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
  2833. PreferredType.enterFunctionArgument(Tok.getLocation(),
  2834. RunSignatureHelp);
  2835. })) {
  2836. if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
  2837. RunSignatureHelp();
  2838. SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
  2839. return ExprError();
  2840. }
  2841. }
  2842. T.consumeClose();
  2843. ConstructorRParen = T.getCloseLocation();
  2844. if (ConstructorRParen.isInvalid()) {
  2845. SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
  2846. return ExprError();
  2847. }
  2848. Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
  2849. ConstructorRParen,
  2850. ConstructorArgs);
  2851. } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
  2852. Diag(Tok.getLocation(),
  2853. diag::warn_cxx98_compat_generalized_initializer_lists);
  2854. Initializer = ParseBraceInitializer();
  2855. }
  2856. if (Initializer.isInvalid())
  2857. return Initializer;
  2858. return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
  2859. PlacementArgs, PlacementRParen,
  2860. TypeIdParens, DeclaratorInfo, Initializer.get());
  2861. }
  2862. /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
  2863. /// passed to ParseDeclaratorInternal.
  2864. ///
  2865. /// direct-new-declarator:
  2866. /// '[' expression[opt] ']'
  2867. /// direct-new-declarator '[' constant-expression ']'
  2868. ///
  2869. void Parser::ParseDirectNewDeclarator(Declarator &D) {
  2870. // Parse the array dimensions.
  2871. bool First = true;
  2872. while (Tok.is(tok::l_square)) {
  2873. // An array-size expression can't start with a lambda.
  2874. if (CheckProhibitedCXX11Attribute())
  2875. continue;
  2876. BalancedDelimiterTracker T(*this, tok::l_square);
  2877. T.consumeOpen();
  2878. ExprResult Size =
  2879. First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
  2880. : ParseConstantExpression();
  2881. if (Size.isInvalid()) {
  2882. // Recover
  2883. SkipUntil(tok::r_square, StopAtSemi);
  2884. return;
  2885. }
  2886. First = false;
  2887. T.consumeClose();
  2888. // Attributes here appertain to the array type. C++11 [expr.new]p5.
  2889. ParsedAttributes Attrs(AttrFactory);
  2890. MaybeParseCXX11Attributes(Attrs);
  2891. D.AddTypeInfo(DeclaratorChunk::getArray(0,
  2892. /*isStatic=*/false, /*isStar=*/false,
  2893. Size.get(), T.getOpenLocation(),
  2894. T.getCloseLocation()),
  2895. std::move(Attrs), T.getCloseLocation());
  2896. if (T.getCloseLocation().isInvalid())
  2897. return;
  2898. }
  2899. }
  2900. /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
  2901. /// This ambiguity appears in the syntax of the C++ new operator.
  2902. ///
  2903. /// new-expression:
  2904. /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
  2905. /// new-initializer[opt]
  2906. ///
  2907. /// new-placement:
  2908. /// '(' expression-list ')'
  2909. ///
  2910. bool Parser::ParseExpressionListOrTypeId(
  2911. SmallVectorImpl<Expr*> &PlacementArgs,
  2912. Declarator &D) {
  2913. // The '(' was already consumed.
  2914. if (isTypeIdInParens()) {
  2915. ParseSpecifierQualifierList(D.getMutableDeclSpec());
  2916. D.SetSourceRange(D.getDeclSpec().getSourceRange());
  2917. ParseDeclarator(D);
  2918. return D.isInvalidType();
  2919. }
  2920. // It's not a type, it has to be an expression list.
  2921. // Discard the comma locations - ActOnCXXNew has enough parameters.
  2922. CommaLocsTy CommaLocs;
  2923. return ParseExpressionList(PlacementArgs, CommaLocs);
  2924. }
  2925. /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
  2926. /// to free memory allocated by new.
  2927. ///
  2928. /// This method is called to parse the 'delete' expression after the optional
  2929. /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
  2930. /// and "Start" is its location. Otherwise, "Start" is the location of the
  2931. /// 'delete' token.
  2932. ///
  2933. /// delete-expression:
  2934. /// '::'[opt] 'delete' cast-expression
  2935. /// '::'[opt] 'delete' '[' ']' cast-expression
  2936. ExprResult
  2937. Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
  2938. assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
  2939. ConsumeToken(); // Consume 'delete'
  2940. // Array delete?
  2941. bool ArrayDelete = false;
  2942. if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
  2943. // C++11 [expr.delete]p1:
  2944. // Whenever the delete keyword is followed by empty square brackets, it
  2945. // shall be interpreted as [array delete].
  2946. // [Footnote: A lambda expression with a lambda-introducer that consists
  2947. // of empty square brackets can follow the delete keyword if
  2948. // the lambda expression is enclosed in parentheses.]
  2949. const Token Next = GetLookAheadToken(2);
  2950. // Basic lookahead to check if we have a lambda expression.
  2951. if (Next.isOneOf(tok::l_brace, tok::less) ||
  2952. (Next.is(tok::l_paren) &&
  2953. (GetLookAheadToken(3).is(tok::r_paren) ||
  2954. (GetLookAheadToken(3).is(tok::identifier) &&
  2955. GetLookAheadToken(4).is(tok::identifier))))) {
  2956. TentativeParsingAction TPA(*this);
  2957. SourceLocation LSquareLoc = Tok.getLocation();
  2958. SourceLocation RSquareLoc = NextToken().getLocation();
  2959. // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
  2960. // case.
  2961. SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
  2962. SourceLocation RBraceLoc;
  2963. bool EmitFixIt = false;
  2964. if (Tok.is(tok::l_brace)) {
  2965. ConsumeBrace();
  2966. SkipUntil(tok::r_brace, StopBeforeMatch);
  2967. RBraceLoc = Tok.getLocation();
  2968. EmitFixIt = true;
  2969. }
  2970. TPA.Revert();
  2971. if (EmitFixIt)
  2972. Diag(Start, diag::err_lambda_after_delete)
  2973. << SourceRange(Start, RSquareLoc)
  2974. << FixItHint::CreateInsertion(LSquareLoc, "(")
  2975. << FixItHint::CreateInsertion(
  2976. Lexer::getLocForEndOfToken(
  2977. RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
  2978. ")");
  2979. else
  2980. Diag(Start, diag::err_lambda_after_delete)
  2981. << SourceRange(Start, RSquareLoc);
  2982. // Warn that the non-capturing lambda isn't surrounded by parentheses
  2983. // to disambiguate it from 'delete[]'.
  2984. ExprResult Lambda = ParseLambdaExpression();
  2985. if (Lambda.isInvalid())
  2986. return ExprError();
  2987. // Evaluate any postfix expressions used on the lambda.
  2988. Lambda = ParsePostfixExpressionSuffix(Lambda);
  2989. if (Lambda.isInvalid())
  2990. return ExprError();
  2991. return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
  2992. Lambda.get());
  2993. }
  2994. ArrayDelete = true;
  2995. BalancedDelimiterTracker T(*this, tok::l_square);
  2996. T.consumeOpen();
  2997. T.consumeClose();
  2998. if (T.getCloseLocation().isInvalid())
  2999. return ExprError();
  3000. }
  3001. ExprResult Operand(ParseCastExpression(AnyCastExpr));
  3002. if (Operand.isInvalid())
  3003. return Operand;
  3004. return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
  3005. }
  3006. /// ParseRequiresExpression - Parse a C++2a requires-expression.
  3007. /// C++2a [expr.prim.req]p1
  3008. /// A requires-expression provides a concise way to express requirements on
  3009. /// template arguments. A requirement is one that can be checked by name
  3010. /// lookup (6.4) or by checking properties of types and expressions.
  3011. ///
  3012. /// requires-expression:
  3013. /// 'requires' requirement-parameter-list[opt] requirement-body
  3014. ///
  3015. /// requirement-parameter-list:
  3016. /// '(' parameter-declaration-clause[opt] ')'
  3017. ///
  3018. /// requirement-body:
  3019. /// '{' requirement-seq '}'
  3020. ///
  3021. /// requirement-seq:
  3022. /// requirement
  3023. /// requirement-seq requirement
  3024. ///
  3025. /// requirement:
  3026. /// simple-requirement
  3027. /// type-requirement
  3028. /// compound-requirement
  3029. /// nested-requirement
  3030. ExprResult Parser::ParseRequiresExpression() {
  3031. assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword");
  3032. SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
  3033. llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
  3034. if (Tok.is(tok::l_paren)) {
  3035. // requirement parameter list is present.
  3036. ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
  3037. Scope::DeclScope);
  3038. BalancedDelimiterTracker Parens(*this, tok::l_paren);
  3039. Parens.consumeOpen();
  3040. if (!Tok.is(tok::r_paren)) {
  3041. ParsedAttributes FirstArgAttrs(getAttrFactory());
  3042. SourceLocation EllipsisLoc;
  3043. llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters;
  3044. ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
  3045. FirstArgAttrs, LocalParameters,
  3046. EllipsisLoc);
  3047. if (EllipsisLoc.isValid())
  3048. Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
  3049. for (auto &ParamInfo : LocalParameters)
  3050. LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
  3051. }
  3052. Parens.consumeClose();
  3053. }
  3054. BalancedDelimiterTracker Braces(*this, tok::l_brace);
  3055. if (Braces.expectAndConsume())
  3056. return ExprError();
  3057. // Start of requirement list
  3058. llvm::SmallVector<concepts::Requirement *, 2> Requirements;
  3059. // C++2a [expr.prim.req]p2
  3060. // Expressions appearing within a requirement-body are unevaluated operands.
  3061. EnterExpressionEvaluationContext Ctx(
  3062. Actions, Sema::ExpressionEvaluationContext::Unevaluated);
  3063. ParseScope BodyScope(this, Scope::DeclScope);
  3064. RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr(
  3065. RequiresKWLoc, LocalParameterDecls, getCurScope());
  3066. if (Tok.is(tok::r_brace)) {
  3067. // Grammar does not allow an empty body.
  3068. // requirement-body:
  3069. // { requirement-seq }
  3070. // requirement-seq:
  3071. // requirement
  3072. // requirement-seq requirement
  3073. Diag(Tok, diag::err_empty_requires_expr);
  3074. // Continue anyway and produce a requires expr with no requirements.
  3075. } else {
  3076. while (!Tok.is(tok::r_brace)) {
  3077. switch (Tok.getKind()) {
  3078. case tok::l_brace: {
  3079. // Compound requirement
  3080. // C++ [expr.prim.req.compound]
  3081. // compound-requirement:
  3082. // '{' expression '}' 'noexcept'[opt]
  3083. // return-type-requirement[opt] ';'
  3084. // return-type-requirement:
  3085. // trailing-return-type
  3086. // '->' cv-qualifier-seq[opt] constrained-parameter
  3087. // cv-qualifier-seq[opt] abstract-declarator[opt]
  3088. BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
  3089. ExprBraces.consumeOpen();
  3090. ExprResult Expression =
  3091. Actions.CorrectDelayedTyposInExpr(ParseExpression());
  3092. if (!Expression.isUsable()) {
  3093. ExprBraces.skipToEnd();
  3094. SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
  3095. break;
  3096. }
  3097. if (ExprBraces.consumeClose())
  3098. ExprBraces.skipToEnd();
  3099. concepts::Requirement *Req = nullptr;
  3100. SourceLocation NoexceptLoc;
  3101. TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
  3102. if (Tok.is(tok::semi)) {
  3103. Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
  3104. if (Req)
  3105. Requirements.push_back(Req);
  3106. break;
  3107. }
  3108. if (!TryConsumeToken(tok::arrow))
  3109. // User probably forgot the arrow, remind them and try to continue.
  3110. Diag(Tok, diag::err_requires_expr_missing_arrow)
  3111. << FixItHint::CreateInsertion(Tok.getLocation(), "->");
  3112. // Try to parse a 'type-constraint'
  3113. if (TryAnnotateTypeConstraint()) {
  3114. SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
  3115. break;
  3116. }
  3117. if (!isTypeConstraintAnnotation()) {
  3118. Diag(Tok, diag::err_requires_expr_expected_type_constraint);
  3119. SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
  3120. break;
  3121. }
  3122. CXXScopeSpec SS;
  3123. if (Tok.is(tok::annot_cxxscope)) {
  3124. Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
  3125. Tok.getAnnotationRange(),
  3126. SS);
  3127. ConsumeAnnotationToken();
  3128. }
  3129. Req = Actions.ActOnCompoundRequirement(
  3130. Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
  3131. TemplateParameterDepth);
  3132. ConsumeAnnotationToken();
  3133. if (Req)
  3134. Requirements.push_back(Req);
  3135. break;
  3136. }
  3137. default: {
  3138. bool PossibleRequiresExprInSimpleRequirement = false;
  3139. if (Tok.is(tok::kw_requires)) {
  3140. auto IsNestedRequirement = [&] {
  3141. RevertingTentativeParsingAction TPA(*this);
  3142. ConsumeToken(); // 'requires'
  3143. if (Tok.is(tok::l_brace))
  3144. // This is a requires expression
  3145. // requires (T t) {
  3146. // requires { t++; };
  3147. // ... ^
  3148. // }
  3149. return false;
  3150. if (Tok.is(tok::l_paren)) {
  3151. // This might be the parameter list of a requires expression
  3152. ConsumeParen();
  3153. auto Res = TryParseParameterDeclarationClause();
  3154. if (Res != TPResult::False) {
  3155. // Skip to the closing parenthesis
  3156. // FIXME: Don't traverse these tokens twice (here and in
  3157. // TryParseParameterDeclarationClause).
  3158. unsigned Depth = 1;
  3159. while (Depth != 0) {
  3160. if (Tok.is(tok::l_paren))
  3161. Depth++;
  3162. else if (Tok.is(tok::r_paren))
  3163. Depth--;
  3164. ConsumeAnyToken();
  3165. }
  3166. // requires (T t) {
  3167. // requires () ?
  3168. // ... ^
  3169. // - OR -
  3170. // requires (int x) ?
  3171. // ... ^
  3172. // }
  3173. if (Tok.is(tok::l_brace))
  3174. // requires (...) {
  3175. // ^ - a requires expression as a
  3176. // simple-requirement.
  3177. return false;
  3178. }
  3179. }
  3180. return true;
  3181. };
  3182. if (IsNestedRequirement()) {
  3183. ConsumeToken();
  3184. // Nested requirement
  3185. // C++ [expr.prim.req.nested]
  3186. // nested-requirement:
  3187. // 'requires' constraint-expression ';'
  3188. ExprResult ConstraintExpr =
  3189. Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
  3190. if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
  3191. SkipUntil(tok::semi, tok::r_brace,
  3192. SkipUntilFlags::StopBeforeMatch);
  3193. break;
  3194. }
  3195. if (auto *Req =
  3196. Actions.ActOnNestedRequirement(ConstraintExpr.get()))
  3197. Requirements.push_back(Req);
  3198. else {
  3199. SkipUntil(tok::semi, tok::r_brace,
  3200. SkipUntilFlags::StopBeforeMatch);
  3201. break;
  3202. }
  3203. break;
  3204. } else
  3205. PossibleRequiresExprInSimpleRequirement = true;
  3206. } else if (Tok.is(tok::kw_typename)) {
  3207. // This might be 'typename T::value_type;' (a type requirement) or
  3208. // 'typename T::value_type{};' (a simple requirement).
  3209. TentativeParsingAction TPA(*this);
  3210. // We need to consume the typename to allow 'requires { typename a; }'
  3211. SourceLocation TypenameKWLoc = ConsumeToken();
  3212. if (TryAnnotateOptionalCXXScopeToken()) {
  3213. TPA.Commit();
  3214. SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
  3215. break;
  3216. }
  3217. CXXScopeSpec SS;
  3218. if (Tok.is(tok::annot_cxxscope)) {
  3219. Actions.RestoreNestedNameSpecifierAnnotation(
  3220. Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
  3221. ConsumeAnnotationToken();
  3222. }
  3223. if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
  3224. !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
  3225. TPA.Commit();
  3226. SourceLocation NameLoc = Tok.getLocation();
  3227. IdentifierInfo *II = nullptr;
  3228. TemplateIdAnnotation *TemplateId = nullptr;
  3229. if (Tok.is(tok::identifier)) {
  3230. II = Tok.getIdentifierInfo();
  3231. ConsumeToken();
  3232. } else {
  3233. TemplateId = takeTemplateIdAnnotation(Tok);
  3234. ConsumeAnnotationToken();
  3235. if (TemplateId->isInvalid())
  3236. break;
  3237. }
  3238. if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
  3239. NameLoc, II,
  3240. TemplateId)) {
  3241. Requirements.push_back(Req);
  3242. }
  3243. break;
  3244. }
  3245. TPA.Revert();
  3246. }
  3247. // Simple requirement
  3248. // C++ [expr.prim.req.simple]
  3249. // simple-requirement:
  3250. // expression ';'
  3251. SourceLocation StartLoc = Tok.getLocation();
  3252. ExprResult Expression =
  3253. Actions.CorrectDelayedTyposInExpr(ParseExpression());
  3254. if (!Expression.isUsable()) {
  3255. SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
  3256. break;
  3257. }
  3258. if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
  3259. Diag(StartLoc, diag::err_requires_expr_in_simple_requirement)
  3260. << FixItHint::CreateInsertion(StartLoc, "requires");
  3261. if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
  3262. Requirements.push_back(Req);
  3263. else {
  3264. SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
  3265. break;
  3266. }
  3267. // User may have tried to put some compound requirement stuff here
  3268. if (Tok.is(tok::kw_noexcept)) {
  3269. Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
  3270. << FixItHint::CreateInsertion(StartLoc, "{")
  3271. << FixItHint::CreateInsertion(Tok.getLocation(), "}");
  3272. SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
  3273. break;
  3274. }
  3275. break;
  3276. }
  3277. }
  3278. if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
  3279. SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
  3280. TryConsumeToken(tok::semi);
  3281. break;
  3282. }
  3283. }
  3284. if (Requirements.empty()) {
  3285. // Don't emit an empty requires expr here to avoid confusing the user with
  3286. // other diagnostics quoting an empty requires expression they never
  3287. // wrote.
  3288. Braces.consumeClose();
  3289. Actions.ActOnFinishRequiresExpr();
  3290. return ExprError();
  3291. }
  3292. }
  3293. Braces.consumeClose();
  3294. Actions.ActOnFinishRequiresExpr();
  3295. return Actions.ActOnRequiresExpr(RequiresKWLoc, Body, LocalParameterDecls,
  3296. Requirements, Braces.getCloseLocation());
  3297. }
  3298. static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
  3299. switch (kind) {
  3300. default: llvm_unreachable("Not a known type trait");
  3301. #define TYPE_TRAIT_1(Spelling, Name, Key) \
  3302. case tok::kw_ ## Spelling: return UTT_ ## Name;
  3303. #define TYPE_TRAIT_2(Spelling, Name, Key) \
  3304. case tok::kw_ ## Spelling: return BTT_ ## Name;
  3305. #include "clang/Basic/TokenKinds.def"
  3306. #define TYPE_TRAIT_N(Spelling, Name, Key) \
  3307. case tok::kw_ ## Spelling: return TT_ ## Name;
  3308. #include "clang/Basic/TokenKinds.def"
  3309. }
  3310. }
  3311. static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
  3312. switch (kind) {
  3313. default:
  3314. llvm_unreachable("Not a known array type trait");
  3315. #define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
  3316. case tok::kw_##Spelling: \
  3317. return ATT_##Name;
  3318. #include "clang/Basic/TokenKinds.def"
  3319. }
  3320. }
  3321. static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
  3322. switch (kind) {
  3323. default:
  3324. llvm_unreachable("Not a known unary expression trait.");
  3325. #define EXPRESSION_TRAIT(Spelling, Name, Key) \
  3326. case tok::kw_##Spelling: \
  3327. return ET_##Name;
  3328. #include "clang/Basic/TokenKinds.def"
  3329. }
  3330. }
  3331. static unsigned TypeTraitArity(tok::TokenKind kind) {
  3332. switch (kind) {
  3333. default: llvm_unreachable("Not a known type trait");
  3334. #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
  3335. #include "clang/Basic/TokenKinds.def"
  3336. }
  3337. }
  3338. /// Parse the built-in type-trait pseudo-functions that allow
  3339. /// implementation of the TR1/C++11 type traits templates.
  3340. ///
  3341. /// primary-expression:
  3342. /// unary-type-trait '(' type-id ')'
  3343. /// binary-type-trait '(' type-id ',' type-id ')'
  3344. /// type-trait '(' type-id-seq ')'
  3345. ///
  3346. /// type-id-seq:
  3347. /// type-id ...[opt] type-id-seq[opt]
  3348. ///
  3349. ExprResult Parser::ParseTypeTrait() {
  3350. tok::TokenKind Kind = Tok.getKind();
  3351. unsigned Arity = TypeTraitArity(Kind);
  3352. SourceLocation Loc = ConsumeToken();
  3353. BalancedDelimiterTracker Parens(*this, tok::l_paren);
  3354. if (Parens.expectAndConsume())
  3355. return ExprError();
  3356. SmallVector<ParsedType, 2> Args;
  3357. do {
  3358. // Parse the next type.
  3359. TypeResult Ty = ParseTypeName();
  3360. if (Ty.isInvalid()) {
  3361. Parens.skipToEnd();
  3362. return ExprError();
  3363. }
  3364. // Parse the ellipsis, if present.
  3365. if (Tok.is(tok::ellipsis)) {
  3366. Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
  3367. if (Ty.isInvalid()) {
  3368. Parens.skipToEnd();
  3369. return ExprError();
  3370. }
  3371. }
  3372. // Add this type to the list of arguments.
  3373. Args.push_back(Ty.get());
  3374. } while (TryConsumeToken(tok::comma));
  3375. if (Parens.consumeClose())
  3376. return ExprError();
  3377. SourceLocation EndLoc = Parens.getCloseLocation();
  3378. if (Arity && Args.size() != Arity) {
  3379. Diag(EndLoc, diag::err_type_trait_arity)
  3380. << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
  3381. return ExprError();
  3382. }
  3383. if (!Arity && Args.empty()) {
  3384. Diag(EndLoc, diag::err_type_trait_arity)
  3385. << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
  3386. return ExprError();
  3387. }
  3388. return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
  3389. }
  3390. /// ParseArrayTypeTrait - Parse the built-in array type-trait
  3391. /// pseudo-functions.
  3392. ///
  3393. /// primary-expression:
  3394. /// [Embarcadero] '__array_rank' '(' type-id ')'
  3395. /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
  3396. ///
  3397. ExprResult Parser::ParseArrayTypeTrait() {
  3398. ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
  3399. SourceLocation Loc = ConsumeToken();
  3400. BalancedDelimiterTracker T(*this, tok::l_paren);
  3401. if (T.expectAndConsume())
  3402. return ExprError();
  3403. TypeResult Ty = ParseTypeName();
  3404. if (Ty.isInvalid()) {
  3405. SkipUntil(tok::comma, StopAtSemi);
  3406. SkipUntil(tok::r_paren, StopAtSemi);
  3407. return ExprError();
  3408. }
  3409. switch (ATT) {
  3410. case ATT_ArrayRank: {
  3411. T.consumeClose();
  3412. return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
  3413. T.getCloseLocation());
  3414. }
  3415. case ATT_ArrayExtent: {
  3416. if (ExpectAndConsume(tok::comma)) {
  3417. SkipUntil(tok::r_paren, StopAtSemi);
  3418. return ExprError();
  3419. }
  3420. ExprResult DimExpr = ParseExpression();
  3421. T.consumeClose();
  3422. return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
  3423. T.getCloseLocation());
  3424. }
  3425. }
  3426. llvm_unreachable("Invalid ArrayTypeTrait!");
  3427. }
  3428. /// ParseExpressionTrait - Parse built-in expression-trait
  3429. /// pseudo-functions like __is_lvalue_expr( xxx ).
  3430. ///
  3431. /// primary-expression:
  3432. /// [Embarcadero] expression-trait '(' expression ')'
  3433. ///
  3434. ExprResult Parser::ParseExpressionTrait() {
  3435. ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
  3436. SourceLocation Loc = ConsumeToken();
  3437. BalancedDelimiterTracker T(*this, tok::l_paren);
  3438. if (T.expectAndConsume())
  3439. return ExprError();
  3440. ExprResult Expr = ParseExpression();
  3441. T.consumeClose();
  3442. return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
  3443. T.getCloseLocation());
  3444. }
  3445. /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
  3446. /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
  3447. /// based on the context past the parens.
  3448. ExprResult
  3449. Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
  3450. ParsedType &CastTy,
  3451. BalancedDelimiterTracker &Tracker,
  3452. ColonProtectionRAIIObject &ColonProt) {
  3453. assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
  3454. assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
  3455. assert(isTypeIdInParens() && "Not a type-id!");
  3456. ExprResult Result(true);
  3457. CastTy = nullptr;
  3458. // We need to disambiguate a very ugly part of the C++ syntax:
  3459. //
  3460. // (T())x; - type-id
  3461. // (T())*x; - type-id
  3462. // (T())/x; - expression
  3463. // (T()); - expression
  3464. //
  3465. // The bad news is that we cannot use the specialized tentative parser, since
  3466. // it can only verify that the thing inside the parens can be parsed as
  3467. // type-id, it is not useful for determining the context past the parens.
  3468. //
  3469. // The good news is that the parser can disambiguate this part without
  3470. // making any unnecessary Action calls.
  3471. //
  3472. // It uses a scheme similar to parsing inline methods. The parenthesized
  3473. // tokens are cached, the context that follows is determined (possibly by
  3474. // parsing a cast-expression), and then we re-introduce the cached tokens
  3475. // into the token stream and parse them appropriately.
  3476. ParenParseOption ParseAs;
  3477. CachedTokens Toks;
  3478. // Store the tokens of the parentheses. We will parse them after we determine
  3479. // the context that follows them.
  3480. if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
  3481. // We didn't find the ')' we expected.
  3482. Tracker.consumeClose();
  3483. return ExprError();
  3484. }
  3485. if (Tok.is(tok::l_brace)) {
  3486. ParseAs = CompoundLiteral;
  3487. } else {
  3488. bool NotCastExpr;
  3489. if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
  3490. NotCastExpr = true;
  3491. } else {
  3492. // Try parsing the cast-expression that may follow.
  3493. // If it is not a cast-expression, NotCastExpr will be true and no token
  3494. // will be consumed.
  3495. ColonProt.restore();
  3496. Result = ParseCastExpression(AnyCastExpr,
  3497. false/*isAddressofOperand*/,
  3498. NotCastExpr,
  3499. // type-id has priority.
  3500. IsTypeCast);
  3501. }
  3502. // If we parsed a cast-expression, it's really a type-id, otherwise it's
  3503. // an expression.
  3504. ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
  3505. }
  3506. // Create a fake EOF to mark end of Toks buffer.
  3507. Token AttrEnd;
  3508. AttrEnd.startToken();
  3509. AttrEnd.setKind(tok::eof);
  3510. AttrEnd.setLocation(Tok.getLocation());
  3511. AttrEnd.setEofData(Toks.data());
  3512. Toks.push_back(AttrEnd);
  3513. // The current token should go after the cached tokens.
  3514. Toks.push_back(Tok);
  3515. // Re-enter the stored parenthesized tokens into the token stream, so we may
  3516. // parse them now.
  3517. PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
  3518. /*IsReinject*/ true);
  3519. // Drop the current token and bring the first cached one. It's the same token
  3520. // as when we entered this function.
  3521. ConsumeAnyToken();
  3522. if (ParseAs >= CompoundLiteral) {
  3523. // Parse the type declarator.
  3524. DeclSpec DS(AttrFactory);
  3525. Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
  3526. {
  3527. ColonProtectionRAIIObject InnerColonProtection(*this);
  3528. ParseSpecifierQualifierList(DS);
  3529. ParseDeclarator(DeclaratorInfo);
  3530. }
  3531. // Match the ')'.
  3532. Tracker.consumeClose();
  3533. ColonProt.restore();
  3534. // Consume EOF marker for Toks buffer.
  3535. assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
  3536. ConsumeAnyToken();
  3537. if (ParseAs == CompoundLiteral) {
  3538. ExprType = CompoundLiteral;
  3539. if (DeclaratorInfo.isInvalidType())
  3540. return ExprError();
  3541. TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  3542. return ParseCompoundLiteralExpression(Ty.get(),
  3543. Tracker.getOpenLocation(),
  3544. Tracker.getCloseLocation());
  3545. }
  3546. // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
  3547. assert(ParseAs == CastExpr);
  3548. if (DeclaratorInfo.isInvalidType())
  3549. return ExprError();
  3550. // Result is what ParseCastExpression returned earlier.
  3551. if (!Result.isInvalid())
  3552. Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
  3553. DeclaratorInfo, CastTy,
  3554. Tracker.getCloseLocation(), Result.get());
  3555. return Result;
  3556. }
  3557. // Not a compound literal, and not followed by a cast-expression.
  3558. assert(ParseAs == SimpleExpr);
  3559. ExprType = SimpleExpr;
  3560. Result = ParseExpression();
  3561. if (!Result.isInvalid() && Tok.is(tok::r_paren))
  3562. Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
  3563. Tok.getLocation(), Result.get());
  3564. // Match the ')'.
  3565. if (Result.isInvalid()) {
  3566. while (Tok.isNot(tok::eof))
  3567. ConsumeAnyToken();
  3568. assert(Tok.getEofData() == AttrEnd.getEofData());
  3569. ConsumeAnyToken();
  3570. return ExprError();
  3571. }
  3572. Tracker.consumeClose();
  3573. // Consume EOF marker for Toks buffer.
  3574. assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
  3575. ConsumeAnyToken();
  3576. return Result;
  3577. }
  3578. /// Parse a __builtin_bit_cast(T, E).
  3579. ExprResult Parser::ParseBuiltinBitCast() {
  3580. SourceLocation KWLoc = ConsumeToken();
  3581. BalancedDelimiterTracker T(*this, tok::l_paren);
  3582. if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
  3583. return ExprError();
  3584. // Parse the common declaration-specifiers piece.
  3585. DeclSpec DS(AttrFactory);
  3586. ParseSpecifierQualifierList(DS);
  3587. // Parse the abstract-declarator, if present.
  3588. Declarator DeclaratorInfo(DS, DeclaratorContext::TypeName);
  3589. ParseDeclarator(DeclaratorInfo);
  3590. if (ExpectAndConsume(tok::comma)) {
  3591. Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
  3592. SkipUntil(tok::r_paren, StopAtSemi);
  3593. return ExprError();
  3594. }
  3595. ExprResult Operand = ParseExpression();
  3596. if (T.consumeClose())
  3597. return ExprError();
  3598. if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
  3599. return ExprError();
  3600. return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
  3601. T.getCloseLocation());
  3602. }