ParseExprCXX.cpp 119 KB

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