ParseExpr.cpp revision 97d7ff0e514793cb305a1595914f3c91833b4d8f
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 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); 798 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), 799 Tok.getIdentifierInfo()); 800 ConsumeToken(); 801 return move(Res); 802 } 803 case tok::kw_const_cast: 804 case tok::kw_dynamic_cast: 805 case tok::kw_reinterpret_cast: 806 case tok::kw_static_cast: 807 Res = ParseCXXCasts(); 808 break; 809 case tok::kw_typeid: 810 Res = ParseCXXTypeid(); 811 break; 812 case tok::kw___uuidof: 813 Res = ParseCXXUuidof(); 814 break; 815 case tok::kw_this: 816 Res = ParseCXXThis(); 817 break; 818 819 case tok::annot_typename: 820 if (isStartOfObjCClassMessageMissingOpenBracket()) { 821 ParsedType Type = getTypeAnnotation(Tok); 822 823 // Fake up a Declarator to use with ActOnTypeName. 824 DeclSpec DS; 825 DS.SetRangeStart(Tok.getLocation()); 826 DS.SetRangeEnd(Tok.getLastLoc()); 827 828 const char *PrevSpec = 0; 829 unsigned DiagID; 830 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(), 831 PrevSpec, DiagID, Type); 832 833 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 834 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 835 if (Ty.isInvalid()) 836 break; 837 838 ConsumeToken(); 839 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 840 Ty.get(), 0); 841 break; 842 } 843 // Fall through 844 845 case tok::kw_char: 846 case tok::kw_wchar_t: 847 case tok::kw_char16_t: 848 case tok::kw_char32_t: 849 case tok::kw_bool: 850 case tok::kw_short: 851 case tok::kw_int: 852 case tok::kw_long: 853 case tok::kw_signed: 854 case tok::kw_unsigned: 855 case tok::kw_float: 856 case tok::kw_double: 857 case tok::kw_void: 858 case tok::kw_typename: 859 case tok::kw_typeof: 860 case tok::kw___vector: { 861 if (!getLang().CPlusPlus) { 862 Diag(Tok, diag::err_expected_expression); 863 return ExprError(); 864 } 865 866 if (SavedKind == tok::kw_typename) { 867 // postfix-expression: typename-specifier '(' expression-list[opt] ')' 868 if (TryAnnotateTypeOrScopeToken()) 869 return ExprError(); 870 } 871 872 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' 873 // 874 DeclSpec DS; 875 ParseCXXSimpleTypeSpecifier(DS); 876 if (Tok.isNot(tok::l_paren)) 877 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) 878 << DS.getSourceRange()); 879 880 Res = ParseCXXTypeConstructExpression(DS); 881 break; 882 } 883 884 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id 885 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 886 // (We can end up in this situation after tentative parsing.) 887 if (TryAnnotateTypeOrScopeToken()) 888 return ExprError(); 889 if (!Tok.is(tok::annot_cxxscope)) 890 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 891 NotCastExpr, TypeOfCast); 892 893 Token Next = NextToken(); 894 if (Next.is(tok::annot_template_id)) { 895 TemplateIdAnnotation *TemplateId 896 = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()); 897 if (TemplateId->Kind == TNK_Type_template) { 898 // We have a qualified template-id that we know refers to a 899 // type, translate it into a type and continue parsing as a 900 // cast expression. 901 CXXScopeSpec SS; 902 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 903 AnnotateTemplateIdTokenAsType(&SS); 904 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 905 NotCastExpr, TypeOfCast); 906 } 907 } 908 909 // Parse as an id-expression. 910 Res = ParseCXXIdExpression(isAddressOfOperand); 911 break; 912 } 913 914 case tok::annot_template_id: { // [C++] template-id 915 TemplateIdAnnotation *TemplateId 916 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 917 if (TemplateId->Kind == TNK_Type_template) { 918 // We have a template-id that we know refers to a type, 919 // translate it into a type and continue parsing as a cast 920 // expression. 921 AnnotateTemplateIdTokenAsType(); 922 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 923 NotCastExpr, TypeOfCast); 924 } 925 926 // Fall through to treat the template-id as an id-expression. 927 } 928 929 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id 930 Res = ParseCXXIdExpression(isAddressOfOperand); 931 break; 932 933 case tok::coloncolon: { 934 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken 935 // annotates the token, tail recurse. 936 if (TryAnnotateTypeOrScopeToken()) 937 return ExprError(); 938 if (!Tok.is(tok::coloncolon)) 939 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 940 941 // ::new -> [C++] new-expression 942 // ::delete -> [C++] delete-expression 943 SourceLocation CCLoc = ConsumeToken(); 944 if (Tok.is(tok::kw_new)) 945 return ParseCXXNewExpression(true, CCLoc); 946 if (Tok.is(tok::kw_delete)) 947 return ParseCXXDeleteExpression(true, CCLoc); 948 949 // This is not a type name or scope specifier, it is an invalid expression. 950 Diag(CCLoc, diag::err_expected_expression); 951 return ExprError(); 952 } 953 954 case tok::kw_new: // [C++] new-expression 955 return ParseCXXNewExpression(false, Tok.getLocation()); 956 957 case tok::kw_delete: // [C++] delete-expression 958 return ParseCXXDeleteExpression(false, Tok.getLocation()); 959 960 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')' 961 SourceLocation KeyLoc = ConsumeToken(); 962 SourceLocation LParen = Tok.getLocation(); 963 if (ExpectAndConsume(tok::l_paren, 964 diag::err_expected_lparen_after, "noexcept")) 965 return ExprError(); 966 // C++ [expr.unary.noexcept]p1: 967 // The noexcept operator determines whether the evaluation of its operand, 968 // which is an unevaluated operand, can throw an exception. 969 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 970 ExprResult Result = ParseExpression(); 971 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 972 if (!Result.isInvalid()) 973 Result = Actions.ActOnNoexceptExpr(KeyLoc, LParen, Result.take(), RParen); 974 return move(Result); 975 } 976 977 case tok::kw___is_pod: // [GNU] unary-type-trait 978 case tok::kw___is_class: 979 case tok::kw___is_enum: 980 case tok::kw___is_union: 981 case tok::kw___is_empty: 982 case tok::kw___is_polymorphic: 983 case tok::kw___is_abstract: 984 case tok::kw___is_literal: 985 case tok::kw___has_trivial_constructor: 986 case tok::kw___has_trivial_copy: 987 case tok::kw___has_trivial_assign: 988 case tok::kw___has_trivial_destructor: 989 case tok::kw___has_nothrow_assign: 990 case tok::kw___has_nothrow_copy: 991 case tok::kw___has_nothrow_constructor: 992 case tok::kw___has_virtual_destructor: 993 return ParseUnaryTypeTrait(); 994 995 case tok::kw___builtin_types_compatible_p: 996 case tok::kw___is_base_of: 997 case tok::kw___is_convertible_to: 998 return ParseBinaryTypeTrait(); 999 1000 case tok::at: { 1001 SourceLocation AtLoc = ConsumeToken(); 1002 return ParseObjCAtExpression(AtLoc); 1003 } 1004 case tok::caret: 1005 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression()); 1006 case tok::code_completion: 1007 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 1008 ConsumeCodeCompletionToken(); 1009 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1010 NotCastExpr, TypeOfCast); 1011 case tok::l_square: 1012 // These can be followed by postfix-expr pieces. 1013 if (getLang().ObjC1) 1014 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression()); 1015 // FALL THROUGH. 1016 default: 1017 NotCastExpr = true; 1018 return ExprError(); 1019 } 1020 1021 // These can be followed by postfix-expr pieces. 1022 return ParsePostfixExpressionSuffix(Res); 1023} 1024 1025/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression 1026/// is parsed, this method parses any suffixes that apply. 1027/// 1028/// postfix-expression: [C99 6.5.2] 1029/// primary-expression 1030/// postfix-expression '[' expression ']' 1031/// postfix-expression '(' argument-expression-list[opt] ')' 1032/// postfix-expression '.' identifier 1033/// postfix-expression '->' identifier 1034/// postfix-expression '++' 1035/// postfix-expression '--' 1036/// '(' type-name ')' '{' initializer-list '}' 1037/// '(' type-name ')' '{' initializer-list ',' '}' 1038/// 1039/// argument-expression-list: [C99 6.5.2] 1040/// argument-expression ...[opt] 1041/// argument-expression-list ',' assignment-expression ...[opt] 1042/// 1043ExprResult 1044Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { 1045 // Now that the primary-expression piece of the postfix-expression has been 1046 // parsed, see if there are any postfix-expression pieces here. 1047 SourceLocation Loc; 1048 while (1) { 1049 switch (Tok.getKind()) { 1050 case tok::code_completion: 1051 if (InMessageExpression) 1052 return move(LHS); 1053 1054 Actions.CodeCompletePostfixExpression(getCurScope(), LHS); 1055 ConsumeCodeCompletionToken(); 1056 LHS = ExprError(); 1057 break; 1058 1059 case tok::identifier: 1060 // If we see identifier: after an expression, and we're not already in a 1061 // message send, then this is probably a message send with a missing 1062 // opening bracket '['. 1063 if (getLang().ObjC1 && !InMessageExpression && 1064 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 1065 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 1066 ParsedType(), LHS.get()); 1067 break; 1068 } 1069 1070 // Fall through; this isn't a message send. 1071 1072 default: // Not a postfix-expression suffix. 1073 return move(LHS); 1074 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 1075 // If we have a array postfix expression that starts on a new line and 1076 // Objective-C is enabled, it is highly likely that the user forgot a 1077 // semicolon after the base expression and that the array postfix-expr is 1078 // actually another message send. In this case, do some look-ahead to see 1079 // if the contents of the square brackets are obviously not a valid 1080 // expression and recover by pretending there is no suffix. 1081 if (getLang().ObjC1 && Tok.isAtStartOfLine() && 1082 isSimpleObjCMessageExpression()) 1083 return move(LHS); 1084 1085 Loc = ConsumeBracket(); 1086 ExprResult Idx(ParseExpression()); 1087 1088 SourceLocation RLoc = Tok.getLocation(); 1089 1090 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 1091 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc, 1092 Idx.take(), RLoc); 1093 } else 1094 LHS = ExprError(); 1095 1096 // Match the ']'. 1097 MatchRHSPunctuation(tok::r_square, Loc); 1098 break; 1099 } 1100 1101 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')' 1102 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>' 1103 // '(' argument-expression-list[opt] ')' 1104 tok::TokenKind OpKind = Tok.getKind(); 1105 InMessageExpressionRAIIObject InMessage(*this, false); 1106 1107 Expr *ExecConfig = 0; 1108 1109 if (OpKind == tok::lesslessless) { 1110 ExprVector ExecConfigExprs(Actions); 1111 CommaLocsTy ExecConfigCommaLocs; 1112 SourceLocation LLLLoc, GGGLoc; 1113 1114 LLLLoc = ConsumeToken(); 1115 1116 if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) { 1117 LHS = ExprError(); 1118 } 1119 1120 if (LHS.isInvalid()) { 1121 SkipUntil(tok::greatergreatergreater); 1122 } else if (Tok.isNot(tok::greatergreatergreater)) { 1123 MatchRHSPunctuation(tok::greatergreatergreater, LLLLoc); 1124 LHS = ExprError(); 1125 } else { 1126 GGGLoc = ConsumeToken(); 1127 } 1128 1129 if (!LHS.isInvalid()) { 1130 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, "")) 1131 LHS = ExprError(); 1132 else 1133 Loc = PrevTokLocation; 1134 } 1135 1136 if (!LHS.isInvalid()) { 1137 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), 1138 LLLLoc, move_arg(ExecConfigExprs), GGGLoc); 1139 if (ECResult.isInvalid()) 1140 LHS = ExprError(); 1141 else 1142 ExecConfig = ECResult.get(); 1143 } 1144 } else { 1145 Loc = ConsumeParen(); 1146 } 1147 1148 ExprVector ArgExprs(Actions); 1149 CommaLocsTy CommaLocs; 1150 1151 if (Tok.is(tok::code_completion)) { 1152 Actions.CodeCompleteCall(getCurScope(), LHS.get(), 0, 0); 1153 ConsumeCodeCompletionToken(); 1154 } 1155 1156 if (OpKind == tok::l_paren || !LHS.isInvalid()) { 1157 if (Tok.isNot(tok::r_paren)) { 1158 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall, 1159 LHS.get())) { 1160 SkipUntil(tok::r_paren); 1161 LHS = ExprError(); 1162 } 1163 } 1164 } 1165 1166 // Match the ')'. 1167 if (LHS.isInvalid()) { 1168 SkipUntil(tok::r_paren); 1169 } else if (Tok.isNot(tok::r_paren)) { 1170 MatchRHSPunctuation(tok::r_paren, Loc); 1171 LHS = ExprError(); 1172 } else { 1173 assert((ArgExprs.size() == 0 || 1174 ArgExprs.size()-1 == CommaLocs.size())&& 1175 "Unexpected number of commas!"); 1176 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc, 1177 move_arg(ArgExprs), Tok.getLocation(), 1178 ExecConfig); 1179 ConsumeParen(); 1180 } 1181 1182 break; 1183 } 1184 case tok::arrow: 1185 case tok::period: { 1186 // postfix-expression: p-e '->' template[opt] id-expression 1187 // postfix-expression: p-e '.' template[opt] id-expression 1188 tok::TokenKind OpKind = Tok.getKind(); 1189 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 1190 1191 CXXScopeSpec SS; 1192 ParsedType ObjectType; 1193 bool MayBePseudoDestructor = false; 1194 if (getLang().CPlusPlus && !LHS.isInvalid()) { 1195 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(), 1196 OpLoc, OpKind, ObjectType, 1197 MayBePseudoDestructor); 1198 if (LHS.isInvalid()) 1199 break; 1200 1201 ParseOptionalCXXScopeSpecifier(SS, ObjectType, false, 1202 &MayBePseudoDestructor); 1203 if (SS.isNotEmpty()) 1204 ObjectType = ParsedType(); 1205 } 1206 1207 if (Tok.is(tok::code_completion)) { 1208 // Code completion for a member access expression. 1209 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(), 1210 OpLoc, OpKind == tok::arrow); 1211 1212 ConsumeCodeCompletionToken(); 1213 } 1214 1215 if (MayBePseudoDestructor && !LHS.isInvalid()) { 1216 LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS, 1217 ObjectType); 1218 break; 1219 } 1220 1221 // Either the action has told is that this cannot be a 1222 // pseudo-destructor expression (based on the type of base 1223 // expression), or we didn't see a '~' in the right place. We 1224 // can still parse a destructor name here, but in that case it 1225 // names a real destructor. 1226 // Allow explicit constructor calls in Microsoft mode. 1227 // FIXME: Add support for explicit call of template constructor. 1228 UnqualifiedId Name; 1229 if (ParseUnqualifiedId(SS, 1230 /*EnteringContext=*/false, 1231 /*AllowDestructorName=*/true, 1232 /*AllowConstructorName=*/ getLang().Microsoft, 1233 ObjectType, 1234 Name)) 1235 LHS = ExprError(); 1236 1237 if (!LHS.isInvalid()) 1238 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc, 1239 OpKind, SS, Name, ObjCImpDecl, 1240 Tok.is(tok::l_paren)); 1241 break; 1242 } 1243 case tok::plusplus: // postfix-expression: postfix-expression '++' 1244 case tok::minusminus: // postfix-expression: postfix-expression '--' 1245 if (!LHS.isInvalid()) { 1246 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(), 1247 Tok.getKind(), LHS.take()); 1248 } 1249 ConsumeToken(); 1250 break; 1251 } 1252 } 1253} 1254 1255/// ParseExprAfterTypeofSizeofAlignof - We parsed a typeof/sizeof/alignof and 1256/// we are at the start of an expression or a parenthesized type-id. 1257/// OpTok is the operand token (typeof/sizeof/alignof). Returns the expression 1258/// (isCastExpr == false) or the type (isCastExpr == true). 1259/// 1260/// unary-expression: [C99 6.5.3] 1261/// 'sizeof' unary-expression 1262/// 'sizeof' '(' type-name ')' 1263/// [GNU] '__alignof' unary-expression 1264/// [GNU] '__alignof' '(' type-name ')' 1265/// [C++0x] 'alignof' '(' type-id ')' 1266/// 1267/// [GNU] typeof-specifier: 1268/// typeof ( expressions ) 1269/// typeof ( type-name ) 1270/// [GNU/C++] typeof unary-expression 1271/// 1272ExprResult 1273Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, 1274 bool &isCastExpr, 1275 ParsedType &CastTy, 1276 SourceRange &CastRange) { 1277 1278 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 1279 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof)) && 1280 "Not a typeof/sizeof/alignof expression!"); 1281 1282 ExprResult Operand; 1283 1284 // If the operand doesn't start with an '(', it must be an expression. 1285 if (Tok.isNot(tok::l_paren)) { 1286 isCastExpr = false; 1287 if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) { 1288 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 1289 return ExprError(); 1290 } 1291 1292 // C++0x [expr.sizeof]p1: 1293 // [...] The operand is either an expression, which is an unevaluated 1294 // operand (Clause 5) [...] 1295 // 1296 // The GNU typeof and alignof extensions also behave as unevaluated 1297 // operands. 1298 EnterExpressionEvaluationContext Unevaluated(Actions, 1299 Sema::Unevaluated); 1300 Operand = ParseCastExpression(true/*isUnaryExpression*/); 1301 } else { 1302 // If it starts with a '(', we know that it is either a parenthesized 1303 // type-name, or it is a unary-expression that starts with a compound 1304 // literal, or starts with a primary-expression that is a parenthesized 1305 // expression. 1306 ParenParseOption ExprType = CastExpr; 1307 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 1308 1309 // C++0x [expr.sizeof]p1: 1310 // [...] The operand is either an expression, which is an unevaluated 1311 // operand (Clause 5) [...] 1312 // 1313 // The GNU typeof and alignof extensions also behave as unevaluated 1314 // operands. 1315 EnterExpressionEvaluationContext Unevaluated(Actions, 1316 Sema::Unevaluated); 1317 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 1318 ParsedType(), CastTy, RParenLoc); 1319 CastRange = SourceRange(LParenLoc, RParenLoc); 1320 1321 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 1322 // a type. 1323 if (ExprType == CastExpr) { 1324 isCastExpr = true; 1325 return ExprEmpty(); 1326 } 1327 1328 if (getLang().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { 1329 // GNU typeof in C requires the expression to be parenthesized. Not so for 1330 // sizeof/alignof or in C++. Therefore, the parenthesized expression is 1331 // the start of a unary-expression, but doesn't include any postfix 1332 // pieces. Parse these now if present. 1333 if (!Operand.isInvalid()) 1334 Operand = ParsePostfixExpressionSuffix(Operand.get()); 1335 } 1336 } 1337 1338 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 1339 isCastExpr = false; 1340 return move(Operand); 1341} 1342 1343 1344/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression. 1345/// unary-expression: [C99 6.5.3] 1346/// 'sizeof' unary-expression 1347/// 'sizeof' '(' type-name ')' 1348/// [C++0x] 'sizeof' '...' '(' identifier ')' 1349/// [GNU] '__alignof' unary-expression 1350/// [GNU] '__alignof' '(' type-name ')' 1351/// [C++0x] 'alignof' '(' type-id ')' 1352ExprResult Parser::ParseSizeofAlignofExpression() { 1353 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) 1354 || Tok.is(tok::kw_alignof)) && 1355 "Not a sizeof/alignof expression!"); 1356 Token OpTok = Tok; 1357 ConsumeToken(); 1358 1359 // [C++0x] 'sizeof' '...' '(' identifier ')' 1360 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) { 1361 SourceLocation EllipsisLoc = ConsumeToken(); 1362 SourceLocation LParenLoc, RParenLoc; 1363 IdentifierInfo *Name = 0; 1364 SourceLocation NameLoc; 1365 if (Tok.is(tok::l_paren)) { 1366 LParenLoc = ConsumeParen(); 1367 if (Tok.is(tok::identifier)) { 1368 Name = Tok.getIdentifierInfo(); 1369 NameLoc = ConsumeToken(); 1370 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1371 if (RParenLoc.isInvalid()) 1372 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1373 } else { 1374 Diag(Tok, diag::err_expected_parameter_pack); 1375 SkipUntil(tok::r_paren); 1376 } 1377 } else if (Tok.is(tok::identifier)) { 1378 Name = Tok.getIdentifierInfo(); 1379 NameLoc = ConsumeToken(); 1380 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc); 1381 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1382 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack) 1383 << Name 1384 << FixItHint::CreateInsertion(LParenLoc, "(") 1385 << FixItHint::CreateInsertion(RParenLoc, ")"); 1386 } else { 1387 Diag(Tok, diag::err_sizeof_parameter_pack); 1388 } 1389 1390 if (!Name) 1391 return ExprError(); 1392 1393 return Actions.ActOnSizeofParameterPackExpr(getCurScope(), 1394 OpTok.getLocation(), 1395 *Name, NameLoc, 1396 RParenLoc); 1397 } 1398 1399 bool isCastExpr; 1400 ParsedType CastTy; 1401 SourceRange CastRange; 1402 ExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 1403 isCastExpr, 1404 CastTy, 1405 CastRange); 1406 1407 if (isCastExpr) 1408 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1409 OpTok.is(tok::kw_sizeof), 1410 /*isType=*/true, 1411 CastTy.getAsOpaquePtr(), 1412 CastRange); 1413 1414 // If we get here, the operand to the sizeof/alignof was an expresion. 1415 if (!Operand.isInvalid()) 1416 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1417 OpTok.is(tok::kw_sizeof), 1418 /*isType=*/false, 1419 Operand.release(), CastRange); 1420 return move(Operand); 1421} 1422 1423/// ParseBuiltinPrimaryExpression 1424/// 1425/// primary-expression: [C99 6.5.1] 1426/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1427/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1428/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1429/// assign-expr ')' 1430/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1431/// 1432/// [GNU] offsetof-member-designator: 1433/// [GNU] identifier 1434/// [GNU] offsetof-member-designator '.' identifier 1435/// [GNU] offsetof-member-designator '[' expression ']' 1436/// 1437ExprResult Parser::ParseBuiltinPrimaryExpression() { 1438 ExprResult Res; 1439 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1440 1441 tok::TokenKind T = Tok.getKind(); 1442 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1443 1444 // All of these start with an open paren. 1445 if (Tok.isNot(tok::l_paren)) 1446 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1447 << BuiltinII); 1448 1449 SourceLocation LParenLoc = ConsumeParen(); 1450 // TODO: Build AST. 1451 1452 switch (T) { 1453 default: assert(0 && "Not a builtin primary expression!"); 1454 case tok::kw___builtin_va_arg: { 1455 ExprResult Expr(ParseAssignmentExpression()); 1456 1457 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1458 Expr = ExprError(); 1459 1460 TypeResult Ty = ParseTypeName(); 1461 1462 if (Tok.isNot(tok::r_paren)) { 1463 Diag(Tok, diag::err_expected_rparen); 1464 Expr = ExprError(); 1465 } 1466 1467 if (Expr.isInvalid() || Ty.isInvalid()) 1468 Res = ExprError(); 1469 else 1470 Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen()); 1471 break; 1472 } 1473 case tok::kw___builtin_offsetof: { 1474 SourceLocation TypeLoc = Tok.getLocation(); 1475 TypeResult Ty = ParseTypeName(); 1476 if (Ty.isInvalid()) { 1477 SkipUntil(tok::r_paren); 1478 return ExprError(); 1479 } 1480 1481 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1482 return ExprError(); 1483 1484 // We must have at least one identifier here. 1485 if (Tok.isNot(tok::identifier)) { 1486 Diag(Tok, diag::err_expected_ident); 1487 SkipUntil(tok::r_paren); 1488 return ExprError(); 1489 } 1490 1491 // Keep track of the various subcomponents we see. 1492 llvm::SmallVector<Sema::OffsetOfComponent, 4> Comps; 1493 1494 Comps.push_back(Sema::OffsetOfComponent()); 1495 Comps.back().isBrackets = false; 1496 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1497 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1498 1499 // FIXME: This loop leaks the index expressions on error. 1500 while (1) { 1501 if (Tok.is(tok::period)) { 1502 // offsetof-member-designator: offsetof-member-designator '.' identifier 1503 Comps.push_back(Sema::OffsetOfComponent()); 1504 Comps.back().isBrackets = false; 1505 Comps.back().LocStart = ConsumeToken(); 1506 1507 if (Tok.isNot(tok::identifier)) { 1508 Diag(Tok, diag::err_expected_ident); 1509 SkipUntil(tok::r_paren); 1510 return ExprError(); 1511 } 1512 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1513 Comps.back().LocEnd = ConsumeToken(); 1514 1515 } else if (Tok.is(tok::l_square)) { 1516 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1517 Comps.push_back(Sema::OffsetOfComponent()); 1518 Comps.back().isBrackets = true; 1519 Comps.back().LocStart = ConsumeBracket(); 1520 Res = ParseExpression(); 1521 if (Res.isInvalid()) { 1522 SkipUntil(tok::r_paren); 1523 return move(Res); 1524 } 1525 Comps.back().U.E = Res.release(); 1526 1527 Comps.back().LocEnd = 1528 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart); 1529 } else { 1530 if (Tok.isNot(tok::r_paren)) { 1531 MatchRHSPunctuation(tok::r_paren, LParenLoc); 1532 Res = ExprError(); 1533 } else if (Ty.isInvalid()) { 1534 Res = ExprError(); 1535 } else { 1536 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc, 1537 Ty.get(), &Comps[0], 1538 Comps.size(), ConsumeParen()); 1539 } 1540 break; 1541 } 1542 } 1543 break; 1544 } 1545 case tok::kw___builtin_choose_expr: { 1546 ExprResult Cond(ParseAssignmentExpression()); 1547 if (Cond.isInvalid()) { 1548 SkipUntil(tok::r_paren); 1549 return move(Cond); 1550 } 1551 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1552 return ExprError(); 1553 1554 ExprResult Expr1(ParseAssignmentExpression()); 1555 if (Expr1.isInvalid()) { 1556 SkipUntil(tok::r_paren); 1557 return move(Expr1); 1558 } 1559 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1560 return ExprError(); 1561 1562 ExprResult Expr2(ParseAssignmentExpression()); 1563 if (Expr2.isInvalid()) { 1564 SkipUntil(tok::r_paren); 1565 return move(Expr2); 1566 } 1567 if (Tok.isNot(tok::r_paren)) { 1568 Diag(Tok, diag::err_expected_rparen); 1569 return ExprError(); 1570 } 1571 Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(), 1572 Expr2.take(), ConsumeParen()); 1573 break; 1574 } 1575 } 1576 1577 if (Res.isInvalid()) 1578 return ExprError(); 1579 1580 // These can be followed by postfix-expr pieces because they are 1581 // primary-expressions. 1582 return ParsePostfixExpressionSuffix(Res.take()); 1583} 1584 1585/// ParseParenExpression - This parses the unit that starts with a '(' token, 1586/// based on what is allowed by ExprType. The actual thing parsed is returned 1587/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1588/// not the parsed cast-expression. 1589/// 1590/// primary-expression: [C99 6.5.1] 1591/// '(' expression ')' 1592/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1593/// postfix-expression: [C99 6.5.2] 1594/// '(' type-name ')' '{' initializer-list '}' 1595/// '(' type-name ')' '{' initializer-list ',' '}' 1596/// cast-expression: [C99 6.5.4] 1597/// '(' type-name ')' cast-expression 1598/// 1599ExprResult 1600Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1601 ParsedType TypeOfCast, ParsedType &CastTy, 1602 SourceLocation &RParenLoc) { 1603 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1604 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 1605 SourceLocation OpenLoc = ConsumeParen(); 1606 ExprResult Result(true); 1607 bool isAmbiguousTypeId; 1608 CastTy = ParsedType(); 1609 1610 if (Tok.is(tok::code_completion)) { 1611 Actions.CodeCompleteOrdinaryName(getCurScope(), 1612 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression 1613 : Sema::PCC_Expression); 1614 ConsumeCodeCompletionToken(); 1615 return ExprError(); 1616 } 1617 1618 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 1619 Diag(Tok, diag::ext_gnu_statement_expr); 1620 ParsedAttributes attrs; 1621 StmtResult Stmt(ParseCompoundStatement(attrs, true)); 1622 ExprType = CompoundStmt; 1623 1624 // If the substmt parsed correctly, build the AST node. 1625 if (!Stmt.isInvalid() && Tok.is(tok::r_paren)) 1626 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation()); 1627 1628 } else if (ExprType >= CompoundLiteral && 1629 isTypeIdInParens(isAmbiguousTypeId)) { 1630 1631 // Otherwise, this is a compound literal expression or cast expression. 1632 1633 // In C++, if the type-id is ambiguous we disambiguate based on context. 1634 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 1635 // in which case we should treat it as type-id. 1636 // if stopIfCastExpr is false, we need to determine the context past the 1637 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 1638 if (isAmbiguousTypeId && !stopIfCastExpr) 1639 return ParseCXXAmbiguousParenExpression(ExprType, CastTy, 1640 OpenLoc, RParenLoc); 1641 1642 TypeResult Ty; 1643 1644 { 1645 InMessageExpressionRAIIObject InMessage(*this, false); 1646 Ty = ParseTypeName(); 1647 } 1648 1649 // If our type is followed by an identifier and either ':' or ']', then 1650 // this is probably an Objective-C message send where the leading '[' is 1651 // missing. Recover as if that were the case. 1652 if (!Ty.isInvalid() && Tok.is(tok::identifier) && !InMessageExpression && 1653 getLang().ObjC1 && !Ty.get().get().isNull() && 1654 (NextToken().is(tok::colon) || NextToken().is(tok::r_square)) && 1655 Ty.get().get()->isObjCObjectOrInterfaceType()) { 1656 Result = ParseObjCMessageExpressionBody(SourceLocation(), 1657 SourceLocation(), 1658 Ty.get(), 0); 1659 } else { 1660 // Match the ')'. 1661 if (Tok.is(tok::r_paren)) 1662 RParenLoc = ConsumeParen(); 1663 else 1664 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1665 1666 if (Tok.is(tok::l_brace)) { 1667 ExprType = CompoundLiteral; 1668 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 1669 } 1670 1671 if (ExprType == CastExpr) { 1672 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 1673 1674 if (Ty.isInvalid()) 1675 return ExprError(); 1676 1677 CastTy = Ty.get(); 1678 1679 // Note that this doesn't parse the subsequent cast-expression, it just 1680 // returns the parsed type to the callee. 1681 if (stopIfCastExpr) 1682 return ExprResult(); 1683 1684 // Reject the cast of super idiom in ObjC. 1685 if (Tok.is(tok::identifier) && getLang().ObjC1 && 1686 Tok.getIdentifierInfo() == Ident_super && 1687 getCurScope()->isInObjcMethodScope() && 1688 GetLookAheadToken(1).isNot(tok::period)) { 1689 Diag(Tok.getLocation(), diag::err_illegal_super_cast) 1690 << SourceRange(OpenLoc, RParenLoc); 1691 return ExprError(); 1692 } 1693 1694 // Parse the cast-expression that follows it next. 1695 // TODO: For cast expression with CastTy. 1696 Result = ParseCastExpression(false, false, CastTy); 1697 if (!Result.isInvalid()) 1698 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, CastTy, 1699 RParenLoc, Result.take()); 1700 return move(Result); 1701 } 1702 1703 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 1704 return ExprError(); 1705 } 1706 } else if (TypeOfCast) { 1707 // Parse the expression-list. 1708 InMessageExpressionRAIIObject InMessage(*this, false); 1709 1710 ExprVector ArgExprs(Actions); 1711 CommaLocsTy CommaLocs; 1712 1713 if (!ParseExpressionList(ArgExprs, CommaLocs)) { 1714 ExprType = SimpleExpr; 1715 Result = Actions.ActOnParenOrParenListExpr(OpenLoc, Tok.getLocation(), 1716 move_arg(ArgExprs), TypeOfCast); 1717 } 1718 } else { 1719 InMessageExpressionRAIIObject InMessage(*this, false); 1720 1721 Result = ParseExpression(); 1722 ExprType = SimpleExpr; 1723 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 1724 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take()); 1725 } 1726 1727 // Match the ')'. 1728 if (Result.isInvalid()) { 1729 SkipUntil(tok::r_paren); 1730 return ExprError(); 1731 } 1732 1733 if (Tok.is(tok::r_paren)) 1734 RParenLoc = ConsumeParen(); 1735 else 1736 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1737 1738 return move(Result); 1739} 1740 1741/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 1742/// and we are at the left brace. 1743/// 1744/// postfix-expression: [C99 6.5.2] 1745/// '(' type-name ')' '{' initializer-list '}' 1746/// '(' type-name ')' '{' initializer-list ',' '}' 1747/// 1748ExprResult 1749Parser::ParseCompoundLiteralExpression(ParsedType Ty, 1750 SourceLocation LParenLoc, 1751 SourceLocation RParenLoc) { 1752 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 1753 if (!getLang().C99) // Compound literals don't exist in C90. 1754 Diag(LParenLoc, diag::ext_c99_compound_literal); 1755 ExprResult Result = ParseInitializer(); 1756 if (!Result.isInvalid() && Ty) 1757 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take()); 1758 return move(Result); 1759} 1760 1761/// ParseStringLiteralExpression - This handles the various token types that 1762/// form string literals, and also handles string concatenation [C99 5.1.1.2, 1763/// translation phase #6]. 1764/// 1765/// primary-expression: [C99 6.5.1] 1766/// string-literal 1767ExprResult Parser::ParseStringLiteralExpression() { 1768 assert(isTokenStringLiteral() && "Not a string literal!"); 1769 1770 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 1771 // considered to be strings for concatenation purposes. 1772 llvm::SmallVector<Token, 4> StringToks; 1773 1774 do { 1775 StringToks.push_back(Tok); 1776 ConsumeStringToken(); 1777 } while (isTokenStringLiteral()); 1778 1779 // Pass the set of string tokens, ready for concatenation, to the actions. 1780 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size()); 1781} 1782 1783/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 1784/// 1785/// argument-expression-list: 1786/// assignment-expression 1787/// argument-expression-list , assignment-expression 1788/// 1789/// [C++] expression-list: 1790/// [C++] assignment-expression ...[opt] 1791/// [C++] expression-list , assignment-expression ...[opt] 1792/// 1793bool Parser::ParseExpressionList(llvm::SmallVectorImpl<Expr*> &Exprs, 1794 llvm::SmallVectorImpl<SourceLocation> &CommaLocs, 1795 void (Sema::*Completer)(Scope *S, 1796 Expr *Data, 1797 Expr **Args, 1798 unsigned NumArgs), 1799 Expr *Data) { 1800 while (1) { 1801 if (Tok.is(tok::code_completion)) { 1802 if (Completer) 1803 (Actions.*Completer)(getCurScope(), Data, Exprs.data(), Exprs.size()); 1804 ConsumeCodeCompletionToken(); 1805 } 1806 1807 ExprResult Expr(ParseAssignmentExpression()); 1808 if (Tok.is(tok::ellipsis)) 1809 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); 1810 if (Expr.isInvalid()) 1811 return true; 1812 1813 Exprs.push_back(Expr.release()); 1814 1815 if (Tok.isNot(tok::comma)) 1816 return false; 1817 // Move to the next argument, remember where the comma was. 1818 CommaLocs.push_back(ConsumeToken()); 1819 } 1820} 1821 1822/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 1823/// 1824/// [clang] block-id: 1825/// [clang] specifier-qualifier-list block-declarator 1826/// 1827void Parser::ParseBlockId() { 1828 if (Tok.is(tok::code_completion)) { 1829 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); 1830 ConsumeCodeCompletionToken(); 1831 } 1832 1833 // Parse the specifier-qualifier-list piece. 1834 DeclSpec DS; 1835 ParseSpecifierQualifierList(DS); 1836 1837 // Parse the block-declarator. 1838 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 1839 ParseDeclarator(DeclaratorInfo); 1840 1841 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 1842 DeclaratorInfo.addAttributes(DS.takeAttributes()); 1843 1844 MaybeParseGNUAttributes(DeclaratorInfo); 1845 1846 // Inform sema that we are starting a block. 1847 Actions.ActOnBlockArguments(DeclaratorInfo, getCurScope()); 1848} 1849 1850/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 1851/// like ^(int x){ return x+1; } 1852/// 1853/// block-literal: 1854/// [clang] '^' block-args[opt] compound-statement 1855/// [clang] '^' block-id compound-statement 1856/// [clang] block-args: 1857/// [clang] '(' parameter-list ')' 1858/// 1859ExprResult Parser::ParseBlockLiteralExpression() { 1860 assert(Tok.is(tok::caret) && "block literal starts with ^"); 1861 SourceLocation CaretLoc = ConsumeToken(); 1862 1863 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 1864 "block literal parsing"); 1865 1866 // Enter a scope to hold everything within the block. This includes the 1867 // argument decls, decls within the compound expression, etc. This also 1868 // allows determining whether a variable reference inside the block is 1869 // within or outside of the block. 1870 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 1871 Scope::BreakScope | Scope::ContinueScope | 1872 Scope::DeclScope); 1873 1874 // Inform sema that we are starting a block. 1875 Actions.ActOnBlockStart(CaretLoc, getCurScope()); 1876 1877 // Parse the return type if present. 1878 DeclSpec DS; 1879 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 1880 // FIXME: Since the return type isn't actually parsed, it can't be used to 1881 // fill ParamInfo with an initial valid range, so do it manually. 1882 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 1883 1884 // If this block has arguments, parse them. There is no ambiguity here with 1885 // the expression case, because the expression case requires a parameter list. 1886 if (Tok.is(tok::l_paren)) { 1887 ParseParenDeclarator(ParamInfo); 1888 // Parse the pieces after the identifier as if we had "int(...)". 1889 // SetIdentifier sets the source range end, but in this case we're past 1890 // that location. 1891 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 1892 ParamInfo.SetIdentifier(0, CaretLoc); 1893 ParamInfo.SetRangeEnd(Tmp); 1894 if (ParamInfo.isInvalidType()) { 1895 // If there was an error parsing the arguments, they may have 1896 // tried to use ^(x+y) which requires an argument list. Just 1897 // skip the whole block literal. 1898 Actions.ActOnBlockError(CaretLoc, getCurScope()); 1899 return ExprError(); 1900 } 1901 1902 MaybeParseGNUAttributes(ParamInfo); 1903 1904 // Inform sema that we are starting a block. 1905 Actions.ActOnBlockArguments(ParamInfo, getCurScope()); 1906 } else if (!Tok.is(tok::l_brace)) { 1907 ParseBlockId(); 1908 } else { 1909 // Otherwise, pretend we saw (void). 1910 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(ParsedAttributes(), 1911 true, false, 1912 SourceLocation(), 1913 0, 0, 0, 1914 true, SourceLocation(), 1915 false, SourceLocation(), 1916 false, 0, 0, 0, 1917 CaretLoc, CaretLoc, 1918 ParamInfo), 1919 CaretLoc); 1920 1921 MaybeParseGNUAttributes(ParamInfo); 1922 1923 // Inform sema that we are starting a block. 1924 Actions.ActOnBlockArguments(ParamInfo, getCurScope()); 1925 } 1926 1927 1928 ExprResult Result(true); 1929 if (!Tok.is(tok::l_brace)) { 1930 // Saw something like: ^expr 1931 Diag(Tok, diag::err_expected_expression); 1932 Actions.ActOnBlockError(CaretLoc, getCurScope()); 1933 return ExprError(); 1934 } 1935 1936 StmtResult Stmt(ParseCompoundStatementBody()); 1937 if (!Stmt.isInvalid()) 1938 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope()); 1939 else 1940 Actions.ActOnBlockError(CaretLoc, getCurScope()); 1941 return move(Result); 1942} 1943