ParseExpr.cpp revision 04992c7d8e74adff8ad7ca7e6b3e2fe96c47acda
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(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(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(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(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 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 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 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 745 // If this identifier was reverted from a token ID, and the next token 746 // is a parenthesis, this is likely to be a use of a type trait. Check 747 // those tokens. 748 if (Next.is(tok::l_paren) && 749 Tok.is(tok::identifier) && 750 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) { 751 IdentifierInfo *II = Tok.getIdentifierInfo(); 752 // Build up the mapping of revertable type traits, for future use. 753 if (RevertableTypeTraits.empty()) { 754#define RTT_JOIN(X,Y) X##Y 755#define REVERTABLE_TYPE_TRAIT(Name) \ 756 RevertableTypeTraits[PP.getIdentifierInfo(#Name)] \ 757 = RTT_JOIN(tok::kw_,Name) 758 759 REVERTABLE_TYPE_TRAIT(__is_arithmetic); 760 REVERTABLE_TYPE_TRAIT(__is_convertible); 761 REVERTABLE_TYPE_TRAIT(__is_empty); 762 REVERTABLE_TYPE_TRAIT(__is_floating_point); 763 REVERTABLE_TYPE_TRAIT(__is_function); 764 REVERTABLE_TYPE_TRAIT(__is_fundamental); 765 REVERTABLE_TYPE_TRAIT(__is_integral); 766 REVERTABLE_TYPE_TRAIT(__is_member_function_pointer); 767 REVERTABLE_TYPE_TRAIT(__is_member_pointer); 768 REVERTABLE_TYPE_TRAIT(__is_pod); 769 REVERTABLE_TYPE_TRAIT(__is_pointer); 770 REVERTABLE_TYPE_TRAIT(__is_same); 771 REVERTABLE_TYPE_TRAIT(__is_scalar); 772 REVERTABLE_TYPE_TRAIT(__is_signed); 773 REVERTABLE_TYPE_TRAIT(__is_unsigned); 774 REVERTABLE_TYPE_TRAIT(__is_void); 775#undef REVERTABLE_TYPE_TRAIT 776#undef RTT_JOIN 777 } 778 779 // If we find that this is in fact the name of a type trait, 780 // update the token kind in place and parse again to treat it as 781 // the appropriate kind of type trait. 782 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known 783 = RevertableTypeTraits.find(II); 784 if (Known != RevertableTypeTraits.end()) { 785 Tok.setKind(Known->second); 786 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 787 NotCastExpr, isTypeCast); 788 } 789 } 790 791 if (Next.is(tok::coloncolon) || 792 (!ColonIsSacred && Next.is(tok::colon)) || 793 Next.is(tok::less) || 794 Next.is(tok::l_paren) || 795 Next.is(tok::l_brace)) { 796 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 797 if (TryAnnotateTypeOrScopeToken()) 798 return ExprError(); 799 if (!Tok.is(tok::identifier)) 800 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 801 } 802 } 803 804 // Consume the identifier so that we can see if it is followed by a '(' or 805 // '.'. 806 IdentifierInfo &II = *Tok.getIdentifierInfo(); 807 SourceLocation ILoc = ConsumeToken(); 808 809 // Support 'Class.property' and 'super.property' notation. 810 if (getLangOpts().ObjC1 && Tok.is(tok::period) && 811 (Actions.getTypeName(II, ILoc, getCurScope()) || 812 // Allow the base to be 'super' if in an objc-method. 813 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) { 814 ConsumeToken(); 815 816 // Allow either an identifier or the keyword 'class' (in C++). 817 if (Tok.isNot(tok::identifier) && 818 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) { 819 Diag(Tok, diag::err_expected_property_name); 820 return ExprError(); 821 } 822 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); 823 SourceLocation PropertyLoc = ConsumeToken(); 824 825 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName, 826 ILoc, PropertyLoc); 827 break; 828 } 829 830 // In an Objective-C method, if we have "super" followed by an identifier, 831 // the token sequence is ill-formed. However, if there's a ':' or ']' after 832 // that identifier, this is probably a message send with a missing open 833 // bracket. Treat it as such. 834 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression && 835 getCurScope()->isInObjcMethodScope() && 836 ((Tok.is(tok::identifier) && 837 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) || 838 Tok.is(tok::code_completion))) { 839 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(), 840 0); 841 break; 842 } 843 844 // If we have an Objective-C class name followed by an identifier 845 // and either ':' or ']', this is an Objective-C class message 846 // send that's missing the opening '['. Recovery 847 // appropriately. Also take this path if we're performing code 848 // completion after an Objective-C class name. 849 if (getLangOpts().ObjC1 && 850 ((Tok.is(tok::identifier) && !InMessageExpression) || 851 Tok.is(tok::code_completion))) { 852 const Token& Next = NextToken(); 853 if (Tok.is(tok::code_completion) || 854 Next.is(tok::colon) || Next.is(tok::r_square)) 855 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope())) 856 if (Typ.get()->isObjCObjectOrInterfaceType()) { 857 // Fake up a Declarator to use with ActOnTypeName. 858 DeclSpec DS(AttrFactory); 859 DS.SetRangeStart(ILoc); 860 DS.SetRangeEnd(ILoc); 861 const char *PrevSpec = 0; 862 unsigned DiagID; 863 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ); 864 865 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 866 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), 867 DeclaratorInfo); 868 if (Ty.isInvalid()) 869 break; 870 871 Res = ParseObjCMessageExpressionBody(SourceLocation(), 872 SourceLocation(), 873 Ty.get(), 0); 874 break; 875 } 876 } 877 878 // Make sure to pass down the right value for isAddressOfOperand. 879 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 880 isAddressOfOperand = false; 881 882 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we 883 // need to know whether or not this identifier is a function designator or 884 // not. 885 UnqualifiedId Name; 886 CXXScopeSpec ScopeSpec; 887 SourceLocation TemplateKWLoc; 888 CastExpressionIdValidator Validator(isTypeCast != NotTypeCast, 889 isTypeCast != IsTypeCast); 890 Name.setIdentifier(&II, ILoc); 891 Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKWLoc, 892 Name, Tok.is(tok::l_paren), 893 isAddressOfOperand, &Validator); 894 break; 895 } 896 case tok::char_constant: // constant: character-constant 897 case tok::wide_char_constant: 898 case tok::utf16_char_constant: 899 case tok::utf32_char_constant: 900 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope()); 901 ConsumeToken(); 902 break; 903 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] 904 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] 905 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS] 906 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] 907 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind); 908 ConsumeToken(); 909 break; 910 case tok::string_literal: // primary-expression: string-literal 911 case tok::wide_string_literal: 912 case tok::utf8_string_literal: 913 case tok::utf16_string_literal: 914 case tok::utf32_string_literal: 915 Res = ParseStringLiteralExpression(true); 916 break; 917 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1] 918 Res = ParseGenericSelectionExpression(); 919 break; 920 case tok::kw___builtin_va_arg: 921 case tok::kw___builtin_offsetof: 922 case tok::kw___builtin_choose_expr: 923 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type() 924 return ParseBuiltinPrimaryExpression(); 925 case tok::kw___null: 926 return Actions.ActOnGNUNullExpr(ConsumeToken()); 927 928 case tok::plusplus: // unary-expression: '++' unary-expression [C99] 929 case tok::minusminus: { // unary-expression: '--' unary-expression [C99] 930 // C++ [expr.unary] has: 931 // unary-expression: 932 // ++ cast-expression 933 // -- cast-expression 934 SourceLocation SavedLoc = ConsumeToken(); 935 Res = ParseCastExpression(!getLangOpts().CPlusPlus); 936 if (!Res.isInvalid()) 937 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 938 return Res; 939 } 940 case tok::amp: { // unary-expression: '&' cast-expression 941 // Special treatment because of member pointers 942 SourceLocation SavedLoc = ConsumeToken(); 943 Res = ParseCastExpression(false, true); 944 if (!Res.isInvalid()) 945 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 946 return Res; 947 } 948 949 case tok::star: // unary-expression: '*' cast-expression 950 case tok::plus: // unary-expression: '+' cast-expression 951 case tok::minus: // unary-expression: '-' cast-expression 952 case tok::tilde: // unary-expression: '~' cast-expression 953 case tok::exclaim: // unary-expression: '!' cast-expression 954 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] 955 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] 956 SourceLocation SavedLoc = ConsumeToken(); 957 Res = ParseCastExpression(false); 958 if (!Res.isInvalid()) 959 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 960 return Res; 961 } 962 963 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] 964 // __extension__ silences extension warnings in the subexpression. 965 ExtensionRAIIObject O(Diags); // Use RAII to do this. 966 SourceLocation SavedLoc = ConsumeToken(); 967 Res = ParseCastExpression(false); 968 if (!Res.isInvalid()) 969 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 970 return Res; 971 } 972 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')' 973 if (!getLangOpts().C11) 974 Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); 975 // fallthrough 976 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')' 977 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression 978 // unary-expression: '__alignof' '(' type-name ')' 979 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression 980 // unary-expression: 'sizeof' '(' type-name ')' 981 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression 982 return ParseUnaryExprOrTypeTraitExpression(); 983 case tok::ampamp: { // unary-expression: '&&' identifier 984 SourceLocation AmpAmpLoc = ConsumeToken(); 985 if (Tok.isNot(tok::identifier)) 986 return ExprError(Diag(Tok, diag::err_expected_ident)); 987 988 if (getCurScope()->getFnParent() == 0) 989 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn)); 990 991 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); 992 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), 993 Tok.getLocation()); 994 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD); 995 ConsumeToken(); 996 return Res; 997 } 998 case tok::kw_const_cast: 999 case tok::kw_dynamic_cast: 1000 case tok::kw_reinterpret_cast: 1001 case tok::kw_static_cast: 1002 Res = ParseCXXCasts(); 1003 break; 1004 case tok::kw_typeid: 1005 Res = ParseCXXTypeid(); 1006 break; 1007 case tok::kw___uuidof: 1008 Res = ParseCXXUuidof(); 1009 break; 1010 case tok::kw_this: 1011 Res = ParseCXXThis(); 1012 break; 1013 1014 case tok::annot_typename: 1015 if (isStartOfObjCClassMessageMissingOpenBracket()) { 1016 ParsedType Type = getTypeAnnotation(Tok); 1017 1018 // Fake up a Declarator to use with ActOnTypeName. 1019 DeclSpec DS(AttrFactory); 1020 DS.SetRangeStart(Tok.getLocation()); 1021 DS.SetRangeEnd(Tok.getLastLoc()); 1022 1023 const char *PrevSpec = 0; 1024 unsigned DiagID; 1025 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(), 1026 PrevSpec, DiagID, Type); 1027 1028 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 1029 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 1030 if (Ty.isInvalid()) 1031 break; 1032 1033 ConsumeToken(); 1034 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 1035 Ty.get(), 0); 1036 break; 1037 } 1038 // Fall through 1039 1040 case tok::annot_decltype: 1041 case tok::kw_char: 1042 case tok::kw_wchar_t: 1043 case tok::kw_char16_t: 1044 case tok::kw_char32_t: 1045 case tok::kw_bool: 1046 case tok::kw_short: 1047 case tok::kw_int: 1048 case tok::kw_long: 1049 case tok::kw___int64: 1050 case tok::kw___int128: 1051 case tok::kw_signed: 1052 case tok::kw_unsigned: 1053 case tok::kw_half: 1054 case tok::kw_float: 1055 case tok::kw_double: 1056 case tok::kw_void: 1057 case tok::kw_typename: 1058 case tok::kw_typeof: 1059 case tok::kw___vector: { 1060 if (!getLangOpts().CPlusPlus) { 1061 Diag(Tok, diag::err_expected_expression); 1062 return ExprError(); 1063 } 1064 1065 if (SavedKind == tok::kw_typename) { 1066 // postfix-expression: typename-specifier '(' expression-list[opt] ')' 1067 // typename-specifier braced-init-list 1068 if (TryAnnotateTypeOrScopeToken()) 1069 return ExprError(); 1070 } 1071 1072 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' 1073 // simple-type-specifier braced-init-list 1074 // 1075 DeclSpec DS(AttrFactory); 1076 ParseCXXSimpleTypeSpecifier(DS); 1077 if (Tok.isNot(tok::l_paren) && 1078 (!getLangOpts().CPlusPlus0x || Tok.isNot(tok::l_brace))) 1079 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) 1080 << DS.getSourceRange()); 1081 1082 if (Tok.is(tok::l_brace)) 1083 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 1084 1085 Res = ParseCXXTypeConstructExpression(DS); 1086 break; 1087 } 1088 1089 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id 1090 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 1091 // (We can end up in this situation after tentative parsing.) 1092 if (TryAnnotateTypeOrScopeToken()) 1093 return ExprError(); 1094 if (!Tok.is(tok::annot_cxxscope)) 1095 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1096 NotCastExpr, isTypeCast); 1097 1098 Token Next = NextToken(); 1099 if (Next.is(tok::annot_template_id)) { 1100 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 1101 if (TemplateId->Kind == TNK_Type_template) { 1102 // We have a qualified template-id that we know refers to a 1103 // type, translate it into a type and continue parsing as a 1104 // cast expression. 1105 CXXScopeSpec SS; 1106 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 1107 /*EnteringContext=*/false); 1108 AnnotateTemplateIdTokenAsType(); 1109 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1110 NotCastExpr, isTypeCast); 1111 } 1112 } 1113 1114 // Parse as an id-expression. 1115 Res = ParseCXXIdExpression(isAddressOfOperand); 1116 break; 1117 } 1118 1119 case tok::annot_template_id: { // [C++] template-id 1120 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1121 if (TemplateId->Kind == TNK_Type_template) { 1122 // We have a template-id that we know refers to a type, 1123 // translate it into a type and continue parsing as a cast 1124 // expression. 1125 AnnotateTemplateIdTokenAsType(); 1126 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1127 NotCastExpr, isTypeCast); 1128 } 1129 1130 // Fall through to treat the template-id as an id-expression. 1131 } 1132 1133 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id 1134 Res = ParseCXXIdExpression(isAddressOfOperand); 1135 break; 1136 1137 case tok::coloncolon: { 1138 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken 1139 // annotates the token, tail recurse. 1140 if (TryAnnotateTypeOrScopeToken()) 1141 return ExprError(); 1142 if (!Tok.is(tok::coloncolon)) 1143 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 1144 1145 // ::new -> [C++] new-expression 1146 // ::delete -> [C++] delete-expression 1147 SourceLocation CCLoc = ConsumeToken(); 1148 if (Tok.is(tok::kw_new)) 1149 return ParseCXXNewExpression(true, CCLoc); 1150 if (Tok.is(tok::kw_delete)) 1151 return ParseCXXDeleteExpression(true, CCLoc); 1152 1153 // This is not a type name or scope specifier, it is an invalid expression. 1154 Diag(CCLoc, diag::err_expected_expression); 1155 return ExprError(); 1156 } 1157 1158 case tok::kw_new: // [C++] new-expression 1159 return ParseCXXNewExpression(false, Tok.getLocation()); 1160 1161 case tok::kw_delete: // [C++] delete-expression 1162 return ParseCXXDeleteExpression(false, Tok.getLocation()); 1163 1164 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')' 1165 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr); 1166 SourceLocation KeyLoc = ConsumeToken(); 1167 BalancedDelimiterTracker T(*this, tok::l_paren); 1168 1169 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept")) 1170 return ExprError(); 1171 // C++11 [expr.unary.noexcept]p1: 1172 // The noexcept operator determines whether the evaluation of its operand, 1173 // which is an unevaluated operand, can throw an exception. 1174 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 1175 ExprResult Result = ParseExpression(); 1176 1177 T.consumeClose(); 1178 1179 if (!Result.isInvalid()) 1180 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), 1181 Result.take(), T.getCloseLocation()); 1182 return Result; 1183 } 1184 1185 case tok::kw___is_abstract: // [GNU] unary-type-trait 1186 case tok::kw___is_class: 1187 case tok::kw___is_empty: 1188 case tok::kw___is_enum: 1189 case tok::kw___is_literal: 1190 case tok::kw___is_arithmetic: 1191 case tok::kw___is_integral: 1192 case tok::kw___is_floating_point: 1193 case tok::kw___is_complete_type: 1194 case tok::kw___is_void: 1195 case tok::kw___is_array: 1196 case tok::kw___is_function: 1197 case tok::kw___is_reference: 1198 case tok::kw___is_lvalue_reference: 1199 case tok::kw___is_rvalue_reference: 1200 case tok::kw___is_fundamental: 1201 case tok::kw___is_object: 1202 case tok::kw___is_scalar: 1203 case tok::kw___is_compound: 1204 case tok::kw___is_pointer: 1205 case tok::kw___is_member_object_pointer: 1206 case tok::kw___is_member_function_pointer: 1207 case tok::kw___is_member_pointer: 1208 case tok::kw___is_const: 1209 case tok::kw___is_volatile: 1210 case tok::kw___is_standard_layout: 1211 case tok::kw___is_signed: 1212 case tok::kw___is_unsigned: 1213 case tok::kw___is_literal_type: 1214 case tok::kw___is_pod: 1215 case tok::kw___is_polymorphic: 1216 case tok::kw___is_trivial: 1217 case tok::kw___is_trivially_copyable: 1218 case tok::kw___is_union: 1219 case tok::kw___is_final: 1220 case tok::kw___has_trivial_constructor: 1221 case tok::kw___has_trivial_copy: 1222 case tok::kw___has_trivial_assign: 1223 case tok::kw___has_trivial_destructor: 1224 case tok::kw___has_nothrow_assign: 1225 case tok::kw___has_nothrow_copy: 1226 case tok::kw___has_nothrow_constructor: 1227 case tok::kw___has_virtual_destructor: 1228 return ParseUnaryTypeTrait(); 1229 1230 case tok::kw___builtin_types_compatible_p: 1231 case tok::kw___is_base_of: 1232 case tok::kw___is_same: 1233 case tok::kw___is_convertible: 1234 case tok::kw___is_convertible_to: 1235 case tok::kw___is_trivially_assignable: 1236 return ParseBinaryTypeTrait(); 1237 1238 case tok::kw___is_trivially_constructible: 1239 return ParseTypeTrait(); 1240 1241 case tok::kw___array_rank: 1242 case tok::kw___array_extent: 1243 return ParseArrayTypeTrait(); 1244 1245 case tok::kw___is_lvalue_expr: 1246 case tok::kw___is_rvalue_expr: 1247 return ParseExpressionTrait(); 1248 1249 case tok::at: { 1250 SourceLocation AtLoc = ConsumeToken(); 1251 return ParseObjCAtExpression(AtLoc); 1252 } 1253 case tok::caret: 1254 Res = ParseBlockLiteralExpression(); 1255 break; 1256 case tok::code_completion: { 1257 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 1258 cutOffParsing(); 1259 return ExprError(); 1260 } 1261 case tok::l_square: 1262 if (getLangOpts().CPlusPlus0x) { 1263 if (getLangOpts().ObjC1) { 1264 // C++11 lambda expressions and Objective-C message sends both start with a 1265 // square bracket. There are three possibilities here: 1266 // we have a valid lambda expression, we have an invalid lambda 1267 // expression, or we have something that doesn't appear to be a lambda. 1268 // If we're in the last case, we fall back to ParseObjCMessageExpression. 1269 Res = TryParseLambdaExpression(); 1270 if (!Res.isInvalid() && !Res.get()) 1271 Res = ParseObjCMessageExpression(); 1272 break; 1273 } 1274 Res = ParseLambdaExpression(); 1275 break; 1276 } 1277 if (getLangOpts().ObjC1) { 1278 Res = ParseObjCMessageExpression(); 1279 break; 1280 } 1281 // FALL THROUGH. 1282 default: 1283 NotCastExpr = true; 1284 return ExprError(); 1285 } 1286 1287 // These can be followed by postfix-expr pieces. 1288 return ParsePostfixExpressionSuffix(Res); 1289} 1290 1291/// \brief Once the leading part of a postfix-expression is parsed, this 1292/// method parses any suffixes that apply. 1293/// 1294/// \verbatim 1295/// postfix-expression: [C99 6.5.2] 1296/// primary-expression 1297/// postfix-expression '[' expression ']' 1298/// postfix-expression '[' braced-init-list ']' 1299/// postfix-expression '(' argument-expression-list[opt] ')' 1300/// postfix-expression '.' identifier 1301/// postfix-expression '->' identifier 1302/// postfix-expression '++' 1303/// postfix-expression '--' 1304/// '(' type-name ')' '{' initializer-list '}' 1305/// '(' type-name ')' '{' initializer-list ',' '}' 1306/// 1307/// argument-expression-list: [C99 6.5.2] 1308/// argument-expression ...[opt] 1309/// argument-expression-list ',' assignment-expression ...[opt] 1310/// \endverbatim 1311ExprResult 1312Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { 1313 // Now that the primary-expression piece of the postfix-expression has been 1314 // parsed, see if there are any postfix-expression pieces here. 1315 SourceLocation Loc; 1316 while (1) { 1317 switch (Tok.getKind()) { 1318 case tok::code_completion: 1319 if (InMessageExpression) 1320 return LHS; 1321 1322 Actions.CodeCompletePostfixExpression(getCurScope(), LHS); 1323 cutOffParsing(); 1324 return ExprError(); 1325 1326 case tok::identifier: 1327 // If we see identifier: after an expression, and we're not already in a 1328 // message send, then this is probably a message send with a missing 1329 // opening bracket '['. 1330 if (getLangOpts().ObjC1 && !InMessageExpression && 1331 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 1332 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 1333 ParsedType(), LHS.get()); 1334 break; 1335 } 1336 1337 // Fall through; this isn't a message send. 1338 1339 default: // Not a postfix-expression suffix. 1340 return LHS; 1341 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 1342 // If we have a array postfix expression that starts on a new line and 1343 // Objective-C is enabled, it is highly likely that the user forgot a 1344 // semicolon after the base expression and that the array postfix-expr is 1345 // actually another message send. In this case, do some look-ahead to see 1346 // if the contents of the square brackets are obviously not a valid 1347 // expression and recover by pretending there is no suffix. 1348 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() && 1349 isSimpleObjCMessageExpression()) 1350 return LHS; 1351 1352 // Reject array indices starting with a lambda-expression. '[[' is 1353 // reserved for attributes. 1354 if (CheckProhibitedCXX11Attribute()) 1355 return ExprError(); 1356 1357 BalancedDelimiterTracker T(*this, tok::l_square); 1358 T.consumeOpen(); 1359 Loc = T.getOpenLocation(); 1360 ExprResult Idx; 1361 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 1362 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 1363 Idx = ParseBraceInitializer(); 1364 } else 1365 Idx = ParseExpression(); 1366 1367 SourceLocation RLoc = Tok.getLocation(); 1368 1369 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 1370 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc, 1371 Idx.take(), RLoc); 1372 } else 1373 LHS = ExprError(); 1374 1375 // Match the ']'. 1376 T.consumeClose(); 1377 break; 1378 } 1379 1380 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')' 1381 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>' 1382 // '(' argument-expression-list[opt] ')' 1383 tok::TokenKind OpKind = Tok.getKind(); 1384 InMessageExpressionRAIIObject InMessage(*this, false); 1385 1386 Expr *ExecConfig = 0; 1387 1388 BalancedDelimiterTracker PT(*this, tok::l_paren); 1389 1390 if (OpKind == tok::lesslessless) { 1391 ExprVector ExecConfigExprs; 1392 CommaLocsTy ExecConfigCommaLocs; 1393 SourceLocation OpenLoc = ConsumeToken(); 1394 1395 if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) { 1396 LHS = ExprError(); 1397 } 1398 1399 SourceLocation CloseLoc = Tok.getLocation(); 1400 if (Tok.is(tok::greatergreatergreater)) { 1401 ConsumeToken(); 1402 } else if (LHS.isInvalid()) { 1403 SkipUntil(tok::greatergreatergreater); 1404 } else { 1405 // There was an error closing the brackets 1406 Diag(Tok, diag::err_expected_ggg); 1407 Diag(OpenLoc, diag::note_matching) << "<<<"; 1408 SkipUntil(tok::greatergreatergreater); 1409 LHS = ExprError(); 1410 } 1411 1412 if (!LHS.isInvalid()) { 1413 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, "")) 1414 LHS = ExprError(); 1415 else 1416 Loc = PrevTokLocation; 1417 } 1418 1419 if (!LHS.isInvalid()) { 1420 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), 1421 OpenLoc, 1422 ExecConfigExprs, 1423 CloseLoc); 1424 if (ECResult.isInvalid()) 1425 LHS = ExprError(); 1426 else 1427 ExecConfig = ECResult.get(); 1428 } 1429 } else { 1430 PT.consumeOpen(); 1431 Loc = PT.getOpenLocation(); 1432 } 1433 1434 ExprVector ArgExprs; 1435 CommaLocsTy CommaLocs; 1436 1437 if (Tok.is(tok::code_completion)) { 1438 Actions.CodeCompleteCall(getCurScope(), LHS.get(), 1439 llvm::ArrayRef<Expr *>()); 1440 cutOffParsing(); 1441 return ExprError(); 1442 } 1443 1444 if (OpKind == tok::l_paren || !LHS.isInvalid()) { 1445 if (Tok.isNot(tok::r_paren)) { 1446 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall, 1447 LHS.get())) { 1448 LHS = ExprError(); 1449 } 1450 } 1451 } 1452 1453 // Match the ')'. 1454 if (LHS.isInvalid()) { 1455 SkipUntil(tok::r_paren); 1456 } else if (Tok.isNot(tok::r_paren)) { 1457 PT.consumeClose(); 1458 LHS = ExprError(); 1459 } else { 1460 assert((ArgExprs.size() == 0 || 1461 ArgExprs.size()-1 == CommaLocs.size())&& 1462 "Unexpected number of commas!"); 1463 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc, 1464 ArgExprs, Tok.getLocation(), 1465 ExecConfig); 1466 PT.consumeClose(); 1467 } 1468 1469 break; 1470 } 1471 case tok::arrow: 1472 case tok::period: { 1473 // postfix-expression: p-e '->' template[opt] id-expression 1474 // postfix-expression: p-e '.' template[opt] id-expression 1475 tok::TokenKind OpKind = Tok.getKind(); 1476 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 1477 1478 CXXScopeSpec SS; 1479 ParsedType ObjectType; 1480 bool MayBePseudoDestructor = false; 1481 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) { 1482 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(), 1483 OpLoc, OpKind, ObjectType, 1484 MayBePseudoDestructor); 1485 if (LHS.isInvalid()) 1486 break; 1487 1488 ParseOptionalCXXScopeSpecifier(SS, ObjectType, 1489 /*EnteringContext=*/false, 1490 &MayBePseudoDestructor); 1491 if (SS.isNotEmpty()) 1492 ObjectType = ParsedType(); 1493 } 1494 1495 if (Tok.is(tok::code_completion)) { 1496 // Code completion for a member access expression. 1497 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(), 1498 OpLoc, OpKind == tok::arrow); 1499 1500 cutOffParsing(); 1501 return ExprError(); 1502 } 1503 1504 if (MayBePseudoDestructor && !LHS.isInvalid()) { 1505 LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS, 1506 ObjectType); 1507 break; 1508 } 1509 1510 // Either the action has told is that this cannot be a 1511 // pseudo-destructor expression (based on the type of base 1512 // expression), or we didn't see a '~' in the right place. We 1513 // can still parse a destructor name here, but in that case it 1514 // names a real destructor. 1515 // Allow explicit constructor calls in Microsoft mode. 1516 // FIXME: Add support for explicit call of template constructor. 1517 SourceLocation TemplateKWLoc; 1518 UnqualifiedId Name; 1519 if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) { 1520 // Objective-C++: 1521 // After a '.' in a member access expression, treat the keyword 1522 // 'class' as if it were an identifier. 1523 // 1524 // This hack allows property access to the 'class' method because it is 1525 // such a common method name. For other C++ keywords that are 1526 // Objective-C method names, one must use the message send syntax. 1527 IdentifierInfo *Id = Tok.getIdentifierInfo(); 1528 SourceLocation Loc = ConsumeToken(); 1529 Name.setIdentifier(Id, Loc); 1530 } else if (ParseUnqualifiedId(SS, 1531 /*EnteringContext=*/false, 1532 /*AllowDestructorName=*/true, 1533 /*AllowConstructorName=*/ 1534 getLangOpts().MicrosoftExt, 1535 ObjectType, TemplateKWLoc, Name)) 1536 LHS = ExprError(); 1537 1538 if (!LHS.isInvalid()) 1539 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc, 1540 OpKind, SS, TemplateKWLoc, Name, 1541 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl : 0, 1542 Tok.is(tok::l_paren)); 1543 break; 1544 } 1545 case tok::plusplus: // postfix-expression: postfix-expression '++' 1546 case tok::minusminus: // postfix-expression: postfix-expression '--' 1547 if (!LHS.isInvalid()) { 1548 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(), 1549 Tok.getKind(), LHS.take()); 1550 } 1551 ConsumeToken(); 1552 break; 1553 } 1554 } 1555} 1556 1557/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/ 1558/// vec_step and we are at the start of an expression or a parenthesized 1559/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the 1560/// expression (isCastExpr == false) or the type (isCastExpr == true). 1561/// 1562/// \verbatim 1563/// unary-expression: [C99 6.5.3] 1564/// 'sizeof' unary-expression 1565/// 'sizeof' '(' type-name ')' 1566/// [GNU] '__alignof' unary-expression 1567/// [GNU] '__alignof' '(' type-name ')' 1568/// [C11] '_Alignof' '(' type-name ')' 1569/// [C++0x] 'alignof' '(' type-id ')' 1570/// 1571/// [GNU] typeof-specifier: 1572/// typeof ( expressions ) 1573/// typeof ( type-name ) 1574/// [GNU/C++] typeof unary-expression 1575/// 1576/// [OpenCL 1.1 6.11.12] vec_step built-in function: 1577/// vec_step ( expressions ) 1578/// vec_step ( type-name ) 1579/// \endverbatim 1580ExprResult 1581Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, 1582 bool &isCastExpr, 1583 ParsedType &CastTy, 1584 SourceRange &CastRange) { 1585 1586 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 1587 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) || 1588 OpTok.is(tok::kw__Alignof) || OpTok.is(tok::kw_vec_step)) && 1589 "Not a typeof/sizeof/alignof/vec_step expression!"); 1590 1591 ExprResult Operand; 1592 1593 // If the operand doesn't start with an '(', it must be an expression. 1594 if (Tok.isNot(tok::l_paren)) { 1595 isCastExpr = false; 1596 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) { 1597 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 1598 return ExprError(); 1599 } 1600 1601 Operand = ParseCastExpression(true/*isUnaryExpression*/); 1602 } else { 1603 // If it starts with a '(', we know that it is either a parenthesized 1604 // type-name, or it is a unary-expression that starts with a compound 1605 // literal, or starts with a primary-expression that is a parenthesized 1606 // expression. 1607 ParenParseOption ExprType = CastExpr; 1608 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 1609 1610 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 1611 false, CastTy, RParenLoc); 1612 CastRange = SourceRange(LParenLoc, RParenLoc); 1613 1614 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 1615 // a type. 1616 if (ExprType == CastExpr) { 1617 isCastExpr = true; 1618 return ExprEmpty(); 1619 } 1620 1621 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { 1622 // GNU typeof in C requires the expression to be parenthesized. Not so for 1623 // sizeof/alignof or in C++. Therefore, the parenthesized expression is 1624 // the start of a unary-expression, but doesn't include any postfix 1625 // pieces. Parse these now if present. 1626 if (!Operand.isInvalid()) 1627 Operand = ParsePostfixExpressionSuffix(Operand.get()); 1628 } 1629 } 1630 1631 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 1632 isCastExpr = false; 1633 return Operand; 1634} 1635 1636 1637/// \brief Parse a sizeof or alignof expression. 1638/// 1639/// \verbatim 1640/// unary-expression: [C99 6.5.3] 1641/// 'sizeof' unary-expression 1642/// 'sizeof' '(' type-name ')' 1643/// [C++0x] 'sizeof' '...' '(' identifier ')' 1644/// [GNU] '__alignof' unary-expression 1645/// [GNU] '__alignof' '(' type-name ')' 1646/// [C11] '_Alignof' '(' type-name ')' 1647/// [C++0x] 'alignof' '(' type-id ')' 1648/// \endverbatim 1649ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { 1650 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) || 1651 Tok.is(tok::kw_alignof) || Tok.is(tok::kw__Alignof) || 1652 Tok.is(tok::kw_vec_step)) && 1653 "Not a sizeof/alignof/vec_step expression!"); 1654 Token OpTok = Tok; 1655 ConsumeToken(); 1656 1657 // [C++0x] 'sizeof' '...' '(' identifier ')' 1658 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) { 1659 SourceLocation EllipsisLoc = ConsumeToken(); 1660 SourceLocation LParenLoc, RParenLoc; 1661 IdentifierInfo *Name = 0; 1662 SourceLocation NameLoc; 1663 if (Tok.is(tok::l_paren)) { 1664 BalancedDelimiterTracker T(*this, tok::l_paren); 1665 T.consumeOpen(); 1666 LParenLoc = T.getOpenLocation(); 1667 if (Tok.is(tok::identifier)) { 1668 Name = Tok.getIdentifierInfo(); 1669 NameLoc = ConsumeToken(); 1670 T.consumeClose(); 1671 RParenLoc = T.getCloseLocation(); 1672 if (RParenLoc.isInvalid()) 1673 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1674 } else { 1675 Diag(Tok, diag::err_expected_parameter_pack); 1676 SkipUntil(tok::r_paren); 1677 } 1678 } else if (Tok.is(tok::identifier)) { 1679 Name = Tok.getIdentifierInfo(); 1680 NameLoc = ConsumeToken(); 1681 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc); 1682 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1683 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack) 1684 << Name 1685 << FixItHint::CreateInsertion(LParenLoc, "(") 1686 << FixItHint::CreateInsertion(RParenLoc, ")"); 1687 } else { 1688 Diag(Tok, diag::err_sizeof_parameter_pack); 1689 } 1690 1691 if (!Name) 1692 return ExprError(); 1693 1694 return Actions.ActOnSizeofParameterPackExpr(getCurScope(), 1695 OpTok.getLocation(), 1696 *Name, NameLoc, 1697 RParenLoc); 1698 } 1699 1700 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof)) 1701 Diag(OpTok, diag::warn_cxx98_compat_alignof); 1702 1703 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 1704 1705 bool isCastExpr; 1706 ParsedType CastTy; 1707 SourceRange CastRange; 1708 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, 1709 isCastExpr, 1710 CastTy, 1711 CastRange); 1712 1713 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf; 1714 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof) || 1715 OpTok.is(tok::kw__Alignof)) 1716 ExprKind = UETT_AlignOf; 1717 else if (OpTok.is(tok::kw_vec_step)) 1718 ExprKind = UETT_VecStep; 1719 1720 if (isCastExpr) 1721 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 1722 ExprKind, 1723 /*isType=*/true, 1724 CastTy.getAsOpaquePtr(), 1725 CastRange); 1726 1727 // If we get here, the operand to the sizeof/alignof was an expresion. 1728 if (!Operand.isInvalid()) 1729 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 1730 ExprKind, 1731 /*isType=*/false, 1732 Operand.release(), 1733 CastRange); 1734 return Operand; 1735} 1736 1737/// ParseBuiltinPrimaryExpression 1738/// 1739/// \verbatim 1740/// primary-expression: [C99 6.5.1] 1741/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1742/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1743/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1744/// assign-expr ')' 1745/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1746/// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')' 1747/// 1748/// [GNU] offsetof-member-designator: 1749/// [GNU] identifier 1750/// [GNU] offsetof-member-designator '.' identifier 1751/// [GNU] offsetof-member-designator '[' expression ']' 1752/// \endverbatim 1753ExprResult Parser::ParseBuiltinPrimaryExpression() { 1754 ExprResult Res; 1755 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1756 1757 tok::TokenKind T = Tok.getKind(); 1758 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1759 1760 // All of these start with an open paren. 1761 if (Tok.isNot(tok::l_paren)) 1762 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1763 << BuiltinII); 1764 1765 BalancedDelimiterTracker PT(*this, tok::l_paren); 1766 PT.consumeOpen(); 1767 1768 // TODO: Build AST. 1769 1770 switch (T) { 1771 default: llvm_unreachable("Not a builtin primary expression!"); 1772 case tok::kw___builtin_va_arg: { 1773 ExprResult Expr(ParseAssignmentExpression()); 1774 1775 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1776 Expr = ExprError(); 1777 1778 TypeResult Ty = ParseTypeName(); 1779 1780 if (Tok.isNot(tok::r_paren)) { 1781 Diag(Tok, diag::err_expected_rparen); 1782 Expr = ExprError(); 1783 } 1784 1785 if (Expr.isInvalid() || Ty.isInvalid()) 1786 Res = ExprError(); 1787 else 1788 Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen()); 1789 break; 1790 } 1791 case tok::kw___builtin_offsetof: { 1792 SourceLocation TypeLoc = Tok.getLocation(); 1793 TypeResult Ty = ParseTypeName(); 1794 if (Ty.isInvalid()) { 1795 SkipUntil(tok::r_paren); 1796 return ExprError(); 1797 } 1798 1799 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1800 return ExprError(); 1801 1802 // We must have at least one identifier here. 1803 if (Tok.isNot(tok::identifier)) { 1804 Diag(Tok, diag::err_expected_ident); 1805 SkipUntil(tok::r_paren); 1806 return ExprError(); 1807 } 1808 1809 // Keep track of the various subcomponents we see. 1810 SmallVector<Sema::OffsetOfComponent, 4> Comps; 1811 1812 Comps.push_back(Sema::OffsetOfComponent()); 1813 Comps.back().isBrackets = false; 1814 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1815 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1816 1817 // FIXME: This loop leaks the index expressions on error. 1818 while (1) { 1819 if (Tok.is(tok::period)) { 1820 // offsetof-member-designator: offsetof-member-designator '.' identifier 1821 Comps.push_back(Sema::OffsetOfComponent()); 1822 Comps.back().isBrackets = false; 1823 Comps.back().LocStart = ConsumeToken(); 1824 1825 if (Tok.isNot(tok::identifier)) { 1826 Diag(Tok, diag::err_expected_ident); 1827 SkipUntil(tok::r_paren); 1828 return ExprError(); 1829 } 1830 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1831 Comps.back().LocEnd = ConsumeToken(); 1832 1833 } else if (Tok.is(tok::l_square)) { 1834 if (CheckProhibitedCXX11Attribute()) 1835 return ExprError(); 1836 1837 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1838 Comps.push_back(Sema::OffsetOfComponent()); 1839 Comps.back().isBrackets = true; 1840 BalancedDelimiterTracker ST(*this, tok::l_square); 1841 ST.consumeOpen(); 1842 Comps.back().LocStart = ST.getOpenLocation(); 1843 Res = ParseExpression(); 1844 if (Res.isInvalid()) { 1845 SkipUntil(tok::r_paren); 1846 return Res; 1847 } 1848 Comps.back().U.E = Res.release(); 1849 1850 ST.consumeClose(); 1851 Comps.back().LocEnd = ST.getCloseLocation(); 1852 } else { 1853 if (Tok.isNot(tok::r_paren)) { 1854 PT.consumeClose(); 1855 Res = ExprError(); 1856 } else if (Ty.isInvalid()) { 1857 Res = ExprError(); 1858 } else { 1859 PT.consumeClose(); 1860 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc, 1861 Ty.get(), &Comps[0], Comps.size(), 1862 PT.getCloseLocation()); 1863 } 1864 break; 1865 } 1866 } 1867 break; 1868 } 1869 case tok::kw___builtin_choose_expr: { 1870 ExprResult Cond(ParseAssignmentExpression()); 1871 if (Cond.isInvalid()) { 1872 SkipUntil(tok::r_paren); 1873 return Cond; 1874 } 1875 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1876 return ExprError(); 1877 1878 ExprResult Expr1(ParseAssignmentExpression()); 1879 if (Expr1.isInvalid()) { 1880 SkipUntil(tok::r_paren); 1881 return Expr1; 1882 } 1883 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1884 return ExprError(); 1885 1886 ExprResult Expr2(ParseAssignmentExpression()); 1887 if (Expr2.isInvalid()) { 1888 SkipUntil(tok::r_paren); 1889 return Expr2; 1890 } 1891 if (Tok.isNot(tok::r_paren)) { 1892 Diag(Tok, diag::err_expected_rparen); 1893 return ExprError(); 1894 } 1895 Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(), 1896 Expr2.take(), ConsumeParen()); 1897 break; 1898 } 1899 case tok::kw___builtin_astype: { 1900 // The first argument is an expression to be converted, followed by a comma. 1901 ExprResult Expr(ParseAssignmentExpression()); 1902 if (Expr.isInvalid()) { 1903 SkipUntil(tok::r_paren); 1904 return ExprError(); 1905 } 1906 1907 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", 1908 tok::r_paren)) 1909 return ExprError(); 1910 1911 // Second argument is the type to bitcast to. 1912 TypeResult DestTy = ParseTypeName(); 1913 if (DestTy.isInvalid()) 1914 return ExprError(); 1915 1916 // Attempt to consume the r-paren. 1917 if (Tok.isNot(tok::r_paren)) { 1918 Diag(Tok, diag::err_expected_rparen); 1919 SkipUntil(tok::r_paren); 1920 return ExprError(); 1921 } 1922 1923 Res = Actions.ActOnAsTypeExpr(Expr.take(), DestTy.get(), StartLoc, 1924 ConsumeParen()); 1925 break; 1926 } 1927 } 1928 1929 if (Res.isInvalid()) 1930 return ExprError(); 1931 1932 // These can be followed by postfix-expr pieces because they are 1933 // primary-expressions. 1934 return ParsePostfixExpressionSuffix(Res.take()); 1935} 1936 1937/// ParseParenExpression - This parses the unit that starts with a '(' token, 1938/// based on what is allowed by ExprType. The actual thing parsed is returned 1939/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1940/// not the parsed cast-expression. 1941/// 1942/// \verbatim 1943/// primary-expression: [C99 6.5.1] 1944/// '(' expression ')' 1945/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1946/// postfix-expression: [C99 6.5.2] 1947/// '(' type-name ')' '{' initializer-list '}' 1948/// '(' type-name ')' '{' initializer-list ',' '}' 1949/// cast-expression: [C99 6.5.4] 1950/// '(' type-name ')' cast-expression 1951/// [ARC] bridged-cast-expression 1952/// 1953/// [ARC] bridged-cast-expression: 1954/// (__bridge type-name) cast-expression 1955/// (__bridge_transfer type-name) cast-expression 1956/// (__bridge_retained type-name) cast-expression 1957/// \endverbatim 1958ExprResult 1959Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1960 bool isTypeCast, ParsedType &CastTy, 1961 SourceLocation &RParenLoc) { 1962 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1963 BalancedDelimiterTracker T(*this, tok::l_paren); 1964 if (T.consumeOpen()) 1965 return ExprError(); 1966 SourceLocation OpenLoc = T.getOpenLocation(); 1967 1968 ExprResult Result(true); 1969 bool isAmbiguousTypeId; 1970 CastTy = ParsedType(); 1971 1972 if (Tok.is(tok::code_completion)) { 1973 Actions.CodeCompleteOrdinaryName(getCurScope(), 1974 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression 1975 : Sema::PCC_Expression); 1976 cutOffParsing(); 1977 return ExprError(); 1978 } 1979 1980 // Diagnose use of bridge casts in non-arc mode. 1981 bool BridgeCast = (getLangOpts().ObjC2 && 1982 (Tok.is(tok::kw___bridge) || 1983 Tok.is(tok::kw___bridge_transfer) || 1984 Tok.is(tok::kw___bridge_retained) || 1985 Tok.is(tok::kw___bridge_retain))); 1986 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) { 1987 StringRef BridgeCastName = Tok.getName(); 1988 SourceLocation BridgeKeywordLoc = ConsumeToken(); 1989 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) 1990 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc) 1991 << BridgeCastName 1992 << FixItHint::CreateReplacement(BridgeKeywordLoc, ""); 1993 BridgeCast = false; 1994 } 1995 1996 // None of these cases should fall through with an invalid Result 1997 // unless they've already reported an error. 1998 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 1999 Diag(Tok, diag::ext_gnu_statement_expr); 2000 Actions.ActOnStartStmtExpr(); 2001 2002 StmtResult Stmt(ParseCompoundStatement(true)); 2003 ExprType = CompoundStmt; 2004 2005 // If the substmt parsed correctly, build the AST node. 2006 if (!Stmt.isInvalid()) { 2007 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation()); 2008 } else { 2009 Actions.ActOnStmtExprError(); 2010 } 2011 } else if (ExprType >= CompoundLiteral && BridgeCast) { 2012 tok::TokenKind tokenKind = Tok.getKind(); 2013 SourceLocation BridgeKeywordLoc = ConsumeToken(); 2014 2015 // Parse an Objective-C ARC ownership cast expression. 2016 ObjCBridgeCastKind Kind; 2017 if (tokenKind == tok::kw___bridge) 2018 Kind = OBC_Bridge; 2019 else if (tokenKind == tok::kw___bridge_transfer) 2020 Kind = OBC_BridgeTransfer; 2021 else if (tokenKind == tok::kw___bridge_retained) 2022 Kind = OBC_BridgeRetained; 2023 else { 2024 // As a hopefully temporary workaround, allow __bridge_retain as 2025 // a synonym for __bridge_retained, but only in system headers. 2026 assert(tokenKind == tok::kw___bridge_retain); 2027 Kind = OBC_BridgeRetained; 2028 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) 2029 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain) 2030 << FixItHint::CreateReplacement(BridgeKeywordLoc, 2031 "__bridge_retained"); 2032 } 2033 2034 TypeResult Ty = ParseTypeName(); 2035 T.consumeClose(); 2036 RParenLoc = T.getCloseLocation(); 2037 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false); 2038 2039 if (Ty.isInvalid() || SubExpr.isInvalid()) 2040 return ExprError(); 2041 2042 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind, 2043 BridgeKeywordLoc, Ty.get(), 2044 RParenLoc, SubExpr.get()); 2045 } else if (ExprType >= CompoundLiteral && 2046 isTypeIdInParens(isAmbiguousTypeId)) { 2047 2048 // Otherwise, this is a compound literal expression or cast expression. 2049 2050 // In C++, if the type-id is ambiguous we disambiguate based on context. 2051 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 2052 // in which case we should treat it as type-id. 2053 // if stopIfCastExpr is false, we need to determine the context past the 2054 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 2055 if (isAmbiguousTypeId && !stopIfCastExpr) { 2056 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T); 2057 RParenLoc = T.getCloseLocation(); 2058 return res; 2059 } 2060 2061 // Parse the type declarator. 2062 DeclSpec DS(AttrFactory); 2063 ParseSpecifierQualifierList(DS); 2064 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 2065 ParseDeclarator(DeclaratorInfo); 2066 2067 // If our type is followed by an identifier and either ':' or ']', then 2068 // this is probably an Objective-C message send where the leading '[' is 2069 // missing. Recover as if that were the case. 2070 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) && 2071 !InMessageExpression && getLangOpts().ObjC1 && 2072 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 2073 TypeResult Ty; 2074 { 2075 InMessageExpressionRAIIObject InMessage(*this, false); 2076 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2077 } 2078 Result = ParseObjCMessageExpressionBody(SourceLocation(), 2079 SourceLocation(), 2080 Ty.get(), 0); 2081 } else { 2082 // Match the ')'. 2083 T.consumeClose(); 2084 RParenLoc = T.getCloseLocation(); 2085 if (Tok.is(tok::l_brace)) { 2086 ExprType = CompoundLiteral; 2087 TypeResult Ty; 2088 { 2089 InMessageExpressionRAIIObject InMessage(*this, false); 2090 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2091 } 2092 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 2093 } 2094 2095 if (ExprType == CastExpr) { 2096 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 2097 2098 if (DeclaratorInfo.isInvalidType()) 2099 return ExprError(); 2100 2101 // Note that this doesn't parse the subsequent cast-expression, it just 2102 // returns the parsed type to the callee. 2103 if (stopIfCastExpr) { 2104 TypeResult Ty; 2105 { 2106 InMessageExpressionRAIIObject InMessage(*this, false); 2107 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2108 } 2109 CastTy = Ty.get(); 2110 return ExprResult(); 2111 } 2112 2113 // Reject the cast of super idiom in ObjC. 2114 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 && 2115 Tok.getIdentifierInfo() == Ident_super && 2116 getCurScope()->isInObjcMethodScope() && 2117 GetLookAheadToken(1).isNot(tok::period)) { 2118 Diag(Tok.getLocation(), diag::err_illegal_super_cast) 2119 << SourceRange(OpenLoc, RParenLoc); 2120 return ExprError(); 2121 } 2122 2123 // Parse the cast-expression that follows it next. 2124 // TODO: For cast expression with CastTy. 2125 Result = ParseCastExpression(/*isUnaryExpression=*/false, 2126 /*isAddressOfOperand=*/false, 2127 /*isTypeCast=*/IsTypeCast); 2128 if (!Result.isInvalid()) { 2129 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, 2130 DeclaratorInfo, CastTy, 2131 RParenLoc, Result.take()); 2132 } 2133 return Result; 2134 } 2135 2136 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 2137 return ExprError(); 2138 } 2139 } else if (isTypeCast) { 2140 // Parse the expression-list. 2141 InMessageExpressionRAIIObject InMessage(*this, false); 2142 2143 ExprVector ArgExprs; 2144 CommaLocsTy CommaLocs; 2145 2146 if (!ParseExpressionList(ArgExprs, CommaLocs)) { 2147 ExprType = SimpleExpr; 2148 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), 2149 ArgExprs); 2150 } 2151 } else { 2152 InMessageExpressionRAIIObject InMessage(*this, false); 2153 2154 Result = ParseExpression(MaybeTypeCast); 2155 ExprType = SimpleExpr; 2156 2157 // Don't build a paren expression unless we actually match a ')'. 2158 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 2159 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take()); 2160 } 2161 2162 // Match the ')'. 2163 if (Result.isInvalid()) { 2164 SkipUntil(tok::r_paren); 2165 return ExprError(); 2166 } 2167 2168 T.consumeClose(); 2169 RParenLoc = T.getCloseLocation(); 2170 return Result; 2171} 2172 2173/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 2174/// and we are at the left brace. 2175/// 2176/// \verbatim 2177/// postfix-expression: [C99 6.5.2] 2178/// '(' type-name ')' '{' initializer-list '}' 2179/// '(' type-name ')' '{' initializer-list ',' '}' 2180/// \endverbatim 2181ExprResult 2182Parser::ParseCompoundLiteralExpression(ParsedType Ty, 2183 SourceLocation LParenLoc, 2184 SourceLocation RParenLoc) { 2185 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 2186 if (!getLangOpts().C99) // Compound literals don't exist in C90. 2187 Diag(LParenLoc, diag::ext_c99_compound_literal); 2188 ExprResult Result = ParseInitializer(); 2189 if (!Result.isInvalid() && Ty) 2190 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take()); 2191 return Result; 2192} 2193 2194/// ParseStringLiteralExpression - This handles the various token types that 2195/// form string literals, and also handles string concatenation [C99 5.1.1.2, 2196/// translation phase #6]. 2197/// 2198/// \verbatim 2199/// primary-expression: [C99 6.5.1] 2200/// string-literal 2201/// \verbatim 2202ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) { 2203 assert(isTokenStringLiteral() && "Not a string literal!"); 2204 2205 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 2206 // considered to be strings for concatenation purposes. 2207 SmallVector<Token, 4> StringToks; 2208 2209 do { 2210 StringToks.push_back(Tok); 2211 ConsumeStringToken(); 2212 } while (isTokenStringLiteral()); 2213 2214 // Pass the set of string tokens, ready for concatenation, to the actions. 2215 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size(), 2216 AllowUserDefinedLiteral ? getCurScope() : 0); 2217} 2218 2219/// ParseGenericSelectionExpression - Parse a C11 generic-selection 2220/// [C11 6.5.1.1]. 2221/// 2222/// \verbatim 2223/// generic-selection: 2224/// _Generic ( assignment-expression , generic-assoc-list ) 2225/// generic-assoc-list: 2226/// generic-association 2227/// generic-assoc-list , generic-association 2228/// generic-association: 2229/// type-name : assignment-expression 2230/// default : assignment-expression 2231/// \endverbatim 2232ExprResult Parser::ParseGenericSelectionExpression() { 2233 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected"); 2234 SourceLocation KeyLoc = ConsumeToken(); 2235 2236 if (!getLangOpts().C11) 2237 Diag(KeyLoc, diag::ext_c11_generic_selection); 2238 2239 BalancedDelimiterTracker T(*this, tok::l_paren); 2240 if (T.expectAndConsume(diag::err_expected_lparen)) 2241 return ExprError(); 2242 2243 ExprResult ControllingExpr; 2244 { 2245 // C11 6.5.1.1p3 "The controlling expression of a generic selection is 2246 // not evaluated." 2247 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 2248 ControllingExpr = ParseAssignmentExpression(); 2249 if (ControllingExpr.isInvalid()) { 2250 SkipUntil(tok::r_paren); 2251 return ExprError(); 2252 } 2253 } 2254 2255 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "")) { 2256 SkipUntil(tok::r_paren); 2257 return ExprError(); 2258 } 2259 2260 SourceLocation DefaultLoc; 2261 TypeVector Types; 2262 ExprVector Exprs; 2263 while (1) { 2264 ParsedType Ty; 2265 if (Tok.is(tok::kw_default)) { 2266 // C11 6.5.1.1p2 "A generic selection shall have no more than one default 2267 // generic association." 2268 if (!DefaultLoc.isInvalid()) { 2269 Diag(Tok, diag::err_duplicate_default_assoc); 2270 Diag(DefaultLoc, diag::note_previous_default_assoc); 2271 SkipUntil(tok::r_paren); 2272 return ExprError(); 2273 } 2274 DefaultLoc = ConsumeToken(); 2275 Ty = ParsedType(); 2276 } else { 2277 ColonProtectionRAIIObject X(*this); 2278 TypeResult TR = ParseTypeName(); 2279 if (TR.isInvalid()) { 2280 SkipUntil(tok::r_paren); 2281 return ExprError(); 2282 } 2283 Ty = TR.release(); 2284 } 2285 Types.push_back(Ty); 2286 2287 if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "")) { 2288 SkipUntil(tok::r_paren); 2289 return ExprError(); 2290 } 2291 2292 // FIXME: These expressions should be parsed in a potentially potentially 2293 // evaluated context. 2294 ExprResult ER(ParseAssignmentExpression()); 2295 if (ER.isInvalid()) { 2296 SkipUntil(tok::r_paren); 2297 return ExprError(); 2298 } 2299 Exprs.push_back(ER.release()); 2300 2301 if (Tok.isNot(tok::comma)) 2302 break; 2303 ConsumeToken(); 2304 } 2305 2306 T.consumeClose(); 2307 if (T.getCloseLocation().isInvalid()) 2308 return ExprError(); 2309 2310 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, 2311 T.getCloseLocation(), 2312 ControllingExpr.release(), 2313 Types, Exprs); 2314} 2315 2316/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 2317/// 2318/// \verbatim 2319/// argument-expression-list: 2320/// assignment-expression 2321/// argument-expression-list , assignment-expression 2322/// 2323/// [C++] expression-list: 2324/// [C++] assignment-expression 2325/// [C++] expression-list , assignment-expression 2326/// 2327/// [C++0x] expression-list: 2328/// [C++0x] initializer-list 2329/// 2330/// [C++0x] initializer-list 2331/// [C++0x] initializer-clause ...[opt] 2332/// [C++0x] initializer-list , initializer-clause ...[opt] 2333/// 2334/// [C++0x] initializer-clause: 2335/// [C++0x] assignment-expression 2336/// [C++0x] braced-init-list 2337/// \endverbatim 2338bool Parser::ParseExpressionList(SmallVectorImpl<Expr*> &Exprs, 2339 SmallVectorImpl<SourceLocation> &CommaLocs, 2340 void (Sema::*Completer)(Scope *S, 2341 Expr *Data, 2342 llvm::ArrayRef<Expr *> Args), 2343 Expr *Data) { 2344 while (1) { 2345 if (Tok.is(tok::code_completion)) { 2346 if (Completer) 2347 (Actions.*Completer)(getCurScope(), Data, Exprs); 2348 else 2349 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 2350 cutOffParsing(); 2351 return true; 2352 } 2353 2354 ExprResult Expr; 2355 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 2356 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 2357 Expr = ParseBraceInitializer(); 2358 } else 2359 Expr = ParseAssignmentExpression(); 2360 2361 if (Tok.is(tok::ellipsis)) 2362 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); 2363 if (Expr.isInvalid()) 2364 return true; 2365 2366 Exprs.push_back(Expr.release()); 2367 2368 if (Tok.isNot(tok::comma)) 2369 return false; 2370 // Move to the next argument, remember where the comma was. 2371 CommaLocs.push_back(ConsumeToken()); 2372 } 2373} 2374 2375/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 2376/// 2377/// \verbatim 2378/// [clang] block-id: 2379/// [clang] specifier-qualifier-list block-declarator 2380/// \endverbatim 2381void Parser::ParseBlockId(SourceLocation CaretLoc) { 2382 if (Tok.is(tok::code_completion)) { 2383 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); 2384 return cutOffParsing(); 2385 } 2386 2387 // Parse the specifier-qualifier-list piece. 2388 DeclSpec DS(AttrFactory); 2389 ParseSpecifierQualifierList(DS); 2390 2391 // Parse the block-declarator. 2392 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 2393 ParseDeclarator(DeclaratorInfo); 2394 2395 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 2396 DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation()); 2397 2398 MaybeParseGNUAttributes(DeclaratorInfo); 2399 2400 // Inform sema that we are starting a block. 2401 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope()); 2402} 2403 2404/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 2405/// like ^(int x){ return x+1; } 2406/// 2407/// \verbatim 2408/// block-literal: 2409/// [clang] '^' block-args[opt] compound-statement 2410/// [clang] '^' block-id compound-statement 2411/// [clang] block-args: 2412/// [clang] '(' parameter-list ')' 2413/// \endverbatim 2414ExprResult Parser::ParseBlockLiteralExpression() { 2415 assert(Tok.is(tok::caret) && "block literal starts with ^"); 2416 SourceLocation CaretLoc = ConsumeToken(); 2417 2418 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 2419 "block literal parsing"); 2420 2421 // Enter a scope to hold everything within the block. This includes the 2422 // argument decls, decls within the compound expression, etc. This also 2423 // allows determining whether a variable reference inside the block is 2424 // within or outside of the block. 2425 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 2426 Scope::DeclScope); 2427 2428 // Inform sema that we are starting a block. 2429 Actions.ActOnBlockStart(CaretLoc, getCurScope()); 2430 2431 // Parse the return type if present. 2432 DeclSpec DS(AttrFactory); 2433 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 2434 // FIXME: Since the return type isn't actually parsed, it can't be used to 2435 // fill ParamInfo with an initial valid range, so do it manually. 2436 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 2437 2438 // If this block has arguments, parse them. There is no ambiguity here with 2439 // the expression case, because the expression case requires a parameter list. 2440 if (Tok.is(tok::l_paren)) { 2441 ParseParenDeclarator(ParamInfo); 2442 // Parse the pieces after the identifier as if we had "int(...)". 2443 // SetIdentifier sets the source range end, but in this case we're past 2444 // that location. 2445 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 2446 ParamInfo.SetIdentifier(0, CaretLoc); 2447 ParamInfo.SetRangeEnd(Tmp); 2448 if (ParamInfo.isInvalidType()) { 2449 // If there was an error parsing the arguments, they may have 2450 // tried to use ^(x+y) which requires an argument list. Just 2451 // skip the whole block literal. 2452 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2453 return ExprError(); 2454 } 2455 2456 MaybeParseGNUAttributes(ParamInfo); 2457 2458 // Inform sema that we are starting a block. 2459 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope()); 2460 } else if (!Tok.is(tok::l_brace)) { 2461 ParseBlockId(CaretLoc); 2462 } else { 2463 // Otherwise, pretend we saw (void). 2464 ParsedAttributes attrs(AttrFactory); 2465 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, false, 2466 SourceLocation(), 2467 0, 0, 0, 2468 true, SourceLocation(), 2469 SourceLocation(), 2470 SourceLocation(), 2471 SourceLocation(), 2472 EST_None, 2473 SourceLocation(), 2474 0, 0, 0, 0, 2475 CaretLoc, CaretLoc, 2476 ParamInfo), 2477 attrs, CaretLoc); 2478 2479 MaybeParseGNUAttributes(ParamInfo); 2480 2481 // Inform sema that we are starting a block. 2482 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope()); 2483 } 2484 2485 2486 ExprResult Result(true); 2487 if (!Tok.is(tok::l_brace)) { 2488 // Saw something like: ^expr 2489 Diag(Tok, diag::err_expected_expression); 2490 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2491 return ExprError(); 2492 } 2493 2494 StmtResult Stmt(ParseCompoundStatementBody()); 2495 BlockScope.Exit(); 2496 if (!Stmt.isInvalid()) 2497 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope()); 2498 else 2499 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2500 return Result; 2501} 2502 2503/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals. 2504/// 2505/// '__objc_yes' 2506/// '__objc_no' 2507ExprResult Parser::ParseObjCBoolLiteral() { 2508 tok::TokenKind Kind = Tok.getKind(); 2509 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind); 2510} 2511