ParseExpr.cpp 121 KB

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