ParseExpr.cpp 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987
  1. //===--- ParseExpr.cpp - 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. /// \file
  11. /// \brief Provides the Expression parsing implementation.
  12. ///
  13. /// Expressions in C99 basically consist of a bunch of binary operators with
  14. /// unary operators and other random stuff at the leaves.
  15. ///
  16. /// In the C99 grammar, these unary operators bind tightest and are represented
  17. /// as the 'cast-expression' production. Everything else is either a binary
  18. /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
  19. /// handled by ParseCastExpression, the higher level pieces are handled by
  20. /// ParseBinaryExpression.
  21. ///
  22. //===----------------------------------------------------------------------===//
  23. #include "clang/Parse/Parser.h"
  24. #include "RAIIObjectsForParser.h"
  25. #include "clang/AST/ASTContext.h"
  26. #include "clang/Basic/PrettyStackTrace.h"
  27. #include "clang/Sema/DeclSpec.h"
  28. #include "clang/Sema/ParsedTemplate.h"
  29. #include "clang/Sema/Scope.h"
  30. #include "clang/Sema/TypoCorrection.h"
  31. #include "llvm/ADT/SmallString.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. using namespace clang;
  34. /// \brief Simple precedence-based parser for binary/ternary operators.
  35. ///
  36. /// Note: we diverge from the C99 grammar when parsing the assignment-expression
  37. /// production. C99 specifies that the LHS of an assignment operator should be
  38. /// parsed as a unary-expression, but consistency dictates that it be a
  39. /// conditional-expession. In practice, the important thing here is that the
  40. /// LHS of an assignment has to be an l-value, which productions between
  41. /// unary-expression and conditional-expression don't produce. Because we want
  42. /// consistency, we parse the LHS as a conditional-expression, then check for
  43. /// l-value-ness in semantic analysis stages.
  44. ///
  45. /// \verbatim
  46. /// pm-expression: [C++ 5.5]
  47. /// cast-expression
  48. /// pm-expression '.*' cast-expression
  49. /// pm-expression '->*' cast-expression
  50. ///
  51. /// multiplicative-expression: [C99 6.5.5]
  52. /// Note: in C++, apply pm-expression instead of cast-expression
  53. /// cast-expression
  54. /// multiplicative-expression '*' cast-expression
  55. /// multiplicative-expression '/' cast-expression
  56. /// multiplicative-expression '%' cast-expression
  57. ///
  58. /// additive-expression: [C99 6.5.6]
  59. /// multiplicative-expression
  60. /// additive-expression '+' multiplicative-expression
  61. /// additive-expression '-' multiplicative-expression
  62. ///
  63. /// shift-expression: [C99 6.5.7]
  64. /// additive-expression
  65. /// shift-expression '<<' additive-expression
  66. /// shift-expression '>>' additive-expression
  67. ///
  68. /// relational-expression: [C99 6.5.8]
  69. /// shift-expression
  70. /// relational-expression '<' shift-expression
  71. /// relational-expression '>' shift-expression
  72. /// relational-expression '<=' shift-expression
  73. /// relational-expression '>=' shift-expression
  74. ///
  75. /// equality-expression: [C99 6.5.9]
  76. /// relational-expression
  77. /// equality-expression '==' relational-expression
  78. /// equality-expression '!=' relational-expression
  79. ///
  80. /// AND-expression: [C99 6.5.10]
  81. /// equality-expression
  82. /// AND-expression '&' equality-expression
  83. ///
  84. /// exclusive-OR-expression: [C99 6.5.11]
  85. /// AND-expression
  86. /// exclusive-OR-expression '^' AND-expression
  87. ///
  88. /// inclusive-OR-expression: [C99 6.5.12]
  89. /// exclusive-OR-expression
  90. /// inclusive-OR-expression '|' exclusive-OR-expression
  91. ///
  92. /// logical-AND-expression: [C99 6.5.13]
  93. /// inclusive-OR-expression
  94. /// logical-AND-expression '&&' inclusive-OR-expression
  95. ///
  96. /// logical-OR-expression: [C99 6.5.14]
  97. /// logical-AND-expression
  98. /// logical-OR-expression '||' logical-AND-expression
  99. ///
  100. /// conditional-expression: [C99 6.5.15]
  101. /// logical-OR-expression
  102. /// logical-OR-expression '?' expression ':' conditional-expression
  103. /// [GNU] logical-OR-expression '?' ':' conditional-expression
  104. /// [C++] the third operand is an assignment-expression
  105. ///
  106. /// assignment-expression: [C99 6.5.16]
  107. /// conditional-expression
  108. /// unary-expression assignment-operator assignment-expression
  109. /// [C++] throw-expression [C++ 15]
  110. ///
  111. /// assignment-operator: one of
  112. /// = *= /= %= += -= <<= >>= &= ^= |=
  113. ///
  114. /// expression: [C99 6.5.17]
  115. /// assignment-expression ...[opt]
  116. /// expression ',' assignment-expression ...[opt]
  117. /// \endverbatim
  118. ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
  119. ExprResult LHS(ParseAssignmentExpression(isTypeCast));
  120. return ParseRHSOfBinaryExpression(LHS, prec::Comma);
  121. }
  122. /// This routine is called when the '@' is seen and consumed.
  123. /// Current token is an Identifier and is not a 'try'. This
  124. /// routine is necessary to disambiguate \@try-statement from,
  125. /// for example, \@encode-expression.
  126. ///
  127. ExprResult
  128. Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
  129. assert(!getLangOpts().HLSL && "@ for obj-c is unsupported in HLSL"); // HLSL Change
  130. ExprResult LHS(ParseObjCAtExpression(AtLoc));
  131. return ParseRHSOfBinaryExpression(LHS, prec::Comma);
  132. }
  133. /// This routine is called when a leading '__extension__' is seen and
  134. /// consumed. This is necessary because the token gets consumed in the
  135. /// process of disambiguating between an expression and a declaration.
  136. ExprResult
  137. Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
  138. ExprResult LHS(true);
  139. {
  140. // Silence extension warnings in the sub-expression
  141. ExtensionRAIIObject O(Diags);
  142. LHS = ParseCastExpression(false);
  143. }
  144. if (!LHS.isInvalid())
  145. LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
  146. LHS.get());
  147. return ParseRHSOfBinaryExpression(LHS, prec::Comma);
  148. }
  149. /// \brief Parse an expr that doesn't include (top-level) commas.
  150. ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
  151. if (Tok.is(tok::code_completion)) {
  152. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
  153. cutOffParsing();
  154. return ExprError();
  155. }
  156. if (Tok.is(tok::kw_throw)) {
  157. // HLSL Change Starts
  158. if (getLangOpts().HLSL) {
  159. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  160. return ExprError();
  161. }
  162. // HLSL Change Ends
  163. return ParseThrowExpression();
  164. }
  165. ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
  166. /*isAddressOfOperand=*/false,
  167. isTypeCast);
  168. return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
  169. }
  170. /// \brief Parse an assignment expression where part of an Objective-C message
  171. /// send has already been parsed.
  172. ///
  173. /// In this case \p LBracLoc indicates the location of the '[' of the message
  174. /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
  175. /// the receiver of the message.
  176. ///
  177. /// Since this handles full assignment-expression's, it handles postfix
  178. /// expressions and other binary operators for these expressions as well.
  179. ExprResult
  180. Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
  181. SourceLocation SuperLoc,
  182. ParsedType ReceiverType,
  183. Expr *ReceiverExpr) {
  184. assert(!getLangOpts().HLSL && "obj-c constructs unsupported in HLSL"); // HLSL Change
  185. ExprResult R
  186. = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
  187. ReceiverType, ReceiverExpr);
  188. R = ParsePostfixExpressionSuffix(R);
  189. return ParseRHSOfBinaryExpression(R, prec::Assignment);
  190. }
  191. ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
  192. // C++03 [basic.def.odr]p2:
  193. // An expression is potentially evaluated unless it appears where an
  194. // integral constant expression is required (see 5.19) [...].
  195. // C++98 and C++11 have no such rule, but this is only a defect in C++98.
  196. EnterExpressionEvaluationContext Unevaluated(Actions,
  197. Sema::ConstantEvaluated);
  198. ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
  199. ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
  200. return Actions.ActOnConstantExpression(Res);
  201. }
  202. /// \brief Parse a constraint-expression.
  203. ///
  204. /// \verbatim
  205. /// constraint-expression: [Concepts TS temp.constr.decl p1]
  206. /// logical-or-expression
  207. /// \endverbatim
  208. ExprResult Parser::ParseConstraintExpression() {
  209. // FIXME: this may erroneously consume a function-body as the braced
  210. // initializer list of a compound literal
  211. //
  212. // FIXME: this may erroneously consume a parenthesized rvalue reference
  213. // declarator as a parenthesized address-of-label expression
  214. ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
  215. ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
  216. return Res;
  217. }
  218. bool Parser::isNotExpressionStart() {
  219. tok::TokenKind K = Tok.getKind();
  220. if (K == tok::l_brace || K == tok::r_brace ||
  221. K == tok::kw_for || K == tok::kw_while ||
  222. K == tok::kw_if || K == tok::kw_else ||
  223. K == tok::kw_goto || K == tok::kw_try)
  224. return true;
  225. // If this is a decl-specifier, we can't be at the start of an expression.
  226. return isKnownToBeDeclarationSpecifier();
  227. }
  228. static bool isFoldOperator(prec::Level Level) {
  229. return Level > prec::Unknown && Level != prec::Conditional;
  230. }
  231. static bool isFoldOperator(tok::TokenKind Kind) {
  232. return isFoldOperator(getBinOpPrecedence(Kind, false, true));
  233. }
  234. /// \brief Parse a binary expression that starts with \p LHS and has a
  235. /// precedence of at least \p MinPrec.
  236. ExprResult
  237. Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
  238. prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
  239. GreaterThanIsOperator,
  240. getLangOpts().CPlusPlus11);
  241. SourceLocation ColonLoc;
  242. while (1) {
  243. // If this token has a lower precedence than we are allowed to parse (e.g.
  244. // because we are called recursively, or because the token is not a binop),
  245. // then we are done!
  246. if (NextTokPrec < MinPrec)
  247. return LHS;
  248. // Consume the operator, saving the operator token for error reporting.
  249. Token OpToken = Tok;
  250. ConsumeToken();
  251. // Bail out when encountering a comma followed by a token which can't
  252. // possibly be the start of an expression. For instance:
  253. // int f() { return 1, }
  254. // We can't do this before consuming the comma, because
  255. // isNotExpressionStart() looks at the token stream.
  256. if (OpToken.is(tok::comma) && isNotExpressionStart()) {
  257. PP.EnterToken(Tok);
  258. Tok = OpToken;
  259. return LHS;
  260. }
  261. // If the next token is an ellipsis, then this is a fold-expression. Leave
  262. // it alone so we can handle it in the paren expression.
  263. if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
  264. // FIXME: We can't check this via lookahead before we consume the token
  265. // because that tickles a lexer bug.
  266. PP.EnterToken(Tok);
  267. Tok = OpToken;
  268. return LHS;
  269. }
  270. // Special case handling for the ternary operator.
  271. ExprResult TernaryMiddle(true);
  272. if (NextTokPrec == prec::Conditional) {
  273. if (Tok.isNot(tok::colon)) {
  274. // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
  275. ColonProtectionRAIIObject X(*this);
  276. // Handle this production specially:
  277. // logical-OR-expression '?' expression ':' conditional-expression
  278. // In particular, the RHS of the '?' is 'expression', not
  279. // 'logical-OR-expression' as we might expect.
  280. TernaryMiddle = ParseExpression();
  281. if (TernaryMiddle.isInvalid()) {
  282. Actions.CorrectDelayedTyposInExpr(LHS);
  283. LHS = ExprError();
  284. TernaryMiddle = nullptr;
  285. }
  286. } else {
  287. // Special case handling of "X ? Y : Z" where Y is empty:
  288. // logical-OR-expression '?' ':' conditional-expression [GNU]
  289. TernaryMiddle = nullptr;
  290. // HLSL Change Starts - provide an alternate message
  291. if (getLangOpts().HLSL)
  292. Diag(Tok, diag::err_hlsl_unsupported_construct) << "use of GNU ?: conditional expression extension, omitting middle operand";
  293. else
  294. Diag(Tok, diag::ext_gnu_conditional_expr);
  295. // HLSL Change Ends
  296. }
  297. if (!TryConsumeToken(tok::colon, ColonLoc)) {
  298. // Otherwise, we're missing a ':'. Assume that this was a typo that
  299. // the user forgot. If we're not in a macro expansion, we can suggest
  300. // a fixit hint. If there were two spaces before the current token,
  301. // suggest inserting the colon in between them, otherwise insert ": ".
  302. SourceLocation FILoc = Tok.getLocation();
  303. const char *FIText = ": ";
  304. const SourceManager &SM = PP.getSourceManager();
  305. if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
  306. assert(FILoc.isFileID());
  307. bool IsInvalid = false;
  308. const char *SourcePtr =
  309. SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
  310. if (!IsInvalid && *SourcePtr == ' ') {
  311. SourcePtr =
  312. SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
  313. if (!IsInvalid && *SourcePtr == ' ') {
  314. FILoc = FILoc.getLocWithOffset(-1);
  315. FIText = ":";
  316. }
  317. }
  318. }
  319. Diag(Tok, diag::err_expected)
  320. << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
  321. Diag(OpToken, diag::note_matching) << tok::question;
  322. ColonLoc = Tok.getLocation();
  323. }
  324. }
  325. // Code completion for the right-hand side of an assignment expression
  326. // goes through a special hook that takes the left-hand side into account.
  327. if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
  328. Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
  329. cutOffParsing();
  330. return ExprError();
  331. }
  332. // Parse another leaf here for the RHS of the operator.
  333. // ParseCastExpression works here because all RHS expressions in C have it
  334. // as a prefix, at least. However, in C++, an assignment-expression could
  335. // be a throw-expression, which is not a valid cast-expression.
  336. // Therefore we need some special-casing here.
  337. // Also note that the third operand of the conditional operator is
  338. // an assignment-expression in C++, and in C++11, we can have a
  339. // braced-init-list on the RHS of an assignment. For better diagnostics,
  340. // parse as if we were allowed braced-init-lists everywhere, and check that
  341. // they only appear on the RHS of assignments later.
  342. ExprResult RHS;
  343. bool RHSIsInitList = false;
  344. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  345. RHS = ParseBraceInitializer();
  346. RHSIsInitList = true;
  347. } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
  348. RHS = ParseAssignmentExpression();
  349. else
  350. RHS = ParseCastExpression(false);
  351. if (RHS.isInvalid()) {
  352. // FIXME: Errors generated by the delayed typo correction should be
  353. // printed before errors from parsing the RHS, not after.
  354. Actions.CorrectDelayedTyposInExpr(LHS);
  355. if (TernaryMiddle.isUsable())
  356. TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
  357. LHS = ExprError();
  358. }
  359. // Remember the precedence of this operator and get the precedence of the
  360. // operator immediately to the right of the RHS.
  361. prec::Level ThisPrec = NextTokPrec;
  362. NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
  363. getLangOpts().CPlusPlus11);
  364. // Assignment and conditional expressions are right-associative.
  365. bool isRightAssoc = ThisPrec == prec::Conditional ||
  366. ThisPrec == prec::Assignment;
  367. // Get the precedence of the operator to the right of the RHS. If it binds
  368. // more tightly with RHS than we do, evaluate it completely first.
  369. if (ThisPrec < NextTokPrec ||
  370. (ThisPrec == NextTokPrec && isRightAssoc)) {
  371. if (!RHS.isInvalid() && RHSIsInitList) {
  372. Diag(Tok, diag::err_init_list_bin_op)
  373. << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
  374. RHS = ExprError();
  375. }
  376. // If this is left-associative, only parse things on the RHS that bind
  377. // more tightly than the current operator. If it is left-associative, it
  378. // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
  379. // A=(B=(C=D)), where each paren is a level of recursion here.
  380. // The function takes ownership of the RHS.
  381. RHS = ParseRHSOfBinaryExpression(RHS,
  382. static_cast<prec::Level>(ThisPrec + !isRightAssoc));
  383. RHSIsInitList = false;
  384. if (RHS.isInvalid()) {
  385. // FIXME: Errors generated by the delayed typo correction should be
  386. // printed before errors from ParseRHSOfBinaryExpression, not after.
  387. Actions.CorrectDelayedTyposInExpr(LHS);
  388. if (TernaryMiddle.isUsable())
  389. TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
  390. LHS = ExprError();
  391. }
  392. NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
  393. getLangOpts().CPlusPlus11);
  394. }
  395. if (!RHS.isInvalid() && RHSIsInitList) {
  396. if (ThisPrec == prec::Assignment) {
  397. Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
  398. << Actions.getExprRange(RHS.get());
  399. } else {
  400. Diag(OpToken, diag::err_init_list_bin_op)
  401. << /*RHS*/1 << PP.getSpelling(OpToken)
  402. << Actions.getExprRange(RHS.get());
  403. LHS = ExprError();
  404. }
  405. }
  406. if (!LHS.isInvalid()) {
  407. // Combine the LHS and RHS into the LHS (e.g. build AST).
  408. if (TernaryMiddle.isInvalid()) {
  409. // If we're using '>>' as an operator within a template
  410. // argument list (in C++98), suggest the addition of
  411. // parentheses so that the code remains well-formed in C++0x.
  412. if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
  413. SuggestParentheses(OpToken.getLocation(),
  414. diag::warn_cxx11_right_shift_in_template_arg,
  415. SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
  416. Actions.getExprRange(RHS.get()).getEnd()));
  417. LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
  418. OpToken.getKind(), LHS.get(), RHS.get());
  419. } else
  420. LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
  421. LHS.get(), TernaryMiddle.get(),
  422. RHS.get());
  423. } else
  424. // Ensure potential typos in the RHS aren't left undiagnosed.
  425. Actions.CorrectDelayedTyposInExpr(RHS);
  426. // HLSL Change Begin - Take care TernaryMiddle.
  427. Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
  428. // HLSL Change End.
  429. }
  430. }
  431. /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
  432. /// parse a unary-expression.
  433. ///
  434. /// \p isAddressOfOperand exists because an id-expression that is the
  435. /// operand of address-of gets special treatment due to member pointers.
  436. ///
  437. ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
  438. bool isAddressOfOperand,
  439. TypeCastState isTypeCast) {
  440. bool NotCastExpr;
  441. ExprResult Res = ParseCastExpression(isUnaryExpression,
  442. isAddressOfOperand,
  443. NotCastExpr,
  444. isTypeCast);
  445. if (NotCastExpr)
  446. Diag(Tok, diag::err_expected_expression);
  447. return Res;
  448. }
  449. namespace {
  450. class CastExpressionIdValidator : public CorrectionCandidateCallback {
  451. public:
  452. CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
  453. : NextToken(Next), AllowNonTypes(AllowNonTypes) {
  454. WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
  455. }
  456. bool ValidateCandidate(const TypoCorrection &candidate) override {
  457. NamedDecl *ND = candidate.getCorrectionDecl();
  458. if (!ND)
  459. return candidate.isKeyword();
  460. if (isa<TypeDecl>(ND))
  461. return WantTypeSpecifiers;
  462. if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
  463. return false;
  464. if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
  465. return true;
  466. for (auto *C : candidate) {
  467. NamedDecl *ND = C->getUnderlyingDecl();
  468. if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
  469. return true;
  470. }
  471. return false;
  472. }
  473. private:
  474. Token NextToken;
  475. bool AllowNonTypes;
  476. };
  477. }
  478. /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
  479. /// a unary-expression.
  480. ///
  481. /// \p isAddressOfOperand exists because an id-expression that is the operand
  482. /// of address-of gets special treatment due to member pointers. NotCastExpr
  483. /// is set to true if the token is not the start of a cast-expression, and no
  484. /// diagnostic is emitted in this case.
  485. ///
  486. /// \verbatim
  487. /// cast-expression: [C99 6.5.4]
  488. /// unary-expression
  489. /// '(' type-name ')' cast-expression
  490. ///
  491. /// unary-expression: [C99 6.5.3]
  492. /// postfix-expression
  493. /// '++' unary-expression
  494. /// '--' unary-expression
  495. /// unary-operator cast-expression
  496. /// 'sizeof' unary-expression
  497. /// 'sizeof' '(' type-name ')'
  498. /// [C++11] 'sizeof' '...' '(' identifier ')'
  499. /// [GNU] '__alignof' unary-expression
  500. /// [GNU] '__alignof' '(' type-name ')'
  501. /// [C11] '_Alignof' '(' type-name ')'
  502. /// [C++11] 'alignof' '(' type-id ')'
  503. /// [GNU] '&&' identifier
  504. /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
  505. /// [C++] new-expression
  506. /// [C++] delete-expression
  507. ///
  508. /// unary-operator: one of
  509. /// '&' '*' '+' '-' '~' '!'
  510. /// [GNU] '__extension__' '__real' '__imag'
  511. ///
  512. /// primary-expression: [C99 6.5.1]
  513. /// [C99] identifier
  514. /// [C++] id-expression
  515. /// constant
  516. /// string-literal
  517. /// [C++] boolean-literal [C++ 2.13.5]
  518. /// [C++11] 'nullptr' [C++11 2.14.7]
  519. /// [C++11] user-defined-literal
  520. /// '(' expression ')'
  521. /// [C11] generic-selection
  522. /// '__func__' [C99 6.4.2.2]
  523. /// [GNU] '__FUNCTION__'
  524. /// [MS] '__FUNCDNAME__'
  525. /// [MS] 'L__FUNCTION__'
  526. /// [GNU] '__PRETTY_FUNCTION__'
  527. /// [GNU] '(' compound-statement ')'
  528. /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
  529. /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
  530. /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
  531. /// assign-expr ')'
  532. /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
  533. /// [GNU] '__null'
  534. /// [OBJC] '[' objc-message-expr ']'
  535. /// [OBJC] '\@selector' '(' objc-selector-arg ')'
  536. /// [OBJC] '\@protocol' '(' identifier ')'
  537. /// [OBJC] '\@encode' '(' type-name ')'
  538. /// [OBJC] objc-string-literal
  539. /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
  540. /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
  541. /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
  542. /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
  543. /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
  544. /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
  545. /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
  546. /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
  547. /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
  548. /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
  549. /// [C++] 'this' [C++ 9.3.2]
  550. /// [G++] unary-type-trait '(' type-id ')'
  551. /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
  552. /// [EMBT] array-type-trait '(' type-id ',' integer ')'
  553. /// [clang] '^' block-literal
  554. ///
  555. /// constant: [C99 6.4.4]
  556. /// integer-constant
  557. /// floating-constant
  558. /// enumeration-constant -> identifier
  559. /// character-constant
  560. ///
  561. /// id-expression: [C++ 5.1]
  562. /// unqualified-id
  563. /// qualified-id
  564. ///
  565. /// unqualified-id: [C++ 5.1]
  566. /// identifier
  567. /// operator-function-id
  568. /// conversion-function-id
  569. /// '~' class-name
  570. /// template-id
  571. ///
  572. /// new-expression: [C++ 5.3.4]
  573. /// '::'[opt] 'new' new-placement[opt] new-type-id
  574. /// new-initializer[opt]
  575. /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
  576. /// new-initializer[opt]
  577. ///
  578. /// delete-expression: [C++ 5.3.5]
  579. /// '::'[opt] 'delete' cast-expression
  580. /// '::'[opt] 'delete' '[' ']' cast-expression
  581. ///
  582. /// [GNU/Embarcadero] unary-type-trait:
  583. /// '__is_arithmetic'
  584. /// '__is_floating_point'
  585. /// '__is_integral'
  586. /// '__is_lvalue_expr'
  587. /// '__is_rvalue_expr'
  588. /// '__is_complete_type'
  589. /// '__is_void'
  590. /// '__is_array'
  591. /// '__is_function'
  592. /// '__is_reference'
  593. /// '__is_lvalue_reference'
  594. /// '__is_rvalue_reference'
  595. /// '__is_fundamental'
  596. /// '__is_object'
  597. /// '__is_scalar'
  598. /// '__is_compound'
  599. /// '__is_pointer'
  600. /// '__is_member_object_pointer'
  601. /// '__is_member_function_pointer'
  602. /// '__is_member_pointer'
  603. /// '__is_const'
  604. /// '__is_volatile'
  605. /// '__is_trivial'
  606. /// '__is_standard_layout'
  607. /// '__is_signed'
  608. /// '__is_unsigned'
  609. ///
  610. /// [GNU] unary-type-trait:
  611. /// '__has_nothrow_assign'
  612. /// '__has_nothrow_copy'
  613. /// '__has_nothrow_constructor'
  614. /// '__has_trivial_assign' [TODO]
  615. /// '__has_trivial_copy' [TODO]
  616. /// '__has_trivial_constructor'
  617. /// '__has_trivial_destructor'
  618. /// '__has_virtual_destructor'
  619. /// '__is_abstract' [TODO]
  620. /// '__is_class'
  621. /// '__is_empty' [TODO]
  622. /// '__is_enum'
  623. /// '__is_final'
  624. /// '__is_pod'
  625. /// '__is_polymorphic'
  626. /// '__is_sealed' [MS]
  627. /// '__is_trivial'
  628. /// '__is_union'
  629. ///
  630. /// [Clang] unary-type-trait:
  631. /// '__trivially_copyable'
  632. ///
  633. /// binary-type-trait:
  634. /// [GNU] '__is_base_of'
  635. /// [MS] '__is_convertible_to'
  636. /// '__is_convertible'
  637. /// '__is_same'
  638. ///
  639. /// [Embarcadero] array-type-trait:
  640. /// '__array_rank'
  641. /// '__array_extent'
  642. ///
  643. /// [Embarcadero] expression-trait:
  644. /// '__is_lvalue_expr'
  645. /// '__is_rvalue_expr'
  646. /// \endverbatim
  647. ///
  648. ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
  649. bool isAddressOfOperand,
  650. bool &NotCastExpr,
  651. TypeCastState isTypeCast) {
  652. ExprResult Res;
  653. tok::TokenKind SavedKind = Tok.getKind();
  654. NotCastExpr = false;
  655. // This handles all of cast-expression, unary-expression, postfix-expression,
  656. // and primary-expression. We handle them together like this for efficiency
  657. // and to simplify handling of an expression starting with a '(' token: which
  658. // may be one of a parenthesized expression, cast-expression, compound literal
  659. // expression, or statement expression.
  660. //
  661. // If the parsed tokens consist of a primary-expression, the cases below
  662. // break out of the switch; at the end we call ParsePostfixExpressionSuffix
  663. // to handle the postfix expression suffixes. Cases that cannot be followed
  664. // by postfix exprs should return without invoking
  665. // ParsePostfixExpressionSuffix.
  666. switch (SavedKind) {
  667. case tok::l_paren: {
  668. // If this expression is limited to being a unary-expression, the parent can
  669. // not start a cast expression.
  670. ParenParseOption ParenExprType =
  671. (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
  672. : CastExpr;
  673. ParsedType CastTy;
  674. SourceLocation RParenLoc;
  675. Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
  676. isTypeCast == IsTypeCast, CastTy, RParenLoc);
  677. switch (ParenExprType) {
  678. case SimpleExpr: break; // Nothing else to do.
  679. case CompoundStmt: break; // Nothing else to do.
  680. case CompoundLiteral:
  681. // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
  682. // postfix-expression exist, parse them now.
  683. break;
  684. case CastExpr:
  685. // We have parsed the cast-expression and no postfix-expr pieces are
  686. // following.
  687. return Res;
  688. }
  689. break;
  690. }
  691. // primary-expression
  692. case tok::numeric_constant:
  693. // constant: integer-constant
  694. // constant: floating-constant
  695. Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
  696. ConsumeToken();
  697. break;
  698. case tok::kw_true:
  699. case tok::kw_false:
  700. return ParseCXXBoolLiteral();
  701. case tok::kw___objc_yes:
  702. case tok::kw___objc_no:
  703. // HLSL Change Starts
  704. HLSLReservedKeyword:
  705. if (getLangOpts().HLSL) {
  706. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  707. return ExprError();
  708. }
  709. // HLSL Change Ends
  710. return ParseObjCBoolLiteral();
  711. case tok::kw_nullptr:
  712. // HLSL Change Starts
  713. assert(!getLangOpts().HLSL && "nullptr is not a keyword in HLSL");
  714. if (getLangOpts().HLSL) goto tok_default_case;
  715. // HLSL Change Ends
  716. Diag(Tok, diag::warn_cxx98_compat_nullptr);
  717. return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
  718. case tok::annot_primary_expr:
  719. assert(Res.get() == nullptr && "Stray primary-expression annotation?");
  720. Res = getExprAnnotation(Tok);
  721. ConsumeToken();
  722. break;
  723. case tok::kw___super:
  724. case tok::kw_decltype:
  725. // HLSL Change Starts
  726. assert(!getLangOpts().HLSL && "decltype is not a keyword in HLSL");
  727. if (getLangOpts().HLSL) goto tok_default_case;
  728. // HLSL Change Ends
  729. // Annotate the token and tail recurse.
  730. if (TryAnnotateTypeOrScopeToken())
  731. return ExprError();
  732. assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
  733. return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
  734. // HLSL Change Starts
  735. case tok::kw_precise:
  736. case tok::kw_sample:
  737. case tok::kw_globallycoherent:
  738. case tok::kw_center:
  739. case tok::kw_indices:
  740. case tok::kw_vertices:
  741. case tok::kw_primitives:
  742. case tok::kw_payload:
  743. // Back-compat: 'precise', 'globallycoherent', 'center' and 'sample' are keywords when used as an interpolation
  744. // modifiers, but in FXC they can also be used an identifiers. No interpolation modifiers are expected here
  745. // so we need to change the token type to tok::identifier and fall through to the next case.
  746. // Similarly 'indices', 'vertices', 'primitives' and 'payload' are keywords when used
  747. // as a type qualifer in mesh shader, but may still be used as a variable name.
  748. Tok.setKind(tok::identifier);
  749. __fallthrough;
  750. // HLSL Change Ends
  751. case tok::identifier: { // primary-expression: identifier
  752. // unqualified-id: identifier
  753. // constant: enumeration-constant
  754. // Turn a potentially qualified name into a annot_typename or
  755. // annot_cxxscope if it would be valid. This handles things like x::y, etc.
  756. if (getLangOpts().CPlusPlus) {
  757. // Avoid the unnecessary parse-time lookup in the common case
  758. // where the syntax forbids a type.
  759. const Token &Next = NextToken();
  760. // If this identifier was reverted from a token ID, and the next token
  761. // is a parenthesis, this is likely to be a use of a type trait. Check
  762. // those tokens.
  763. if (Next.is(tok::l_paren) && !getLangOpts().HLSL && // HLSL Change - no type trait support in HLSL
  764. Tok.is(tok::identifier) &&
  765. Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
  766. IdentifierInfo *II = Tok.getIdentifierInfo();
  767. // Build up the mapping of revertible type traits, for future use.
  768. if (RevertibleTypeTraits.empty()) {
  769. #define RTT_JOIN(X,Y) X##Y
  770. #define REVERTIBLE_TYPE_TRAIT(Name) \
  771. RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
  772. = RTT_JOIN(tok::kw_,Name)
  773. REVERTIBLE_TYPE_TRAIT(__is_abstract);
  774. REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
  775. REVERTIBLE_TYPE_TRAIT(__is_array);
  776. REVERTIBLE_TYPE_TRAIT(__is_base_of);
  777. REVERTIBLE_TYPE_TRAIT(__is_class);
  778. REVERTIBLE_TYPE_TRAIT(__is_complete_type);
  779. REVERTIBLE_TYPE_TRAIT(__is_compound);
  780. REVERTIBLE_TYPE_TRAIT(__is_const);
  781. REVERTIBLE_TYPE_TRAIT(__is_constructible);
  782. REVERTIBLE_TYPE_TRAIT(__is_convertible);
  783. REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
  784. REVERTIBLE_TYPE_TRAIT(__is_destructible);
  785. REVERTIBLE_TYPE_TRAIT(__is_empty);
  786. REVERTIBLE_TYPE_TRAIT(__is_enum);
  787. REVERTIBLE_TYPE_TRAIT(__is_floating_point);
  788. REVERTIBLE_TYPE_TRAIT(__is_final);
  789. REVERTIBLE_TYPE_TRAIT(__is_function);
  790. REVERTIBLE_TYPE_TRAIT(__is_fundamental);
  791. REVERTIBLE_TYPE_TRAIT(__is_integral);
  792. REVERTIBLE_TYPE_TRAIT(__is_interface_class);
  793. REVERTIBLE_TYPE_TRAIT(__is_literal);
  794. REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
  795. REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
  796. REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
  797. REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
  798. REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
  799. REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
  800. REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
  801. REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
  802. REVERTIBLE_TYPE_TRAIT(__is_object);
  803. REVERTIBLE_TYPE_TRAIT(__is_pod);
  804. REVERTIBLE_TYPE_TRAIT(__is_pointer);
  805. REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
  806. REVERTIBLE_TYPE_TRAIT(__is_reference);
  807. REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
  808. REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
  809. REVERTIBLE_TYPE_TRAIT(__is_same);
  810. REVERTIBLE_TYPE_TRAIT(__is_scalar);
  811. REVERTIBLE_TYPE_TRAIT(__is_sealed);
  812. REVERTIBLE_TYPE_TRAIT(__is_signed);
  813. REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
  814. REVERTIBLE_TYPE_TRAIT(__is_trivial);
  815. REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
  816. REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
  817. REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
  818. REVERTIBLE_TYPE_TRAIT(__is_union);
  819. REVERTIBLE_TYPE_TRAIT(__is_unsigned);
  820. REVERTIBLE_TYPE_TRAIT(__is_void);
  821. REVERTIBLE_TYPE_TRAIT(__is_volatile);
  822. #undef REVERTIBLE_TYPE_TRAIT
  823. #undef RTT_JOIN
  824. }
  825. // If we find that this is in fact the name of a type trait,
  826. // update the token kind in place and parse again to treat it as
  827. // the appropriate kind of type trait.
  828. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
  829. = RevertibleTypeTraits.find(II);
  830. if (Known != RevertibleTypeTraits.end()) {
  831. Tok.setKind(Known->second);
  832. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  833. NotCastExpr, isTypeCast);
  834. }
  835. }
  836. if ((!ColonIsSacred && Next.is(tok::colon)) ||
  837. Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
  838. tok::l_brace)) {
  839. // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
  840. if (TryAnnotateTypeOrScopeToken())
  841. return ExprError();
  842. if (!Tok.is(tok::identifier))
  843. return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
  844. }
  845. }
  846. // Consume the identifier so that we can see if it is followed by a '(' or
  847. // '.'.
  848. IdentifierInfo &II = *Tok.getIdentifierInfo();
  849. SourceLocation ILoc = ConsumeToken();
  850. // Support 'Class.property' and 'super.property' notation.
  851. if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
  852. (Actions.getTypeName(II, ILoc, getCurScope()) ||
  853. // Allow the base to be 'super' if in an objc-method.
  854. (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
  855. ConsumeToken();
  856. // Allow either an identifier or the keyword 'class' (in C++).
  857. if (Tok.isNot(tok::identifier) &&
  858. !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
  859. Diag(Tok, diag::err_expected_property_name);
  860. return ExprError();
  861. }
  862. IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
  863. SourceLocation PropertyLoc = ConsumeToken();
  864. Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
  865. ILoc, PropertyLoc);
  866. break;
  867. }
  868. // In an Objective-C method, if we have "super" followed by an identifier,
  869. // the token sequence is ill-formed. However, if there's a ':' or ']' after
  870. // that identifier, this is probably a message send with a missing open
  871. // bracket. Treat it as such.
  872. if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
  873. getCurScope()->isInObjcMethodScope() &&
  874. ((Tok.is(tok::identifier) &&
  875. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
  876. Tok.is(tok::code_completion))) {
  877. Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
  878. nullptr);
  879. break;
  880. }
  881. // If we have an Objective-C class name followed by an identifier
  882. // and either ':' or ']', this is an Objective-C class message
  883. // send that's missing the opening '['. Recovery
  884. // appropriately. Also take this path if we're performing code
  885. // completion after an Objective-C class name.
  886. if (getLangOpts().ObjC1 &&
  887. ((Tok.is(tok::identifier) && !InMessageExpression) ||
  888. Tok.is(tok::code_completion))) {
  889. const Token& Next = NextToken();
  890. if (Tok.is(tok::code_completion) ||
  891. Next.is(tok::colon) || Next.is(tok::r_square))
  892. if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
  893. if (Typ.get()->isObjCObjectOrInterfaceType()) {
  894. // Fake up a Declarator to use with ActOnTypeName.
  895. DeclSpec DS(AttrFactory);
  896. DS.SetRangeStart(ILoc);
  897. DS.SetRangeEnd(ILoc);
  898. const char *PrevSpec = nullptr;
  899. unsigned DiagID;
  900. DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
  901. Actions.getASTContext().getPrintingPolicy());
  902. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  903. TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
  904. DeclaratorInfo);
  905. if (Ty.isInvalid())
  906. break;
  907. Res = ParseObjCMessageExpressionBody(SourceLocation(),
  908. SourceLocation(),
  909. Ty.get(), nullptr);
  910. break;
  911. }
  912. }
  913. // Make sure to pass down the right value for isAddressOfOperand.
  914. if (isAddressOfOperand && isPostfixExpressionSuffixStart())
  915. isAddressOfOperand = false;
  916. // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
  917. // need to know whether or not this identifier is a function designator or
  918. // not.
  919. UnqualifiedId Name;
  920. CXXScopeSpec ScopeSpec;
  921. SourceLocation TemplateKWLoc;
  922. Token Replacement;
  923. auto Validator = llvm::make_unique<CastExpressionIdValidator>(
  924. Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
  925. Validator->IsAddressOfOperand = isAddressOfOperand;
  926. if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
  927. Validator->WantExpressionKeywords = false;
  928. Validator->WantRemainingKeywords = false;
  929. } else {
  930. Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
  931. }
  932. Name.setIdentifier(&II, ILoc);
  933. Res = Actions.ActOnIdExpression(
  934. getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
  935. isAddressOfOperand, std::move(Validator),
  936. /*IsInlineAsmIdentifier=*/false,
  937. Tok.is(tok::r_paren) ? nullptr : &Replacement);
  938. if (!Res.isInvalid() && !Res.get()) {
  939. UnconsumeToken(Replacement);
  940. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  941. NotCastExpr, isTypeCast);
  942. }
  943. break;
  944. }
  945. case tok::char_constant: // constant: character-constant
  946. case tok::wide_char_constant:
  947. case tok::utf8_char_constant:
  948. case tok::utf16_char_constant:
  949. case tok::utf32_char_constant:
  950. // HLSL Change Starts
  951. // Character constants become 32-bit unsigned ints. That will happen in Sema.
  952. if (getLangOpts().HLSL && Tok.getKind() != tok::char_constant) {
  953. Diag(Tok, diag::err_hlsl_unsupported_construct) << "non-ASCII/multiple-char character constant";
  954. return ExprError();
  955. }
  956. // HLSL Change Ends
  957. Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
  958. ConsumeToken();
  959. break;
  960. case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
  961. case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
  962. case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
  963. case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
  964. case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
  965. case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
  966. // HLSL Change Starts
  967. if (getLangOpts().HLSL) {
  968. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  969. return ExprError();
  970. }
  971. // HLSL Change Ends
  972. Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
  973. ConsumeToken();
  974. break;
  975. case tok::string_literal: // primary-expression: string-literal
  976. case tok::wide_string_literal:
  977. case tok::utf8_string_literal:
  978. case tok::utf16_string_literal:
  979. case tok::utf32_string_literal:
  980. // HLSL Change Starts
  981. if (getLangOpts().HLSL && Tok.getKind() != tok::string_literal) {
  982. Diag(Tok, diag::err_hlsl_unsupported_construct) << "non-ASCII string constant";
  983. return ExprError();
  984. }
  985. // HLSL Change Ends
  986. Res = ParseStringLiteralExpression(true);
  987. break;
  988. case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
  989. // HLSL Change Starts
  990. if (getLangOpts().HLSL) {
  991. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  992. return ExprError();
  993. }
  994. // HLSL Change Ends
  995. Res = ParseGenericSelectionExpression();
  996. break;
  997. case tok::kw___builtin_va_arg:
  998. case tok::kw___builtin_offsetof:
  999. case tok::kw___builtin_choose_expr:
  1000. case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
  1001. case tok::kw___builtin_convertvector:
  1002. if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported
  1003. return ParseBuiltinPrimaryExpression();
  1004. case tok::kw___null:
  1005. if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported
  1006. return Actions.ActOnGNUNullExpr(ConsumeToken());
  1007. case tok::plusplus: // unary-expression: '++' unary-expression [C99]
  1008. case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
  1009. // C++ [expr.unary] has:
  1010. // unary-expression:
  1011. // ++ cast-expression
  1012. // -- cast-expression
  1013. SourceLocation SavedLoc = ConsumeToken();
  1014. // One special case is implicitly handled here: if the preceding tokens are
  1015. // an ambiguous cast expression, such as "(T())++", then we recurse to
  1016. // determine whether the '++' is prefix or postfix.
  1017. Res = ParseCastExpression(!getLangOpts().CPlusPlus,
  1018. /*isAddressOfOperand*/false, NotCastExpr,
  1019. NotTypeCast);
  1020. if (!Res.isInvalid())
  1021. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  1022. return Res;
  1023. }
  1024. case tok::amp: { // unary-expression: '&' cast-expression
  1025. // Special treatment because of member pointers
  1026. SourceLocation SavedLoc = ConsumeToken();
  1027. Res = ParseCastExpression(false, true);
  1028. if (!Res.isInvalid())
  1029. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  1030. return Res;
  1031. }
  1032. case tok::star: // unary-expression: '*' cast-expression
  1033. case tok::plus: // unary-expression: '+' cast-expression
  1034. case tok::minus: // unary-expression: '-' cast-expression
  1035. case tok::tilde: // unary-expression: '~' cast-expression
  1036. case tok::exclaim: // unary-expression: '!' cast-expression
  1037. case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
  1038. case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
  1039. // HLSL Change Starts
  1040. if (getLangOpts().HLSL && (SavedKind == tok::kw___real || SavedKind == tok::kw___imag)) {
  1041. goto HLSLReservedKeyword;
  1042. }
  1043. // HLSL Change Ends
  1044. SourceLocation SavedLoc = ConsumeToken();
  1045. Res = ParseCastExpression(false);
  1046. if (!Res.isInvalid())
  1047. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  1048. return Res;
  1049. }
  1050. case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
  1051. // __extension__ silences extension warnings in the subexpression.
  1052. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  1053. SourceLocation SavedLoc = ConsumeToken();
  1054. Res = ParseCastExpression(false);
  1055. if (!Res.isInvalid())
  1056. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  1057. return Res;
  1058. }
  1059. case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
  1060. if (!getLangOpts().C11)
  1061. Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
  1062. // fallthrough
  1063. case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
  1064. case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
  1065. // unary-expression: '__alignof' '(' type-name ')'
  1066. case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
  1067. // unary-expression: 'sizeof' '(' type-name ')'
  1068. case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
  1069. // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
  1070. case tok::kw___builtin_omp_required_simd_align:
  1071. if (getLangOpts().HLSL && Tok.getKind() != tok::kw_sizeof) { goto HLSLReservedKeyword; } // HLSL Change - not supported
  1072. return ParseUnaryExprOrTypeTraitExpression();
  1073. case tok::ampamp: { // unary-expression: '&&' identifier
  1074. // HLSL Change Starts
  1075. if (getLangOpts().HLSL) {
  1076. Diag(Tok, diag::err_hlsl_unsupported_construct) << "address of label";
  1077. return ExprError();
  1078. }
  1079. // HLSL Change Ends
  1080. SourceLocation AmpAmpLoc = ConsumeToken();
  1081. if (Tok.isNot(tok::identifier))
  1082. return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
  1083. if (getCurScope()->getFnParent() == nullptr)
  1084. return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
  1085. Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
  1086. LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
  1087. Tok.getLocation());
  1088. Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
  1089. ConsumeToken();
  1090. return Res;
  1091. }
  1092. case tok::kw_const_cast:
  1093. case tok::kw_dynamic_cast:
  1094. case tok::kw_reinterpret_cast:
  1095. case tok::kw_static_cast:
  1096. // HLSL Change Starts
  1097. if (getLangOpts().HLSL) {
  1098. Diag(Tok, diag::err_hlsl_unsupported_construct) << "C++-style cast";
  1099. return ExprError();
  1100. }
  1101. // HLSL Change Ends
  1102. Res = ParseCXXCasts();
  1103. break;
  1104. case tok::kw_typeid:
  1105. if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported
  1106. Res = ParseCXXTypeid();
  1107. break;
  1108. case tok::kw___uuidof:
  1109. // HLSL Change Starts
  1110. assert(!getLangOpts().HLSL && "__uuidof is not a keyword in HLSL");
  1111. if (getLangOpts().HLSL) goto tok_default_case;
  1112. // HLSL Change Ends
  1113. Res = ParseCXXUuidof();
  1114. break;
  1115. case tok::kw_this:
  1116. Res = ParseCXXThis();
  1117. break;
  1118. case tok::annot_typename:
  1119. if (isStartOfObjCClassMessageMissingOpenBracket()) {
  1120. ParsedType Type = getTypeAnnotation(Tok);
  1121. // Fake up a Declarator to use with ActOnTypeName.
  1122. DeclSpec DS(AttrFactory);
  1123. DS.SetRangeStart(Tok.getLocation());
  1124. DS.SetRangeEnd(Tok.getLastLoc());
  1125. const char *PrevSpec = nullptr;
  1126. unsigned DiagID;
  1127. DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
  1128. PrevSpec, DiagID, Type,
  1129. Actions.getASTContext().getPrintingPolicy());
  1130. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  1131. TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  1132. if (Ty.isInvalid())
  1133. break;
  1134. ConsumeToken();
  1135. Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
  1136. Ty.get(), nullptr);
  1137. break;
  1138. }
  1139. // Fall through
  1140. case tok::annot_decltype:
  1141. case tok::kw_char:
  1142. case tok::kw_wchar_t:
  1143. case tok::kw_char16_t:
  1144. case tok::kw_char32_t:
  1145. case tok::kw_bool:
  1146. case tok::kw_short:
  1147. case tok::kw_int:
  1148. case tok::kw_long:
  1149. case tok::kw___int64:
  1150. case tok::kw___int128:
  1151. // HLSL Change Starts
  1152. case tok::kw_column_major:
  1153. case tok::kw_row_major:
  1154. case tok::kw_snorm:
  1155. case tok::kw_unorm:
  1156. // HLSL Change Ends
  1157. case tok::kw_signed:
  1158. case tok::kw_unsigned:
  1159. case tok::kw_half:
  1160. case tok::kw_float:
  1161. case tok::kw_double:
  1162. case tok::kw_void:
  1163. case tok::kw_typename:
  1164. case tok::kw_typeof:
  1165. case tok::kw___vector: {
  1166. // HLSL Change Starts
  1167. if (getLangOpts().HLSL && (
  1168. SavedKind == tok::kw_wchar_t || SavedKind == tok::kw_char || SavedKind == tok::kw_char16_t || SavedKind == tok::kw_char32_t ||
  1169. SavedKind == tok::kw_short || SavedKind == tok::kw_long || SavedKind == tok::kw___int64 || SavedKind == tok::kw___int128 ||
  1170. (SavedKind == tok::kw_typename && !getLangOpts().EnableTemplates) || SavedKind == tok::kw_typeof)) {
  1171. // the vector/image/sampler/event keywords aren't returned by the lexer for HLSL
  1172. goto HLSLReservedKeyword;
  1173. }
  1174. // HLSL Change Ends
  1175. if (!getLangOpts().CPlusPlus) {
  1176. Diag(Tok, diag::err_expected_expression);
  1177. return ExprError();
  1178. }
  1179. if (SavedKind == tok::kw_typename) {
  1180. // postfix-expression: typename-specifier '(' expression-list[opt] ')'
  1181. // typename-specifier braced-init-list
  1182. if (TryAnnotateTypeOrScopeToken())
  1183. return ExprError();
  1184. if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
  1185. // We are trying to parse a simple-type-specifier but might not get such
  1186. // a token after error recovery.
  1187. return ExprError();
  1188. }
  1189. // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
  1190. // simple-type-specifier braced-init-list
  1191. //
  1192. DeclSpec DS(AttrFactory);
  1193. ParseCXXSimpleTypeSpecifier(DS);
  1194. if (Tok.isNot(tok::l_paren) &&
  1195. (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
  1196. return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
  1197. << DS.getSourceRange());
  1198. if (Tok.is(tok::l_brace))
  1199. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  1200. Res = ParseCXXTypeConstructExpression(DS);
  1201. break;
  1202. }
  1203. case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
  1204. // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
  1205. // (We can end up in this situation after tentative parsing.)
  1206. if (TryAnnotateTypeOrScopeToken())
  1207. return ExprError();
  1208. if (!Tok.is(tok::annot_cxxscope))
  1209. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  1210. NotCastExpr, isTypeCast);
  1211. Token Next = NextToken();
  1212. if (Next.is(tok::annot_template_id)) {
  1213. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
  1214. if (TemplateId->Kind == TNK_Type_template) {
  1215. // We have a qualified template-id that we know refers to a
  1216. // type, translate it into a type and continue parsing as a
  1217. // cast expression.
  1218. CXXScopeSpec SS;
  1219. ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  1220. /*EnteringContext=*/false);
  1221. AnnotateTemplateIdTokenAsType();
  1222. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  1223. NotCastExpr, isTypeCast);
  1224. }
  1225. }
  1226. // Parse as an id-expression.
  1227. Res = ParseCXXIdExpression(isAddressOfOperand);
  1228. break;
  1229. }
  1230. case tok::annot_template_id: { // [C++] template-id
  1231. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1232. if (TemplateId->Kind == TNK_Type_template) {
  1233. // We have a template-id that we know refers to a type,
  1234. // translate it into a type and continue parsing as a cast
  1235. // expression.
  1236. AnnotateTemplateIdTokenAsType();
  1237. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  1238. NotCastExpr, isTypeCast);
  1239. }
  1240. // Fall through to treat the template-id as an id-expression.
  1241. }
  1242. case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
  1243. if (getLangOpts().HLSL && SavedKind == tok::kw_operator) goto HLSLReservedKeyword; // HLSL Change - 'operator' is reserved
  1244. Res = ParseCXXIdExpression(isAddressOfOperand);
  1245. break;
  1246. case tok::coloncolon: {
  1247. // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
  1248. // annotates the token, tail recurse.
  1249. if (TryAnnotateTypeOrScopeToken())
  1250. return ExprError();
  1251. if (!Tok.is(tok::coloncolon))
  1252. return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
  1253. // ::new -> [C++] new-expression
  1254. // ::delete -> [C++] delete-expression
  1255. SourceLocation CCLoc = ConsumeToken();
  1256. if (Tok.is(tok::kw_new)) {
  1257. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'new' is reserved
  1258. return ParseCXXNewExpression(true, CCLoc);
  1259. }
  1260. if (Tok.is(tok::kw_delete)) {
  1261. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'delete' is reserved
  1262. return ParseCXXDeleteExpression(true, CCLoc);
  1263. }
  1264. // This is not a type name or scope specifier, it is an invalid expression.
  1265. Diag(CCLoc, diag::err_expected_expression);
  1266. return ExprError();
  1267. }
  1268. case tok::kw_new: // [C++] new-expression
  1269. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'new' is reserved
  1270. return ParseCXXNewExpression(false, Tok.getLocation());
  1271. case tok::kw_delete: // [C++] delete-expression
  1272. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'delete' is reserved
  1273. return ParseCXXDeleteExpression(false, Tok.getLocation());
  1274. case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
  1275. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - reserved keyword
  1276. Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
  1277. SourceLocation KeyLoc = ConsumeToken();
  1278. BalancedDelimiterTracker T(*this, tok::l_paren);
  1279. if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
  1280. return ExprError();
  1281. // C++11 [expr.unary.noexcept]p1:
  1282. // The noexcept operator determines whether the evaluation of its operand,
  1283. // which is an unevaluated operand, can throw an exception.
  1284. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  1285. ExprResult Result = ParseExpression();
  1286. T.consumeClose();
  1287. if (!Result.isInvalid())
  1288. Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
  1289. Result.get(), T.getCloseLocation());
  1290. return Result;
  1291. }
  1292. #define TYPE_TRAIT(N,Spelling,K) \
  1293. case tok::kw_##Spelling:
  1294. #include "clang/Basic/TokenKinds.def"
  1295. return ParseTypeTrait();
  1296. case tok::kw___array_rank:
  1297. case tok::kw___array_extent:
  1298. return ParseArrayTypeTrait();
  1299. case tok::kw___is_lvalue_expr:
  1300. case tok::kw___is_rvalue_expr:
  1301. return ParseExpressionTrait();
  1302. case tok::at: {
  1303. // HLSL Change Starts
  1304. assert(!getLangOpts().HLSL && "HLSL does not recognize '@' as a token");
  1305. if (getLangOpts().HLSL) goto tok_default_case;
  1306. // HLSL Change Ends
  1307. SourceLocation AtLoc = ConsumeToken();
  1308. return ParseObjCAtExpression(AtLoc);
  1309. }
  1310. case tok::caret:
  1311. // HLSL Change Starts
  1312. if (getLangOpts().HLSL) {
  1313. Diag(Tok, diag::err_hlsl_unsupported_construct) << "block";
  1314. return ExprError();
  1315. }
  1316. // HLSL Change Ends
  1317. Res = ParseBlockLiteralExpression();
  1318. break;
  1319. case tok::code_completion: {
  1320. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
  1321. cutOffParsing();
  1322. return ExprError();
  1323. }
  1324. case tok::l_square:
  1325. if (getLangOpts().CPlusPlus11) {
  1326. if (getLangOpts().ObjC1) {
  1327. // C++11 lambda expressions and Objective-C message sends both start with a
  1328. // square bracket. There are three possibilities here:
  1329. // we have a valid lambda expression, we have an invalid lambda
  1330. // expression, or we have something that doesn't appear to be a lambda.
  1331. // If we're in the last case, we fall back to ParseObjCMessageExpression.
  1332. Res = TryParseLambdaExpression();
  1333. if (!Res.isInvalid() && !Res.get())
  1334. Res = ParseObjCMessageExpression();
  1335. break;
  1336. }
  1337. Res = ParseLambdaExpression();
  1338. break;
  1339. }
  1340. if (getLangOpts().ObjC1) {
  1341. Res = ParseObjCMessageExpression();
  1342. break;
  1343. }
  1344. // FALL THROUGH.
  1345. tok_default_case: // HLSL Change - add to target cases dead-code'd by HLSL
  1346. default:
  1347. NotCastExpr = true;
  1348. return ExprError();
  1349. }
  1350. // These can be followed by postfix-expr pieces.
  1351. return ParsePostfixExpressionSuffix(Res);
  1352. }
  1353. /// \brief Once the leading part of a postfix-expression is parsed, this
  1354. /// method parses any suffixes that apply.
  1355. ///
  1356. /// \verbatim
  1357. /// postfix-expression: [C99 6.5.2]
  1358. /// primary-expression
  1359. /// postfix-expression '[' expression ']'
  1360. /// postfix-expression '[' braced-init-list ']'
  1361. /// postfix-expression '(' argument-expression-list[opt] ')'
  1362. /// postfix-expression '.' identifier
  1363. /// postfix-expression '->' identifier
  1364. /// postfix-expression '++'
  1365. /// postfix-expression '--'
  1366. /// '(' type-name ')' '{' initializer-list '}'
  1367. /// '(' type-name ')' '{' initializer-list ',' '}'
  1368. ///
  1369. /// argument-expression-list: [C99 6.5.2]
  1370. /// argument-expression ...[opt]
  1371. /// argument-expression-list ',' assignment-expression ...[opt]
  1372. /// \endverbatim
  1373. ExprResult
  1374. Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
  1375. // Now that the primary-expression piece of the postfix-expression has been
  1376. // parsed, see if there are any postfix-expression pieces here.
  1377. SourceLocation Loc;
  1378. while (1) {
  1379. switch (Tok.getKind()) {
  1380. case tok::code_completion:
  1381. if (InMessageExpression)
  1382. return LHS;
  1383. Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
  1384. cutOffParsing();
  1385. return ExprError();
  1386. case tok::identifier:
  1387. // If we see identifier: after an expression, and we're not already in a
  1388. // message send, then this is probably a message send with a missing
  1389. // opening bracket '['.
  1390. if (getLangOpts().ObjC1 && !InMessageExpression &&
  1391. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
  1392. LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
  1393. ParsedType(), LHS.get());
  1394. break;
  1395. }
  1396. // Fall through; this isn't a message send.
  1397. default: // Not a postfix-expression suffix.
  1398. return LHS;
  1399. case tok::l_square: { // postfix-expression: p-e '[' expression ']'
  1400. // If we have a array postfix expression that starts on a new line and
  1401. // Objective-C is enabled, it is highly likely that the user forgot a
  1402. // semicolon after the base expression and that the array postfix-expr is
  1403. // actually another message send. In this case, do some look-ahead to see
  1404. // if the contents of the square brackets are obviously not a valid
  1405. // expression and recover by pretending there is no suffix.
  1406. if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
  1407. isSimpleObjCMessageExpression())
  1408. return LHS;
  1409. // Reject array indices starting with a lambda-expression. '[[' is
  1410. // reserved for attributes.
  1411. if (CheckProhibitedCXX11Attribute())
  1412. return ExprError();
  1413. BalancedDelimiterTracker T(*this, tok::l_square);
  1414. T.consumeOpen();
  1415. Loc = T.getOpenLocation();
  1416. ExprResult Idx;
  1417. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  1418. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  1419. Idx = ParseBraceInitializer();
  1420. } else
  1421. Idx = ParseExpression();
  1422. SourceLocation RLoc = Tok.getLocation();
  1423. if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
  1424. LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
  1425. Idx.get(), RLoc);
  1426. } else {
  1427. (void)Actions.CorrectDelayedTyposInExpr(LHS);
  1428. (void)Actions.CorrectDelayedTyposInExpr(Idx);
  1429. LHS = ExprError();
  1430. Idx = ExprError();
  1431. }
  1432. // Match the ']'.
  1433. T.consumeClose();
  1434. break;
  1435. }
  1436. case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
  1437. case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
  1438. // '(' argument-expression-list[opt] ')'
  1439. tok::TokenKind OpKind = Tok.getKind();
  1440. InMessageExpressionRAIIObject InMessage(*this, false);
  1441. Expr *ExecConfig = nullptr;
  1442. BalancedDelimiterTracker PT(*this, tok::l_paren);
  1443. if (getLangOpts().HLSL && OpKind == tok::lesslessless) { // HLSL Change: <<< is not supported in HLSL
  1444. ExprVector ExecConfigExprs;
  1445. CommaLocsTy ExecConfigCommaLocs;
  1446. SourceLocation OpenLoc = ConsumeToken();
  1447. if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
  1448. (void)Actions.CorrectDelayedTyposInExpr(LHS);
  1449. LHS = ExprError();
  1450. }
  1451. SourceLocation CloseLoc;
  1452. if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
  1453. } else if (LHS.isInvalid()) {
  1454. SkipUntil(tok::greatergreatergreater, StopAtSemi);
  1455. } else {
  1456. // There was an error closing the brackets
  1457. Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
  1458. Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
  1459. SkipUntil(tok::greatergreatergreater, StopAtSemi);
  1460. LHS = ExprError();
  1461. }
  1462. if (!LHS.isInvalid()) {
  1463. if (ExpectAndConsume(tok::l_paren))
  1464. LHS = ExprError();
  1465. else
  1466. Loc = PrevTokLocation;
  1467. }
  1468. if (!LHS.isInvalid()) {
  1469. ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
  1470. OpenLoc,
  1471. ExecConfigExprs,
  1472. CloseLoc);
  1473. if (ECResult.isInvalid())
  1474. LHS = ExprError();
  1475. else
  1476. ExecConfig = ECResult.get();
  1477. }
  1478. } else {
  1479. PT.consumeOpen();
  1480. Loc = PT.getOpenLocation();
  1481. }
  1482. ExprVector ArgExprs;
  1483. CommaLocsTy CommaLocs;
  1484. if (Tok.is(tok::code_completion)) {
  1485. Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
  1486. cutOffParsing();
  1487. return ExprError();
  1488. }
  1489. if (OpKind == tok::l_paren || !LHS.isInvalid()) {
  1490. if (Tok.isNot(tok::r_paren)) {
  1491. if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
  1492. Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
  1493. })) {
  1494. (void)Actions.CorrectDelayedTyposInExpr(LHS);
  1495. LHS = ExprError();
  1496. } else if (LHS.isInvalid()) {
  1497. for (auto &E : ArgExprs)
  1498. Actions.CorrectDelayedTyposInExpr(E);
  1499. }
  1500. }
  1501. }
  1502. // Match the ')'.
  1503. if (LHS.isInvalid()) {
  1504. SkipUntil(tok::r_paren, StopAtSemi);
  1505. } else if (Tok.isNot(tok::r_paren)) {
  1506. bool HadDelayedTypo = false;
  1507. if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
  1508. HadDelayedTypo = true;
  1509. for (auto &E : ArgExprs)
  1510. if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
  1511. HadDelayedTypo = true;
  1512. // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
  1513. // instead of PT.consumeClose() to avoid emitting extra diagnostics for
  1514. // the unmatched l_paren.
  1515. if (HadDelayedTypo)
  1516. SkipUntil(tok::r_paren, StopAtSemi);
  1517. else
  1518. PT.consumeClose();
  1519. LHS = ExprError();
  1520. } else {
  1521. assert((ArgExprs.size() == 0 ||
  1522. ArgExprs.size()-1 == CommaLocs.size())&&
  1523. "Unexpected number of commas!");
  1524. LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
  1525. ArgExprs, Tok.getLocation(),
  1526. ExecConfig);
  1527. PT.consumeClose();
  1528. }
  1529. break;
  1530. }
  1531. case tok::arrow:
  1532. case tok::period: {
  1533. // postfix-expression: p-e '->' template[opt] id-expression
  1534. // postfix-expression: p-e '.' template[opt] id-expression
  1535. tok::TokenKind OpKind = Tok.getKind();
  1536. SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
  1537. CXXScopeSpec SS;
  1538. ParsedType ObjectType;
  1539. bool MayBePseudoDestructor = false;
  1540. if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
  1541. Expr *Base = LHS.get();
  1542. const Type* BaseType = Base->getType().getTypePtrOrNull();
  1543. if (BaseType && Tok.is(tok::l_paren) &&
  1544. (BaseType->isFunctionType() ||
  1545. BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
  1546. Diag(OpLoc, diag::err_function_is_not_record)
  1547. << OpKind << Base->getSourceRange()
  1548. << FixItHint::CreateRemoval(OpLoc);
  1549. return ParsePostfixExpressionSuffix(Base);
  1550. }
  1551. LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
  1552. OpLoc, OpKind, ObjectType,
  1553. MayBePseudoDestructor);
  1554. if (LHS.isInvalid())
  1555. break;
  1556. ParseOptionalCXXScopeSpecifier(SS, ObjectType,
  1557. /*EnteringContext=*/false,
  1558. &MayBePseudoDestructor);
  1559. if (SS.isNotEmpty())
  1560. ObjectType = ParsedType();
  1561. }
  1562. // HLSL Change Starts
  1563. // At this point, if we have an arrow, a diagnostic has been emitted, and
  1564. // we recover parsing by treating this as a period.
  1565. if (getLangOpts().HLSL) {
  1566. OpKind = tok::period;
  1567. }
  1568. // HLSL Change Ends
  1569. if (Tok.is(tok::code_completion)) {
  1570. // Code completion for a member access expression.
  1571. Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
  1572. OpLoc, OpKind == tok::arrow);
  1573. cutOffParsing();
  1574. return ExprError();
  1575. }
  1576. if (MayBePseudoDestructor && !LHS.isInvalid()) {
  1577. LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
  1578. ObjectType);
  1579. break;
  1580. }
  1581. // HLSL Change Starts
  1582. // 'sample' and others are keywords when used as modifiers, but they are
  1583. // also built-in field of some types. By the time we're considering a
  1584. // field access, update the token if necessary to reflect this.
  1585. if (getLangOpts().HLSL) {
  1586. switch (auto tk = Tok.getKind()) {
  1587. case tok::kw_center:
  1588. case tok::kw_globallycoherent:
  1589. case tok::kw_precise:
  1590. case tok::kw_sample:
  1591. case tok::kw_indices:
  1592. case tok::kw_vertices:
  1593. case tok::kw_primitives:
  1594. case tok::kw_payload:
  1595. Tok.setKind(tok::identifier);
  1596. Tok.setIdentifierInfo(PP.getIdentifierInfo(getKeywordSpelling(tk)));
  1597. break;
  1598. default:
  1599. break;
  1600. }
  1601. }
  1602. // HLSL Change Ends
  1603. // Either the action has told us that this cannot be a
  1604. // pseudo-destructor expression (based on the type of base
  1605. // expression), or we didn't see a '~' in the right place. We
  1606. // can still parse a destructor name here, but in that case it
  1607. // names a real destructor.
  1608. // Allow explicit constructor calls in Microsoft mode.
  1609. // FIXME: Add support for explicit call of template constructor.
  1610. SourceLocation TemplateKWLoc;
  1611. UnqualifiedId Name;
  1612. if (getLangOpts().ObjC2 && OpKind == tok::period &&
  1613. Tok.is(tok::kw_class)) {
  1614. // Objective-C++:
  1615. // After a '.' in a member access expression, treat the keyword
  1616. // 'class' as if it were an identifier.
  1617. //
  1618. // This hack allows property access to the 'class' method because it is
  1619. // such a common method name. For other C++ keywords that are
  1620. // Objective-C method names, one must use the message send syntax.
  1621. IdentifierInfo *Id = Tok.getIdentifierInfo();
  1622. SourceLocation Loc = ConsumeToken();
  1623. Name.setIdentifier(Id, Loc);
  1624. } else if (ParseUnqualifiedId(SS,
  1625. /*EnteringContext=*/false,
  1626. /*AllowDestructorName=*/true,
  1627. /*AllowConstructorName=*/
  1628. getLangOpts().MicrosoftExt,
  1629. ObjectType, TemplateKWLoc, Name)) {
  1630. (void)Actions.CorrectDelayedTyposInExpr(LHS);
  1631. LHS = ExprError();
  1632. }
  1633. if (!LHS.isInvalid())
  1634. LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
  1635. OpKind, SS, TemplateKWLoc, Name,
  1636. CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
  1637. : nullptr);
  1638. break;
  1639. }
  1640. case tok::plusplus: // postfix-expression: postfix-expression '++'
  1641. case tok::minusminus: // postfix-expression: postfix-expression '--'
  1642. if (!LHS.isInvalid()) {
  1643. LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
  1644. Tok.getKind(), LHS.get());
  1645. }
  1646. ConsumeToken();
  1647. break;
  1648. }
  1649. }
  1650. }
  1651. /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
  1652. /// vec_step and we are at the start of an expression or a parenthesized
  1653. /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
  1654. /// expression (isCastExpr == false) or the type (isCastExpr == true).
  1655. ///
  1656. /// \verbatim
  1657. /// unary-expression: [C99 6.5.3]
  1658. /// 'sizeof' unary-expression
  1659. /// 'sizeof' '(' type-name ')'
  1660. /// [GNU] '__alignof' unary-expression
  1661. /// [GNU] '__alignof' '(' type-name ')'
  1662. /// [C11] '_Alignof' '(' type-name ')'
  1663. /// [C++0x] 'alignof' '(' type-id ')'
  1664. ///
  1665. /// [GNU] typeof-specifier:
  1666. /// typeof ( expressions )
  1667. /// typeof ( type-name )
  1668. /// [GNU/C++] typeof unary-expression
  1669. ///
  1670. /// [OpenCL 1.1 6.11.12] vec_step built-in function:
  1671. /// vec_step ( expressions )
  1672. /// vec_step ( type-name )
  1673. /// \endverbatim
  1674. ExprResult
  1675. Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
  1676. bool &isCastExpr,
  1677. ParsedType &CastTy,
  1678. SourceRange &CastRange) {
  1679. // HLSL Change Begin
  1680. assert((!getLangOpts().HLSL || OpTok.getKind() == tok::kw_sizeof)
  1681. && "not supported for HLSL - unreachable");
  1682. // HLSL Change End
  1683. assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
  1684. tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
  1685. tok::kw___builtin_omp_required_simd_align) &&
  1686. "Not a typeof/sizeof/alignof/vec_step expression!");
  1687. ExprResult Operand;
  1688. // If the operand doesn't start with an '(', it must be an expression.
  1689. if (Tok.isNot(tok::l_paren)) {
  1690. // If construct allows a form without parenthesis, user may forget to put
  1691. // pathenthesis around type name.
  1692. if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
  1693. tok::kw__Alignof)) {
  1694. if (isTypeIdUnambiguously()) {
  1695. DeclSpec DS(AttrFactory);
  1696. ParseSpecifierQualifierList(DS);
  1697. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  1698. ParseDeclarator(DeclaratorInfo);
  1699. SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
  1700. SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
  1701. Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
  1702. << OpTok.getName()
  1703. << FixItHint::CreateInsertion(LParenLoc, "(")
  1704. << FixItHint::CreateInsertion(RParenLoc, ")");
  1705. isCastExpr = true;
  1706. return ExprEmpty();
  1707. }
  1708. }
  1709. isCastExpr = false;
  1710. if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
  1711. Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
  1712. << tok::l_paren;
  1713. return ExprError();
  1714. }
  1715. Operand = ParseCastExpression(true/*isUnaryExpression*/);
  1716. } else {
  1717. // If it starts with a '(', we know that it is either a parenthesized
  1718. // type-name, or it is a unary-expression that starts with a compound
  1719. // literal, or starts with a primary-expression that is a parenthesized
  1720. // expression.
  1721. ParenParseOption ExprType = CastExpr;
  1722. SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
  1723. Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
  1724. false, CastTy, RParenLoc);
  1725. CastRange = SourceRange(LParenLoc, RParenLoc);
  1726. // If ParseParenExpression parsed a '(typename)' sequence only, then this is
  1727. // a type.
  1728. if (ExprType == CastExpr) {
  1729. isCastExpr = true;
  1730. return ExprEmpty();
  1731. }
  1732. if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
  1733. // GNU typeof in C requires the expression to be parenthesized. Not so for
  1734. // sizeof/alignof or in C++. Therefore, the parenthesized expression is
  1735. // the start of a unary-expression, but doesn't include any postfix
  1736. // pieces. Parse these now if present.
  1737. if (!Operand.isInvalid())
  1738. Operand = ParsePostfixExpressionSuffix(Operand.get());
  1739. }
  1740. }
  1741. // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
  1742. isCastExpr = false;
  1743. return Operand;
  1744. }
  1745. /// \brief Parse a sizeof or alignof expression.
  1746. ///
  1747. /// \verbatim
  1748. /// unary-expression: [C99 6.5.3]
  1749. /// 'sizeof' unary-expression
  1750. /// 'sizeof' '(' type-name ')'
  1751. /// [C++11] 'sizeof' '...' '(' identifier ')'
  1752. /// [GNU] '__alignof' unary-expression
  1753. /// [GNU] '__alignof' '(' type-name ')'
  1754. /// [C11] '_Alignof' '(' type-name ')'
  1755. /// [C++11] 'alignof' '(' type-id ')'
  1756. /// \endverbatim
  1757. ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
  1758. // HLSL Change Begin
  1759. assert((!getLangOpts().HLSL || Tok.getKind() == tok::kw_sizeof)
  1760. && "not supported for HLSL - unreachable");
  1761. // HLSL Change End
  1762. assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
  1763. tok::kw__Alignof, tok::kw_vec_step,
  1764. tok::kw___builtin_omp_required_simd_align) &&
  1765. "Not a sizeof/alignof/vec_step expression!");
  1766. Token OpTok = Tok;
  1767. ConsumeToken();
  1768. // [C++11] 'sizeof' '...' '(' identifier ')'
  1769. if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof) && !getLangOpts().HLSL) { // HLSL Change
  1770. SourceLocation EllipsisLoc = ConsumeToken();
  1771. SourceLocation LParenLoc, RParenLoc;
  1772. IdentifierInfo *Name = nullptr;
  1773. SourceLocation NameLoc;
  1774. if (Tok.is(tok::l_paren)) {
  1775. BalancedDelimiterTracker T(*this, tok::l_paren);
  1776. T.consumeOpen();
  1777. LParenLoc = T.getOpenLocation();
  1778. if (Tok.is(tok::identifier)) {
  1779. Name = Tok.getIdentifierInfo();
  1780. NameLoc = ConsumeToken();
  1781. T.consumeClose();
  1782. RParenLoc = T.getCloseLocation();
  1783. if (RParenLoc.isInvalid())
  1784. RParenLoc = PP.getLocForEndOfToken(NameLoc);
  1785. } else {
  1786. Diag(Tok, diag::err_expected_parameter_pack);
  1787. SkipUntil(tok::r_paren, StopAtSemi);
  1788. }
  1789. } else if (Tok.is(tok::identifier)) {
  1790. Name = Tok.getIdentifierInfo();
  1791. NameLoc = ConsumeToken();
  1792. LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
  1793. RParenLoc = PP.getLocForEndOfToken(NameLoc);
  1794. Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
  1795. << Name
  1796. << FixItHint::CreateInsertion(LParenLoc, "(")
  1797. << FixItHint::CreateInsertion(RParenLoc, ")");
  1798. } else {
  1799. Diag(Tok, diag::err_sizeof_parameter_pack);
  1800. }
  1801. if (!Name)
  1802. return ExprError();
  1803. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
  1804. Sema::ReuseLambdaContextDecl);
  1805. return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
  1806. OpTok.getLocation(),
  1807. *Name, NameLoc,
  1808. RParenLoc);
  1809. }
  1810. if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
  1811. Diag(OpTok, diag::warn_cxx98_compat_alignof);
  1812. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
  1813. Sema::ReuseLambdaContextDecl);
  1814. bool isCastExpr;
  1815. ParsedType CastTy;
  1816. SourceRange CastRange;
  1817. ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
  1818. isCastExpr,
  1819. CastTy,
  1820. CastRange);
  1821. UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
  1822. if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
  1823. ExprKind = UETT_AlignOf;
  1824. else if (OpTok.is(tok::kw_vec_step))
  1825. ExprKind = UETT_VecStep;
  1826. else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
  1827. ExprKind = UETT_OpenMPRequiredSimdAlign;
  1828. if (isCastExpr)
  1829. return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
  1830. ExprKind,
  1831. /*isType=*/true,
  1832. CastTy.getAsOpaquePtr(),
  1833. CastRange);
  1834. if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
  1835. Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
  1836. // If we get here, the operand to the sizeof/alignof was an expresion.
  1837. if (!Operand.isInvalid())
  1838. Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
  1839. ExprKind,
  1840. /*isType=*/false,
  1841. Operand.get(),
  1842. CastRange);
  1843. return Operand;
  1844. }
  1845. /// ParseBuiltinPrimaryExpression
  1846. ///
  1847. /// \verbatim
  1848. /// primary-expression: [C99 6.5.1]
  1849. /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
  1850. /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
  1851. /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
  1852. /// assign-expr ')'
  1853. /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
  1854. /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
  1855. ///
  1856. /// [GNU] offsetof-member-designator:
  1857. /// [GNU] identifier
  1858. /// [GNU] offsetof-member-designator '.' identifier
  1859. /// [GNU] offsetof-member-designator '[' expression ']'
  1860. /// \endverbatim
  1861. ExprResult Parser::ParseBuiltinPrimaryExpression() {
  1862. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  1863. ExprResult Res;
  1864. const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
  1865. tok::TokenKind T = Tok.getKind();
  1866. SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
  1867. // All of these start with an open paren.
  1868. if (Tok.isNot(tok::l_paren))
  1869. return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
  1870. << tok::l_paren);
  1871. BalancedDelimiterTracker PT(*this, tok::l_paren);
  1872. PT.consumeOpen();
  1873. // TODO: Build AST.
  1874. switch (T) {
  1875. default: llvm_unreachable("Not a builtin primary expression!");
  1876. case tok::kw___builtin_va_arg: {
  1877. ExprResult Expr(ParseAssignmentExpression());
  1878. if (ExpectAndConsume(tok::comma)) {
  1879. SkipUntil(tok::r_paren, StopAtSemi);
  1880. Expr = ExprError();
  1881. }
  1882. TypeResult Ty = ParseTypeName();
  1883. if (Tok.isNot(tok::r_paren)) {
  1884. Diag(Tok, diag::err_expected) << tok::r_paren;
  1885. Expr = ExprError();
  1886. }
  1887. if (Expr.isInvalid() || Ty.isInvalid())
  1888. Res = ExprError();
  1889. else
  1890. Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
  1891. break;
  1892. }
  1893. case tok::kw___builtin_offsetof: {
  1894. SourceLocation TypeLoc = Tok.getLocation();
  1895. TypeResult Ty = ParseTypeName();
  1896. if (Ty.isInvalid()) {
  1897. SkipUntil(tok::r_paren, StopAtSemi);
  1898. return ExprError();
  1899. }
  1900. if (ExpectAndConsume(tok::comma)) {
  1901. SkipUntil(tok::r_paren, StopAtSemi);
  1902. return ExprError();
  1903. }
  1904. // We must have at least one identifier here.
  1905. if (Tok.isNot(tok::identifier)) {
  1906. Diag(Tok, diag::err_expected) << tok::identifier;
  1907. SkipUntil(tok::r_paren, StopAtSemi);
  1908. return ExprError();
  1909. }
  1910. // Keep track of the various subcomponents we see.
  1911. SmallVector<Sema::OffsetOfComponent, 4> Comps;
  1912. Comps.push_back(Sema::OffsetOfComponent());
  1913. Comps.back().isBrackets = false;
  1914. Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
  1915. Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
  1916. // FIXME: This loop leaks the index expressions on error.
  1917. while (1) {
  1918. if (Tok.is(tok::period)) {
  1919. // offsetof-member-designator: offsetof-member-designator '.' identifier
  1920. Comps.push_back(Sema::OffsetOfComponent());
  1921. Comps.back().isBrackets = false;
  1922. Comps.back().LocStart = ConsumeToken();
  1923. if (Tok.isNot(tok::identifier)) {
  1924. Diag(Tok, diag::err_expected) << tok::identifier;
  1925. SkipUntil(tok::r_paren, StopAtSemi);
  1926. return ExprError();
  1927. }
  1928. Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
  1929. Comps.back().LocEnd = ConsumeToken();
  1930. } else if (Tok.is(tok::l_square)) {
  1931. if (CheckProhibitedCXX11Attribute())
  1932. return ExprError();
  1933. // offsetof-member-designator: offsetof-member-design '[' expression ']'
  1934. Comps.push_back(Sema::OffsetOfComponent());
  1935. Comps.back().isBrackets = true;
  1936. BalancedDelimiterTracker ST(*this, tok::l_square);
  1937. ST.consumeOpen();
  1938. Comps.back().LocStart = ST.getOpenLocation();
  1939. Res = ParseExpression();
  1940. if (Res.isInvalid()) {
  1941. SkipUntil(tok::r_paren, StopAtSemi);
  1942. return Res;
  1943. }
  1944. Comps.back().U.E = Res.get();
  1945. ST.consumeClose();
  1946. Comps.back().LocEnd = ST.getCloseLocation();
  1947. } else {
  1948. if (Tok.isNot(tok::r_paren)) {
  1949. PT.consumeClose();
  1950. Res = ExprError();
  1951. } else if (Ty.isInvalid()) {
  1952. Res = ExprError();
  1953. } else {
  1954. PT.consumeClose();
  1955. Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
  1956. Ty.get(), &Comps[0], Comps.size(),
  1957. PT.getCloseLocation());
  1958. }
  1959. break;
  1960. }
  1961. }
  1962. break;
  1963. }
  1964. case tok::kw___builtin_choose_expr: {
  1965. ExprResult Cond(ParseAssignmentExpression());
  1966. if (Cond.isInvalid()) {
  1967. SkipUntil(tok::r_paren, StopAtSemi);
  1968. return Cond;
  1969. }
  1970. if (ExpectAndConsume(tok::comma)) {
  1971. SkipUntil(tok::r_paren, StopAtSemi);
  1972. return ExprError();
  1973. }
  1974. ExprResult Expr1(ParseAssignmentExpression());
  1975. if (Expr1.isInvalid()) {
  1976. SkipUntil(tok::r_paren, StopAtSemi);
  1977. return Expr1;
  1978. }
  1979. if (ExpectAndConsume(tok::comma)) {
  1980. SkipUntil(tok::r_paren, StopAtSemi);
  1981. return ExprError();
  1982. }
  1983. ExprResult Expr2(ParseAssignmentExpression());
  1984. if (Expr2.isInvalid()) {
  1985. SkipUntil(tok::r_paren, StopAtSemi);
  1986. return Expr2;
  1987. }
  1988. if (Tok.isNot(tok::r_paren)) {
  1989. Diag(Tok, diag::err_expected) << tok::r_paren;
  1990. return ExprError();
  1991. }
  1992. Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
  1993. Expr2.get(), ConsumeParen());
  1994. break;
  1995. }
  1996. case tok::kw___builtin_astype: {
  1997. // The first argument is an expression to be converted, followed by a comma.
  1998. ExprResult Expr(ParseAssignmentExpression());
  1999. if (Expr.isInvalid()) {
  2000. SkipUntil(tok::r_paren, StopAtSemi);
  2001. return ExprError();
  2002. }
  2003. if (ExpectAndConsume(tok::comma)) {
  2004. SkipUntil(tok::r_paren, StopAtSemi);
  2005. return ExprError();
  2006. }
  2007. // Second argument is the type to bitcast to.
  2008. TypeResult DestTy = ParseTypeName();
  2009. if (DestTy.isInvalid())
  2010. return ExprError();
  2011. // Attempt to consume the r-paren.
  2012. if (Tok.isNot(tok::r_paren)) {
  2013. Diag(Tok, diag::err_expected) << tok::r_paren;
  2014. SkipUntil(tok::r_paren, StopAtSemi);
  2015. return ExprError();
  2016. }
  2017. Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
  2018. ConsumeParen());
  2019. break;
  2020. }
  2021. case tok::kw___builtin_convertvector: {
  2022. // The first argument is an expression to be converted, followed by a comma.
  2023. ExprResult Expr(ParseAssignmentExpression());
  2024. if (Expr.isInvalid()) {
  2025. SkipUntil(tok::r_paren, StopAtSemi);
  2026. return ExprError();
  2027. }
  2028. if (ExpectAndConsume(tok::comma)) {
  2029. SkipUntil(tok::r_paren, StopAtSemi);
  2030. return ExprError();
  2031. }
  2032. // Second argument is the type to bitcast to.
  2033. TypeResult DestTy = ParseTypeName();
  2034. if (DestTy.isInvalid())
  2035. return ExprError();
  2036. // Attempt to consume the r-paren.
  2037. if (Tok.isNot(tok::r_paren)) {
  2038. Diag(Tok, diag::err_expected) << tok::r_paren;
  2039. SkipUntil(tok::r_paren, StopAtSemi);
  2040. return ExprError();
  2041. }
  2042. Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
  2043. ConsumeParen());
  2044. break;
  2045. }
  2046. }
  2047. if (Res.isInvalid())
  2048. return ExprError();
  2049. // These can be followed by postfix-expr pieces because they are
  2050. // primary-expressions.
  2051. return ParsePostfixExpressionSuffix(Res.get());
  2052. }
  2053. /// ParseParenExpression - This parses the unit that starts with a '(' token,
  2054. /// based on what is allowed by ExprType. The actual thing parsed is returned
  2055. /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
  2056. /// not the parsed cast-expression.
  2057. ///
  2058. /// \verbatim
  2059. /// primary-expression: [C99 6.5.1]
  2060. /// '(' expression ')'
  2061. /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
  2062. /// postfix-expression: [C99 6.5.2]
  2063. /// '(' type-name ')' '{' initializer-list '}'
  2064. /// '(' type-name ')' '{' initializer-list ',' '}'
  2065. /// cast-expression: [C99 6.5.4]
  2066. /// '(' type-name ')' cast-expression
  2067. /// [ARC] bridged-cast-expression
  2068. /// [ARC] bridged-cast-expression:
  2069. /// (__bridge type-name) cast-expression
  2070. /// (__bridge_transfer type-name) cast-expression
  2071. /// (__bridge_retained type-name) cast-expression
  2072. /// fold-expression: [C++1z]
  2073. /// '(' cast-expression fold-operator '...' ')'
  2074. /// '(' '...' fold-operator cast-expression ')'
  2075. /// '(' cast-expression fold-operator '...'
  2076. /// fold-operator cast-expression ')'
  2077. /// \endverbatim
  2078. ExprResult
  2079. Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
  2080. bool isTypeCast, ParsedType &CastTy,
  2081. SourceLocation &RParenLoc) {
  2082. assert(Tok.is(tok::l_paren) && "Not a paren expr!");
  2083. ColonProtectionRAIIObject ColonProtection(*this, false);
  2084. BalancedDelimiterTracker T(*this, tok::l_paren);
  2085. if (T.consumeOpen())
  2086. return ExprError();
  2087. SourceLocation OpenLoc = T.getOpenLocation();
  2088. ExprResult Result(true);
  2089. bool isAmbiguousTypeId;
  2090. CastTy = ParsedType();
  2091. if (Tok.is(tok::code_completion)) {
  2092. Actions.CodeCompleteOrdinaryName(getCurScope(),
  2093. ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
  2094. : Sema::PCC_Expression);
  2095. cutOffParsing();
  2096. return ExprError();
  2097. }
  2098. // Diagnose use of bridge casts in non-arc mode.
  2099. bool BridgeCast = (getLangOpts().ObjC2 &&
  2100. Tok.isOneOf(tok::kw___bridge,
  2101. tok::kw___bridge_transfer,
  2102. tok::kw___bridge_retained,
  2103. tok::kw___bridge_retain));
  2104. if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
  2105. if (!TryConsumeToken(tok::kw___bridge)) {
  2106. StringRef BridgeCastName = Tok.getName();
  2107. SourceLocation BridgeKeywordLoc = ConsumeToken();
  2108. if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
  2109. Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
  2110. << BridgeCastName
  2111. << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
  2112. }
  2113. BridgeCast = false;
  2114. }
  2115. // None of these cases should fall through with an invalid Result
  2116. // unless they've already reported an error.
  2117. if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
  2118. Diag(Tok, diag::ext_gnu_statement_expr);
  2119. if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
  2120. Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
  2121. } else {
  2122. // Find the nearest non-record decl context. Variables declared in a
  2123. // statement expression behave as if they were declared in the enclosing
  2124. // function, block, or other code construct.
  2125. DeclContext *CodeDC = Actions.CurContext;
  2126. while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
  2127. CodeDC = CodeDC->getParent();
  2128. assert(CodeDC && !CodeDC->isFileContext() &&
  2129. "statement expr not in code context");
  2130. }
  2131. Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
  2132. Actions.ActOnStartStmtExpr();
  2133. StmtResult Stmt(ParseCompoundStatement(true));
  2134. ExprType = CompoundStmt;
  2135. // If the substmt parsed correctly, build the AST node.
  2136. if (!Stmt.isInvalid()) {
  2137. Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
  2138. } else {
  2139. Actions.ActOnStmtExprError();
  2140. }
  2141. }
  2142. } else if (ExprType >= CompoundLiteral && BridgeCast) {
  2143. tok::TokenKind tokenKind = Tok.getKind();
  2144. SourceLocation BridgeKeywordLoc = ConsumeToken();
  2145. // Parse an Objective-C ARC ownership cast expression.
  2146. ObjCBridgeCastKind Kind;
  2147. if (tokenKind == tok::kw___bridge)
  2148. Kind = OBC_Bridge;
  2149. else if (tokenKind == tok::kw___bridge_transfer)
  2150. Kind = OBC_BridgeTransfer;
  2151. else if (tokenKind == tok::kw___bridge_retained)
  2152. Kind = OBC_BridgeRetained;
  2153. else {
  2154. // As a hopefully temporary workaround, allow __bridge_retain as
  2155. // a synonym for __bridge_retained, but only in system headers.
  2156. assert(tokenKind == tok::kw___bridge_retain);
  2157. Kind = OBC_BridgeRetained;
  2158. if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
  2159. Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
  2160. << FixItHint::CreateReplacement(BridgeKeywordLoc,
  2161. "__bridge_retained");
  2162. }
  2163. TypeResult Ty = ParseTypeName();
  2164. T.consumeClose();
  2165. ColonProtection.restore();
  2166. RParenLoc = T.getCloseLocation();
  2167. ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
  2168. if (Ty.isInvalid() || SubExpr.isInvalid())
  2169. return ExprError();
  2170. return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
  2171. BridgeKeywordLoc, Ty.get(),
  2172. RParenLoc, SubExpr.get());
  2173. } else if (ExprType >= CompoundLiteral &&
  2174. isTypeIdInParens(isAmbiguousTypeId)) {
  2175. // Otherwise, this is a compound literal expression or cast expression.
  2176. // In C++, if the type-id is ambiguous we disambiguate based on context.
  2177. // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
  2178. // in which case we should treat it as type-id.
  2179. // if stopIfCastExpr is false, we need to determine the context past the
  2180. // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
  2181. if (isAmbiguousTypeId && !stopIfCastExpr) {
  2182. ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
  2183. ColonProtection);
  2184. RParenLoc = T.getCloseLocation();
  2185. return res;
  2186. }
  2187. // Parse the type declarator.
  2188. DeclSpec DS(AttrFactory);
  2189. ParseSpecifierQualifierList(DS);
  2190. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  2191. ParseDeclarator(DeclaratorInfo);
  2192. // If our type is followed by an identifier and either ':' or ']', then
  2193. // this is probably an Objective-C message send where the leading '[' is
  2194. // missing. Recover as if that were the case.
  2195. if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
  2196. !InMessageExpression && getLangOpts().ObjC1 &&
  2197. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
  2198. TypeResult Ty;
  2199. {
  2200. InMessageExpressionRAIIObject InMessage(*this, false);
  2201. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  2202. }
  2203. Result = ParseObjCMessageExpressionBody(SourceLocation(),
  2204. SourceLocation(),
  2205. Ty.get(), nullptr);
  2206. } else {
  2207. // Match the ')'.
  2208. T.consumeClose();
  2209. ColonProtection.restore();
  2210. RParenLoc = T.getCloseLocation();
  2211. if (Tok.is(tok::l_brace)) {
  2212. // HLSL Change Starts
  2213. if (getLangOpts().HLSL) {
  2214. // (type-name) { initializer-list }
  2215. Diag(Tok, diag::err_hlsl_unsupported_construct) << "compound literal";
  2216. return ExprError();
  2217. }
  2218. // HLSL Change Ends
  2219. ExprType = CompoundLiteral;
  2220. TypeResult Ty;
  2221. {
  2222. InMessageExpressionRAIIObject InMessage(*this, false);
  2223. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  2224. }
  2225. return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
  2226. }
  2227. if (ExprType == CastExpr) {
  2228. // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
  2229. if (DeclaratorInfo.isInvalidType())
  2230. return ExprError();
  2231. // Note that this doesn't parse the subsequent cast-expression, it just
  2232. // returns the parsed type to the callee.
  2233. if (stopIfCastExpr) {
  2234. TypeResult Ty;
  2235. {
  2236. InMessageExpressionRAIIObject InMessage(*this, false);
  2237. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  2238. }
  2239. CastTy = Ty.get();
  2240. return ExprResult();
  2241. }
  2242. // Reject the cast of super idiom in ObjC.
  2243. if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
  2244. Tok.getIdentifierInfo() == Ident_super &&
  2245. getCurScope()->isInObjcMethodScope() &&
  2246. GetLookAheadToken(1).isNot(tok::period)) {
  2247. Diag(Tok.getLocation(), diag::err_illegal_super_cast)
  2248. << SourceRange(OpenLoc, RParenLoc);
  2249. return ExprError();
  2250. }
  2251. // Parse the cast-expression that follows it next.
  2252. // TODO: For cast expression with CastTy.
  2253. Result = ParseCastExpression(/*isUnaryExpression=*/false,
  2254. /*isAddressOfOperand=*/false,
  2255. /*isTypeCast=*/IsTypeCast);
  2256. if (!Result.isInvalid()) {
  2257. Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
  2258. DeclaratorInfo, CastTy,
  2259. RParenLoc, Result.get());
  2260. }
  2261. return Result;
  2262. }
  2263. Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
  2264. return ExprError();
  2265. }
  2266. } else if (Tok.is(tok::ellipsis) &&
  2267. isFoldOperator(NextToken().getKind())) {
  2268. return ParseFoldExpression(ExprResult(), T);
  2269. } else if (isTypeCast) {
  2270. // Parse the expression-list.
  2271. InMessageExpressionRAIIObject InMessage(*this, false);
  2272. ExprVector ArgExprs;
  2273. CommaLocsTy CommaLocs;
  2274. if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
  2275. // FIXME: If we ever support comma expressions as operands to
  2276. // fold-expressions, we'll need to allow multiple ArgExprs here.
  2277. if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
  2278. NextToken().is(tok::ellipsis))
  2279. return ParseFoldExpression(Result, T);
  2280. ExprType = SimpleExpr;
  2281. Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
  2282. ArgExprs);
  2283. }
  2284. } else {
  2285. InMessageExpressionRAIIObject InMessage(*this, false);
  2286. Result = ParseExpression(MaybeTypeCast);
  2287. if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
  2288. // Correct typos in non-C++ code earlier so that implicit-cast-like
  2289. // expressions are parsed correctly.
  2290. Result = Actions.CorrectDelayedTyposInExpr(Result);
  2291. }
  2292. ExprType = SimpleExpr;
  2293. if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
  2294. return ParseFoldExpression(Result, T);
  2295. // Don't build a paren expression unless we actually match a ')'.
  2296. if (!Result.isInvalid() && Tok.is(tok::r_paren))
  2297. Result =
  2298. Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
  2299. }
  2300. // Match the ')'.
  2301. if (Result.isInvalid()) {
  2302. SkipUntil(tok::r_paren, StopAtSemi);
  2303. return ExprError();
  2304. }
  2305. T.consumeClose();
  2306. RParenLoc = T.getCloseLocation();
  2307. return Result;
  2308. }
  2309. /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
  2310. /// and we are at the left brace.
  2311. ///
  2312. /// \verbatim
  2313. /// postfix-expression: [C99 6.5.2]
  2314. /// '(' type-name ')' '{' initializer-list '}'
  2315. /// '(' type-name ')' '{' initializer-list ',' '}'
  2316. /// \endverbatim
  2317. ExprResult
  2318. Parser::ParseCompoundLiteralExpression(ParsedType Ty,
  2319. SourceLocation LParenLoc,
  2320. SourceLocation RParenLoc) {
  2321. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2322. assert(Tok.is(tok::l_brace) && "Not a compound literal!");
  2323. if (!getLangOpts().C99) // Compound literals don't exist in C90.
  2324. Diag(LParenLoc, diag::ext_c99_compound_literal);
  2325. ExprResult Result = ParseInitializer();
  2326. if (!Result.isInvalid() && Ty)
  2327. return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
  2328. return Result;
  2329. }
  2330. /// ParseStringLiteralExpression - This handles the various token types that
  2331. /// form string literals, and also handles string concatenation [C99 5.1.1.2,
  2332. /// translation phase #6].
  2333. ///
  2334. /// \verbatim
  2335. /// primary-expression: [C99 6.5.1]
  2336. /// string-literal
  2337. /// \verbatim
  2338. ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
  2339. assert(isTokenStringLiteral() && "Not a string literal!");
  2340. // String concat. Note that keywords like __func__ and __FUNCTION__ are not
  2341. // considered to be strings for concatenation purposes.
  2342. SmallVector<Token, 4> StringToks;
  2343. do {
  2344. StringToks.push_back(Tok);
  2345. ConsumeStringToken();
  2346. } while (isTokenStringLiteral());
  2347. // Pass the set of string tokens, ready for concatenation, to the actions.
  2348. return Actions.ActOnStringLiteral(StringToks,
  2349. AllowUserDefinedLiteral ? getCurScope()
  2350. : nullptr);
  2351. }
  2352. /// ParseGenericSelectionExpression - Parse a C11 generic-selection
  2353. /// [C11 6.5.1.1].
  2354. ///
  2355. /// \verbatim
  2356. /// generic-selection:
  2357. /// _Generic ( assignment-expression , generic-assoc-list )
  2358. /// generic-assoc-list:
  2359. /// generic-association
  2360. /// generic-assoc-list , generic-association
  2361. /// generic-association:
  2362. /// type-name : assignment-expression
  2363. /// default : assignment-expression
  2364. /// \endverbatim
  2365. ExprResult Parser::ParseGenericSelectionExpression() {
  2366. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2367. assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
  2368. SourceLocation KeyLoc = ConsumeToken();
  2369. if (!getLangOpts().C11)
  2370. Diag(KeyLoc, diag::ext_c11_generic_selection);
  2371. BalancedDelimiterTracker T(*this, tok::l_paren);
  2372. if (T.expectAndConsume())
  2373. return ExprError();
  2374. ExprResult ControllingExpr;
  2375. {
  2376. // C11 6.5.1.1p3 "The controlling expression of a generic selection is
  2377. // not evaluated."
  2378. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  2379. ControllingExpr =
  2380. Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
  2381. if (ControllingExpr.isInvalid()) {
  2382. SkipUntil(tok::r_paren, StopAtSemi);
  2383. return ExprError();
  2384. }
  2385. }
  2386. if (ExpectAndConsume(tok::comma)) {
  2387. SkipUntil(tok::r_paren, StopAtSemi);
  2388. return ExprError();
  2389. }
  2390. SourceLocation DefaultLoc;
  2391. TypeVector Types;
  2392. ExprVector Exprs;
  2393. do {
  2394. ParsedType Ty;
  2395. if (Tok.is(tok::kw_default)) {
  2396. // C11 6.5.1.1p2 "A generic selection shall have no more than one default
  2397. // generic association."
  2398. if (!DefaultLoc.isInvalid()) {
  2399. Diag(Tok, diag::err_duplicate_default_assoc);
  2400. Diag(DefaultLoc, diag::note_previous_default_assoc);
  2401. SkipUntil(tok::r_paren, StopAtSemi);
  2402. return ExprError();
  2403. }
  2404. DefaultLoc = ConsumeToken();
  2405. Ty = ParsedType();
  2406. } else {
  2407. ColonProtectionRAIIObject X(*this);
  2408. TypeResult TR = ParseTypeName();
  2409. if (TR.isInvalid()) {
  2410. SkipUntil(tok::r_paren, StopAtSemi);
  2411. return ExprError();
  2412. }
  2413. Ty = TR.get();
  2414. }
  2415. Types.push_back(Ty);
  2416. if (ExpectAndConsume(tok::colon)) {
  2417. SkipUntil(tok::r_paren, StopAtSemi);
  2418. return ExprError();
  2419. }
  2420. // FIXME: These expressions should be parsed in a potentially potentially
  2421. // evaluated context.
  2422. ExprResult ER(
  2423. Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
  2424. if (ER.isInvalid()) {
  2425. SkipUntil(tok::r_paren, StopAtSemi);
  2426. return ExprError();
  2427. }
  2428. Exprs.push_back(ER.get());
  2429. } while (TryConsumeToken(tok::comma));
  2430. T.consumeClose();
  2431. if (T.getCloseLocation().isInvalid())
  2432. return ExprError();
  2433. return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
  2434. T.getCloseLocation(),
  2435. ControllingExpr.get(),
  2436. Types, Exprs);
  2437. }
  2438. /// \brief Parse A C++1z fold-expression after the opening paren and optional
  2439. /// left-hand-side expression.
  2440. ///
  2441. /// \verbatim
  2442. /// fold-expression:
  2443. /// ( cast-expression fold-operator ... )
  2444. /// ( ... fold-operator cast-expression )
  2445. /// ( cast-expression fold-operator ... fold-operator cast-expression )
  2446. ExprResult Parser::ParseFoldExpression(ExprResult LHS,
  2447. BalancedDelimiterTracker &T) {
  2448. if (LHS.isInvalid()) {
  2449. T.skipToEnd();
  2450. return true;
  2451. }
  2452. tok::TokenKind Kind = tok::unknown;
  2453. SourceLocation FirstOpLoc;
  2454. if (LHS.isUsable()) {
  2455. Kind = Tok.getKind();
  2456. assert(isFoldOperator(Kind) && "missing fold-operator");
  2457. FirstOpLoc = ConsumeToken();
  2458. }
  2459. assert(Tok.is(tok::ellipsis) && "not a fold-expression");
  2460. SourceLocation EllipsisLoc = ConsumeToken();
  2461. ExprResult RHS;
  2462. if (Tok.isNot(tok::r_paren)) {
  2463. if (!isFoldOperator(Tok.getKind()))
  2464. return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
  2465. if (Kind != tok::unknown && Tok.getKind() != Kind)
  2466. Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
  2467. << SourceRange(FirstOpLoc);
  2468. Kind = Tok.getKind();
  2469. ConsumeToken();
  2470. RHS = ParseExpression();
  2471. if (RHS.isInvalid()) {
  2472. T.skipToEnd();
  2473. return true;
  2474. }
  2475. }
  2476. Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
  2477. ? diag::warn_cxx14_compat_fold_expression
  2478. : diag::ext_fold_expression);
  2479. T.consumeClose();
  2480. return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
  2481. EllipsisLoc, RHS.get(), T.getCloseLocation());
  2482. }
  2483. /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
  2484. ///
  2485. /// \verbatim
  2486. /// argument-expression-list:
  2487. /// assignment-expression
  2488. /// argument-expression-list , assignment-expression
  2489. ///
  2490. /// [C++] expression-list:
  2491. /// [C++] assignment-expression
  2492. /// [C++] expression-list , assignment-expression
  2493. ///
  2494. /// [C++0x] expression-list:
  2495. /// [C++0x] initializer-list
  2496. ///
  2497. /// [C++0x] initializer-list
  2498. /// [C++0x] initializer-clause ...[opt]
  2499. /// [C++0x] initializer-list , initializer-clause ...[opt]
  2500. ///
  2501. /// [C++0x] initializer-clause:
  2502. /// [C++0x] assignment-expression
  2503. /// [C++0x] braced-init-list
  2504. /// \endverbatim
  2505. bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
  2506. SmallVectorImpl<SourceLocation> &CommaLocs,
  2507. std::function<void()> Completer) {
  2508. bool SawError = false;
  2509. while (1) {
  2510. if (Tok.is(tok::code_completion)) {
  2511. if (Completer)
  2512. Completer();
  2513. else
  2514. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
  2515. cutOffParsing();
  2516. return true;
  2517. }
  2518. ExprResult Expr;
  2519. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  2520. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  2521. Expr = ParseBraceInitializer();
  2522. } else
  2523. Expr = ParseAssignmentExpression();
  2524. if (Tok.is(tok::ellipsis)) {
  2525. // HLSL Change Starts
  2526. if (getLangOpts().HLSL) {
  2527. Diag(Tok, diag::err_hlsl_variadic_templates);
  2528. SkipUntil(tok::r_paren, StopBeforeMatch);
  2529. Actions.CorrectDelayedTyposInExpr(Expr);
  2530. Expr = ExprError();
  2531. SawError = true;
  2532. break;
  2533. }
  2534. // HLSL Change Ends
  2535. Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
  2536. }
  2537. if (Expr.isInvalid()) {
  2538. SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
  2539. SawError = true;
  2540. } else {
  2541. Exprs.push_back(Expr.get());
  2542. }
  2543. if (Tok.isNot(tok::comma))
  2544. break;
  2545. // Move to the next argument, remember where the comma was.
  2546. CommaLocs.push_back(ConsumeToken());
  2547. }
  2548. if (SawError) {
  2549. // Ensure typos get diagnosed when errors were encountered while parsing the
  2550. // expression list.
  2551. for (auto &E : Exprs) {
  2552. ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
  2553. if (Expr.isUsable()) E = Expr.get();
  2554. }
  2555. }
  2556. return SawError;
  2557. }
  2558. /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
  2559. /// used for misc language extensions.
  2560. ///
  2561. /// \verbatim
  2562. /// simple-expression-list:
  2563. /// assignment-expression
  2564. /// simple-expression-list , assignment-expression
  2565. /// \endverbatim
  2566. bool
  2567. Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
  2568. SmallVectorImpl<SourceLocation> &CommaLocs) {
  2569. while (1) {
  2570. ExprResult Expr = ParseAssignmentExpression();
  2571. if (Expr.isInvalid())
  2572. return true;
  2573. Exprs.push_back(Expr.get());
  2574. if (Tok.isNot(tok::comma))
  2575. return false;
  2576. // Move to the next argument, remember where the comma was.
  2577. CommaLocs.push_back(ConsumeToken());
  2578. }
  2579. }
  2580. /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
  2581. ///
  2582. /// \verbatim
  2583. /// [clang] block-id:
  2584. /// [clang] specifier-qualifier-list block-declarator
  2585. /// \endverbatim
  2586. void Parser::ParseBlockId(SourceLocation CaretLoc) {
  2587. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2588. if (Tok.is(tok::code_completion)) {
  2589. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
  2590. return cutOffParsing();
  2591. }
  2592. // Parse the specifier-qualifier-list piece.
  2593. DeclSpec DS(AttrFactory);
  2594. ParseSpecifierQualifierList(DS);
  2595. // Parse the block-declarator.
  2596. Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
  2597. ParseDeclarator(DeclaratorInfo);
  2598. MaybeParseGNUAttributes(DeclaratorInfo);
  2599. // Inform sema that we are starting a block.
  2600. Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
  2601. }
  2602. /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
  2603. /// like ^(int x){ return x+1; }
  2604. ///
  2605. /// \verbatim
  2606. /// block-literal:
  2607. /// [clang] '^' block-args[opt] compound-statement
  2608. /// [clang] '^' block-id compound-statement
  2609. /// [clang] block-args:
  2610. /// [clang] '(' parameter-list ')'
  2611. /// \endverbatim
  2612. ExprResult Parser::ParseBlockLiteralExpression() {
  2613. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2614. assert(Tok.is(tok::caret) && "block literal starts with ^");
  2615. SourceLocation CaretLoc = ConsumeToken();
  2616. PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
  2617. "block literal parsing");
  2618. // Enter a scope to hold everything within the block. This includes the
  2619. // argument decls, decls within the compound expression, etc. This also
  2620. // allows determining whether a variable reference inside the block is
  2621. // within or outside of the block.
  2622. ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
  2623. Scope::DeclScope);
  2624. // Inform sema that we are starting a block.
  2625. Actions.ActOnBlockStart(CaretLoc, getCurScope());
  2626. // Parse the return type if present.
  2627. DeclSpec DS(AttrFactory);
  2628. Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
  2629. // FIXME: Since the return type isn't actually parsed, it can't be used to
  2630. // fill ParamInfo with an initial valid range, so do it manually.
  2631. ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
  2632. // If this block has arguments, parse them. There is no ambiguity here with
  2633. // the expression case, because the expression case requires a parameter list.
  2634. if (Tok.is(tok::l_paren)) {
  2635. ParseParenDeclarator(ParamInfo);
  2636. // Parse the pieces after the identifier as if we had "int(...)".
  2637. // SetIdentifier sets the source range end, but in this case we're past
  2638. // that location.
  2639. SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
  2640. ParamInfo.SetIdentifier(nullptr, CaretLoc);
  2641. ParamInfo.SetRangeEnd(Tmp);
  2642. if (ParamInfo.isInvalidType()) {
  2643. // If there was an error parsing the arguments, they may have
  2644. // tried to use ^(x+y) which requires an argument list. Just
  2645. // skip the whole block literal.
  2646. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2647. return ExprError();
  2648. }
  2649. MaybeParseGNUAttributes(ParamInfo);
  2650. // Inform sema that we are starting a block.
  2651. Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
  2652. } else if (!Tok.is(tok::l_brace)) {
  2653. ParseBlockId(CaretLoc);
  2654. } else {
  2655. // Otherwise, pretend we saw (void).
  2656. ParsedAttributes attrs(AttrFactory);
  2657. SourceLocation NoLoc;
  2658. ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
  2659. /*IsAmbiguous=*/false,
  2660. /*RParenLoc=*/NoLoc,
  2661. /*ArgInfo=*/nullptr,
  2662. /*NumArgs=*/0,
  2663. /*EllipsisLoc=*/NoLoc,
  2664. /*RParenLoc=*/NoLoc,
  2665. /*TypeQuals=*/0,
  2666. /*RefQualifierIsLvalueRef=*/true,
  2667. /*RefQualifierLoc=*/NoLoc,
  2668. /*ConstQualifierLoc=*/NoLoc,
  2669. /*VolatileQualifierLoc=*/NoLoc,
  2670. /*RestrictQualifierLoc=*/NoLoc,
  2671. /*MutableLoc=*/NoLoc,
  2672. EST_None,
  2673. /*ESpecLoc=*/NoLoc,
  2674. /*Exceptions=*/nullptr,
  2675. /*ExceptionRanges=*/nullptr,
  2676. /*NumExceptions=*/0,
  2677. /*NoexceptExpr=*/nullptr,
  2678. /*ExceptionSpecTokens=*/nullptr,
  2679. CaretLoc, CaretLoc,
  2680. ParamInfo),
  2681. attrs, CaretLoc);
  2682. MaybeParseGNUAttributes(ParamInfo);
  2683. // Inform sema that we are starting a block.
  2684. Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
  2685. }
  2686. ExprResult Result(true);
  2687. if (!Tok.is(tok::l_brace)) {
  2688. // Saw something like: ^expr
  2689. Diag(Tok, diag::err_expected_expression);
  2690. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2691. return ExprError();
  2692. }
  2693. StmtResult Stmt(ParseCompoundStatementBody());
  2694. BlockScope.Exit();
  2695. if (!Stmt.isInvalid())
  2696. Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
  2697. else
  2698. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2699. return Result;
  2700. }
  2701. /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
  2702. ///
  2703. /// '__objc_yes'
  2704. /// '__objc_no'
  2705. ExprResult Parser::ParseObjCBoolLiteral() {
  2706. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2707. tok::TokenKind Kind = Tok.getKind();
  2708. return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
  2709. }