ParseExpr.cpp 121 KB

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