ParseExpr.cpp revision 200b2921390bd75a659be3c77011e9a5548b7273
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/Basic/PrettyStackTrace.h" 27#include "RAIIObjectsForParser.h" 28#include "llvm/ADT/SmallVector.h" 29#include "llvm/ADT/SmallString.h" 30using namespace clang; 31 32/// getBinOpPrecedence - Return the precedence of the specified binary operator 33/// token. 34static prec::Level getBinOpPrecedence(tok::TokenKind Kind, 35 bool GreaterThanIsOperator, 36 bool CPlusPlus0x) { 37 switch (Kind) { 38 case tok::greater: 39 // C++ [temp.names]p3: 40 // [...] When parsing a template-argument-list, the first 41 // non-nested > is taken as the ending delimiter rather than a 42 // greater-than operator. [...] 43 if (GreaterThanIsOperator) 44 return prec::Relational; 45 return prec::Unknown; 46 47 case tok::greatergreater: 48 // C++0x [temp.names]p3: 49 // 50 // [...] Similarly, the first non-nested >> is treated as two 51 // consecutive but distinct > tokens, the first of which is 52 // taken as the end of the template-argument-list and completes 53 // the template-id. [...] 54 if (GreaterThanIsOperator || !CPlusPlus0x) 55 return prec::Shift; 56 return prec::Unknown; 57 58 default: return prec::Unknown; 59 case tok::comma: return prec::Comma; 60 case tok::equal: 61 case tok::starequal: 62 case tok::slashequal: 63 case tok::percentequal: 64 case tok::plusequal: 65 case tok::minusequal: 66 case tok::lesslessequal: 67 case tok::greatergreaterequal: 68 case tok::ampequal: 69 case tok::caretequal: 70 case tok::pipeequal: return prec::Assignment; 71 case tok::question: return prec::Conditional; 72 case tok::pipepipe: return prec::LogicalOr; 73 case tok::ampamp: return prec::LogicalAnd; 74 case tok::pipe: return prec::InclusiveOr; 75 case tok::caret: return prec::ExclusiveOr; 76 case tok::amp: return prec::And; 77 case tok::exclaimequal: 78 case tok::equalequal: return prec::Equality; 79 case tok::lessequal: 80 case tok::less: 81 case tok::greaterequal: return prec::Relational; 82 case tok::lessless: return prec::Shift; 83 case tok::plus: 84 case tok::minus: return prec::Additive; 85 case tok::percent: 86 case tok::slash: 87 case tok::star: return prec::Multiplicative; 88 case tok::periodstar: 89 case tok::arrowstar: return prec::PointerToMember; 90 } 91} 92 93 94/// ParseExpression - Simple precedence-based parser for binary/ternary 95/// operators. 96/// 97/// Note: we diverge from the C99 grammar when parsing the assignment-expression 98/// production. C99 specifies that the LHS of an assignment operator should be 99/// parsed as a unary-expression, but consistency dictates that it be a 100/// conditional-expession. In practice, the important thing here is that the 101/// LHS of an assignment has to be an l-value, which productions between 102/// unary-expression and conditional-expression don't produce. Because we want 103/// consistency, we parse the LHS as a conditional-expression, then check for 104/// l-value-ness in semantic analysis stages. 105/// 106/// pm-expression: [C++ 5.5] 107/// cast-expression 108/// pm-expression '.*' cast-expression 109/// pm-expression '->*' cast-expression 110/// 111/// multiplicative-expression: [C99 6.5.5] 112/// Note: in C++, apply pm-expression instead of cast-expression 113/// cast-expression 114/// multiplicative-expression '*' cast-expression 115/// multiplicative-expression '/' cast-expression 116/// multiplicative-expression '%' cast-expression 117/// 118/// additive-expression: [C99 6.5.6] 119/// multiplicative-expression 120/// additive-expression '+' multiplicative-expression 121/// additive-expression '-' multiplicative-expression 122/// 123/// shift-expression: [C99 6.5.7] 124/// additive-expression 125/// shift-expression '<<' additive-expression 126/// shift-expression '>>' additive-expression 127/// 128/// relational-expression: [C99 6.5.8] 129/// shift-expression 130/// relational-expression '<' shift-expression 131/// relational-expression '>' shift-expression 132/// relational-expression '<=' shift-expression 133/// relational-expression '>=' shift-expression 134/// 135/// equality-expression: [C99 6.5.9] 136/// relational-expression 137/// equality-expression '==' relational-expression 138/// equality-expression '!=' relational-expression 139/// 140/// AND-expression: [C99 6.5.10] 141/// equality-expression 142/// AND-expression '&' equality-expression 143/// 144/// exclusive-OR-expression: [C99 6.5.11] 145/// AND-expression 146/// exclusive-OR-expression '^' AND-expression 147/// 148/// inclusive-OR-expression: [C99 6.5.12] 149/// exclusive-OR-expression 150/// inclusive-OR-expression '|' exclusive-OR-expression 151/// 152/// logical-AND-expression: [C99 6.5.13] 153/// inclusive-OR-expression 154/// logical-AND-expression '&&' inclusive-OR-expression 155/// 156/// logical-OR-expression: [C99 6.5.14] 157/// logical-AND-expression 158/// logical-OR-expression '||' logical-AND-expression 159/// 160/// conditional-expression: [C99 6.5.15] 161/// logical-OR-expression 162/// logical-OR-expression '?' expression ':' conditional-expression 163/// [GNU] logical-OR-expression '?' ':' conditional-expression 164/// [C++] the third operand is an assignment-expression 165/// 166/// assignment-expression: [C99 6.5.16] 167/// conditional-expression 168/// unary-expression assignment-operator assignment-expression 169/// [C++] throw-expression [C++ 15] 170/// 171/// assignment-operator: one of 172/// = *= /= %= += -= <<= >>= &= ^= |= 173/// 174/// expression: [C99 6.5.17] 175/// assignment-expression 176/// expression ',' assignment-expression 177/// 178ExprResult Parser::ParseExpression() { 179 ExprResult LHS(ParseAssignmentExpression()); 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. 215/// 216ExprResult Parser::ParseAssignmentExpression() { 217 if (Tok.is(tok::code_completion)) { 218 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 219 ConsumeCodeCompletionToken(); 220 } 221 222 if (Tok.is(tok::kw_throw)) 223 return ParseThrowExpression(); 224 225 ExprResult LHS(ParseCastExpression(false)); 226 return ParseRHSOfBinaryExpression(move(LHS), prec::Assignment); 227} 228 229/// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression 230/// where part of an objc message send has already been parsed. In this case 231/// LBracLoc indicates the location of the '[' of the message send, and either 232/// ReceiverName or ReceiverExpr is non-null indicating the receiver of the 233/// message. 234/// 235/// Since this handles full assignment-expression's, it handles postfix 236/// expressions and other binary operators for these expressions as well. 237ExprResult 238Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc, 239 SourceLocation SuperLoc, 240 ParsedType ReceiverType, 241 Expr *ReceiverExpr) { 242 ExprResult R 243 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc, 244 ReceiverType, ReceiverExpr); 245 if (R.isInvalid()) return move(R); 246 R = ParsePostfixExpressionSuffix(R.take()); 247 return ParseRHSOfBinaryExpression(R, prec::Assignment); 248} 249 250 251ExprResult Parser::ParseConstantExpression() { 252 // C++ [basic.def.odr]p2: 253 // An expression is potentially evaluated unless it appears where an 254 // integral constant expression is required (see 5.19) [...]. 255 EnterExpressionEvaluationContext Unevaluated(Actions, 256 Sema::Unevaluated); 257 258 ExprResult LHS(ParseCastExpression(false)); 259 return ParseRHSOfBinaryExpression(LHS, prec::Conditional); 260} 261 262/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with 263/// LHS and has a precedence of at least MinPrec. 264ExprResult 265Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) { 266 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(), 267 GreaterThanIsOperator, 268 getLang().CPlusPlus0x); 269 SourceLocation ColonLoc; 270 271 while (1) { 272 // If this token has a lower precedence than we are allowed to parse (e.g. 273 // because we are called recursively, or because the token is not a binop), 274 // then we are done! 275 if (NextTokPrec < MinPrec) 276 return move(LHS); 277 278 // Consume the operator, saving the operator token for error reporting. 279 Token OpToken = Tok; 280 ConsumeToken(); 281 282 // Special case handling for the ternary operator. 283 ExprResult TernaryMiddle(true); 284 if (NextTokPrec == prec::Conditional) { 285 if (Tok.isNot(tok::colon)) { 286 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 287 ColonProtectionRAIIObject X(*this); 288 289 // Handle this production specially: 290 // logical-OR-expression '?' expression ':' conditional-expression 291 // In particular, the RHS of the '?' is 'expression', not 292 // 'logical-OR-expression' as we might expect. 293 TernaryMiddle = ParseExpression(); 294 if (TernaryMiddle.isInvalid()) 295 return move(TernaryMiddle); 296 } else { 297 // Special case handling of "X ? Y : Z" where Y is empty: 298 // logical-OR-expression '?' ':' conditional-expression [GNU] 299 TernaryMiddle = 0; 300 Diag(Tok, diag::ext_gnu_conditional_expr); 301 } 302 303 if (Tok.is(tok::colon)) { 304 // Eat the colon. 305 ColonLoc = ConsumeToken(); 306 } else { 307 // Otherwise, we're missing a ':'. Assume that this was a typo that the 308 // user forgot. If we're not in a macro instantion, we can suggest a 309 // fixit hint. If there were two spaces before the current token, 310 // suggest inserting the colon in between them, otherwise insert ": ". 311 SourceLocation FILoc = Tok.getLocation(); 312 const char *FIText = ": "; 313 if (FILoc.isFileID()) { 314 const SourceManager &SM = PP.getSourceManager(); 315 bool IsInvalid = false; 316 const char *SourcePtr = 317 SM.getCharacterData(FILoc.getFileLocWithOffset(-1), &IsInvalid); 318 if (!IsInvalid && *SourcePtr == ' ') { 319 SourcePtr = 320 SM.getCharacterData(FILoc.getFileLocWithOffset(-2), &IsInvalid); 321 if (!IsInvalid && *SourcePtr == ' ') { 322 FILoc = FILoc.getFileLocWithOffset(-1); 323 FIText = ":"; 324 } 325 } 326 } 327 328 Diag(Tok, diag::err_expected_colon) 329 << FixItHint::CreateInsertion(FILoc, FIText); 330 Diag(OpToken, diag::note_matching) << "?"; 331 ColonLoc = Tok.getLocation(); 332 } 333 } 334 335 // Code completion for the right-hand side of an assignment expression 336 // goes through a special hook that takes the left-hand side into account. 337 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) { 338 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get()); 339 ConsumeCodeCompletionToken(); 340 return ExprError(); 341 } 342 343 // Parse another leaf here for the RHS of the operator. 344 // ParseCastExpression works here because all RHS expressions in C have it 345 // as a prefix, at least. However, in C++, an assignment-expression could 346 // be a throw-expression, which is not a valid cast-expression. 347 // Therefore we need some special-casing here. 348 // Also note that the third operand of the conditional operator is 349 // an assignment-expression in C++. 350 ExprResult RHS; 351 if (getLang().CPlusPlus && NextTokPrec <= prec::Conditional) 352 RHS = ParseAssignmentExpression(); 353 else 354 RHS = ParseCastExpression(false); 355 356 if (RHS.isInvalid()) 357 LHS = ExprError(); 358 359 // Remember the precedence of this operator and get the precedence of the 360 // operator immediately to the right of the RHS. 361 prec::Level ThisPrec = NextTokPrec; 362 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, 363 getLang().CPlusPlus0x); 364 365 // Assignment and conditional expressions are right-associative. 366 bool isRightAssoc = ThisPrec == prec::Conditional || 367 ThisPrec == prec::Assignment; 368 369 // Get the precedence of the operator to the right of the RHS. If it binds 370 // more tightly with RHS than we do, evaluate it completely first. 371 if (ThisPrec < NextTokPrec || 372 (ThisPrec == NextTokPrec && isRightAssoc)) { 373 // If this is left-associative, only parse things on the RHS that bind 374 // more tightly than the current operator. If it is left-associative, it 375 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as 376 // A=(B=(C=D)), where each paren is a level of recursion here. 377 // The function takes ownership of the RHS. 378 RHS = ParseRHSOfBinaryExpression(RHS, 379 static_cast<prec::Level>(ThisPrec + !isRightAssoc)); 380 381 if (RHS.isInvalid()) 382 LHS = ExprError(); 383 384 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, 385 getLang().CPlusPlus0x); 386 } 387 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!"); 388 389 if (!LHS.isInvalid()) { 390 // Combine the LHS and RHS into the LHS (e.g. build AST). 391 if (TernaryMiddle.isInvalid()) { 392 // If we're using '>>' as an operator within a template 393 // argument list (in C++98), suggest the addition of 394 // parentheses so that the code remains well-formed in C++0x. 395 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater)) 396 SuggestParentheses(OpToken.getLocation(), 397 diag::warn_cxx0x_right_shift_in_template_arg, 398 SourceRange(Actions.getExprRange(LHS.get()).getBegin(), 399 Actions.getExprRange(RHS.get()).getEnd())); 400 401 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(), 402 OpToken.getKind(), LHS.take(), RHS.take()); 403 } else 404 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc, 405 LHS.take(), TernaryMiddle.take(), 406 RHS.take()); 407 } 408 } 409} 410 411/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is 412/// true, parse a unary-expression. isAddressOfOperand exists because an 413/// id-expression that is the operand of address-of gets special treatment 414/// due to member pointers. 415/// 416ExprResult Parser::ParseCastExpression(bool isUnaryExpression, 417 bool isAddressOfOperand, 418 ParsedType TypeOfCast) { 419 bool NotCastExpr; 420 ExprResult Res = ParseCastExpression(isUnaryExpression, 421 isAddressOfOperand, 422 NotCastExpr, 423 TypeOfCast); 424 if (NotCastExpr) 425 Diag(Tok, diag::err_expected_expression); 426 return move(Res); 427} 428 429/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is 430/// true, parse a unary-expression. isAddressOfOperand exists because an 431/// id-expression that is the operand of address-of gets special treatment 432/// due to member pointers. NotCastExpr is set to true if the token is not the 433/// start of a cast-expression, and no diagnostic is emitted in this case. 434/// 435/// cast-expression: [C99 6.5.4] 436/// unary-expression 437/// '(' type-name ')' cast-expression 438/// 439/// unary-expression: [C99 6.5.3] 440/// postfix-expression 441/// '++' unary-expression 442/// '--' unary-expression 443/// unary-operator cast-expression 444/// 'sizeof' unary-expression 445/// 'sizeof' '(' type-name ')' 446/// [GNU] '__alignof' unary-expression 447/// [GNU] '__alignof' '(' type-name ')' 448/// [C++0x] 'alignof' '(' type-id ')' 449/// [GNU] '&&' identifier 450/// [C++] new-expression 451/// [C++] delete-expression 452/// [C++0x] 'noexcept' '(' expression ')' 453/// 454/// unary-operator: one of 455/// '&' '*' '+' '-' '~' '!' 456/// [GNU] '__extension__' '__real' '__imag' 457/// 458/// primary-expression: [C99 6.5.1] 459/// [C99] identifier 460/// [C++] id-expression 461/// constant 462/// string-literal 463/// [C++] boolean-literal [C++ 2.13.5] 464/// [C++0x] 'nullptr' [C++0x 2.14.7] 465/// '(' expression ')' 466/// '__func__' [C99 6.4.2.2] 467/// [GNU] '__FUNCTION__' 468/// [GNU] '__PRETTY_FUNCTION__' 469/// [GNU] '(' compound-statement ')' 470/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 471/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 472/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 473/// assign-expr ')' 474/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 475/// [GNU] '__null' 476/// [OBJC] '[' objc-message-expr ']' 477/// [OBJC] '@selector' '(' objc-selector-arg ')' 478/// [OBJC] '@protocol' '(' identifier ')' 479/// [OBJC] '@encode' '(' type-name ')' 480/// [OBJC] objc-string-literal 481/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 482/// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 483/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 484/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 485/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 486/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 487/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1] 488/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1] 489/// [C++] 'this' [C++ 9.3.2] 490/// [G++] unary-type-trait '(' type-id ')' 491/// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO] 492/// [clang] '^' block-literal 493/// 494/// constant: [C99 6.4.4] 495/// integer-constant 496/// floating-constant 497/// enumeration-constant -> identifier 498/// character-constant 499/// 500/// id-expression: [C++ 5.1] 501/// unqualified-id 502/// qualified-id 503/// 504/// unqualified-id: [C++ 5.1] 505/// identifier 506/// operator-function-id 507/// conversion-function-id 508/// '~' class-name 509/// template-id 510/// 511/// new-expression: [C++ 5.3.4] 512/// '::'[opt] 'new' new-placement[opt] new-type-id 513/// new-initializer[opt] 514/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 515/// new-initializer[opt] 516/// 517/// delete-expression: [C++ 5.3.5] 518/// '::'[opt] 'delete' cast-expression 519/// '::'[opt] 'delete' '[' ']' cast-expression 520/// 521/// [GNU] unary-type-trait: 522/// '__has_nothrow_assign' 523/// '__has_nothrow_copy' 524/// '__has_nothrow_constructor' 525/// '__has_trivial_assign' [TODO] 526/// '__has_trivial_copy' [TODO] 527/// '__has_trivial_constructor' 528/// '__has_trivial_destructor' 529/// '__has_virtual_destructor' 530/// '__is_abstract' [TODO] 531/// '__is_class' 532/// '__is_empty' [TODO] 533/// '__is_enum' 534/// '__is_pod' 535/// '__is_polymorphic' 536/// '__is_union' 537/// 538/// [GNU] binary-type-trait: 539/// '__is_base_of' [TODO] 540/// 541ExprResult Parser::ParseCastExpression(bool isUnaryExpression, 542 bool isAddressOfOperand, 543 bool &NotCastExpr, 544 ParsedType TypeOfCast) { 545 ExprResult Res; 546 tok::TokenKind SavedKind = Tok.getKind(); 547 NotCastExpr = false; 548 549 // This handles all of cast-expression, unary-expression, postfix-expression, 550 // and primary-expression. We handle them together like this for efficiency 551 // and to simplify handling of an expression starting with a '(' token: which 552 // may be one of a parenthesized expression, cast-expression, compound literal 553 // expression, or statement expression. 554 // 555 // If the parsed tokens consist of a primary-expression, the cases below 556 // break out of the switch; at the end we call ParsePostfixExpressionSuffix 557 // to handle the postfix expression suffixes. Cases that cannot be followed 558 // by postfix exprs should return without invoking 559 // ParsePostfixExpressionSuffix. 560 switch (SavedKind) { 561 case tok::l_paren: { 562 // If this expression is limited to being a unary-expression, the parent can 563 // not start a cast expression. 564 ParenParseOption ParenExprType = 565 (isUnaryExpression && !getLang().CPlusPlus)? CompoundLiteral : CastExpr; 566 ParsedType CastTy; 567 SourceLocation LParenLoc = Tok.getLocation(); 568 SourceLocation RParenLoc; 569 570 { 571 // The inside of the parens don't need to be a colon protected scope, and 572 // isn't immediately a message send. 573 ColonProtectionRAIIObject X(*this, false); 574 575 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/, 576 TypeOfCast, CastTy, RParenLoc); 577 if (Res.isInvalid()) 578 return move(Res); 579 } 580 581 switch (ParenExprType) { 582 case SimpleExpr: break; // Nothing else to do. 583 case CompoundStmt: break; // Nothing else to do. 584 case CompoundLiteral: 585 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of 586 // postfix-expression exist, parse them now. 587 break; 588 case CastExpr: 589 // We have parsed the cast-expression and no postfix-expr pieces are 590 // following. 591 return move(Res); 592 } 593 594 break; 595 } 596 597 // primary-expression 598 case tok::numeric_constant: 599 // constant: integer-constant 600 // constant: floating-constant 601 602 Res = Actions.ActOnNumericConstant(Tok); 603 ConsumeToken(); 604 break; 605 606 case tok::kw_true: 607 case tok::kw_false: 608 return ParseCXXBoolLiteral(); 609 610 case tok::kw_nullptr: 611 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken()); 612 613 case tok::identifier: { // primary-expression: identifier 614 // unqualified-id: identifier 615 // constant: enumeration-constant 616 // Turn a potentially qualified name into a annot_typename or 617 // annot_cxxscope if it would be valid. This handles things like x::y, etc. 618 if (getLang().CPlusPlus) { 619 // Avoid the unnecessary parse-time lookup in the common case 620 // where the syntax forbids a type. 621 const Token &Next = NextToken(); 622 if (Next.is(tok::coloncolon) || 623 (!ColonIsSacred && Next.is(tok::colon)) || 624 Next.is(tok::less) || 625 Next.is(tok::l_paren)) { 626 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 627 if (TryAnnotateTypeOrScopeToken()) 628 return ExprError(); 629 if (!Tok.is(tok::identifier)) 630 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 631 } 632 } 633 634 // Consume the identifier so that we can see if it is followed by a '(' or 635 // '.'. 636 IdentifierInfo &II = *Tok.getIdentifierInfo(); 637 SourceLocation ILoc = ConsumeToken(); 638 639 // Support 'Class.property' and 'super.property' notation. 640 if (getLang().ObjC1 && Tok.is(tok::period) && 641 (Actions.getTypeName(II, ILoc, getCurScope()) || 642 // Allow the base to be 'super' if in an objc-method. 643 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) { 644 SourceLocation DotLoc = ConsumeToken(); 645 646 if (Tok.isNot(tok::identifier)) { 647 Diag(Tok, diag::err_expected_property_name); 648 return ExprError(); 649 } 650 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); 651 SourceLocation PropertyLoc = ConsumeToken(); 652 653 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName, 654 ILoc, PropertyLoc); 655 break; 656 } 657 658 // In an Objective-C method, if we have "super" followed by an identifier, 659 // the token sequence is ill-formed. However, if there's a ':' or ']' after 660 // that identifier, this is probably a message send with a missing open 661 // bracket. Treat it as such. 662 if (getLang().ObjC1 && &II == Ident_super && !InMessageExpression && 663 getCurScope()->isInObjcMethodScope() && 664 ((Tok.is(tok::identifier) && 665 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) || 666 Tok.is(tok::code_completion))) { 667 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(), 668 0); 669 break; 670 } 671 672 // If we have an Objective-C class name followed by an identifier and 673 // either ':' or ']', this is an Objective-C class message send that's 674 // missing the opening '['. Recovery appropriately. 675 if (getLang().ObjC1 && Tok.is(tok::identifier)) { 676 const Token& Next = NextToken(); 677 if (Next.is(tok::colon) || Next.is(tok::r_square)) 678 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope())) 679 if (Typ.get()->isObjCObjectOrInterfaceType()) { 680 // Fake up a Declarator to use with ActOnTypeName. 681 DeclSpec DS; 682 DS.SetRangeStart(ILoc); 683 DS.SetRangeEnd(ILoc); 684 const char *PrevSpec = 0; 685 unsigned DiagID; 686 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ); 687 688 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 689 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), 690 DeclaratorInfo); 691 if (Ty.isInvalid()) 692 break; 693 694 Res = ParseObjCMessageExpressionBody(SourceLocation(), 695 SourceLocation(), 696 Ty.get(), 0); 697 break; 698 } 699 } 700 701 // Make sure to pass down the right value for isAddressOfOperand. 702 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 703 isAddressOfOperand = false; 704 705 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we 706 // need to know whether or not this identifier is a function designator or 707 // not. 708 UnqualifiedId Name; 709 CXXScopeSpec ScopeSpec; 710 Name.setIdentifier(&II, ILoc); 711 Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, Name, 712 Tok.is(tok::l_paren), isAddressOfOperand); 713 break; 714 } 715 case tok::char_constant: // constant: character-constant 716 Res = Actions.ActOnCharacterConstant(Tok); 717 ConsumeToken(); 718 break; 719 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] 720 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] 721 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] 722 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind); 723 ConsumeToken(); 724 break; 725 case tok::string_literal: // primary-expression: string-literal 726 case tok::wide_string_literal: 727 Res = ParseStringLiteralExpression(); 728 break; 729 case tok::kw___builtin_va_arg: 730 case tok::kw___builtin_offsetof: 731 case tok::kw___builtin_choose_expr: 732 case tok::kw___builtin_types_compatible_p: 733 return ParseBuiltinPrimaryExpression(); 734 case tok::kw___null: 735 return Actions.ActOnGNUNullExpr(ConsumeToken()); 736 break; 737 case tok::plusplus: // unary-expression: '++' unary-expression [C99] 738 case tok::minusminus: { // unary-expression: '--' unary-expression [C99] 739 // C++ [expr.unary] has: 740 // unary-expression: 741 // ++ cast-expression 742 // -- cast-expression 743 SourceLocation SavedLoc = ConsumeToken(); 744 Res = ParseCastExpression(!getLang().CPlusPlus); 745 if (!Res.isInvalid()) 746 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 747 return move(Res); 748 } 749 case tok::amp: { // unary-expression: '&' cast-expression 750 // Special treatment because of member pointers 751 SourceLocation SavedLoc = ConsumeToken(); 752 Res = ParseCastExpression(false, true); 753 if (!Res.isInvalid()) 754 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 755 return move(Res); 756 } 757 758 case tok::star: // unary-expression: '*' cast-expression 759 case tok::plus: // unary-expression: '+' cast-expression 760 case tok::minus: // unary-expression: '-' cast-expression 761 case tok::tilde: // unary-expression: '~' cast-expression 762 case tok::exclaim: // unary-expression: '!' cast-expression 763 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] 764 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] 765 SourceLocation SavedLoc = ConsumeToken(); 766 Res = ParseCastExpression(false); 767 if (!Res.isInvalid()) 768 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 769 return move(Res); 770 } 771 772 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] 773 // __extension__ silences extension warnings in the subexpression. 774 ExtensionRAIIObject O(Diags); // Use RAII to do this. 775 SourceLocation SavedLoc = ConsumeToken(); 776 Res = ParseCastExpression(false); 777 if (!Res.isInvalid()) 778 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 779 return move(Res); 780 } 781 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression 782 // unary-expression: 'sizeof' '(' type-name ')' 783 case tok::kw_alignof: 784 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression 785 // unary-expression: '__alignof' '(' type-name ')' 786 // unary-expression: 'alignof' '(' type-id ')' 787 return ParseSizeofAlignofExpression(); 788 case tok::ampamp: { // unary-expression: '&&' identifier 789 SourceLocation AmpAmpLoc = ConsumeToken(); 790 if (Tok.isNot(tok::identifier)) 791 return ExprError(Diag(Tok, diag::err_expected_ident)); 792 793 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); 794 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), 795 Tok.getIdentifierInfo()); 796 ConsumeToken(); 797 return move(Res); 798 } 799 case tok::kw_const_cast: 800 case tok::kw_dynamic_cast: 801 case tok::kw_reinterpret_cast: 802 case tok::kw_static_cast: 803 Res = ParseCXXCasts(); 804 break; 805 case tok::kw_typeid: 806 Res = ParseCXXTypeid(); 807 break; 808 case tok::kw___uuidof: 809 Res = ParseCXXUuidof(); 810 break; 811 case tok::kw_this: 812 Res = ParseCXXThis(); 813 break; 814 815 case tok::annot_typename: 816 if (isStartOfObjCClassMessageMissingOpenBracket()) { 817 ParsedType Type = getTypeAnnotation(Tok); 818 819 // Fake up a Declarator to use with ActOnTypeName. 820 DeclSpec DS; 821 DS.SetRangeStart(Tok.getLocation()); 822 DS.SetRangeEnd(Tok.getLastLoc()); 823 824 const char *PrevSpec = 0; 825 unsigned DiagID; 826 DS.SetTypeSpecType(TST_typename, Tok.getLocation(), PrevSpec, DiagID, 827 Type); 828 829 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 830 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 831 if (Ty.isInvalid()) 832 break; 833 834 ConsumeToken(); 835 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 836 Ty.get(), 0); 837 break; 838 } 839 // Fall through 840 841 case tok::kw_char: 842 case tok::kw_wchar_t: 843 case tok::kw_char16_t: 844 case tok::kw_char32_t: 845 case tok::kw_bool: 846 case tok::kw_short: 847 case tok::kw_int: 848 case tok::kw_long: 849 case tok::kw_signed: 850 case tok::kw_unsigned: 851 case tok::kw_float: 852 case tok::kw_double: 853 case tok::kw_void: 854 case tok::kw_typename: 855 case tok::kw_typeof: 856 case tok::kw___vector: { 857 if (!getLang().CPlusPlus) { 858 Diag(Tok, diag::err_expected_expression); 859 return ExprError(); 860 } 861 862 if (SavedKind == tok::kw_typename) { 863 // postfix-expression: typename-specifier '(' expression-list[opt] ')' 864 if (TryAnnotateTypeOrScopeToken()) 865 return ExprError(); 866 } 867 868 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' 869 // 870 DeclSpec DS; 871 ParseCXXSimpleTypeSpecifier(DS); 872 if (Tok.isNot(tok::l_paren)) 873 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) 874 << DS.getSourceRange()); 875 876 Res = ParseCXXTypeConstructExpression(DS); 877 break; 878 } 879 880 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id 881 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 882 // (We can end up in this situation after tentative parsing.) 883 if (TryAnnotateTypeOrScopeToken()) 884 return ExprError(); 885 if (!Tok.is(tok::annot_cxxscope)) 886 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 887 NotCastExpr, TypeOfCast); 888 889 Token Next = NextToken(); 890 if (Next.is(tok::annot_template_id)) { 891 TemplateIdAnnotation *TemplateId 892 = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()); 893 if (TemplateId->Kind == TNK_Type_template) { 894 // We have a qualified template-id that we know refers to a 895 // type, translate it into a type and continue parsing as a 896 // cast expression. 897 CXXScopeSpec SS; 898 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 899 AnnotateTemplateIdTokenAsType(&SS); 900 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 901 NotCastExpr, TypeOfCast); 902 } 903 } 904 905 // Parse as an id-expression. 906 Res = ParseCXXIdExpression(isAddressOfOperand); 907 break; 908 } 909 910 case tok::annot_template_id: { // [C++] template-id 911 TemplateIdAnnotation *TemplateId 912 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 913 if (TemplateId->Kind == TNK_Type_template) { 914 // We have a template-id that we know refers to a type, 915 // translate it into a type and continue parsing as a cast 916 // expression. 917 AnnotateTemplateIdTokenAsType(); 918 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 919 NotCastExpr, TypeOfCast); 920 } 921 922 // Fall through to treat the template-id as an id-expression. 923 } 924 925 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id 926 Res = ParseCXXIdExpression(isAddressOfOperand); 927 break; 928 929 case tok::coloncolon: { 930 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken 931 // annotates the token, tail recurse. 932 if (TryAnnotateTypeOrScopeToken()) 933 return ExprError(); 934 if (!Tok.is(tok::coloncolon)) 935 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 936 937 // ::new -> [C++] new-expression 938 // ::delete -> [C++] delete-expression 939 SourceLocation CCLoc = ConsumeToken(); 940 if (Tok.is(tok::kw_new)) 941 return ParseCXXNewExpression(true, CCLoc); 942 if (Tok.is(tok::kw_delete)) 943 return ParseCXXDeleteExpression(true, CCLoc); 944 945 // This is not a type name or scope specifier, it is an invalid expression. 946 Diag(CCLoc, diag::err_expected_expression); 947 return ExprError(); 948 } 949 950 case tok::kw_new: // [C++] new-expression 951 return ParseCXXNewExpression(false, Tok.getLocation()); 952 953 case tok::kw_delete: // [C++] delete-expression 954 return ParseCXXDeleteExpression(false, Tok.getLocation()); 955 956 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')' 957 SourceLocation KeyLoc = ConsumeToken(); 958 SourceLocation LParen = Tok.getLocation(); 959 if (ExpectAndConsume(tok::l_paren, 960 diag::err_expected_lparen_after, "noexcept")) 961 return ExprError(); 962 // C++ [expr.unary.noexcept]p1: 963 // The noexcept operator determines whether the evaluation of its operand, 964 // which is an unevaluated operand, can throw an exception. 965 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 966 ExprResult Result = ParseExpression(); 967 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 968 if (!Result.isInvalid()) 969 Result = Actions.ActOnNoexceptExpr(KeyLoc, LParen, Result.take(), RParen); 970 return move(Result); 971 } 972 973 case tok::kw___is_pod: // [GNU] unary-type-trait 974 case tok::kw___is_class: 975 case tok::kw___is_enum: 976 case tok::kw___is_union: 977 case tok::kw___is_empty: 978 case tok::kw___is_polymorphic: 979 case tok::kw___is_abstract: 980 case tok::kw___is_literal: 981 case tok::kw___has_trivial_constructor: 982 case tok::kw___has_trivial_copy: 983 case tok::kw___has_trivial_assign: 984 case tok::kw___has_trivial_destructor: 985 case tok::kw___has_nothrow_assign: 986 case tok::kw___has_nothrow_copy: 987 case tok::kw___has_nothrow_constructor: 988 case tok::kw___has_virtual_destructor: 989 return ParseUnaryTypeTrait(); 990 991 case tok::at: { 992 SourceLocation AtLoc = ConsumeToken(); 993 return ParseObjCAtExpression(AtLoc); 994 } 995 case tok::caret: 996 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression()); 997 case tok::code_completion: 998 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 999 ConsumeCodeCompletionToken(); 1000 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1001 NotCastExpr, TypeOfCast); 1002 case tok::l_square: 1003 // These can be followed by postfix-expr pieces. 1004 if (getLang().ObjC1) 1005 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression()); 1006 // FALL THROUGH. 1007 default: 1008 NotCastExpr = true; 1009 return ExprError(); 1010 } 1011 1012 // These can be followed by postfix-expr pieces. 1013 if (Res.isInvalid()) return move(Res); 1014 return ParsePostfixExpressionSuffix(Res.get()); 1015} 1016 1017/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression 1018/// is parsed, this method parses any suffixes that apply. 1019/// 1020/// postfix-expression: [C99 6.5.2] 1021/// primary-expression 1022/// postfix-expression '[' expression ']' 1023/// postfix-expression '(' argument-expression-list[opt] ')' 1024/// postfix-expression '.' identifier 1025/// postfix-expression '->' identifier 1026/// postfix-expression '++' 1027/// postfix-expression '--' 1028/// '(' type-name ')' '{' initializer-list '}' 1029/// '(' type-name ')' '{' initializer-list ',' '}' 1030/// 1031/// argument-expression-list: [C99 6.5.2] 1032/// argument-expression 1033/// argument-expression-list ',' assignment-expression 1034/// 1035ExprResult 1036Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { 1037 // Now that the primary-expression piece of the postfix-expression has been 1038 // parsed, see if there are any postfix-expression pieces here. 1039 SourceLocation Loc; 1040 while (1) { 1041 switch (Tok.getKind()) { 1042 case tok::code_completion: 1043 if (InMessageExpression) 1044 return move(LHS); 1045 1046 Actions.CodeCompletePostfixExpression(getCurScope(), LHS.take()); 1047 ConsumeCodeCompletionToken(); 1048 LHS = ExprError(); 1049 break; 1050 1051 case tok::identifier: 1052 // If we see identifier: after an expression, and we're not already in a 1053 // message send, then this is probably a message send with a missing 1054 // opening bracket '['. 1055 if (getLang().ObjC1 && !InMessageExpression && 1056 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 1057 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 1058 ParsedType(), LHS.get()); 1059 break; 1060 } 1061 1062 // Fall through; this isn't a message send. 1063 1064 default: // Not a postfix-expression suffix. 1065 return move(LHS); 1066 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 1067 // If we have a array postfix expression that starts on a new line and 1068 // Objective-C is enabled, it is highly likely that the user forgot a 1069 // semicolon after the base expression and that the array postfix-expr is 1070 // actually another message send. In this case, do some look-ahead to see 1071 // if the contents of the square brackets are obviously not a valid 1072 // expression and recover by pretending there is no suffix. 1073 if (getLang().ObjC1 && Tok.isAtStartOfLine() && 1074 isSimpleObjCMessageExpression()) 1075 return move(LHS); 1076 1077 Loc = ConsumeBracket(); 1078 ExprResult Idx(ParseExpression()); 1079 1080 SourceLocation RLoc = Tok.getLocation(); 1081 1082 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 1083 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc, 1084 Idx.take(), RLoc); 1085 } else 1086 LHS = ExprError(); 1087 1088 // Match the ']'. 1089 MatchRHSPunctuation(tok::r_square, Loc); 1090 break; 1091 } 1092 1093 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')' 1094 InMessageExpressionRAIIObject InMessage(*this, false); 1095 1096 ExprVector ArgExprs(Actions); 1097 CommaLocsTy CommaLocs; 1098 1099 Loc = ConsumeParen(); 1100 1101 if (LHS.isInvalid()) { 1102 SkipUntil(tok::r_paren); 1103 return ExprError(); 1104 } 1105 1106 if (Tok.is(tok::code_completion)) { 1107 Actions.CodeCompleteCall(getCurScope(), LHS.get(), 0, 0); 1108 ConsumeCodeCompletionToken(); 1109 } 1110 1111 if (Tok.isNot(tok::r_paren)) { 1112 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall, 1113 LHS.get())) { 1114 SkipUntil(tok::r_paren); 1115 return ExprError(); 1116 } 1117 } 1118 1119 // Match the ')'. 1120 if (Tok.isNot(tok::r_paren)) { 1121 MatchRHSPunctuation(tok::r_paren, Loc); 1122 return ExprError(); 1123 } 1124 1125 if (!LHS.isInvalid()) { 1126 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&& 1127 "Unexpected number of commas!"); 1128 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc, 1129 move_arg(ArgExprs), Tok.getLocation()); 1130 } 1131 1132 ConsumeParen(); 1133 break; 1134 } 1135 case tok::arrow: 1136 case tok::period: { 1137 // postfix-expression: p-e '->' template[opt] id-expression 1138 // postfix-expression: p-e '.' template[opt] id-expression 1139 tok::TokenKind OpKind = Tok.getKind(); 1140 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 1141 1142 CXXScopeSpec SS; 1143 ParsedType ObjectType; 1144 bool MayBePseudoDestructor = false; 1145 if (getLang().CPlusPlus && !LHS.isInvalid()) { 1146 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(), 1147 OpLoc, OpKind, ObjectType, 1148 MayBePseudoDestructor); 1149 if (LHS.isInvalid()) 1150 break; 1151 1152 ParseOptionalCXXScopeSpecifier(SS, ObjectType, false, 1153 &MayBePseudoDestructor); 1154 if (SS.isNotEmpty()) 1155 ObjectType = ParsedType(); 1156 } 1157 1158 if (Tok.is(tok::code_completion)) { 1159 // Code completion for a member access expression. 1160 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(), 1161 OpLoc, OpKind == tok::arrow); 1162 1163 ConsumeCodeCompletionToken(); 1164 } 1165 1166 if (MayBePseudoDestructor && !LHS.isInvalid()) { 1167 LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS, 1168 ObjectType); 1169 break; 1170 } 1171 1172 // Either the action has told is that this cannot be a 1173 // pseudo-destructor expression (based on the type of base 1174 // expression), or we didn't see a '~' in the right place. We 1175 // can still parse a destructor name here, but in that case it 1176 // names a real destructor. 1177 UnqualifiedId Name; 1178 if (ParseUnqualifiedId(SS, 1179 /*EnteringContext=*/false, 1180 /*AllowDestructorName=*/true, 1181 /*AllowConstructorName=*/false, 1182 ObjectType, 1183 Name)) 1184 return ExprError(); 1185 1186 if (!LHS.isInvalid()) 1187 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc, 1188 OpKind, SS, Name, ObjCImpDecl, 1189 Tok.is(tok::l_paren)); 1190 break; 1191 } 1192 case tok::plusplus: // postfix-expression: postfix-expression '++' 1193 case tok::minusminus: // postfix-expression: postfix-expression '--' 1194 if (!LHS.isInvalid()) { 1195 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(), 1196 Tok.getKind(), LHS.take()); 1197 } 1198 ConsumeToken(); 1199 break; 1200 } 1201 } 1202} 1203 1204/// ParseExprAfterTypeofSizeofAlignof - We parsed a typeof/sizeof/alignof and 1205/// we are at the start of an expression or a parenthesized type-id. 1206/// OpTok is the operand token (typeof/sizeof/alignof). Returns the expression 1207/// (isCastExpr == false) or the type (isCastExpr == true). 1208/// 1209/// unary-expression: [C99 6.5.3] 1210/// 'sizeof' unary-expression 1211/// 'sizeof' '(' type-name ')' 1212/// [GNU] '__alignof' unary-expression 1213/// [GNU] '__alignof' '(' type-name ')' 1214/// [C++0x] 'alignof' '(' type-id ')' 1215/// 1216/// [GNU] typeof-specifier: 1217/// typeof ( expressions ) 1218/// typeof ( type-name ) 1219/// [GNU/C++] typeof unary-expression 1220/// 1221ExprResult 1222Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, 1223 bool &isCastExpr, 1224 ParsedType &CastTy, 1225 SourceRange &CastRange) { 1226 1227 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 1228 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof)) && 1229 "Not a typeof/sizeof/alignof expression!"); 1230 1231 ExprResult Operand; 1232 1233 // If the operand doesn't start with an '(', it must be an expression. 1234 if (Tok.isNot(tok::l_paren)) { 1235 isCastExpr = false; 1236 if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) { 1237 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 1238 return ExprError(); 1239 } 1240 1241 // C++0x [expr.sizeof]p1: 1242 // [...] The operand is either an expression, which is an unevaluated 1243 // operand (Clause 5) [...] 1244 // 1245 // The GNU typeof and alignof extensions also behave as unevaluated 1246 // operands. 1247 EnterExpressionEvaluationContext Unevaluated(Actions, 1248 Sema::Unevaluated); 1249 Operand = ParseCastExpression(true/*isUnaryExpression*/); 1250 } else { 1251 // If it starts with a '(', we know that it is either a parenthesized 1252 // type-name, or it is a unary-expression that starts with a compound 1253 // literal, or starts with a primary-expression that is a parenthesized 1254 // expression. 1255 ParenParseOption ExprType = CastExpr; 1256 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 1257 1258 // C++0x [expr.sizeof]p1: 1259 // [...] The operand is either an expression, which is an unevaluated 1260 // operand (Clause 5) [...] 1261 // 1262 // The GNU typeof and alignof extensions also behave as unevaluated 1263 // operands. 1264 EnterExpressionEvaluationContext Unevaluated(Actions, 1265 Sema::Unevaluated); 1266 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 1267 ParsedType(), CastTy, RParenLoc); 1268 CastRange = SourceRange(LParenLoc, RParenLoc); 1269 1270 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 1271 // a type. 1272 if (ExprType == CastExpr) { 1273 isCastExpr = true; 1274 return ExprEmpty(); 1275 } 1276 1277 if (getLang().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { 1278 // GNU typeof in C requires the expression to be parenthesized. Not so for 1279 // sizeof/alignof or in C++. Therefore, the parenthesized expression is 1280 // the start of a unary-expression, but doesn't include any postfix 1281 // pieces. Parse these now if present. 1282 if (!Operand.isInvalid()) 1283 Operand = ParsePostfixExpressionSuffix(Operand.get()); 1284 } 1285 } 1286 1287 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 1288 isCastExpr = false; 1289 return move(Operand); 1290} 1291 1292 1293/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression. 1294/// unary-expression: [C99 6.5.3] 1295/// 'sizeof' unary-expression 1296/// 'sizeof' '(' type-name ')' 1297/// [GNU] '__alignof' unary-expression 1298/// [GNU] '__alignof' '(' type-name ')' 1299/// [C++0x] 'alignof' '(' type-id ')' 1300ExprResult Parser::ParseSizeofAlignofExpression() { 1301 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) 1302 || Tok.is(tok::kw_alignof)) && 1303 "Not a sizeof/alignof expression!"); 1304 Token OpTok = Tok; 1305 ConsumeToken(); 1306 1307 bool isCastExpr; 1308 ParsedType CastTy; 1309 SourceRange CastRange; 1310 ExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 1311 isCastExpr, 1312 CastTy, 1313 CastRange); 1314 1315 if (isCastExpr) 1316 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1317 OpTok.is(tok::kw_sizeof), 1318 /*isType=*/true, 1319 CastTy.getAsOpaquePtr(), 1320 CastRange); 1321 1322 // If we get here, the operand to the sizeof/alignof was an expresion. 1323 if (!Operand.isInvalid()) 1324 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1325 OpTok.is(tok::kw_sizeof), 1326 /*isType=*/false, 1327 Operand.release(), CastRange); 1328 return move(Operand); 1329} 1330 1331/// ParseBuiltinPrimaryExpression 1332/// 1333/// primary-expression: [C99 6.5.1] 1334/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1335/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1336/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1337/// assign-expr ')' 1338/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1339/// 1340/// [GNU] offsetof-member-designator: 1341/// [GNU] identifier 1342/// [GNU] offsetof-member-designator '.' identifier 1343/// [GNU] offsetof-member-designator '[' expression ']' 1344/// 1345ExprResult Parser::ParseBuiltinPrimaryExpression() { 1346 ExprResult Res; 1347 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1348 1349 tok::TokenKind T = Tok.getKind(); 1350 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1351 1352 // All of these start with an open paren. 1353 if (Tok.isNot(tok::l_paren)) 1354 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1355 << BuiltinII); 1356 1357 SourceLocation LParenLoc = ConsumeParen(); 1358 // TODO: Build AST. 1359 1360 switch (T) { 1361 default: assert(0 && "Not a builtin primary expression!"); 1362 case tok::kw___builtin_va_arg: { 1363 ExprResult Expr(ParseAssignmentExpression()); 1364 if (Expr.isInvalid()) { 1365 SkipUntil(tok::r_paren); 1366 return ExprError(); 1367 } 1368 1369 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1370 return ExprError(); 1371 1372 TypeResult Ty = ParseTypeName(); 1373 1374 if (Tok.isNot(tok::r_paren)) { 1375 Diag(Tok, diag::err_expected_rparen); 1376 return ExprError(); 1377 } 1378 if (Ty.isInvalid()) 1379 Res = ExprError(); 1380 else 1381 Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen()); 1382 break; 1383 } 1384 case tok::kw___builtin_offsetof: { 1385 SourceLocation TypeLoc = Tok.getLocation(); 1386 TypeResult Ty = ParseTypeName(); 1387 if (Ty.isInvalid()) { 1388 SkipUntil(tok::r_paren); 1389 return ExprError(); 1390 } 1391 1392 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1393 return ExprError(); 1394 1395 // We must have at least one identifier here. 1396 if (Tok.isNot(tok::identifier)) { 1397 Diag(Tok, diag::err_expected_ident); 1398 SkipUntil(tok::r_paren); 1399 return ExprError(); 1400 } 1401 1402 // Keep track of the various subcomponents we see. 1403 llvm::SmallVector<Sema::OffsetOfComponent, 4> Comps; 1404 1405 Comps.push_back(Sema::OffsetOfComponent()); 1406 Comps.back().isBrackets = false; 1407 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1408 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1409 1410 // FIXME: This loop leaks the index expressions on error. 1411 while (1) { 1412 if (Tok.is(tok::period)) { 1413 // offsetof-member-designator: offsetof-member-designator '.' identifier 1414 Comps.push_back(Sema::OffsetOfComponent()); 1415 Comps.back().isBrackets = false; 1416 Comps.back().LocStart = ConsumeToken(); 1417 1418 if (Tok.isNot(tok::identifier)) { 1419 Diag(Tok, diag::err_expected_ident); 1420 SkipUntil(tok::r_paren); 1421 return ExprError(); 1422 } 1423 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1424 Comps.back().LocEnd = ConsumeToken(); 1425 1426 } else if (Tok.is(tok::l_square)) { 1427 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1428 Comps.push_back(Sema::OffsetOfComponent()); 1429 Comps.back().isBrackets = true; 1430 Comps.back().LocStart = ConsumeBracket(); 1431 Res = ParseExpression(); 1432 if (Res.isInvalid()) { 1433 SkipUntil(tok::r_paren); 1434 return move(Res); 1435 } 1436 Comps.back().U.E = Res.release(); 1437 1438 Comps.back().LocEnd = 1439 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart); 1440 } else { 1441 if (Tok.isNot(tok::r_paren)) { 1442 MatchRHSPunctuation(tok::r_paren, LParenLoc); 1443 Res = ExprError(); 1444 } else if (Ty.isInvalid()) { 1445 Res = ExprError(); 1446 } else { 1447 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc, 1448 Ty.get(), &Comps[0], 1449 Comps.size(), ConsumeParen()); 1450 } 1451 break; 1452 } 1453 } 1454 break; 1455 } 1456 case tok::kw___builtin_choose_expr: { 1457 ExprResult Cond(ParseAssignmentExpression()); 1458 if (Cond.isInvalid()) { 1459 SkipUntil(tok::r_paren); 1460 return move(Cond); 1461 } 1462 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1463 return ExprError(); 1464 1465 ExprResult Expr1(ParseAssignmentExpression()); 1466 if (Expr1.isInvalid()) { 1467 SkipUntil(tok::r_paren); 1468 return move(Expr1); 1469 } 1470 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1471 return ExprError(); 1472 1473 ExprResult Expr2(ParseAssignmentExpression()); 1474 if (Expr2.isInvalid()) { 1475 SkipUntil(tok::r_paren); 1476 return move(Expr2); 1477 } 1478 if (Tok.isNot(tok::r_paren)) { 1479 Diag(Tok, diag::err_expected_rparen); 1480 return ExprError(); 1481 } 1482 Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(), 1483 Expr2.take(), ConsumeParen()); 1484 break; 1485 } 1486 case tok::kw___builtin_types_compatible_p: 1487 TypeResult Ty1 = ParseTypeName(); 1488 1489 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1490 return ExprError(); 1491 1492 TypeResult Ty2 = ParseTypeName(); 1493 1494 if (Tok.isNot(tok::r_paren)) { 1495 Diag(Tok, diag::err_expected_rparen); 1496 return ExprError(); 1497 } 1498 1499 if (Ty1.isInvalid() || Ty2.isInvalid()) 1500 Res = ExprError(); 1501 else 1502 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1.get(), Ty2.get(), 1503 ConsumeParen()); 1504 break; 1505 } 1506 1507 if (Res.isInvalid()) 1508 return ExprError(); 1509 1510 // These can be followed by postfix-expr pieces because they are 1511 // primary-expressions. 1512 return ParsePostfixExpressionSuffix(Res.take()); 1513} 1514 1515/// ParseParenExpression - This parses the unit that starts with a '(' token, 1516/// based on what is allowed by ExprType. The actual thing parsed is returned 1517/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1518/// not the parsed cast-expression. 1519/// 1520/// primary-expression: [C99 6.5.1] 1521/// '(' expression ')' 1522/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1523/// postfix-expression: [C99 6.5.2] 1524/// '(' type-name ')' '{' initializer-list '}' 1525/// '(' type-name ')' '{' initializer-list ',' '}' 1526/// cast-expression: [C99 6.5.4] 1527/// '(' type-name ')' cast-expression 1528/// 1529ExprResult 1530Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1531 ParsedType TypeOfCast, ParsedType &CastTy, 1532 SourceLocation &RParenLoc) { 1533 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1534 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 1535 SourceLocation OpenLoc = ConsumeParen(); 1536 ExprResult Result(true); 1537 bool isAmbiguousTypeId; 1538 CastTy = ParsedType(); 1539 1540 if (Tok.is(tok::code_completion)) { 1541 Actions.CodeCompleteOrdinaryName(getCurScope(), 1542 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression 1543 : Sema::PCC_Expression); 1544 ConsumeCodeCompletionToken(); 1545 return ExprError(); 1546 } 1547 1548 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 1549 Diag(Tok, diag::ext_gnu_statement_expr); 1550 StmtResult Stmt(ParseCompoundStatement(0, true)); 1551 ExprType = CompoundStmt; 1552 1553 // If the substmt parsed correctly, build the AST node. 1554 if (!Stmt.isInvalid() && Tok.is(tok::r_paren)) 1555 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation()); 1556 1557 } else if (ExprType >= CompoundLiteral && 1558 isTypeIdInParens(isAmbiguousTypeId)) { 1559 1560 // Otherwise, this is a compound literal expression or cast expression. 1561 1562 // In C++, if the type-id is ambiguous we disambiguate based on context. 1563 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 1564 // in which case we should treat it as type-id. 1565 // if stopIfCastExpr is false, we need to determine the context past the 1566 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 1567 if (isAmbiguousTypeId && !stopIfCastExpr) 1568 return ParseCXXAmbiguousParenExpression(ExprType, CastTy, 1569 OpenLoc, RParenLoc); 1570 1571 TypeResult Ty; 1572 1573 { 1574 InMessageExpressionRAIIObject InMessage(*this, false); 1575 Ty = ParseTypeName(); 1576 } 1577 1578 // If our type is followed by an identifier and either ':' or ']', then 1579 // this is probably an Objective-C message send where the leading '[' is 1580 // missing. Recover as if that were the case. 1581 if (!Ty.isInvalid() && Tok.is(tok::identifier) && !InMessageExpression && 1582 getLang().ObjC1 && !Ty.get().get().isNull() && 1583 (NextToken().is(tok::colon) || NextToken().is(tok::r_square)) && 1584 Ty.get().get()->isObjCObjectOrInterfaceType()) { 1585 Result = ParseObjCMessageExpressionBody(SourceLocation(), 1586 SourceLocation(), 1587 Ty.get(), 0); 1588 } else { 1589 // Match the ')'. 1590 if (Tok.is(tok::r_paren)) 1591 RParenLoc = ConsumeParen(); 1592 else 1593 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1594 1595 if (Tok.is(tok::l_brace)) { 1596 ExprType = CompoundLiteral; 1597 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 1598 } 1599 1600 if (ExprType == CastExpr) { 1601 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 1602 1603 if (Ty.isInvalid()) 1604 return ExprError(); 1605 1606 CastTy = Ty.get(); 1607 1608 // Note that this doesn't parse the subsequent cast-expression, it just 1609 // returns the parsed type to the callee. 1610 if (stopIfCastExpr) 1611 return ExprResult(); 1612 1613 // Reject the cast of super idiom in ObjC. 1614 if (Tok.is(tok::identifier) && getLang().ObjC1 && 1615 Tok.getIdentifierInfo() == Ident_super && 1616 getCurScope()->isInObjcMethodScope() && 1617 GetLookAheadToken(1).isNot(tok::period)) { 1618 Diag(Tok.getLocation(), diag::err_illegal_super_cast) 1619 << SourceRange(OpenLoc, RParenLoc); 1620 return ExprError(); 1621 } 1622 1623 // Parse the cast-expression that follows it next. 1624 // TODO: For cast expression with CastTy. 1625 Result = ParseCastExpression(false, false, CastTy); 1626 if (!Result.isInvalid()) 1627 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, CastTy, 1628 RParenLoc, Result.take()); 1629 return move(Result); 1630 } 1631 1632 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 1633 return ExprError(); 1634 } 1635 } else if (TypeOfCast) { 1636 // Parse the expression-list. 1637 InMessageExpressionRAIIObject InMessage(*this, false); 1638 1639 ExprVector ArgExprs(Actions); 1640 CommaLocsTy CommaLocs; 1641 1642 if (!ParseExpressionList(ArgExprs, CommaLocs)) { 1643 ExprType = SimpleExpr; 1644 Result = Actions.ActOnParenOrParenListExpr(OpenLoc, Tok.getLocation(), 1645 move_arg(ArgExprs), TypeOfCast); 1646 } 1647 } else { 1648 InMessageExpressionRAIIObject InMessage(*this, false); 1649 1650 Result = ParseExpression(); 1651 ExprType = SimpleExpr; 1652 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 1653 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take()); 1654 } 1655 1656 // Match the ')'. 1657 if (Result.isInvalid()) { 1658 SkipUntil(tok::r_paren); 1659 return ExprError(); 1660 } 1661 1662 if (Tok.is(tok::r_paren)) 1663 RParenLoc = ConsumeParen(); 1664 else 1665 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1666 1667 return move(Result); 1668} 1669 1670/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 1671/// and we are at the left brace. 1672/// 1673/// postfix-expression: [C99 6.5.2] 1674/// '(' type-name ')' '{' initializer-list '}' 1675/// '(' type-name ')' '{' initializer-list ',' '}' 1676/// 1677ExprResult 1678Parser::ParseCompoundLiteralExpression(ParsedType Ty, 1679 SourceLocation LParenLoc, 1680 SourceLocation RParenLoc) { 1681 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 1682 if (!getLang().C99) // Compound literals don't exist in C90. 1683 Diag(LParenLoc, diag::ext_c99_compound_literal); 1684 ExprResult Result = ParseInitializer(); 1685 if (!Result.isInvalid() && Ty) 1686 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take()); 1687 return move(Result); 1688} 1689 1690/// ParseStringLiteralExpression - This handles the various token types that 1691/// form string literals, and also handles string concatenation [C99 5.1.1.2, 1692/// translation phase #6]. 1693/// 1694/// primary-expression: [C99 6.5.1] 1695/// string-literal 1696ExprResult Parser::ParseStringLiteralExpression() { 1697 assert(isTokenStringLiteral() && "Not a string literal!"); 1698 1699 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 1700 // considered to be strings for concatenation purposes. 1701 llvm::SmallVector<Token, 4> StringToks; 1702 1703 do { 1704 StringToks.push_back(Tok); 1705 ConsumeStringToken(); 1706 } while (isTokenStringLiteral()); 1707 1708 // Pass the set of string tokens, ready for concatenation, to the actions. 1709 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size()); 1710} 1711 1712/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 1713/// 1714/// argument-expression-list: 1715/// assignment-expression 1716/// argument-expression-list , assignment-expression 1717/// 1718/// [C++] expression-list: 1719/// [C++] assignment-expression 1720/// [C++] expression-list , assignment-expression 1721/// 1722bool Parser::ParseExpressionList(llvm::SmallVectorImpl<Expr*> &Exprs, 1723 llvm::SmallVectorImpl<SourceLocation> &CommaLocs, 1724 void (Sema::*Completer)(Scope *S, 1725 Expr *Data, 1726 Expr **Args, 1727 unsigned NumArgs), 1728 Expr *Data) { 1729 while (1) { 1730 if (Tok.is(tok::code_completion)) { 1731 if (Completer) 1732 (Actions.*Completer)(getCurScope(), Data, Exprs.data(), Exprs.size()); 1733 ConsumeCodeCompletionToken(); 1734 } 1735 1736 ExprResult Expr(ParseAssignmentExpression()); 1737 if (Expr.isInvalid()) 1738 return true; 1739 1740 Exprs.push_back(Expr.release()); 1741 1742 if (Tok.isNot(tok::comma)) 1743 return false; 1744 // Move to the next argument, remember where the comma was. 1745 CommaLocs.push_back(ConsumeToken()); 1746 } 1747} 1748 1749/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 1750/// 1751/// [clang] block-id: 1752/// [clang] specifier-qualifier-list block-declarator 1753/// 1754void Parser::ParseBlockId() { 1755 // Parse the specifier-qualifier-list piece. 1756 DeclSpec DS; 1757 ParseSpecifierQualifierList(DS); 1758 1759 // Parse the block-declarator. 1760 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 1761 ParseDeclarator(DeclaratorInfo); 1762 1763 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 1764 DeclaratorInfo.AddAttributes(DS.TakeAttributes(), 1765 SourceLocation()); 1766 1767 if (Tok.is(tok::kw___attribute)) { 1768 SourceLocation Loc; 1769 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1770 DeclaratorInfo.AddAttributes(AttrList, Loc); 1771 } 1772 1773 // Inform sema that we are starting a block. 1774 Actions.ActOnBlockArguments(DeclaratorInfo, getCurScope()); 1775} 1776 1777/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 1778/// like ^(int x){ return x+1; } 1779/// 1780/// block-literal: 1781/// [clang] '^' block-args[opt] compound-statement 1782/// [clang] '^' block-id compound-statement 1783/// [clang] block-args: 1784/// [clang] '(' parameter-list ')' 1785/// 1786ExprResult Parser::ParseBlockLiteralExpression() { 1787 assert(Tok.is(tok::caret) && "block literal starts with ^"); 1788 SourceLocation CaretLoc = ConsumeToken(); 1789 1790 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 1791 "block literal parsing"); 1792 1793 // Enter a scope to hold everything within the block. This includes the 1794 // argument decls, decls within the compound expression, etc. This also 1795 // allows determining whether a variable reference inside the block is 1796 // within or outside of the block. 1797 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 1798 Scope::BreakScope | Scope::ContinueScope | 1799 Scope::DeclScope); 1800 1801 // Inform sema that we are starting a block. 1802 Actions.ActOnBlockStart(CaretLoc, getCurScope()); 1803 1804 // Parse the return type if present. 1805 DeclSpec DS; 1806 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 1807 // FIXME: Since the return type isn't actually parsed, it can't be used to 1808 // fill ParamInfo with an initial valid range, so do it manually. 1809 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 1810 1811 // If this block has arguments, parse them. There is no ambiguity here with 1812 // the expression case, because the expression case requires a parameter list. 1813 if (Tok.is(tok::l_paren)) { 1814 ParseParenDeclarator(ParamInfo); 1815 // Parse the pieces after the identifier as if we had "int(...)". 1816 // SetIdentifier sets the source range end, but in this case we're past 1817 // that location. 1818 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 1819 ParamInfo.SetIdentifier(0, CaretLoc); 1820 ParamInfo.SetRangeEnd(Tmp); 1821 if (ParamInfo.isInvalidType()) { 1822 // If there was an error parsing the arguments, they may have 1823 // tried to use ^(x+y) which requires an argument list. Just 1824 // skip the whole block literal. 1825 Actions.ActOnBlockError(CaretLoc, getCurScope()); 1826 return ExprError(); 1827 } 1828 1829 if (Tok.is(tok::kw___attribute)) { 1830 SourceLocation Loc; 1831 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1832 ParamInfo.AddAttributes(AttrList, Loc); 1833 } 1834 1835 // Inform sema that we are starting a block. 1836 Actions.ActOnBlockArguments(ParamInfo, getCurScope()); 1837 } else if (!Tok.is(tok::l_brace)) { 1838 ParseBlockId(); 1839 } else { 1840 // Otherwise, pretend we saw (void). 1841 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, 1842 SourceLocation(), 1843 0, 0, 0, 1844 false, SourceLocation(), 1845 false, 0, 0, 0, 1846 CaretLoc, CaretLoc, 1847 ParamInfo), 1848 CaretLoc); 1849 1850 if (Tok.is(tok::kw___attribute)) { 1851 SourceLocation Loc; 1852 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1853 ParamInfo.AddAttributes(AttrList, Loc); 1854 } 1855 1856 // Inform sema that we are starting a block. 1857 Actions.ActOnBlockArguments(ParamInfo, getCurScope()); 1858 } 1859 1860 1861 ExprResult Result(true); 1862 if (!Tok.is(tok::l_brace)) { 1863 // Saw something like: ^expr 1864 Diag(Tok, diag::err_expected_expression); 1865 Actions.ActOnBlockError(CaretLoc, getCurScope()); 1866 return ExprError(); 1867 } 1868 1869 StmtResult Stmt(ParseCompoundStatementBody()); 1870 if (!Stmt.isInvalid()) 1871 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope()); 1872 else 1873 Actions.ActOnBlockError(CaretLoc, getCurScope()); 1874 return move(Result); 1875} 1876