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