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