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