ParseExpr.cpp 114 KB

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