ParseExpr.cpp revision b7e9589bce9852b4db9575f55ac9137572147eb5
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_pod: 993 case tok::kw___is_polymorphic: 994 case tok::kw___is_trivial: 995 case tok::kw___is_union: 996 case tok::kw___has_trivial_constructor: 997 case tok::kw___has_trivial_copy: 998 case tok::kw___has_trivial_assign: 999 case tok::kw___has_trivial_destructor: 1000 case tok::kw___has_nothrow_assign: 1001 case tok::kw___has_nothrow_copy: 1002 case tok::kw___has_nothrow_constructor: 1003 case tok::kw___has_virtual_destructor: 1004 return ParseUnaryTypeTrait(); 1005 1006 case tok::kw___builtin_types_compatible_p: 1007 case tok::kw___is_base_of: 1008 case tok::kw___is_convertible_to: 1009 return ParseBinaryTypeTrait(); 1010 1011 case tok::at: { 1012 SourceLocation AtLoc = ConsumeToken(); 1013 return ParseObjCAtExpression(AtLoc); 1014 } 1015 case tok::caret: 1016 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression()); 1017 case tok::code_completion: 1018 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 1019 ConsumeCodeCompletionToken(); 1020 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1021 NotCastExpr, TypeOfCast); 1022 case tok::l_square: 1023 // These can be followed by postfix-expr pieces. 1024 if (getLang().ObjC1) 1025 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression()); 1026 // FALL THROUGH. 1027 default: 1028 NotCastExpr = true; 1029 return ExprError(); 1030 } 1031 1032 // These can be followed by postfix-expr pieces. 1033 return ParsePostfixExpressionSuffix(Res); 1034} 1035 1036/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression 1037/// is parsed, this method parses any suffixes that apply. 1038/// 1039/// postfix-expression: [C99 6.5.2] 1040/// primary-expression 1041/// postfix-expression '[' expression ']' 1042/// postfix-expression '(' argument-expression-list[opt] ')' 1043/// postfix-expression '.' identifier 1044/// postfix-expression '->' identifier 1045/// postfix-expression '++' 1046/// postfix-expression '--' 1047/// '(' type-name ')' '{' initializer-list '}' 1048/// '(' type-name ')' '{' initializer-list ',' '}' 1049/// 1050/// argument-expression-list: [C99 6.5.2] 1051/// argument-expression ...[opt] 1052/// argument-expression-list ',' assignment-expression ...[opt] 1053/// 1054ExprResult 1055Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { 1056 // Now that the primary-expression piece of the postfix-expression has been 1057 // parsed, see if there are any postfix-expression pieces here. 1058 SourceLocation Loc; 1059 while (1) { 1060 switch (Tok.getKind()) { 1061 case tok::code_completion: 1062 if (InMessageExpression) 1063 return move(LHS); 1064 1065 Actions.CodeCompletePostfixExpression(getCurScope(), LHS); 1066 ConsumeCodeCompletionToken(); 1067 LHS = ExprError(); 1068 break; 1069 1070 case tok::identifier: 1071 // If we see identifier: after an expression, and we're not already in a 1072 // message send, then this is probably a message send with a missing 1073 // opening bracket '['. 1074 if (getLang().ObjC1 && !InMessageExpression && 1075 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 1076 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 1077 ParsedType(), LHS.get()); 1078 break; 1079 } 1080 1081 // Fall through; this isn't a message send. 1082 1083 default: // Not a postfix-expression suffix. 1084 return move(LHS); 1085 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 1086 // If we have a array postfix expression that starts on a new line and 1087 // Objective-C is enabled, it is highly likely that the user forgot a 1088 // semicolon after the base expression and that the array postfix-expr is 1089 // actually another message send. In this case, do some look-ahead to see 1090 // if the contents of the square brackets are obviously not a valid 1091 // expression and recover by pretending there is no suffix. 1092 if (getLang().ObjC1 && Tok.isAtStartOfLine() && 1093 isSimpleObjCMessageExpression()) 1094 return move(LHS); 1095 1096 Loc = ConsumeBracket(); 1097 ExprResult Idx(ParseExpression()); 1098 1099 SourceLocation RLoc = Tok.getLocation(); 1100 1101 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 1102 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc, 1103 Idx.take(), RLoc); 1104 } else 1105 LHS = ExprError(); 1106 1107 // Match the ']'. 1108 MatchRHSPunctuation(tok::r_square, Loc); 1109 break; 1110 } 1111 1112 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')' 1113 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>' 1114 // '(' argument-expression-list[opt] ')' 1115 tok::TokenKind OpKind = Tok.getKind(); 1116 InMessageExpressionRAIIObject InMessage(*this, false); 1117 1118 Expr *ExecConfig = 0; 1119 1120 if (OpKind == tok::lesslessless) { 1121 ExprVector ExecConfigExprs(Actions); 1122 CommaLocsTy ExecConfigCommaLocs; 1123 SourceLocation LLLLoc, GGGLoc; 1124 1125 LLLLoc = ConsumeToken(); 1126 1127 if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) { 1128 LHS = ExprError(); 1129 } 1130 1131 if (LHS.isInvalid()) { 1132 SkipUntil(tok::greatergreatergreater); 1133 } else if (Tok.isNot(tok::greatergreatergreater)) { 1134 MatchRHSPunctuation(tok::greatergreatergreater, LLLLoc); 1135 LHS = ExprError(); 1136 } else { 1137 GGGLoc = ConsumeToken(); 1138 } 1139 1140 if (!LHS.isInvalid()) { 1141 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, "")) 1142 LHS = ExprError(); 1143 else 1144 Loc = PrevTokLocation; 1145 } 1146 1147 if (!LHS.isInvalid()) { 1148 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), 1149 LLLLoc, move_arg(ExecConfigExprs), GGGLoc); 1150 if (ECResult.isInvalid()) 1151 LHS = ExprError(); 1152 else 1153 ExecConfig = ECResult.get(); 1154 } 1155 } else { 1156 Loc = ConsumeParen(); 1157 } 1158 1159 ExprVector ArgExprs(Actions); 1160 CommaLocsTy CommaLocs; 1161 1162 if (Tok.is(tok::code_completion)) { 1163 Actions.CodeCompleteCall(getCurScope(), LHS.get(), 0, 0); 1164 ConsumeCodeCompletionToken(); 1165 } 1166 1167 if (OpKind == tok::l_paren || !LHS.isInvalid()) { 1168 if (Tok.isNot(tok::r_paren)) { 1169 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall, 1170 LHS.get())) { 1171 SkipUntil(tok::r_paren); 1172 LHS = ExprError(); 1173 } 1174 } 1175 } 1176 1177 // Match the ')'. 1178 if (LHS.isInvalid()) { 1179 SkipUntil(tok::r_paren); 1180 } else if (Tok.isNot(tok::r_paren)) { 1181 MatchRHSPunctuation(tok::r_paren, Loc); 1182 LHS = ExprError(); 1183 } else { 1184 assert((ArgExprs.size() == 0 || 1185 ArgExprs.size()-1 == CommaLocs.size())&& 1186 "Unexpected number of commas!"); 1187 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc, 1188 move_arg(ArgExprs), Tok.getLocation(), 1189 ExecConfig); 1190 ConsumeParen(); 1191 } 1192 1193 break; 1194 } 1195 case tok::arrow: 1196 case tok::period: { 1197 // postfix-expression: p-e '->' template[opt] id-expression 1198 // postfix-expression: p-e '.' template[opt] id-expression 1199 tok::TokenKind OpKind = Tok.getKind(); 1200 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 1201 1202 CXXScopeSpec SS; 1203 ParsedType ObjectType; 1204 bool MayBePseudoDestructor = false; 1205 if (getLang().CPlusPlus && !LHS.isInvalid()) { 1206 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(), 1207 OpLoc, OpKind, ObjectType, 1208 MayBePseudoDestructor); 1209 if (LHS.isInvalid()) 1210 break; 1211 1212 ParseOptionalCXXScopeSpecifier(SS, ObjectType, false, 1213 &MayBePseudoDestructor); 1214 if (SS.isNotEmpty()) 1215 ObjectType = ParsedType(); 1216 } 1217 1218 if (Tok.is(tok::code_completion)) { 1219 // Code completion for a member access expression. 1220 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(), 1221 OpLoc, OpKind == tok::arrow); 1222 1223 ConsumeCodeCompletionToken(); 1224 } 1225 1226 if (MayBePseudoDestructor && !LHS.isInvalid()) { 1227 LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS, 1228 ObjectType); 1229 break; 1230 } 1231 1232 // Either the action has told is that this cannot be a 1233 // pseudo-destructor expression (based on the type of base 1234 // expression), or we didn't see a '~' in the right place. We 1235 // can still parse a destructor name here, but in that case it 1236 // names a real destructor. 1237 // Allow explicit constructor calls in Microsoft mode. 1238 // FIXME: Add support for explicit call of template constructor. 1239 UnqualifiedId Name; 1240 if (ParseUnqualifiedId(SS, 1241 /*EnteringContext=*/false, 1242 /*AllowDestructorName=*/true, 1243 /*AllowConstructorName=*/ getLang().Microsoft, 1244 ObjectType, 1245 Name)) 1246 LHS = ExprError(); 1247 1248 if (!LHS.isInvalid()) 1249 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc, 1250 OpKind, SS, Name, ObjCImpDecl, 1251 Tok.is(tok::l_paren)); 1252 break; 1253 } 1254 case tok::plusplus: // postfix-expression: postfix-expression '++' 1255 case tok::minusminus: // postfix-expression: postfix-expression '--' 1256 if (!LHS.isInvalid()) { 1257 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(), 1258 Tok.getKind(), LHS.take()); 1259 } 1260 ConsumeToken(); 1261 break; 1262 } 1263 } 1264} 1265 1266/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/ 1267/// vec_step and we are at the start of an expression or a parenthesized 1268/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the 1269/// expression (isCastExpr == false) or the type (isCastExpr == true). 1270/// 1271/// unary-expression: [C99 6.5.3] 1272/// 'sizeof' unary-expression 1273/// 'sizeof' '(' type-name ')' 1274/// [GNU] '__alignof' unary-expression 1275/// [GNU] '__alignof' '(' type-name ')' 1276/// [C++0x] 'alignof' '(' type-id ')' 1277/// 1278/// [GNU] typeof-specifier: 1279/// typeof ( expressions ) 1280/// typeof ( type-name ) 1281/// [GNU/C++] typeof unary-expression 1282/// 1283/// [OpenCL 1.1 6.11.12] vec_step built-in function: 1284/// vec_step ( expressions ) 1285/// vec_step ( type-name ) 1286/// 1287ExprResult 1288Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, 1289 bool &isCastExpr, 1290 ParsedType &CastTy, 1291 SourceRange &CastRange) { 1292 1293 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 1294 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) || 1295 OpTok.is(tok::kw_vec_step)) && 1296 "Not a typeof/sizeof/alignof/vec_step expression!"); 1297 1298 ExprResult Operand; 1299 1300 // If the operand doesn't start with an '(', it must be an expression. 1301 if (Tok.isNot(tok::l_paren)) { 1302 isCastExpr = false; 1303 if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) { 1304 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 1305 return ExprError(); 1306 } 1307 1308 // C++0x [expr.sizeof]p1: 1309 // [...] The operand is either an expression, which is an unevaluated 1310 // operand (Clause 5) [...] 1311 // 1312 // The GNU typeof and alignof extensions also behave as unevaluated 1313 // operands. 1314 EnterExpressionEvaluationContext Unevaluated(Actions, 1315 Sema::Unevaluated); 1316 Operand = ParseCastExpression(true/*isUnaryExpression*/); 1317 } else { 1318 // If it starts with a '(', we know that it is either a parenthesized 1319 // type-name, or it is a unary-expression that starts with a compound 1320 // literal, or starts with a primary-expression that is a parenthesized 1321 // expression. 1322 ParenParseOption ExprType = CastExpr; 1323 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 1324 1325 // C++0x [expr.sizeof]p1: 1326 // [...] The operand is either an expression, which is an unevaluated 1327 // operand (Clause 5) [...] 1328 // 1329 // The GNU typeof and alignof extensions also behave as unevaluated 1330 // operands. 1331 EnterExpressionEvaluationContext Unevaluated(Actions, 1332 Sema::Unevaluated); 1333 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 1334 ParsedType(), CastTy, RParenLoc); 1335 CastRange = SourceRange(LParenLoc, RParenLoc); 1336 1337 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 1338 // a type. 1339 if (ExprType == CastExpr) { 1340 isCastExpr = true; 1341 return ExprEmpty(); 1342 } 1343 1344 if (getLang().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { 1345 // GNU typeof in C requires the expression to be parenthesized. Not so for 1346 // sizeof/alignof or in C++. Therefore, the parenthesized expression is 1347 // the start of a unary-expression, but doesn't include any postfix 1348 // pieces. Parse these now if present. 1349 if (!Operand.isInvalid()) 1350 Operand = ParsePostfixExpressionSuffix(Operand.get()); 1351 } 1352 } 1353 1354 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 1355 isCastExpr = false; 1356 return move(Operand); 1357} 1358 1359 1360/// ParseUnaryExprOrTypeTraitExpression - Parse a sizeof or alignof expression. 1361/// unary-expression: [C99 6.5.3] 1362/// 'sizeof' unary-expression 1363/// 'sizeof' '(' type-name ')' 1364/// [C++0x] 'sizeof' '...' '(' identifier ')' 1365/// [GNU] '__alignof' unary-expression 1366/// [GNU] '__alignof' '(' type-name ')' 1367/// [C++0x] 'alignof' '(' type-id ')' 1368ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { 1369 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) 1370 || Tok.is(tok::kw_alignof) || Tok.is(tok::kw_vec_step)) && 1371 "Not a sizeof/alignof/vec_step expression!"); 1372 Token OpTok = Tok; 1373 ConsumeToken(); 1374 1375 // [C++0x] 'sizeof' '...' '(' identifier ')' 1376 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) { 1377 SourceLocation EllipsisLoc = ConsumeToken(); 1378 SourceLocation LParenLoc, RParenLoc; 1379 IdentifierInfo *Name = 0; 1380 SourceLocation NameLoc; 1381 if (Tok.is(tok::l_paren)) { 1382 LParenLoc = ConsumeParen(); 1383 if (Tok.is(tok::identifier)) { 1384 Name = Tok.getIdentifierInfo(); 1385 NameLoc = ConsumeToken(); 1386 RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1387 if (RParenLoc.isInvalid()) 1388 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1389 } else { 1390 Diag(Tok, diag::err_expected_parameter_pack); 1391 SkipUntil(tok::r_paren); 1392 } 1393 } else if (Tok.is(tok::identifier)) { 1394 Name = Tok.getIdentifierInfo(); 1395 NameLoc = ConsumeToken(); 1396 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc); 1397 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1398 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack) 1399 << Name 1400 << FixItHint::CreateInsertion(LParenLoc, "(") 1401 << FixItHint::CreateInsertion(RParenLoc, ")"); 1402 } else { 1403 Diag(Tok, diag::err_sizeof_parameter_pack); 1404 } 1405 1406 if (!Name) 1407 return ExprError(); 1408 1409 return Actions.ActOnSizeofParameterPackExpr(getCurScope(), 1410 OpTok.getLocation(), 1411 *Name, NameLoc, 1412 RParenLoc); 1413 } 1414 1415 bool isCastExpr; 1416 ParsedType CastTy; 1417 SourceRange CastRange; 1418 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, 1419 isCastExpr, 1420 CastTy, 1421 CastRange); 1422 1423 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf; 1424 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof)) 1425 ExprKind = UETT_AlignOf; 1426 else if (OpTok.is(tok::kw_vec_step)) 1427 ExprKind = UETT_VecStep; 1428 1429 if (isCastExpr) 1430 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 1431 ExprKind, 1432 /*isType=*/true, 1433 CastTy.getAsOpaquePtr(), 1434 CastRange); 1435 1436 // If we get here, the operand to the sizeof/alignof was an expresion. 1437 if (!Operand.isInvalid()) 1438 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 1439 ExprKind, 1440 /*isType=*/false, 1441 Operand.release(), 1442 CastRange); 1443 return move(Operand); 1444} 1445 1446/// ParseBuiltinPrimaryExpression 1447/// 1448/// primary-expression: [C99 6.5.1] 1449/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1450/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1451/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1452/// assign-expr ')' 1453/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1454/// 1455/// [GNU] offsetof-member-designator: 1456/// [GNU] identifier 1457/// [GNU] offsetof-member-designator '.' identifier 1458/// [GNU] offsetof-member-designator '[' expression ']' 1459/// 1460ExprResult Parser::ParseBuiltinPrimaryExpression() { 1461 ExprResult Res; 1462 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1463 1464 tok::TokenKind T = Tok.getKind(); 1465 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1466 1467 // All of these start with an open paren. 1468 if (Tok.isNot(tok::l_paren)) 1469 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1470 << BuiltinII); 1471 1472 SourceLocation LParenLoc = ConsumeParen(); 1473 // TODO: Build AST. 1474 1475 switch (T) { 1476 default: assert(0 && "Not a builtin primary expression!"); 1477 case tok::kw___builtin_va_arg: { 1478 ExprResult Expr(ParseAssignmentExpression()); 1479 1480 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1481 Expr = ExprError(); 1482 1483 TypeResult Ty = ParseTypeName(); 1484 1485 if (Tok.isNot(tok::r_paren)) { 1486 Diag(Tok, diag::err_expected_rparen); 1487 Expr = ExprError(); 1488 } 1489 1490 if (Expr.isInvalid() || Ty.isInvalid()) 1491 Res = ExprError(); 1492 else 1493 Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen()); 1494 break; 1495 } 1496 case tok::kw___builtin_offsetof: { 1497 SourceLocation TypeLoc = Tok.getLocation(); 1498 TypeResult Ty = ParseTypeName(); 1499 if (Ty.isInvalid()) { 1500 SkipUntil(tok::r_paren); 1501 return ExprError(); 1502 } 1503 1504 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1505 return ExprError(); 1506 1507 // We must have at least one identifier here. 1508 if (Tok.isNot(tok::identifier)) { 1509 Diag(Tok, diag::err_expected_ident); 1510 SkipUntil(tok::r_paren); 1511 return ExprError(); 1512 } 1513 1514 // Keep track of the various subcomponents we see. 1515 llvm::SmallVector<Sema::OffsetOfComponent, 4> Comps; 1516 1517 Comps.push_back(Sema::OffsetOfComponent()); 1518 Comps.back().isBrackets = false; 1519 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1520 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1521 1522 // FIXME: This loop leaks the index expressions on error. 1523 while (1) { 1524 if (Tok.is(tok::period)) { 1525 // offsetof-member-designator: offsetof-member-designator '.' identifier 1526 Comps.push_back(Sema::OffsetOfComponent()); 1527 Comps.back().isBrackets = false; 1528 Comps.back().LocStart = ConsumeToken(); 1529 1530 if (Tok.isNot(tok::identifier)) { 1531 Diag(Tok, diag::err_expected_ident); 1532 SkipUntil(tok::r_paren); 1533 return ExprError(); 1534 } 1535 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1536 Comps.back().LocEnd = ConsumeToken(); 1537 1538 } else if (Tok.is(tok::l_square)) { 1539 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1540 Comps.push_back(Sema::OffsetOfComponent()); 1541 Comps.back().isBrackets = true; 1542 Comps.back().LocStart = ConsumeBracket(); 1543 Res = ParseExpression(); 1544 if (Res.isInvalid()) { 1545 SkipUntil(tok::r_paren); 1546 return move(Res); 1547 } 1548 Comps.back().U.E = Res.release(); 1549 1550 Comps.back().LocEnd = 1551 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart); 1552 } else { 1553 if (Tok.isNot(tok::r_paren)) { 1554 MatchRHSPunctuation(tok::r_paren, LParenLoc); 1555 Res = ExprError(); 1556 } else if (Ty.isInvalid()) { 1557 Res = ExprError(); 1558 } else { 1559 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc, 1560 Ty.get(), &Comps[0], 1561 Comps.size(), ConsumeParen()); 1562 } 1563 break; 1564 } 1565 } 1566 break; 1567 } 1568 case tok::kw___builtin_choose_expr: { 1569 ExprResult Cond(ParseAssignmentExpression()); 1570 if (Cond.isInvalid()) { 1571 SkipUntil(tok::r_paren); 1572 return move(Cond); 1573 } 1574 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1575 return ExprError(); 1576 1577 ExprResult Expr1(ParseAssignmentExpression()); 1578 if (Expr1.isInvalid()) { 1579 SkipUntil(tok::r_paren); 1580 return move(Expr1); 1581 } 1582 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1583 return ExprError(); 1584 1585 ExprResult Expr2(ParseAssignmentExpression()); 1586 if (Expr2.isInvalid()) { 1587 SkipUntil(tok::r_paren); 1588 return move(Expr2); 1589 } 1590 if (Tok.isNot(tok::r_paren)) { 1591 Diag(Tok, diag::err_expected_rparen); 1592 return ExprError(); 1593 } 1594 Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(), 1595 Expr2.take(), ConsumeParen()); 1596 break; 1597 } 1598 } 1599 1600 if (Res.isInvalid()) 1601 return ExprError(); 1602 1603 // These can be followed by postfix-expr pieces because they are 1604 // primary-expressions. 1605 return ParsePostfixExpressionSuffix(Res.take()); 1606} 1607 1608/// ParseParenExpression - This parses the unit that starts with a '(' token, 1609/// based on what is allowed by ExprType. The actual thing parsed is returned 1610/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1611/// not the parsed cast-expression. 1612/// 1613/// primary-expression: [C99 6.5.1] 1614/// '(' expression ')' 1615/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1616/// postfix-expression: [C99 6.5.2] 1617/// '(' type-name ')' '{' initializer-list '}' 1618/// '(' type-name ')' '{' initializer-list ',' '}' 1619/// cast-expression: [C99 6.5.4] 1620/// '(' type-name ')' cast-expression 1621/// 1622ExprResult 1623Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1624 ParsedType TypeOfCast, ParsedType &CastTy, 1625 SourceLocation &RParenLoc) { 1626 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1627 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 1628 SourceLocation OpenLoc = ConsumeParen(); 1629 ExprResult Result(true); 1630 bool isAmbiguousTypeId; 1631 CastTy = ParsedType(); 1632 1633 if (Tok.is(tok::code_completion)) { 1634 Actions.CodeCompleteOrdinaryName(getCurScope(), 1635 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression 1636 : Sema::PCC_Expression); 1637 ConsumeCodeCompletionToken(); 1638 return ExprError(); 1639 } 1640 1641 // None of these cases should fall through with an invalid Result 1642 // unless they've already reported an error. 1643 1644 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 1645 Diag(Tok, diag::ext_gnu_statement_expr); 1646 ParsedAttributes attrs(AttrFactory); 1647 StmtResult Stmt(ParseCompoundStatement(attrs, true)); 1648 ExprType = CompoundStmt; 1649 1650 // If the substmt parsed correctly, build the AST node. 1651 if (!Stmt.isInvalid()) 1652 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation()); 1653 1654 } else if (ExprType >= CompoundLiteral && 1655 isTypeIdInParens(isAmbiguousTypeId)) { 1656 1657 // Otherwise, this is a compound literal expression or cast expression. 1658 1659 // In C++, if the type-id is ambiguous we disambiguate based on context. 1660 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 1661 // in which case we should treat it as type-id. 1662 // if stopIfCastExpr is false, we need to determine the context past the 1663 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 1664 if (isAmbiguousTypeId && !stopIfCastExpr) 1665 return ParseCXXAmbiguousParenExpression(ExprType, CastTy, 1666 OpenLoc, RParenLoc); 1667 1668 TypeResult Ty; 1669 1670 { 1671 InMessageExpressionRAIIObject InMessage(*this, false); 1672 Ty = ParseTypeName(); 1673 } 1674 1675 // If our type is followed by an identifier and either ':' or ']', then 1676 // this is probably an Objective-C message send where the leading '[' is 1677 // missing. Recover as if that were the case. 1678 if (!Ty.isInvalid() && Tok.is(tok::identifier) && !InMessageExpression && 1679 getLang().ObjC1 && !Ty.get().get().isNull() && 1680 (NextToken().is(tok::colon) || NextToken().is(tok::r_square)) && 1681 Ty.get().get()->isObjCObjectOrInterfaceType()) { 1682 Result = ParseObjCMessageExpressionBody(SourceLocation(), 1683 SourceLocation(), 1684 Ty.get(), 0); 1685 } else { 1686 // Match the ')'. 1687 if (Tok.is(tok::r_paren)) 1688 RParenLoc = ConsumeParen(); 1689 else 1690 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1691 1692 if (Tok.is(tok::l_brace)) { 1693 ExprType = CompoundLiteral; 1694 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 1695 } 1696 1697 if (ExprType == CastExpr) { 1698 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 1699 1700 if (Ty.isInvalid()) 1701 return ExprError(); 1702 1703 CastTy = Ty.get(); 1704 1705 // Note that this doesn't parse the subsequent cast-expression, it just 1706 // returns the parsed type to the callee. 1707 if (stopIfCastExpr) 1708 return ExprResult(); 1709 1710 // Reject the cast of super idiom in ObjC. 1711 if (Tok.is(tok::identifier) && getLang().ObjC1 && 1712 Tok.getIdentifierInfo() == Ident_super && 1713 getCurScope()->isInObjcMethodScope() && 1714 GetLookAheadToken(1).isNot(tok::period)) { 1715 Diag(Tok.getLocation(), diag::err_illegal_super_cast) 1716 << SourceRange(OpenLoc, RParenLoc); 1717 return ExprError(); 1718 } 1719 1720 // Parse the cast-expression that follows it next. 1721 // TODO: For cast expression with CastTy. 1722 Result = ParseCastExpression(false, false, CastTy); 1723 if (!Result.isInvalid()) 1724 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, CastTy, 1725 RParenLoc, Result.take()); 1726 return move(Result); 1727 } 1728 1729 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 1730 return ExprError(); 1731 } 1732 } else if (TypeOfCast) { 1733 // Parse the expression-list. 1734 InMessageExpressionRAIIObject InMessage(*this, false); 1735 1736 ExprVector ArgExprs(Actions); 1737 CommaLocsTy CommaLocs; 1738 1739 if (!ParseExpressionList(ArgExprs, CommaLocs)) { 1740 ExprType = SimpleExpr; 1741 Result = Actions.ActOnParenOrParenListExpr(OpenLoc, Tok.getLocation(), 1742 move_arg(ArgExprs), TypeOfCast); 1743 } 1744 } else { 1745 InMessageExpressionRAIIObject InMessage(*this, false); 1746 1747 Result = ParseExpression(); 1748 ExprType = SimpleExpr; 1749 1750 // Don't build a paren expression unless we actually match a ')'. 1751 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 1752 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take()); 1753 } 1754 1755 // Match the ')'. 1756 if (Result.isInvalid()) { 1757 SkipUntil(tok::r_paren); 1758 return ExprError(); 1759 } 1760 1761 if (Tok.is(tok::r_paren)) 1762 RParenLoc = ConsumeParen(); 1763 else 1764 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1765 1766 return move(Result); 1767} 1768 1769/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 1770/// and we are at the left brace. 1771/// 1772/// postfix-expression: [C99 6.5.2] 1773/// '(' type-name ')' '{' initializer-list '}' 1774/// '(' type-name ')' '{' initializer-list ',' '}' 1775/// 1776ExprResult 1777Parser::ParseCompoundLiteralExpression(ParsedType Ty, 1778 SourceLocation LParenLoc, 1779 SourceLocation RParenLoc) { 1780 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 1781 if (!getLang().C99) // Compound literals don't exist in C90. 1782 Diag(LParenLoc, diag::ext_c99_compound_literal); 1783 ExprResult Result = ParseInitializer(); 1784 if (!Result.isInvalid() && Ty) 1785 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take()); 1786 return move(Result); 1787} 1788 1789/// ParseStringLiteralExpression - This handles the various token types that 1790/// form string literals, and also handles string concatenation [C99 5.1.1.2, 1791/// translation phase #6]. 1792/// 1793/// primary-expression: [C99 6.5.1] 1794/// string-literal 1795ExprResult Parser::ParseStringLiteralExpression() { 1796 assert(isTokenStringLiteral() && "Not a string literal!"); 1797 1798 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 1799 // considered to be strings for concatenation purposes. 1800 llvm::SmallVector<Token, 4> StringToks; 1801 1802 do { 1803 StringToks.push_back(Tok); 1804 ConsumeStringToken(); 1805 } while (isTokenStringLiteral()); 1806 1807 // Pass the set of string tokens, ready for concatenation, to the actions. 1808 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size()); 1809} 1810 1811/// ParseGenericSelectionExpression - Parse a C1X generic-selection 1812/// [C1X 6.5.1.1]. 1813/// 1814/// generic-selection: 1815/// _Generic ( assignment-expression , generic-assoc-list ) 1816/// generic-assoc-list: 1817/// generic-association 1818/// generic-assoc-list , generic-association 1819/// generic-association: 1820/// type-name : assignment-expression 1821/// default : assignment-expression 1822ExprResult Parser::ParseGenericSelectionExpression() { 1823 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected"); 1824 SourceLocation KeyLoc = ConsumeToken(); 1825 1826 if (!getLang().C1X) 1827 Diag(KeyLoc, diag::ext_c1x_generic_selection); 1828 1829 SourceLocation LParenLoc = Tok.getLocation(); 1830 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, "")) 1831 return ExprError(); 1832 1833 ExprResult ControllingExpr; 1834 { 1835 // C1X 6.5.1.1p3 "The controlling expression of a generic selection is 1836 // not evaluated." 1837 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 1838 ControllingExpr = ParseAssignmentExpression(); 1839 if (ControllingExpr.isInvalid()) { 1840 SkipUntil(tok::r_paren); 1841 return ExprError(); 1842 } 1843 } 1844 1845 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "")) { 1846 SkipUntil(tok::r_paren); 1847 return ExprError(); 1848 } 1849 1850 SourceLocation DefaultLoc; 1851 TypeVector Types(Actions); 1852 ExprVector Exprs(Actions); 1853 while (1) { 1854 ParsedType Ty; 1855 if (Tok.is(tok::kw_default)) { 1856 // C1X 6.5.1.1p2 "A generic selection shall have no more than one default 1857 // generic association." 1858 if (!DefaultLoc.isInvalid()) { 1859 Diag(Tok, diag::err_duplicate_default_assoc); 1860 Diag(DefaultLoc, diag::note_previous_default_assoc); 1861 SkipUntil(tok::r_paren); 1862 return ExprError(); 1863 } 1864 DefaultLoc = ConsumeToken(); 1865 Ty = ParsedType(); 1866 } else { 1867 ColonProtectionRAIIObject X(*this); 1868 TypeResult TR = ParseTypeName(); 1869 if (TR.isInvalid()) { 1870 SkipUntil(tok::r_paren); 1871 return ExprError(); 1872 } 1873 Ty = TR.release(); 1874 } 1875 Types.push_back(Ty); 1876 1877 if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "")) { 1878 SkipUntil(tok::r_paren); 1879 return ExprError(); 1880 } 1881 1882 // FIXME: These expressions should be parsed in a potentially potentially 1883 // evaluated context. 1884 ExprResult ER(ParseAssignmentExpression()); 1885 if (ER.isInvalid()) { 1886 SkipUntil(tok::r_paren); 1887 return ExprError(); 1888 } 1889 Exprs.push_back(ER.release()); 1890 1891 if (Tok.isNot(tok::comma)) 1892 break; 1893 ConsumeToken(); 1894 } 1895 1896 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1897 if (RParenLoc.isInvalid()) 1898 return ExprError(); 1899 1900 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1901 ControllingExpr.release(), 1902 move_arg(Types), move_arg(Exprs)); 1903} 1904 1905/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 1906/// 1907/// argument-expression-list: 1908/// assignment-expression 1909/// argument-expression-list , assignment-expression 1910/// 1911/// [C++] expression-list: 1912/// [C++] assignment-expression ...[opt] 1913/// [C++] expression-list , assignment-expression ...[opt] 1914/// 1915bool Parser::ParseExpressionList(llvm::SmallVectorImpl<Expr*> &Exprs, 1916 llvm::SmallVectorImpl<SourceLocation> &CommaLocs, 1917 void (Sema::*Completer)(Scope *S, 1918 Expr *Data, 1919 Expr **Args, 1920 unsigned NumArgs), 1921 Expr *Data) { 1922 while (1) { 1923 if (Tok.is(tok::code_completion)) { 1924 if (Completer) 1925 (Actions.*Completer)(getCurScope(), Data, Exprs.data(), Exprs.size()); 1926 else 1927 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 1928 ConsumeCodeCompletionToken(); 1929 } 1930 1931 ExprResult Expr(ParseAssignmentExpression()); 1932 if (Tok.is(tok::ellipsis)) 1933 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); 1934 if (Expr.isInvalid()) 1935 return true; 1936 1937 Exprs.push_back(Expr.release()); 1938 1939 if (Tok.isNot(tok::comma)) 1940 return false; 1941 // Move to the next argument, remember where the comma was. 1942 CommaLocs.push_back(ConsumeToken()); 1943 } 1944} 1945 1946/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 1947/// 1948/// [clang] block-id: 1949/// [clang] specifier-qualifier-list block-declarator 1950/// 1951void Parser::ParseBlockId() { 1952 if (Tok.is(tok::code_completion)) { 1953 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); 1954 ConsumeCodeCompletionToken(); 1955 } 1956 1957 // Parse the specifier-qualifier-list piece. 1958 DeclSpec DS(AttrFactory); 1959 ParseSpecifierQualifierList(DS); 1960 1961 // Parse the block-declarator. 1962 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 1963 ParseDeclarator(DeclaratorInfo); 1964 1965 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 1966 DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation()); 1967 1968 MaybeParseGNUAttributes(DeclaratorInfo); 1969 1970 // Inform sema that we are starting a block. 1971 Actions.ActOnBlockArguments(DeclaratorInfo, getCurScope()); 1972} 1973 1974/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 1975/// like ^(int x){ return x+1; } 1976/// 1977/// block-literal: 1978/// [clang] '^' block-args[opt] compound-statement 1979/// [clang] '^' block-id compound-statement 1980/// [clang] block-args: 1981/// [clang] '(' parameter-list ')' 1982/// 1983ExprResult Parser::ParseBlockLiteralExpression() { 1984 assert(Tok.is(tok::caret) && "block literal starts with ^"); 1985 SourceLocation CaretLoc = ConsumeToken(); 1986 1987 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 1988 "block literal parsing"); 1989 1990 // Enter a scope to hold everything within the block. This includes the 1991 // argument decls, decls within the compound expression, etc. This also 1992 // allows determining whether a variable reference inside the block is 1993 // within or outside of the block. 1994 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 1995 Scope::BreakScope | Scope::ContinueScope | 1996 Scope::DeclScope); 1997 1998 // Inform sema that we are starting a block. 1999 Actions.ActOnBlockStart(CaretLoc, getCurScope()); 2000 2001 // Parse the return type if present. 2002 DeclSpec DS(AttrFactory); 2003 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 2004 // FIXME: Since the return type isn't actually parsed, it can't be used to 2005 // fill ParamInfo with an initial valid range, so do it manually. 2006 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 2007 2008 // If this block has arguments, parse them. There is no ambiguity here with 2009 // the expression case, because the expression case requires a parameter list. 2010 if (Tok.is(tok::l_paren)) { 2011 ParseParenDeclarator(ParamInfo); 2012 // Parse the pieces after the identifier as if we had "int(...)". 2013 // SetIdentifier sets the source range end, but in this case we're past 2014 // that location. 2015 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 2016 ParamInfo.SetIdentifier(0, CaretLoc); 2017 ParamInfo.SetRangeEnd(Tmp); 2018 if (ParamInfo.isInvalidType()) { 2019 // If there was an error parsing the arguments, they may have 2020 // tried to use ^(x+y) which requires an argument list. Just 2021 // skip the whole block literal. 2022 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2023 return ExprError(); 2024 } 2025 2026 MaybeParseGNUAttributes(ParamInfo); 2027 2028 // Inform sema that we are starting a block. 2029 Actions.ActOnBlockArguments(ParamInfo, getCurScope()); 2030 } else if (!Tok.is(tok::l_brace)) { 2031 ParseBlockId(); 2032 } else { 2033 // Otherwise, pretend we saw (void). 2034 ParsedAttributes attrs(AttrFactory); 2035 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, 2036 SourceLocation(), 2037 0, 0, 0, 2038 true, SourceLocation(), 2039 EST_None, 2040 SourceLocation(), 2041 0, 0, 0, 0, 2042 CaretLoc, CaretLoc, 2043 ParamInfo), 2044 attrs, CaretLoc); 2045 2046 MaybeParseGNUAttributes(ParamInfo); 2047 2048 // Inform sema that we are starting a block. 2049 Actions.ActOnBlockArguments(ParamInfo, getCurScope()); 2050 } 2051 2052 2053 ExprResult Result(true); 2054 if (!Tok.is(tok::l_brace)) { 2055 // Saw something like: ^expr 2056 Diag(Tok, diag::err_expected_expression); 2057 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2058 return ExprError(); 2059 } 2060 2061 StmtResult Stmt(ParseCompoundStatementBody()); 2062 BlockScope.Exit(); 2063 if (!Stmt.isInvalid()) 2064 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope()); 2065 else 2066 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2067 return move(Result); 2068} 2069