ParseExpr.cpp 141 KB

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