ParseExpr.cpp 121 KB

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