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