ParseExpr.cpp 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463
  1. //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief Provides the Expression parsing implementation.
  12. ///
  13. /// Expressions in C99 basically consist of a bunch of binary operators with
  14. /// unary operators and other random stuff at the leaves.
  15. ///
  16. /// In the C99 grammar, these unary operators bind tightest and are represented
  17. /// as the 'cast-expression' production. Everything else is either a binary
  18. /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
  19. /// handled by ParseCastExpression, the higher level pieces are handled by
  20. /// ParseBinaryExpression.
  21. ///
  22. //===----------------------------------------------------------------------===//
  23. #include "clang/Parse/Parser.h"
  24. #include "clang/Sema/DeclSpec.h"
  25. #include "clang/Sema/Scope.h"
  26. #include "clang/Sema/ParsedTemplate.h"
  27. #include "clang/Sema/TypoCorrection.h"
  28. #include "clang/Basic/PrettyStackTrace.h"
  29. #include "RAIIObjectsForParser.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/SmallString.h"
  32. using namespace clang;
  33. /// \brief Return the precedence of the specified binary operator token.
  34. static prec::Level getBinOpPrecedence(tok::TokenKind Kind,
  35. bool GreaterThanIsOperator,
  36. bool CPlusPlus0x) {
  37. switch (Kind) {
  38. case tok::greater:
  39. // C++ [temp.names]p3:
  40. // [...] When parsing a template-argument-list, the first
  41. // non-nested > is taken as the ending delimiter rather than a
  42. // greater-than operator. [...]
  43. if (GreaterThanIsOperator)
  44. return prec::Relational;
  45. return prec::Unknown;
  46. case tok::greatergreater:
  47. // C++0x [temp.names]p3:
  48. //
  49. // [...] Similarly, the first non-nested >> is treated as two
  50. // consecutive but distinct > tokens, the first of which is
  51. // taken as the end of the template-argument-list and completes
  52. // the template-id. [...]
  53. if (GreaterThanIsOperator || !CPlusPlus0x)
  54. return prec::Shift;
  55. return prec::Unknown;
  56. default: return prec::Unknown;
  57. case tok::comma: return prec::Comma;
  58. case tok::equal:
  59. case tok::starequal:
  60. case tok::slashequal:
  61. case tok::percentequal:
  62. case tok::plusequal:
  63. case tok::minusequal:
  64. case tok::lesslessequal:
  65. case tok::greatergreaterequal:
  66. case tok::ampequal:
  67. case tok::caretequal:
  68. case tok::pipeequal: return prec::Assignment;
  69. case tok::question: return prec::Conditional;
  70. case tok::pipepipe: return prec::LogicalOr;
  71. case tok::ampamp: return prec::LogicalAnd;
  72. case tok::pipe: return prec::InclusiveOr;
  73. case tok::caret: return prec::ExclusiveOr;
  74. case tok::amp: return prec::And;
  75. case tok::exclaimequal:
  76. case tok::equalequal: return prec::Equality;
  77. case tok::lessequal:
  78. case tok::less:
  79. case tok::greaterequal: return prec::Relational;
  80. case tok::lessless: return prec::Shift;
  81. case tok::plus:
  82. case tok::minus: return prec::Additive;
  83. case tok::percent:
  84. case tok::slash:
  85. case tok::star: return prec::Multiplicative;
  86. case tok::periodstar:
  87. case tok::arrowstar: return prec::PointerToMember;
  88. }
  89. }
  90. /// \brief Simple precedence-based parser for binary/ternary operators.
  91. ///
  92. /// Note: we diverge from the C99 grammar when parsing the assignment-expression
  93. /// production. C99 specifies that the LHS of an assignment operator should be
  94. /// parsed as a unary-expression, but consistency dictates that it be a
  95. /// conditional-expession. In practice, the important thing here is that the
  96. /// LHS of an assignment has to be an l-value, which productions between
  97. /// unary-expression and conditional-expression don't produce. Because we want
  98. /// consistency, we parse the LHS as a conditional-expression, then check for
  99. /// l-value-ness in semantic analysis stages.
  100. ///
  101. /// \verbatim
  102. /// pm-expression: [C++ 5.5]
  103. /// cast-expression
  104. /// pm-expression '.*' cast-expression
  105. /// pm-expression '->*' cast-expression
  106. ///
  107. /// multiplicative-expression: [C99 6.5.5]
  108. /// Note: in C++, apply pm-expression instead of cast-expression
  109. /// cast-expression
  110. /// multiplicative-expression '*' cast-expression
  111. /// multiplicative-expression '/' cast-expression
  112. /// multiplicative-expression '%' cast-expression
  113. ///
  114. /// additive-expression: [C99 6.5.6]
  115. /// multiplicative-expression
  116. /// additive-expression '+' multiplicative-expression
  117. /// additive-expression '-' multiplicative-expression
  118. ///
  119. /// shift-expression: [C99 6.5.7]
  120. /// additive-expression
  121. /// shift-expression '<<' additive-expression
  122. /// shift-expression '>>' additive-expression
  123. ///
  124. /// relational-expression: [C99 6.5.8]
  125. /// shift-expression
  126. /// relational-expression '<' shift-expression
  127. /// relational-expression '>' shift-expression
  128. /// relational-expression '<=' shift-expression
  129. /// relational-expression '>=' shift-expression
  130. ///
  131. /// equality-expression: [C99 6.5.9]
  132. /// relational-expression
  133. /// equality-expression '==' relational-expression
  134. /// equality-expression '!=' relational-expression
  135. ///
  136. /// AND-expression: [C99 6.5.10]
  137. /// equality-expression
  138. /// AND-expression '&' equality-expression
  139. ///
  140. /// exclusive-OR-expression: [C99 6.5.11]
  141. /// AND-expression
  142. /// exclusive-OR-expression '^' AND-expression
  143. ///
  144. /// inclusive-OR-expression: [C99 6.5.12]
  145. /// exclusive-OR-expression
  146. /// inclusive-OR-expression '|' exclusive-OR-expression
  147. ///
  148. /// logical-AND-expression: [C99 6.5.13]
  149. /// inclusive-OR-expression
  150. /// logical-AND-expression '&&' inclusive-OR-expression
  151. ///
  152. /// logical-OR-expression: [C99 6.5.14]
  153. /// logical-AND-expression
  154. /// logical-OR-expression '||' logical-AND-expression
  155. ///
  156. /// conditional-expression: [C99 6.5.15]
  157. /// logical-OR-expression
  158. /// logical-OR-expression '?' expression ':' conditional-expression
  159. /// [GNU] logical-OR-expression '?' ':' conditional-expression
  160. /// [C++] the third operand is an assignment-expression
  161. ///
  162. /// assignment-expression: [C99 6.5.16]
  163. /// conditional-expression
  164. /// unary-expression assignment-operator assignment-expression
  165. /// [C++] throw-expression [C++ 15]
  166. ///
  167. /// assignment-operator: one of
  168. /// = *= /= %= += -= <<= >>= &= ^= |=
  169. ///
  170. /// expression: [C99 6.5.17]
  171. /// assignment-expression ...[opt]
  172. /// expression ',' assignment-expression ...[opt]
  173. /// \endverbatim
  174. ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
  175. ExprResult LHS(ParseAssignmentExpression(isTypeCast));
  176. return ParseRHSOfBinaryExpression(LHS, prec::Comma);
  177. }
  178. /// This routine is called when the '@' is seen and consumed.
  179. /// Current token is an Identifier and is not a 'try'. This
  180. /// routine is necessary to disambiguate \@try-statement from,
  181. /// for example, \@encode-expression.
  182. ///
  183. ExprResult
  184. Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
  185. ExprResult LHS(ParseObjCAtExpression(AtLoc));
  186. return ParseRHSOfBinaryExpression(LHS, prec::Comma);
  187. }
  188. /// This routine is called when a leading '__extension__' is seen and
  189. /// consumed. This is necessary because the token gets consumed in the
  190. /// process of disambiguating between an expression and a declaration.
  191. ExprResult
  192. Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
  193. ExprResult LHS(true);
  194. {
  195. // Silence extension warnings in the sub-expression
  196. ExtensionRAIIObject O(Diags);
  197. LHS = ParseCastExpression(false);
  198. }
  199. if (!LHS.isInvalid())
  200. LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
  201. LHS.take());
  202. return ParseRHSOfBinaryExpression(LHS, prec::Comma);
  203. }
  204. /// \brief Parse an expr that doesn't include (top-level) commas.
  205. ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
  206. if (Tok.is(tok::code_completion)) {
  207. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
  208. cutOffParsing();
  209. return ExprError();
  210. }
  211. if (Tok.is(tok::kw_throw))
  212. return ParseThrowExpression();
  213. ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
  214. /*isAddressOfOperand=*/false,
  215. isTypeCast);
  216. return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
  217. }
  218. /// \brief Parse an assignment expression where part of an Objective-C message
  219. /// send has already been parsed.
  220. ///
  221. /// In this case \p LBracLoc indicates the location of the '[' of the message
  222. /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
  223. /// the receiver of the message.
  224. ///
  225. /// Since this handles full assignment-expression's, it handles postfix
  226. /// expressions and other binary operators for these expressions as well.
  227. ExprResult
  228. Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
  229. SourceLocation SuperLoc,
  230. ParsedType ReceiverType,
  231. Expr *ReceiverExpr) {
  232. ExprResult R
  233. = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
  234. ReceiverType, ReceiverExpr);
  235. R = ParsePostfixExpressionSuffix(R);
  236. return ParseRHSOfBinaryExpression(R, prec::Assignment);
  237. }
  238. ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
  239. // C++03 [basic.def.odr]p2:
  240. // An expression is potentially evaluated unless it appears where an
  241. // integral constant expression is required (see 5.19) [...].
  242. // C++98 and C++11 have no such rule, but this is only a defect in C++98.
  243. EnterExpressionEvaluationContext Unevaluated(Actions,
  244. Sema::ConstantEvaluated);
  245. ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
  246. ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
  247. return Actions.ActOnConstantExpression(Res);
  248. }
  249. /// \brief Parse a binary expression that starts with \p LHS and has a
  250. /// precedence of at least \p MinPrec.
  251. ExprResult
  252. Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
  253. prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
  254. GreaterThanIsOperator,
  255. getLangOpts().CPlusPlus0x);
  256. SourceLocation ColonLoc;
  257. while (1) {
  258. // If this token has a lower precedence than we are allowed to parse (e.g.
  259. // because we are called recursively, or because the token is not a binop),
  260. // then we are done!
  261. if (NextTokPrec < MinPrec)
  262. return LHS;
  263. // Consume the operator, saving the operator token for error reporting.
  264. Token OpToken = Tok;
  265. ConsumeToken();
  266. // Special case handling for the ternary operator.
  267. ExprResult TernaryMiddle(true);
  268. if (NextTokPrec == prec::Conditional) {
  269. if (Tok.isNot(tok::colon)) {
  270. // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
  271. ColonProtectionRAIIObject X(*this);
  272. // Handle this production specially:
  273. // logical-OR-expression '?' expression ':' conditional-expression
  274. // In particular, the RHS of the '?' is 'expression', not
  275. // 'logical-OR-expression' as we might expect.
  276. TernaryMiddle = ParseExpression();
  277. if (TernaryMiddle.isInvalid()) {
  278. LHS = ExprError();
  279. TernaryMiddle = 0;
  280. }
  281. } else {
  282. // Special case handling of "X ? Y : Z" where Y is empty:
  283. // logical-OR-expression '?' ':' conditional-expression [GNU]
  284. TernaryMiddle = 0;
  285. Diag(Tok, diag::ext_gnu_conditional_expr);
  286. }
  287. if (Tok.is(tok::colon)) {
  288. // Eat the colon.
  289. ColonLoc = ConsumeToken();
  290. } else {
  291. // Otherwise, we're missing a ':'. Assume that this was a typo that
  292. // the user forgot. If we're not in a macro expansion, we can suggest
  293. // a fixit hint. If there were two spaces before the current token,
  294. // suggest inserting the colon in between them, otherwise insert ": ".
  295. SourceLocation FILoc = Tok.getLocation();
  296. const char *FIText = ": ";
  297. const SourceManager &SM = PP.getSourceManager();
  298. if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
  299. assert(FILoc.isFileID());
  300. bool IsInvalid = false;
  301. const char *SourcePtr =
  302. SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
  303. if (!IsInvalid && *SourcePtr == ' ') {
  304. SourcePtr =
  305. SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
  306. if (!IsInvalid && *SourcePtr == ' ') {
  307. FILoc = FILoc.getLocWithOffset(-1);
  308. FIText = ":";
  309. }
  310. }
  311. }
  312. Diag(Tok, diag::err_expected_colon)
  313. << FixItHint::CreateInsertion(FILoc, FIText);
  314. Diag(OpToken, diag::note_matching) << "?";
  315. ColonLoc = Tok.getLocation();
  316. }
  317. }
  318. // Code completion for the right-hand side of an assignment expression
  319. // goes through a special hook that takes the left-hand side into account.
  320. if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
  321. Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
  322. cutOffParsing();
  323. return ExprError();
  324. }
  325. // Parse another leaf here for the RHS of the operator.
  326. // ParseCastExpression works here because all RHS expressions in C have it
  327. // as a prefix, at least. However, in C++, an assignment-expression could
  328. // be a throw-expression, which is not a valid cast-expression.
  329. // Therefore we need some special-casing here.
  330. // Also note that the third operand of the conditional operator is
  331. // an assignment-expression in C++, and in C++11, we can have a
  332. // braced-init-list on the RHS of an assignment. For better diagnostics,
  333. // parse as if we were allowed braced-init-lists everywhere, and check that
  334. // they only appear on the RHS of assignments later.
  335. ExprResult RHS;
  336. bool RHSIsInitList = false;
  337. if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
  338. RHS = ParseBraceInitializer();
  339. RHSIsInitList = true;
  340. } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
  341. RHS = ParseAssignmentExpression();
  342. else
  343. RHS = ParseCastExpression(false);
  344. if (RHS.isInvalid())
  345. LHS = ExprError();
  346. // Remember the precedence of this operator and get the precedence of the
  347. // operator immediately to the right of the RHS.
  348. prec::Level ThisPrec = NextTokPrec;
  349. NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
  350. getLangOpts().CPlusPlus0x);
  351. // Assignment and conditional expressions are right-associative.
  352. bool isRightAssoc = ThisPrec == prec::Conditional ||
  353. ThisPrec == prec::Assignment;
  354. // Get the precedence of the operator to the right of the RHS. If it binds
  355. // more tightly with RHS than we do, evaluate it completely first.
  356. if (ThisPrec < NextTokPrec ||
  357. (ThisPrec == NextTokPrec && isRightAssoc)) {
  358. if (!RHS.isInvalid() && RHSIsInitList) {
  359. Diag(Tok, diag::err_init_list_bin_op)
  360. << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
  361. RHS = ExprError();
  362. }
  363. // If this is left-associative, only parse things on the RHS that bind
  364. // more tightly than the current operator. If it is left-associative, it
  365. // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
  366. // A=(B=(C=D)), where each paren is a level of recursion here.
  367. // The function takes ownership of the RHS.
  368. RHS = ParseRHSOfBinaryExpression(RHS,
  369. static_cast<prec::Level>(ThisPrec + !isRightAssoc));
  370. RHSIsInitList = false;
  371. if (RHS.isInvalid())
  372. LHS = ExprError();
  373. NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
  374. getLangOpts().CPlusPlus0x);
  375. }
  376. assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
  377. if (!RHS.isInvalid() && RHSIsInitList) {
  378. if (ThisPrec == prec::Assignment) {
  379. Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
  380. << Actions.getExprRange(RHS.get());
  381. } else {
  382. Diag(OpToken, diag::err_init_list_bin_op)
  383. << /*RHS*/1 << PP.getSpelling(OpToken)
  384. << Actions.getExprRange(RHS.get());
  385. LHS = ExprError();
  386. }
  387. }
  388. if (!LHS.isInvalid()) {
  389. // Combine the LHS and RHS into the LHS (e.g. build AST).
  390. if (TernaryMiddle.isInvalid()) {
  391. // If we're using '>>' as an operator within a template
  392. // argument list (in C++98), suggest the addition of
  393. // parentheses so that the code remains well-formed in C++0x.
  394. if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
  395. SuggestParentheses(OpToken.getLocation(),
  396. diag::warn_cxx0x_right_shift_in_template_arg,
  397. SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
  398. Actions.getExprRange(RHS.get()).getEnd()));
  399. LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
  400. OpToken.getKind(), LHS.take(), RHS.take());
  401. } else
  402. LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
  403. LHS.take(), TernaryMiddle.take(),
  404. RHS.take());
  405. }
  406. }
  407. }
  408. /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
  409. /// parse a unary-expression.
  410. ///
  411. /// \p isAddressOfOperand exists because an id-expression that is the
  412. /// operand of address-of gets special treatment due to member pointers.
  413. ///
  414. ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
  415. bool isAddressOfOperand,
  416. TypeCastState isTypeCast) {
  417. bool NotCastExpr;
  418. ExprResult Res = ParseCastExpression(isUnaryExpression,
  419. isAddressOfOperand,
  420. NotCastExpr,
  421. isTypeCast);
  422. if (NotCastExpr)
  423. Diag(Tok, diag::err_expected_expression);
  424. return Res;
  425. }
  426. namespace {
  427. class CastExpressionIdValidator : public CorrectionCandidateCallback {
  428. public:
  429. CastExpressionIdValidator(bool AllowTypes, bool AllowNonTypes)
  430. : AllowNonTypes(AllowNonTypes) {
  431. WantTypeSpecifiers = AllowTypes;
  432. }
  433. virtual bool ValidateCandidate(const TypoCorrection &candidate) {
  434. NamedDecl *ND = candidate.getCorrectionDecl();
  435. if (!ND)
  436. return candidate.isKeyword();
  437. if (isa<TypeDecl>(ND))
  438. return WantTypeSpecifiers;
  439. return AllowNonTypes;
  440. }
  441. private:
  442. bool AllowNonTypes;
  443. };
  444. }
  445. /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
  446. /// a unary-expression.
  447. ///
  448. /// \p isAddressOfOperand exists because an id-expression that is the operand
  449. /// of address-of gets special treatment due to member pointers. NotCastExpr
  450. /// is set to true if the token is not the start of a cast-expression, and no
  451. /// diagnostic is emitted in this case.
  452. ///
  453. /// \verbatim
  454. /// cast-expression: [C99 6.5.4]
  455. /// unary-expression
  456. /// '(' type-name ')' cast-expression
  457. ///
  458. /// unary-expression: [C99 6.5.3]
  459. /// postfix-expression
  460. /// '++' unary-expression
  461. /// '--' unary-expression
  462. /// unary-operator cast-expression
  463. /// 'sizeof' unary-expression
  464. /// 'sizeof' '(' type-name ')'
  465. /// [C++11] 'sizeof' '...' '(' identifier ')'
  466. /// [GNU] '__alignof' unary-expression
  467. /// [GNU] '__alignof' '(' type-name ')'
  468. /// [C11] '_Alignof' '(' type-name ')'
  469. /// [C++11] 'alignof' '(' type-id ')'
  470. /// [GNU] '&&' identifier
  471. /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
  472. /// [C++] new-expression
  473. /// [C++] delete-expression
  474. ///
  475. /// unary-operator: one of
  476. /// '&' '*' '+' '-' '~' '!'
  477. /// [GNU] '__extension__' '__real' '__imag'
  478. ///
  479. /// primary-expression: [C99 6.5.1]
  480. /// [C99] identifier
  481. /// [C++] id-expression
  482. /// constant
  483. /// string-literal
  484. /// [C++] boolean-literal [C++ 2.13.5]
  485. /// [C++11] 'nullptr' [C++11 2.14.7]
  486. /// [C++11] user-defined-literal
  487. /// '(' expression ')'
  488. /// [C11] generic-selection
  489. /// '__func__' [C99 6.4.2.2]
  490. /// [GNU] '__FUNCTION__'
  491. /// [GNU] '__PRETTY_FUNCTION__'
  492. /// [GNU] '(' compound-statement ')'
  493. /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
  494. /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
  495. /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
  496. /// assign-expr ')'
  497. /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
  498. /// [GNU] '__null'
  499. /// [OBJC] '[' objc-message-expr ']'
  500. /// [OBJC] '\@selector' '(' objc-selector-arg ')'
  501. /// [OBJC] '\@protocol' '(' identifier ')'
  502. /// [OBJC] '\@encode' '(' type-name ')'
  503. /// [OBJC] objc-string-literal
  504. /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
  505. /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
  506. /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
  507. /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
  508. /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
  509. /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
  510. /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
  511. /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
  512. /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
  513. /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
  514. /// [C++] 'this' [C++ 9.3.2]
  515. /// [G++] unary-type-trait '(' type-id ')'
  516. /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
  517. /// [EMBT] array-type-trait '(' type-id ',' integer ')'
  518. /// [clang] '^' block-literal
  519. ///
  520. /// constant: [C99 6.4.4]
  521. /// integer-constant
  522. /// floating-constant
  523. /// enumeration-constant -> identifier
  524. /// character-constant
  525. ///
  526. /// id-expression: [C++ 5.1]
  527. /// unqualified-id
  528. /// qualified-id
  529. ///
  530. /// unqualified-id: [C++ 5.1]
  531. /// identifier
  532. /// operator-function-id
  533. /// conversion-function-id
  534. /// '~' class-name
  535. /// template-id
  536. ///
  537. /// new-expression: [C++ 5.3.4]
  538. /// '::'[opt] 'new' new-placement[opt] new-type-id
  539. /// new-initializer[opt]
  540. /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
  541. /// new-initializer[opt]
  542. ///
  543. /// delete-expression: [C++ 5.3.5]
  544. /// '::'[opt] 'delete' cast-expression
  545. /// '::'[opt] 'delete' '[' ']' cast-expression
  546. ///
  547. /// [GNU/Embarcadero] unary-type-trait:
  548. /// '__is_arithmetic'
  549. /// '__is_floating_point'
  550. /// '__is_integral'
  551. /// '__is_lvalue_expr'
  552. /// '__is_rvalue_expr'
  553. /// '__is_complete_type'
  554. /// '__is_void'
  555. /// '__is_array'
  556. /// '__is_function'
  557. /// '__is_reference'
  558. /// '__is_lvalue_reference'
  559. /// '__is_rvalue_reference'
  560. /// '__is_fundamental'
  561. /// '__is_object'
  562. /// '__is_scalar'
  563. /// '__is_compound'
  564. /// '__is_pointer'
  565. /// '__is_member_object_pointer'
  566. /// '__is_member_function_pointer'
  567. /// '__is_member_pointer'
  568. /// '__is_const'
  569. /// '__is_volatile'
  570. /// '__is_trivial'
  571. /// '__is_standard_layout'
  572. /// '__is_signed'
  573. /// '__is_unsigned'
  574. ///
  575. /// [GNU] unary-type-trait:
  576. /// '__has_nothrow_assign'
  577. /// '__has_nothrow_copy'
  578. /// '__has_nothrow_constructor'
  579. /// '__has_trivial_assign' [TODO]
  580. /// '__has_trivial_copy' [TODO]
  581. /// '__has_trivial_constructor'
  582. /// '__has_trivial_destructor'
  583. /// '__has_virtual_destructor'
  584. /// '__is_abstract' [TODO]
  585. /// '__is_class'
  586. /// '__is_empty' [TODO]
  587. /// '__is_enum'
  588. /// '__is_final'
  589. /// '__is_pod'
  590. /// '__is_polymorphic'
  591. /// '__is_trivial'
  592. /// '__is_union'
  593. ///
  594. /// [Clang] unary-type-trait:
  595. /// '__trivially_copyable'
  596. ///
  597. /// binary-type-trait:
  598. /// [GNU] '__is_base_of'
  599. /// [MS] '__is_convertible_to'
  600. /// '__is_convertible'
  601. /// '__is_same'
  602. ///
  603. /// [Embarcadero] array-type-trait:
  604. /// '__array_rank'
  605. /// '__array_extent'
  606. ///
  607. /// [Embarcadero] expression-trait:
  608. /// '__is_lvalue_expr'
  609. /// '__is_rvalue_expr'
  610. /// \endverbatim
  611. ///
  612. ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
  613. bool isAddressOfOperand,
  614. bool &NotCastExpr,
  615. TypeCastState isTypeCast) {
  616. ExprResult Res;
  617. tok::TokenKind SavedKind = Tok.getKind();
  618. NotCastExpr = false;
  619. // This handles all of cast-expression, unary-expression, postfix-expression,
  620. // and primary-expression. We handle them together like this for efficiency
  621. // and to simplify handling of an expression starting with a '(' token: which
  622. // may be one of a parenthesized expression, cast-expression, compound literal
  623. // expression, or statement expression.
  624. //
  625. // If the parsed tokens consist of a primary-expression, the cases below
  626. // break out of the switch; at the end we call ParsePostfixExpressionSuffix
  627. // to handle the postfix expression suffixes. Cases that cannot be followed
  628. // by postfix exprs should return without invoking
  629. // ParsePostfixExpressionSuffix.
  630. switch (SavedKind) {
  631. case tok::l_paren: {
  632. // If this expression is limited to being a unary-expression, the parent can
  633. // not start a cast expression.
  634. ParenParseOption ParenExprType =
  635. (isUnaryExpression && !getLangOpts().CPlusPlus)? CompoundLiteral : CastExpr;
  636. ParsedType CastTy;
  637. SourceLocation RParenLoc;
  638. {
  639. // The inside of the parens don't need to be a colon protected scope, and
  640. // isn't immediately a message send.
  641. ColonProtectionRAIIObject X(*this, false);
  642. Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
  643. isTypeCast == IsTypeCast, CastTy, RParenLoc);
  644. }
  645. switch (ParenExprType) {
  646. case SimpleExpr: break; // Nothing else to do.
  647. case CompoundStmt: break; // Nothing else to do.
  648. case CompoundLiteral:
  649. // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
  650. // postfix-expression exist, parse them now.
  651. break;
  652. case CastExpr:
  653. // We have parsed the cast-expression and no postfix-expr pieces are
  654. // following.
  655. return Res;
  656. }
  657. break;
  658. }
  659. // primary-expression
  660. case tok::numeric_constant:
  661. // constant: integer-constant
  662. // constant: floating-constant
  663. Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
  664. ConsumeToken();
  665. break;
  666. case tok::kw_true:
  667. case tok::kw_false:
  668. return ParseCXXBoolLiteral();
  669. case tok::kw___objc_yes:
  670. case tok::kw___objc_no:
  671. return ParseObjCBoolLiteral();
  672. case tok::kw_nullptr:
  673. Diag(Tok, diag::warn_cxx98_compat_nullptr);
  674. return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
  675. case tok::annot_primary_expr:
  676. assert(Res.get() == 0 && "Stray primary-expression annotation?");
  677. Res = getExprAnnotation(Tok);
  678. ConsumeToken();
  679. break;
  680. case tok::kw_decltype:
  681. case tok::identifier: { // primary-expression: identifier
  682. // unqualified-id: identifier
  683. // constant: enumeration-constant
  684. // Turn a potentially qualified name into a annot_typename or
  685. // annot_cxxscope if it would be valid. This handles things like x::y, etc.
  686. if (getLangOpts().CPlusPlus) {
  687. // Avoid the unnecessary parse-time lookup in the common case
  688. // where the syntax forbids a type.
  689. const Token &Next = NextToken();
  690. if (Next.is(tok::coloncolon) ||
  691. (!ColonIsSacred && Next.is(tok::colon)) ||
  692. Next.is(tok::less) ||
  693. Next.is(tok::l_paren) ||
  694. Next.is(tok::l_brace)) {
  695. // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
  696. if (TryAnnotateTypeOrScopeToken())
  697. return ExprError();
  698. if (!Tok.is(tok::identifier))
  699. return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
  700. }
  701. }
  702. // Consume the identifier so that we can see if it is followed by a '(' or
  703. // '.'.
  704. IdentifierInfo &II = *Tok.getIdentifierInfo();
  705. SourceLocation ILoc = ConsumeToken();
  706. // Support 'Class.property' and 'super.property' notation.
  707. if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
  708. (Actions.getTypeName(II, ILoc, getCurScope()) ||
  709. // Allow the base to be 'super' if in an objc-method.
  710. (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
  711. ConsumeToken();
  712. // Allow either an identifier or the keyword 'class' (in C++).
  713. if (Tok.isNot(tok::identifier) &&
  714. !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
  715. Diag(Tok, diag::err_expected_property_name);
  716. return ExprError();
  717. }
  718. IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
  719. SourceLocation PropertyLoc = ConsumeToken();
  720. Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
  721. ILoc, PropertyLoc);
  722. break;
  723. }
  724. // In an Objective-C method, if we have "super" followed by an identifier,
  725. // the token sequence is ill-formed. However, if there's a ':' or ']' after
  726. // that identifier, this is probably a message send with a missing open
  727. // bracket. Treat it as such.
  728. if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
  729. getCurScope()->isInObjcMethodScope() &&
  730. ((Tok.is(tok::identifier) &&
  731. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
  732. Tok.is(tok::code_completion))) {
  733. Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
  734. 0);
  735. break;
  736. }
  737. // If we have an Objective-C class name followed by an identifier
  738. // and either ':' or ']', this is an Objective-C class message
  739. // send that's missing the opening '['. Recovery
  740. // appropriately. Also take this path if we're performing code
  741. // completion after an Objective-C class name.
  742. if (getLangOpts().ObjC1 &&
  743. ((Tok.is(tok::identifier) && !InMessageExpression) ||
  744. Tok.is(tok::code_completion))) {
  745. const Token& Next = NextToken();
  746. if (Tok.is(tok::code_completion) ||
  747. Next.is(tok::colon) || Next.is(tok::r_square))
  748. if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
  749. if (Typ.get()->isObjCObjectOrInterfaceType()) {
  750. // Fake up a Declarator to use with ActOnTypeName.
  751. DeclSpec DS(AttrFactory);
  752. DS.SetRangeStart(ILoc);
  753. DS.SetRangeEnd(ILoc);
  754. const char *PrevSpec = 0;
  755. unsigned DiagID;
  756. DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ);
  757. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  758. TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
  759. DeclaratorInfo);
  760. if (Ty.isInvalid())
  761. break;
  762. Res = ParseObjCMessageExpressionBody(SourceLocation(),
  763. SourceLocation(),
  764. Ty.get(), 0);
  765. break;
  766. }
  767. }
  768. // Make sure to pass down the right value for isAddressOfOperand.
  769. if (isAddressOfOperand && isPostfixExpressionSuffixStart())
  770. isAddressOfOperand = false;
  771. // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
  772. // need to know whether or not this identifier is a function designator or
  773. // not.
  774. UnqualifiedId Name;
  775. CXXScopeSpec ScopeSpec;
  776. SourceLocation TemplateKWLoc;
  777. CastExpressionIdValidator Validator(isTypeCast != NotTypeCast,
  778. isTypeCast != IsTypeCast);
  779. Name.setIdentifier(&II, ILoc);
  780. Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKWLoc,
  781. Name, Tok.is(tok::l_paren),
  782. isAddressOfOperand, &Validator);
  783. break;
  784. }
  785. case tok::char_constant: // constant: character-constant
  786. case tok::wide_char_constant:
  787. case tok::utf16_char_constant:
  788. case tok::utf32_char_constant:
  789. Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
  790. ConsumeToken();
  791. break;
  792. case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
  793. case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
  794. case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
  795. case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
  796. Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
  797. ConsumeToken();
  798. break;
  799. case tok::string_literal: // primary-expression: string-literal
  800. case tok::wide_string_literal:
  801. case tok::utf8_string_literal:
  802. case tok::utf16_string_literal:
  803. case tok::utf32_string_literal:
  804. Res = ParseStringLiteralExpression(true);
  805. break;
  806. case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
  807. Res = ParseGenericSelectionExpression();
  808. break;
  809. case tok::kw___builtin_va_arg:
  810. case tok::kw___builtin_offsetof:
  811. case tok::kw___builtin_choose_expr:
  812. case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
  813. return ParseBuiltinPrimaryExpression();
  814. case tok::kw___null:
  815. return Actions.ActOnGNUNullExpr(ConsumeToken());
  816. case tok::plusplus: // unary-expression: '++' unary-expression [C99]
  817. case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
  818. // C++ [expr.unary] has:
  819. // unary-expression:
  820. // ++ cast-expression
  821. // -- cast-expression
  822. SourceLocation SavedLoc = ConsumeToken();
  823. Res = ParseCastExpression(!getLangOpts().CPlusPlus);
  824. if (!Res.isInvalid())
  825. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  826. return Res;
  827. }
  828. case tok::amp: { // unary-expression: '&' cast-expression
  829. // Special treatment because of member pointers
  830. SourceLocation SavedLoc = ConsumeToken();
  831. Res = ParseCastExpression(false, true);
  832. if (!Res.isInvalid())
  833. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  834. return Res;
  835. }
  836. case tok::star: // unary-expression: '*' cast-expression
  837. case tok::plus: // unary-expression: '+' cast-expression
  838. case tok::minus: // unary-expression: '-' cast-expression
  839. case tok::tilde: // unary-expression: '~' cast-expression
  840. case tok::exclaim: // unary-expression: '!' cast-expression
  841. case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
  842. case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
  843. SourceLocation SavedLoc = ConsumeToken();
  844. Res = ParseCastExpression(false);
  845. if (!Res.isInvalid())
  846. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  847. return Res;
  848. }
  849. case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
  850. // __extension__ silences extension warnings in the subexpression.
  851. ExtensionRAIIObject O(Diags); // Use RAII to do this.
  852. SourceLocation SavedLoc = ConsumeToken();
  853. Res = ParseCastExpression(false);
  854. if (!Res.isInvalid())
  855. Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
  856. return Res;
  857. }
  858. case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
  859. if (!getLangOpts().C11)
  860. Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
  861. // fallthrough
  862. case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
  863. case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
  864. // unary-expression: '__alignof' '(' type-name ')'
  865. case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
  866. // unary-expression: 'sizeof' '(' type-name ')'
  867. case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
  868. return ParseUnaryExprOrTypeTraitExpression();
  869. case tok::ampamp: { // unary-expression: '&&' identifier
  870. SourceLocation AmpAmpLoc = ConsumeToken();
  871. if (Tok.isNot(tok::identifier))
  872. return ExprError(Diag(Tok, diag::err_expected_ident));
  873. if (getCurScope()->getFnParent() == 0)
  874. return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
  875. Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
  876. LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
  877. Tok.getLocation());
  878. Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
  879. ConsumeToken();
  880. return Res;
  881. }
  882. case tok::kw_const_cast:
  883. case tok::kw_dynamic_cast:
  884. case tok::kw_reinterpret_cast:
  885. case tok::kw_static_cast:
  886. Res = ParseCXXCasts();
  887. break;
  888. case tok::kw_typeid:
  889. Res = ParseCXXTypeid();
  890. break;
  891. case tok::kw___uuidof:
  892. Res = ParseCXXUuidof();
  893. break;
  894. case tok::kw_this:
  895. Res = ParseCXXThis();
  896. break;
  897. case tok::annot_typename:
  898. if (isStartOfObjCClassMessageMissingOpenBracket()) {
  899. ParsedType Type = getTypeAnnotation(Tok);
  900. // Fake up a Declarator to use with ActOnTypeName.
  901. DeclSpec DS(AttrFactory);
  902. DS.SetRangeStart(Tok.getLocation());
  903. DS.SetRangeEnd(Tok.getLastLoc());
  904. const char *PrevSpec = 0;
  905. unsigned DiagID;
  906. DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
  907. PrevSpec, DiagID, Type);
  908. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  909. TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  910. if (Ty.isInvalid())
  911. break;
  912. ConsumeToken();
  913. Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
  914. Ty.get(), 0);
  915. break;
  916. }
  917. // Fall through
  918. case tok::annot_decltype:
  919. case tok::kw_char:
  920. case tok::kw_wchar_t:
  921. case tok::kw_char16_t:
  922. case tok::kw_char32_t:
  923. case tok::kw_bool:
  924. case tok::kw_short:
  925. case tok::kw_int:
  926. case tok::kw_long:
  927. case tok::kw___int64:
  928. case tok::kw___int128:
  929. case tok::kw_signed:
  930. case tok::kw_unsigned:
  931. case tok::kw_half:
  932. case tok::kw_float:
  933. case tok::kw_double:
  934. case tok::kw_void:
  935. case tok::kw_typename:
  936. case tok::kw_typeof:
  937. case tok::kw___vector: {
  938. if (!getLangOpts().CPlusPlus) {
  939. Diag(Tok, diag::err_expected_expression);
  940. return ExprError();
  941. }
  942. if (SavedKind == tok::kw_typename) {
  943. // postfix-expression: typename-specifier '(' expression-list[opt] ')'
  944. // typename-specifier braced-init-list
  945. if (TryAnnotateTypeOrScopeToken())
  946. return ExprError();
  947. }
  948. // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
  949. // simple-type-specifier braced-init-list
  950. //
  951. DeclSpec DS(AttrFactory);
  952. ParseCXXSimpleTypeSpecifier(DS);
  953. if (Tok.isNot(tok::l_paren) &&
  954. (!getLangOpts().CPlusPlus0x || Tok.isNot(tok::l_brace)))
  955. return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
  956. << DS.getSourceRange());
  957. if (Tok.is(tok::l_brace))
  958. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  959. Res = ParseCXXTypeConstructExpression(DS);
  960. break;
  961. }
  962. case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
  963. // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
  964. // (We can end up in this situation after tentative parsing.)
  965. if (TryAnnotateTypeOrScopeToken())
  966. return ExprError();
  967. if (!Tok.is(tok::annot_cxxscope))
  968. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  969. NotCastExpr, isTypeCast);
  970. Token Next = NextToken();
  971. if (Next.is(tok::annot_template_id)) {
  972. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
  973. if (TemplateId->Kind == TNK_Type_template) {
  974. // We have a qualified template-id that we know refers to a
  975. // type, translate it into a type and continue parsing as a
  976. // cast expression.
  977. CXXScopeSpec SS;
  978. ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
  979. /*EnteringContext=*/false);
  980. AnnotateTemplateIdTokenAsType();
  981. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  982. NotCastExpr, isTypeCast);
  983. }
  984. }
  985. // Parse as an id-expression.
  986. Res = ParseCXXIdExpression(isAddressOfOperand);
  987. break;
  988. }
  989. case tok::annot_template_id: { // [C++] template-id
  990. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
  991. if (TemplateId->Kind == TNK_Type_template) {
  992. // We have a template-id that we know refers to a type,
  993. // translate it into a type and continue parsing as a cast
  994. // expression.
  995. AnnotateTemplateIdTokenAsType();
  996. return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
  997. NotCastExpr, isTypeCast);
  998. }
  999. // Fall through to treat the template-id as an id-expression.
  1000. }
  1001. case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
  1002. Res = ParseCXXIdExpression(isAddressOfOperand);
  1003. break;
  1004. case tok::coloncolon: {
  1005. // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
  1006. // annotates the token, tail recurse.
  1007. if (TryAnnotateTypeOrScopeToken())
  1008. return ExprError();
  1009. if (!Tok.is(tok::coloncolon))
  1010. return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
  1011. // ::new -> [C++] new-expression
  1012. // ::delete -> [C++] delete-expression
  1013. SourceLocation CCLoc = ConsumeToken();
  1014. if (Tok.is(tok::kw_new))
  1015. return ParseCXXNewExpression(true, CCLoc);
  1016. if (Tok.is(tok::kw_delete))
  1017. return ParseCXXDeleteExpression(true, CCLoc);
  1018. // This is not a type name or scope specifier, it is an invalid expression.
  1019. Diag(CCLoc, diag::err_expected_expression);
  1020. return ExprError();
  1021. }
  1022. case tok::kw_new: // [C++] new-expression
  1023. return ParseCXXNewExpression(false, Tok.getLocation());
  1024. case tok::kw_delete: // [C++] delete-expression
  1025. return ParseCXXDeleteExpression(false, Tok.getLocation());
  1026. case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
  1027. Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
  1028. SourceLocation KeyLoc = ConsumeToken();
  1029. BalancedDelimiterTracker T(*this, tok::l_paren);
  1030. if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
  1031. return ExprError();
  1032. // C++11 [expr.unary.noexcept]p1:
  1033. // The noexcept operator determines whether the evaluation of its operand,
  1034. // which is an unevaluated operand, can throw an exception.
  1035. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  1036. ExprResult Result = ParseExpression();
  1037. T.consumeClose();
  1038. if (!Result.isInvalid())
  1039. Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
  1040. Result.take(), T.getCloseLocation());
  1041. return Result;
  1042. }
  1043. case tok::kw___is_abstract: // [GNU] unary-type-trait
  1044. case tok::kw___is_class:
  1045. case tok::kw___is_empty:
  1046. case tok::kw___is_enum:
  1047. case tok::kw___is_literal:
  1048. case tok::kw___is_arithmetic:
  1049. case tok::kw___is_integral:
  1050. case tok::kw___is_floating_point:
  1051. case tok::kw___is_complete_type:
  1052. case tok::kw___is_void:
  1053. case tok::kw___is_array:
  1054. case tok::kw___is_function:
  1055. case tok::kw___is_reference:
  1056. case tok::kw___is_lvalue_reference:
  1057. case tok::kw___is_rvalue_reference:
  1058. case tok::kw___is_fundamental:
  1059. case tok::kw___is_object:
  1060. case tok::kw___is_scalar:
  1061. case tok::kw___is_compound:
  1062. case tok::kw___is_pointer:
  1063. case tok::kw___is_member_object_pointer:
  1064. case tok::kw___is_member_function_pointer:
  1065. case tok::kw___is_member_pointer:
  1066. case tok::kw___is_const:
  1067. case tok::kw___is_volatile:
  1068. case tok::kw___is_standard_layout:
  1069. case tok::kw___is_signed:
  1070. case tok::kw___is_unsigned:
  1071. case tok::kw___is_literal_type:
  1072. case tok::kw___is_pod:
  1073. case tok::kw___is_polymorphic:
  1074. case tok::kw___is_trivial:
  1075. case tok::kw___is_trivially_copyable:
  1076. case tok::kw___is_union:
  1077. case tok::kw___is_final:
  1078. case tok::kw___has_trivial_constructor:
  1079. case tok::kw___has_trivial_copy:
  1080. case tok::kw___has_trivial_assign:
  1081. case tok::kw___has_trivial_destructor:
  1082. case tok::kw___has_nothrow_assign:
  1083. case tok::kw___has_nothrow_copy:
  1084. case tok::kw___has_nothrow_constructor:
  1085. case tok::kw___has_virtual_destructor:
  1086. return ParseUnaryTypeTrait();
  1087. case tok::kw___builtin_types_compatible_p:
  1088. case tok::kw___is_base_of:
  1089. case tok::kw___is_same:
  1090. case tok::kw___is_convertible:
  1091. case tok::kw___is_convertible_to:
  1092. case tok::kw___is_trivially_assignable:
  1093. return ParseBinaryTypeTrait();
  1094. case tok::kw___is_trivially_constructible:
  1095. return ParseTypeTrait();
  1096. case tok::kw___array_rank:
  1097. case tok::kw___array_extent:
  1098. return ParseArrayTypeTrait();
  1099. case tok::kw___is_lvalue_expr:
  1100. case tok::kw___is_rvalue_expr:
  1101. return ParseExpressionTrait();
  1102. case tok::at: {
  1103. SourceLocation AtLoc = ConsumeToken();
  1104. return ParseObjCAtExpression(AtLoc);
  1105. }
  1106. case tok::caret:
  1107. Res = ParseBlockLiteralExpression();
  1108. break;
  1109. case tok::code_completion: {
  1110. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
  1111. cutOffParsing();
  1112. return ExprError();
  1113. }
  1114. case tok::l_square:
  1115. if (getLangOpts().CPlusPlus0x) {
  1116. if (getLangOpts().ObjC1) {
  1117. // C++11 lambda expressions and Objective-C message sends both start with a
  1118. // square bracket. There are three possibilities here:
  1119. // we have a valid lambda expression, we have an invalid lambda
  1120. // expression, or we have something that doesn't appear to be a lambda.
  1121. // If we're in the last case, we fall back to ParseObjCMessageExpression.
  1122. Res = TryParseLambdaExpression();
  1123. if (!Res.isInvalid() && !Res.get())
  1124. Res = ParseObjCMessageExpression();
  1125. break;
  1126. }
  1127. Res = ParseLambdaExpression();
  1128. break;
  1129. }
  1130. if (getLangOpts().ObjC1) {
  1131. Res = ParseObjCMessageExpression();
  1132. break;
  1133. }
  1134. // FALL THROUGH.
  1135. default:
  1136. NotCastExpr = true;
  1137. return ExprError();
  1138. }
  1139. // These can be followed by postfix-expr pieces.
  1140. return ParsePostfixExpressionSuffix(Res);
  1141. }
  1142. /// \brief Once the leading part of a postfix-expression is parsed, this
  1143. /// method parses any suffixes that apply.
  1144. ///
  1145. /// \verbatim
  1146. /// postfix-expression: [C99 6.5.2]
  1147. /// primary-expression
  1148. /// postfix-expression '[' expression ']'
  1149. /// postfix-expression '[' braced-init-list ']'
  1150. /// postfix-expression '(' argument-expression-list[opt] ')'
  1151. /// postfix-expression '.' identifier
  1152. /// postfix-expression '->' identifier
  1153. /// postfix-expression '++'
  1154. /// postfix-expression '--'
  1155. /// '(' type-name ')' '{' initializer-list '}'
  1156. /// '(' type-name ')' '{' initializer-list ',' '}'
  1157. ///
  1158. /// argument-expression-list: [C99 6.5.2]
  1159. /// argument-expression ...[opt]
  1160. /// argument-expression-list ',' assignment-expression ...[opt]
  1161. /// \endverbatim
  1162. ExprResult
  1163. Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
  1164. // Now that the primary-expression piece of the postfix-expression has been
  1165. // parsed, see if there are any postfix-expression pieces here.
  1166. SourceLocation Loc;
  1167. while (1) {
  1168. switch (Tok.getKind()) {
  1169. case tok::code_completion:
  1170. if (InMessageExpression)
  1171. return LHS;
  1172. Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
  1173. cutOffParsing();
  1174. return ExprError();
  1175. case tok::identifier:
  1176. // If we see identifier: after an expression, and we're not already in a
  1177. // message send, then this is probably a message send with a missing
  1178. // opening bracket '['.
  1179. if (getLangOpts().ObjC1 && !InMessageExpression &&
  1180. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
  1181. LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
  1182. ParsedType(), LHS.get());
  1183. break;
  1184. }
  1185. // Fall through; this isn't a message send.
  1186. default: // Not a postfix-expression suffix.
  1187. return LHS;
  1188. case tok::l_square: { // postfix-expression: p-e '[' expression ']'
  1189. // If we have a array postfix expression that starts on a new line and
  1190. // Objective-C is enabled, it is highly likely that the user forgot a
  1191. // semicolon after the base expression and that the array postfix-expr is
  1192. // actually another message send. In this case, do some look-ahead to see
  1193. // if the contents of the square brackets are obviously not a valid
  1194. // expression and recover by pretending there is no suffix.
  1195. if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
  1196. isSimpleObjCMessageExpression())
  1197. return LHS;
  1198. // Reject array indices starting with a lambda-expression. '[[' is
  1199. // reserved for attributes.
  1200. if (CheckProhibitedCXX11Attribute())
  1201. return ExprError();
  1202. BalancedDelimiterTracker T(*this, tok::l_square);
  1203. T.consumeOpen();
  1204. Loc = T.getOpenLocation();
  1205. ExprResult Idx;
  1206. if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
  1207. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  1208. Idx = ParseBraceInitializer();
  1209. } else
  1210. Idx = ParseExpression();
  1211. SourceLocation RLoc = Tok.getLocation();
  1212. if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
  1213. LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc,
  1214. Idx.take(), RLoc);
  1215. } else
  1216. LHS = ExprError();
  1217. // Match the ']'.
  1218. T.consumeClose();
  1219. break;
  1220. }
  1221. case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
  1222. case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
  1223. // '(' argument-expression-list[opt] ')'
  1224. tok::TokenKind OpKind = Tok.getKind();
  1225. InMessageExpressionRAIIObject InMessage(*this, false);
  1226. Expr *ExecConfig = 0;
  1227. BalancedDelimiterTracker PT(*this, tok::l_paren);
  1228. if (OpKind == tok::lesslessless) {
  1229. ExprVector ExecConfigExprs(Actions);
  1230. CommaLocsTy ExecConfigCommaLocs;
  1231. SourceLocation OpenLoc = ConsumeToken();
  1232. if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
  1233. LHS = ExprError();
  1234. }
  1235. SourceLocation CloseLoc = Tok.getLocation();
  1236. if (Tok.is(tok::greatergreatergreater)) {
  1237. ConsumeToken();
  1238. } else if (LHS.isInvalid()) {
  1239. SkipUntil(tok::greatergreatergreater);
  1240. } else {
  1241. // There was an error closing the brackets
  1242. Diag(Tok, diag::err_expected_ggg);
  1243. Diag(OpenLoc, diag::note_matching) << "<<<";
  1244. SkipUntil(tok::greatergreatergreater);
  1245. LHS = ExprError();
  1246. }
  1247. if (!LHS.isInvalid()) {
  1248. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, ""))
  1249. LHS = ExprError();
  1250. else
  1251. Loc = PrevTokLocation;
  1252. }
  1253. if (!LHS.isInvalid()) {
  1254. ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
  1255. OpenLoc,
  1256. ExecConfigExprs,
  1257. CloseLoc);
  1258. if (ECResult.isInvalid())
  1259. LHS = ExprError();
  1260. else
  1261. ExecConfig = ECResult.get();
  1262. }
  1263. } else {
  1264. PT.consumeOpen();
  1265. Loc = PT.getOpenLocation();
  1266. }
  1267. ExprVector ArgExprs(Actions);
  1268. CommaLocsTy CommaLocs;
  1269. if (Tok.is(tok::code_completion)) {
  1270. Actions.CodeCompleteCall(getCurScope(), LHS.get(),
  1271. llvm::ArrayRef<Expr *>());
  1272. cutOffParsing();
  1273. return ExprError();
  1274. }
  1275. if (OpKind == tok::l_paren || !LHS.isInvalid()) {
  1276. if (Tok.isNot(tok::r_paren)) {
  1277. if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall,
  1278. LHS.get())) {
  1279. LHS = ExprError();
  1280. }
  1281. }
  1282. }
  1283. // Match the ')'.
  1284. if (LHS.isInvalid()) {
  1285. SkipUntil(tok::r_paren);
  1286. } else if (Tok.isNot(tok::r_paren)) {
  1287. PT.consumeClose();
  1288. LHS = ExprError();
  1289. } else {
  1290. assert((ArgExprs.size() == 0 ||
  1291. ArgExprs.size()-1 == CommaLocs.size())&&
  1292. "Unexpected number of commas!");
  1293. LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc,
  1294. ArgExprs, Tok.getLocation(),
  1295. ExecConfig);
  1296. PT.consumeClose();
  1297. }
  1298. break;
  1299. }
  1300. case tok::arrow:
  1301. case tok::period: {
  1302. // postfix-expression: p-e '->' template[opt] id-expression
  1303. // postfix-expression: p-e '.' template[opt] id-expression
  1304. tok::TokenKind OpKind = Tok.getKind();
  1305. SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
  1306. CXXScopeSpec SS;
  1307. ParsedType ObjectType;
  1308. bool MayBePseudoDestructor = false;
  1309. if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
  1310. LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(),
  1311. OpLoc, OpKind, ObjectType,
  1312. MayBePseudoDestructor);
  1313. if (LHS.isInvalid())
  1314. break;
  1315. ParseOptionalCXXScopeSpecifier(SS, ObjectType,
  1316. /*EnteringContext=*/false,
  1317. &MayBePseudoDestructor);
  1318. if (SS.isNotEmpty())
  1319. ObjectType = ParsedType();
  1320. }
  1321. if (Tok.is(tok::code_completion)) {
  1322. // Code completion for a member access expression.
  1323. Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
  1324. OpLoc, OpKind == tok::arrow);
  1325. cutOffParsing();
  1326. return ExprError();
  1327. }
  1328. if (MayBePseudoDestructor && !LHS.isInvalid()) {
  1329. LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS,
  1330. ObjectType);
  1331. break;
  1332. }
  1333. // Either the action has told is that this cannot be a
  1334. // pseudo-destructor expression (based on the type of base
  1335. // expression), or we didn't see a '~' in the right place. We
  1336. // can still parse a destructor name here, but in that case it
  1337. // names a real destructor.
  1338. // Allow explicit constructor calls in Microsoft mode.
  1339. // FIXME: Add support for explicit call of template constructor.
  1340. SourceLocation TemplateKWLoc;
  1341. UnqualifiedId Name;
  1342. if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) {
  1343. // Objective-C++:
  1344. // After a '.' in a member access expression, treat the keyword
  1345. // 'class' as if it were an identifier.
  1346. //
  1347. // This hack allows property access to the 'class' method because it is
  1348. // such a common method name. For other C++ keywords that are
  1349. // Objective-C method names, one must use the message send syntax.
  1350. IdentifierInfo *Id = Tok.getIdentifierInfo();
  1351. SourceLocation Loc = ConsumeToken();
  1352. Name.setIdentifier(Id, Loc);
  1353. } else if (ParseUnqualifiedId(SS,
  1354. /*EnteringContext=*/false,
  1355. /*AllowDestructorName=*/true,
  1356. /*AllowConstructorName=*/
  1357. getLangOpts().MicrosoftExt,
  1358. ObjectType, TemplateKWLoc, Name))
  1359. LHS = ExprError();
  1360. if (!LHS.isInvalid())
  1361. LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc,
  1362. OpKind, SS, TemplateKWLoc, Name,
  1363. CurParsedObjCImpl ? CurParsedObjCImpl->Dcl : 0,
  1364. Tok.is(tok::l_paren));
  1365. break;
  1366. }
  1367. case tok::plusplus: // postfix-expression: postfix-expression '++'
  1368. case tok::minusminus: // postfix-expression: postfix-expression '--'
  1369. if (!LHS.isInvalid()) {
  1370. LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
  1371. Tok.getKind(), LHS.take());
  1372. }
  1373. ConsumeToken();
  1374. break;
  1375. }
  1376. }
  1377. }
  1378. /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
  1379. /// vec_step and we are at the start of an expression or a parenthesized
  1380. /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
  1381. /// expression (isCastExpr == false) or the type (isCastExpr == true).
  1382. ///
  1383. /// \verbatim
  1384. /// unary-expression: [C99 6.5.3]
  1385. /// 'sizeof' unary-expression
  1386. /// 'sizeof' '(' type-name ')'
  1387. /// [GNU] '__alignof' unary-expression
  1388. /// [GNU] '__alignof' '(' type-name ')'
  1389. /// [C11] '_Alignof' '(' type-name ')'
  1390. /// [C++0x] 'alignof' '(' type-id ')'
  1391. ///
  1392. /// [GNU] typeof-specifier:
  1393. /// typeof ( expressions )
  1394. /// typeof ( type-name )
  1395. /// [GNU/C++] typeof unary-expression
  1396. ///
  1397. /// [OpenCL 1.1 6.11.12] vec_step built-in function:
  1398. /// vec_step ( expressions )
  1399. /// vec_step ( type-name )
  1400. /// \endverbatim
  1401. ExprResult
  1402. Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
  1403. bool &isCastExpr,
  1404. ParsedType &CastTy,
  1405. SourceRange &CastRange) {
  1406. assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) ||
  1407. OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) ||
  1408. OpTok.is(tok::kw__Alignof) || OpTok.is(tok::kw_vec_step)) &&
  1409. "Not a typeof/sizeof/alignof/vec_step expression!");
  1410. ExprResult Operand;
  1411. // If the operand doesn't start with an '(', it must be an expression.
  1412. if (Tok.isNot(tok::l_paren)) {
  1413. isCastExpr = false;
  1414. if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
  1415. Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo();
  1416. return ExprError();
  1417. }
  1418. Operand = ParseCastExpression(true/*isUnaryExpression*/);
  1419. } else {
  1420. // If it starts with a '(', we know that it is either a parenthesized
  1421. // type-name, or it is a unary-expression that starts with a compound
  1422. // literal, or starts with a primary-expression that is a parenthesized
  1423. // expression.
  1424. ParenParseOption ExprType = CastExpr;
  1425. SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
  1426. Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
  1427. false, CastTy, RParenLoc);
  1428. CastRange = SourceRange(LParenLoc, RParenLoc);
  1429. // If ParseParenExpression parsed a '(typename)' sequence only, then this is
  1430. // a type.
  1431. if (ExprType == CastExpr) {
  1432. isCastExpr = true;
  1433. return ExprEmpty();
  1434. }
  1435. if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
  1436. // GNU typeof in C requires the expression to be parenthesized. Not so for
  1437. // sizeof/alignof or in C++. Therefore, the parenthesized expression is
  1438. // the start of a unary-expression, but doesn't include any postfix
  1439. // pieces. Parse these now if present.
  1440. if (!Operand.isInvalid())
  1441. Operand = ParsePostfixExpressionSuffix(Operand.get());
  1442. }
  1443. }
  1444. // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
  1445. isCastExpr = false;
  1446. return Operand;
  1447. }
  1448. /// \brief Parse a sizeof or alignof expression.
  1449. ///
  1450. /// \verbatim
  1451. /// unary-expression: [C99 6.5.3]
  1452. /// 'sizeof' unary-expression
  1453. /// 'sizeof' '(' type-name ')'
  1454. /// [C++0x] 'sizeof' '...' '(' identifier ')'
  1455. /// [GNU] '__alignof' unary-expression
  1456. /// [GNU] '__alignof' '(' type-name ')'
  1457. /// [C11] '_Alignof' '(' type-name ')'
  1458. /// [C++0x] 'alignof' '(' type-id ')'
  1459. /// \endverbatim
  1460. ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
  1461. assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) ||
  1462. Tok.is(tok::kw_alignof) || Tok.is(tok::kw__Alignof) ||
  1463. Tok.is(tok::kw_vec_step)) &&
  1464. "Not a sizeof/alignof/vec_step expression!");
  1465. Token OpTok = Tok;
  1466. ConsumeToken();
  1467. // [C++0x] 'sizeof' '...' '(' identifier ')'
  1468. if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
  1469. SourceLocation EllipsisLoc = ConsumeToken();
  1470. SourceLocation LParenLoc, RParenLoc;
  1471. IdentifierInfo *Name = 0;
  1472. SourceLocation NameLoc;
  1473. if (Tok.is(tok::l_paren)) {
  1474. BalancedDelimiterTracker T(*this, tok::l_paren);
  1475. T.consumeOpen();
  1476. LParenLoc = T.getOpenLocation();
  1477. if (Tok.is(tok::identifier)) {
  1478. Name = Tok.getIdentifierInfo();
  1479. NameLoc = ConsumeToken();
  1480. T.consumeClose();
  1481. RParenLoc = T.getCloseLocation();
  1482. if (RParenLoc.isInvalid())
  1483. RParenLoc = PP.getLocForEndOfToken(NameLoc);
  1484. } else {
  1485. Diag(Tok, diag::err_expected_parameter_pack);
  1486. SkipUntil(tok::r_paren);
  1487. }
  1488. } else if (Tok.is(tok::identifier)) {
  1489. Name = Tok.getIdentifierInfo();
  1490. NameLoc = ConsumeToken();
  1491. LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
  1492. RParenLoc = PP.getLocForEndOfToken(NameLoc);
  1493. Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
  1494. << Name
  1495. << FixItHint::CreateInsertion(LParenLoc, "(")
  1496. << FixItHint::CreateInsertion(RParenLoc, ")");
  1497. } else {
  1498. Diag(Tok, diag::err_sizeof_parameter_pack);
  1499. }
  1500. if (!Name)
  1501. return ExprError();
  1502. return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
  1503. OpTok.getLocation(),
  1504. *Name, NameLoc,
  1505. RParenLoc);
  1506. }
  1507. if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof))
  1508. Diag(OpTok, diag::warn_cxx98_compat_alignof);
  1509. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  1510. bool isCastExpr;
  1511. ParsedType CastTy;
  1512. SourceRange CastRange;
  1513. ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
  1514. isCastExpr,
  1515. CastTy,
  1516. CastRange);
  1517. UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
  1518. if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof) ||
  1519. OpTok.is(tok::kw__Alignof))
  1520. ExprKind = UETT_AlignOf;
  1521. else if (OpTok.is(tok::kw_vec_step))
  1522. ExprKind = UETT_VecStep;
  1523. if (isCastExpr)
  1524. return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
  1525. ExprKind,
  1526. /*isType=*/true,
  1527. CastTy.getAsOpaquePtr(),
  1528. CastRange);
  1529. // If we get here, the operand to the sizeof/alignof was an expresion.
  1530. if (!Operand.isInvalid())
  1531. Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
  1532. ExprKind,
  1533. /*isType=*/false,
  1534. Operand.release(),
  1535. CastRange);
  1536. return Operand;
  1537. }
  1538. /// ParseBuiltinPrimaryExpression
  1539. ///
  1540. /// \verbatim
  1541. /// primary-expression: [C99 6.5.1]
  1542. /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
  1543. /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
  1544. /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
  1545. /// assign-expr ')'
  1546. /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
  1547. /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
  1548. ///
  1549. /// [GNU] offsetof-member-designator:
  1550. /// [GNU] identifier
  1551. /// [GNU] offsetof-member-designator '.' identifier
  1552. /// [GNU] offsetof-member-designator '[' expression ']'
  1553. /// \endverbatim
  1554. ExprResult Parser::ParseBuiltinPrimaryExpression() {
  1555. ExprResult Res;
  1556. const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
  1557. tok::TokenKind T = Tok.getKind();
  1558. SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
  1559. // All of these start with an open paren.
  1560. if (Tok.isNot(tok::l_paren))
  1561. return ExprError(Diag(Tok, diag::err_expected_lparen_after_id)
  1562. << BuiltinII);
  1563. BalancedDelimiterTracker PT(*this, tok::l_paren);
  1564. PT.consumeOpen();
  1565. // TODO: Build AST.
  1566. switch (T) {
  1567. default: llvm_unreachable("Not a builtin primary expression!");
  1568. case tok::kw___builtin_va_arg: {
  1569. ExprResult Expr(ParseAssignmentExpression());
  1570. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
  1571. Expr = ExprError();
  1572. TypeResult Ty = ParseTypeName();
  1573. if (Tok.isNot(tok::r_paren)) {
  1574. Diag(Tok, diag::err_expected_rparen);
  1575. Expr = ExprError();
  1576. }
  1577. if (Expr.isInvalid() || Ty.isInvalid())
  1578. Res = ExprError();
  1579. else
  1580. Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen());
  1581. break;
  1582. }
  1583. case tok::kw___builtin_offsetof: {
  1584. SourceLocation TypeLoc = Tok.getLocation();
  1585. TypeResult Ty = ParseTypeName();
  1586. if (Ty.isInvalid()) {
  1587. SkipUntil(tok::r_paren);
  1588. return ExprError();
  1589. }
  1590. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
  1591. return ExprError();
  1592. // We must have at least one identifier here.
  1593. if (Tok.isNot(tok::identifier)) {
  1594. Diag(Tok, diag::err_expected_ident);
  1595. SkipUntil(tok::r_paren);
  1596. return ExprError();
  1597. }
  1598. // Keep track of the various subcomponents we see.
  1599. SmallVector<Sema::OffsetOfComponent, 4> Comps;
  1600. Comps.push_back(Sema::OffsetOfComponent());
  1601. Comps.back().isBrackets = false;
  1602. Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
  1603. Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
  1604. // FIXME: This loop leaks the index expressions on error.
  1605. while (1) {
  1606. if (Tok.is(tok::period)) {
  1607. // offsetof-member-designator: offsetof-member-designator '.' identifier
  1608. Comps.push_back(Sema::OffsetOfComponent());
  1609. Comps.back().isBrackets = false;
  1610. Comps.back().LocStart = ConsumeToken();
  1611. if (Tok.isNot(tok::identifier)) {
  1612. Diag(Tok, diag::err_expected_ident);
  1613. SkipUntil(tok::r_paren);
  1614. return ExprError();
  1615. }
  1616. Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
  1617. Comps.back().LocEnd = ConsumeToken();
  1618. } else if (Tok.is(tok::l_square)) {
  1619. if (CheckProhibitedCXX11Attribute())
  1620. return ExprError();
  1621. // offsetof-member-designator: offsetof-member-design '[' expression ']'
  1622. Comps.push_back(Sema::OffsetOfComponent());
  1623. Comps.back().isBrackets = true;
  1624. BalancedDelimiterTracker ST(*this, tok::l_square);
  1625. ST.consumeOpen();
  1626. Comps.back().LocStart = ST.getOpenLocation();
  1627. Res = ParseExpression();
  1628. if (Res.isInvalid()) {
  1629. SkipUntil(tok::r_paren);
  1630. return Res;
  1631. }
  1632. Comps.back().U.E = Res.release();
  1633. ST.consumeClose();
  1634. Comps.back().LocEnd = ST.getCloseLocation();
  1635. } else {
  1636. if (Tok.isNot(tok::r_paren)) {
  1637. PT.consumeClose();
  1638. Res = ExprError();
  1639. } else if (Ty.isInvalid()) {
  1640. Res = ExprError();
  1641. } else {
  1642. PT.consumeClose();
  1643. Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
  1644. Ty.get(), &Comps[0], Comps.size(),
  1645. PT.getCloseLocation());
  1646. }
  1647. break;
  1648. }
  1649. }
  1650. break;
  1651. }
  1652. case tok::kw___builtin_choose_expr: {
  1653. ExprResult Cond(ParseAssignmentExpression());
  1654. if (Cond.isInvalid()) {
  1655. SkipUntil(tok::r_paren);
  1656. return Cond;
  1657. }
  1658. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
  1659. return ExprError();
  1660. ExprResult Expr1(ParseAssignmentExpression());
  1661. if (Expr1.isInvalid()) {
  1662. SkipUntil(tok::r_paren);
  1663. return Expr1;
  1664. }
  1665. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
  1666. return ExprError();
  1667. ExprResult Expr2(ParseAssignmentExpression());
  1668. if (Expr2.isInvalid()) {
  1669. SkipUntil(tok::r_paren);
  1670. return Expr2;
  1671. }
  1672. if (Tok.isNot(tok::r_paren)) {
  1673. Diag(Tok, diag::err_expected_rparen);
  1674. return ExprError();
  1675. }
  1676. Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(),
  1677. Expr2.take(), ConsumeParen());
  1678. break;
  1679. }
  1680. case tok::kw___builtin_astype: {
  1681. // The first argument is an expression to be converted, followed by a comma.
  1682. ExprResult Expr(ParseAssignmentExpression());
  1683. if (Expr.isInvalid()) {
  1684. SkipUntil(tok::r_paren);
  1685. return ExprError();
  1686. }
  1687. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",
  1688. tok::r_paren))
  1689. return ExprError();
  1690. // Second argument is the type to bitcast to.
  1691. TypeResult DestTy = ParseTypeName();
  1692. if (DestTy.isInvalid())
  1693. return ExprError();
  1694. // Attempt to consume the r-paren.
  1695. if (Tok.isNot(tok::r_paren)) {
  1696. Diag(Tok, diag::err_expected_rparen);
  1697. SkipUntil(tok::r_paren);
  1698. return ExprError();
  1699. }
  1700. Res = Actions.ActOnAsTypeExpr(Expr.take(), DestTy.get(), StartLoc,
  1701. ConsumeParen());
  1702. break;
  1703. }
  1704. }
  1705. if (Res.isInvalid())
  1706. return ExprError();
  1707. // These can be followed by postfix-expr pieces because they are
  1708. // primary-expressions.
  1709. return ParsePostfixExpressionSuffix(Res.take());
  1710. }
  1711. /// ParseParenExpression - This parses the unit that starts with a '(' token,
  1712. /// based on what is allowed by ExprType. The actual thing parsed is returned
  1713. /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
  1714. /// not the parsed cast-expression.
  1715. ///
  1716. /// \verbatim
  1717. /// primary-expression: [C99 6.5.1]
  1718. /// '(' expression ')'
  1719. /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
  1720. /// postfix-expression: [C99 6.5.2]
  1721. /// '(' type-name ')' '{' initializer-list '}'
  1722. /// '(' type-name ')' '{' initializer-list ',' '}'
  1723. /// cast-expression: [C99 6.5.4]
  1724. /// '(' type-name ')' cast-expression
  1725. /// [ARC] bridged-cast-expression
  1726. ///
  1727. /// [ARC] bridged-cast-expression:
  1728. /// (__bridge type-name) cast-expression
  1729. /// (__bridge_transfer type-name) cast-expression
  1730. /// (__bridge_retained type-name) cast-expression
  1731. /// \endverbatim
  1732. ExprResult
  1733. Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
  1734. bool isTypeCast, ParsedType &CastTy,
  1735. SourceLocation &RParenLoc) {
  1736. assert(Tok.is(tok::l_paren) && "Not a paren expr!");
  1737. BalancedDelimiterTracker T(*this, tok::l_paren);
  1738. if (T.consumeOpen())
  1739. return ExprError();
  1740. SourceLocation OpenLoc = T.getOpenLocation();
  1741. ExprResult Result(true);
  1742. bool isAmbiguousTypeId;
  1743. CastTy = ParsedType();
  1744. if (Tok.is(tok::code_completion)) {
  1745. Actions.CodeCompleteOrdinaryName(getCurScope(),
  1746. ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
  1747. : Sema::PCC_Expression);
  1748. cutOffParsing();
  1749. return ExprError();
  1750. }
  1751. // Diagnose use of bridge casts in non-arc mode.
  1752. bool BridgeCast = (getLangOpts().ObjC2 &&
  1753. (Tok.is(tok::kw___bridge) ||
  1754. Tok.is(tok::kw___bridge_transfer) ||
  1755. Tok.is(tok::kw___bridge_retained) ||
  1756. Tok.is(tok::kw___bridge_retain)));
  1757. if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
  1758. StringRef BridgeCastName = Tok.getName();
  1759. SourceLocation BridgeKeywordLoc = ConsumeToken();
  1760. if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
  1761. Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
  1762. << BridgeCastName
  1763. << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
  1764. BridgeCast = false;
  1765. }
  1766. // None of these cases should fall through with an invalid Result
  1767. // unless they've already reported an error.
  1768. if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
  1769. Diag(Tok, diag::ext_gnu_statement_expr);
  1770. Actions.ActOnStartStmtExpr();
  1771. StmtResult Stmt(ParseCompoundStatement(true));
  1772. ExprType = CompoundStmt;
  1773. // If the substmt parsed correctly, build the AST node.
  1774. if (!Stmt.isInvalid()) {
  1775. Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation());
  1776. } else {
  1777. Actions.ActOnStmtExprError();
  1778. }
  1779. } else if (ExprType >= CompoundLiteral && BridgeCast) {
  1780. tok::TokenKind tokenKind = Tok.getKind();
  1781. SourceLocation BridgeKeywordLoc = ConsumeToken();
  1782. // Parse an Objective-C ARC ownership cast expression.
  1783. ObjCBridgeCastKind Kind;
  1784. if (tokenKind == tok::kw___bridge)
  1785. Kind = OBC_Bridge;
  1786. else if (tokenKind == tok::kw___bridge_transfer)
  1787. Kind = OBC_BridgeTransfer;
  1788. else if (tokenKind == tok::kw___bridge_retained)
  1789. Kind = OBC_BridgeRetained;
  1790. else {
  1791. // As a hopefully temporary workaround, allow __bridge_retain as
  1792. // a synonym for __bridge_retained, but only in system headers.
  1793. assert(tokenKind == tok::kw___bridge_retain);
  1794. Kind = OBC_BridgeRetained;
  1795. if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
  1796. Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
  1797. << FixItHint::CreateReplacement(BridgeKeywordLoc,
  1798. "__bridge_retained");
  1799. }
  1800. TypeResult Ty = ParseTypeName();
  1801. T.consumeClose();
  1802. RParenLoc = T.getCloseLocation();
  1803. ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
  1804. if (Ty.isInvalid() || SubExpr.isInvalid())
  1805. return ExprError();
  1806. return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
  1807. BridgeKeywordLoc, Ty.get(),
  1808. RParenLoc, SubExpr.get());
  1809. } else if (ExprType >= CompoundLiteral &&
  1810. isTypeIdInParens(isAmbiguousTypeId)) {
  1811. // Otherwise, this is a compound literal expression or cast expression.
  1812. // In C++, if the type-id is ambiguous we disambiguate based on context.
  1813. // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
  1814. // in which case we should treat it as type-id.
  1815. // if stopIfCastExpr is false, we need to determine the context past the
  1816. // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
  1817. if (isAmbiguousTypeId && !stopIfCastExpr) {
  1818. ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T);
  1819. RParenLoc = T.getCloseLocation();
  1820. return res;
  1821. }
  1822. // Parse the type declarator.
  1823. DeclSpec DS(AttrFactory);
  1824. ParseSpecifierQualifierList(DS);
  1825. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
  1826. ParseDeclarator(DeclaratorInfo);
  1827. // If our type is followed by an identifier and either ':' or ']', then
  1828. // this is probably an Objective-C message send where the leading '[' is
  1829. // missing. Recover as if that were the case.
  1830. if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
  1831. !InMessageExpression && getLangOpts().ObjC1 &&
  1832. (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
  1833. TypeResult Ty;
  1834. {
  1835. InMessageExpressionRAIIObject InMessage(*this, false);
  1836. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  1837. }
  1838. Result = ParseObjCMessageExpressionBody(SourceLocation(),
  1839. SourceLocation(),
  1840. Ty.get(), 0);
  1841. } else {
  1842. // Match the ')'.
  1843. T.consumeClose();
  1844. RParenLoc = T.getCloseLocation();
  1845. if (Tok.is(tok::l_brace)) {
  1846. ExprType = CompoundLiteral;
  1847. TypeResult Ty;
  1848. {
  1849. InMessageExpressionRAIIObject InMessage(*this, false);
  1850. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  1851. }
  1852. return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
  1853. }
  1854. if (ExprType == CastExpr) {
  1855. // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
  1856. if (DeclaratorInfo.isInvalidType())
  1857. return ExprError();
  1858. // Note that this doesn't parse the subsequent cast-expression, it just
  1859. // returns the parsed type to the callee.
  1860. if (stopIfCastExpr) {
  1861. TypeResult Ty;
  1862. {
  1863. InMessageExpressionRAIIObject InMessage(*this, false);
  1864. Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
  1865. }
  1866. CastTy = Ty.get();
  1867. return ExprResult();
  1868. }
  1869. // Reject the cast of super idiom in ObjC.
  1870. if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
  1871. Tok.getIdentifierInfo() == Ident_super &&
  1872. getCurScope()->isInObjcMethodScope() &&
  1873. GetLookAheadToken(1).isNot(tok::period)) {
  1874. Diag(Tok.getLocation(), diag::err_illegal_super_cast)
  1875. << SourceRange(OpenLoc, RParenLoc);
  1876. return ExprError();
  1877. }
  1878. // Parse the cast-expression that follows it next.
  1879. // TODO: For cast expression with CastTy.
  1880. Result = ParseCastExpression(/*isUnaryExpression=*/false,
  1881. /*isAddressOfOperand=*/false,
  1882. /*isTypeCast=*/IsTypeCast);
  1883. if (!Result.isInvalid()) {
  1884. Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
  1885. DeclaratorInfo, CastTy,
  1886. RParenLoc, Result.take());
  1887. }
  1888. return Result;
  1889. }
  1890. Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
  1891. return ExprError();
  1892. }
  1893. } else if (isTypeCast) {
  1894. // Parse the expression-list.
  1895. InMessageExpressionRAIIObject InMessage(*this, false);
  1896. ExprVector ArgExprs(Actions);
  1897. CommaLocsTy CommaLocs;
  1898. if (!ParseExpressionList(ArgExprs, CommaLocs)) {
  1899. ExprType = SimpleExpr;
  1900. Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
  1901. ArgExprs);
  1902. }
  1903. } else {
  1904. InMessageExpressionRAIIObject InMessage(*this, false);
  1905. Result = ParseExpression(MaybeTypeCast);
  1906. ExprType = SimpleExpr;
  1907. // Don't build a paren expression unless we actually match a ')'.
  1908. if (!Result.isInvalid() && Tok.is(tok::r_paren))
  1909. Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take());
  1910. }
  1911. // Match the ')'.
  1912. if (Result.isInvalid()) {
  1913. SkipUntil(tok::r_paren);
  1914. return ExprError();
  1915. }
  1916. T.consumeClose();
  1917. RParenLoc = T.getCloseLocation();
  1918. return Result;
  1919. }
  1920. /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
  1921. /// and we are at the left brace.
  1922. ///
  1923. /// \verbatim
  1924. /// postfix-expression: [C99 6.5.2]
  1925. /// '(' type-name ')' '{' initializer-list '}'
  1926. /// '(' type-name ')' '{' initializer-list ',' '}'
  1927. /// \endverbatim
  1928. ExprResult
  1929. Parser::ParseCompoundLiteralExpression(ParsedType Ty,
  1930. SourceLocation LParenLoc,
  1931. SourceLocation RParenLoc) {
  1932. assert(Tok.is(tok::l_brace) && "Not a compound literal!");
  1933. if (!getLangOpts().C99) // Compound literals don't exist in C90.
  1934. Diag(LParenLoc, diag::ext_c99_compound_literal);
  1935. ExprResult Result = ParseInitializer();
  1936. if (!Result.isInvalid() && Ty)
  1937. return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take());
  1938. return Result;
  1939. }
  1940. /// ParseStringLiteralExpression - This handles the various token types that
  1941. /// form string literals, and also handles string concatenation [C99 5.1.1.2,
  1942. /// translation phase #6].
  1943. ///
  1944. /// \verbatim
  1945. /// primary-expression: [C99 6.5.1]
  1946. /// string-literal
  1947. /// \verbatim
  1948. ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
  1949. assert(isTokenStringLiteral() && "Not a string literal!");
  1950. // String concat. Note that keywords like __func__ and __FUNCTION__ are not
  1951. // considered to be strings for concatenation purposes.
  1952. SmallVector<Token, 4> StringToks;
  1953. do {
  1954. StringToks.push_back(Tok);
  1955. ConsumeStringToken();
  1956. } while (isTokenStringLiteral());
  1957. // Pass the set of string tokens, ready for concatenation, to the actions.
  1958. return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size(),
  1959. AllowUserDefinedLiteral ? getCurScope() : 0);
  1960. }
  1961. /// ParseGenericSelectionExpression - Parse a C11 generic-selection
  1962. /// [C11 6.5.1.1].
  1963. ///
  1964. /// \verbatim
  1965. /// generic-selection:
  1966. /// _Generic ( assignment-expression , generic-assoc-list )
  1967. /// generic-assoc-list:
  1968. /// generic-association
  1969. /// generic-assoc-list , generic-association
  1970. /// generic-association:
  1971. /// type-name : assignment-expression
  1972. /// default : assignment-expression
  1973. /// \endverbatim
  1974. ExprResult Parser::ParseGenericSelectionExpression() {
  1975. assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
  1976. SourceLocation KeyLoc = ConsumeToken();
  1977. if (!getLangOpts().C11)
  1978. Diag(KeyLoc, diag::ext_c11_generic_selection);
  1979. BalancedDelimiterTracker T(*this, tok::l_paren);
  1980. if (T.expectAndConsume(diag::err_expected_lparen))
  1981. return ExprError();
  1982. ExprResult ControllingExpr;
  1983. {
  1984. // C11 6.5.1.1p3 "The controlling expression of a generic selection is
  1985. // not evaluated."
  1986. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
  1987. ControllingExpr = ParseAssignmentExpression();
  1988. if (ControllingExpr.isInvalid()) {
  1989. SkipUntil(tok::r_paren);
  1990. return ExprError();
  1991. }
  1992. }
  1993. if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "")) {
  1994. SkipUntil(tok::r_paren);
  1995. return ExprError();
  1996. }
  1997. SourceLocation DefaultLoc;
  1998. TypeVector Types(Actions);
  1999. ExprVector Exprs(Actions);
  2000. while (1) {
  2001. ParsedType Ty;
  2002. if (Tok.is(tok::kw_default)) {
  2003. // C11 6.5.1.1p2 "A generic selection shall have no more than one default
  2004. // generic association."
  2005. if (!DefaultLoc.isInvalid()) {
  2006. Diag(Tok, diag::err_duplicate_default_assoc);
  2007. Diag(DefaultLoc, diag::note_previous_default_assoc);
  2008. SkipUntil(tok::r_paren);
  2009. return ExprError();
  2010. }
  2011. DefaultLoc = ConsumeToken();
  2012. Ty = ParsedType();
  2013. } else {
  2014. ColonProtectionRAIIObject X(*this);
  2015. TypeResult TR = ParseTypeName();
  2016. if (TR.isInvalid()) {
  2017. SkipUntil(tok::r_paren);
  2018. return ExprError();
  2019. }
  2020. Ty = TR.release();
  2021. }
  2022. Types.push_back(Ty);
  2023. if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "")) {
  2024. SkipUntil(tok::r_paren);
  2025. return ExprError();
  2026. }
  2027. // FIXME: These expressions should be parsed in a potentially potentially
  2028. // evaluated context.
  2029. ExprResult ER(ParseAssignmentExpression());
  2030. if (ER.isInvalid()) {
  2031. SkipUntil(tok::r_paren);
  2032. return ExprError();
  2033. }
  2034. Exprs.push_back(ER.release());
  2035. if (Tok.isNot(tok::comma))
  2036. break;
  2037. ConsumeToken();
  2038. }
  2039. T.consumeClose();
  2040. if (T.getCloseLocation().isInvalid())
  2041. return ExprError();
  2042. return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
  2043. T.getCloseLocation(),
  2044. ControllingExpr.release(),
  2045. Types, Exprs);
  2046. }
  2047. /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
  2048. ///
  2049. /// \verbatim
  2050. /// argument-expression-list:
  2051. /// assignment-expression
  2052. /// argument-expression-list , assignment-expression
  2053. ///
  2054. /// [C++] expression-list:
  2055. /// [C++] assignment-expression
  2056. /// [C++] expression-list , assignment-expression
  2057. ///
  2058. /// [C++0x] expression-list:
  2059. /// [C++0x] initializer-list
  2060. ///
  2061. /// [C++0x] initializer-list
  2062. /// [C++0x] initializer-clause ...[opt]
  2063. /// [C++0x] initializer-list , initializer-clause ...[opt]
  2064. ///
  2065. /// [C++0x] initializer-clause:
  2066. /// [C++0x] assignment-expression
  2067. /// [C++0x] braced-init-list
  2068. /// \endverbatim
  2069. bool Parser::ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
  2070. SmallVectorImpl<SourceLocation> &CommaLocs,
  2071. void (Sema::*Completer)(Scope *S,
  2072. Expr *Data,
  2073. llvm::ArrayRef<Expr *> Args),
  2074. Expr *Data) {
  2075. while (1) {
  2076. if (Tok.is(tok::code_completion)) {
  2077. if (Completer)
  2078. (Actions.*Completer)(getCurScope(), Data, Exprs);
  2079. else
  2080. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
  2081. cutOffParsing();
  2082. return true;
  2083. }
  2084. ExprResult Expr;
  2085. if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
  2086. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
  2087. Expr = ParseBraceInitializer();
  2088. } else
  2089. Expr = ParseAssignmentExpression();
  2090. if (Tok.is(tok::ellipsis))
  2091. Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
  2092. if (Expr.isInvalid())
  2093. return true;
  2094. Exprs.push_back(Expr.release());
  2095. if (Tok.isNot(tok::comma))
  2096. return false;
  2097. // Move to the next argument, remember where the comma was.
  2098. CommaLocs.push_back(ConsumeToken());
  2099. }
  2100. }
  2101. /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
  2102. ///
  2103. /// \verbatim
  2104. /// [clang] block-id:
  2105. /// [clang] specifier-qualifier-list block-declarator
  2106. /// \endverbatim
  2107. void Parser::ParseBlockId(SourceLocation CaretLoc) {
  2108. if (Tok.is(tok::code_completion)) {
  2109. Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
  2110. return cutOffParsing();
  2111. }
  2112. // Parse the specifier-qualifier-list piece.
  2113. DeclSpec DS(AttrFactory);
  2114. ParseSpecifierQualifierList(DS);
  2115. // Parse the block-declarator.
  2116. Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
  2117. ParseDeclarator(DeclaratorInfo);
  2118. // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes.
  2119. DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation());
  2120. MaybeParseGNUAttributes(DeclaratorInfo);
  2121. // Inform sema that we are starting a block.
  2122. Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
  2123. }
  2124. /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
  2125. /// like ^(int x){ return x+1; }
  2126. ///
  2127. /// \verbatim
  2128. /// block-literal:
  2129. /// [clang] '^' block-args[opt] compound-statement
  2130. /// [clang] '^' block-id compound-statement
  2131. /// [clang] block-args:
  2132. /// [clang] '(' parameter-list ')'
  2133. /// \endverbatim
  2134. ExprResult Parser::ParseBlockLiteralExpression() {
  2135. assert(Tok.is(tok::caret) && "block literal starts with ^");
  2136. SourceLocation CaretLoc = ConsumeToken();
  2137. PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
  2138. "block literal parsing");
  2139. // Enter a scope to hold everything within the block. This includes the
  2140. // argument decls, decls within the compound expression, etc. This also
  2141. // allows determining whether a variable reference inside the block is
  2142. // within or outside of the block.
  2143. ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
  2144. Scope::DeclScope);
  2145. // Inform sema that we are starting a block.
  2146. Actions.ActOnBlockStart(CaretLoc, getCurScope());
  2147. // Parse the return type if present.
  2148. DeclSpec DS(AttrFactory);
  2149. Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
  2150. // FIXME: Since the return type isn't actually parsed, it can't be used to
  2151. // fill ParamInfo with an initial valid range, so do it manually.
  2152. ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
  2153. // If this block has arguments, parse them. There is no ambiguity here with
  2154. // the expression case, because the expression case requires a parameter list.
  2155. if (Tok.is(tok::l_paren)) {
  2156. ParseParenDeclarator(ParamInfo);
  2157. // Parse the pieces after the identifier as if we had "int(...)".
  2158. // SetIdentifier sets the source range end, but in this case we're past
  2159. // that location.
  2160. SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
  2161. ParamInfo.SetIdentifier(0, CaretLoc);
  2162. ParamInfo.SetRangeEnd(Tmp);
  2163. if (ParamInfo.isInvalidType()) {
  2164. // If there was an error parsing the arguments, they may have
  2165. // tried to use ^(x+y) which requires an argument list. Just
  2166. // skip the whole block literal.
  2167. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2168. return ExprError();
  2169. }
  2170. MaybeParseGNUAttributes(ParamInfo);
  2171. // Inform sema that we are starting a block.
  2172. Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
  2173. } else if (!Tok.is(tok::l_brace)) {
  2174. ParseBlockId(CaretLoc);
  2175. } else {
  2176. // Otherwise, pretend we saw (void).
  2177. ParsedAttributes attrs(AttrFactory);
  2178. ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, false,
  2179. SourceLocation(),
  2180. 0, 0, 0,
  2181. true, SourceLocation(),
  2182. SourceLocation(),
  2183. SourceLocation(),
  2184. SourceLocation(),
  2185. EST_None,
  2186. SourceLocation(),
  2187. 0, 0, 0, 0,
  2188. CaretLoc, CaretLoc,
  2189. ParamInfo),
  2190. attrs, CaretLoc);
  2191. MaybeParseGNUAttributes(ParamInfo);
  2192. // Inform sema that we are starting a block.
  2193. Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
  2194. }
  2195. ExprResult Result(true);
  2196. if (!Tok.is(tok::l_brace)) {
  2197. // Saw something like: ^expr
  2198. Diag(Tok, diag::err_expected_expression);
  2199. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2200. return ExprError();
  2201. }
  2202. StmtResult Stmt(ParseCompoundStatementBody());
  2203. BlockScope.Exit();
  2204. if (!Stmt.isInvalid())
  2205. Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope());
  2206. else
  2207. Actions.ActOnBlockError(CaretLoc, getCurScope());
  2208. return Result;
  2209. }
  2210. /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
  2211. ///
  2212. /// '__objc_yes'
  2213. /// '__objc_no'
  2214. ExprResult Parser::ParseObjCBoolLiteral() {
  2215. tok::TokenKind Kind = Tok.getKind();
  2216. return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
  2217. }