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