ParseExprCXX.cpp 119 KB

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