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