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