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