ParseExpr.cpp 117 KB

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