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