ParseExpr.cpp 118 KB

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