ParseExpr.cpp 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942
  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. case tok::identifier: { // primary-expression: identifier
  735. // unqualified-id: identifier
  736. // constant: enumeration-constant
  737. // Turn a potentially qualified name into a annot_typename or
  738. // annot_cxxscope if it would be valid. This handles things like x::y, etc.
  739. if (getLangOpts().CPlusPlus) {
  740. // Avoid the unnecessary parse-time lookup in the common case
  741. // where the syntax forbids a type.
  742. const Token &Next = NextToken();
  743. // If this identifier was reverted from a token ID, and the next token
  744. // is a parenthesis, this is likely to be a use of a type trait. Check
  745. // those tokens.
  746. if (Next.is(tok::l_paren) && !getLangOpts().HLSL && // HLSL Change - no type trait support in HLSL
  747. Tok.is(tok::identifier) &&
  748. Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
  749. IdentifierInfo *II = Tok.getIdentifierInfo();
  750. // Build up the mapping of revertible type traits, for future use.
  751. if (RevertibleTypeTraits.empty()) {
  752. #define RTT_JOIN(X,Y) X##Y
  753. #define REVERTIBLE_TYPE_TRAIT(Name) \
  754. RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
  755. = RTT_JOIN(tok::kw_,Name)
  756. REVERTIBLE_TYPE_TRAIT(__is_abstract);
  757. REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
  758. REVERTIBLE_TYPE_TRAIT(__is_array);
  759. REVERTIBLE_TYPE_TRAIT(__is_base_of);
  760. REVERTIBLE_TYPE_TRAIT(__is_class);
  761. REVERTIBLE_TYPE_TRAIT(__is_complete_type);
  762. REVERTIBLE_TYPE_TRAIT(__is_compound);
  763. REVERTIBLE_TYPE_TRAIT(__is_const);
  764. REVERTIBLE_TYPE_TRAIT(__is_constructible);
  765. REVERTIBLE_TYPE_TRAIT(__is_convertible);
  766. REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
  767. REVERTIBLE_TYPE_TRAIT(__is_destructible);
  768. REVERTIBLE_TYPE_TRAIT(__is_empty);
  769. REVERTIBLE_TYPE_TRAIT(__is_enum);
  770. REVERTIBLE_TYPE_TRAIT(__is_floating_point);
  771. REVERTIBLE_TYPE_TRAIT(__is_final);
  772. REVERTIBLE_TYPE_TRAIT(__is_function);
  773. REVERTIBLE_TYPE_TRAIT(__is_fundamental);
  774. REVERTIBLE_TYPE_TRAIT(__is_integral);
  775. REVERTIBLE_TYPE_TRAIT(__is_interface_class);
  776. REVERTIBLE_TYPE_TRAIT(__is_literal);
  777. REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
  778. REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
  779. REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
  780. REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
  781. REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
  782. REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
  783. REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
  784. REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
  785. REVERTIBLE_TYPE_TRAIT(__is_object);
  786. REVERTIBLE_TYPE_TRAIT(__is_pod);
  787. REVERTIBLE_TYPE_TRAIT(__is_pointer);
  788. REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
  789. REVERTIBLE_TYPE_TRAIT(__is_reference);
  790. REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
  791. REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
  792. REVERTIBLE_TYPE_TRAIT(__is_same);
  793. REVERTIBLE_TYPE_TRAIT(__is_scalar);
  794. REVERTIBLE_TYPE_TRAIT(__is_sealed);
  795. REVERTIBLE_TYPE_TRAIT(__is_signed);
  796. REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
  797. REVERTIBLE_TYPE_TRAIT(__is_trivial);
  798. REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
  799. REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
  800. REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
  801. REVERTIBLE_TYPE_TRAIT(__is_union);
  802. REVERTIBLE_TYPE_TRAIT(__is_unsigned);
  803. REVERTIBLE_TYPE_TRAIT(__is_void);
  804. REVERTIBLE_TYPE_TRAIT(__is_volatile);
  805. #undef REVERTIBLE_TYPE_TRAIT
  806. #undef RTT_JOIN
  807. }
  808. // If we find that this is in fact the name of a type trait,
  809. // update the token kind in place and parse again to treat it as
  810. // the appropriate kind of type trait.
  811. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
  812. = RevertibleTypeTraits.find(II);
  813. if (Known != RevertibleTypeTraits.end()) {
  814. Tok.setKind(Known->second);
  815. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  816. NotCastExpr, isTypeCast);
  817. }
  818. }
  819. if ((!ColonIsSacred && Next.is(tok::colon)) ||
  820. Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
  821. tok::l_brace)) {
  822. // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
  823. if (TryAnnotateTypeOrScopeToken())
  824. return ExprError();
  825. if (!Tok.is(tok::identifier))
  826. return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
  827. }
  828. }
  829. // Consume the identifier so that we can see if it is followed by a '(' or
  830. // '.'.
  831. IdentifierInfo &II = *Tok.getIdentifierInfo();
  832. SourceLocation ILoc = ConsumeToken();
  833. // Support 'Class.property' and 'super.property' notation.
  834. if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
  835. (Actions.getTypeName(II, ILoc, getCurScope()) ||
  836. // Allow the base to be 'super' if in an objc-method.
  837. (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
  838. ConsumeToken();
  839. // Allow either an identifier or the keyword 'class' (in C++).
  840. if (Tok.isNot(tok::identifier) &&
  841. !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
  842. Diag(Tok, diag::err_expected_property_name);
  843. return ExprError();
  844. }
  845. IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
  846. SourceLocation PropertyLoc = ConsumeToken();
  847. Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
  848. ILoc, PropertyLoc);
  849. break;
  850. }
  851. // In an Objective-C method, if we have "super" followed by an identifier,
  852. // the token sequence is ill-formed. However, if there's a ':' or ']' after
  853. // that identifier, this is probably a message send with a missing open
  854. // bracket. Treat it as such.
  855. if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
  856. getCurScope()->isInObjcMethodScope() &&
  857. ((Tok.is(tok::identifier) &&
  858. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
  859. Tok.is(tok::code_completion))) {
  860. Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
  861. nullptr);
  862. break;
  863. }
  864. // If we have an Objective-C class name followed by an identifier
  865. // and either ':' or ']', this is an Objective-C class message
  866. // send that's missing the opening '['. Recovery
  867. // appropriately. Also take this path if we're performing code
  868. // completion after an Objective-C class name.
  869. if (getLangOpts().ObjC1 &&
  870. ((Tok.is(tok::identifier) && !InMessageExpression) ||
  871. Tok.is(tok::code_completion))) {
  872. const Token& Next = NextToken();
  873. if (Tok.is(tok::code_completion) ||
  874. Next.is(tok::colon) || Next.is(tok::r_square))
  875. if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
  876. if (Typ.get()->isObjCObjectOrInterfaceType()) {
  877. // Fake up a Declarator to use with ActOnTypeName.
  878. DeclSpec DS(AttrFactory);
  879. DS.SetRangeStart(ILoc);
  880. DS.SetRangeEnd(ILoc);
  881. const char *PrevSpec = nullptr;
  882. unsigned DiagID;
  883. DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
  884. Actions.getASTContext().getPrintingPolicy());
  885. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  886. TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
  887. DeclaratorInfo);
  888. if (Ty.isInvalid())
  889. break;
  890. Res = ParseObjCMessageExpressionBody(SourceLocation(),
  891. SourceLocation(),
  892. Ty.get(), nullptr);
  893. break;
  894. }
  895. }
  896. // Make sure to pass down the right value for isAddressOfOperand.
  897. if (isAddressOfOperand && isPostfixExpressionSuffixStart())
  898. isAddressOfOperand = false;
  899. // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
  900. // need to know whether or not this identifier is a function designator or
  901. // not.
  902. UnqualifiedId Name;
  903. CXXScopeSpec ScopeSpec;
  904. SourceLocation TemplateKWLoc;
  905. Token Replacement;
  906. auto Validator = llvm::make_unique<CastExpressionIdValidator>(
  907. Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
  908. Validator->IsAddressOfOperand = isAddressOfOperand;
  909. if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
  910. Validator->WantExpressionKeywords = false;
  911. Validator->WantRemainingKeywords = false;
  912. } else {
  913. Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
  914. }
  915. Name.setIdentifier(&II, ILoc);
  916. Res = Actions.ActOnIdExpression(
  917. getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
  918. isAddressOfOperand, std::move(Validator),
  919. /*IsInlineAsmIdentifier=*/false,
  920. Tok.is(tok::r_paren) ? nullptr : &Replacement);
  921. if (!Res.isInvalid() && !Res.get()) {
  922. UnconsumeToken(Replacement);
  923. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  924. NotCastExpr, isTypeCast);
  925. }
  926. break;
  927. }
  928. case tok::char_constant: // constant: character-constant
  929. case tok::wide_char_constant:
  930. case tok::utf8_char_constant:
  931. case tok::utf16_char_constant:
  932. case tok::utf32_char_constant:
  933. // HLSL Change Starts
  934. // Character constants become 32-bit unsigned ints. That will happen in Sema.
  935. if (getLangOpts().HLSL && Tok.getKind() != tok::char_constant) {
  936. Diag(Tok, diag::err_hlsl_unsupported_construct) << "non-ASCII/multiple-char character constant";
  937. return ExprError();
  938. }
  939. // HLSL Change Ends
  940. Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
  941. ConsumeToken();
  942. break;
  943. case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
  944. case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
  945. case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
  946. case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
  947. case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
  948. case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
  949. // HLSL Change Starts
  950. if (getLangOpts().HLSL) {
  951. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  952. return ExprError();
  953. }
  954. // HLSL Change Ends
  955. Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
  956. ConsumeToken();
  957. break;
  958. case tok::string_literal: // primary-expression: string-literal
  959. case tok::wide_string_literal:
  960. case tok::utf8_string_literal:
  961. case tok::utf16_string_literal:
  962. case tok::utf32_string_literal:
  963. // HLSL Change Starts
  964. if (getLangOpts().HLSL && Tok.getKind() != tok::string_literal) {
  965. Diag(Tok, diag::err_hlsl_unsupported_construct) << "non-ASCII string constant";
  966. return ExprError();
  967. }
  968. // HLSL Change Ends
  969. Res = ParseStringLiteralExpression(true);
  970. break;
  971. case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
  972. // HLSL Change Starts
  973. if (getLangOpts().HLSL) {
  974. Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName();
  975. return ExprError();
  976. }
  977. // HLSL Change Ends
  978. Res = ParseGenericSelectionExpression();
  979. break;
  980. case tok::kw___builtin_va_arg:
  981. case tok::kw___builtin_offsetof:
  982. case tok::kw___builtin_choose_expr:
  983. case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
  984. case tok::kw___builtin_convertvector:
  985. if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported
  986. return ParseBuiltinPrimaryExpression();
  987. case tok::kw___null:
  988. if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported
  989. return Actions.ActOnGNUNullExpr(ConsumeToken());
  990. case tok::plusplus: // unary-expression: '++' unary-expression [C99]
  991. case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
  992. // C++ [expr.unary] has:
  993. // unary-expression:
  994. // ++ cast-expression
  995. // -- cast-expression
  996. SourceLocation SavedLoc = ConsumeToken();
  997. // One special case is implicitly handled here: if the preceding tokens are
  998. // an ambiguous cast expression, such as "(T())++", then we recurse to
  999. // determine whether the '++' is prefix or postfix.
  1000. Res = ParseCastExpression(!getLangOpts().CPlusPlus,
  1001. /*isAddressOfOperand*/false, NotCastExpr,
  1002. NotTypeCast);
  1003. if (!Res.isInvalid())
  1004. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  1005. return Res;
  1006. }
  1007. case tok::amp: { // unary-expression: '&' cast-expression
  1008. // Special treatment because of member pointers
  1009. SourceLocation SavedLoc = ConsumeToken();
  1010. Res = ParseCastExpression(false, true);
  1011. if (!Res.isInvalid())
  1012. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  1013. return Res;
  1014. }
  1015. case tok::star: // unary-expression: '*' cast-expression
  1016. case tok::plus: // unary-expression: '+' cast-expression
  1017. case tok::minus: // unary-expression: '-' cast-expression
  1018. case tok::tilde: // unary-expression: '~' cast-expression
  1019. case tok::exclaim: // unary-expression: '!' cast-expression
  1020. case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
  1021. case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
  1022. // HLSL Change Starts
  1023. if (getLangOpts().HLSL && Tok.getKind() == tok::kw___real || Tok.getKind() == tok::kw___imag) {
  1024. goto HLSLReservedKeyword;
  1025. }
  1026. // HLSL Change Ends
  1027. SourceLocation SavedLoc = ConsumeToken();
  1028. Res = ParseCastExpression(false);
  1029. if (!Res.isInvalid())
  1030. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  1031. return Res;
  1032. }
  1033. case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
  1034. // __extension__ silences extension warnings in the subexpression.
  1035. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  1036. SourceLocation SavedLoc = ConsumeToken();
  1037. Res = ParseCastExpression(false);
  1038. if (!Res.isInvalid())
  1039. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  1040. return Res;
  1041. }
  1042. case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
  1043. if (!getLangOpts().C11)
  1044. Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
  1045. // fallthrough
  1046. case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
  1047. case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
  1048. // unary-expression: '__alignof' '(' type-name ')'
  1049. case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
  1050. // unary-expression: 'sizeof' '(' type-name ')'
  1051. case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
  1052. // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
  1053. case tok::kw___builtin_omp_required_simd_align:
  1054. if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported
  1055. return ParseUnaryExprOrTypeTraitExpression();
  1056. case tok::ampamp: { // unary-expression: '&&' identifier
  1057. // HLSL Change Starts
  1058. if (getLangOpts().HLSL) {
  1059. Diag(Tok, diag::err_hlsl_unsupported_construct) << "address of label";
  1060. return ExprError();
  1061. }
  1062. // HLSL Change Ends
  1063. SourceLocation AmpAmpLoc = ConsumeToken();
  1064. if (Tok.isNot(tok::identifier))
  1065. return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
  1066. if (getCurScope()->getFnParent() == nullptr)
  1067. return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
  1068. Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
  1069. LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
  1070. Tok.getLocation());
  1071. Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
  1072. ConsumeToken();
  1073. return Res;
  1074. }
  1075. case tok::kw_const_cast:
  1076. case tok::kw_dynamic_cast:
  1077. case tok::kw_reinterpret_cast:
  1078. case tok::kw_static_cast:
  1079. // HLSL Change Starts
  1080. if (getLangOpts().HLSL) {
  1081. Diag(Tok, diag::err_hlsl_unsupported_construct) << "C++-style cast";
  1082. return ExprError();
  1083. }
  1084. // HLSL Change Ends
  1085. Res = ParseCXXCasts();
  1086. break;
  1087. case tok::kw_typeid:
  1088. if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported
  1089. Res = ParseCXXTypeid();
  1090. break;
  1091. case tok::kw___uuidof:
  1092. // HLSL Change Starts
  1093. assert(!getLangOpts().HLSL && "__uuidof is not a keyword in HLSL");
  1094. if (getLangOpts().HLSL) goto tok_default_case;
  1095. // HLSL Change Ends
  1096. Res = ParseCXXUuidof();
  1097. break;
  1098. case tok::kw_this:
  1099. Res = ParseCXXThis();
  1100. break;
  1101. case tok::annot_typename:
  1102. if (isStartOfObjCClassMessageMissingOpenBracket()) {
  1103. ParsedType Type = getTypeAnnotation(Tok);
  1104. // Fake up a Declarator to use with ActOnTypeName.
  1105. DeclSpec DS(AttrFactory);
  1106. DS.SetRangeStart(Tok.getLocation());
  1107. DS.SetRangeEnd(Tok.getLastLoc());
  1108. const char *PrevSpec = nullptr;
  1109. unsigned DiagID;
  1110. DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
  1111. PrevSpec, DiagID, Type,
  1112. Actions.getASTContext().getPrintingPolicy());
  1113. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  1114. TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  1115. if (Ty.isInvalid())
  1116. break;
  1117. ConsumeToken();
  1118. Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
  1119. Ty.get(), nullptr);
  1120. break;
  1121. }
  1122. // Fall through
  1123. case tok::annot_decltype:
  1124. case tok::kw_char:
  1125. case tok::kw_wchar_t:
  1126. case tok::kw_char16_t:
  1127. case tok::kw_char32_t:
  1128. case tok::kw_bool:
  1129. case tok::kw_short:
  1130. case tok::kw_int:
  1131. case tok::kw_long:
  1132. case tok::kw___int64:
  1133. case tok::kw___int128:
  1134. // HLSL Change Starts
  1135. case tok::kw_column_major:
  1136. case tok::kw_row_major:
  1137. case tok::kw_snorm:
  1138. case tok::kw_unorm:
  1139. // HLSL Change Ends
  1140. case tok::kw_signed:
  1141. case tok::kw_unsigned:
  1142. case tok::kw_half:
  1143. case tok::kw_float:
  1144. case tok::kw_double:
  1145. case tok::kw_void:
  1146. case tok::kw_typename:
  1147. case tok::kw_typeof:
  1148. case tok::kw___vector: {
  1149. // HLSL Change Starts
  1150. if (getLangOpts().HLSL && (
  1151. SavedKind == tok::kw_wchar_t || SavedKind == tok::kw_char || SavedKind == tok::kw_char16_t || SavedKind == tok::kw_char32_t ||
  1152. SavedKind == tok::kw_short || SavedKind == tok::kw_long || SavedKind == tok::kw___int64 || SavedKind == tok::kw___int128 ||
  1153. SavedKind == tok::kw_typename || SavedKind == tok::kw_typeof)) {
  1154. // the vector/image/sampler/event keywords aren't returned by the lexer for HLSL
  1155. goto HLSLReservedKeyword;
  1156. }
  1157. // HLSL Change Ends
  1158. if (!getLangOpts().CPlusPlus) {
  1159. Diag(Tok, diag::err_expected_expression);
  1160. return ExprError();
  1161. }
  1162. if (SavedKind == tok::kw_typename) {
  1163. // postfix-expression: typename-specifier '(' expression-list[opt] ')'
  1164. // typename-specifier braced-init-list
  1165. if (TryAnnotateTypeOrScopeToken())
  1166. return ExprError();
  1167. if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
  1168. // We are trying to parse a simple-type-specifier but might not get such
  1169. // a token after error recovery.
  1170. return ExprError();
  1171. }
  1172. // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
  1173. // simple-type-specifier braced-init-list
  1174. //
  1175. DeclSpec DS(AttrFactory);
  1176. ParseCXXSimpleTypeSpecifier(DS);
  1177. if (Tok.isNot(tok::l_paren) &&
  1178. (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
  1179. return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
  1180. << DS.getSourceRange());
  1181. if (Tok.is(tok::l_brace))
  1182. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  1183. Res = ParseCXXTypeConstructExpression(DS);
  1184. break;
  1185. }
  1186. case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
  1187. // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
  1188. // (We can end up in this situation after tentative parsing.)
  1189. if (TryAnnotateTypeOrScopeToken())
  1190. return ExprError();
  1191. if (!Tok.is(tok::annot_cxxscope))
  1192. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  1193. NotCastExpr, isTypeCast);
  1194. Token Next = NextToken();
  1195. if (Next.is(tok::annot_template_id)) {
  1196. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
  1197. if (TemplateId->Kind == TNK_Type_template) {
  1198. // We have a qualified template-id that we know refers to a
  1199. // type, translate it into a type and continue parsing as a
  1200. // cast expression.
  1201. CXXScopeSpec SS;
  1202. ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  1203. /*EnteringContext=*/false);
  1204. AnnotateTemplateIdTokenAsType();
  1205. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  1206. NotCastExpr, isTypeCast);
  1207. }
  1208. }
  1209. // Parse as an id-expression.
  1210. Res = ParseCXXIdExpression(isAddressOfOperand);
  1211. break;
  1212. }
  1213. case tok::annot_template_id: { // [C++] template-id
  1214. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  1215. if (TemplateId->Kind == TNK_Type_template) {
  1216. // We have a template-id that we know refers to a type,
  1217. // translate it into a type and continue parsing as a cast
  1218. // expression.
  1219. AnnotateTemplateIdTokenAsType();
  1220. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  1221. NotCastExpr, isTypeCast);
  1222. }
  1223. // Fall through to treat the template-id as an id-expression.
  1224. }
  1225. case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
  1226. if (getLangOpts().HLSL && SavedKind == tok::kw_operator) goto HLSLReservedKeyword; // HLSL Change - 'operator' is reserved
  1227. Res = ParseCXXIdExpression(isAddressOfOperand);
  1228. break;
  1229. case tok::coloncolon: {
  1230. // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
  1231. // annotates the token, tail recurse.
  1232. if (TryAnnotateTypeOrScopeToken())
  1233. return ExprError();
  1234. if (!Tok.is(tok::coloncolon))
  1235. return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
  1236. // ::new -> [C++] new-expression
  1237. // ::delete -> [C++] delete-expression
  1238. SourceLocation CCLoc = ConsumeToken();
  1239. if (Tok.is(tok::kw_new)) {
  1240. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'new' is reserved
  1241. return ParseCXXNewExpression(true, CCLoc);
  1242. }
  1243. if (Tok.is(tok::kw_delete)) {
  1244. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'delete' is reserved
  1245. return ParseCXXDeleteExpression(true, CCLoc);
  1246. }
  1247. // This is not a type name or scope specifier, it is an invalid expression.
  1248. Diag(CCLoc, diag::err_expected_expression);
  1249. return ExprError();
  1250. }
  1251. case tok::kw_new: // [C++] new-expression
  1252. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'new' is reserved
  1253. return ParseCXXNewExpression(false, Tok.getLocation());
  1254. case tok::kw_delete: // [C++] delete-expression
  1255. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'delete' is reserved
  1256. return ParseCXXDeleteExpression(false, Tok.getLocation());
  1257. case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
  1258. if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - reserved keyword
  1259. Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
  1260. SourceLocation KeyLoc = ConsumeToken();
  1261. BalancedDelimiterTracker T(*this, tok::l_paren);
  1262. if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
  1263. return ExprError();
  1264. // C++11 [expr.unary.noexcept]p1:
  1265. // The noexcept operator determines whether the evaluation of its operand,
  1266. // which is an unevaluated operand, can throw an exception.
  1267. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  1268. ExprResult Result = ParseExpression();
  1269. T.consumeClose();
  1270. if (!Result.isInvalid())
  1271. Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
  1272. Result.get(), T.getCloseLocation());
  1273. return Result;
  1274. }
  1275. #define TYPE_TRAIT(N,Spelling,K) \
  1276. case tok::kw_##Spelling:
  1277. #include "clang/Basic/TokenKinds.def"
  1278. return ParseTypeTrait();
  1279. case tok::kw___array_rank:
  1280. case tok::kw___array_extent:
  1281. return ParseArrayTypeTrait();
  1282. case tok::kw___is_lvalue_expr:
  1283. case tok::kw___is_rvalue_expr:
  1284. return ParseExpressionTrait();
  1285. case tok::at: {
  1286. // HLSL Change Starts
  1287. assert(!getLangOpts().HLSL && "HLSL does not recognize '@' as a token");
  1288. if (getLangOpts().HLSL) goto tok_default_case;
  1289. // HLSL Change Ends
  1290. SourceLocation AtLoc = ConsumeToken();
  1291. return ParseObjCAtExpression(AtLoc);
  1292. }
  1293. case tok::caret:
  1294. // HLSL Change Starts
  1295. if (getLangOpts().HLSL) {
  1296. Diag(Tok, diag::err_hlsl_unsupported_construct) << "block";
  1297. return ExprError();
  1298. }
  1299. // HLSL Change Ends
  1300. Res = ParseBlockLiteralExpression();
  1301. break;
  1302. case tok::code_completion: {
  1303. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
  1304. cutOffParsing();
  1305. return ExprError();
  1306. }
  1307. case tok::l_square:
  1308. if (getLangOpts().CPlusPlus11) {
  1309. if (getLangOpts().ObjC1) {
  1310. // C++11 lambda expressions and Objective-C message sends both start with a
  1311. // square bracket. There are three possibilities here:
  1312. // we have a valid lambda expression, we have an invalid lambda
  1313. // expression, or we have something that doesn't appear to be a lambda.
  1314. // If we're in the last case, we fall back to ParseObjCMessageExpression.
  1315. Res = TryParseLambdaExpression();
  1316. if (!Res.isInvalid() && !Res.get())
  1317. Res = ParseObjCMessageExpression();
  1318. break;
  1319. }
  1320. Res = ParseLambdaExpression();
  1321. break;
  1322. }
  1323. if (getLangOpts().ObjC1) {
  1324. Res = ParseObjCMessageExpression();
  1325. break;
  1326. }
  1327. // FALL THROUGH.
  1328. tok_default_case: // HLSL Change - add to target cases dead-code'd by HLSL
  1329. default:
  1330. NotCastExpr = true;
  1331. return ExprError();
  1332. }
  1333. // These can be followed by postfix-expr pieces.
  1334. return ParsePostfixExpressionSuffix(Res);
  1335. }
  1336. /// \brief Once the leading part of a postfix-expression is parsed, this
  1337. /// method parses any suffixes that apply.
  1338. ///
  1339. /// \verbatim
  1340. /// postfix-expression: [C99 6.5.2]
  1341. /// primary-expression
  1342. /// postfix-expression '[' expression ']'
  1343. /// postfix-expression '[' braced-init-list ']'
  1344. /// postfix-expression '(' argument-expression-list[opt] ')'
  1345. /// postfix-expression '.' identifier
  1346. /// postfix-expression '->' identifier
  1347. /// postfix-expression '++'
  1348. /// postfix-expression '--'
  1349. /// '(' type-name ')' '{' initializer-list '}'
  1350. /// '(' type-name ')' '{' initializer-list ',' '}'
  1351. ///
  1352. /// argument-expression-list: [C99 6.5.2]
  1353. /// argument-expression ...[opt]
  1354. /// argument-expression-list ',' assignment-expression ...[opt]
  1355. /// \endverbatim
  1356. ExprResult
  1357. Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
  1358. // Now that the primary-expression piece of the postfix-expression has been
  1359. // parsed, see if there are any postfix-expression pieces here.
  1360. SourceLocation Loc;
  1361. while (1) {
  1362. switch (Tok.getKind()) {
  1363. case tok::code_completion:
  1364. if (InMessageExpression)
  1365. return LHS;
  1366. Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
  1367. cutOffParsing();
  1368. return ExprError();
  1369. case tok::identifier:
  1370. // If we see identifier: after an expression, and we're not already in a
  1371. // message send, then this is probably a message send with a missing
  1372. // opening bracket '['.
  1373. if (getLangOpts().ObjC1 && !InMessageExpression &&
  1374. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
  1375. LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
  1376. ParsedType(), LHS.get());
  1377. break;
  1378. }
  1379. // Fall through; this isn't a message send.
  1380. default: // Not a postfix-expression suffix.
  1381. return LHS;
  1382. case tok::l_square: { // postfix-expression: p-e '[' expression ']'
  1383. // If we have a array postfix expression that starts on a new line and
  1384. // Objective-C is enabled, it is highly likely that the user forgot a
  1385. // semicolon after the base expression and that the array postfix-expr is
  1386. // actually another message send. In this case, do some look-ahead to see
  1387. // if the contents of the square brackets are obviously not a valid
  1388. // expression and recover by pretending there is no suffix.
  1389. if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
  1390. isSimpleObjCMessageExpression())
  1391. return LHS;
  1392. // Reject array indices starting with a lambda-expression. '[[' is
  1393. // reserved for attributes.
  1394. if (CheckProhibitedCXX11Attribute())
  1395. return ExprError();
  1396. BalancedDelimiterTracker T(*this, tok::l_square);
  1397. T.consumeOpen();
  1398. Loc = T.getOpenLocation();
  1399. ExprResult Idx;
  1400. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  1401. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  1402. Idx = ParseBraceInitializer();
  1403. } else
  1404. Idx = ParseExpression();
  1405. SourceLocation RLoc = Tok.getLocation();
  1406. if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
  1407. LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
  1408. Idx.get(), RLoc);
  1409. } else {
  1410. (void)Actions.CorrectDelayedTyposInExpr(LHS);
  1411. (void)Actions.CorrectDelayedTyposInExpr(Idx);
  1412. LHS = ExprError();
  1413. Idx = ExprError();
  1414. }
  1415. // Match the ']'.
  1416. T.consumeClose();
  1417. break;
  1418. }
  1419. case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
  1420. case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
  1421. // '(' argument-expression-list[opt] ')'
  1422. tok::TokenKind OpKind = Tok.getKind();
  1423. InMessageExpressionRAIIObject InMessage(*this, false);
  1424. Expr *ExecConfig = nullptr;
  1425. BalancedDelimiterTracker PT(*this, tok::l_paren);
  1426. if (getLangOpts().HLSL && OpKind == tok::lesslessless) { // HLSL Change: <<< is not supported in HLSL
  1427. ExprVector ExecConfigExprs;
  1428. CommaLocsTy ExecConfigCommaLocs;
  1429. SourceLocation OpenLoc = ConsumeToken();
  1430. if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
  1431. (void)Actions.CorrectDelayedTyposInExpr(LHS);
  1432. LHS = ExprError();
  1433. }
  1434. SourceLocation CloseLoc;
  1435. if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
  1436. } else if (LHS.isInvalid()) {
  1437. SkipUntil(tok::greatergreatergreater, StopAtSemi);
  1438. } else {
  1439. // There was an error closing the brackets
  1440. Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
  1441. Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
  1442. SkipUntil(tok::greatergreatergreater, StopAtSemi);
  1443. LHS = ExprError();
  1444. }
  1445. if (!LHS.isInvalid()) {
  1446. if (ExpectAndConsume(tok::l_paren))
  1447. LHS = ExprError();
  1448. else
  1449. Loc = PrevTokLocation;
  1450. }
  1451. if (!LHS.isInvalid()) {
  1452. ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
  1453. OpenLoc,
  1454. ExecConfigExprs,
  1455. CloseLoc);
  1456. if (ECResult.isInvalid())
  1457. LHS = ExprError();
  1458. else
  1459. ExecConfig = ECResult.get();
  1460. }
  1461. } else {
  1462. PT.consumeOpen();
  1463. Loc = PT.getOpenLocation();
  1464. }
  1465. ExprVector ArgExprs;
  1466. CommaLocsTy CommaLocs;
  1467. if (Tok.is(tok::code_completion)) {
  1468. Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
  1469. cutOffParsing();
  1470. return ExprError();
  1471. }
  1472. if (OpKind == tok::l_paren || !LHS.isInvalid()) {
  1473. if (Tok.isNot(tok::r_paren)) {
  1474. if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
  1475. Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
  1476. })) {
  1477. (void)Actions.CorrectDelayedTyposInExpr(LHS);
  1478. LHS = ExprError();
  1479. } else if (LHS.isInvalid()) {
  1480. for (auto &E : ArgExprs)
  1481. Actions.CorrectDelayedTyposInExpr(E);
  1482. }
  1483. }
  1484. }
  1485. // Match the ')'.
  1486. if (LHS.isInvalid()) {
  1487. SkipUntil(tok::r_paren, StopAtSemi);
  1488. } else if (Tok.isNot(tok::r_paren)) {
  1489. bool HadDelayedTypo = false;
  1490. if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
  1491. HadDelayedTypo = true;
  1492. for (auto &E : ArgExprs)
  1493. if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
  1494. HadDelayedTypo = true;
  1495. // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
  1496. // instead of PT.consumeClose() to avoid emitting extra diagnostics for
  1497. // the unmatched l_paren.
  1498. if (HadDelayedTypo)
  1499. SkipUntil(tok::r_paren, StopAtSemi);
  1500. else
  1501. PT.consumeClose();
  1502. LHS = ExprError();
  1503. } else {
  1504. assert((ArgExprs.size() == 0 ||
  1505. ArgExprs.size()-1 == CommaLocs.size())&&
  1506. "Unexpected number of commas!");
  1507. LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
  1508. ArgExprs, Tok.getLocation(),
  1509. ExecConfig);
  1510. PT.consumeClose();
  1511. }
  1512. break;
  1513. }
  1514. case tok::arrow:
  1515. case tok::period: {
  1516. // postfix-expression: p-e '->' template[opt] id-expression
  1517. // postfix-expression: p-e '.' template[opt] id-expression
  1518. tok::TokenKind OpKind = Tok.getKind();
  1519. SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
  1520. CXXScopeSpec SS;
  1521. ParsedType ObjectType;
  1522. bool MayBePseudoDestructor = false;
  1523. if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
  1524. Expr *Base = LHS.get();
  1525. const Type* BaseType = Base->getType().getTypePtrOrNull();
  1526. if (BaseType && Tok.is(tok::l_paren) &&
  1527. (BaseType->isFunctionType() ||
  1528. BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
  1529. Diag(OpLoc, diag::err_function_is_not_record)
  1530. << OpKind << Base->getSourceRange()
  1531. << FixItHint::CreateRemoval(OpLoc);
  1532. return ParsePostfixExpressionSuffix(Base);
  1533. }
  1534. LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
  1535. OpLoc, OpKind, ObjectType,
  1536. MayBePseudoDestructor);
  1537. if (LHS.isInvalid())
  1538. break;
  1539. ParseOptionalCXXScopeSpecifier(SS, ObjectType,
  1540. /*EnteringContext=*/false,
  1541. &MayBePseudoDestructor);
  1542. if (SS.isNotEmpty())
  1543. ObjectType = ParsedType();
  1544. }
  1545. // HLSL Change Starts
  1546. // At this point, if we have an arrow, a diagnostic has been emitted, and
  1547. // we recover parsing by treating this as a period.
  1548. if (getLangOpts().HLSL) {
  1549. OpKind = tok::period;
  1550. }
  1551. // HLSL Change Ends
  1552. if (Tok.is(tok::code_completion)) {
  1553. // Code completion for a member access expression.
  1554. Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
  1555. OpLoc, OpKind == tok::arrow);
  1556. cutOffParsing();
  1557. return ExprError();
  1558. }
  1559. if (MayBePseudoDestructor && !LHS.isInvalid()) {
  1560. LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
  1561. ObjectType);
  1562. break;
  1563. }
  1564. // HLSL Change Starts
  1565. // 'sample' is a keyword when used as an interpolation modifier, but it is
  1566. // also a built-in field of some types. By the time we're considering a
  1567. // field access, update the token if necessary to reflect this.
  1568. if (getLangOpts().HLSL) {
  1569. if (Tok.is(tok::kw_sample)) {
  1570. Tok.setKind(tok::identifier);
  1571. Tok.setIdentifierInfo(PP.getIdentifierInfo(StringRef("sample")));
  1572. }
  1573. }
  1574. // HLSL Change Ends
  1575. // Either the action has told us that this cannot be a
  1576. // pseudo-destructor expression (based on the type of base
  1577. // expression), or we didn't see a '~' in the right place. We
  1578. // can still parse a destructor name here, but in that case it
  1579. // names a real destructor.
  1580. // Allow explicit constructor calls in Microsoft mode.
  1581. // FIXME: Add support for explicit call of template constructor.
  1582. SourceLocation TemplateKWLoc;
  1583. UnqualifiedId Name;
  1584. if (getLangOpts().ObjC2 && OpKind == tok::period &&
  1585. Tok.is(tok::kw_class)) {
  1586. // Objective-C++:
  1587. // After a '.' in a member access expression, treat the keyword
  1588. // 'class' as if it were an identifier.
  1589. //
  1590. // This hack allows property access to the 'class' method because it is
  1591. // such a common method name. For other C++ keywords that are
  1592. // Objective-C method names, one must use the message send syntax.
  1593. IdentifierInfo *Id = Tok.getIdentifierInfo();
  1594. SourceLocation Loc = ConsumeToken();
  1595. Name.setIdentifier(Id, Loc);
  1596. } else if (ParseUnqualifiedId(SS,
  1597. /*EnteringContext=*/false,
  1598. /*AllowDestructorName=*/true,
  1599. /*AllowConstructorName=*/
  1600. getLangOpts().MicrosoftExt,
  1601. ObjectType, TemplateKWLoc, Name)) {
  1602. (void)Actions.CorrectDelayedTyposInExpr(LHS);
  1603. LHS = ExprError();
  1604. }
  1605. if (!LHS.isInvalid())
  1606. LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
  1607. OpKind, SS, TemplateKWLoc, Name,
  1608. CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
  1609. : nullptr);
  1610. break;
  1611. }
  1612. case tok::plusplus: // postfix-expression: postfix-expression '++'
  1613. case tok::minusminus: // postfix-expression: postfix-expression '--'
  1614. if (!LHS.isInvalid()) {
  1615. LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
  1616. Tok.getKind(), LHS.get());
  1617. }
  1618. ConsumeToken();
  1619. break;
  1620. }
  1621. }
  1622. }
  1623. /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
  1624. /// vec_step and we are at the start of an expression or a parenthesized
  1625. /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
  1626. /// expression (isCastExpr == false) or the type (isCastExpr == true).
  1627. ///
  1628. /// \verbatim
  1629. /// unary-expression: [C99 6.5.3]
  1630. /// 'sizeof' unary-expression
  1631. /// 'sizeof' '(' type-name ')'
  1632. /// [GNU] '__alignof' unary-expression
  1633. /// [GNU] '__alignof' '(' type-name ')'
  1634. /// [C11] '_Alignof' '(' type-name ')'
  1635. /// [C++0x] 'alignof' '(' type-id ')'
  1636. ///
  1637. /// [GNU] typeof-specifier:
  1638. /// typeof ( expressions )
  1639. /// typeof ( type-name )
  1640. /// [GNU/C++] typeof unary-expression
  1641. ///
  1642. /// [OpenCL 1.1 6.11.12] vec_step built-in function:
  1643. /// vec_step ( expressions )
  1644. /// vec_step ( type-name )
  1645. /// \endverbatim
  1646. ExprResult
  1647. Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
  1648. bool &isCastExpr,
  1649. ParsedType &CastTy,
  1650. SourceRange &CastRange) {
  1651. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  1652. assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
  1653. tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
  1654. tok::kw___builtin_omp_required_simd_align) &&
  1655. "Not a typeof/sizeof/alignof/vec_step expression!");
  1656. ExprResult Operand;
  1657. // If the operand doesn't start with an '(', it must be an expression.
  1658. if (Tok.isNot(tok::l_paren)) {
  1659. // If construct allows a form without parenthesis, user may forget to put
  1660. // pathenthesis around type name.
  1661. if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
  1662. tok::kw__Alignof)) {
  1663. if (isTypeIdUnambiguously()) {
  1664. DeclSpec DS(AttrFactory);
  1665. ParseSpecifierQualifierList(DS);
  1666. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  1667. ParseDeclarator(DeclaratorInfo);
  1668. SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
  1669. SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
  1670. Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
  1671. << OpTok.getName()
  1672. << FixItHint::CreateInsertion(LParenLoc, "(")
  1673. << FixItHint::CreateInsertion(RParenLoc, ")");
  1674. isCastExpr = true;
  1675. return ExprEmpty();
  1676. }
  1677. }
  1678. isCastExpr = false;
  1679. if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
  1680. Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
  1681. << tok::l_paren;
  1682. return ExprError();
  1683. }
  1684. Operand = ParseCastExpression(true/*isUnaryExpression*/);
  1685. } else {
  1686. // If it starts with a '(', we know that it is either a parenthesized
  1687. // type-name, or it is a unary-expression that starts with a compound
  1688. // literal, or starts with a primary-expression that is a parenthesized
  1689. // expression.
  1690. ParenParseOption ExprType = CastExpr;
  1691. SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
  1692. Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
  1693. false, CastTy, RParenLoc);
  1694. CastRange = SourceRange(LParenLoc, RParenLoc);
  1695. // If ParseParenExpression parsed a '(typename)' sequence only, then this is
  1696. // a type.
  1697. if (ExprType == CastExpr) {
  1698. isCastExpr = true;
  1699. return ExprEmpty();
  1700. }
  1701. if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
  1702. // GNU typeof in C requires the expression to be parenthesized. Not so for
  1703. // sizeof/alignof or in C++. Therefore, the parenthesized expression is
  1704. // the start of a unary-expression, but doesn't include any postfix
  1705. // pieces. Parse these now if present.
  1706. if (!Operand.isInvalid())
  1707. Operand = ParsePostfixExpressionSuffix(Operand.get());
  1708. }
  1709. }
  1710. // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
  1711. isCastExpr = false;
  1712. return Operand;
  1713. }
  1714. /// \brief Parse a sizeof or alignof expression.
  1715. ///
  1716. /// \verbatim
  1717. /// unary-expression: [C99 6.5.3]
  1718. /// 'sizeof' unary-expression
  1719. /// 'sizeof' '(' type-name ')'
  1720. /// [C++11] 'sizeof' '...' '(' identifier ')'
  1721. /// [GNU] '__alignof' unary-expression
  1722. /// [GNU] '__alignof' '(' type-name ')'
  1723. /// [C11] '_Alignof' '(' type-name ')'
  1724. /// [C++11] 'alignof' '(' type-id ')'
  1725. /// \endverbatim
  1726. ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
  1727. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  1728. assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
  1729. tok::kw__Alignof, tok::kw_vec_step,
  1730. tok::kw___builtin_omp_required_simd_align) &&
  1731. "Not a sizeof/alignof/vec_step expression!");
  1732. Token OpTok = Tok;
  1733. ConsumeToken();
  1734. // [C++11] 'sizeof' '...' '(' identifier ')'
  1735. if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
  1736. SourceLocation EllipsisLoc = ConsumeToken();
  1737. SourceLocation LParenLoc, RParenLoc;
  1738. IdentifierInfo *Name = nullptr;
  1739. SourceLocation NameLoc;
  1740. if (Tok.is(tok::l_paren)) {
  1741. BalancedDelimiterTracker T(*this, tok::l_paren);
  1742. T.consumeOpen();
  1743. LParenLoc = T.getOpenLocation();
  1744. if (Tok.is(tok::identifier)) {
  1745. Name = Tok.getIdentifierInfo();
  1746. NameLoc = ConsumeToken();
  1747. T.consumeClose();
  1748. RParenLoc = T.getCloseLocation();
  1749. if (RParenLoc.isInvalid())
  1750. RParenLoc = PP.getLocForEndOfToken(NameLoc);
  1751. } else {
  1752. Diag(Tok, diag::err_expected_parameter_pack);
  1753. SkipUntil(tok::r_paren, StopAtSemi);
  1754. }
  1755. } else if (Tok.is(tok::identifier)) {
  1756. Name = Tok.getIdentifierInfo();
  1757. NameLoc = ConsumeToken();
  1758. LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
  1759. RParenLoc = PP.getLocForEndOfToken(NameLoc);
  1760. Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
  1761. << Name
  1762. << FixItHint::CreateInsertion(LParenLoc, "(")
  1763. << FixItHint::CreateInsertion(RParenLoc, ")");
  1764. } else {
  1765. Diag(Tok, diag::err_sizeof_parameter_pack);
  1766. }
  1767. if (!Name)
  1768. return ExprError();
  1769. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
  1770. Sema::ReuseLambdaContextDecl);
  1771. return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
  1772. OpTok.getLocation(),
  1773. *Name, NameLoc,
  1774. RParenLoc);
  1775. }
  1776. if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
  1777. Diag(OpTok, diag::warn_cxx98_compat_alignof);
  1778. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
  1779. Sema::ReuseLambdaContextDecl);
  1780. bool isCastExpr;
  1781. ParsedType CastTy;
  1782. SourceRange CastRange;
  1783. ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
  1784. isCastExpr,
  1785. CastTy,
  1786. CastRange);
  1787. UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
  1788. if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
  1789. ExprKind = UETT_AlignOf;
  1790. else if (OpTok.is(tok::kw_vec_step))
  1791. ExprKind = UETT_VecStep;
  1792. else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
  1793. ExprKind = UETT_OpenMPRequiredSimdAlign;
  1794. if (isCastExpr)
  1795. return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
  1796. ExprKind,
  1797. /*isType=*/true,
  1798. CastTy.getAsOpaquePtr(),
  1799. CastRange);
  1800. if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
  1801. Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
  1802. // If we get here, the operand to the sizeof/alignof was an expresion.
  1803. if (!Operand.isInvalid())
  1804. Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
  1805. ExprKind,
  1806. /*isType=*/false,
  1807. Operand.get(),
  1808. CastRange);
  1809. return Operand;
  1810. }
  1811. /// ParseBuiltinPrimaryExpression
  1812. ///
  1813. /// \verbatim
  1814. /// primary-expression: [C99 6.5.1]
  1815. /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
  1816. /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
  1817. /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
  1818. /// assign-expr ')'
  1819. /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
  1820. /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
  1821. ///
  1822. /// [GNU] offsetof-member-designator:
  1823. /// [GNU] identifier
  1824. /// [GNU] offsetof-member-designator '.' identifier
  1825. /// [GNU] offsetof-member-designator '[' expression ']'
  1826. /// \endverbatim
  1827. ExprResult Parser::ParseBuiltinPrimaryExpression() {
  1828. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  1829. ExprResult Res;
  1830. const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
  1831. tok::TokenKind T = Tok.getKind();
  1832. SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
  1833. // All of these start with an open paren.
  1834. if (Tok.isNot(tok::l_paren))
  1835. return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
  1836. << tok::l_paren);
  1837. BalancedDelimiterTracker PT(*this, tok::l_paren);
  1838. PT.consumeOpen();
  1839. // TODO: Build AST.
  1840. switch (T) {
  1841. default: llvm_unreachable("Not a builtin primary expression!");
  1842. case tok::kw___builtin_va_arg: {
  1843. ExprResult Expr(ParseAssignmentExpression());
  1844. if (ExpectAndConsume(tok::comma)) {
  1845. SkipUntil(tok::r_paren, StopAtSemi);
  1846. Expr = ExprError();
  1847. }
  1848. TypeResult Ty = ParseTypeName();
  1849. if (Tok.isNot(tok::r_paren)) {
  1850. Diag(Tok, diag::err_expected) << tok::r_paren;
  1851. Expr = ExprError();
  1852. }
  1853. if (Expr.isInvalid() || Ty.isInvalid())
  1854. Res = ExprError();
  1855. else
  1856. Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
  1857. break;
  1858. }
  1859. case tok::kw___builtin_offsetof: {
  1860. SourceLocation TypeLoc = Tok.getLocation();
  1861. TypeResult Ty = ParseTypeName();
  1862. if (Ty.isInvalid()) {
  1863. SkipUntil(tok::r_paren, StopAtSemi);
  1864. return ExprError();
  1865. }
  1866. if (ExpectAndConsume(tok::comma)) {
  1867. SkipUntil(tok::r_paren, StopAtSemi);
  1868. return ExprError();
  1869. }
  1870. // We must have at least one identifier here.
  1871. if (Tok.isNot(tok::identifier)) {
  1872. Diag(Tok, diag::err_expected) << tok::identifier;
  1873. SkipUntil(tok::r_paren, StopAtSemi);
  1874. return ExprError();
  1875. }
  1876. // Keep track of the various subcomponents we see.
  1877. SmallVector<Sema::OffsetOfComponent, 4> Comps;
  1878. Comps.push_back(Sema::OffsetOfComponent());
  1879. Comps.back().isBrackets = false;
  1880. Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
  1881. Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
  1882. // FIXME: This loop leaks the index expressions on error.
  1883. while (1) {
  1884. if (Tok.is(tok::period)) {
  1885. // offsetof-member-designator: offsetof-member-designator '.' identifier
  1886. Comps.push_back(Sema::OffsetOfComponent());
  1887. Comps.back().isBrackets = false;
  1888. Comps.back().LocStart = ConsumeToken();
  1889. if (Tok.isNot(tok::identifier)) {
  1890. Diag(Tok, diag::err_expected) << tok::identifier;
  1891. SkipUntil(tok::r_paren, StopAtSemi);
  1892. return ExprError();
  1893. }
  1894. Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
  1895. Comps.back().LocEnd = ConsumeToken();
  1896. } else if (Tok.is(tok::l_square)) {
  1897. if (CheckProhibitedCXX11Attribute())
  1898. return ExprError();
  1899. // offsetof-member-designator: offsetof-member-design '[' expression ']'
  1900. Comps.push_back(Sema::OffsetOfComponent());
  1901. Comps.back().isBrackets = true;
  1902. BalancedDelimiterTracker ST(*this, tok::l_square);
  1903. ST.consumeOpen();
  1904. Comps.back().LocStart = ST.getOpenLocation();
  1905. Res = ParseExpression();
  1906. if (Res.isInvalid()) {
  1907. SkipUntil(tok::r_paren, StopAtSemi);
  1908. return Res;
  1909. }
  1910. Comps.back().U.E = Res.get();
  1911. ST.consumeClose();
  1912. Comps.back().LocEnd = ST.getCloseLocation();
  1913. } else {
  1914. if (Tok.isNot(tok::r_paren)) {
  1915. PT.consumeClose();
  1916. Res = ExprError();
  1917. } else if (Ty.isInvalid()) {
  1918. Res = ExprError();
  1919. } else {
  1920. PT.consumeClose();
  1921. Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
  1922. Ty.get(), &Comps[0], Comps.size(),
  1923. PT.getCloseLocation());
  1924. }
  1925. break;
  1926. }
  1927. }
  1928. break;
  1929. }
  1930. case tok::kw___builtin_choose_expr: {
  1931. ExprResult Cond(ParseAssignmentExpression());
  1932. if (Cond.isInvalid()) {
  1933. SkipUntil(tok::r_paren, StopAtSemi);
  1934. return Cond;
  1935. }
  1936. if (ExpectAndConsume(tok::comma)) {
  1937. SkipUntil(tok::r_paren, StopAtSemi);
  1938. return ExprError();
  1939. }
  1940. ExprResult Expr1(ParseAssignmentExpression());
  1941. if (Expr1.isInvalid()) {
  1942. SkipUntil(tok::r_paren, StopAtSemi);
  1943. return Expr1;
  1944. }
  1945. if (ExpectAndConsume(tok::comma)) {
  1946. SkipUntil(tok::r_paren, StopAtSemi);
  1947. return ExprError();
  1948. }
  1949. ExprResult Expr2(ParseAssignmentExpression());
  1950. if (Expr2.isInvalid()) {
  1951. SkipUntil(tok::r_paren, StopAtSemi);
  1952. return Expr2;
  1953. }
  1954. if (Tok.isNot(tok::r_paren)) {
  1955. Diag(Tok, diag::err_expected) << tok::r_paren;
  1956. return ExprError();
  1957. }
  1958. Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
  1959. Expr2.get(), ConsumeParen());
  1960. break;
  1961. }
  1962. case tok::kw___builtin_astype: {
  1963. // The first argument is an expression to be converted, followed by a comma.
  1964. ExprResult Expr(ParseAssignmentExpression());
  1965. if (Expr.isInvalid()) {
  1966. SkipUntil(tok::r_paren, StopAtSemi);
  1967. return ExprError();
  1968. }
  1969. if (ExpectAndConsume(tok::comma)) {
  1970. SkipUntil(tok::r_paren, StopAtSemi);
  1971. return ExprError();
  1972. }
  1973. // Second argument is the type to bitcast to.
  1974. TypeResult DestTy = ParseTypeName();
  1975. if (DestTy.isInvalid())
  1976. return ExprError();
  1977. // Attempt to consume the r-paren.
  1978. if (Tok.isNot(tok::r_paren)) {
  1979. Diag(Tok, diag::err_expected) << tok::r_paren;
  1980. SkipUntil(tok::r_paren, StopAtSemi);
  1981. return ExprError();
  1982. }
  1983. Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
  1984. ConsumeParen());
  1985. break;
  1986. }
  1987. case tok::kw___builtin_convertvector: {
  1988. // The first argument is an expression to be converted, followed by a comma.
  1989. ExprResult Expr(ParseAssignmentExpression());
  1990. if (Expr.isInvalid()) {
  1991. SkipUntil(tok::r_paren, StopAtSemi);
  1992. return ExprError();
  1993. }
  1994. if (ExpectAndConsume(tok::comma)) {
  1995. SkipUntil(tok::r_paren, StopAtSemi);
  1996. return ExprError();
  1997. }
  1998. // Second argument is the type to bitcast to.
  1999. TypeResult DestTy = ParseTypeName();
  2000. if (DestTy.isInvalid())
  2001. return ExprError();
  2002. // Attempt to consume the r-paren.
  2003. if (Tok.isNot(tok::r_paren)) {
  2004. Diag(Tok, diag::err_expected) << tok::r_paren;
  2005. SkipUntil(tok::r_paren, StopAtSemi);
  2006. return ExprError();
  2007. }
  2008. Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
  2009. ConsumeParen());
  2010. break;
  2011. }
  2012. }
  2013. if (Res.isInvalid())
  2014. return ExprError();
  2015. // These can be followed by postfix-expr pieces because they are
  2016. // primary-expressions.
  2017. return ParsePostfixExpressionSuffix(Res.get());
  2018. }
  2019. /// ParseParenExpression - This parses the unit that starts with a '(' token,
  2020. /// based on what is allowed by ExprType. The actual thing parsed is returned
  2021. /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
  2022. /// not the parsed cast-expression.
  2023. ///
  2024. /// \verbatim
  2025. /// primary-expression: [C99 6.5.1]
  2026. /// '(' expression ')'
  2027. /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
  2028. /// postfix-expression: [C99 6.5.2]
  2029. /// '(' type-name ')' '{' initializer-list '}'
  2030. /// '(' type-name ')' '{' initializer-list ',' '}'
  2031. /// cast-expression: [C99 6.5.4]
  2032. /// '(' type-name ')' cast-expression
  2033. /// [ARC] bridged-cast-expression
  2034. /// [ARC] bridged-cast-expression:
  2035. /// (__bridge type-name) cast-expression
  2036. /// (__bridge_transfer type-name) cast-expression
  2037. /// (__bridge_retained type-name) cast-expression
  2038. /// fold-expression: [C++1z]
  2039. /// '(' cast-expression fold-operator '...' ')'
  2040. /// '(' '...' fold-operator cast-expression ')'
  2041. /// '(' cast-expression fold-operator '...'
  2042. /// fold-operator cast-expression ')'
  2043. /// \endverbatim
  2044. ExprResult
  2045. Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
  2046. bool isTypeCast, ParsedType &CastTy,
  2047. SourceLocation &RParenLoc) {
  2048. assert(Tok.is(tok::l_paren) && "Not a paren expr!");
  2049. ColonProtectionRAIIObject ColonProtection(*this, false);
  2050. BalancedDelimiterTracker T(*this, tok::l_paren);
  2051. if (T.consumeOpen())
  2052. return ExprError();
  2053. SourceLocation OpenLoc = T.getOpenLocation();
  2054. ExprResult Result(true);
  2055. bool isAmbiguousTypeId;
  2056. CastTy = ParsedType();
  2057. if (Tok.is(tok::code_completion)) {
  2058. Actions.CodeCompleteOrdinaryName(getCurScope(),
  2059. ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
  2060. : Sema::PCC_Expression);
  2061. cutOffParsing();
  2062. return ExprError();
  2063. }
  2064. // Diagnose use of bridge casts in non-arc mode.
  2065. bool BridgeCast = (getLangOpts().ObjC2 &&
  2066. Tok.isOneOf(tok::kw___bridge,
  2067. tok::kw___bridge_transfer,
  2068. tok::kw___bridge_retained,
  2069. tok::kw___bridge_retain));
  2070. if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
  2071. if (!TryConsumeToken(tok::kw___bridge)) {
  2072. StringRef BridgeCastName = Tok.getName();
  2073. SourceLocation BridgeKeywordLoc = ConsumeToken();
  2074. if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
  2075. Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
  2076. << BridgeCastName
  2077. << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
  2078. }
  2079. BridgeCast = false;
  2080. }
  2081. // None of these cases should fall through with an invalid Result
  2082. // unless they've already reported an error.
  2083. if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
  2084. Diag(Tok, diag::ext_gnu_statement_expr);
  2085. if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
  2086. Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
  2087. } else {
  2088. // Find the nearest non-record decl context. Variables declared in a
  2089. // statement expression behave as if they were declared in the enclosing
  2090. // function, block, or other code construct.
  2091. DeclContext *CodeDC = Actions.CurContext;
  2092. while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
  2093. CodeDC = CodeDC->getParent();
  2094. assert(CodeDC && !CodeDC->isFileContext() &&
  2095. "statement expr not in code context");
  2096. }
  2097. Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
  2098. Actions.ActOnStartStmtExpr();
  2099. StmtResult Stmt(ParseCompoundStatement(true));
  2100. ExprType = CompoundStmt;
  2101. // If the substmt parsed correctly, build the AST node.
  2102. if (!Stmt.isInvalid()) {
  2103. Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
  2104. } else {
  2105. Actions.ActOnStmtExprError();
  2106. }
  2107. }
  2108. } else if (ExprType >= CompoundLiteral && BridgeCast) {
  2109. tok::TokenKind tokenKind = Tok.getKind();
  2110. SourceLocation BridgeKeywordLoc = ConsumeToken();
  2111. // Parse an Objective-C ARC ownership cast expression.
  2112. ObjCBridgeCastKind Kind;
  2113. if (tokenKind == tok::kw___bridge)
  2114. Kind = OBC_Bridge;
  2115. else if (tokenKind == tok::kw___bridge_transfer)
  2116. Kind = OBC_BridgeTransfer;
  2117. else if (tokenKind == tok::kw___bridge_retained)
  2118. Kind = OBC_BridgeRetained;
  2119. else {
  2120. // As a hopefully temporary workaround, allow __bridge_retain as
  2121. // a synonym for __bridge_retained, but only in system headers.
  2122. assert(tokenKind == tok::kw___bridge_retain);
  2123. Kind = OBC_BridgeRetained;
  2124. if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
  2125. Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
  2126. << FixItHint::CreateReplacement(BridgeKeywordLoc,
  2127. "__bridge_retained");
  2128. }
  2129. TypeResult Ty = ParseTypeName();
  2130. T.consumeClose();
  2131. ColonProtection.restore();
  2132. RParenLoc = T.getCloseLocation();
  2133. ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
  2134. if (Ty.isInvalid() || SubExpr.isInvalid())
  2135. return ExprError();
  2136. return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
  2137. BridgeKeywordLoc, Ty.get(),
  2138. RParenLoc, SubExpr.get());
  2139. } else if (ExprType >= CompoundLiteral &&
  2140. isTypeIdInParens(isAmbiguousTypeId)) {
  2141. // Otherwise, this is a compound literal expression or cast expression.
  2142. // In C++, if the type-id is ambiguous we disambiguate based on context.
  2143. // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
  2144. // in which case we should treat it as type-id.
  2145. // if stopIfCastExpr is false, we need to determine the context past the
  2146. // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
  2147. if (isAmbiguousTypeId && !stopIfCastExpr) {
  2148. ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
  2149. ColonProtection);
  2150. RParenLoc = T.getCloseLocation();
  2151. return res;
  2152. }
  2153. // Parse the type declarator.
  2154. DeclSpec DS(AttrFactory);
  2155. ParseSpecifierQualifierList(DS);
  2156. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  2157. ParseDeclarator(DeclaratorInfo);
  2158. // If our type is followed by an identifier and either ':' or ']', then
  2159. // this is probably an Objective-C message send where the leading '[' is
  2160. // missing. Recover as if that were the case.
  2161. if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
  2162. !InMessageExpression && getLangOpts().ObjC1 &&
  2163. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
  2164. TypeResult Ty;
  2165. {
  2166. InMessageExpressionRAIIObject InMessage(*this, false);
  2167. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  2168. }
  2169. Result = ParseObjCMessageExpressionBody(SourceLocation(),
  2170. SourceLocation(),
  2171. Ty.get(), nullptr);
  2172. } else {
  2173. // Match the ')'.
  2174. T.consumeClose();
  2175. ColonProtection.restore();
  2176. RParenLoc = T.getCloseLocation();
  2177. if (Tok.is(tok::l_brace)) {
  2178. // HLSL Change Starts
  2179. if (getLangOpts().HLSL) {
  2180. // (type-name) { initializer-list }
  2181. Diag(Tok, diag::err_hlsl_unsupported_construct) << "compound literal";
  2182. return ExprError();
  2183. }
  2184. // HLSL Change Ends
  2185. ExprType = CompoundLiteral;
  2186. TypeResult Ty;
  2187. {
  2188. InMessageExpressionRAIIObject InMessage(*this, false);
  2189. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  2190. }
  2191. return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
  2192. }
  2193. if (ExprType == CastExpr) {
  2194. // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
  2195. if (DeclaratorInfo.isInvalidType())
  2196. return ExprError();
  2197. // Note that this doesn't parse the subsequent cast-expression, it just
  2198. // returns the parsed type to the callee.
  2199. if (stopIfCastExpr) {
  2200. TypeResult Ty;
  2201. {
  2202. InMessageExpressionRAIIObject InMessage(*this, false);
  2203. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  2204. }
  2205. CastTy = Ty.get();
  2206. return ExprResult();
  2207. }
  2208. // Reject the cast of super idiom in ObjC.
  2209. if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
  2210. Tok.getIdentifierInfo() == Ident_super &&
  2211. getCurScope()->isInObjcMethodScope() &&
  2212. GetLookAheadToken(1).isNot(tok::period)) {
  2213. Diag(Tok.getLocation(), diag::err_illegal_super_cast)
  2214. << SourceRange(OpenLoc, RParenLoc);
  2215. return ExprError();
  2216. }
  2217. // Parse the cast-expression that follows it next.
  2218. // TODO: For cast expression with CastTy.
  2219. Result = ParseCastExpression(/*isUnaryExpression=*/false,
  2220. /*isAddressOfOperand=*/false,
  2221. /*isTypeCast=*/IsTypeCast);
  2222. if (!Result.isInvalid()) {
  2223. Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
  2224. DeclaratorInfo, CastTy,
  2225. RParenLoc, Result.get());
  2226. }
  2227. return Result;
  2228. }
  2229. Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
  2230. return ExprError();
  2231. }
  2232. } else if (Tok.is(tok::ellipsis) &&
  2233. isFoldOperator(NextToken().getKind())) {
  2234. return ParseFoldExpression(ExprResult(), T);
  2235. } else if (isTypeCast) {
  2236. // Parse the expression-list.
  2237. InMessageExpressionRAIIObject InMessage(*this, false);
  2238. ExprVector ArgExprs;
  2239. CommaLocsTy CommaLocs;
  2240. if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
  2241. // FIXME: If we ever support comma expressions as operands to
  2242. // fold-expressions, we'll need to allow multiple ArgExprs here.
  2243. if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
  2244. NextToken().is(tok::ellipsis))
  2245. return ParseFoldExpression(Result, T);
  2246. ExprType = SimpleExpr;
  2247. Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
  2248. ArgExprs);
  2249. }
  2250. } else {
  2251. InMessageExpressionRAIIObject InMessage(*this, false);
  2252. Result = ParseExpression(MaybeTypeCast);
  2253. if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
  2254. // Correct typos in non-C++ code earlier so that implicit-cast-like
  2255. // expressions are parsed correctly.
  2256. Result = Actions.CorrectDelayedTyposInExpr(Result);
  2257. }
  2258. ExprType = SimpleExpr;
  2259. if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
  2260. return ParseFoldExpression(Result, T);
  2261. // Don't build a paren expression unless we actually match a ')'.
  2262. if (!Result.isInvalid() && Tok.is(tok::r_paren))
  2263. Result =
  2264. Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
  2265. }
  2266. // Match the ')'.
  2267. if (Result.isInvalid()) {
  2268. SkipUntil(tok::r_paren, StopAtSemi);
  2269. return ExprError();
  2270. }
  2271. T.consumeClose();
  2272. RParenLoc = T.getCloseLocation();
  2273. return Result;
  2274. }
  2275. /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
  2276. /// and we are at the left brace.
  2277. ///
  2278. /// \verbatim
  2279. /// postfix-expression: [C99 6.5.2]
  2280. /// '(' type-name ')' '{' initializer-list '}'
  2281. /// '(' type-name ')' '{' initializer-list ',' '}'
  2282. /// \endverbatim
  2283. ExprResult
  2284. Parser::ParseCompoundLiteralExpression(ParsedType Ty,
  2285. SourceLocation LParenLoc,
  2286. SourceLocation RParenLoc) {
  2287. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2288. assert(Tok.is(tok::l_brace) && "Not a compound literal!");
  2289. if (!getLangOpts().C99) // Compound literals don't exist in C90.
  2290. Diag(LParenLoc, diag::ext_c99_compound_literal);
  2291. ExprResult Result = ParseInitializer();
  2292. if (!Result.isInvalid() && Ty)
  2293. return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
  2294. return Result;
  2295. }
  2296. /// ParseStringLiteralExpression - This handles the various token types that
  2297. /// form string literals, and also handles string concatenation [C99 5.1.1.2,
  2298. /// translation phase #6].
  2299. ///
  2300. /// \verbatim
  2301. /// primary-expression: [C99 6.5.1]
  2302. /// string-literal
  2303. /// \verbatim
  2304. ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
  2305. assert(isTokenStringLiteral() && "Not a string literal!");
  2306. // String concat. Note that keywords like __func__ and __FUNCTION__ are not
  2307. // considered to be strings for concatenation purposes.
  2308. SmallVector<Token, 4> StringToks;
  2309. do {
  2310. StringToks.push_back(Tok);
  2311. ConsumeStringToken();
  2312. } while (isTokenStringLiteral());
  2313. // Pass the set of string tokens, ready for concatenation, to the actions.
  2314. return Actions.ActOnStringLiteral(StringToks,
  2315. AllowUserDefinedLiteral ? getCurScope()
  2316. : nullptr);
  2317. }
  2318. /// ParseGenericSelectionExpression - Parse a C11 generic-selection
  2319. /// [C11 6.5.1.1].
  2320. ///
  2321. /// \verbatim
  2322. /// generic-selection:
  2323. /// _Generic ( assignment-expression , generic-assoc-list )
  2324. /// generic-assoc-list:
  2325. /// generic-association
  2326. /// generic-assoc-list , generic-association
  2327. /// generic-association:
  2328. /// type-name : assignment-expression
  2329. /// default : assignment-expression
  2330. /// \endverbatim
  2331. ExprResult Parser::ParseGenericSelectionExpression() {
  2332. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2333. assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
  2334. SourceLocation KeyLoc = ConsumeToken();
  2335. if (!getLangOpts().C11)
  2336. Diag(KeyLoc, diag::ext_c11_generic_selection);
  2337. BalancedDelimiterTracker T(*this, tok::l_paren);
  2338. if (T.expectAndConsume())
  2339. return ExprError();
  2340. ExprResult ControllingExpr;
  2341. {
  2342. // C11 6.5.1.1p3 "The controlling expression of a generic selection is
  2343. // not evaluated."
  2344. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  2345. ControllingExpr =
  2346. Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
  2347. if (ControllingExpr.isInvalid()) {
  2348. SkipUntil(tok::r_paren, StopAtSemi);
  2349. return ExprError();
  2350. }
  2351. }
  2352. if (ExpectAndConsume(tok::comma)) {
  2353. SkipUntil(tok::r_paren, StopAtSemi);
  2354. return ExprError();
  2355. }
  2356. SourceLocation DefaultLoc;
  2357. TypeVector Types;
  2358. ExprVector Exprs;
  2359. do {
  2360. ParsedType Ty;
  2361. if (Tok.is(tok::kw_default)) {
  2362. // C11 6.5.1.1p2 "A generic selection shall have no more than one default
  2363. // generic association."
  2364. if (!DefaultLoc.isInvalid()) {
  2365. Diag(Tok, diag::err_duplicate_default_assoc);
  2366. Diag(DefaultLoc, diag::note_previous_default_assoc);
  2367. SkipUntil(tok::r_paren, StopAtSemi);
  2368. return ExprError();
  2369. }
  2370. DefaultLoc = ConsumeToken();
  2371. Ty = ParsedType();
  2372. } else {
  2373. ColonProtectionRAIIObject X(*this);
  2374. TypeResult TR = ParseTypeName();
  2375. if (TR.isInvalid()) {
  2376. SkipUntil(tok::r_paren, StopAtSemi);
  2377. return ExprError();
  2378. }
  2379. Ty = TR.get();
  2380. }
  2381. Types.push_back(Ty);
  2382. if (ExpectAndConsume(tok::colon)) {
  2383. SkipUntil(tok::r_paren, StopAtSemi);
  2384. return ExprError();
  2385. }
  2386. // FIXME: These expressions should be parsed in a potentially potentially
  2387. // evaluated context.
  2388. ExprResult ER(
  2389. Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
  2390. if (ER.isInvalid()) {
  2391. SkipUntil(tok::r_paren, StopAtSemi);
  2392. return ExprError();
  2393. }
  2394. Exprs.push_back(ER.get());
  2395. } while (TryConsumeToken(tok::comma));
  2396. T.consumeClose();
  2397. if (T.getCloseLocation().isInvalid())
  2398. return ExprError();
  2399. return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
  2400. T.getCloseLocation(),
  2401. ControllingExpr.get(),
  2402. Types, Exprs);
  2403. }
  2404. /// \brief Parse A C++1z fold-expression after the opening paren and optional
  2405. /// left-hand-side expression.
  2406. ///
  2407. /// \verbatim
  2408. /// fold-expression:
  2409. /// ( cast-expression fold-operator ... )
  2410. /// ( ... fold-operator cast-expression )
  2411. /// ( cast-expression fold-operator ... fold-operator cast-expression )
  2412. ExprResult Parser::ParseFoldExpression(ExprResult LHS,
  2413. BalancedDelimiterTracker &T) {
  2414. if (LHS.isInvalid()) {
  2415. T.skipToEnd();
  2416. return true;
  2417. }
  2418. tok::TokenKind Kind = tok::unknown;
  2419. SourceLocation FirstOpLoc;
  2420. if (LHS.isUsable()) {
  2421. Kind = Tok.getKind();
  2422. assert(isFoldOperator(Kind) && "missing fold-operator");
  2423. FirstOpLoc = ConsumeToken();
  2424. }
  2425. assert(Tok.is(tok::ellipsis) && "not a fold-expression");
  2426. SourceLocation EllipsisLoc = ConsumeToken();
  2427. ExprResult RHS;
  2428. if (Tok.isNot(tok::r_paren)) {
  2429. if (!isFoldOperator(Tok.getKind()))
  2430. return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
  2431. if (Kind != tok::unknown && Tok.getKind() != Kind)
  2432. Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
  2433. << SourceRange(FirstOpLoc);
  2434. Kind = Tok.getKind();
  2435. ConsumeToken();
  2436. RHS = ParseExpression();
  2437. if (RHS.isInvalid()) {
  2438. T.skipToEnd();
  2439. return true;
  2440. }
  2441. }
  2442. Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
  2443. ? diag::warn_cxx14_compat_fold_expression
  2444. : diag::ext_fold_expression);
  2445. T.consumeClose();
  2446. return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
  2447. EllipsisLoc, RHS.get(), T.getCloseLocation());
  2448. }
  2449. /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
  2450. ///
  2451. /// \verbatim
  2452. /// argument-expression-list:
  2453. /// assignment-expression
  2454. /// argument-expression-list , assignment-expression
  2455. ///
  2456. /// [C++] expression-list:
  2457. /// [C++] assignment-expression
  2458. /// [C++] expression-list , assignment-expression
  2459. ///
  2460. /// [C++0x] expression-list:
  2461. /// [C++0x] initializer-list
  2462. ///
  2463. /// [C++0x] initializer-list
  2464. /// [C++0x] initializer-clause ...[opt]
  2465. /// [C++0x] initializer-list , initializer-clause ...[opt]
  2466. ///
  2467. /// [C++0x] initializer-clause:
  2468. /// [C++0x] assignment-expression
  2469. /// [C++0x] braced-init-list
  2470. /// \endverbatim
  2471. bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
  2472. SmallVectorImpl<SourceLocation> &CommaLocs,
  2473. std::function<void()> Completer) {
  2474. bool SawError = false;
  2475. while (1) {
  2476. if (Tok.is(tok::code_completion)) {
  2477. if (Completer)
  2478. Completer();
  2479. else
  2480. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
  2481. cutOffParsing();
  2482. return true;
  2483. }
  2484. ExprResult Expr;
  2485. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
  2486. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  2487. Expr = ParseBraceInitializer();
  2488. } else
  2489. Expr = ParseAssignmentExpression();
  2490. if (Tok.is(tok::ellipsis))
  2491. Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
  2492. if (Expr.isInvalid()) {
  2493. SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
  2494. SawError = true;
  2495. } else {
  2496. Exprs.push_back(Expr.get());
  2497. }
  2498. if (Tok.isNot(tok::comma))
  2499. break;
  2500. // Move to the next argument, remember where the comma was.
  2501. CommaLocs.push_back(ConsumeToken());
  2502. }
  2503. if (SawError) {
  2504. // Ensure typos get diagnosed when errors were encountered while parsing the
  2505. // expression list.
  2506. for (auto &E : Exprs) {
  2507. ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
  2508. if (Expr.isUsable()) E = Expr.get();
  2509. }
  2510. }
  2511. return SawError;
  2512. }
  2513. /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
  2514. /// used for misc language extensions.
  2515. ///
  2516. /// \verbatim
  2517. /// simple-expression-list:
  2518. /// assignment-expression
  2519. /// simple-expression-list , assignment-expression
  2520. /// \endverbatim
  2521. bool
  2522. Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
  2523. SmallVectorImpl<SourceLocation> &CommaLocs) {
  2524. while (1) {
  2525. ExprResult Expr = ParseAssignmentExpression();
  2526. if (Expr.isInvalid())
  2527. return true;
  2528. Exprs.push_back(Expr.get());
  2529. if (Tok.isNot(tok::comma))
  2530. return false;
  2531. // Move to the next argument, remember where the comma was.
  2532. CommaLocs.push_back(ConsumeToken());
  2533. }
  2534. }
  2535. /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
  2536. ///
  2537. /// \verbatim
  2538. /// [clang] block-id:
  2539. /// [clang] specifier-qualifier-list block-declarator
  2540. /// \endverbatim
  2541. void Parser::ParseBlockId(SourceLocation CaretLoc) {
  2542. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2543. if (Tok.is(tok::code_completion)) {
  2544. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
  2545. return cutOffParsing();
  2546. }
  2547. // Parse the specifier-qualifier-list piece.
  2548. DeclSpec DS(AttrFactory);
  2549. ParseSpecifierQualifierList(DS);
  2550. // Parse the block-declarator.
  2551. Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
  2552. ParseDeclarator(DeclaratorInfo);
  2553. MaybeParseGNUAttributes(DeclaratorInfo);
  2554. // Inform sema that we are starting a block.
  2555. Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
  2556. }
  2557. /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
  2558. /// like ^(int x){ return x+1; }
  2559. ///
  2560. /// \verbatim
  2561. /// block-literal:
  2562. /// [clang] '^' block-args[opt] compound-statement
  2563. /// [clang] '^' block-id compound-statement
  2564. /// [clang] block-args:
  2565. /// [clang] '(' parameter-list ')'
  2566. /// \endverbatim
  2567. ExprResult Parser::ParseBlockLiteralExpression() {
  2568. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2569. assert(Tok.is(tok::caret) && "block literal starts with ^");
  2570. SourceLocation CaretLoc = ConsumeToken();
  2571. PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
  2572. "block literal parsing");
  2573. // Enter a scope to hold everything within the block. This includes the
  2574. // argument decls, decls within the compound expression, etc. This also
  2575. // allows determining whether a variable reference inside the block is
  2576. // within or outside of the block.
  2577. ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
  2578. Scope::DeclScope);
  2579. // Inform sema that we are starting a block.
  2580. Actions.ActOnBlockStart(CaretLoc, getCurScope());
  2581. // Parse the return type if present.
  2582. DeclSpec DS(AttrFactory);
  2583. Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
  2584. // FIXME: Since the return type isn't actually parsed, it can't be used to
  2585. // fill ParamInfo with an initial valid range, so do it manually.
  2586. ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
  2587. // If this block has arguments, parse them. There is no ambiguity here with
  2588. // the expression case, because the expression case requires a parameter list.
  2589. if (Tok.is(tok::l_paren)) {
  2590. ParseParenDeclarator(ParamInfo);
  2591. // Parse the pieces after the identifier as if we had "int(...)".
  2592. // SetIdentifier sets the source range end, but in this case we're past
  2593. // that location.
  2594. SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
  2595. ParamInfo.SetIdentifier(nullptr, CaretLoc);
  2596. ParamInfo.SetRangeEnd(Tmp);
  2597. if (ParamInfo.isInvalidType()) {
  2598. // If there was an error parsing the arguments, they may have
  2599. // tried to use ^(x+y) which requires an argument list. Just
  2600. // skip the whole block literal.
  2601. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2602. return ExprError();
  2603. }
  2604. MaybeParseGNUAttributes(ParamInfo);
  2605. // Inform sema that we are starting a block.
  2606. Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
  2607. } else if (!Tok.is(tok::l_brace)) {
  2608. ParseBlockId(CaretLoc);
  2609. } else {
  2610. // Otherwise, pretend we saw (void).
  2611. ParsedAttributes attrs(AttrFactory);
  2612. SourceLocation NoLoc;
  2613. ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
  2614. /*IsAmbiguous=*/false,
  2615. /*RParenLoc=*/NoLoc,
  2616. /*ArgInfo=*/nullptr,
  2617. /*NumArgs=*/0,
  2618. /*EllipsisLoc=*/NoLoc,
  2619. /*RParenLoc=*/NoLoc,
  2620. /*TypeQuals=*/0,
  2621. /*RefQualifierIsLvalueRef=*/true,
  2622. /*RefQualifierLoc=*/NoLoc,
  2623. /*ConstQualifierLoc=*/NoLoc,
  2624. /*VolatileQualifierLoc=*/NoLoc,
  2625. /*RestrictQualifierLoc=*/NoLoc,
  2626. /*MutableLoc=*/NoLoc,
  2627. EST_None,
  2628. /*ESpecLoc=*/NoLoc,
  2629. /*Exceptions=*/nullptr,
  2630. /*ExceptionRanges=*/nullptr,
  2631. /*NumExceptions=*/0,
  2632. /*NoexceptExpr=*/nullptr,
  2633. /*ExceptionSpecTokens=*/nullptr,
  2634. CaretLoc, CaretLoc,
  2635. ParamInfo),
  2636. attrs, CaretLoc);
  2637. MaybeParseGNUAttributes(ParamInfo);
  2638. // Inform sema that we are starting a block.
  2639. Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
  2640. }
  2641. ExprResult Result(true);
  2642. if (!Tok.is(tok::l_brace)) {
  2643. // Saw something like: ^expr
  2644. Diag(Tok, diag::err_expected_expression);
  2645. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2646. return ExprError();
  2647. }
  2648. StmtResult Stmt(ParseCompoundStatementBody());
  2649. BlockScope.Exit();
  2650. if (!Stmt.isInvalid())
  2651. Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
  2652. else
  2653. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2654. return Result;
  2655. }
  2656. /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
  2657. ///
  2658. /// '__objc_yes'
  2659. /// '__objc_no'
  2660. ExprResult Parser::ParseObjCBoolLiteral() {
  2661. assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change
  2662. tok::TokenKind Kind = Tok.getKind();
  2663. return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
  2664. }