ParseExpr.cpp revision b13621d08e20ac7aa550e05896de8a57ee99c1e8
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/// \file 11/// \brief Provides the Expression parsing implementation. 12/// 13/// Expressions in C99 basically consist of a bunch of binary operators with 14/// unary operators and other random stuff at the leaves. 15/// 16/// In the C99 grammar, these unary operators bind tightest and are represented 17/// as the 'cast-expression' production. Everything else is either a binary 18/// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are 19/// handled by ParseCastExpression, the higher level pieces are handled by 20/// ParseBinaryExpression. 21/// 22//===----------------------------------------------------------------------===// 23 24#include "clang/Parse/Parser.h" 25#include "RAIIObjectsForParser.h" 26#include "clang/Basic/PrettyStackTrace.h" 27#include "clang/Sema/DeclSpec.h" 28#include "clang/Sema/ParsedTemplate.h" 29#include "clang/Sema/Scope.h" 30#include "clang/Sema/TypoCorrection.h" 31#include "llvm/ADT/SmallString.h" 32#include "llvm/ADT/SmallVector.h" 33using namespace clang; 34 35/// \brief Return the precedence of the specified binary operator token. 36static prec::Level getBinOpPrecedence(tok::TokenKind Kind, 37 bool GreaterThanIsOperator, 38 bool CPlusPlus0x) { 39 switch (Kind) { 40 case tok::greater: 41 // C++ [temp.names]p3: 42 // [...] When parsing a template-argument-list, the first 43 // non-nested > is taken as the ending delimiter rather than a 44 // greater-than operator. [...] 45 if (GreaterThanIsOperator) 46 return prec::Relational; 47 return prec::Unknown; 48 49 case tok::greatergreater: 50 // C++0x [temp.names]p3: 51 // 52 // [...] Similarly, the first non-nested >> is treated as two 53 // consecutive but distinct > tokens, the first of which is 54 // taken as the end of the template-argument-list and completes 55 // the template-id. [...] 56 if (GreaterThanIsOperator || !CPlusPlus0x) 57 return prec::Shift; 58 return prec::Unknown; 59 60 default: return prec::Unknown; 61 case tok::comma: return prec::Comma; 62 case tok::equal: 63 case tok::starequal: 64 case tok::slashequal: 65 case tok::percentequal: 66 case tok::plusequal: 67 case tok::minusequal: 68 case tok::lesslessequal: 69 case tok::greatergreaterequal: 70 case tok::ampequal: 71 case tok::caretequal: 72 case tok::pipeequal: return prec::Assignment; 73 case tok::question: return prec::Conditional; 74 case tok::pipepipe: return prec::LogicalOr; 75 case tok::ampamp: return prec::LogicalAnd; 76 case tok::pipe: return prec::InclusiveOr; 77 case tok::caret: return prec::ExclusiveOr; 78 case tok::amp: return prec::And; 79 case tok::exclaimequal: 80 case tok::equalequal: return prec::Equality; 81 case tok::lessequal: 82 case tok::less: 83 case tok::greaterequal: return prec::Relational; 84 case tok::lessless: return prec::Shift; 85 case tok::plus: 86 case tok::minus: return prec::Additive; 87 case tok::percent: 88 case tok::slash: 89 case tok::star: return prec::Multiplicative; 90 case tok::periodstar: 91 case tok::arrowstar: return prec::PointerToMember; 92 } 93} 94 95 96/// \brief Simple precedence-based parser for binary/ternary operators. 97/// 98/// Note: we diverge from the C99 grammar when parsing the assignment-expression 99/// production. C99 specifies that the LHS of an assignment operator should be 100/// parsed as a unary-expression, but consistency dictates that it be a 101/// conditional-expession. In practice, the important thing here is that the 102/// LHS of an assignment has to be an l-value, which productions between 103/// unary-expression and conditional-expression don't produce. Because we want 104/// consistency, we parse the LHS as a conditional-expression, then check for 105/// l-value-ness in semantic analysis stages. 106/// 107/// \verbatim 108/// pm-expression: [C++ 5.5] 109/// cast-expression 110/// pm-expression '.*' cast-expression 111/// pm-expression '->*' cast-expression 112/// 113/// multiplicative-expression: [C99 6.5.5] 114/// Note: in C++, apply pm-expression instead of cast-expression 115/// cast-expression 116/// multiplicative-expression '*' cast-expression 117/// multiplicative-expression '/' cast-expression 118/// multiplicative-expression '%' cast-expression 119/// 120/// additive-expression: [C99 6.5.6] 121/// multiplicative-expression 122/// additive-expression '+' multiplicative-expression 123/// additive-expression '-' multiplicative-expression 124/// 125/// shift-expression: [C99 6.5.7] 126/// additive-expression 127/// shift-expression '<<' additive-expression 128/// shift-expression '>>' additive-expression 129/// 130/// relational-expression: [C99 6.5.8] 131/// shift-expression 132/// relational-expression '<' shift-expression 133/// relational-expression '>' shift-expression 134/// relational-expression '<=' shift-expression 135/// relational-expression '>=' shift-expression 136/// 137/// equality-expression: [C99 6.5.9] 138/// relational-expression 139/// equality-expression '==' relational-expression 140/// equality-expression '!=' relational-expression 141/// 142/// AND-expression: [C99 6.5.10] 143/// equality-expression 144/// AND-expression '&' equality-expression 145/// 146/// exclusive-OR-expression: [C99 6.5.11] 147/// AND-expression 148/// exclusive-OR-expression '^' AND-expression 149/// 150/// inclusive-OR-expression: [C99 6.5.12] 151/// exclusive-OR-expression 152/// inclusive-OR-expression '|' exclusive-OR-expression 153/// 154/// logical-AND-expression: [C99 6.5.13] 155/// inclusive-OR-expression 156/// logical-AND-expression '&&' inclusive-OR-expression 157/// 158/// logical-OR-expression: [C99 6.5.14] 159/// logical-AND-expression 160/// logical-OR-expression '||' logical-AND-expression 161/// 162/// conditional-expression: [C99 6.5.15] 163/// logical-OR-expression 164/// logical-OR-expression '?' expression ':' conditional-expression 165/// [GNU] logical-OR-expression '?' ':' conditional-expression 166/// [C++] the third operand is an assignment-expression 167/// 168/// assignment-expression: [C99 6.5.16] 169/// conditional-expression 170/// unary-expression assignment-operator assignment-expression 171/// [C++] throw-expression [C++ 15] 172/// 173/// assignment-operator: one of 174/// = *= /= %= += -= <<= >>= &= ^= |= 175/// 176/// expression: [C99 6.5.17] 177/// assignment-expression ...[opt] 178/// expression ',' assignment-expression ...[opt] 179/// \endverbatim 180ExprResult Parser::ParseExpression(TypeCastState isTypeCast) { 181 ExprResult LHS(ParseAssignmentExpression(isTypeCast)); 182 return ParseRHSOfBinaryExpression(LHS, prec::Comma); 183} 184 185/// This routine is called when the '@' is seen and consumed. 186/// Current token is an Identifier and is not a 'try'. This 187/// routine is necessary to disambiguate \@try-statement from, 188/// for example, \@encode-expression. 189/// 190ExprResult 191Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) { 192 ExprResult LHS(ParseObjCAtExpression(AtLoc)); 193 return ParseRHSOfBinaryExpression(LHS, prec::Comma); 194} 195 196/// This routine is called when a leading '__extension__' is seen and 197/// consumed. This is necessary because the token gets consumed in the 198/// process of disambiguating between an expression and a declaration. 199ExprResult 200Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) { 201 ExprResult LHS(true); 202 { 203 // Silence extension warnings in the sub-expression 204 ExtensionRAIIObject O(Diags); 205 206 LHS = ParseCastExpression(false); 207 } 208 209 if (!LHS.isInvalid()) 210 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__, 211 LHS.take()); 212 213 return ParseRHSOfBinaryExpression(LHS, prec::Comma); 214} 215 216/// \brief Parse an expr that doesn't include (top-level) commas. 217ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) { 218 if (Tok.is(tok::code_completion)) { 219 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 220 cutOffParsing(); 221 return ExprError(); 222 } 223 224 if (Tok.is(tok::kw_throw)) 225 return ParseThrowExpression(); 226 227 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false, 228 /*isAddressOfOperand=*/false, 229 isTypeCast); 230 return ParseRHSOfBinaryExpression(LHS, prec::Assignment); 231} 232 233/// \brief Parse an assignment expression where part of an Objective-C message 234/// send has already been parsed. 235/// 236/// In this case \p LBracLoc indicates the location of the '[' of the message 237/// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating 238/// the receiver of the message. 239/// 240/// Since this handles full assignment-expression's, it handles postfix 241/// expressions and other binary operators for these expressions as well. 242ExprResult 243Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc, 244 SourceLocation SuperLoc, 245 ParsedType ReceiverType, 246 Expr *ReceiverExpr) { 247 ExprResult R 248 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc, 249 ReceiverType, ReceiverExpr); 250 R = ParsePostfixExpressionSuffix(R); 251 return ParseRHSOfBinaryExpression(R, prec::Assignment); 252} 253 254 255ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) { 256 // C++03 [basic.def.odr]p2: 257 // An expression is potentially evaluated unless it appears where an 258 // integral constant expression is required (see 5.19) [...]. 259 // C++98 and C++11 have no such rule, but this is only a defect in C++98. 260 EnterExpressionEvaluationContext Unevaluated(Actions, 261 Sema::ConstantEvaluated); 262 263 ExprResult LHS(ParseCastExpression(false, false, isTypeCast)); 264 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 265 return Actions.ActOnConstantExpression(Res); 266} 267 268bool Parser::isNotExpressionStart() { 269 tok::TokenKind K = Tok.getKind(); 270 if (K == tok::l_brace || K == tok::r_brace || 271 K == tok::kw_for || K == tok::kw_while || 272 K == tok::kw_if || K == tok::kw_else || 273 K == tok::kw_goto || K == tok::kw_try) 274 return true; 275 // If this is a decl-specifier, we can't be at the start of an expression. 276 return isKnownToBeDeclarationSpecifier(); 277} 278 279/// \brief Parse a binary expression that starts with \p LHS and has a 280/// precedence of at least \p MinPrec. 281ExprResult 282Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) { 283 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(), 284 GreaterThanIsOperator, 285 getLangOpts().CPlusPlus0x); 286 SourceLocation ColonLoc; 287 288 while (1) { 289 // If this token has a lower precedence than we are allowed to parse (e.g. 290 // because we are called recursively, or because the token is not a binop), 291 // then we are done! 292 if (NextTokPrec < MinPrec) 293 return LHS; 294 295 // Consume the operator, saving the operator token for error reporting. 296 Token OpToken = Tok; 297 ConsumeToken(); 298 299 // Bail out when encountering a comma followed by a token which can't 300 // possibly be the start of an expression. For instance: 301 // int f() { return 1, } 302 // We can't do this before consuming the comma, because 303 // isNotExpressionStart() looks at the token stream. 304 if (OpToken.is(tok::comma) && isNotExpressionStart()) { 305 PP.EnterToken(Tok); 306 Tok = OpToken; 307 return LHS; 308 } 309 310 // Special case handling for the ternary operator. 311 ExprResult TernaryMiddle(true); 312 if (NextTokPrec == prec::Conditional) { 313 if (Tok.isNot(tok::colon)) { 314 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 315 ColonProtectionRAIIObject X(*this); 316 317 // Handle this production specially: 318 // logical-OR-expression '?' expression ':' conditional-expression 319 // In particular, the RHS of the '?' is 'expression', not 320 // 'logical-OR-expression' as we might expect. 321 TernaryMiddle = ParseExpression(); 322 if (TernaryMiddle.isInvalid()) { 323 LHS = ExprError(); 324 TernaryMiddle = 0; 325 } 326 } else { 327 // Special case handling of "X ? Y : Z" where Y is empty: 328 // logical-OR-expression '?' ':' conditional-expression [GNU] 329 TernaryMiddle = 0; 330 Diag(Tok, diag::ext_gnu_conditional_expr); 331 } 332 333 if (Tok.is(tok::colon)) { 334 // Eat the colon. 335 ColonLoc = ConsumeToken(); 336 } else { 337 // Otherwise, we're missing a ':'. Assume that this was a typo that 338 // the user forgot. If we're not in a macro expansion, we can suggest 339 // a fixit hint. If there were two spaces before the current token, 340 // suggest inserting the colon in between them, otherwise insert ": ". 341 SourceLocation FILoc = Tok.getLocation(); 342 const char *FIText = ": "; 343 const SourceManager &SM = PP.getSourceManager(); 344 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) { 345 assert(FILoc.isFileID()); 346 bool IsInvalid = false; 347 const char *SourcePtr = 348 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid); 349 if (!IsInvalid && *SourcePtr == ' ') { 350 SourcePtr = 351 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid); 352 if (!IsInvalid && *SourcePtr == ' ') { 353 FILoc = FILoc.getLocWithOffset(-1); 354 FIText = ":"; 355 } 356 } 357 } 358 359 Diag(Tok, diag::err_expected_colon) 360 << FixItHint::CreateInsertion(FILoc, FIText); 361 Diag(OpToken, diag::note_matching) << "?"; 362 ColonLoc = Tok.getLocation(); 363 } 364 } 365 366 // Code completion for the right-hand side of an assignment expression 367 // goes through a special hook that takes the left-hand side into account. 368 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) { 369 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get()); 370 cutOffParsing(); 371 return ExprError(); 372 } 373 374 // Parse another leaf here for the RHS of the operator. 375 // ParseCastExpression works here because all RHS expressions in C have it 376 // as a prefix, at least. However, in C++, an assignment-expression could 377 // be a throw-expression, which is not a valid cast-expression. 378 // Therefore we need some special-casing here. 379 // Also note that the third operand of the conditional operator is 380 // an assignment-expression in C++, and in C++11, we can have a 381 // braced-init-list on the RHS of an assignment. For better diagnostics, 382 // parse as if we were allowed braced-init-lists everywhere, and check that 383 // they only appear on the RHS of assignments later. 384 ExprResult RHS; 385 bool RHSIsInitList = false; 386 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 387 RHS = ParseBraceInitializer(); 388 RHSIsInitList = true; 389 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional) 390 RHS = ParseAssignmentExpression(); 391 else 392 RHS = ParseCastExpression(false); 393 394 if (RHS.isInvalid()) 395 LHS = ExprError(); 396 397 // Remember the precedence of this operator and get the precedence of the 398 // operator immediately to the right of the RHS. 399 prec::Level ThisPrec = NextTokPrec; 400 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, 401 getLangOpts().CPlusPlus0x); 402 403 // Assignment and conditional expressions are right-associative. 404 bool isRightAssoc = ThisPrec == prec::Conditional || 405 ThisPrec == prec::Assignment; 406 407 // Get the precedence of the operator to the right of the RHS. If it binds 408 // more tightly with RHS than we do, evaluate it completely first. 409 if (ThisPrec < NextTokPrec || 410 (ThisPrec == NextTokPrec && isRightAssoc)) { 411 if (!RHS.isInvalid() && RHSIsInitList) { 412 Diag(Tok, diag::err_init_list_bin_op) 413 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get()); 414 RHS = ExprError(); 415 } 416 // If this is left-associative, only parse things on the RHS that bind 417 // more tightly than the current operator. If it is left-associative, it 418 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as 419 // A=(B=(C=D)), where each paren is a level of recursion here. 420 // The function takes ownership of the RHS. 421 RHS = ParseRHSOfBinaryExpression(RHS, 422 static_cast<prec::Level>(ThisPrec + !isRightAssoc)); 423 RHSIsInitList = false; 424 425 if (RHS.isInvalid()) 426 LHS = ExprError(); 427 428 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, 429 getLangOpts().CPlusPlus0x); 430 } 431 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!"); 432 433 if (!RHS.isInvalid() && RHSIsInitList) { 434 if (ThisPrec == prec::Assignment) { 435 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists) 436 << Actions.getExprRange(RHS.get()); 437 } else { 438 Diag(OpToken, diag::err_init_list_bin_op) 439 << /*RHS*/1 << PP.getSpelling(OpToken) 440 << Actions.getExprRange(RHS.get()); 441 LHS = ExprError(); 442 } 443 } 444 445 if (!LHS.isInvalid()) { 446 // Combine the LHS and RHS into the LHS (e.g. build AST). 447 if (TernaryMiddle.isInvalid()) { 448 // If we're using '>>' as an operator within a template 449 // argument list (in C++98), suggest the addition of 450 // parentheses so that the code remains well-formed in C++0x. 451 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater)) 452 SuggestParentheses(OpToken.getLocation(), 453 diag::warn_cxx0x_right_shift_in_template_arg, 454 SourceRange(Actions.getExprRange(LHS.get()).getBegin(), 455 Actions.getExprRange(RHS.get()).getEnd())); 456 457 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(), 458 OpToken.getKind(), LHS.take(), RHS.take()); 459 } else 460 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc, 461 LHS.take(), TernaryMiddle.take(), 462 RHS.take()); 463 } 464 } 465} 466 467/// \brief Parse a cast-expression, or, if \p isUnaryExpression is true, 468/// parse a unary-expression. 469/// 470/// \p isAddressOfOperand exists because an id-expression that is the 471/// operand of address-of gets special treatment due to member pointers. 472/// 473ExprResult Parser::ParseCastExpression(bool isUnaryExpression, 474 bool isAddressOfOperand, 475 TypeCastState isTypeCast) { 476 bool NotCastExpr; 477 ExprResult Res = ParseCastExpression(isUnaryExpression, 478 isAddressOfOperand, 479 NotCastExpr, 480 isTypeCast); 481 if (NotCastExpr) 482 Diag(Tok, diag::err_expected_expression); 483 return Res; 484} 485 486namespace { 487class CastExpressionIdValidator : public CorrectionCandidateCallback { 488 public: 489 CastExpressionIdValidator(bool AllowTypes, bool AllowNonTypes) 490 : AllowNonTypes(AllowNonTypes) { 491 WantTypeSpecifiers = AllowTypes; 492 } 493 494 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 495 NamedDecl *ND = candidate.getCorrectionDecl(); 496 if (!ND) 497 return candidate.isKeyword(); 498 499 if (isa<TypeDecl>(ND)) 500 return WantTypeSpecifiers; 501 return AllowNonTypes; 502 } 503 504 private: 505 bool AllowNonTypes; 506}; 507} 508 509/// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse 510/// a unary-expression. 511/// 512/// \p isAddressOfOperand exists because an id-expression that is the operand 513/// of address-of gets special treatment due to member pointers. NotCastExpr 514/// is set to true if the token is not the start of a cast-expression, and no 515/// diagnostic is emitted in this case. 516/// 517/// \verbatim 518/// cast-expression: [C99 6.5.4] 519/// unary-expression 520/// '(' type-name ')' cast-expression 521/// 522/// unary-expression: [C99 6.5.3] 523/// postfix-expression 524/// '++' unary-expression 525/// '--' unary-expression 526/// unary-operator cast-expression 527/// 'sizeof' unary-expression 528/// 'sizeof' '(' type-name ')' 529/// [C++11] 'sizeof' '...' '(' identifier ')' 530/// [GNU] '__alignof' unary-expression 531/// [GNU] '__alignof' '(' type-name ')' 532/// [C11] '_Alignof' '(' type-name ')' 533/// [C++11] 'alignof' '(' type-id ')' 534/// [GNU] '&&' identifier 535/// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7] 536/// [C++] new-expression 537/// [C++] delete-expression 538/// 539/// unary-operator: one of 540/// '&' '*' '+' '-' '~' '!' 541/// [GNU] '__extension__' '__real' '__imag' 542/// 543/// primary-expression: [C99 6.5.1] 544/// [C99] identifier 545/// [C++] id-expression 546/// constant 547/// string-literal 548/// [C++] boolean-literal [C++ 2.13.5] 549/// [C++11] 'nullptr' [C++11 2.14.7] 550/// [C++11] user-defined-literal 551/// '(' expression ')' 552/// [C11] generic-selection 553/// '__func__' [C99 6.4.2.2] 554/// [GNU] '__FUNCTION__' 555/// [GNU] '__PRETTY_FUNCTION__' 556/// [GNU] '(' compound-statement ')' 557/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 558/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 559/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 560/// assign-expr ')' 561/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 562/// [GNU] '__null' 563/// [OBJC] '[' objc-message-expr ']' 564/// [OBJC] '\@selector' '(' objc-selector-arg ')' 565/// [OBJC] '\@protocol' '(' identifier ')' 566/// [OBJC] '\@encode' '(' type-name ')' 567/// [OBJC] objc-string-literal 568/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 569/// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3] 570/// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 571/// [C++11] typename-specifier braced-init-list [C++11 5.2.3] 572/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 573/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 574/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 575/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 576/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1] 577/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1] 578/// [C++] 'this' [C++ 9.3.2] 579/// [G++] unary-type-trait '(' type-id ')' 580/// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO] 581/// [EMBT] array-type-trait '(' type-id ',' integer ')' 582/// [clang] '^' block-literal 583/// 584/// constant: [C99 6.4.4] 585/// integer-constant 586/// floating-constant 587/// enumeration-constant -> identifier 588/// character-constant 589/// 590/// id-expression: [C++ 5.1] 591/// unqualified-id 592/// qualified-id 593/// 594/// unqualified-id: [C++ 5.1] 595/// identifier 596/// operator-function-id 597/// conversion-function-id 598/// '~' class-name 599/// template-id 600/// 601/// new-expression: [C++ 5.3.4] 602/// '::'[opt] 'new' new-placement[opt] new-type-id 603/// new-initializer[opt] 604/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 605/// new-initializer[opt] 606/// 607/// delete-expression: [C++ 5.3.5] 608/// '::'[opt] 'delete' cast-expression 609/// '::'[opt] 'delete' '[' ']' cast-expression 610/// 611/// [GNU/Embarcadero] unary-type-trait: 612/// '__is_arithmetic' 613/// '__is_floating_point' 614/// '__is_integral' 615/// '__is_lvalue_expr' 616/// '__is_rvalue_expr' 617/// '__is_complete_type' 618/// '__is_void' 619/// '__is_array' 620/// '__is_function' 621/// '__is_reference' 622/// '__is_lvalue_reference' 623/// '__is_rvalue_reference' 624/// '__is_fundamental' 625/// '__is_object' 626/// '__is_scalar' 627/// '__is_compound' 628/// '__is_pointer' 629/// '__is_member_object_pointer' 630/// '__is_member_function_pointer' 631/// '__is_member_pointer' 632/// '__is_const' 633/// '__is_volatile' 634/// '__is_trivial' 635/// '__is_standard_layout' 636/// '__is_signed' 637/// '__is_unsigned' 638/// 639/// [GNU] unary-type-trait: 640/// '__has_nothrow_assign' 641/// '__has_nothrow_copy' 642/// '__has_nothrow_constructor' 643/// '__has_trivial_assign' [TODO] 644/// '__has_trivial_copy' [TODO] 645/// '__has_trivial_constructor' 646/// '__has_trivial_destructor' 647/// '__has_virtual_destructor' 648/// '__is_abstract' [TODO] 649/// '__is_class' 650/// '__is_empty' [TODO] 651/// '__is_enum' 652/// '__is_final' 653/// '__is_pod' 654/// '__is_polymorphic' 655/// '__is_trivial' 656/// '__is_union' 657/// 658/// [Clang] unary-type-trait: 659/// '__trivially_copyable' 660/// 661/// binary-type-trait: 662/// [GNU] '__is_base_of' 663/// [MS] '__is_convertible_to' 664/// '__is_convertible' 665/// '__is_same' 666/// 667/// [Embarcadero] array-type-trait: 668/// '__array_rank' 669/// '__array_extent' 670/// 671/// [Embarcadero] expression-trait: 672/// '__is_lvalue_expr' 673/// '__is_rvalue_expr' 674/// \endverbatim 675/// 676ExprResult Parser::ParseCastExpression(bool isUnaryExpression, 677 bool isAddressOfOperand, 678 bool &NotCastExpr, 679 TypeCastState isTypeCast) { 680 ExprResult Res; 681 tok::TokenKind SavedKind = Tok.getKind(); 682 NotCastExpr = false; 683 684 // This handles all of cast-expression, unary-expression, postfix-expression, 685 // and primary-expression. We handle them together like this for efficiency 686 // and to simplify handling of an expression starting with a '(' token: which 687 // may be one of a parenthesized expression, cast-expression, compound literal 688 // expression, or statement expression. 689 // 690 // If the parsed tokens consist of a primary-expression, the cases below 691 // break out of the switch; at the end we call ParsePostfixExpressionSuffix 692 // to handle the postfix expression suffixes. Cases that cannot be followed 693 // by postfix exprs should return without invoking 694 // ParsePostfixExpressionSuffix. 695 switch (SavedKind) { 696 case tok::l_paren: { 697 // If this expression is limited to being a unary-expression, the parent can 698 // not start a cast expression. 699 ParenParseOption ParenExprType = 700 (isUnaryExpression && !getLangOpts().CPlusPlus)? CompoundLiteral : CastExpr; 701 ParsedType CastTy; 702 SourceLocation RParenLoc; 703 704 { 705 // The inside of the parens don't need to be a colon protected scope, and 706 // isn't immediately a message send. 707 ColonProtectionRAIIObject X(*this, false); 708 709 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/, 710 isTypeCast == IsTypeCast, CastTy, RParenLoc); 711 } 712 713 switch (ParenExprType) { 714 case SimpleExpr: break; // Nothing else to do. 715 case CompoundStmt: break; // Nothing else to do. 716 case CompoundLiteral: 717 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of 718 // postfix-expression exist, parse them now. 719 break; 720 case CastExpr: 721 // We have parsed the cast-expression and no postfix-expr pieces are 722 // following. 723 return Res; 724 } 725 726 break; 727 } 728 729 // primary-expression 730 case tok::numeric_constant: 731 // constant: integer-constant 732 // constant: floating-constant 733 734 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope()); 735 ConsumeToken(); 736 break; 737 738 case tok::kw_true: 739 case tok::kw_false: 740 return ParseCXXBoolLiteral(); 741 742 case tok::kw___objc_yes: 743 case tok::kw___objc_no: 744 return ParseObjCBoolLiteral(); 745 746 case tok::kw_nullptr: 747 Diag(Tok, diag::warn_cxx98_compat_nullptr); 748 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken()); 749 750 case tok::annot_primary_expr: 751 assert(Res.get() == 0 && "Stray primary-expression annotation?"); 752 Res = getExprAnnotation(Tok); 753 ConsumeToken(); 754 break; 755 756 case tok::kw_decltype: 757 case tok::identifier: { // primary-expression: identifier 758 // unqualified-id: identifier 759 // constant: enumeration-constant 760 // Turn a potentially qualified name into a annot_typename or 761 // annot_cxxscope if it would be valid. This handles things like x::y, etc. 762 if (getLangOpts().CPlusPlus) { 763 // Avoid the unnecessary parse-time lookup in the common case 764 // where the syntax forbids a type. 765 const Token &Next = NextToken(); 766 767 // If this identifier was reverted from a token ID, and the next token 768 // is a parenthesis, this is likely to be a use of a type trait. Check 769 // those tokens. 770 if (Next.is(tok::l_paren) && 771 Tok.is(tok::identifier) && 772 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) { 773 IdentifierInfo *II = Tok.getIdentifierInfo(); 774 // Build up the mapping of revertable type traits, for future use. 775 if (RevertableTypeTraits.empty()) { 776#define RTT_JOIN(X,Y) X##Y 777#define REVERTABLE_TYPE_TRAIT(Name) \ 778 RevertableTypeTraits[PP.getIdentifierInfo(#Name)] \ 779 = RTT_JOIN(tok::kw_,Name) 780 781 REVERTABLE_TYPE_TRAIT(__is_arithmetic); 782 REVERTABLE_TYPE_TRAIT(__is_convertible); 783 REVERTABLE_TYPE_TRAIT(__is_empty); 784 REVERTABLE_TYPE_TRAIT(__is_floating_point); 785 REVERTABLE_TYPE_TRAIT(__is_function); 786 REVERTABLE_TYPE_TRAIT(__is_fundamental); 787 REVERTABLE_TYPE_TRAIT(__is_integral); 788 REVERTABLE_TYPE_TRAIT(__is_member_function_pointer); 789 REVERTABLE_TYPE_TRAIT(__is_member_pointer); 790 REVERTABLE_TYPE_TRAIT(__is_pod); 791 REVERTABLE_TYPE_TRAIT(__is_pointer); 792 REVERTABLE_TYPE_TRAIT(__is_same); 793 REVERTABLE_TYPE_TRAIT(__is_scalar); 794 REVERTABLE_TYPE_TRAIT(__is_signed); 795 REVERTABLE_TYPE_TRAIT(__is_unsigned); 796 REVERTABLE_TYPE_TRAIT(__is_void); 797#undef REVERTABLE_TYPE_TRAIT 798#undef RTT_JOIN 799 } 800 801 // If we find that this is in fact the name of a type trait, 802 // update the token kind in place and parse again to treat it as 803 // the appropriate kind of type trait. 804 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known 805 = RevertableTypeTraits.find(II); 806 if (Known != RevertableTypeTraits.end()) { 807 Tok.setKind(Known->second); 808 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 809 NotCastExpr, isTypeCast); 810 } 811 } 812 813 if (Next.is(tok::coloncolon) || 814 (!ColonIsSacred && Next.is(tok::colon)) || 815 Next.is(tok::less) || 816 Next.is(tok::l_paren) || 817 Next.is(tok::l_brace)) { 818 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 819 if (TryAnnotateTypeOrScopeToken()) 820 return ExprError(); 821 if (!Tok.is(tok::identifier)) 822 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 823 } 824 } 825 826 // Consume the identifier so that we can see if it is followed by a '(' or 827 // '.'. 828 IdentifierInfo &II = *Tok.getIdentifierInfo(); 829 SourceLocation ILoc = ConsumeToken(); 830 831 // Support 'Class.property' and 'super.property' notation. 832 if (getLangOpts().ObjC1 && Tok.is(tok::period) && 833 (Actions.getTypeName(II, ILoc, getCurScope()) || 834 // Allow the base to be 'super' if in an objc-method. 835 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) { 836 ConsumeToken(); 837 838 // Allow either an identifier or the keyword 'class' (in C++). 839 if (Tok.isNot(tok::identifier) && 840 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) { 841 Diag(Tok, diag::err_expected_property_name); 842 return ExprError(); 843 } 844 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); 845 SourceLocation PropertyLoc = ConsumeToken(); 846 847 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName, 848 ILoc, PropertyLoc); 849 break; 850 } 851 852 // In an Objective-C method, if we have "super" followed by an identifier, 853 // the token sequence is ill-formed. However, if there's a ':' or ']' after 854 // that identifier, this is probably a message send with a missing open 855 // bracket. Treat it as such. 856 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression && 857 getCurScope()->isInObjcMethodScope() && 858 ((Tok.is(tok::identifier) && 859 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) || 860 Tok.is(tok::code_completion))) { 861 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(), 862 0); 863 break; 864 } 865 866 // If we have an Objective-C class name followed by an identifier 867 // and either ':' or ']', this is an Objective-C class message 868 // send that's missing the opening '['. Recovery 869 // appropriately. Also take this path if we're performing code 870 // completion after an Objective-C class name. 871 if (getLangOpts().ObjC1 && 872 ((Tok.is(tok::identifier) && !InMessageExpression) || 873 Tok.is(tok::code_completion))) { 874 const Token& Next = NextToken(); 875 if (Tok.is(tok::code_completion) || 876 Next.is(tok::colon) || Next.is(tok::r_square)) 877 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope())) 878 if (Typ.get()->isObjCObjectOrInterfaceType()) { 879 // Fake up a Declarator to use with ActOnTypeName. 880 DeclSpec DS(AttrFactory); 881 DS.SetRangeStart(ILoc); 882 DS.SetRangeEnd(ILoc); 883 const char *PrevSpec = 0; 884 unsigned DiagID; 885 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ); 886 887 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 888 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), 889 DeclaratorInfo); 890 if (Ty.isInvalid()) 891 break; 892 893 Res = ParseObjCMessageExpressionBody(SourceLocation(), 894 SourceLocation(), 895 Ty.get(), 0); 896 break; 897 } 898 } 899 900 // Make sure to pass down the right value for isAddressOfOperand. 901 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 902 isAddressOfOperand = false; 903 904 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we 905 // need to know whether or not this identifier is a function designator or 906 // not. 907 UnqualifiedId Name; 908 CXXScopeSpec ScopeSpec; 909 SourceLocation TemplateKWLoc; 910 CastExpressionIdValidator Validator(isTypeCast != NotTypeCast, 911 isTypeCast != IsTypeCast); 912 Name.setIdentifier(&II, ILoc); 913 Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKWLoc, 914 Name, Tok.is(tok::l_paren), 915 isAddressOfOperand, &Validator); 916 break; 917 } 918 case tok::char_constant: // constant: character-constant 919 case tok::wide_char_constant: 920 case tok::utf16_char_constant: 921 case tok::utf32_char_constant: 922 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope()); 923 ConsumeToken(); 924 break; 925 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] 926 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] 927 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS] 928 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] 929 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind); 930 ConsumeToken(); 931 break; 932 case tok::string_literal: // primary-expression: string-literal 933 case tok::wide_string_literal: 934 case tok::utf8_string_literal: 935 case tok::utf16_string_literal: 936 case tok::utf32_string_literal: 937 Res = ParseStringLiteralExpression(true); 938 break; 939 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1] 940 Res = ParseGenericSelectionExpression(); 941 break; 942 case tok::kw___builtin_va_arg: 943 case tok::kw___builtin_offsetof: 944 case tok::kw___builtin_choose_expr: 945 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type() 946 return ParseBuiltinPrimaryExpression(); 947 case tok::kw___null: 948 return Actions.ActOnGNUNullExpr(ConsumeToken()); 949 950 case tok::plusplus: // unary-expression: '++' unary-expression [C99] 951 case tok::minusminus: { // unary-expression: '--' unary-expression [C99] 952 // C++ [expr.unary] has: 953 // unary-expression: 954 // ++ cast-expression 955 // -- cast-expression 956 SourceLocation SavedLoc = ConsumeToken(); 957 Res = ParseCastExpression(!getLangOpts().CPlusPlus); 958 if (!Res.isInvalid()) 959 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 960 return Res; 961 } 962 case tok::amp: { // unary-expression: '&' cast-expression 963 // Special treatment because of member pointers 964 SourceLocation SavedLoc = ConsumeToken(); 965 Res = ParseCastExpression(false, true); 966 if (!Res.isInvalid()) 967 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 968 return Res; 969 } 970 971 case tok::star: // unary-expression: '*' cast-expression 972 case tok::plus: // unary-expression: '+' cast-expression 973 case tok::minus: // unary-expression: '-' cast-expression 974 case tok::tilde: // unary-expression: '~' cast-expression 975 case tok::exclaim: // unary-expression: '!' cast-expression 976 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] 977 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] 978 SourceLocation SavedLoc = ConsumeToken(); 979 Res = ParseCastExpression(false); 980 if (!Res.isInvalid()) 981 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 982 return Res; 983 } 984 985 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] 986 // __extension__ silences extension warnings in the subexpression. 987 ExtensionRAIIObject O(Diags); // Use RAII to do this. 988 SourceLocation SavedLoc = ConsumeToken(); 989 Res = ParseCastExpression(false); 990 if (!Res.isInvalid()) 991 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 992 return Res; 993 } 994 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')' 995 if (!getLangOpts().C11) 996 Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); 997 // fallthrough 998 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')' 999 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression 1000 // unary-expression: '__alignof' '(' type-name ')' 1001 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression 1002 // unary-expression: 'sizeof' '(' type-name ')' 1003 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression 1004 return ParseUnaryExprOrTypeTraitExpression(); 1005 case tok::ampamp: { // unary-expression: '&&' identifier 1006 SourceLocation AmpAmpLoc = ConsumeToken(); 1007 if (Tok.isNot(tok::identifier)) 1008 return ExprError(Diag(Tok, diag::err_expected_ident)); 1009 1010 if (getCurScope()->getFnParent() == 0) 1011 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn)); 1012 1013 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); 1014 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), 1015 Tok.getLocation()); 1016 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD); 1017 ConsumeToken(); 1018 return Res; 1019 } 1020 case tok::kw_const_cast: 1021 case tok::kw_dynamic_cast: 1022 case tok::kw_reinterpret_cast: 1023 case tok::kw_static_cast: 1024 Res = ParseCXXCasts(); 1025 break; 1026 case tok::kw_typeid: 1027 Res = ParseCXXTypeid(); 1028 break; 1029 case tok::kw___uuidof: 1030 Res = ParseCXXUuidof(); 1031 break; 1032 case tok::kw_this: 1033 Res = ParseCXXThis(); 1034 break; 1035 1036 case tok::annot_typename: 1037 if (isStartOfObjCClassMessageMissingOpenBracket()) { 1038 ParsedType Type = getTypeAnnotation(Tok); 1039 1040 // Fake up a Declarator to use with ActOnTypeName. 1041 DeclSpec DS(AttrFactory); 1042 DS.SetRangeStart(Tok.getLocation()); 1043 DS.SetRangeEnd(Tok.getLastLoc()); 1044 1045 const char *PrevSpec = 0; 1046 unsigned DiagID; 1047 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(), 1048 PrevSpec, DiagID, Type); 1049 1050 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 1051 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 1052 if (Ty.isInvalid()) 1053 break; 1054 1055 ConsumeToken(); 1056 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 1057 Ty.get(), 0); 1058 break; 1059 } 1060 // Fall through 1061 1062 case tok::annot_decltype: 1063 case tok::kw_char: 1064 case tok::kw_wchar_t: 1065 case tok::kw_char16_t: 1066 case tok::kw_char32_t: 1067 case tok::kw_bool: 1068 case tok::kw_short: 1069 case tok::kw_int: 1070 case tok::kw_long: 1071 case tok::kw___int64: 1072 case tok::kw___int128: 1073 case tok::kw_signed: 1074 case tok::kw_unsigned: 1075 case tok::kw_half: 1076 case tok::kw_float: 1077 case tok::kw_double: 1078 case tok::kw_void: 1079 case tok::kw_typename: 1080 case tok::kw_typeof: 1081 case tok::kw___vector: 1082 case tok::kw_image1d_t: 1083 case tok::kw_image1d_array_t: 1084 case tok::kw_image1d_buffer_t: 1085 case tok::kw_image2d_t: 1086 case tok::kw_image2d_array_t: 1087 case tok::kw_image3d_t: { 1088 if (!getLangOpts().CPlusPlus) { 1089 Diag(Tok, diag::err_expected_expression); 1090 return ExprError(); 1091 } 1092 1093 if (SavedKind == tok::kw_typename) { 1094 // postfix-expression: typename-specifier '(' expression-list[opt] ')' 1095 // typename-specifier braced-init-list 1096 if (TryAnnotateTypeOrScopeToken()) 1097 return ExprError(); 1098 } 1099 1100 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' 1101 // simple-type-specifier braced-init-list 1102 // 1103 DeclSpec DS(AttrFactory); 1104 ParseCXXSimpleTypeSpecifier(DS); 1105 if (Tok.isNot(tok::l_paren) && 1106 (!getLangOpts().CPlusPlus0x || Tok.isNot(tok::l_brace))) 1107 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) 1108 << DS.getSourceRange()); 1109 1110 if (Tok.is(tok::l_brace)) 1111 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 1112 1113 Res = ParseCXXTypeConstructExpression(DS); 1114 break; 1115 } 1116 1117 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id 1118 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 1119 // (We can end up in this situation after tentative parsing.) 1120 if (TryAnnotateTypeOrScopeToken()) 1121 return ExprError(); 1122 if (!Tok.is(tok::annot_cxxscope)) 1123 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1124 NotCastExpr, isTypeCast); 1125 1126 Token Next = NextToken(); 1127 if (Next.is(tok::annot_template_id)) { 1128 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 1129 if (TemplateId->Kind == TNK_Type_template) { 1130 // We have a qualified template-id that we know refers to a 1131 // type, translate it into a type and continue parsing as a 1132 // cast expression. 1133 CXXScopeSpec SS; 1134 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 1135 /*EnteringContext=*/false); 1136 AnnotateTemplateIdTokenAsType(); 1137 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1138 NotCastExpr, isTypeCast); 1139 } 1140 } 1141 1142 // Parse as an id-expression. 1143 Res = ParseCXXIdExpression(isAddressOfOperand); 1144 break; 1145 } 1146 1147 case tok::annot_template_id: { // [C++] template-id 1148 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 1149 if (TemplateId->Kind == TNK_Type_template) { 1150 // We have a template-id that we know refers to a type, 1151 // translate it into a type and continue parsing as a cast 1152 // expression. 1153 AnnotateTemplateIdTokenAsType(); 1154 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 1155 NotCastExpr, isTypeCast); 1156 } 1157 1158 // Fall through to treat the template-id as an id-expression. 1159 } 1160 1161 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id 1162 Res = ParseCXXIdExpression(isAddressOfOperand); 1163 break; 1164 1165 case tok::coloncolon: { 1166 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken 1167 // annotates the token, tail recurse. 1168 if (TryAnnotateTypeOrScopeToken()) 1169 return ExprError(); 1170 if (!Tok.is(tok::coloncolon)) 1171 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 1172 1173 // ::new -> [C++] new-expression 1174 // ::delete -> [C++] delete-expression 1175 SourceLocation CCLoc = ConsumeToken(); 1176 if (Tok.is(tok::kw_new)) 1177 return ParseCXXNewExpression(true, CCLoc); 1178 if (Tok.is(tok::kw_delete)) 1179 return ParseCXXDeleteExpression(true, CCLoc); 1180 1181 // This is not a type name or scope specifier, it is an invalid expression. 1182 Diag(CCLoc, diag::err_expected_expression); 1183 return ExprError(); 1184 } 1185 1186 case tok::kw_new: // [C++] new-expression 1187 return ParseCXXNewExpression(false, Tok.getLocation()); 1188 1189 case tok::kw_delete: // [C++] delete-expression 1190 return ParseCXXDeleteExpression(false, Tok.getLocation()); 1191 1192 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')' 1193 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr); 1194 SourceLocation KeyLoc = ConsumeToken(); 1195 BalancedDelimiterTracker T(*this, tok::l_paren); 1196 1197 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept")) 1198 return ExprError(); 1199 // C++11 [expr.unary.noexcept]p1: 1200 // The noexcept operator determines whether the evaluation of its operand, 1201 // which is an unevaluated operand, can throw an exception. 1202 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 1203 ExprResult Result = ParseExpression(); 1204 1205 T.consumeClose(); 1206 1207 if (!Result.isInvalid()) 1208 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), 1209 Result.take(), T.getCloseLocation()); 1210 return Result; 1211 } 1212 1213 case tok::kw___is_abstract: // [GNU] unary-type-trait 1214 case tok::kw___is_class: 1215 case tok::kw___is_empty: 1216 case tok::kw___is_enum: 1217 case tok::kw___is_interface_class: 1218 case tok::kw___is_literal: 1219 case tok::kw___is_arithmetic: 1220 case tok::kw___is_integral: 1221 case tok::kw___is_floating_point: 1222 case tok::kw___is_complete_type: 1223 case tok::kw___is_void: 1224 case tok::kw___is_array: 1225 case tok::kw___is_function: 1226 case tok::kw___is_reference: 1227 case tok::kw___is_lvalue_reference: 1228 case tok::kw___is_rvalue_reference: 1229 case tok::kw___is_fundamental: 1230 case tok::kw___is_object: 1231 case tok::kw___is_scalar: 1232 case tok::kw___is_compound: 1233 case tok::kw___is_pointer: 1234 case tok::kw___is_member_object_pointer: 1235 case tok::kw___is_member_function_pointer: 1236 case tok::kw___is_member_pointer: 1237 case tok::kw___is_const: 1238 case tok::kw___is_volatile: 1239 case tok::kw___is_standard_layout: 1240 case tok::kw___is_signed: 1241 case tok::kw___is_unsigned: 1242 case tok::kw___is_literal_type: 1243 case tok::kw___is_pod: 1244 case tok::kw___is_polymorphic: 1245 case tok::kw___is_trivial: 1246 case tok::kw___is_trivially_copyable: 1247 case tok::kw___is_union: 1248 case tok::kw___is_final: 1249 case tok::kw___has_trivial_constructor: 1250 case tok::kw___has_trivial_copy: 1251 case tok::kw___has_trivial_assign: 1252 case tok::kw___has_trivial_destructor: 1253 case tok::kw___has_nothrow_assign: 1254 case tok::kw___has_nothrow_copy: 1255 case tok::kw___has_nothrow_constructor: 1256 case tok::kw___has_virtual_destructor: 1257 return ParseUnaryTypeTrait(); 1258 1259 case tok::kw___builtin_types_compatible_p: 1260 case tok::kw___is_base_of: 1261 case tok::kw___is_same: 1262 case tok::kw___is_convertible: 1263 case tok::kw___is_convertible_to: 1264 case tok::kw___is_trivially_assignable: 1265 return ParseBinaryTypeTrait(); 1266 1267 case tok::kw___is_trivially_constructible: 1268 return ParseTypeTrait(); 1269 1270 case tok::kw___array_rank: 1271 case tok::kw___array_extent: 1272 return ParseArrayTypeTrait(); 1273 1274 case tok::kw___is_lvalue_expr: 1275 case tok::kw___is_rvalue_expr: 1276 return ParseExpressionTrait(); 1277 1278 case tok::at: { 1279 SourceLocation AtLoc = ConsumeToken(); 1280 return ParseObjCAtExpression(AtLoc); 1281 } 1282 case tok::caret: 1283 Res = ParseBlockLiteralExpression(); 1284 break; 1285 case tok::code_completion: { 1286 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 1287 cutOffParsing(); 1288 return ExprError(); 1289 } 1290 case tok::l_square: 1291 if (getLangOpts().CPlusPlus0x) { 1292 if (getLangOpts().ObjC1) { 1293 // C++11 lambda expressions and Objective-C message sends both start with a 1294 // square bracket. There are three possibilities here: 1295 // we have a valid lambda expression, we have an invalid lambda 1296 // expression, or we have something that doesn't appear to be a lambda. 1297 // If we're in the last case, we fall back to ParseObjCMessageExpression. 1298 Res = TryParseLambdaExpression(); 1299 if (!Res.isInvalid() && !Res.get()) 1300 Res = ParseObjCMessageExpression(); 1301 break; 1302 } 1303 Res = ParseLambdaExpression(); 1304 break; 1305 } 1306 if (getLangOpts().ObjC1) { 1307 Res = ParseObjCMessageExpression(); 1308 break; 1309 } 1310 // FALL THROUGH. 1311 default: 1312 NotCastExpr = true; 1313 return ExprError(); 1314 } 1315 1316 // These can be followed by postfix-expr pieces. 1317 return ParsePostfixExpressionSuffix(Res); 1318} 1319 1320/// \brief Once the leading part of a postfix-expression is parsed, this 1321/// method parses any suffixes that apply. 1322/// 1323/// \verbatim 1324/// postfix-expression: [C99 6.5.2] 1325/// primary-expression 1326/// postfix-expression '[' expression ']' 1327/// postfix-expression '[' braced-init-list ']' 1328/// postfix-expression '(' argument-expression-list[opt] ')' 1329/// postfix-expression '.' identifier 1330/// postfix-expression '->' identifier 1331/// postfix-expression '++' 1332/// postfix-expression '--' 1333/// '(' type-name ')' '{' initializer-list '}' 1334/// '(' type-name ')' '{' initializer-list ',' '}' 1335/// 1336/// argument-expression-list: [C99 6.5.2] 1337/// argument-expression ...[opt] 1338/// argument-expression-list ',' assignment-expression ...[opt] 1339/// \endverbatim 1340ExprResult 1341Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { 1342 // Now that the primary-expression piece of the postfix-expression has been 1343 // parsed, see if there are any postfix-expression pieces here. 1344 SourceLocation Loc; 1345 while (1) { 1346 switch (Tok.getKind()) { 1347 case tok::code_completion: 1348 if (InMessageExpression) 1349 return LHS; 1350 1351 Actions.CodeCompletePostfixExpression(getCurScope(), LHS); 1352 cutOffParsing(); 1353 return ExprError(); 1354 1355 case tok::identifier: 1356 // If we see identifier: after an expression, and we're not already in a 1357 // message send, then this is probably a message send with a missing 1358 // opening bracket '['. 1359 if (getLangOpts().ObjC1 && !InMessageExpression && 1360 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 1361 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 1362 ParsedType(), LHS.get()); 1363 break; 1364 } 1365 1366 // Fall through; this isn't a message send. 1367 1368 default: // Not a postfix-expression suffix. 1369 return LHS; 1370 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 1371 // If we have a array postfix expression that starts on a new line and 1372 // Objective-C is enabled, it is highly likely that the user forgot a 1373 // semicolon after the base expression and that the array postfix-expr is 1374 // actually another message send. In this case, do some look-ahead to see 1375 // if the contents of the square brackets are obviously not a valid 1376 // expression and recover by pretending there is no suffix. 1377 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() && 1378 isSimpleObjCMessageExpression()) 1379 return LHS; 1380 1381 // Reject array indices starting with a lambda-expression. '[[' is 1382 // reserved for attributes. 1383 if (CheckProhibitedCXX11Attribute()) 1384 return ExprError(); 1385 1386 BalancedDelimiterTracker T(*this, tok::l_square); 1387 T.consumeOpen(); 1388 Loc = T.getOpenLocation(); 1389 ExprResult Idx; 1390 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 1391 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 1392 Idx = ParseBraceInitializer(); 1393 } else 1394 Idx = ParseExpression(); 1395 1396 SourceLocation RLoc = Tok.getLocation(); 1397 1398 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 1399 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc, 1400 Idx.take(), RLoc); 1401 } else 1402 LHS = ExprError(); 1403 1404 // Match the ']'. 1405 T.consumeClose(); 1406 break; 1407 } 1408 1409 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')' 1410 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>' 1411 // '(' argument-expression-list[opt] ')' 1412 tok::TokenKind OpKind = Tok.getKind(); 1413 InMessageExpressionRAIIObject InMessage(*this, false); 1414 1415 Expr *ExecConfig = 0; 1416 1417 BalancedDelimiterTracker PT(*this, tok::l_paren); 1418 1419 if (OpKind == tok::lesslessless) { 1420 ExprVector ExecConfigExprs; 1421 CommaLocsTy ExecConfigCommaLocs; 1422 SourceLocation OpenLoc = ConsumeToken(); 1423 1424 if (ParseExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) { 1425 LHS = ExprError(); 1426 } 1427 1428 SourceLocation CloseLoc = Tok.getLocation(); 1429 if (Tok.is(tok::greatergreatergreater)) { 1430 ConsumeToken(); 1431 } else if (LHS.isInvalid()) { 1432 SkipUntil(tok::greatergreatergreater); 1433 } else { 1434 // There was an error closing the brackets 1435 Diag(Tok, diag::err_expected_ggg); 1436 Diag(OpenLoc, diag::note_matching) << "<<<"; 1437 SkipUntil(tok::greatergreatergreater); 1438 LHS = ExprError(); 1439 } 1440 1441 if (!LHS.isInvalid()) { 1442 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, "")) 1443 LHS = ExprError(); 1444 else 1445 Loc = PrevTokLocation; 1446 } 1447 1448 if (!LHS.isInvalid()) { 1449 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), 1450 OpenLoc, 1451 ExecConfigExprs, 1452 CloseLoc); 1453 if (ECResult.isInvalid()) 1454 LHS = ExprError(); 1455 else 1456 ExecConfig = ECResult.get(); 1457 } 1458 } else { 1459 PT.consumeOpen(); 1460 Loc = PT.getOpenLocation(); 1461 } 1462 1463 ExprVector ArgExprs; 1464 CommaLocsTy CommaLocs; 1465 1466 if (Tok.is(tok::code_completion)) { 1467 Actions.CodeCompleteCall(getCurScope(), LHS.get(), 1468 llvm::ArrayRef<Expr *>()); 1469 cutOffParsing(); 1470 return ExprError(); 1471 } 1472 1473 if (OpKind == tok::l_paren || !LHS.isInvalid()) { 1474 if (Tok.isNot(tok::r_paren)) { 1475 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall, 1476 LHS.get())) { 1477 LHS = ExprError(); 1478 } 1479 } 1480 } 1481 1482 // Match the ')'. 1483 if (LHS.isInvalid()) { 1484 SkipUntil(tok::r_paren); 1485 } else if (Tok.isNot(tok::r_paren)) { 1486 PT.consumeClose(); 1487 LHS = ExprError(); 1488 } else { 1489 assert((ArgExprs.size() == 0 || 1490 ArgExprs.size()-1 == CommaLocs.size())&& 1491 "Unexpected number of commas!"); 1492 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc, 1493 ArgExprs, Tok.getLocation(), 1494 ExecConfig); 1495 PT.consumeClose(); 1496 } 1497 1498 break; 1499 } 1500 case tok::arrow: 1501 case tok::period: { 1502 // postfix-expression: p-e '->' template[opt] id-expression 1503 // postfix-expression: p-e '.' template[opt] id-expression 1504 tok::TokenKind OpKind = Tok.getKind(); 1505 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 1506 1507 CXXScopeSpec SS; 1508 ParsedType ObjectType; 1509 bool MayBePseudoDestructor = false; 1510 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) { 1511 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), LHS.take(), 1512 OpLoc, OpKind, ObjectType, 1513 MayBePseudoDestructor); 1514 if (LHS.isInvalid()) 1515 break; 1516 1517 ParseOptionalCXXScopeSpecifier(SS, ObjectType, 1518 /*EnteringContext=*/false, 1519 &MayBePseudoDestructor); 1520 if (SS.isNotEmpty()) 1521 ObjectType = ParsedType(); 1522 } 1523 1524 if (Tok.is(tok::code_completion)) { 1525 // Code completion for a member access expression. 1526 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(), 1527 OpLoc, OpKind == tok::arrow); 1528 1529 cutOffParsing(); 1530 return ExprError(); 1531 } 1532 1533 if (MayBePseudoDestructor && !LHS.isInvalid()) { 1534 LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS, 1535 ObjectType); 1536 break; 1537 } 1538 1539 // Either the action has told is that this cannot be a 1540 // pseudo-destructor expression (based on the type of base 1541 // expression), or we didn't see a '~' in the right place. We 1542 // can still parse a destructor name here, but in that case it 1543 // names a real destructor. 1544 // Allow explicit constructor calls in Microsoft mode. 1545 // FIXME: Add support for explicit call of template constructor. 1546 SourceLocation TemplateKWLoc; 1547 UnqualifiedId Name; 1548 if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) { 1549 // Objective-C++: 1550 // After a '.' in a member access expression, treat the keyword 1551 // 'class' as if it were an identifier. 1552 // 1553 // This hack allows property access to the 'class' method because it is 1554 // such a common method name. For other C++ keywords that are 1555 // Objective-C method names, one must use the message send syntax. 1556 IdentifierInfo *Id = Tok.getIdentifierInfo(); 1557 SourceLocation Loc = ConsumeToken(); 1558 Name.setIdentifier(Id, Loc); 1559 } else if (ParseUnqualifiedId(SS, 1560 /*EnteringContext=*/false, 1561 /*AllowDestructorName=*/true, 1562 /*AllowConstructorName=*/ 1563 getLangOpts().MicrosoftExt, 1564 ObjectType, TemplateKWLoc, Name)) 1565 LHS = ExprError(); 1566 1567 if (!LHS.isInvalid()) 1568 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc, 1569 OpKind, SS, TemplateKWLoc, Name, 1570 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl : 0, 1571 Tok.is(tok::l_paren)); 1572 break; 1573 } 1574 case tok::plusplus: // postfix-expression: postfix-expression '++' 1575 case tok::minusminus: // postfix-expression: postfix-expression '--' 1576 if (!LHS.isInvalid()) { 1577 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(), 1578 Tok.getKind(), LHS.take()); 1579 } 1580 ConsumeToken(); 1581 break; 1582 } 1583 } 1584} 1585 1586/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/ 1587/// vec_step and we are at the start of an expression or a parenthesized 1588/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the 1589/// expression (isCastExpr == false) or the type (isCastExpr == true). 1590/// 1591/// \verbatim 1592/// unary-expression: [C99 6.5.3] 1593/// 'sizeof' unary-expression 1594/// 'sizeof' '(' type-name ')' 1595/// [GNU] '__alignof' unary-expression 1596/// [GNU] '__alignof' '(' type-name ')' 1597/// [C11] '_Alignof' '(' type-name ')' 1598/// [C++0x] 'alignof' '(' type-id ')' 1599/// 1600/// [GNU] typeof-specifier: 1601/// typeof ( expressions ) 1602/// typeof ( type-name ) 1603/// [GNU/C++] typeof unary-expression 1604/// 1605/// [OpenCL 1.1 6.11.12] vec_step built-in function: 1606/// vec_step ( expressions ) 1607/// vec_step ( type-name ) 1608/// \endverbatim 1609ExprResult 1610Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, 1611 bool &isCastExpr, 1612 ParsedType &CastTy, 1613 SourceRange &CastRange) { 1614 1615 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 1616 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) || 1617 OpTok.is(tok::kw__Alignof) || OpTok.is(tok::kw_vec_step)) && 1618 "Not a typeof/sizeof/alignof/vec_step expression!"); 1619 1620 ExprResult Operand; 1621 1622 // If the operand doesn't start with an '(', it must be an expression. 1623 if (Tok.isNot(tok::l_paren)) { 1624 isCastExpr = false; 1625 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) { 1626 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 1627 return ExprError(); 1628 } 1629 1630 Operand = ParseCastExpression(true/*isUnaryExpression*/); 1631 } else { 1632 // If it starts with a '(', we know that it is either a parenthesized 1633 // type-name, or it is a unary-expression that starts with a compound 1634 // literal, or starts with a primary-expression that is a parenthesized 1635 // expression. 1636 ParenParseOption ExprType = CastExpr; 1637 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 1638 1639 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 1640 false, CastTy, RParenLoc); 1641 CastRange = SourceRange(LParenLoc, RParenLoc); 1642 1643 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 1644 // a type. 1645 if (ExprType == CastExpr) { 1646 isCastExpr = true; 1647 return ExprEmpty(); 1648 } 1649 1650 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { 1651 // GNU typeof in C requires the expression to be parenthesized. Not so for 1652 // sizeof/alignof or in C++. Therefore, the parenthesized expression is 1653 // the start of a unary-expression, but doesn't include any postfix 1654 // pieces. Parse these now if present. 1655 if (!Operand.isInvalid()) 1656 Operand = ParsePostfixExpressionSuffix(Operand.get()); 1657 } 1658 } 1659 1660 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 1661 isCastExpr = false; 1662 return Operand; 1663} 1664 1665 1666/// \brief Parse a sizeof or alignof expression. 1667/// 1668/// \verbatim 1669/// unary-expression: [C99 6.5.3] 1670/// 'sizeof' unary-expression 1671/// 'sizeof' '(' type-name ')' 1672/// [C++0x] 'sizeof' '...' '(' identifier ')' 1673/// [GNU] '__alignof' unary-expression 1674/// [GNU] '__alignof' '(' type-name ')' 1675/// [C11] '_Alignof' '(' type-name ')' 1676/// [C++0x] 'alignof' '(' type-id ')' 1677/// \endverbatim 1678ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { 1679 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) || 1680 Tok.is(tok::kw_alignof) || Tok.is(tok::kw__Alignof) || 1681 Tok.is(tok::kw_vec_step)) && 1682 "Not a sizeof/alignof/vec_step expression!"); 1683 Token OpTok = Tok; 1684 ConsumeToken(); 1685 1686 // [C++0x] 'sizeof' '...' '(' identifier ')' 1687 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) { 1688 SourceLocation EllipsisLoc = ConsumeToken(); 1689 SourceLocation LParenLoc, RParenLoc; 1690 IdentifierInfo *Name = 0; 1691 SourceLocation NameLoc; 1692 if (Tok.is(tok::l_paren)) { 1693 BalancedDelimiterTracker T(*this, tok::l_paren); 1694 T.consumeOpen(); 1695 LParenLoc = T.getOpenLocation(); 1696 if (Tok.is(tok::identifier)) { 1697 Name = Tok.getIdentifierInfo(); 1698 NameLoc = ConsumeToken(); 1699 T.consumeClose(); 1700 RParenLoc = T.getCloseLocation(); 1701 if (RParenLoc.isInvalid()) 1702 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1703 } else { 1704 Diag(Tok, diag::err_expected_parameter_pack); 1705 SkipUntil(tok::r_paren); 1706 } 1707 } else if (Tok.is(tok::identifier)) { 1708 Name = Tok.getIdentifierInfo(); 1709 NameLoc = ConsumeToken(); 1710 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc); 1711 RParenLoc = PP.getLocForEndOfToken(NameLoc); 1712 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack) 1713 << Name 1714 << FixItHint::CreateInsertion(LParenLoc, "(") 1715 << FixItHint::CreateInsertion(RParenLoc, ")"); 1716 } else { 1717 Diag(Tok, diag::err_sizeof_parameter_pack); 1718 } 1719 1720 if (!Name) 1721 return ExprError(); 1722 1723 return Actions.ActOnSizeofParameterPackExpr(getCurScope(), 1724 OpTok.getLocation(), 1725 *Name, NameLoc, 1726 RParenLoc); 1727 } 1728 1729 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof)) 1730 Diag(OpTok, diag::warn_cxx98_compat_alignof); 1731 1732 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 1733 Sema::ReuseLambdaContextDecl); 1734 1735 bool isCastExpr; 1736 ParsedType CastTy; 1737 SourceRange CastRange; 1738 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, 1739 isCastExpr, 1740 CastTy, 1741 CastRange); 1742 1743 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf; 1744 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof) || 1745 OpTok.is(tok::kw__Alignof)) 1746 ExprKind = UETT_AlignOf; 1747 else if (OpTok.is(tok::kw_vec_step)) 1748 ExprKind = UETT_VecStep; 1749 1750 if (isCastExpr) 1751 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 1752 ExprKind, 1753 /*isType=*/true, 1754 CastTy.getAsOpaquePtr(), 1755 CastRange); 1756 1757 // If we get here, the operand to the sizeof/alignof was an expresion. 1758 if (!Operand.isInvalid()) 1759 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 1760 ExprKind, 1761 /*isType=*/false, 1762 Operand.release(), 1763 CastRange); 1764 return Operand; 1765} 1766 1767/// ParseBuiltinPrimaryExpression 1768/// 1769/// \verbatim 1770/// primary-expression: [C99 6.5.1] 1771/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1772/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1773/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1774/// assign-expr ')' 1775/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1776/// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')' 1777/// 1778/// [GNU] offsetof-member-designator: 1779/// [GNU] identifier 1780/// [GNU] offsetof-member-designator '.' identifier 1781/// [GNU] offsetof-member-designator '[' expression ']' 1782/// \endverbatim 1783ExprResult Parser::ParseBuiltinPrimaryExpression() { 1784 ExprResult Res; 1785 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1786 1787 tok::TokenKind T = Tok.getKind(); 1788 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1789 1790 // All of these start with an open paren. 1791 if (Tok.isNot(tok::l_paren)) 1792 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1793 << BuiltinII); 1794 1795 BalancedDelimiterTracker PT(*this, tok::l_paren); 1796 PT.consumeOpen(); 1797 1798 // TODO: Build AST. 1799 1800 switch (T) { 1801 default: llvm_unreachable("Not a builtin primary expression!"); 1802 case tok::kw___builtin_va_arg: { 1803 ExprResult Expr(ParseAssignmentExpression()); 1804 1805 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1806 Expr = ExprError(); 1807 1808 TypeResult Ty = ParseTypeName(); 1809 1810 if (Tok.isNot(tok::r_paren)) { 1811 Diag(Tok, diag::err_expected_rparen); 1812 Expr = ExprError(); 1813 } 1814 1815 if (Expr.isInvalid() || Ty.isInvalid()) 1816 Res = ExprError(); 1817 else 1818 Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen()); 1819 break; 1820 } 1821 case tok::kw___builtin_offsetof: { 1822 SourceLocation TypeLoc = Tok.getLocation(); 1823 TypeResult Ty = ParseTypeName(); 1824 if (Ty.isInvalid()) { 1825 SkipUntil(tok::r_paren); 1826 return ExprError(); 1827 } 1828 1829 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1830 return ExprError(); 1831 1832 // We must have at least one identifier here. 1833 if (Tok.isNot(tok::identifier)) { 1834 Diag(Tok, diag::err_expected_ident); 1835 SkipUntil(tok::r_paren); 1836 return ExprError(); 1837 } 1838 1839 // Keep track of the various subcomponents we see. 1840 SmallVector<Sema::OffsetOfComponent, 4> Comps; 1841 1842 Comps.push_back(Sema::OffsetOfComponent()); 1843 Comps.back().isBrackets = false; 1844 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1845 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1846 1847 // FIXME: This loop leaks the index expressions on error. 1848 while (1) { 1849 if (Tok.is(tok::period)) { 1850 // offsetof-member-designator: offsetof-member-designator '.' identifier 1851 Comps.push_back(Sema::OffsetOfComponent()); 1852 Comps.back().isBrackets = false; 1853 Comps.back().LocStart = ConsumeToken(); 1854 1855 if (Tok.isNot(tok::identifier)) { 1856 Diag(Tok, diag::err_expected_ident); 1857 SkipUntil(tok::r_paren); 1858 return ExprError(); 1859 } 1860 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1861 Comps.back().LocEnd = ConsumeToken(); 1862 1863 } else if (Tok.is(tok::l_square)) { 1864 if (CheckProhibitedCXX11Attribute()) 1865 return ExprError(); 1866 1867 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1868 Comps.push_back(Sema::OffsetOfComponent()); 1869 Comps.back().isBrackets = true; 1870 BalancedDelimiterTracker ST(*this, tok::l_square); 1871 ST.consumeOpen(); 1872 Comps.back().LocStart = ST.getOpenLocation(); 1873 Res = ParseExpression(); 1874 if (Res.isInvalid()) { 1875 SkipUntil(tok::r_paren); 1876 return Res; 1877 } 1878 Comps.back().U.E = Res.release(); 1879 1880 ST.consumeClose(); 1881 Comps.back().LocEnd = ST.getCloseLocation(); 1882 } else { 1883 if (Tok.isNot(tok::r_paren)) { 1884 PT.consumeClose(); 1885 Res = ExprError(); 1886 } else if (Ty.isInvalid()) { 1887 Res = ExprError(); 1888 } else { 1889 PT.consumeClose(); 1890 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc, 1891 Ty.get(), &Comps[0], Comps.size(), 1892 PT.getCloseLocation()); 1893 } 1894 break; 1895 } 1896 } 1897 break; 1898 } 1899 case tok::kw___builtin_choose_expr: { 1900 ExprResult Cond(ParseAssignmentExpression()); 1901 if (Cond.isInvalid()) { 1902 SkipUntil(tok::r_paren); 1903 return Cond; 1904 } 1905 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1906 return ExprError(); 1907 1908 ExprResult Expr1(ParseAssignmentExpression()); 1909 if (Expr1.isInvalid()) { 1910 SkipUntil(tok::r_paren); 1911 return Expr1; 1912 } 1913 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1914 return ExprError(); 1915 1916 ExprResult Expr2(ParseAssignmentExpression()); 1917 if (Expr2.isInvalid()) { 1918 SkipUntil(tok::r_paren); 1919 return Expr2; 1920 } 1921 if (Tok.isNot(tok::r_paren)) { 1922 Diag(Tok, diag::err_expected_rparen); 1923 return ExprError(); 1924 } 1925 Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(), 1926 Expr2.take(), ConsumeParen()); 1927 break; 1928 } 1929 case tok::kw___builtin_astype: { 1930 // The first argument is an expression to be converted, followed by a comma. 1931 ExprResult Expr(ParseAssignmentExpression()); 1932 if (Expr.isInvalid()) { 1933 SkipUntil(tok::r_paren); 1934 return ExprError(); 1935 } 1936 1937 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", 1938 tok::r_paren)) 1939 return ExprError(); 1940 1941 // Second argument is the type to bitcast to. 1942 TypeResult DestTy = ParseTypeName(); 1943 if (DestTy.isInvalid()) 1944 return ExprError(); 1945 1946 // Attempt to consume the r-paren. 1947 if (Tok.isNot(tok::r_paren)) { 1948 Diag(Tok, diag::err_expected_rparen); 1949 SkipUntil(tok::r_paren); 1950 return ExprError(); 1951 } 1952 1953 Res = Actions.ActOnAsTypeExpr(Expr.take(), DestTy.get(), StartLoc, 1954 ConsumeParen()); 1955 break; 1956 } 1957 } 1958 1959 if (Res.isInvalid()) 1960 return ExprError(); 1961 1962 // These can be followed by postfix-expr pieces because they are 1963 // primary-expressions. 1964 return ParsePostfixExpressionSuffix(Res.take()); 1965} 1966 1967/// ParseParenExpression - This parses the unit that starts with a '(' token, 1968/// based on what is allowed by ExprType. The actual thing parsed is returned 1969/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1970/// not the parsed cast-expression. 1971/// 1972/// \verbatim 1973/// primary-expression: [C99 6.5.1] 1974/// '(' expression ')' 1975/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1976/// postfix-expression: [C99 6.5.2] 1977/// '(' type-name ')' '{' initializer-list '}' 1978/// '(' type-name ')' '{' initializer-list ',' '}' 1979/// cast-expression: [C99 6.5.4] 1980/// '(' type-name ')' cast-expression 1981/// [ARC] bridged-cast-expression 1982/// 1983/// [ARC] bridged-cast-expression: 1984/// (__bridge type-name) cast-expression 1985/// (__bridge_transfer type-name) cast-expression 1986/// (__bridge_retained type-name) cast-expression 1987/// \endverbatim 1988ExprResult 1989Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1990 bool isTypeCast, ParsedType &CastTy, 1991 SourceLocation &RParenLoc) { 1992 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1993 BalancedDelimiterTracker T(*this, tok::l_paren); 1994 if (T.consumeOpen()) 1995 return ExprError(); 1996 SourceLocation OpenLoc = T.getOpenLocation(); 1997 1998 ExprResult Result(true); 1999 bool isAmbiguousTypeId; 2000 CastTy = ParsedType(); 2001 2002 if (Tok.is(tok::code_completion)) { 2003 Actions.CodeCompleteOrdinaryName(getCurScope(), 2004 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression 2005 : Sema::PCC_Expression); 2006 cutOffParsing(); 2007 return ExprError(); 2008 } 2009 2010 // Diagnose use of bridge casts in non-arc mode. 2011 bool BridgeCast = (getLangOpts().ObjC2 && 2012 (Tok.is(tok::kw___bridge) || 2013 Tok.is(tok::kw___bridge_transfer) || 2014 Tok.is(tok::kw___bridge_retained) || 2015 Tok.is(tok::kw___bridge_retain))); 2016 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) { 2017 StringRef BridgeCastName = Tok.getName(); 2018 SourceLocation BridgeKeywordLoc = ConsumeToken(); 2019 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) 2020 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc) 2021 << BridgeCastName 2022 << FixItHint::CreateReplacement(BridgeKeywordLoc, ""); 2023 BridgeCast = false; 2024 } 2025 2026 // None of these cases should fall through with an invalid Result 2027 // unless they've already reported an error. 2028 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 2029 Diag(Tok, diag::ext_gnu_statement_expr); 2030 Actions.ActOnStartStmtExpr(); 2031 2032 StmtResult Stmt(ParseCompoundStatement(true)); 2033 ExprType = CompoundStmt; 2034 2035 // If the substmt parsed correctly, build the AST node. 2036 if (!Stmt.isInvalid()) { 2037 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation()); 2038 } else { 2039 Actions.ActOnStmtExprError(); 2040 } 2041 } else if (ExprType >= CompoundLiteral && BridgeCast) { 2042 tok::TokenKind tokenKind = Tok.getKind(); 2043 SourceLocation BridgeKeywordLoc = ConsumeToken(); 2044 2045 // Parse an Objective-C ARC ownership cast expression. 2046 ObjCBridgeCastKind Kind; 2047 if (tokenKind == tok::kw___bridge) 2048 Kind = OBC_Bridge; 2049 else if (tokenKind == tok::kw___bridge_transfer) 2050 Kind = OBC_BridgeTransfer; 2051 else if (tokenKind == tok::kw___bridge_retained) 2052 Kind = OBC_BridgeRetained; 2053 else { 2054 // As a hopefully temporary workaround, allow __bridge_retain as 2055 // a synonym for __bridge_retained, but only in system headers. 2056 assert(tokenKind == tok::kw___bridge_retain); 2057 Kind = OBC_BridgeRetained; 2058 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) 2059 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain) 2060 << FixItHint::CreateReplacement(BridgeKeywordLoc, 2061 "__bridge_retained"); 2062 } 2063 2064 TypeResult Ty = ParseTypeName(); 2065 T.consumeClose(); 2066 RParenLoc = T.getCloseLocation(); 2067 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false); 2068 2069 if (Ty.isInvalid() || SubExpr.isInvalid()) 2070 return ExprError(); 2071 2072 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind, 2073 BridgeKeywordLoc, Ty.get(), 2074 RParenLoc, SubExpr.get()); 2075 } else if (ExprType >= CompoundLiteral && 2076 isTypeIdInParens(isAmbiguousTypeId)) { 2077 2078 // Otherwise, this is a compound literal expression or cast expression. 2079 2080 // In C++, if the type-id is ambiguous we disambiguate based on context. 2081 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 2082 // in which case we should treat it as type-id. 2083 // if stopIfCastExpr is false, we need to determine the context past the 2084 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 2085 if (isAmbiguousTypeId && !stopIfCastExpr) { 2086 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T); 2087 RParenLoc = T.getCloseLocation(); 2088 return res; 2089 } 2090 2091 // Parse the type declarator. 2092 DeclSpec DS(AttrFactory); 2093 ParseSpecifierQualifierList(DS); 2094 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 2095 ParseDeclarator(DeclaratorInfo); 2096 2097 // If our type is followed by an identifier and either ':' or ']', then 2098 // this is probably an Objective-C message send where the leading '[' is 2099 // missing. Recover as if that were the case. 2100 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) && 2101 !InMessageExpression && getLangOpts().ObjC1 && 2102 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 2103 TypeResult Ty; 2104 { 2105 InMessageExpressionRAIIObject InMessage(*this, false); 2106 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2107 } 2108 Result = ParseObjCMessageExpressionBody(SourceLocation(), 2109 SourceLocation(), 2110 Ty.get(), 0); 2111 } else { 2112 // Match the ')'. 2113 T.consumeClose(); 2114 RParenLoc = T.getCloseLocation(); 2115 if (Tok.is(tok::l_brace)) { 2116 ExprType = CompoundLiteral; 2117 TypeResult Ty; 2118 { 2119 InMessageExpressionRAIIObject InMessage(*this, false); 2120 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2121 } 2122 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 2123 } 2124 2125 if (ExprType == CastExpr) { 2126 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 2127 2128 if (DeclaratorInfo.isInvalidType()) 2129 return ExprError(); 2130 2131 // Note that this doesn't parse the subsequent cast-expression, it just 2132 // returns the parsed type to the callee. 2133 if (stopIfCastExpr) { 2134 TypeResult Ty; 2135 { 2136 InMessageExpressionRAIIObject InMessage(*this, false); 2137 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 2138 } 2139 CastTy = Ty.get(); 2140 return ExprResult(); 2141 } 2142 2143 // Reject the cast of super idiom in ObjC. 2144 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 && 2145 Tok.getIdentifierInfo() == Ident_super && 2146 getCurScope()->isInObjcMethodScope() && 2147 GetLookAheadToken(1).isNot(tok::period)) { 2148 Diag(Tok.getLocation(), diag::err_illegal_super_cast) 2149 << SourceRange(OpenLoc, RParenLoc); 2150 return ExprError(); 2151 } 2152 2153 // Parse the cast-expression that follows it next. 2154 // TODO: For cast expression with CastTy. 2155 Result = ParseCastExpression(/*isUnaryExpression=*/false, 2156 /*isAddressOfOperand=*/false, 2157 /*isTypeCast=*/IsTypeCast); 2158 if (!Result.isInvalid()) { 2159 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, 2160 DeclaratorInfo, CastTy, 2161 RParenLoc, Result.take()); 2162 } 2163 return Result; 2164 } 2165 2166 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 2167 return ExprError(); 2168 } 2169 } else if (isTypeCast) { 2170 // Parse the expression-list. 2171 InMessageExpressionRAIIObject InMessage(*this, false); 2172 2173 ExprVector ArgExprs; 2174 CommaLocsTy CommaLocs; 2175 2176 if (!ParseExpressionList(ArgExprs, CommaLocs)) { 2177 ExprType = SimpleExpr; 2178 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), 2179 ArgExprs); 2180 } 2181 } else { 2182 InMessageExpressionRAIIObject InMessage(*this, false); 2183 2184 Result = ParseExpression(MaybeTypeCast); 2185 ExprType = SimpleExpr; 2186 2187 // Don't build a paren expression unless we actually match a ')'. 2188 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 2189 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take()); 2190 } 2191 2192 // Match the ')'. 2193 if (Result.isInvalid()) { 2194 SkipUntil(tok::r_paren); 2195 return ExprError(); 2196 } 2197 2198 T.consumeClose(); 2199 RParenLoc = T.getCloseLocation(); 2200 return Result; 2201} 2202 2203/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 2204/// and we are at the left brace. 2205/// 2206/// \verbatim 2207/// postfix-expression: [C99 6.5.2] 2208/// '(' type-name ')' '{' initializer-list '}' 2209/// '(' type-name ')' '{' initializer-list ',' '}' 2210/// \endverbatim 2211ExprResult 2212Parser::ParseCompoundLiteralExpression(ParsedType Ty, 2213 SourceLocation LParenLoc, 2214 SourceLocation RParenLoc) { 2215 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 2216 if (!getLangOpts().C99) // Compound literals don't exist in C90. 2217 Diag(LParenLoc, diag::ext_c99_compound_literal); 2218 ExprResult Result = ParseInitializer(); 2219 if (!Result.isInvalid() && Ty) 2220 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take()); 2221 return Result; 2222} 2223 2224/// ParseStringLiteralExpression - This handles the various token types that 2225/// form string literals, and also handles string concatenation [C99 5.1.1.2, 2226/// translation phase #6]. 2227/// 2228/// \verbatim 2229/// primary-expression: [C99 6.5.1] 2230/// string-literal 2231/// \verbatim 2232ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) { 2233 assert(isTokenStringLiteral() && "Not a string literal!"); 2234 2235 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 2236 // considered to be strings for concatenation purposes. 2237 SmallVector<Token, 4> StringToks; 2238 2239 do { 2240 StringToks.push_back(Tok); 2241 ConsumeStringToken(); 2242 } while (isTokenStringLiteral()); 2243 2244 // Pass the set of string tokens, ready for concatenation, to the actions. 2245 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size(), 2246 AllowUserDefinedLiteral ? getCurScope() : 0); 2247} 2248 2249/// ParseGenericSelectionExpression - Parse a C11 generic-selection 2250/// [C11 6.5.1.1]. 2251/// 2252/// \verbatim 2253/// generic-selection: 2254/// _Generic ( assignment-expression , generic-assoc-list ) 2255/// generic-assoc-list: 2256/// generic-association 2257/// generic-assoc-list , generic-association 2258/// generic-association: 2259/// type-name : assignment-expression 2260/// default : assignment-expression 2261/// \endverbatim 2262ExprResult Parser::ParseGenericSelectionExpression() { 2263 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected"); 2264 SourceLocation KeyLoc = ConsumeToken(); 2265 2266 if (!getLangOpts().C11) 2267 Diag(KeyLoc, diag::ext_c11_generic_selection); 2268 2269 BalancedDelimiterTracker T(*this, tok::l_paren); 2270 if (T.expectAndConsume(diag::err_expected_lparen)) 2271 return ExprError(); 2272 2273 ExprResult ControllingExpr; 2274 { 2275 // C11 6.5.1.1p3 "The controlling expression of a generic selection is 2276 // not evaluated." 2277 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 2278 ControllingExpr = ParseAssignmentExpression(); 2279 if (ControllingExpr.isInvalid()) { 2280 SkipUntil(tok::r_paren); 2281 return ExprError(); 2282 } 2283 } 2284 2285 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "")) { 2286 SkipUntil(tok::r_paren); 2287 return ExprError(); 2288 } 2289 2290 SourceLocation DefaultLoc; 2291 TypeVector Types; 2292 ExprVector Exprs; 2293 while (1) { 2294 ParsedType Ty; 2295 if (Tok.is(tok::kw_default)) { 2296 // C11 6.5.1.1p2 "A generic selection shall have no more than one default 2297 // generic association." 2298 if (!DefaultLoc.isInvalid()) { 2299 Diag(Tok, diag::err_duplicate_default_assoc); 2300 Diag(DefaultLoc, diag::note_previous_default_assoc); 2301 SkipUntil(tok::r_paren); 2302 return ExprError(); 2303 } 2304 DefaultLoc = ConsumeToken(); 2305 Ty = ParsedType(); 2306 } else { 2307 ColonProtectionRAIIObject X(*this); 2308 TypeResult TR = ParseTypeName(); 2309 if (TR.isInvalid()) { 2310 SkipUntil(tok::r_paren); 2311 return ExprError(); 2312 } 2313 Ty = TR.release(); 2314 } 2315 Types.push_back(Ty); 2316 2317 if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "")) { 2318 SkipUntil(tok::r_paren); 2319 return ExprError(); 2320 } 2321 2322 // FIXME: These expressions should be parsed in a potentially potentially 2323 // evaluated context. 2324 ExprResult ER(ParseAssignmentExpression()); 2325 if (ER.isInvalid()) { 2326 SkipUntil(tok::r_paren); 2327 return ExprError(); 2328 } 2329 Exprs.push_back(ER.release()); 2330 2331 if (Tok.isNot(tok::comma)) 2332 break; 2333 ConsumeToken(); 2334 } 2335 2336 T.consumeClose(); 2337 if (T.getCloseLocation().isInvalid()) 2338 return ExprError(); 2339 2340 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, 2341 T.getCloseLocation(), 2342 ControllingExpr.release(), 2343 Types, Exprs); 2344} 2345 2346/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 2347/// 2348/// \verbatim 2349/// argument-expression-list: 2350/// assignment-expression 2351/// argument-expression-list , assignment-expression 2352/// 2353/// [C++] expression-list: 2354/// [C++] assignment-expression 2355/// [C++] expression-list , assignment-expression 2356/// 2357/// [C++0x] expression-list: 2358/// [C++0x] initializer-list 2359/// 2360/// [C++0x] initializer-list 2361/// [C++0x] initializer-clause ...[opt] 2362/// [C++0x] initializer-list , initializer-clause ...[opt] 2363/// 2364/// [C++0x] initializer-clause: 2365/// [C++0x] assignment-expression 2366/// [C++0x] braced-init-list 2367/// \endverbatim 2368bool Parser::ParseExpressionList(SmallVectorImpl<Expr*> &Exprs, 2369 SmallVectorImpl<SourceLocation> &CommaLocs, 2370 void (Sema::*Completer)(Scope *S, 2371 Expr *Data, 2372 llvm::ArrayRef<Expr *> Args), 2373 Expr *Data) { 2374 while (1) { 2375 if (Tok.is(tok::code_completion)) { 2376 if (Completer) 2377 (Actions.*Completer)(getCurScope(), Data, Exprs); 2378 else 2379 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 2380 cutOffParsing(); 2381 return true; 2382 } 2383 2384 ExprResult Expr; 2385 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) { 2386 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 2387 Expr = ParseBraceInitializer(); 2388 } else 2389 Expr = ParseAssignmentExpression(); 2390 2391 if (Tok.is(tok::ellipsis)) 2392 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); 2393 if (Expr.isInvalid()) 2394 return true; 2395 2396 Exprs.push_back(Expr.release()); 2397 2398 if (Tok.isNot(tok::comma)) 2399 return false; 2400 // Move to the next argument, remember where the comma was. 2401 CommaLocs.push_back(ConsumeToken()); 2402 } 2403} 2404 2405/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 2406/// 2407/// \verbatim 2408/// [clang] block-id: 2409/// [clang] specifier-qualifier-list block-declarator 2410/// \endverbatim 2411void Parser::ParseBlockId(SourceLocation CaretLoc) { 2412 if (Tok.is(tok::code_completion)) { 2413 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); 2414 return cutOffParsing(); 2415 } 2416 2417 // Parse the specifier-qualifier-list piece. 2418 DeclSpec DS(AttrFactory); 2419 ParseSpecifierQualifierList(DS); 2420 2421 // Parse the block-declarator. 2422 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 2423 ParseDeclarator(DeclaratorInfo); 2424 2425 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 2426 DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation()); 2427 2428 MaybeParseGNUAttributes(DeclaratorInfo); 2429 2430 // Inform sema that we are starting a block. 2431 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope()); 2432} 2433 2434/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 2435/// like ^(int x){ return x+1; } 2436/// 2437/// \verbatim 2438/// block-literal: 2439/// [clang] '^' block-args[opt] compound-statement 2440/// [clang] '^' block-id compound-statement 2441/// [clang] block-args: 2442/// [clang] '(' parameter-list ')' 2443/// \endverbatim 2444ExprResult Parser::ParseBlockLiteralExpression() { 2445 assert(Tok.is(tok::caret) && "block literal starts with ^"); 2446 SourceLocation CaretLoc = ConsumeToken(); 2447 2448 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 2449 "block literal parsing"); 2450 2451 // Enter a scope to hold everything within the block. This includes the 2452 // argument decls, decls within the compound expression, etc. This also 2453 // allows determining whether a variable reference inside the block is 2454 // within or outside of the block. 2455 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 2456 Scope::DeclScope); 2457 2458 // Inform sema that we are starting a block. 2459 Actions.ActOnBlockStart(CaretLoc, getCurScope()); 2460 2461 // Parse the return type if present. 2462 DeclSpec DS(AttrFactory); 2463 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 2464 // FIXME: Since the return type isn't actually parsed, it can't be used to 2465 // fill ParamInfo with an initial valid range, so do it manually. 2466 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 2467 2468 // If this block has arguments, parse them. There is no ambiguity here with 2469 // the expression case, because the expression case requires a parameter list. 2470 if (Tok.is(tok::l_paren)) { 2471 ParseParenDeclarator(ParamInfo); 2472 // Parse the pieces after the identifier as if we had "int(...)". 2473 // SetIdentifier sets the source range end, but in this case we're past 2474 // that location. 2475 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 2476 ParamInfo.SetIdentifier(0, CaretLoc); 2477 ParamInfo.SetRangeEnd(Tmp); 2478 if (ParamInfo.isInvalidType()) { 2479 // If there was an error parsing the arguments, they may have 2480 // tried to use ^(x+y) which requires an argument list. Just 2481 // skip the whole block literal. 2482 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2483 return ExprError(); 2484 } 2485 2486 MaybeParseGNUAttributes(ParamInfo); 2487 2488 // Inform sema that we are starting a block. 2489 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope()); 2490 } else if (!Tok.is(tok::l_brace)) { 2491 ParseBlockId(CaretLoc); 2492 } else { 2493 // Otherwise, pretend we saw (void). 2494 ParsedAttributes attrs(AttrFactory); 2495 SourceLocation NoLoc; 2496 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true, 2497 /*IsAmbiguous=*/false, 2498 /*RParenLoc=*/NoLoc, 2499 /*ArgInfo=*/0, 2500 /*NumArgs=*/0, 2501 /*EllipsisLoc=*/NoLoc, 2502 /*RParenLoc=*/NoLoc, 2503 /*TypeQuals=*/0, 2504 /*RefQualifierIsLvalueRef=*/true, 2505 /*RefQualifierLoc=*/NoLoc, 2506 /*ConstQualifierLoc=*/NoLoc, 2507 /*VolatileQualifierLoc=*/NoLoc, 2508 /*MutableLoc=*/NoLoc, 2509 EST_None, 2510 /*ESpecLoc=*/NoLoc, 2511 /*Exceptions=*/0, 2512 /*ExceptionRanges=*/0, 2513 /*NumExceptions=*/0, 2514 /*NoexceptExpr=*/0, 2515 CaretLoc, CaretLoc, 2516 ParamInfo), 2517 attrs, CaretLoc); 2518 2519 MaybeParseGNUAttributes(ParamInfo); 2520 2521 // Inform sema that we are starting a block. 2522 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope()); 2523 } 2524 2525 2526 ExprResult Result(true); 2527 if (!Tok.is(tok::l_brace)) { 2528 // Saw something like: ^expr 2529 Diag(Tok, diag::err_expected_expression); 2530 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2531 return ExprError(); 2532 } 2533 2534 StmtResult Stmt(ParseCompoundStatementBody()); 2535 BlockScope.Exit(); 2536 if (!Stmt.isInvalid()) 2537 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope()); 2538 else 2539 Actions.ActOnBlockError(CaretLoc, getCurScope()); 2540 return Result; 2541} 2542 2543/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals. 2544/// 2545/// '__objc_yes' 2546/// '__objc_no' 2547ExprResult Parser::ParseObjCBoolLiteral() { 2548 tok::TokenKind Kind = Tok.getKind(); 2549 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind); 2550} 2551