ParseExpr.cpp 138 KB

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