ParseExprCXX.cpp 129 KB

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