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