ParseExpr.cpp revision 3840281126e7d10552c55f6fd8b1ec9483898906
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/// [C1X] generic-selection 469/// '__func__' [C99 6.4.2.2] 470/// [GNU] '__FUNCTION__' 471/// [GNU] '__PRETTY_FUNCTION__' 472/// [GNU] '(' compound-statement ')' 473/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 474/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 475/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 476/// assign-expr ')' 477/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 478/// [GNU] '__null' 479/// [OBJC] '[' objc-message-expr ']' 480/// [OBJC] '@selector' '(' objc-selector-arg ')' 481/// [OBJC] '@protocol' '(' identifier ')' 482/// [OBJC] '@encode' '(' type-name ')' 483/// [OBJC] objc-string-literal 484/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 485/// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 486/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 487/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 488/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 489/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 490/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1] 491/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1] 492/// [C++] 'this' [C++ 9.3.2] 493/// [G++] unary-type-trait '(' type-id ')' 494/// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO] 495/// [clang] '^' block-literal 496/// 497/// constant: [C99 6.4.4] 498/// integer-constant 499/// floating-constant 500/// enumeration-constant -> identifier 501/// character-constant 502/// 503/// id-expression: [C++ 5.1] 504/// unqualified-id 505/// qualified-id 506/// 507/// unqualified-id: [C++ 5.1] 508/// identifier 509/// operator-function-id 510/// conversion-function-id 511/// '~' class-name 512/// template-id 513/// 514/// new-expression: [C++ 5.3.4] 515/// '::'[opt] 'new' new-placement[opt] new-type-id 516/// new-initializer[opt] 517/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 518/// new-initializer[opt] 519/// 520/// delete-expression: [C++ 5.3.5] 521/// '::'[opt] 'delete' cast-expression 522/// '::'[opt] 'delete' '[' ']' cast-expression 523/// 524/// [GNU] unary-type-trait: 525/// '__has_nothrow_assign' 526/// '__has_nothrow_copy' 527/// '__has_nothrow_constructor' 528/// '__has_trivial_assign' [TODO] 529/// '__has_trivial_copy' [TODO] 530/// '__has_trivial_constructor' 531/// '__has_trivial_destructor' 532/// '__has_virtual_destructor' 533/// '__is_abstract' [TODO] 534/// '__is_class' 535/// '__is_empty' [TODO] 536/// '__is_enum' 537/// '__is_pod' 538/// '__is_polymorphic' 539/// '__is_trivial' 540/// '__is_union' 541/// 542/// binary-type-trait: 543/// [GNU] '__is_base_of' 544/// [MS] '__is_convertible_to' 545/// 546ExprResult Parser::ParseCastExpression(bool isUnaryExpression, 547 bool isAddressOfOperand, 548 bool &NotCastExpr, 549 ParsedType TypeOfCast) { 550 ExprResult Res; 551 tok::TokenKind SavedKind = Tok.getKind(); 552 NotCastExpr = false; 553 554 // This handles all of cast-expression, unary-expression, postfix-expression, 555 // and primary-expression. We handle them together like this for efficiency 556 // and to simplify handling of an expression starting with a '(' token: which 557 // may be one of a parenthesized expression, cast-expression, compound literal 558 // expression, or statement expression. 559 // 560 // If the parsed tokens consist of a primary-expression, the cases below 561 // break out of the switch; at the end we call ParsePostfixExpressionSuffix 562 // to handle the postfix expression suffixes. Cases that cannot be followed 563 // by postfix exprs should return without invoking 564 // ParsePostfixExpressionSuffix. 565 switch (SavedKind) { 566 case tok::l_paren: { 567 // If this expression is limited to being a unary-expression, the parent can 568 // not start a cast expression. 569 ParenParseOption ParenExprType = 570 (isUnaryExpression && !getLang().CPlusPlus)? CompoundLiteral : CastExpr; 571 ParsedType CastTy; 572 SourceLocation RParenLoc; 573 574 { 575 // The inside of the parens don't need to be a colon protected scope, and 576 // isn't immediately a message send. 577 ColonProtectionRAIIObject X(*this, false); 578 579 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/, 580 TypeOfCast, CastTy, RParenLoc); 581 } 582 583 switch (ParenExprType) { 584 case SimpleExpr: break; // Nothing else to do. 585 case CompoundStmt: break; // Nothing else to do. 586 case CompoundLiteral: 587 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of 588 // postfix-expression exist, parse them now. 589 break; 590 case CastExpr: 591 // We have parsed the cast-expression and no postfix-expr pieces are 592 // following. 593 return move(Res); 594 } 595 596 break; 597 } 598 599 // primary-expression 600 case tok::numeric_constant: 601 // constant: integer-constant 602 // constant: floating-constant 603 604 Res = Actions.ActOnNumericConstant(Tok); 605 ConsumeToken(); 606 break; 607 608 case tok::kw_true: 609 case tok::kw_false: 610 return ParseCXXBoolLiteral(); 611 612 case tok::kw_nullptr: 613 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken()); 614 615 case tok::identifier: { // primary-expression: identifier 616 // unqualified-id: identifier 617 // constant: enumeration-constant 618 // Turn a potentially qualified name into a annot_typename or 619 // annot_cxxscope if it would be valid. This handles things like x::y, etc. 620 if (getLang().CPlusPlus) { 621 // Avoid the unnecessary parse-time lookup in the common case 622 // where the syntax forbids a type. 623 const Token &Next = NextToken(); 624 if (Next.is(tok::coloncolon) || 625 (!ColonIsSacred && Next.is(tok::colon)) || 626 Next.is(tok::less) || 627 Next.is(tok::l_paren)) { 628 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 629 if (TryAnnotateTypeOrScopeToken()) 630 return ExprError(); 631 if (!Tok.is(tok::identifier)) 632 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 633 } 634 } 635 636 // Consume the identifier so that we can see if it is followed by a '(' or 637 // '.'. 638 IdentifierInfo &II = *Tok.getIdentifierInfo(); 639 SourceLocation ILoc = ConsumeToken(); 640 641 // Support 'Class.property' and 'super.property' notation. 642 if (getLang().ObjC1 && Tok.is(tok::period) && 643 (Actions.getTypeName(II, ILoc, getCurScope()) || 644 // Allow the base to be 'super' if in an objc-method. 645 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) { 646 ConsumeToken(); 647 648 if (Tok.isNot(tok::identifier)) { 649 Diag(Tok, diag::err_expected_property_name); 650 return ExprError(); 651 } 652 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); 653 SourceLocation PropertyLoc = ConsumeToken(); 654 655 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName, 656 ILoc, PropertyLoc); 657 break; 658 } 659 660 // In an Objective-C method, if we have "super" followed by an identifier, 661 // the token sequence is ill-formed. However, if there's a ':' or ']' after 662 // that identifier, this is probably a message send with a missing open 663 // bracket. Treat it as such. 664 if (getLang().ObjC1 && &II == Ident_super && !InMessageExpression && 665 getCurScope()->isInObjcMethodScope() && 666 ((Tok.is(tok::identifier) && 667 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) || 668 Tok.is(tok::code_completion))) { 669 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(), 670 0); 671 break; 672 } 673 674 // If we have an Objective-C class name followed by an identifier 675 // and either ':' or ']', this is an Objective-C class message 676 // send that's missing the opening '['. Recovery 677 // appropriately. Also take this path if we're performing code 678 // completion after an Objective-C class name. 679 if (getLang().ObjC1 && 680 ((Tok.is(tok::identifier) && !InMessageExpression) || 681 Tok.is(tok::code_completion))) { 682 const Token& Next = NextToken(); 683 if (Tok.is(tok::code_completion) || 684 Next.is(tok::colon) || Next.is(tok::r_square)) 685 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope())) 686 if (Typ.get()->isObjCObjectOrInterfaceType()) { 687 // Fake up a Declarator to use with ActOnTypeName. 688 DeclSpec DS(AttrFactory); 689 DS.SetRangeStart(ILoc); 690 DS.SetRangeEnd(ILoc); 691 const char *PrevSpec = 0; 692 unsigned DiagID; 693 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ); 694 695 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 696 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), 697 DeclaratorInfo); 698 if (Ty.isInvalid()) 699 break; 700 701 Res = ParseObjCMessageExpressionBody(SourceLocation(), 702 SourceLocation(), 703 Ty.get(), 0); 704 break; 705 } 706 } 707 708 // Make sure to pass down the right value for isAddressOfOperand. 709 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 710 isAddressOfOperand = false; 711 712 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we 713 // need to know whether or not this identifier is a function designator or 714 // not. 715 UnqualifiedId Name; 716 CXXScopeSpec ScopeSpec; 717 Name.setIdentifier(&II, ILoc); 718 Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, Name, 719 Tok.is(tok::l_paren), isAddressOfOperand); 720 break; 721 } 722 case tok::char_constant: // constant: character-constant 723 Res = Actions.ActOnCharacterConstant(Tok); 724 ConsumeToken(); 725 break; 726 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] 727 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] 728 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] 729 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind); 730 ConsumeToken(); 731 break; 732 case tok::string_literal: // primary-expression: string-literal 733 case tok::wide_string_literal: 734 Res = ParseStringLiteralExpression(); 735 break; 736 case tok::kw__Generic: // primary-expression: generic-selection [C1X 6.5.1] 737 Res = ParseGenericSelectionExpression(); 738 break; 739 case tok::kw___builtin_va_arg: 740 case tok::kw___builtin_offsetof: 741 case tok::kw___builtin_choose_expr: 742 return ParseBuiltinPrimaryExpression(); 743 case tok::kw___null: 744 return Actions.ActOnGNUNullExpr(ConsumeToken()); 745 break; 746 case tok::plusplus: // unary-expression: '++' unary-expression [C99] 747 case tok::minusminus: { // unary-expression: '--' unary-expression [C99] 748 // C++ [expr.unary] has: 749 // unary-expression: 750 // ++ cast-expression 751 // -- cast-expression 752 SourceLocation SavedLoc = ConsumeToken(); 753 Res = ParseCastExpression(!getLang().CPlusPlus); 754 if (!Res.isInvalid()) 755 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 756 return move(Res); 757 } 758 case tok::amp: { // unary-expression: '&' cast-expression 759 // Special treatment because of member pointers 760 SourceLocation SavedLoc = ConsumeToken(); 761 Res = ParseCastExpression(false, true); 762 if (!Res.isInvalid()) 763 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 764 return move(Res); 765 } 766 767 case tok::star: // unary-expression: '*' cast-expression 768 case tok::plus: // unary-expression: '+' cast-expression 769 case tok::minus: // unary-expression: '-' cast-expression 770 case tok::tilde: // unary-expression: '~' cast-expression 771 case tok::exclaim: // unary-expression: '!' cast-expression 772 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] 773 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] 774 SourceLocation SavedLoc = ConsumeToken(); 775 Res = ParseCastExpression(false); 776 if (!Res.isInvalid()) 777 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 778 return move(Res); 779 } 780 781 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] 782 // __extension__ silences extension warnings in the subexpression. 783 ExtensionRAIIObject O(Diags); // Use RAII to do this. 784 SourceLocation SavedLoc = ConsumeToken(); 785 Res = ParseCastExpression(false); 786 if (!Res.isInvalid()) 787 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 788 return move(Res); 789 } 790 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression 791 // unary-expression: 'sizeof' '(' type-name ')' 792 case tok::kw_alignof: 793 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression 794 // unary-expression: '__alignof' '(' type-name ')' 795 // unary-expression: 'alignof' '(' type-id ')' 796 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression 797 return ParseUnaryExprOrTypeTraitExpression(); 798 case tok::ampamp: { // unary-expression: '&&' identifier 799 SourceLocation AmpAmpLoc = ConsumeToken(); 800 if (Tok.isNot(tok::identifier)) 801 return ExprError(Diag(Tok, diag::err_expected_ident)); 802 803 if (getCurScope()->getFnParent() == 0) 804 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn)); 805 806 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); 807 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), 808 Tok.getLocation()); 809 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD); 810 ConsumeToken(); 811 return move(Res); 812 } 813 case tok::kw_const_cast: 814 case tok::kw_dynamic_cast: 815 case tok::kw_reinterpret_cast: 816 case tok::kw_static_cast: 817 Res = ParseCXXCasts(); 818 break; 819 case tok::kw_typeid: 820 Res = ParseCXXTypeid(); 821 break; 822 case tok::kw___uuidof: 823 Res = ParseCXXUuidof(); 824 break; 825 case tok::kw_this: 826 Res = ParseCXXThis(); 827 break; 828 829 case tok::annot_typename: 830 if (isStartOfObjCClassMessageMissingOpenBracket()) { 831 ParsedType Type = getTypeAnnotation(Tok); 832 833 // Fake up a Declarator to use with ActOnTypeName. 834 DeclSpec DS(AttrFactory); 835 DS.SetRangeStart(Tok.getLocation()); 836 DS.SetRangeEnd(Tok.getLastLoc()); 837 838 const char *PrevSpec = 0; 839 unsigned DiagID; 840 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(), 841 PrevSpec, DiagID, Type); 842 843 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 844 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 845 if (Ty.isInvalid()) 846 break; 847 848 ConsumeToken(); 849 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 850 Ty.get(), 0); 851 break; 852 } 853 // Fall through 854 855 case tok::kw_char: 856 case tok::kw_wchar_t: 857 case tok::kw_char16_t: 858 case tok::kw_char32_t: 859 case tok::kw_bool: 860 case tok::kw_short: 861 case tok::kw_int: 862 case tok::kw_long: 863 case tok::kw_signed: 864 case tok::kw_unsigned: 865 case tok::kw_float: 866 case tok::kw_double: 867 case tok::kw_void: 868 case tok::kw_typename: 869 case tok::kw_typeof: 870 case tok::kw___vector: { 871 if (!getLang().CPlusPlus) { 872 Diag(Tok, diag::err_expected_expression); 873 return ExprError(); 874 } 875 876 if (SavedKind == tok::kw_typename) { 877 // postfix-expression: typename-specifier '(' expression-list[opt] ')' 878 if (TryAnnotateTypeOrScopeToken()) 879 return ExprError(); 880 } 881 882 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' 883 // 884 DeclSpec DS(AttrFactory); 885 ParseCXXSimpleTypeSpecifier(DS); 886 if (Tok.isNot(tok::l_paren)) 887 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) 888 << DS.getSourceRange()); 889 890 Res = ParseCXXTypeConstructExpression(DS); 891 break; 892 } 893 894 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id 895 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 896 // (We can end up in this situation after tentative parsing.) 897 if (TryAnnotateTypeOrScopeToken()) 898 return ExprError(); 899 if (!Tok.is(tok::annot_cxxscope)) 900 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 901 NotCastExpr, TypeOfCast); 902 903 Token Next = NextToken(); 904 if (Next.is(tok::annot_template_id)) { 905 TemplateIdAnnotation *TemplateId 906 = static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()); 907 if (TemplateId->Kind == TNK_Type_template) { 908 // We have a qualified template-id that we know refers to a 909 // type, translate it into a type and continue parsing as a 910 // cast expression. 911 CXXScopeSpec SS; 912 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 913 AnnotateTemplateIdTokenAsType(); 914 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 915 NotCastExpr, TypeOfCast); 916 } 917 } 918 919 // Parse as an id-expression. 920 Res = ParseCXXIdExpression(isAddressOfOperand); 921 break; 922 } 923 924 case tok::annot_template_id: { // [C++] template-id 925 TemplateIdAnnotation *TemplateId 926 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 927 if (TemplateId->Kind == TNK_Type_template) { 928 // We have a template-id that we know refers to a type, 929 // translate it into a type and continue parsing as a cast 930 // expression. 931 AnnotateTemplateIdTokenAsType(); 932 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 933 NotCastExpr, TypeOfCast); 934 } 935 936 // Fall through to treat the template-id as an id-expression. 937 } 938 939 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id 940 Res = ParseCXXIdExpression(isAddressOfOperand); 941 break; 942 943 case tok::coloncolon: { 944 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken 945 // annotates the token, tail recurse. 946 if (TryAnnotateTypeOrScopeToken()) 947 return ExprError(); 948 if (!Tok.is(tok::coloncolon)) 949 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 950 951 // ::new -> [C++] new-expression 952 // ::delete -> [C++] delete-expression 953 SourceLocation CCLoc = ConsumeToken(); 954 if (Tok.is(tok::kw_new)) 955 return ParseCXXNewExpression(true, CCLoc); 956 if (Tok.is(tok::kw_delete)) 957 return ParseCXXDeleteExpression(true, CCLoc); 958 959 // This is not a type name or scope specifier, it is an invalid expression. 960 Diag(CCLoc, diag::err_expected_expression); 961 return ExprError(); 962 } 963 964 case tok::kw_new: // [C++] new-expression 965 return ParseCXXNewExpression(false, Tok.getLocation()); 966 967 case tok::kw_delete: // [C++] delete-expression 968 return ParseCXXDeleteExpression(false, Tok.getLocation()); 969 970 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')' 971 SourceLocation KeyLoc = ConsumeToken(); 972 SourceLocation LParen = Tok.getLocation(); 973 if (ExpectAndConsume(tok::l_paren, 974 diag::err_expected_lparen_after, "noexcept")) 975 return ExprError(); 976 // C++ [expr.unary.noexcept]p1: 977 // The noexcept operator determines whether the evaluation of its operand, 978 // which is an unevaluated operand, can throw an exception. 979 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 980 ExprResult Result = ParseExpression(); 981 SourceLocation RParen = MatchRHSPunctuation(tok::r_paren, LParen); 982 if (!Result.isInvalid()) 983 Result = Actions.ActOnNoexceptExpr(KeyLoc, LParen, Result.take(), RParen); 984 return move(Result); 985 } 986 987 case tok::kw___is_abstract: // [GNU] unary-type-trait 988 case tok::kw___is_class: 989 case tok::kw___is_empty: 990 case tok::kw___is_enum: 991 case tok::kw___is_literal: 992 case tok::kw___is_literal_type: 993 case tok::kw___is_pod: 994 case tok::kw___is_polymorphic: 995 case tok::kw___is_trivial: 996 case tok::kw___is_union: 997 case tok::kw___has_trivial_constructor: 998 case tok::kw___has_trivial_copy: 999 case tok::kw___has_trivial_assign: 1000 case tok::kw___has_trivial_destructor: 1001 case tok::kw___has_nothrow_assign: 1002 case tok::kw___has_nothrow_copy: 1003 case tok::kw___has_nothrow_constructor: 1004 case tok::kw___has_virtual_destructor: 1005 return ParseUnaryTypeTrait(); 1006 1007 case tok::kw___builtin_types_compatible_p: 1008 case tok::kw___is_base_of: 1009 case tok::kw___is_convertible_to: 1010 return ParseBinaryTypeTrait(); 1011 1012 case tok::at: { 1013 SourceLocation AtLoc = ConsumeToken(); 1014 return ParseObjCAtExpression(AtLoc); 1015 } 1016 case tok::caret: 1017 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression()); 1018 case tok::code_completion: 1019 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 1020 ConsumeCodeCompletionToken(); 1021 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1022 NotCastExpr, TypeOfCast); 1023 case tok::l_square: 1024 // These can be followed by postfix-expr pieces. 1025 if (getLang().ObjC1) 1026 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression()); 1027 // FALL THROUGH. 1028 default: 1029 NotCastExpr = true; 1030 return ExprError(); 1031 } 1032 1033 // These can be followed by postfix-expr pieces. 1034 return ParsePostfixExpressionSuffix(Res); 1035} 1036 1037/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression 1038/// is parsed, this method parses any suffixes that apply. 1039/// 1040/// postfix-expression: [C99 6.5.2] 1041/// primary-expression 1042/// postfix-expression '[' expression ']' 1043/// postfix-expression '(' argument-expression-list[opt] ')' 1044/// postfix-expression '.' identifier 1045/// postfix-expression '->' identifier 1046/// postfix-expression '++' 1047/// postfix-expression '--' 1048/// '(' type-name ')' '{' initializer-list '}' 1049/// '(' type-name ')' '{' initializer-list ',' '}' 1050/// 1051/// argument-expression-list: [C99 6.5.2] 1052/// argument-expression ...[opt] 1053/// argument-expression-list ',' assignment-expression ...[opt] 1054/// 1055ExprResult 1056Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { 1057 // Now that the primary-expression piece of the postfix-expression has been 1058 // parsed, see if there are any postfix-expression pieces here. 1059 SourceLocation Loc; 1060 while (1) { 1061 switch (Tok.getKind()) { 1062 case tok::code_completion: 1063 if (InMessageExpression) 1064 return move(LHS); 1065 1066 Actions.CodeCompletePostfixExpression(getCurScope(), LHS); 1067 ConsumeCodeCompletionToken(); 1068 LHS = ExprError(); 1069 break; 1070 1071 case tok::identifier: 1072 // If we see identifier: after an expression, and we're not already in a 1073 // message send, then this is probably a message send with a missing 1074 // opening bracket '['. 1075 if (getLang().ObjC1 && !InMessageExpression && 1076 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 1077 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 1078 ParsedType(), LHS.get()); 1079 break; 1080 } 1081 1082 // Fall through; this isn't a message send. 1083 1084 default: // Not a postfix-expression suffix. 1085 return move(LHS); 1086 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 1087 // If we have a array postfix expression that starts on a new line and 1088 // Objective-C is enabled, it is highly likely that the user forgot a 1089 // semicolon after the base expression and that the array postfix-expr is 1090 // actually another message send. In this case, do some look-ahead to see 1091 // if the contents of the square brackets are obviously not a valid 1092 // expression and recover by pretending there is no suffix. 1093 if (getLang().ObjC1 && Tok.isAtStartOfLine() && 1094 isSimpleObjCMessageExpression()) 1095 return move(LHS); 1096 1097 Loc = ConsumeBracket(); 1098 ExprResult Idx(ParseExpression()); 1099 1100 SourceLocation RLoc = Tok.getLocation(); 1101 1102 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 1103 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc, 1104 Idx.take(), RLoc); 1105 } else 1106 LHS = ExprError(); 1107 1108 // Match the ']'. 1109 MatchRHSPunctuation(tok::r_square, Loc); 1110 break; 1111 } 1112 1113 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')' 1114 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>' 1115 // '(' argument-expression-list[opt] ')' 1116 tok::TokenKind OpKind = Tok.getKind(); 1117 InMessageExpressionRAIIObject InMessage(*this, false); 1118 1119 Expr *ExecConfig = 0; 1120 1121 if (OpKind == tok::lesslessless) { 1122 ExprVector ExecConfigExprs(Actions); 1123 CommaLocsTy ExecConfigCommaLocs; 1124 SourceLocation LLLLoc, GGGLoc; 1125 1126 LLLLoc = ConsumeToken(); 1127 1128 if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) { 1129 LHS = ExprError(); 1130 } 1131 1132 if (LHS.isInvalid()) { 1133 SkipUntil(tok::greatergreatergreater); 1134 } else if (Tok.isNot(tok::greatergreatergreater)) { 1135 MatchRHSPunctuation(tok::greatergreatergreater, LLLLoc); 1136 LHS = ExprError(); 1137 } else { 1138 GGGLoc = ConsumeToken(); 1139 } 1140 1141 if (!LHS.isInvalid()) { 1142 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, "")) 1143 LHS = ExprError(); 1144 else 1145 Loc = PrevTokLocation; 1146 } 1147 1148 if (!LHS.isInvalid()) { 1149 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), 1150 LLLLoc, move_arg(ExecConfigExprs), GGGLoc); 1151 if (ECResult.isInvalid()) 1152 LHS = ExprError(); 1153 else 1154 ExecConfig = ECResult.get(); 1155 } 1156 } else { 1157 Loc = ConsumeParen(); 1158 } 1159 1160 ExprVector ArgExprs(Actions); 1161 CommaLocsTy CommaLocs; 1162 1163 if (Tok.is(tok::code_completion)) { 1164 Actions.CodeCompleteCall(getCurScope(), LHS.get(), 0, 0); 1165 ConsumeCodeCompletionToken(); 1166 } 1167 1168 if (OpKind == tok::l_paren || !LHS.isInvalid()) { 1169 if (Tok.isNot(tok::r_paren)) { 1170 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall, 1171 LHS.get())) { 1172 SkipUntil(tok::r_paren); 1173 LHS = ExprError(); 1174 } 1175 } 1176 } 1177 1178 // Match the ')'. 1179 if (LHS.isInvalid()) { 1180 SkipUntil(tok::r_paren); 1181 } else if (Tok.isNot(tok::r_paren)) { 1182 MatchRHSPunctuation(tok::r_paren, Loc); 1183 LHS = ExprError(); 1184 } else { 1185 assert((ArgExprs.size() == 0 || 1186 ArgExprs.size()-1 == CommaLocs.size())&& 1187 "Unexpected number of commas!"); 1188 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc, 1189 move_arg(ArgExprs), Tok.getLocation(), 1190 ExecConfig); 1191 ConsumeParen(); 1192 } 1193 1194 break; 1195 } 1196 case tok::arrow: 1197 case tok::period: { 1198 // postfix-expression: p-e '->' template[opt] id-expression 1199 // postfix-expression: p-e '.' template[opt] id-expression 1200 tok::TokenKind OpKind = Tok.getKind(); 1201 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 1202 1203 CXXScopeSpec SS; 1204 ParsedType ObjectType; 1205 bool MayBePseudoDestructor = false; 1206 if (getLang().CPlusPlus && !LHS.isInvalid()) { 1207 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(), 1208 OpLoc, OpKind, ObjectType, 1209 MayBePseudoDestructor); 1210 if (LHS.isInvalid()) 1211 break; 1212 1213 ParseOptionalCXXScopeSpecifier(SS, ObjectType, false, 1214 &MayBePseudoDestructor); 1215 if (SS.isNotEmpty()) 1216 ObjectType = ParsedType(); 1217 } 1218 1219 if (Tok.is(tok::code_completion)) { 1220 // Code completion for a member access expression. 1221 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(), 1222 OpLoc, OpKind == tok::arrow); 1223 1224 ConsumeCodeCompletionToken(); 1225 } 1226 1227 if (MayBePseudoDestructor && !LHS.isInvalid()) { 1228 LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS, 1229 ObjectType); 1230 break; 1231 } 1232 1233 // Either the action has told is that this cannot be a 1234 // pseudo-destructor expression (based on the type of base 1235 // expression), or we didn't see a '~' in the right place. We 1236 // can still parse a destructor name here, but in that case it 1237 // names a real destructor. 1238 // Allow explicit constructor calls in Microsoft mode. 1239 // FIXME: Add support for explicit call of template constructor. 1240 UnqualifiedId Name; 1241 if (ParseUnqualifiedId(SS, 1242 /*EnteringContext=*/false, 1243 /*AllowDestructorName=*/true, 1244 /*AllowConstructorName=*/ getLang().Microsoft, 1245 ObjectType, 1246 Name)) 1247 LHS = ExprError(); 1248 1249 if (!LHS.isInvalid()) 1250 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc, 1251 OpKind, SS, Name, ObjCImpDecl, 1252 Tok.is(tok::l_paren)); 1253 break; 1254 } 1255 case tok::plusplus: // postfix-expression: postfix-expression '++' 1256 case tok::minusminus: // postfix-expression: postfix-expression '--' 1257 if (!LHS.isInvalid()) { 1258 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(), 1259 Tok.getKind(), LHS.take()); 1260 } 1261 ConsumeToken(); 1262 break; 1263 } 1264 } 1265} 1266 1267/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/ 1268/// vec_step and we are at the start of an expression or a parenthesized 1269/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the 1270/// expression (isCastExpr == false) or the type (isCastExpr == true). 1271/// 1272/// unary-expression: [C99 6.5.3] 1273/// 'sizeof' unary-expression 1274/// 'sizeof' '(' type-name ')' 1275/// [GNU] '__alignof' unary-expression 1276/// [GNU] '__alignof' '(' type-name ')' 1277/// [C++0x] 'alignof' '(' type-id ')' 1278/// 1279/// [GNU] typeof-specifier: 1280/// typeof ( expressions ) 1281/// typeof ( type-name ) 1282/// [GNU/C++] typeof unary-expression 1283/// 1284/// [OpenCL 1.1 6.11.12] vec_step built-in function: 1285/// vec_step ( expressions ) 1286/// vec_step ( type-name ) 1287/// 1288ExprResult 1289Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, 1290 bool &isCastExpr, 1291 ParsedType &CastTy, 1292 SourceRange &CastRange) { 1293 1294 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 1295 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) || 1296 OpTok.is(tok::kw_vec_step)) && 1297 "Not a typeof/sizeof/alignof/vec_step expression!"); 1298 1299 ExprResult Operand; 1300 1301 // If the operand doesn't start with an '(', it must be an expression. 1302 if (Tok.isNot(tok::l_paren)) { 1303 isCastExpr = false; 1304 if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) { 1305 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 1306 return ExprError(); 1307 } 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 = ParseCastExpression(true/*isUnaryExpression*/); 1318 } else { 1319 // If it starts with a '(', we know that it is either a parenthesized 1320 // type-name, or it is a unary-expression that starts with a compound 1321 // literal, or starts with a primary-expression that is a parenthesized 1322 // expression. 1323 ParenParseOption ExprType = CastExpr; 1324 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 1325 1326 // C++0x [expr.sizeof]p1: 1327 // [...] The operand is either an expression, which is an unevaluated 1328 // operand (Clause 5) [...] 1329 // 1330 // The GNU typeof and alignof extensions also behave as unevaluated 1331 // operands. 1332 EnterExpressionEvaluationContext Unevaluated(Actions, 1333 Sema::Unevaluated); 1334 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 1335 ParsedType(), CastTy, RParenLoc); 1336 CastRange = SourceRange(LParenLoc, RParenLoc); 1337 1338 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 1339 // a type. 1340 if (ExprType == CastExpr) { 1341 isCastExpr = true; 1342 return ExprEmpty(); 1343 } 1344 1345 if (getLang().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { 1346 // GNU typeof in C requires the expression to be parenthesized. Not so for 1347 // sizeof/alignof or in C++. Therefore, the parenthesized expression is 1348 // the start of a unary-expression, but doesn't include any postfix 1349 // pieces. Parse these now if present. 1350 if (!Operand.isInvalid()) 1351 Operand = ParsePostfixExpressionSuffix(Operand.get()); 1352 } 1353 } 1354 1355 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 1356 isCastExpr = false; 1357 return move(Operand); 1358} 1359 1360 1361/// ParseUnaryExprOrTypeTraitExpression - Parse a sizeof or alignof expression. 1362/// unary-expression: [C99 6.5.3] 1363/// 'sizeof' unary-expression 1364/// 'sizeof' '(' type-name ')' 1365/// [C++0x] 'sizeof' '...' '(' identifier ')' 1366/// [GNU] '__alignof' unary-expression 1367/// [GNU] '__alignof' '(' type-name ')' 1368/// [C++0x] 'alignof' '(' type-id ')' 1369ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { 1370 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) 1371 || Tok.is(tok::kw_alignof) || Tok.is(tok::kw_vec_step)) && 1372 "Not a sizeof/alignof/vec_step expression!"); 1373 Token OpTok = Tok; 1374 ConsumeToken(); 1375 1376 // [C++0x] 'sizeof' '...' '(' identifier ')' 1377 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) { 1378 SourceLocation EllipsisLoc = ConsumeToken(); 1379 SourceLocation LParenLoc, RParenLoc; 1380 IdentifierInfo *Name = 0; 1381 SourceLocation NameLoc; 1382 if (Tok.is(tok::l_paren)) { 1383 LParenLoc = ConsumeParen(); 1384 if (Tok.is(tok::identifier)) { 1385 Name = Tok.getIdentifierInfo(); 1386 NameLoc = ConsumeToken(); 1387 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1388 if (RParenLoc.isInvalid()) 1389 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1390 } else { 1391 Diag(Tok, diag::err_expected_parameter_pack); 1392 SkipUntil(tok::r_paren); 1393 } 1394 } else if (Tok.is(tok::identifier)) { 1395 Name = Tok.getIdentifierInfo(); 1396 NameLoc = ConsumeToken(); 1397 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc); 1398 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1399 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack) 1400 << Name 1401 << FixItHint::CreateInsertion(LParenLoc, "(") 1402 << FixItHint::CreateInsertion(RParenLoc, ")"); 1403 } else { 1404 Diag(Tok, diag::err_sizeof_parameter_pack); 1405 } 1406 1407 if (!Name) 1408 return ExprError(); 1409 1410 return Actions.ActOnSizeofParameterPackExpr(getCurScope(), 1411 OpTok.getLocation(), 1412 *Name, NameLoc, 1413 RParenLoc); 1414 } 1415 1416 bool isCastExpr; 1417 ParsedType CastTy; 1418 SourceRange CastRange; 1419 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, 1420 isCastExpr, 1421 CastTy, 1422 CastRange); 1423 1424 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf; 1425 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof)) 1426 ExprKind = UETT_AlignOf; 1427 else if (OpTok.is(tok::kw_vec_step)) 1428 ExprKind = UETT_VecStep; 1429 1430 if (isCastExpr) 1431 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 1432 ExprKind, 1433 /*isType=*/true, 1434 CastTy.getAsOpaquePtr(), 1435 CastRange); 1436 1437 // If we get here, the operand to the sizeof/alignof was an expresion. 1438 if (!Operand.isInvalid()) 1439 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 1440 ExprKind, 1441 /*isType=*/false, 1442 Operand.release(), 1443 CastRange); 1444 return move(Operand); 1445} 1446 1447/// ParseBuiltinPrimaryExpression 1448/// 1449/// primary-expression: [C99 6.5.1] 1450/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1451/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1452/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1453/// assign-expr ')' 1454/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1455/// 1456/// [GNU] offsetof-member-designator: 1457/// [GNU] identifier 1458/// [GNU] offsetof-member-designator '.' identifier 1459/// [GNU] offsetof-member-designator '[' expression ']' 1460/// 1461ExprResult Parser::ParseBuiltinPrimaryExpression() { 1462 ExprResult Res; 1463 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1464 1465 tok::TokenKind T = Tok.getKind(); 1466 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1467 1468 // All of these start with an open paren. 1469 if (Tok.isNot(tok::l_paren)) 1470 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1471 << BuiltinII); 1472 1473 SourceLocation LParenLoc = ConsumeParen(); 1474 // TODO: Build AST. 1475 1476 switch (T) { 1477 default: assert(0 && "Not a builtin primary expression!"); 1478 case tok::kw___builtin_va_arg: { 1479 ExprResult Expr(ParseAssignmentExpression()); 1480 1481 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1482 Expr = ExprError(); 1483 1484 TypeResult Ty = ParseTypeName(); 1485 1486 if (Tok.isNot(tok::r_paren)) { 1487 Diag(Tok, diag::err_expected_rparen); 1488 Expr = ExprError(); 1489 } 1490 1491 if (Expr.isInvalid() || Ty.isInvalid()) 1492 Res = ExprError(); 1493 else 1494 Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen()); 1495 break; 1496 } 1497 case tok::kw___builtin_offsetof: { 1498 SourceLocation TypeLoc = Tok.getLocation(); 1499 TypeResult Ty = ParseTypeName(); 1500 if (Ty.isInvalid()) { 1501 SkipUntil(tok::r_paren); 1502 return ExprError(); 1503 } 1504 1505 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1506 return ExprError(); 1507 1508 // We must have at least one identifier here. 1509 if (Tok.isNot(tok::identifier)) { 1510 Diag(Tok, diag::err_expected_ident); 1511 SkipUntil(tok::r_paren); 1512 return ExprError(); 1513 } 1514 1515 // Keep track of the various subcomponents we see. 1516 llvm::SmallVector<Sema::OffsetOfComponent, 4> Comps; 1517 1518 Comps.push_back(Sema::OffsetOfComponent()); 1519 Comps.back().isBrackets = false; 1520 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1521 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1522 1523 // FIXME: This loop leaks the index expressions on error. 1524 while (1) { 1525 if (Tok.is(tok::period)) { 1526 // offsetof-member-designator: offsetof-member-designator '.' identifier 1527 Comps.push_back(Sema::OffsetOfComponent()); 1528 Comps.back().isBrackets = false; 1529 Comps.back().LocStart = ConsumeToken(); 1530 1531 if (Tok.isNot(tok::identifier)) { 1532 Diag(Tok, diag::err_expected_ident); 1533 SkipUntil(tok::r_paren); 1534 return ExprError(); 1535 } 1536 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1537 Comps.back().LocEnd = ConsumeToken(); 1538 1539 } else if (Tok.is(tok::l_square)) { 1540 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1541 Comps.push_back(Sema::OffsetOfComponent()); 1542 Comps.back().isBrackets = true; 1543 Comps.back().LocStart = ConsumeBracket(); 1544 Res = ParseExpression(); 1545 if (Res.isInvalid()) { 1546 SkipUntil(tok::r_paren); 1547 return move(Res); 1548 } 1549 Comps.back().U.E = Res.release(); 1550 1551 Comps.back().LocEnd = 1552 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart); 1553 } else { 1554 if (Tok.isNot(tok::r_paren)) { 1555 MatchRHSPunctuation(tok::r_paren, LParenLoc); 1556 Res = ExprError(); 1557 } else if (Ty.isInvalid()) { 1558 Res = ExprError(); 1559 } else { 1560 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc, 1561 Ty.get(), &Comps[0], 1562 Comps.size(), ConsumeParen()); 1563 } 1564 break; 1565 } 1566 } 1567 break; 1568 } 1569 case tok::kw___builtin_choose_expr: { 1570 ExprResult Cond(ParseAssignmentExpression()); 1571 if (Cond.isInvalid()) { 1572 SkipUntil(tok::r_paren); 1573 return move(Cond); 1574 } 1575 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1576 return ExprError(); 1577 1578 ExprResult Expr1(ParseAssignmentExpression()); 1579 if (Expr1.isInvalid()) { 1580 SkipUntil(tok::r_paren); 1581 return move(Expr1); 1582 } 1583 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1584 return ExprError(); 1585 1586 ExprResult Expr2(ParseAssignmentExpression()); 1587 if (Expr2.isInvalid()) { 1588 SkipUntil(tok::r_paren); 1589 return move(Expr2); 1590 } 1591 if (Tok.isNot(tok::r_paren)) { 1592 Diag(Tok, diag::err_expected_rparen); 1593 return ExprError(); 1594 } 1595 Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(), 1596 Expr2.take(), ConsumeParen()); 1597 break; 1598 } 1599 } 1600 1601 if (Res.isInvalid()) 1602 return ExprError(); 1603 1604 // These can be followed by postfix-expr pieces because they are 1605 // primary-expressions. 1606 return ParsePostfixExpressionSuffix(Res.take()); 1607} 1608 1609/// ParseParenExpression - This parses the unit that starts with a '(' token, 1610/// based on what is allowed by ExprType. The actual thing parsed is returned 1611/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1612/// not the parsed cast-expression. 1613/// 1614/// primary-expression: [C99 6.5.1] 1615/// '(' expression ')' 1616/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1617/// postfix-expression: [C99 6.5.2] 1618/// '(' type-name ')' '{' initializer-list '}' 1619/// '(' type-name ')' '{' initializer-list ',' '}' 1620/// cast-expression: [C99 6.5.4] 1621/// '(' type-name ')' cast-expression 1622/// 1623ExprResult 1624Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1625 ParsedType TypeOfCast, ParsedType &CastTy, 1626 SourceLocation &RParenLoc) { 1627 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1628 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 1629 SourceLocation OpenLoc = ConsumeParen(); 1630 ExprResult Result(true); 1631 bool isAmbiguousTypeId; 1632 CastTy = ParsedType(); 1633 1634 if (Tok.is(tok::code_completion)) { 1635 Actions.CodeCompleteOrdinaryName(getCurScope(), 1636 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression 1637 : Sema::PCC_Expression); 1638 ConsumeCodeCompletionToken(); 1639 return ExprError(); 1640 } 1641 1642 // None of these cases should fall through with an invalid Result 1643 // unless they've already reported an error. 1644 1645 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 1646 Diag(Tok, diag::ext_gnu_statement_expr); 1647 ParsedAttributes attrs(AttrFactory); 1648 StmtResult Stmt(ParseCompoundStatement(attrs, true)); 1649 ExprType = CompoundStmt; 1650 1651 // If the substmt parsed correctly, build the AST node. 1652 if (!Stmt.isInvalid()) 1653 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation()); 1654 1655 } else if (ExprType >= CompoundLiteral && 1656 isTypeIdInParens(isAmbiguousTypeId)) { 1657 1658 // Otherwise, this is a compound literal expression or cast expression. 1659 1660 // In C++, if the type-id is ambiguous we disambiguate based on context. 1661 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 1662 // in which case we should treat it as type-id. 1663 // if stopIfCastExpr is false, we need to determine the context past the 1664 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 1665 if (isAmbiguousTypeId && !stopIfCastExpr) 1666 return ParseCXXAmbiguousParenExpression(ExprType, CastTy, 1667 OpenLoc, RParenLoc); 1668 1669 TypeResult Ty; 1670 1671 { 1672 InMessageExpressionRAIIObject InMessage(*this, false); 1673 Ty = ParseTypeName(); 1674 } 1675 1676 // If our type is followed by an identifier and either ':' or ']', then 1677 // this is probably an Objective-C message send where the leading '[' is 1678 // missing. Recover as if that were the case. 1679 if (!Ty.isInvalid() && Tok.is(tok::identifier) && !InMessageExpression && 1680 getLang().ObjC1 && !Ty.get().get().isNull() && 1681 (NextToken().is(tok::colon) || NextToken().is(tok::r_square)) && 1682 Ty.get().get()->isObjCObjectOrInterfaceType()) { 1683 Result = ParseObjCMessageExpressionBody(SourceLocation(), 1684 SourceLocation(), 1685 Ty.get(), 0); 1686 } else { 1687 // Match the ')'. 1688 if (Tok.is(tok::r_paren)) 1689 RParenLoc = ConsumeParen(); 1690 else 1691 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1692 1693 if (Tok.is(tok::l_brace)) { 1694 ExprType = CompoundLiteral; 1695 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 1696 } 1697 1698 if (ExprType == CastExpr) { 1699 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 1700 1701 if (Ty.isInvalid()) 1702 return ExprError(); 1703 1704 CastTy = Ty.get(); 1705 1706 // Note that this doesn't parse the subsequent cast-expression, it just 1707 // returns the parsed type to the callee. 1708 if (stopIfCastExpr) 1709 return ExprResult(); 1710 1711 // Reject the cast of super idiom in ObjC. 1712 if (Tok.is(tok::identifier) && getLang().ObjC1 && 1713 Tok.getIdentifierInfo() == Ident_super && 1714 getCurScope()->isInObjcMethodScope() && 1715 GetLookAheadToken(1).isNot(tok::period)) { 1716 Diag(Tok.getLocation(), diag::err_illegal_super_cast) 1717 << SourceRange(OpenLoc, RParenLoc); 1718 return ExprError(); 1719 } 1720 1721 // Parse the cast-expression that follows it next. 1722 // TODO: For cast expression with CastTy. 1723 Result = ParseCastExpression(false, false, CastTy); 1724 if (!Result.isInvalid()) 1725 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, CastTy, 1726 RParenLoc, Result.take()); 1727 return move(Result); 1728 } 1729 1730 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 1731 return ExprError(); 1732 } 1733 } else if (TypeOfCast) { 1734 // Parse the expression-list. 1735 InMessageExpressionRAIIObject InMessage(*this, false); 1736 1737 ExprVector ArgExprs(Actions); 1738 CommaLocsTy CommaLocs; 1739 1740 if (!ParseExpressionList(ArgExprs, CommaLocs)) { 1741 ExprType = SimpleExpr; 1742 Result = Actions.ActOnParenOrParenListExpr(OpenLoc, Tok.getLocation(), 1743 move_arg(ArgExprs), TypeOfCast); 1744 } 1745 } else { 1746 InMessageExpressionRAIIObject InMessage(*this, false); 1747 1748 Result = ParseExpression(); 1749 ExprType = SimpleExpr; 1750 1751 // Don't build a paren expression unless we actually match a ')'. 1752 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 1753 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take()); 1754 } 1755 1756 // Match the ')'. 1757 if (Result.isInvalid()) { 1758 SkipUntil(tok::r_paren); 1759 return ExprError(); 1760 } 1761 1762 if (Tok.is(tok::r_paren)) 1763 RParenLoc = ConsumeParen(); 1764 else 1765 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1766 1767 return move(Result); 1768} 1769 1770/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 1771/// and we are at the left brace. 1772/// 1773/// postfix-expression: [C99 6.5.2] 1774/// '(' type-name ')' '{' initializer-list '}' 1775/// '(' type-name ')' '{' initializer-list ',' '}' 1776/// 1777ExprResult 1778Parser::ParseCompoundLiteralExpression(ParsedType Ty, 1779 SourceLocation LParenLoc, 1780 SourceLocation RParenLoc) { 1781 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 1782 if (!getLang().C99) // Compound literals don't exist in C90. 1783 Diag(LParenLoc, diag::ext_c99_compound_literal); 1784 ExprResult Result = ParseInitializer(); 1785 if (!Result.isInvalid() && Ty) 1786 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take()); 1787 return move(Result); 1788} 1789 1790/// ParseStringLiteralExpression - This handles the various token types that 1791/// form string literals, and also handles string concatenation [C99 5.1.1.2, 1792/// translation phase #6]. 1793/// 1794/// primary-expression: [C99 6.5.1] 1795/// string-literal 1796ExprResult Parser::ParseStringLiteralExpression() { 1797 assert(isTokenStringLiteral() && "Not a string literal!"); 1798 1799 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 1800 // considered to be strings for concatenation purposes. 1801 llvm::SmallVector<Token, 4> StringToks; 1802 1803 do { 1804 StringToks.push_back(Tok); 1805 ConsumeStringToken(); 1806 } while (isTokenStringLiteral()); 1807 1808 // Pass the set of string tokens, ready for concatenation, to the actions. 1809 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size()); 1810} 1811 1812/// ParseGenericSelectionExpression - Parse a C1X generic-selection 1813/// [C1X 6.5.1.1]. 1814/// 1815/// generic-selection: 1816/// _Generic ( assignment-expression , generic-assoc-list ) 1817/// generic-assoc-list: 1818/// generic-association 1819/// generic-assoc-list , generic-association 1820/// generic-association: 1821/// type-name : assignment-expression 1822/// default : assignment-expression 1823ExprResult Parser::ParseGenericSelectionExpression() { 1824 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected"); 1825 SourceLocation KeyLoc = ConsumeToken(); 1826 1827 if (!getLang().C1X) 1828 Diag(KeyLoc, diag::ext_c1x_generic_selection); 1829 1830 SourceLocation LParenLoc = Tok.getLocation(); 1831 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, "")) 1832 return ExprError(); 1833 1834 ExprResult ControllingExpr; 1835 { 1836 // C1X 6.5.1.1p3 "The controlling expression of a generic selection is 1837 // not evaluated." 1838 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 1839 ControllingExpr = ParseAssignmentExpression(); 1840 if (ControllingExpr.isInvalid()) { 1841 SkipUntil(tok::r_paren); 1842 return ExprError(); 1843 } 1844 } 1845 1846 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "")) { 1847 SkipUntil(tok::r_paren); 1848 return ExprError(); 1849 } 1850 1851 SourceLocation DefaultLoc; 1852 TypeVector Types(Actions); 1853 ExprVector Exprs(Actions); 1854 while (1) { 1855 ParsedType Ty; 1856 if (Tok.is(tok::kw_default)) { 1857 // C1X 6.5.1.1p2 "A generic selection shall have no more than one default 1858 // generic association." 1859 if (!DefaultLoc.isInvalid()) { 1860 Diag(Tok, diag::err_duplicate_default_assoc); 1861 Diag(DefaultLoc, diag::note_previous_default_assoc); 1862 SkipUntil(tok::r_paren); 1863 return ExprError(); 1864 } 1865 DefaultLoc = ConsumeToken(); 1866 Ty = ParsedType(); 1867 } else { 1868 ColonProtectionRAIIObject X(*this); 1869 TypeResult TR = ParseTypeName(); 1870 if (TR.isInvalid()) { 1871 SkipUntil(tok::r_paren); 1872 return ExprError(); 1873 } 1874 Ty = TR.release(); 1875 } 1876 Types.push_back(Ty); 1877 1878 if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "")) { 1879 SkipUntil(tok::r_paren); 1880 return ExprError(); 1881 } 1882 1883 // FIXME: These expressions should be parsed in a potentially potentially 1884 // evaluated context. 1885 ExprResult ER(ParseAssignmentExpression()); 1886 if (ER.isInvalid()) { 1887 SkipUntil(tok::r_paren); 1888 return ExprError(); 1889 } 1890 Exprs.push_back(ER.release()); 1891 1892 if (Tok.isNot(tok::comma)) 1893 break; 1894 ConsumeToken(); 1895 } 1896 1897 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1898 if (RParenLoc.isInvalid()) 1899 return ExprError(); 1900 1901 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1902 ControllingExpr.release(), 1903 move_arg(Types), move_arg(Exprs)); 1904} 1905 1906/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 1907/// 1908/// argument-expression-list: 1909/// assignment-expression 1910/// argument-expression-list , assignment-expression 1911/// 1912/// [C++] expression-list: 1913/// [C++] assignment-expression ...[opt] 1914/// [C++] expression-list , assignment-expression ...[opt] 1915/// 1916bool Parser::ParseExpressionList(llvm::SmallVectorImpl<Expr*> &Exprs, 1917 llvm::SmallVectorImpl<SourceLocation> &CommaLocs, 1918 void (Sema::*Completer)(Scope *S, 1919 Expr *Data, 1920 Expr **Args, 1921 unsigned NumArgs), 1922 Expr *Data) { 1923 while (1) { 1924 if (Tok.is(tok::code_completion)) { 1925 if (Completer) 1926 (Actions.*Completer)(getCurScope(), Data, Exprs.data(), Exprs.size()); 1927 else 1928 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 1929 ConsumeCodeCompletionToken(); 1930 } 1931 1932 ExprResult Expr(ParseAssignmentExpression()); 1933 if (Tok.is(tok::ellipsis)) 1934 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); 1935 if (Expr.isInvalid()) 1936 return true; 1937 1938 Exprs.push_back(Expr.release()); 1939 1940 if (Tok.isNot(tok::comma)) 1941 return false; 1942 // Move to the next argument, remember where the comma was. 1943 CommaLocs.push_back(ConsumeToken()); 1944 } 1945} 1946 1947/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 1948/// 1949/// [clang] block-id: 1950/// [clang] specifier-qualifier-list block-declarator 1951/// 1952void Parser::ParseBlockId() { 1953 if (Tok.is(tok::code_completion)) { 1954 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); 1955 ConsumeCodeCompletionToken(); 1956 } 1957 1958 // Parse the specifier-qualifier-list piece. 1959 DeclSpec DS(AttrFactory); 1960 ParseSpecifierQualifierList(DS); 1961 1962 // Parse the block-declarator. 1963 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 1964 ParseDeclarator(DeclaratorInfo); 1965 1966 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 1967 DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation()); 1968 1969 MaybeParseGNUAttributes(DeclaratorInfo); 1970 1971 // Inform sema that we are starting a block. 1972 Actions.ActOnBlockArguments(DeclaratorInfo, getCurScope()); 1973} 1974 1975/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 1976/// like ^(int x){ return x+1; } 1977/// 1978/// block-literal: 1979/// [clang] '^' block-args[opt] compound-statement 1980/// [clang] '^' block-id compound-statement 1981/// [clang] block-args: 1982/// [clang] '(' parameter-list ')' 1983/// 1984ExprResult Parser::ParseBlockLiteralExpression() { 1985 assert(Tok.is(tok::caret) && "block literal starts with ^"); 1986 SourceLocation CaretLoc = ConsumeToken(); 1987 1988 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 1989 "block literal parsing"); 1990 1991 // Enter a scope to hold everything within the block. This includes the 1992 // argument decls, decls within the compound expression, etc. This also 1993 // allows determining whether a variable reference inside the block is 1994 // within or outside of the block. 1995 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 1996 Scope::BreakScope | Scope::ContinueScope | 1997 Scope::DeclScope); 1998 1999 // Inform sema that we are starting a block. 2000 Actions.ActOnBlockStart(CaretLoc, getCurScope()); 2001 2002 // Parse the return type if present. 2003 DeclSpec DS(AttrFactory); 2004 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 2005 // FIXME: Since the return type isn't actually parsed, it can't be used to 2006 // fill ParamInfo with an initial valid range, so do it manually. 2007 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 2008 2009 // If this block has arguments, parse them. There is no ambiguity here with 2010 // the expression case, because the expression case requires a parameter list. 2011 if (Tok.is(tok::l_paren)) { 2012 ParseParenDeclarator(ParamInfo); 2013 // Parse the pieces after the identifier as if we had "int(...)". 2014 // SetIdentifier sets the source range end, but in this case we're past 2015 // that location. 2016 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 2017 ParamInfo.SetIdentifier(0, CaretLoc); 2018 ParamInfo.SetRangeEnd(Tmp); 2019 if (ParamInfo.isInvalidType()) { 2020 // If there was an error parsing the arguments, they may have 2021 // tried to use ^(x+y) which requires an argument list. Just 2022 // skip the whole block literal. 2023 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2024 return ExprError(); 2025 } 2026 2027 MaybeParseGNUAttributes(ParamInfo); 2028 2029 // Inform sema that we are starting a block. 2030 Actions.ActOnBlockArguments(ParamInfo, getCurScope()); 2031 } else if (!Tok.is(tok::l_brace)) { 2032 ParseBlockId(); 2033 } else { 2034 // Otherwise, pretend we saw (void). 2035 ParsedAttributes attrs(AttrFactory); 2036 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, 2037 SourceLocation(), 2038 0, 0, 0, 2039 true, SourceLocation(), 2040 EST_None, 2041 SourceLocation(), 2042 0, 0, 0, 0, 2043 CaretLoc, CaretLoc, 2044 ParamInfo), 2045 attrs, CaretLoc); 2046 2047 MaybeParseGNUAttributes(ParamInfo); 2048 2049 // Inform sema that we are starting a block. 2050 Actions.ActOnBlockArguments(ParamInfo, getCurScope()); 2051 } 2052 2053 2054 ExprResult Result(true); 2055 if (!Tok.is(tok::l_brace)) { 2056 // Saw something like: ^expr 2057 Diag(Tok, diag::err_expected_expression); 2058 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2059 return ExprError(); 2060 } 2061 2062 StmtResult Stmt(ParseCompoundStatementBody()); 2063 BlockScope.Exit(); 2064 if (!Stmt.isInvalid()) 2065 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope()); 2066 else 2067 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2068 return move(Result); 2069} 2070