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