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