ParseExprCXX.cpp 150 KB

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