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