clang API Documentation
00001 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 /// 00010 /// \file 00011 /// \brief Provides the Expression parsing implementation. 00012 /// 00013 /// Expressions in C99 basically consist of a bunch of binary operators with 00014 /// unary operators and other random stuff at the leaves. 00015 /// 00016 /// In the C99 grammar, these unary operators bind tightest and are represented 00017 /// as the 'cast-expression' production. Everything else is either a binary 00018 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are 00019 /// handled by ParseCastExpression, the higher level pieces are handled by 00020 /// ParseBinaryExpression. 00021 /// 00022 //===----------------------------------------------------------------------===// 00023 00024 #include "clang/Parse/Parser.h" 00025 #include "RAIIObjectsForParser.h" 00026 #include "clang/AST/ASTContext.h" 00027 #include "clang/Basic/PrettyStackTrace.h" 00028 #include "clang/Sema/DeclSpec.h" 00029 #include "clang/Sema/ParsedTemplate.h" 00030 #include "clang/Sema/Scope.h" 00031 #include "clang/Sema/TypoCorrection.h" 00032 #include "llvm/ADT/SmallString.h" 00033 #include "llvm/ADT/SmallVector.h" 00034 using namespace clang; 00035 00036 /// \brief Simple precedence-based parser for binary/ternary operators. 00037 /// 00038 /// Note: we diverge from the C99 grammar when parsing the assignment-expression 00039 /// production. C99 specifies that the LHS of an assignment operator should be 00040 /// parsed as a unary-expression, but consistency dictates that it be a 00041 /// conditional-expession. In practice, the important thing here is that the 00042 /// LHS of an assignment has to be an l-value, which productions between 00043 /// unary-expression and conditional-expression don't produce. Because we want 00044 /// consistency, we parse the LHS as a conditional-expression, then check for 00045 /// l-value-ness in semantic analysis stages. 00046 /// 00047 /// \verbatim 00048 /// pm-expression: [C++ 5.5] 00049 /// cast-expression 00050 /// pm-expression '.*' cast-expression 00051 /// pm-expression '->*' cast-expression 00052 /// 00053 /// multiplicative-expression: [C99 6.5.5] 00054 /// Note: in C++, apply pm-expression instead of cast-expression 00055 /// cast-expression 00056 /// multiplicative-expression '*' cast-expression 00057 /// multiplicative-expression '/' cast-expression 00058 /// multiplicative-expression '%' cast-expression 00059 /// 00060 /// additive-expression: [C99 6.5.6] 00061 /// multiplicative-expression 00062 /// additive-expression '+' multiplicative-expression 00063 /// additive-expression '-' multiplicative-expression 00064 /// 00065 /// shift-expression: [C99 6.5.7] 00066 /// additive-expression 00067 /// shift-expression '<<' additive-expression 00068 /// shift-expression '>>' additive-expression 00069 /// 00070 /// relational-expression: [C99 6.5.8] 00071 /// shift-expression 00072 /// relational-expression '<' shift-expression 00073 /// relational-expression '>' shift-expression 00074 /// relational-expression '<=' shift-expression 00075 /// relational-expression '>=' shift-expression 00076 /// 00077 /// equality-expression: [C99 6.5.9] 00078 /// relational-expression 00079 /// equality-expression '==' relational-expression 00080 /// equality-expression '!=' relational-expression 00081 /// 00082 /// AND-expression: [C99 6.5.10] 00083 /// equality-expression 00084 /// AND-expression '&' equality-expression 00085 /// 00086 /// exclusive-OR-expression: [C99 6.5.11] 00087 /// AND-expression 00088 /// exclusive-OR-expression '^' AND-expression 00089 /// 00090 /// inclusive-OR-expression: [C99 6.5.12] 00091 /// exclusive-OR-expression 00092 /// inclusive-OR-expression '|' exclusive-OR-expression 00093 /// 00094 /// logical-AND-expression: [C99 6.5.13] 00095 /// inclusive-OR-expression 00096 /// logical-AND-expression '&&' inclusive-OR-expression 00097 /// 00098 /// logical-OR-expression: [C99 6.5.14] 00099 /// logical-AND-expression 00100 /// logical-OR-expression '||' logical-AND-expression 00101 /// 00102 /// conditional-expression: [C99 6.5.15] 00103 /// logical-OR-expression 00104 /// logical-OR-expression '?' expression ':' conditional-expression 00105 /// [GNU] logical-OR-expression '?' ':' conditional-expression 00106 /// [C++] the third operand is an assignment-expression 00107 /// 00108 /// assignment-expression: [C99 6.5.16] 00109 /// conditional-expression 00110 /// unary-expression assignment-operator assignment-expression 00111 /// [C++] throw-expression [C++ 15] 00112 /// 00113 /// assignment-operator: one of 00114 /// = *= /= %= += -= <<= >>= &= ^= |= 00115 /// 00116 /// expression: [C99 6.5.17] 00117 /// assignment-expression ...[opt] 00118 /// expression ',' assignment-expression ...[opt] 00119 /// \endverbatim 00120 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) { 00121 ExprResult LHS(ParseAssignmentExpression(isTypeCast)); 00122 return ParseRHSOfBinaryExpression(LHS, prec::Comma); 00123 } 00124 00125 /// This routine is called when the '@' is seen and consumed. 00126 /// Current token is an Identifier and is not a 'try'. This 00127 /// routine is necessary to disambiguate \@try-statement from, 00128 /// for example, \@encode-expression. 00129 /// 00130 ExprResult 00131 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) { 00132 ExprResult LHS(ParseObjCAtExpression(AtLoc)); 00133 return ParseRHSOfBinaryExpression(LHS, prec::Comma); 00134 } 00135 00136 /// This routine is called when a leading '__extension__' is seen and 00137 /// consumed. This is necessary because the token gets consumed in the 00138 /// process of disambiguating between an expression and a declaration. 00139 ExprResult 00140 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) { 00141 ExprResult LHS(true); 00142 { 00143 // Silence extension warnings in the sub-expression 00144 ExtensionRAIIObject O(Diags); 00145 00146 LHS = ParseCastExpression(false); 00147 } 00148 00149 if (!LHS.isInvalid()) 00150 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__, 00151 LHS.get()); 00152 00153 return ParseRHSOfBinaryExpression(LHS, prec::Comma); 00154 } 00155 00156 /// \brief Parse an expr that doesn't include (top-level) commas. 00157 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) { 00158 if (Tok.is(tok::code_completion)) { 00159 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 00160 cutOffParsing(); 00161 return ExprError(); 00162 } 00163 00164 if (Tok.is(tok::kw_throw)) 00165 return ParseThrowExpression(); 00166 00167 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false, 00168 /*isAddressOfOperand=*/false, 00169 isTypeCast); 00170 return ParseRHSOfBinaryExpression(LHS, prec::Assignment); 00171 } 00172 00173 /// \brief Parse an assignment expression where part of an Objective-C message 00174 /// send has already been parsed. 00175 /// 00176 /// In this case \p LBracLoc indicates the location of the '[' of the message 00177 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating 00178 /// the receiver of the message. 00179 /// 00180 /// Since this handles full assignment-expression's, it handles postfix 00181 /// expressions and other binary operators for these expressions as well. 00182 ExprResult 00183 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc, 00184 SourceLocation SuperLoc, 00185 ParsedType ReceiverType, 00186 Expr *ReceiverExpr) { 00187 ExprResult R 00188 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc, 00189 ReceiverType, ReceiverExpr); 00190 R = ParsePostfixExpressionSuffix(R); 00191 return ParseRHSOfBinaryExpression(R, prec::Assignment); 00192 } 00193 00194 00195 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) { 00196 // C++03 [basic.def.odr]p2: 00197 // An expression is potentially evaluated unless it appears where an 00198 // integral constant expression is required (see 5.19) [...]. 00199 // C++98 and C++11 have no such rule, but this is only a defect in C++98. 00200 EnterExpressionEvaluationContext Unevaluated(Actions, 00201 Sema::ConstantEvaluated); 00202 00203 ExprResult LHS(ParseCastExpression(false, false, isTypeCast)); 00204 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 00205 return Actions.ActOnConstantExpression(Res); 00206 } 00207 00208 bool Parser::isNotExpressionStart() { 00209 tok::TokenKind K = Tok.getKind(); 00210 if (K == tok::l_brace || K == tok::r_brace || 00211 K == tok::kw_for || K == tok::kw_while || 00212 K == tok::kw_if || K == tok::kw_else || 00213 K == tok::kw_goto || K == tok::kw_try) 00214 return true; 00215 // If this is a decl-specifier, we can't be at the start of an expression. 00216 return isKnownToBeDeclarationSpecifier(); 00217 } 00218 00219 static bool isFoldOperator(prec::Level Level) { 00220 return Level > prec::Unknown && Level != prec::Conditional; 00221 } 00222 static bool isFoldOperator(tok::TokenKind Kind) { 00223 return isFoldOperator(getBinOpPrecedence(Kind, false, true)); 00224 } 00225 00226 /// \brief Parse a binary expression that starts with \p LHS and has a 00227 /// precedence of at least \p MinPrec. 00228 ExprResult 00229 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) { 00230 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(), 00231 GreaterThanIsOperator, 00232 getLangOpts().CPlusPlus11); 00233 SourceLocation ColonLoc; 00234 00235 while (1) { 00236 // If this token has a lower precedence than we are allowed to parse (e.g. 00237 // because we are called recursively, or because the token is not a binop), 00238 // then we are done! 00239 if (NextTokPrec < MinPrec) 00240 return LHS; 00241 00242 // Consume the operator, saving the operator token for error reporting. 00243 Token OpToken = Tok; 00244 ConsumeToken(); 00245 00246 // Bail out when encountering a comma followed by a token which can't 00247 // possibly be the start of an expression. For instance: 00248 // int f() { return 1, } 00249 // We can't do this before consuming the comma, because 00250 // isNotExpressionStart() looks at the token stream. 00251 if (OpToken.is(tok::comma) && isNotExpressionStart()) { 00252 PP.EnterToken(Tok); 00253 Tok = OpToken; 00254 return LHS; 00255 } 00256 00257 // If the next token is an ellipsis, then this is a fold-expression. Leave 00258 // it alone so we can handle it in the paren expression. 00259 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) { 00260 // FIXME: We can't check this via lookahead before we consume the token 00261 // because that tickles a lexer bug. 00262 PP.EnterToken(Tok); 00263 Tok = OpToken; 00264 return LHS; 00265 } 00266 00267 // Special case handling for the ternary operator. 00268 ExprResult TernaryMiddle(true); 00269 if (NextTokPrec == prec::Conditional) { 00270 if (Tok.isNot(tok::colon)) { 00271 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 00272 ColonProtectionRAIIObject X(*this); 00273 00274 // Handle this production specially: 00275 // logical-OR-expression '?' expression ':' conditional-expression 00276 // In particular, the RHS of the '?' is 'expression', not 00277 // 'logical-OR-expression' as we might expect. 00278 TernaryMiddle = ParseExpression(); 00279 if (TernaryMiddle.isInvalid()) { 00280 LHS = ExprError(); 00281 TernaryMiddle = nullptr; 00282 } 00283 } else { 00284 // Special case handling of "X ? Y : Z" where Y is empty: 00285 // logical-OR-expression '?' ':' conditional-expression [GNU] 00286 TernaryMiddle = nullptr; 00287 Diag(Tok, diag::ext_gnu_conditional_expr); 00288 } 00289 00290 if (!TryConsumeToken(tok::colon, ColonLoc)) { 00291 // Otherwise, we're missing a ':'. Assume that this was a typo that 00292 // the user forgot. If we're not in a macro expansion, we can suggest 00293 // a fixit hint. If there were two spaces before the current token, 00294 // suggest inserting the colon in between them, otherwise insert ": ". 00295 SourceLocation FILoc = Tok.getLocation(); 00296 const char *FIText = ": "; 00297 const SourceManager &SM = PP.getSourceManager(); 00298 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) { 00299 assert(FILoc.isFileID()); 00300 bool IsInvalid = false; 00301 const char *SourcePtr = 00302 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid); 00303 if (!IsInvalid && *SourcePtr == ' ') { 00304 SourcePtr = 00305 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid); 00306 if (!IsInvalid && *SourcePtr == ' ') { 00307 FILoc = FILoc.getLocWithOffset(-1); 00308 FIText = ":"; 00309 } 00310 } 00311 } 00312 00313 Diag(Tok, diag::err_expected) 00314 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText); 00315 Diag(OpToken, diag::note_matching) << tok::question; 00316 ColonLoc = Tok.getLocation(); 00317 } 00318 } 00319 00320 // Code completion for the right-hand side of an assignment expression 00321 // goes through a special hook that takes the left-hand side into account. 00322 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) { 00323 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get()); 00324 cutOffParsing(); 00325 return ExprError(); 00326 } 00327 00328 // Parse another leaf here for the RHS of the operator. 00329 // ParseCastExpression works here because all RHS expressions in C have it 00330 // as a prefix, at least. However, in C++, an assignment-expression could 00331 // be a throw-expression, which is not a valid cast-expression. 00332 // Therefore we need some special-casing here. 00333 // Also note that the third operand of the conditional operator is 00334 // an assignment-expression in C++, and in C++11, we can have a 00335 // braced-init-list on the RHS of an assignment. For better diagnostics, 00336 // parse as if we were allowed braced-init-lists everywhere, and check that 00337 // they only appear on the RHS of assignments later. 00338 ExprResult RHS; 00339 bool RHSIsInitList = false; 00340 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 00341 RHS = ParseBraceInitializer(); 00342 RHSIsInitList = true; 00343 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional) 00344 RHS = ParseAssignmentExpression(); 00345 else 00346 RHS = ParseCastExpression(false); 00347 00348 if (RHS.isInvalid()) 00349 LHS = ExprError(); 00350 00351 // Remember the precedence of this operator and get the precedence of the 00352 // operator immediately to the right of the RHS. 00353 prec::Level ThisPrec = NextTokPrec; 00354 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, 00355 getLangOpts().CPlusPlus11); 00356 00357 // Assignment and conditional expressions are right-associative. 00358 bool isRightAssoc = ThisPrec == prec::Conditional || 00359 ThisPrec == prec::Assignment; 00360 00361 // Get the precedence of the operator to the right of the RHS. If it binds 00362 // more tightly with RHS than we do, evaluate it completely first. 00363 if (ThisPrec < NextTokPrec || 00364 (ThisPrec == NextTokPrec && isRightAssoc)) { 00365 if (!RHS.isInvalid() && RHSIsInitList) { 00366 Diag(Tok, diag::err_init_list_bin_op) 00367 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get()); 00368 RHS = ExprError(); 00369 } 00370 // If this is left-associative, only parse things on the RHS that bind 00371 // more tightly than the current operator. If it is left-associative, it 00372 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as 00373 // A=(B=(C=D)), where each paren is a level of recursion here. 00374 // The function takes ownership of the RHS. 00375 RHS = ParseRHSOfBinaryExpression(RHS, 00376 static_cast<prec::Level>(ThisPrec + !isRightAssoc)); 00377 RHSIsInitList = false; 00378 00379 if (RHS.isInvalid()) 00380 LHS = ExprError(); 00381 00382 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, 00383 getLangOpts().CPlusPlus11); 00384 } 00385 00386 if (!RHS.isInvalid() && RHSIsInitList) { 00387 if (ThisPrec == prec::Assignment) { 00388 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists) 00389 << Actions.getExprRange(RHS.get()); 00390 } else { 00391 Diag(OpToken, diag::err_init_list_bin_op) 00392 << /*RHS*/1 << PP.getSpelling(OpToken) 00393 << Actions.getExprRange(RHS.get()); 00394 LHS = ExprError(); 00395 } 00396 } 00397 00398 if (!LHS.isInvalid()) { 00399 // Combine the LHS and RHS into the LHS (e.g. build AST). 00400 if (TernaryMiddle.isInvalid()) { 00401 // If we're using '>>' as an operator within a template 00402 // argument list (in C++98), suggest the addition of 00403 // parentheses so that the code remains well-formed in C++0x. 00404 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater)) 00405 SuggestParentheses(OpToken.getLocation(), 00406 diag::warn_cxx11_right_shift_in_template_arg, 00407 SourceRange(Actions.getExprRange(LHS.get()).getBegin(), 00408 Actions.getExprRange(RHS.get()).getEnd())); 00409 00410 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(), 00411 OpToken.getKind(), LHS.get(), RHS.get()); 00412 } else 00413 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc, 00414 LHS.get(), TernaryMiddle.get(), 00415 RHS.get()); 00416 } 00417 } 00418 } 00419 00420 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true, 00421 /// parse a unary-expression. 00422 /// 00423 /// \p isAddressOfOperand exists because an id-expression that is the 00424 /// operand of address-of gets special treatment due to member pointers. 00425 /// 00426 ExprResult Parser::ParseCastExpression(bool isUnaryExpression, 00427 bool isAddressOfOperand, 00428 TypeCastState isTypeCast) { 00429 bool NotCastExpr; 00430 ExprResult Res = ParseCastExpression(isUnaryExpression, 00431 isAddressOfOperand, 00432 NotCastExpr, 00433 isTypeCast); 00434 if (NotCastExpr) 00435 Diag(Tok, diag::err_expected_expression); 00436 return Res; 00437 } 00438 00439 namespace { 00440 class CastExpressionIdValidator : public CorrectionCandidateCallback { 00441 public: 00442 CastExpressionIdValidator(bool AllowTypes, bool AllowNonTypes) 00443 : AllowNonTypes(AllowNonTypes) { 00444 WantTypeSpecifiers = AllowTypes; 00445 } 00446 00447 bool ValidateCandidate(const TypoCorrection &candidate) override { 00448 NamedDecl *ND = candidate.getCorrectionDecl(); 00449 if (!ND) 00450 return candidate.isKeyword(); 00451 00452 if (isa<TypeDecl>(ND)) 00453 return WantTypeSpecifiers; 00454 return AllowNonTypes && 00455 CorrectionCandidateCallback::ValidateCandidate(candidate); 00456 } 00457 00458 private: 00459 bool AllowNonTypes; 00460 }; 00461 } 00462 00463 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse 00464 /// a unary-expression. 00465 /// 00466 /// \p isAddressOfOperand exists because an id-expression that is the operand 00467 /// of address-of gets special treatment due to member pointers. NotCastExpr 00468 /// is set to true if the token is not the start of a cast-expression, and no 00469 /// diagnostic is emitted in this case. 00470 /// 00471 /// \verbatim 00472 /// cast-expression: [C99 6.5.4] 00473 /// unary-expression 00474 /// '(' type-name ')' cast-expression 00475 /// 00476 /// unary-expression: [C99 6.5.3] 00477 /// postfix-expression 00478 /// '++' unary-expression 00479 /// '--' unary-expression 00480 /// unary-operator cast-expression 00481 /// 'sizeof' unary-expression 00482 /// 'sizeof' '(' type-name ')' 00483 /// [C++11] 'sizeof' '...' '(' identifier ')' 00484 /// [GNU] '__alignof' unary-expression 00485 /// [GNU] '__alignof' '(' type-name ')' 00486 /// [C11] '_Alignof' '(' type-name ')' 00487 /// [C++11] 'alignof' '(' type-id ')' 00488 /// [GNU] '&&' identifier 00489 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7] 00490 /// [C++] new-expression 00491 /// [C++] delete-expression 00492 /// 00493 /// unary-operator: one of 00494 /// '&' '*' '+' '-' '~' '!' 00495 /// [GNU] '__extension__' '__real' '__imag' 00496 /// 00497 /// primary-expression: [C99 6.5.1] 00498 /// [C99] identifier 00499 /// [C++] id-expression 00500 /// constant 00501 /// string-literal 00502 /// [C++] boolean-literal [C++ 2.13.5] 00503 /// [C++11] 'nullptr' [C++11 2.14.7] 00504 /// [C++11] user-defined-literal 00505 /// '(' expression ')' 00506 /// [C11] generic-selection 00507 /// '__func__' [C99 6.4.2.2] 00508 /// [GNU] '__FUNCTION__' 00509 /// [MS] '__FUNCDNAME__' 00510 /// [MS] 'L__FUNCTION__' 00511 /// [GNU] '__PRETTY_FUNCTION__' 00512 /// [GNU] '(' compound-statement ')' 00513 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 00514 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 00515 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 00516 /// assign-expr ')' 00517 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 00518 /// [GNU] '__null' 00519 /// [OBJC] '[' objc-message-expr ']' 00520 /// [OBJC] '\@selector' '(' objc-selector-arg ')' 00521 /// [OBJC] '\@protocol' '(' identifier ')' 00522 /// [OBJC] '\@encode' '(' type-name ')' 00523 /// [OBJC] objc-string-literal 00524 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 00525 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3] 00526 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 00527 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3] 00528 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 00529 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 00530 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 00531 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 00532 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1] 00533 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1] 00534 /// [C++] 'this' [C++ 9.3.2] 00535 /// [G++] unary-type-trait '(' type-id ')' 00536 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO] 00537 /// [EMBT] array-type-trait '(' type-id ',' integer ')' 00538 /// [clang] '^' block-literal 00539 /// 00540 /// constant: [C99 6.4.4] 00541 /// integer-constant 00542 /// floating-constant 00543 /// enumeration-constant -> identifier 00544 /// character-constant 00545 /// 00546 /// id-expression: [C++ 5.1] 00547 /// unqualified-id 00548 /// qualified-id 00549 /// 00550 /// unqualified-id: [C++ 5.1] 00551 /// identifier 00552 /// operator-function-id 00553 /// conversion-function-id 00554 /// '~' class-name 00555 /// template-id 00556 /// 00557 /// new-expression: [C++ 5.3.4] 00558 /// '::'[opt] 'new' new-placement[opt] new-type-id 00559 /// new-initializer[opt] 00560 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 00561 /// new-initializer[opt] 00562 /// 00563 /// delete-expression: [C++ 5.3.5] 00564 /// '::'[opt] 'delete' cast-expression 00565 /// '::'[opt] 'delete' '[' ']' cast-expression 00566 /// 00567 /// [GNU/Embarcadero] unary-type-trait: 00568 /// '__is_arithmetic' 00569 /// '__is_floating_point' 00570 /// '__is_integral' 00571 /// '__is_lvalue_expr' 00572 /// '__is_rvalue_expr' 00573 /// '__is_complete_type' 00574 /// '__is_void' 00575 /// '__is_array' 00576 /// '__is_function' 00577 /// '__is_reference' 00578 /// '__is_lvalue_reference' 00579 /// '__is_rvalue_reference' 00580 /// '__is_fundamental' 00581 /// '__is_object' 00582 /// '__is_scalar' 00583 /// '__is_compound' 00584 /// '__is_pointer' 00585 /// '__is_member_object_pointer' 00586 /// '__is_member_function_pointer' 00587 /// '__is_member_pointer' 00588 /// '__is_const' 00589 /// '__is_volatile' 00590 /// '__is_trivial' 00591 /// '__is_standard_layout' 00592 /// '__is_signed' 00593 /// '__is_unsigned' 00594 /// 00595 /// [GNU] unary-type-trait: 00596 /// '__has_nothrow_assign' 00597 /// '__has_nothrow_copy' 00598 /// '__has_nothrow_constructor' 00599 /// '__has_trivial_assign' [TODO] 00600 /// '__has_trivial_copy' [TODO] 00601 /// '__has_trivial_constructor' 00602 /// '__has_trivial_destructor' 00603 /// '__has_virtual_destructor' 00604 /// '__is_abstract' [TODO] 00605 /// '__is_class' 00606 /// '__is_empty' [TODO] 00607 /// '__is_enum' 00608 /// '__is_final' 00609 /// '__is_pod' 00610 /// '__is_polymorphic' 00611 /// '__is_sealed' [MS] 00612 /// '__is_trivial' 00613 /// '__is_union' 00614 /// 00615 /// [Clang] unary-type-trait: 00616 /// '__trivially_copyable' 00617 /// 00618 /// binary-type-trait: 00619 /// [GNU] '__is_base_of' 00620 /// [MS] '__is_convertible_to' 00621 /// '__is_convertible' 00622 /// '__is_same' 00623 /// 00624 /// [Embarcadero] array-type-trait: 00625 /// '__array_rank' 00626 /// '__array_extent' 00627 /// 00628 /// [Embarcadero] expression-trait: 00629 /// '__is_lvalue_expr' 00630 /// '__is_rvalue_expr' 00631 /// \endverbatim 00632 /// 00633 ExprResult Parser::ParseCastExpression(bool isUnaryExpression, 00634 bool isAddressOfOperand, 00635 bool &NotCastExpr, 00636 TypeCastState isTypeCast) { 00637 ExprResult Res; 00638 tok::TokenKind SavedKind = Tok.getKind(); 00639 NotCastExpr = false; 00640 00641 // This handles all of cast-expression, unary-expression, postfix-expression, 00642 // and primary-expression. We handle them together like this for efficiency 00643 // and to simplify handling of an expression starting with a '(' token: which 00644 // may be one of a parenthesized expression, cast-expression, compound literal 00645 // expression, or statement expression. 00646 // 00647 // If the parsed tokens consist of a primary-expression, the cases below 00648 // break out of the switch; at the end we call ParsePostfixExpressionSuffix 00649 // to handle the postfix expression suffixes. Cases that cannot be followed 00650 // by postfix exprs should return without invoking 00651 // ParsePostfixExpressionSuffix. 00652 switch (SavedKind) { 00653 case tok::l_paren: { 00654 // If this expression is limited to being a unary-expression, the parent can 00655 // not start a cast expression. 00656 ParenParseOption ParenExprType = 00657 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral 00658 : CastExpr; 00659 ParsedType CastTy; 00660 SourceLocation RParenLoc; 00661 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/, 00662 isTypeCast == IsTypeCast, CastTy, RParenLoc); 00663 00664 switch (ParenExprType) { 00665 case SimpleExpr: break; // Nothing else to do. 00666 case CompoundStmt: break; // Nothing else to do. 00667 case CompoundLiteral: 00668 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of 00669 // postfix-expression exist, parse them now. 00670 break; 00671 case CastExpr: 00672 // We have parsed the cast-expression and no postfix-expr pieces are 00673 // following. 00674 return Res; 00675 } 00676 00677 break; 00678 } 00679 00680 // primary-expression 00681 case tok::numeric_constant: 00682 // constant: integer-constant 00683 // constant: floating-constant 00684 00685 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope()); 00686 ConsumeToken(); 00687 break; 00688 00689 case tok::kw_true: 00690 case tok::kw_false: 00691 return ParseCXXBoolLiteral(); 00692 00693 case tok::kw___objc_yes: 00694 case tok::kw___objc_no: 00695 return ParseObjCBoolLiteral(); 00696 00697 case tok::kw_nullptr: 00698 Diag(Tok, diag::warn_cxx98_compat_nullptr); 00699 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken()); 00700 00701 case tok::annot_primary_expr: 00702 assert(Res.get() == nullptr && "Stray primary-expression annotation?"); 00703 Res = getExprAnnotation(Tok); 00704 ConsumeToken(); 00705 break; 00706 00707 case tok::kw___super: 00708 case tok::kw_decltype: 00709 // Annotate the token and tail recurse. 00710 if (TryAnnotateTypeOrScopeToken()) 00711 return ExprError(); 00712 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super)); 00713 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 00714 00715 case tok::identifier: { // primary-expression: identifier 00716 // unqualified-id: identifier 00717 // constant: enumeration-constant 00718 // Turn a potentially qualified name into a annot_typename or 00719 // annot_cxxscope if it would be valid. This handles things like x::y, etc. 00720 if (getLangOpts().CPlusPlus) { 00721 // Avoid the unnecessary parse-time lookup in the common case 00722 // where the syntax forbids a type. 00723 const Token &Next = NextToken(); 00724 00725 // If this identifier was reverted from a token ID, and the next token 00726 // is a parenthesis, this is likely to be a use of a type trait. Check 00727 // those tokens. 00728 if (Next.is(tok::l_paren) && 00729 Tok.is(tok::identifier) && 00730 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) { 00731 IdentifierInfo *II = Tok.getIdentifierInfo(); 00732 // Build up the mapping of revertible type traits, for future use. 00733 if (RevertibleTypeTraits.empty()) { 00734 #define RTT_JOIN(X,Y) X##Y 00735 #define REVERTIBLE_TYPE_TRAIT(Name) \ 00736 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \ 00737 = RTT_JOIN(tok::kw_,Name) 00738 00739 REVERTIBLE_TYPE_TRAIT(__is_abstract); 00740 REVERTIBLE_TYPE_TRAIT(__is_arithmetic); 00741 REVERTIBLE_TYPE_TRAIT(__is_array); 00742 REVERTIBLE_TYPE_TRAIT(__is_base_of); 00743 REVERTIBLE_TYPE_TRAIT(__is_class); 00744 REVERTIBLE_TYPE_TRAIT(__is_complete_type); 00745 REVERTIBLE_TYPE_TRAIT(__is_compound); 00746 REVERTIBLE_TYPE_TRAIT(__is_const); 00747 REVERTIBLE_TYPE_TRAIT(__is_constructible); 00748 REVERTIBLE_TYPE_TRAIT(__is_convertible); 00749 REVERTIBLE_TYPE_TRAIT(__is_convertible_to); 00750 REVERTIBLE_TYPE_TRAIT(__is_destructible); 00751 REVERTIBLE_TYPE_TRAIT(__is_empty); 00752 REVERTIBLE_TYPE_TRAIT(__is_enum); 00753 REVERTIBLE_TYPE_TRAIT(__is_floating_point); 00754 REVERTIBLE_TYPE_TRAIT(__is_final); 00755 REVERTIBLE_TYPE_TRAIT(__is_function); 00756 REVERTIBLE_TYPE_TRAIT(__is_fundamental); 00757 REVERTIBLE_TYPE_TRAIT(__is_integral); 00758 REVERTIBLE_TYPE_TRAIT(__is_interface_class); 00759 REVERTIBLE_TYPE_TRAIT(__is_literal); 00760 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr); 00761 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference); 00762 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer); 00763 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer); 00764 REVERTIBLE_TYPE_TRAIT(__is_member_pointer); 00765 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable); 00766 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible); 00767 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible); 00768 REVERTIBLE_TYPE_TRAIT(__is_object); 00769 REVERTIBLE_TYPE_TRAIT(__is_pod); 00770 REVERTIBLE_TYPE_TRAIT(__is_pointer); 00771 REVERTIBLE_TYPE_TRAIT(__is_polymorphic); 00772 REVERTIBLE_TYPE_TRAIT(__is_reference); 00773 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr); 00774 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference); 00775 REVERTIBLE_TYPE_TRAIT(__is_same); 00776 REVERTIBLE_TYPE_TRAIT(__is_scalar); 00777 REVERTIBLE_TYPE_TRAIT(__is_sealed); 00778 REVERTIBLE_TYPE_TRAIT(__is_signed); 00779 REVERTIBLE_TYPE_TRAIT(__is_standard_layout); 00780 REVERTIBLE_TYPE_TRAIT(__is_trivial); 00781 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable); 00782 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible); 00783 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable); 00784 REVERTIBLE_TYPE_TRAIT(__is_union); 00785 REVERTIBLE_TYPE_TRAIT(__is_unsigned); 00786 REVERTIBLE_TYPE_TRAIT(__is_void); 00787 REVERTIBLE_TYPE_TRAIT(__is_volatile); 00788 #undef REVERTIBLE_TYPE_TRAIT 00789 #undef RTT_JOIN 00790 } 00791 00792 // If we find that this is in fact the name of a type trait, 00793 // update the token kind in place and parse again to treat it as 00794 // the appropriate kind of type trait. 00795 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known 00796 = RevertibleTypeTraits.find(II); 00797 if (Known != RevertibleTypeTraits.end()) { 00798 Tok.setKind(Known->second); 00799 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 00800 NotCastExpr, isTypeCast); 00801 } 00802 } 00803 00804 if (Next.is(tok::coloncolon) || 00805 (!ColonIsSacred && Next.is(tok::colon)) || 00806 Next.is(tok::less) || 00807 Next.is(tok::l_paren) || 00808 Next.is(tok::l_brace)) { 00809 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 00810 if (TryAnnotateTypeOrScopeToken()) 00811 return ExprError(); 00812 if (!Tok.is(tok::identifier)) 00813 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 00814 } 00815 } 00816 00817 // Consume the identifier so that we can see if it is followed by a '(' or 00818 // '.'. 00819 IdentifierInfo &II = *Tok.getIdentifierInfo(); 00820 SourceLocation ILoc = ConsumeToken(); 00821 00822 // Support 'Class.property' and 'super.property' notation. 00823 if (getLangOpts().ObjC1 && Tok.is(tok::period) && 00824 (Actions.getTypeName(II, ILoc, getCurScope()) || 00825 // Allow the base to be 'super' if in an objc-method. 00826 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) { 00827 ConsumeToken(); 00828 00829 // Allow either an identifier or the keyword 'class' (in C++). 00830 if (Tok.isNot(tok::identifier) && 00831 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) { 00832 Diag(Tok, diag::err_expected_property_name); 00833 return ExprError(); 00834 } 00835 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); 00836 SourceLocation PropertyLoc = ConsumeToken(); 00837 00838 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName, 00839 ILoc, PropertyLoc); 00840 break; 00841 } 00842 00843 // In an Objective-C method, if we have "super" followed by an identifier, 00844 // the token sequence is ill-formed. However, if there's a ':' or ']' after 00845 // that identifier, this is probably a message send with a missing open 00846 // bracket. Treat it as such. 00847 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression && 00848 getCurScope()->isInObjcMethodScope() && 00849 ((Tok.is(tok::identifier) && 00850 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) || 00851 Tok.is(tok::code_completion))) { 00852 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(), 00853 nullptr); 00854 break; 00855 } 00856 00857 // If we have an Objective-C class name followed by an identifier 00858 // and either ':' or ']', this is an Objective-C class message 00859 // send that's missing the opening '['. Recovery 00860 // appropriately. Also take this path if we're performing code 00861 // completion after an Objective-C class name. 00862 if (getLangOpts().ObjC1 && 00863 ((Tok.is(tok::identifier) && !InMessageExpression) || 00864 Tok.is(tok::code_completion))) { 00865 const Token& Next = NextToken(); 00866 if (Tok.is(tok::code_completion) || 00867 Next.is(tok::colon) || Next.is(tok::r_square)) 00868 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope())) 00869 if (Typ.get()->isObjCObjectOrInterfaceType()) { 00870 // Fake up a Declarator to use with ActOnTypeName. 00871 DeclSpec DS(AttrFactory); 00872 DS.SetRangeStart(ILoc); 00873 DS.SetRangeEnd(ILoc); 00874 const char *PrevSpec = nullptr; 00875 unsigned DiagID; 00876 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ, 00877 Actions.getASTContext().getPrintingPolicy()); 00878 00879 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 00880 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), 00881 DeclaratorInfo); 00882 if (Ty.isInvalid()) 00883 break; 00884 00885 Res = ParseObjCMessageExpressionBody(SourceLocation(), 00886 SourceLocation(), 00887 Ty.get(), nullptr); 00888 break; 00889 } 00890 } 00891 00892 // Make sure to pass down the right value for isAddressOfOperand. 00893 if (isAddressOfOperand && isPostfixExpressionSuffixStart()) 00894 isAddressOfOperand = false; 00895 00896 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we 00897 // need to know whether or not this identifier is a function designator or 00898 // not. 00899 UnqualifiedId Name; 00900 CXXScopeSpec ScopeSpec; 00901 SourceLocation TemplateKWLoc; 00902 auto Validator = llvm::make_unique<CastExpressionIdValidator>( 00903 isTypeCast != NotTypeCast, isTypeCast != IsTypeCast); 00904 Validator->IsAddressOfOperand = isAddressOfOperand; 00905 Name.setIdentifier(&II, ILoc); 00906 Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKWLoc, 00907 Name, Tok.is(tok::l_paren), 00908 isAddressOfOperand, std::move(Validator)); 00909 break; 00910 } 00911 case tok::char_constant: // constant: character-constant 00912 case tok::wide_char_constant: 00913 case tok::utf8_char_constant: 00914 case tok::utf16_char_constant: 00915 case tok::utf32_char_constant: 00916 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope()); 00917 ConsumeToken(); 00918 break; 00919 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] 00920 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] 00921 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS] 00922 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS] 00923 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS] 00924 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] 00925 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind); 00926 ConsumeToken(); 00927 break; 00928 case tok::string_literal: // primary-expression: string-literal 00929 case tok::wide_string_literal: 00930 case tok::utf8_string_literal: 00931 case tok::utf16_string_literal: 00932 case tok::utf32_string_literal: 00933 Res = ParseStringLiteralExpression(true); 00934 break; 00935 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1] 00936 Res = ParseGenericSelectionExpression(); 00937 break; 00938 case tok::kw___builtin_va_arg: 00939 case tok::kw___builtin_offsetof: 00940 case tok::kw___builtin_choose_expr: 00941 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type() 00942 case tok::kw___builtin_convertvector: 00943 return ParseBuiltinPrimaryExpression(); 00944 case tok::kw___null: 00945 return Actions.ActOnGNUNullExpr(ConsumeToken()); 00946 00947 case tok::plusplus: // unary-expression: '++' unary-expression [C99] 00948 case tok::minusminus: { // unary-expression: '--' unary-expression [C99] 00949 // C++ [expr.unary] has: 00950 // unary-expression: 00951 // ++ cast-expression 00952 // -- cast-expression 00953 SourceLocation SavedLoc = ConsumeToken(); 00954 // One special case is implicitly handled here: if the preceding tokens are 00955 // an ambiguous cast expression, such as "(T())++", then we recurse to 00956 // determine whether the '++' is prefix or postfix. 00957 Res = ParseCastExpression(!getLangOpts().CPlusPlus, 00958 /*isAddressOfOperand*/false, NotCastExpr, 00959 NotTypeCast); 00960 if (!Res.isInvalid()) 00961 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 00962 return Res; 00963 } 00964 case tok::amp: { // unary-expression: '&' cast-expression 00965 // Special treatment because of member pointers 00966 SourceLocation SavedLoc = ConsumeToken(); 00967 Res = ParseCastExpression(false, true); 00968 if (!Res.isInvalid()) 00969 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 00970 return Res; 00971 } 00972 00973 case tok::star: // unary-expression: '*' cast-expression 00974 case tok::plus: // unary-expression: '+' cast-expression 00975 case tok::minus: // unary-expression: '-' cast-expression 00976 case tok::tilde: // unary-expression: '~' cast-expression 00977 case tok::exclaim: // unary-expression: '!' cast-expression 00978 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] 00979 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] 00980 SourceLocation SavedLoc = ConsumeToken(); 00981 Res = ParseCastExpression(false); 00982 if (!Res.isInvalid()) 00983 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 00984 return Res; 00985 } 00986 00987 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] 00988 // __extension__ silences extension warnings in the subexpression. 00989 ExtensionRAIIObject O(Diags); // Use RAII to do this. 00990 SourceLocation SavedLoc = ConsumeToken(); 00991 Res = ParseCastExpression(false); 00992 if (!Res.isInvalid()) 00993 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); 00994 return Res; 00995 } 00996 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')' 00997 if (!getLangOpts().C11) 00998 Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); 00999 // fallthrough 01000 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')' 01001 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression 01002 // unary-expression: '__alignof' '(' type-name ')' 01003 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression 01004 // unary-expression: 'sizeof' '(' type-name ')' 01005 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression 01006 return ParseUnaryExprOrTypeTraitExpression(); 01007 case tok::ampamp: { // unary-expression: '&&' identifier 01008 SourceLocation AmpAmpLoc = ConsumeToken(); 01009 if (Tok.isNot(tok::identifier)) 01010 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); 01011 01012 if (getCurScope()->getFnParent() == nullptr) 01013 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn)); 01014 01015 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); 01016 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), 01017 Tok.getLocation()); 01018 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD); 01019 ConsumeToken(); 01020 return Res; 01021 } 01022 case tok::kw_const_cast: 01023 case tok::kw_dynamic_cast: 01024 case tok::kw_reinterpret_cast: 01025 case tok::kw_static_cast: 01026 Res = ParseCXXCasts(); 01027 break; 01028 case tok::kw_typeid: 01029 Res = ParseCXXTypeid(); 01030 break; 01031 case tok::kw___uuidof: 01032 Res = ParseCXXUuidof(); 01033 break; 01034 case tok::kw_this: 01035 Res = ParseCXXThis(); 01036 break; 01037 01038 case tok::annot_typename: 01039 if (isStartOfObjCClassMessageMissingOpenBracket()) { 01040 ParsedType Type = getTypeAnnotation(Tok); 01041 01042 // Fake up a Declarator to use with ActOnTypeName. 01043 DeclSpec DS(AttrFactory); 01044 DS.SetRangeStart(Tok.getLocation()); 01045 DS.SetRangeEnd(Tok.getLastLoc()); 01046 01047 const char *PrevSpec = nullptr; 01048 unsigned DiagID; 01049 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(), 01050 PrevSpec, DiagID, Type, 01051 Actions.getASTContext().getPrintingPolicy()); 01052 01053 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 01054 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 01055 if (Ty.isInvalid()) 01056 break; 01057 01058 ConsumeToken(); 01059 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 01060 Ty.get(), nullptr); 01061 break; 01062 } 01063 // Fall through 01064 01065 case tok::annot_decltype: 01066 case tok::kw_char: 01067 case tok::kw_wchar_t: 01068 case tok::kw_char16_t: 01069 case tok::kw_char32_t: 01070 case tok::kw_bool: 01071 case tok::kw_short: 01072 case tok::kw_int: 01073 case tok::kw_long: 01074 case tok::kw___int64: 01075 case tok::kw___int128: 01076 case tok::kw_signed: 01077 case tok::kw_unsigned: 01078 case tok::kw_half: 01079 case tok::kw_float: 01080 case tok::kw_double: 01081 case tok::kw_void: 01082 case tok::kw_typename: 01083 case tok::kw_typeof: 01084 case tok::kw___vector: { 01085 if (!getLangOpts().CPlusPlus) { 01086 Diag(Tok, diag::err_expected_expression); 01087 return ExprError(); 01088 } 01089 01090 if (SavedKind == tok::kw_typename) { 01091 // postfix-expression: typename-specifier '(' expression-list[opt] ')' 01092 // typename-specifier braced-init-list 01093 if (TryAnnotateTypeOrScopeToken()) 01094 return ExprError(); 01095 01096 if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) 01097 // We are trying to parse a simple-type-specifier but might not get such 01098 // a token after error recovery. 01099 return ExprError(); 01100 } 01101 01102 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' 01103 // simple-type-specifier braced-init-list 01104 // 01105 DeclSpec DS(AttrFactory); 01106 01107 ParseCXXSimpleTypeSpecifier(DS); 01108 if (Tok.isNot(tok::l_paren) && 01109 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace))) 01110 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) 01111 << DS.getSourceRange()); 01112 01113 if (Tok.is(tok::l_brace)) 01114 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 01115 01116 Res = ParseCXXTypeConstructExpression(DS); 01117 break; 01118 } 01119 01120 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id 01121 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 01122 // (We can end up in this situation after tentative parsing.) 01123 if (TryAnnotateTypeOrScopeToken()) 01124 return ExprError(); 01125 if (!Tok.is(tok::annot_cxxscope)) 01126 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 01127 NotCastExpr, isTypeCast); 01128 01129 Token Next = NextToken(); 01130 if (Next.is(tok::annot_template_id)) { 01131 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); 01132 if (TemplateId->Kind == TNK_Type_template) { 01133 // We have a qualified template-id that we know refers to a 01134 // type, translate it into a type and continue parsing as a 01135 // cast expression. 01136 CXXScopeSpec SS; 01137 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), 01138 /*EnteringContext=*/false); 01139 AnnotateTemplateIdTokenAsType(); 01140 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 01141 NotCastExpr, isTypeCast); 01142 } 01143 } 01144 01145 // Parse as an id-expression. 01146 Res = ParseCXXIdExpression(isAddressOfOperand); 01147 break; 01148 } 01149 01150 case tok::annot_template_id: { // [C++] template-id 01151 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); 01152 if (TemplateId->Kind == TNK_Type_template) { 01153 // We have a template-id that we know refers to a type, 01154 // translate it into a type and continue parsing as a cast 01155 // expression. 01156 AnnotateTemplateIdTokenAsType(); 01157 return ParseCastExpression(isUnaryExpression, isAddressOfOperand, 01158 NotCastExpr, isTypeCast); 01159 } 01160 01161 // Fall through to treat the template-id as an id-expression. 01162 } 01163 01164 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id 01165 Res = ParseCXXIdExpression(isAddressOfOperand); 01166 break; 01167 01168 case tok::coloncolon: { 01169 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken 01170 // annotates the token, tail recurse. 01171 if (TryAnnotateTypeOrScopeToken()) 01172 return ExprError(); 01173 if (!Tok.is(tok::coloncolon)) 01174 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 01175 01176 // ::new -> [C++] new-expression 01177 // ::delete -> [C++] delete-expression 01178 SourceLocation CCLoc = ConsumeToken(); 01179 if (Tok.is(tok::kw_new)) 01180 return ParseCXXNewExpression(true, CCLoc); 01181 if (Tok.is(tok::kw_delete)) 01182 return ParseCXXDeleteExpression(true, CCLoc); 01183 01184 // This is not a type name or scope specifier, it is an invalid expression. 01185 Diag(CCLoc, diag::err_expected_expression); 01186 return ExprError(); 01187 } 01188 01189 case tok::kw_new: // [C++] new-expression 01190 return ParseCXXNewExpression(false, Tok.getLocation()); 01191 01192 case tok::kw_delete: // [C++] delete-expression 01193 return ParseCXXDeleteExpression(false, Tok.getLocation()); 01194 01195 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')' 01196 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr); 01197 SourceLocation KeyLoc = ConsumeToken(); 01198 BalancedDelimiterTracker T(*this, tok::l_paren); 01199 01200 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept")) 01201 return ExprError(); 01202 // C++11 [expr.unary.noexcept]p1: 01203 // The noexcept operator determines whether the evaluation of its operand, 01204 // which is an unevaluated operand, can throw an exception. 01205 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 01206 ExprResult Result = ParseExpression(); 01207 01208 T.consumeClose(); 01209 01210 if (!Result.isInvalid()) 01211 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), 01212 Result.get(), T.getCloseLocation()); 01213 return Result; 01214 } 01215 01216 #define TYPE_TRAIT(N,Spelling,K) \ 01217 case tok::kw_##Spelling: 01218 #include "clang/Basic/TokenKinds.def" 01219 return ParseTypeTrait(); 01220 01221 case tok::kw___array_rank: 01222 case tok::kw___array_extent: 01223 return ParseArrayTypeTrait(); 01224 01225 case tok::kw___is_lvalue_expr: 01226 case tok::kw___is_rvalue_expr: 01227 return ParseExpressionTrait(); 01228 01229 case tok::at: { 01230 SourceLocation AtLoc = ConsumeToken(); 01231 return ParseObjCAtExpression(AtLoc); 01232 } 01233 case tok::caret: 01234 Res = ParseBlockLiteralExpression(); 01235 break; 01236 case tok::code_completion: { 01237 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 01238 cutOffParsing(); 01239 return ExprError(); 01240 } 01241 case tok::l_square: 01242 if (getLangOpts().CPlusPlus11) { 01243 if (getLangOpts().ObjC1) { 01244 // C++11 lambda expressions and Objective-C message sends both start with a 01245 // square bracket. There are three possibilities here: 01246 // we have a valid lambda expression, we have an invalid lambda 01247 // expression, or we have something that doesn't appear to be a lambda. 01248 // If we're in the last case, we fall back to ParseObjCMessageExpression. 01249 Res = TryParseLambdaExpression(); 01250 if (!Res.isInvalid() && !Res.get()) 01251 Res = ParseObjCMessageExpression(); 01252 break; 01253 } 01254 Res = ParseLambdaExpression(); 01255 break; 01256 } 01257 if (getLangOpts().ObjC1) { 01258 Res = ParseObjCMessageExpression(); 01259 break; 01260 } 01261 // FALL THROUGH. 01262 default: 01263 NotCastExpr = true; 01264 return ExprError(); 01265 } 01266 01267 // These can be followed by postfix-expr pieces. 01268 return ParsePostfixExpressionSuffix(Res); 01269 } 01270 01271 /// \brief Once the leading part of a postfix-expression is parsed, this 01272 /// method parses any suffixes that apply. 01273 /// 01274 /// \verbatim 01275 /// postfix-expression: [C99 6.5.2] 01276 /// primary-expression 01277 /// postfix-expression '[' expression ']' 01278 /// postfix-expression '[' braced-init-list ']' 01279 /// postfix-expression '(' argument-expression-list[opt] ')' 01280 /// postfix-expression '.' identifier 01281 /// postfix-expression '->' identifier 01282 /// postfix-expression '++' 01283 /// postfix-expression '--' 01284 /// '(' type-name ')' '{' initializer-list '}' 01285 /// '(' type-name ')' '{' initializer-list ',' '}' 01286 /// 01287 /// argument-expression-list: [C99 6.5.2] 01288 /// argument-expression ...[opt] 01289 /// argument-expression-list ',' assignment-expression ...[opt] 01290 /// \endverbatim 01291 ExprResult 01292 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { 01293 // Now that the primary-expression piece of the postfix-expression has been 01294 // parsed, see if there are any postfix-expression pieces here. 01295 SourceLocation Loc; 01296 while (1) { 01297 switch (Tok.getKind()) { 01298 case tok::code_completion: 01299 if (InMessageExpression) 01300 return LHS; 01301 01302 Actions.CodeCompletePostfixExpression(getCurScope(), LHS); 01303 cutOffParsing(); 01304 return ExprError(); 01305 01306 case tok::identifier: 01307 // If we see identifier: after an expression, and we're not already in a 01308 // message send, then this is probably a message send with a missing 01309 // opening bracket '['. 01310 if (getLangOpts().ObjC1 && !InMessageExpression && 01311 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 01312 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), 01313 ParsedType(), LHS.get()); 01314 break; 01315 } 01316 01317 // Fall through; this isn't a message send. 01318 01319 default: // Not a postfix-expression suffix. 01320 return LHS; 01321 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 01322 // If we have a array postfix expression that starts on a new line and 01323 // Objective-C is enabled, it is highly likely that the user forgot a 01324 // semicolon after the base expression and that the array postfix-expr is 01325 // actually another message send. In this case, do some look-ahead to see 01326 // if the contents of the square brackets are obviously not a valid 01327 // expression and recover by pretending there is no suffix. 01328 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() && 01329 isSimpleObjCMessageExpression()) 01330 return LHS; 01331 01332 // Reject array indices starting with a lambda-expression. '[[' is 01333 // reserved for attributes. 01334 if (CheckProhibitedCXX11Attribute()) 01335 return ExprError(); 01336 01337 BalancedDelimiterTracker T(*this, tok::l_square); 01338 T.consumeOpen(); 01339 Loc = T.getOpenLocation(); 01340 ExprResult Idx; 01341 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 01342 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 01343 Idx = ParseBraceInitializer(); 01344 } else 01345 Idx = ParseExpression(); 01346 01347 SourceLocation RLoc = Tok.getLocation(); 01348 01349 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 01350 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc, 01351 Idx.get(), RLoc); 01352 } else 01353 LHS = ExprError(); 01354 01355 // Match the ']'. 01356 T.consumeClose(); 01357 break; 01358 } 01359 01360 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')' 01361 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>' 01362 // '(' argument-expression-list[opt] ')' 01363 tok::TokenKind OpKind = Tok.getKind(); 01364 InMessageExpressionRAIIObject InMessage(*this, false); 01365 01366 Expr *ExecConfig = nullptr; 01367 01368 BalancedDelimiterTracker PT(*this, tok::l_paren); 01369 01370 if (OpKind == tok::lesslessless) { 01371 ExprVector ExecConfigExprs; 01372 CommaLocsTy ExecConfigCommaLocs; 01373 SourceLocation OpenLoc = ConsumeToken(); 01374 01375 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) { 01376 LHS = ExprError(); 01377 } 01378 01379 SourceLocation CloseLoc; 01380 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) { 01381 } else if (LHS.isInvalid()) { 01382 SkipUntil(tok::greatergreatergreater, StopAtSemi); 01383 } else { 01384 // There was an error closing the brackets 01385 Diag(Tok, diag::err_expected) << tok::greatergreatergreater; 01386 Diag(OpenLoc, diag::note_matching) << tok::lesslessless; 01387 SkipUntil(tok::greatergreatergreater, StopAtSemi); 01388 LHS = ExprError(); 01389 } 01390 01391 if (!LHS.isInvalid()) { 01392 if (ExpectAndConsume(tok::l_paren)) 01393 LHS = ExprError(); 01394 else 01395 Loc = PrevTokLocation; 01396 } 01397 01398 if (!LHS.isInvalid()) { 01399 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), 01400 OpenLoc, 01401 ExecConfigExprs, 01402 CloseLoc); 01403 if (ECResult.isInvalid()) 01404 LHS = ExprError(); 01405 else 01406 ExecConfig = ECResult.get(); 01407 } 01408 } else { 01409 PT.consumeOpen(); 01410 Loc = PT.getOpenLocation(); 01411 } 01412 01413 ExprVector ArgExprs; 01414 CommaLocsTy CommaLocs; 01415 01416 if (Tok.is(tok::code_completion)) { 01417 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None); 01418 cutOffParsing(); 01419 return ExprError(); 01420 } 01421 01422 if (OpKind == tok::l_paren || !LHS.isInvalid()) { 01423 if (Tok.isNot(tok::r_paren)) { 01424 if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall, 01425 LHS.get())) { 01426 LHS = ExprError(); 01427 } 01428 } 01429 } 01430 01431 // Match the ')'. 01432 if (LHS.isInvalid()) { 01433 SkipUntil(tok::r_paren, StopAtSemi); 01434 } else if (Tok.isNot(tok::r_paren)) { 01435 PT.consumeClose(); 01436 LHS = ExprError(); 01437 } else { 01438 assert((ArgExprs.size() == 0 || 01439 ArgExprs.size()-1 == CommaLocs.size())&& 01440 "Unexpected number of commas!"); 01441 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc, 01442 ArgExprs, Tok.getLocation(), 01443 ExecConfig); 01444 PT.consumeClose(); 01445 } 01446 01447 break; 01448 } 01449 case tok::arrow: 01450 case tok::period: { 01451 // postfix-expression: p-e '->' template[opt] id-expression 01452 // postfix-expression: p-e '.' template[opt] id-expression 01453 tok::TokenKind OpKind = Tok.getKind(); 01454 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 01455 01456 CXXScopeSpec SS; 01457 ParsedType ObjectType; 01458 bool MayBePseudoDestructor = false; 01459 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) { 01460 Expr *Base = LHS.get(); 01461 const Type* BaseType = Base->getType().getTypePtrOrNull(); 01462 if (BaseType && Tok.is(tok::l_paren) && 01463 (BaseType->isFunctionType() || 01464 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) { 01465 Diag(OpLoc, diag::err_function_is_not_record) 01466 << OpKind << Base->getSourceRange() 01467 << FixItHint::CreateRemoval(OpLoc); 01468 return ParsePostfixExpressionSuffix(Base); 01469 } 01470 01471 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, 01472 OpLoc, OpKind, ObjectType, 01473 MayBePseudoDestructor); 01474 if (LHS.isInvalid()) 01475 break; 01476 01477 ParseOptionalCXXScopeSpecifier(SS, ObjectType, 01478 /*EnteringContext=*/false, 01479 &MayBePseudoDestructor); 01480 if (SS.isNotEmpty()) 01481 ObjectType = ParsedType(); 01482 } 01483 01484 if (Tok.is(tok::code_completion)) { 01485 // Code completion for a member access expression. 01486 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(), 01487 OpLoc, OpKind == tok::arrow); 01488 01489 cutOffParsing(); 01490 return ExprError(); 01491 } 01492 01493 if (MayBePseudoDestructor && !LHS.isInvalid()) { 01494 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS, 01495 ObjectType); 01496 break; 01497 } 01498 01499 // Either the action has told is that this cannot be a 01500 // pseudo-destructor expression (based on the type of base 01501 // expression), or we didn't see a '~' in the right place. We 01502 // can still parse a destructor name here, but in that case it 01503 // names a real destructor. 01504 // Allow explicit constructor calls in Microsoft mode. 01505 // FIXME: Add support for explicit call of template constructor. 01506 SourceLocation TemplateKWLoc; 01507 UnqualifiedId Name; 01508 if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) { 01509 // Objective-C++: 01510 // After a '.' in a member access expression, treat the keyword 01511 // 'class' as if it were an identifier. 01512 // 01513 // This hack allows property access to the 'class' method because it is 01514 // such a common method name. For other C++ keywords that are 01515 // Objective-C method names, one must use the message send syntax. 01516 IdentifierInfo *Id = Tok.getIdentifierInfo(); 01517 SourceLocation Loc = ConsumeToken(); 01518 Name.setIdentifier(Id, Loc); 01519 } else if (ParseUnqualifiedId(SS, 01520 /*EnteringContext=*/false, 01521 /*AllowDestructorName=*/true, 01522 /*AllowConstructorName=*/ 01523 getLangOpts().MicrosoftExt, 01524 ObjectType, TemplateKWLoc, Name)) 01525 LHS = ExprError(); 01526 01527 if (!LHS.isInvalid()) 01528 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc, 01529 OpKind, SS, TemplateKWLoc, Name, 01530 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl 01531 : nullptr, 01532 Tok.is(tok::l_paren)); 01533 break; 01534 } 01535 case tok::plusplus: // postfix-expression: postfix-expression '++' 01536 case tok::minusminus: // postfix-expression: postfix-expression '--' 01537 if (!LHS.isInvalid()) { 01538 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(), 01539 Tok.getKind(), LHS.get()); 01540 } 01541 ConsumeToken(); 01542 break; 01543 } 01544 } 01545 } 01546 01547 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/ 01548 /// vec_step and we are at the start of an expression or a parenthesized 01549 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the 01550 /// expression (isCastExpr == false) or the type (isCastExpr == true). 01551 /// 01552 /// \verbatim 01553 /// unary-expression: [C99 6.5.3] 01554 /// 'sizeof' unary-expression 01555 /// 'sizeof' '(' type-name ')' 01556 /// [GNU] '__alignof' unary-expression 01557 /// [GNU] '__alignof' '(' type-name ')' 01558 /// [C11] '_Alignof' '(' type-name ')' 01559 /// [C++0x] 'alignof' '(' type-id ')' 01560 /// 01561 /// [GNU] typeof-specifier: 01562 /// typeof ( expressions ) 01563 /// typeof ( type-name ) 01564 /// [GNU/C++] typeof unary-expression 01565 /// 01566 /// [OpenCL 1.1 6.11.12] vec_step built-in function: 01567 /// vec_step ( expressions ) 01568 /// vec_step ( type-name ) 01569 /// \endverbatim 01570 ExprResult 01571 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, 01572 bool &isCastExpr, 01573 ParsedType &CastTy, 01574 SourceRange &CastRange) { 01575 01576 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 01577 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) || 01578 OpTok.is(tok::kw__Alignof) || OpTok.is(tok::kw_vec_step)) && 01579 "Not a typeof/sizeof/alignof/vec_step expression!"); 01580 01581 ExprResult Operand; 01582 01583 // If the operand doesn't start with an '(', it must be an expression. 01584 if (Tok.isNot(tok::l_paren)) { 01585 // If construct allows a form without parenthesis, user may forget to put 01586 // pathenthesis around type name. 01587 if (OpTok.is(tok::kw_sizeof) || OpTok.is(tok::kw___alignof) || 01588 OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof)) { 01589 if (isTypeIdUnambiguously()) { 01590 DeclSpec DS(AttrFactory); 01591 ParseSpecifierQualifierList(DS); 01592 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 01593 ParseDeclarator(DeclaratorInfo); 01594 01595 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation()); 01596 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation); 01597 Diag(LParenLoc, diag::err_expected_parentheses_around_typename) 01598 << OpTok.getName() 01599 << FixItHint::CreateInsertion(LParenLoc, "(") 01600 << FixItHint::CreateInsertion(RParenLoc, ")"); 01601 isCastExpr = true; 01602 return ExprEmpty(); 01603 } 01604 } 01605 01606 isCastExpr = false; 01607 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) { 01608 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo() 01609 << tok::l_paren; 01610 return ExprError(); 01611 } 01612 01613 Operand = ParseCastExpression(true/*isUnaryExpression*/); 01614 } else { 01615 // If it starts with a '(', we know that it is either a parenthesized 01616 // type-name, or it is a unary-expression that starts with a compound 01617 // literal, or starts with a primary-expression that is a parenthesized 01618 // expression. 01619 ParenParseOption ExprType = CastExpr; 01620 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 01621 01622 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 01623 false, CastTy, RParenLoc); 01624 CastRange = SourceRange(LParenLoc, RParenLoc); 01625 01626 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 01627 // a type. 01628 if (ExprType == CastExpr) { 01629 isCastExpr = true; 01630 return ExprEmpty(); 01631 } 01632 01633 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { 01634 // GNU typeof in C requires the expression to be parenthesized. Not so for 01635 // sizeof/alignof or in C++. Therefore, the parenthesized expression is 01636 // the start of a unary-expression, but doesn't include any postfix 01637 // pieces. Parse these now if present. 01638 if (!Operand.isInvalid()) 01639 Operand = ParsePostfixExpressionSuffix(Operand.get()); 01640 } 01641 } 01642 01643 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 01644 isCastExpr = false; 01645 return Operand; 01646 } 01647 01648 01649 /// \brief Parse a sizeof or alignof expression. 01650 /// 01651 /// \verbatim 01652 /// unary-expression: [C99 6.5.3] 01653 /// 'sizeof' unary-expression 01654 /// 'sizeof' '(' type-name ')' 01655 /// [C++11] 'sizeof' '...' '(' identifier ')' 01656 /// [GNU] '__alignof' unary-expression 01657 /// [GNU] '__alignof' '(' type-name ')' 01658 /// [C11] '_Alignof' '(' type-name ')' 01659 /// [C++11] 'alignof' '(' type-id ')' 01660 /// \endverbatim 01661 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { 01662 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) || 01663 Tok.is(tok::kw_alignof) || Tok.is(tok::kw__Alignof) || 01664 Tok.is(tok::kw_vec_step)) && 01665 "Not a sizeof/alignof/vec_step expression!"); 01666 Token OpTok = Tok; 01667 ConsumeToken(); 01668 01669 // [C++11] 'sizeof' '...' '(' identifier ')' 01670 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) { 01671 SourceLocation EllipsisLoc = ConsumeToken(); 01672 SourceLocation LParenLoc, RParenLoc; 01673 IdentifierInfo *Name = nullptr; 01674 SourceLocation NameLoc; 01675 if (Tok.is(tok::l_paren)) { 01676 BalancedDelimiterTracker T(*this, tok::l_paren); 01677 T.consumeOpen(); 01678 LParenLoc = T.getOpenLocation(); 01679 if (Tok.is(tok::identifier)) { 01680 Name = Tok.getIdentifierInfo(); 01681 NameLoc = ConsumeToken(); 01682 T.consumeClose(); 01683 RParenLoc = T.getCloseLocation(); 01684 if (RParenLoc.isInvalid()) 01685 RParenLoc = PP.getLocForEndOfToken(NameLoc); 01686 } else { 01687 Diag(Tok, diag::err_expected_parameter_pack); 01688 SkipUntil(tok::r_paren, StopAtSemi); 01689 } 01690 } else if (Tok.is(tok::identifier)) { 01691 Name = Tok.getIdentifierInfo(); 01692 NameLoc = ConsumeToken(); 01693 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc); 01694 RParenLoc = PP.getLocForEndOfToken(NameLoc); 01695 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack) 01696 << Name 01697 << FixItHint::CreateInsertion(LParenLoc, "(") 01698 << FixItHint::CreateInsertion(RParenLoc, ")"); 01699 } else { 01700 Diag(Tok, diag::err_sizeof_parameter_pack); 01701 } 01702 01703 if (!Name) 01704 return ExprError(); 01705 01706 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 01707 Sema::ReuseLambdaContextDecl); 01708 01709 return Actions.ActOnSizeofParameterPackExpr(getCurScope(), 01710 OpTok.getLocation(), 01711 *Name, NameLoc, 01712 RParenLoc); 01713 } 01714 01715 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof)) 01716 Diag(OpTok, diag::warn_cxx98_compat_alignof); 01717 01718 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, 01719 Sema::ReuseLambdaContextDecl); 01720 01721 bool isCastExpr; 01722 ParsedType CastTy; 01723 SourceRange CastRange; 01724 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, 01725 isCastExpr, 01726 CastTy, 01727 CastRange); 01728 01729 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf; 01730 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof) || 01731 OpTok.is(tok::kw__Alignof)) 01732 ExprKind = UETT_AlignOf; 01733 else if (OpTok.is(tok::kw_vec_step)) 01734 ExprKind = UETT_VecStep; 01735 01736 if (isCastExpr) 01737 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 01738 ExprKind, 01739 /*isType=*/true, 01740 CastTy.getAsOpaquePtr(), 01741 CastRange); 01742 01743 if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof)) 01744 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo(); 01745 01746 // If we get here, the operand to the sizeof/alignof was an expresion. 01747 if (!Operand.isInvalid()) 01748 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), 01749 ExprKind, 01750 /*isType=*/false, 01751 Operand.get(), 01752 CastRange); 01753 return Operand; 01754 } 01755 01756 /// ParseBuiltinPrimaryExpression 01757 /// 01758 /// \verbatim 01759 /// primary-expression: [C99 6.5.1] 01760 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 01761 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 01762 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 01763 /// assign-expr ')' 01764 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 01765 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')' 01766 /// 01767 /// [GNU] offsetof-member-designator: 01768 /// [GNU] identifier 01769 /// [GNU] offsetof-member-designator '.' identifier 01770 /// [GNU] offsetof-member-designator '[' expression ']' 01771 /// \endverbatim 01772 ExprResult Parser::ParseBuiltinPrimaryExpression() { 01773 ExprResult Res; 01774 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 01775 01776 tok::TokenKind T = Tok.getKind(); 01777 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 01778 01779 // All of these start with an open paren. 01780 if (Tok.isNot(tok::l_paren)) 01781 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII 01782 << tok::l_paren); 01783 01784 BalancedDelimiterTracker PT(*this, tok::l_paren); 01785 PT.consumeOpen(); 01786 01787 // TODO: Build AST. 01788 01789 switch (T) { 01790 default: llvm_unreachable("Not a builtin primary expression!"); 01791 case tok::kw___builtin_va_arg: { 01792 ExprResult Expr(ParseAssignmentExpression()); 01793 01794 if (ExpectAndConsume(tok::comma)) { 01795 SkipUntil(tok::r_paren, StopAtSemi); 01796 Expr = ExprError(); 01797 } 01798 01799 TypeResult Ty = ParseTypeName(); 01800 01801 if (Tok.isNot(tok::r_paren)) { 01802 Diag(Tok, diag::err_expected) << tok::r_paren; 01803 Expr = ExprError(); 01804 } 01805 01806 if (Expr.isInvalid() || Ty.isInvalid()) 01807 Res = ExprError(); 01808 else 01809 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen()); 01810 break; 01811 } 01812 case tok::kw___builtin_offsetof: { 01813 SourceLocation TypeLoc = Tok.getLocation(); 01814 TypeResult Ty = ParseTypeName(); 01815 if (Ty.isInvalid()) { 01816 SkipUntil(tok::r_paren, StopAtSemi); 01817 return ExprError(); 01818 } 01819 01820 if (ExpectAndConsume(tok::comma)) { 01821 SkipUntil(tok::r_paren, StopAtSemi); 01822 return ExprError(); 01823 } 01824 01825 // We must have at least one identifier here. 01826 if (Tok.isNot(tok::identifier)) { 01827 Diag(Tok, diag::err_expected) << tok::identifier; 01828 SkipUntil(tok::r_paren, StopAtSemi); 01829 return ExprError(); 01830 } 01831 01832 // Keep track of the various subcomponents we see. 01833 SmallVector<Sema::OffsetOfComponent, 4> Comps; 01834 01835 Comps.push_back(Sema::OffsetOfComponent()); 01836 Comps.back().isBrackets = false; 01837 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 01838 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 01839 01840 // FIXME: This loop leaks the index expressions on error. 01841 while (1) { 01842 if (Tok.is(tok::period)) { 01843 // offsetof-member-designator: offsetof-member-designator '.' identifier 01844 Comps.push_back(Sema::OffsetOfComponent()); 01845 Comps.back().isBrackets = false; 01846 Comps.back().LocStart = ConsumeToken(); 01847 01848 if (Tok.isNot(tok::identifier)) { 01849 Diag(Tok, diag::err_expected) << tok::identifier; 01850 SkipUntil(tok::r_paren, StopAtSemi); 01851 return ExprError(); 01852 } 01853 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 01854 Comps.back().LocEnd = ConsumeToken(); 01855 01856 } else if (Tok.is(tok::l_square)) { 01857 if (CheckProhibitedCXX11Attribute()) 01858 return ExprError(); 01859 01860 // offsetof-member-designator: offsetof-member-design '[' expression ']' 01861 Comps.push_back(Sema::OffsetOfComponent()); 01862 Comps.back().isBrackets = true; 01863 BalancedDelimiterTracker ST(*this, tok::l_square); 01864 ST.consumeOpen(); 01865 Comps.back().LocStart = ST.getOpenLocation(); 01866 Res = ParseExpression(); 01867 if (Res.isInvalid()) { 01868 SkipUntil(tok::r_paren, StopAtSemi); 01869 return Res; 01870 } 01871 Comps.back().U.E = Res.get(); 01872 01873 ST.consumeClose(); 01874 Comps.back().LocEnd = ST.getCloseLocation(); 01875 } else { 01876 if (Tok.isNot(tok::r_paren)) { 01877 PT.consumeClose(); 01878 Res = ExprError(); 01879 } else if (Ty.isInvalid()) { 01880 Res = ExprError(); 01881 } else { 01882 PT.consumeClose(); 01883 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc, 01884 Ty.get(), &Comps[0], Comps.size(), 01885 PT.getCloseLocation()); 01886 } 01887 break; 01888 } 01889 } 01890 break; 01891 } 01892 case tok::kw___builtin_choose_expr: { 01893 ExprResult Cond(ParseAssignmentExpression()); 01894 if (Cond.isInvalid()) { 01895 SkipUntil(tok::r_paren, StopAtSemi); 01896 return Cond; 01897 } 01898 if (ExpectAndConsume(tok::comma)) { 01899 SkipUntil(tok::r_paren, StopAtSemi); 01900 return ExprError(); 01901 } 01902 01903 ExprResult Expr1(ParseAssignmentExpression()); 01904 if (Expr1.isInvalid()) { 01905 SkipUntil(tok::r_paren, StopAtSemi); 01906 return Expr1; 01907 } 01908 if (ExpectAndConsume(tok::comma)) { 01909 SkipUntil(tok::r_paren, StopAtSemi); 01910 return ExprError(); 01911 } 01912 01913 ExprResult Expr2(ParseAssignmentExpression()); 01914 if (Expr2.isInvalid()) { 01915 SkipUntil(tok::r_paren, StopAtSemi); 01916 return Expr2; 01917 } 01918 if (Tok.isNot(tok::r_paren)) { 01919 Diag(Tok, diag::err_expected) << tok::r_paren; 01920 return ExprError(); 01921 } 01922 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(), 01923 Expr2.get(), ConsumeParen()); 01924 break; 01925 } 01926 case tok::kw___builtin_astype: { 01927 // The first argument is an expression to be converted, followed by a comma. 01928 ExprResult Expr(ParseAssignmentExpression()); 01929 if (Expr.isInvalid()) { 01930 SkipUntil(tok::r_paren, StopAtSemi); 01931 return ExprError(); 01932 } 01933 01934 if (ExpectAndConsume(tok::comma)) { 01935 SkipUntil(tok::r_paren, StopAtSemi); 01936 return ExprError(); 01937 } 01938 01939 // Second argument is the type to bitcast to. 01940 TypeResult DestTy = ParseTypeName(); 01941 if (DestTy.isInvalid()) 01942 return ExprError(); 01943 01944 // Attempt to consume the r-paren. 01945 if (Tok.isNot(tok::r_paren)) { 01946 Diag(Tok, diag::err_expected) << tok::r_paren; 01947 SkipUntil(tok::r_paren, StopAtSemi); 01948 return ExprError(); 01949 } 01950 01951 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc, 01952 ConsumeParen()); 01953 break; 01954 } 01955 case tok::kw___builtin_convertvector: { 01956 // The first argument is an expression to be converted, followed by a comma. 01957 ExprResult Expr(ParseAssignmentExpression()); 01958 if (Expr.isInvalid()) { 01959 SkipUntil(tok::r_paren, StopAtSemi); 01960 return ExprError(); 01961 } 01962 01963 if (ExpectAndConsume(tok::comma)) { 01964 SkipUntil(tok::r_paren, StopAtSemi); 01965 return ExprError(); 01966 } 01967 01968 // Second argument is the type to bitcast to. 01969 TypeResult DestTy = ParseTypeName(); 01970 if (DestTy.isInvalid()) 01971 return ExprError(); 01972 01973 // Attempt to consume the r-paren. 01974 if (Tok.isNot(tok::r_paren)) { 01975 Diag(Tok, diag::err_expected) << tok::r_paren; 01976 SkipUntil(tok::r_paren, StopAtSemi); 01977 return ExprError(); 01978 } 01979 01980 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc, 01981 ConsumeParen()); 01982 break; 01983 } 01984 } 01985 01986 if (Res.isInvalid()) 01987 return ExprError(); 01988 01989 // These can be followed by postfix-expr pieces because they are 01990 // primary-expressions. 01991 return ParsePostfixExpressionSuffix(Res.get()); 01992 } 01993 01994 /// ParseParenExpression - This parses the unit that starts with a '(' token, 01995 /// based on what is allowed by ExprType. The actual thing parsed is returned 01996 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 01997 /// not the parsed cast-expression. 01998 /// 01999 /// \verbatim 02000 /// primary-expression: [C99 6.5.1] 02001 /// '(' expression ')' 02002 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 02003 /// postfix-expression: [C99 6.5.2] 02004 /// '(' type-name ')' '{' initializer-list '}' 02005 /// '(' type-name ')' '{' initializer-list ',' '}' 02006 /// cast-expression: [C99 6.5.4] 02007 /// '(' type-name ')' cast-expression 02008 /// [ARC] bridged-cast-expression 02009 /// [ARC] bridged-cast-expression: 02010 /// (__bridge type-name) cast-expression 02011 /// (__bridge_transfer type-name) cast-expression 02012 /// (__bridge_retained type-name) cast-expression 02013 /// fold-expression: [C++1z] 02014 /// '(' cast-expression fold-operator '...' ')' 02015 /// '(' '...' fold-operator cast-expression ')' 02016 /// '(' cast-expression fold-operator '...' 02017 /// fold-operator cast-expression ')' 02018 /// \endverbatim 02019 ExprResult 02020 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 02021 bool isTypeCast, ParsedType &CastTy, 02022 SourceLocation &RParenLoc) { 02023 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 02024 ColonProtectionRAIIObject ColonProtection(*this, false); 02025 BalancedDelimiterTracker T(*this, tok::l_paren); 02026 if (T.consumeOpen()) 02027 return ExprError(); 02028 SourceLocation OpenLoc = T.getOpenLocation(); 02029 02030 ExprResult Result(true); 02031 bool isAmbiguousTypeId; 02032 CastTy = ParsedType(); 02033 02034 if (Tok.is(tok::code_completion)) { 02035 Actions.CodeCompleteOrdinaryName(getCurScope(), 02036 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression 02037 : Sema::PCC_Expression); 02038 cutOffParsing(); 02039 return ExprError(); 02040 } 02041 02042 // Diagnose use of bridge casts in non-arc mode. 02043 bool BridgeCast = (getLangOpts().ObjC2 && 02044 (Tok.is(tok::kw___bridge) || 02045 Tok.is(tok::kw___bridge_transfer) || 02046 Tok.is(tok::kw___bridge_retained) || 02047 Tok.is(tok::kw___bridge_retain))); 02048 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) { 02049 if (!TryConsumeToken(tok::kw___bridge)) { 02050 StringRef BridgeCastName = Tok.getName(); 02051 SourceLocation BridgeKeywordLoc = ConsumeToken(); 02052 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) 02053 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc) 02054 << BridgeCastName 02055 << FixItHint::CreateReplacement(BridgeKeywordLoc, ""); 02056 } 02057 BridgeCast = false; 02058 } 02059 02060 // None of these cases should fall through with an invalid Result 02061 // unless they've already reported an error. 02062 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 02063 Diag(Tok, diag::ext_gnu_statement_expr); 02064 Actions.ActOnStartStmtExpr(); 02065 02066 StmtResult Stmt(ParseCompoundStatement(true)); 02067 ExprType = CompoundStmt; 02068 02069 // If the substmt parsed correctly, build the AST node. 02070 if (!Stmt.isInvalid()) { 02071 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation()); 02072 } else { 02073 Actions.ActOnStmtExprError(); 02074 } 02075 } else if (ExprType >= CompoundLiteral && BridgeCast) { 02076 tok::TokenKind tokenKind = Tok.getKind(); 02077 SourceLocation BridgeKeywordLoc = ConsumeToken(); 02078 02079 // Parse an Objective-C ARC ownership cast expression. 02080 ObjCBridgeCastKind Kind; 02081 if (tokenKind == tok::kw___bridge) 02082 Kind = OBC_Bridge; 02083 else if (tokenKind == tok::kw___bridge_transfer) 02084 Kind = OBC_BridgeTransfer; 02085 else if (tokenKind == tok::kw___bridge_retained) 02086 Kind = OBC_BridgeRetained; 02087 else { 02088 // As a hopefully temporary workaround, allow __bridge_retain as 02089 // a synonym for __bridge_retained, but only in system headers. 02090 assert(tokenKind == tok::kw___bridge_retain); 02091 Kind = OBC_BridgeRetained; 02092 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) 02093 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain) 02094 << FixItHint::CreateReplacement(BridgeKeywordLoc, 02095 "__bridge_retained"); 02096 } 02097 02098 TypeResult Ty = ParseTypeName(); 02099 T.consumeClose(); 02100 ColonProtection.restore(); 02101 RParenLoc = T.getCloseLocation(); 02102 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false); 02103 02104 if (Ty.isInvalid() || SubExpr.isInvalid()) 02105 return ExprError(); 02106 02107 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind, 02108 BridgeKeywordLoc, Ty.get(), 02109 RParenLoc, SubExpr.get()); 02110 } else if (ExprType >= CompoundLiteral && 02111 isTypeIdInParens(isAmbiguousTypeId)) { 02112 02113 // Otherwise, this is a compound literal expression or cast expression. 02114 02115 // In C++, if the type-id is ambiguous we disambiguate based on context. 02116 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 02117 // in which case we should treat it as type-id. 02118 // if stopIfCastExpr is false, we need to determine the context past the 02119 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 02120 if (isAmbiguousTypeId && !stopIfCastExpr) { 02121 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T, 02122 ColonProtection); 02123 RParenLoc = T.getCloseLocation(); 02124 return res; 02125 } 02126 02127 // Parse the type declarator. 02128 DeclSpec DS(AttrFactory); 02129 ParseSpecifierQualifierList(DS); 02130 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); 02131 ParseDeclarator(DeclaratorInfo); 02132 02133 // If our type is followed by an identifier and either ':' or ']', then 02134 // this is probably an Objective-C message send where the leading '[' is 02135 // missing. Recover as if that were the case. 02136 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) && 02137 !InMessageExpression && getLangOpts().ObjC1 && 02138 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { 02139 TypeResult Ty; 02140 { 02141 InMessageExpressionRAIIObject InMessage(*this, false); 02142 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 02143 } 02144 Result = ParseObjCMessageExpressionBody(SourceLocation(), 02145 SourceLocation(), 02146 Ty.get(), nullptr); 02147 } else { 02148 // Match the ')'. 02149 T.consumeClose(); 02150 ColonProtection.restore(); 02151 RParenLoc = T.getCloseLocation(); 02152 if (Tok.is(tok::l_brace)) { 02153 ExprType = CompoundLiteral; 02154 TypeResult Ty; 02155 { 02156 InMessageExpressionRAIIObject InMessage(*this, false); 02157 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 02158 } 02159 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 02160 } 02161 02162 if (ExprType == CastExpr) { 02163 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 02164 02165 if (DeclaratorInfo.isInvalidType()) 02166 return ExprError(); 02167 02168 // Note that this doesn't parse the subsequent cast-expression, it just 02169 // returns the parsed type to the callee. 02170 if (stopIfCastExpr) { 02171 TypeResult Ty; 02172 { 02173 InMessageExpressionRAIIObject InMessage(*this, false); 02174 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); 02175 } 02176 CastTy = Ty.get(); 02177 return ExprResult(); 02178 } 02179 02180 // Reject the cast of super idiom in ObjC. 02181 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 && 02182 Tok.getIdentifierInfo() == Ident_super && 02183 getCurScope()->isInObjcMethodScope() && 02184 GetLookAheadToken(1).isNot(tok::period)) { 02185 Diag(Tok.getLocation(), diag::err_illegal_super_cast) 02186 << SourceRange(OpenLoc, RParenLoc); 02187 return ExprError(); 02188 } 02189 02190 // Parse the cast-expression that follows it next. 02191 // TODO: For cast expression with CastTy. 02192 Result = ParseCastExpression(/*isUnaryExpression=*/false, 02193 /*isAddressOfOperand=*/false, 02194 /*isTypeCast=*/IsTypeCast); 02195 if (!Result.isInvalid()) { 02196 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, 02197 DeclaratorInfo, CastTy, 02198 RParenLoc, Result.get()); 02199 } 02200 return Result; 02201 } 02202 02203 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 02204 return ExprError(); 02205 } 02206 } else if (Tok.is(tok::ellipsis) && 02207 isFoldOperator(NextToken().getKind())) { 02208 return ParseFoldExpression(ExprResult(), T); 02209 } else if (isTypeCast) { 02210 // Parse the expression-list. 02211 InMessageExpressionRAIIObject InMessage(*this, false); 02212 02213 ExprVector ArgExprs; 02214 CommaLocsTy CommaLocs; 02215 02216 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) { 02217 // FIXME: If we ever support comma expressions as operands to 02218 // fold-expressions, we'll need to allow multiple ArgExprs here. 02219 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) && 02220 NextToken().is(tok::ellipsis)) 02221 return ParseFoldExpression(Result, T); 02222 02223 ExprType = SimpleExpr; 02224 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), 02225 ArgExprs); 02226 } 02227 } else { 02228 InMessageExpressionRAIIObject InMessage(*this, false); 02229 02230 Result = ParseExpression(MaybeTypeCast); 02231 ExprType = SimpleExpr; 02232 02233 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) 02234 return ParseFoldExpression(Result, T); 02235 02236 // Don't build a paren expression unless we actually match a ')'. 02237 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 02238 Result = 02239 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get()); 02240 } 02241 02242 // Match the ')'. 02243 if (Result.isInvalid()) { 02244 SkipUntil(tok::r_paren, StopAtSemi); 02245 return ExprError(); 02246 } 02247 02248 T.consumeClose(); 02249 RParenLoc = T.getCloseLocation(); 02250 return Result; 02251 } 02252 02253 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 02254 /// and we are at the left brace. 02255 /// 02256 /// \verbatim 02257 /// postfix-expression: [C99 6.5.2] 02258 /// '(' type-name ')' '{' initializer-list '}' 02259 /// '(' type-name ')' '{' initializer-list ',' '}' 02260 /// \endverbatim 02261 ExprResult 02262 Parser::ParseCompoundLiteralExpression(ParsedType Ty, 02263 SourceLocation LParenLoc, 02264 SourceLocation RParenLoc) { 02265 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 02266 if (!getLangOpts().C99) // Compound literals don't exist in C90. 02267 Diag(LParenLoc, diag::ext_c99_compound_literal); 02268 ExprResult Result = ParseInitializer(); 02269 if (!Result.isInvalid() && Ty) 02270 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get()); 02271 return Result; 02272 } 02273 02274 /// ParseStringLiteralExpression - This handles the various token types that 02275 /// form string literals, and also handles string concatenation [C99 5.1.1.2, 02276 /// translation phase #6]. 02277 /// 02278 /// \verbatim 02279 /// primary-expression: [C99 6.5.1] 02280 /// string-literal 02281 /// \verbatim 02282 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) { 02283 assert(isTokenStringLiteral() && "Not a string literal!"); 02284 02285 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 02286 // considered to be strings for concatenation purposes. 02287 SmallVector<Token, 4> StringToks; 02288 02289 do { 02290 StringToks.push_back(Tok); 02291 ConsumeStringToken(); 02292 } while (isTokenStringLiteral()); 02293 02294 // Pass the set of string tokens, ready for concatenation, to the actions. 02295 return Actions.ActOnStringLiteral(StringToks, 02296 AllowUserDefinedLiteral ? getCurScope() 02297 : nullptr); 02298 } 02299 02300 /// ParseGenericSelectionExpression - Parse a C11 generic-selection 02301 /// [C11 6.5.1.1]. 02302 /// 02303 /// \verbatim 02304 /// generic-selection: 02305 /// _Generic ( assignment-expression , generic-assoc-list ) 02306 /// generic-assoc-list: 02307 /// generic-association 02308 /// generic-assoc-list , generic-association 02309 /// generic-association: 02310 /// type-name : assignment-expression 02311 /// default : assignment-expression 02312 /// \endverbatim 02313 ExprResult Parser::ParseGenericSelectionExpression() { 02314 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected"); 02315 SourceLocation KeyLoc = ConsumeToken(); 02316 02317 if (!getLangOpts().C11) 02318 Diag(KeyLoc, diag::ext_c11_generic_selection); 02319 02320 BalancedDelimiterTracker T(*this, tok::l_paren); 02321 if (T.expectAndConsume()) 02322 return ExprError(); 02323 02324 ExprResult ControllingExpr; 02325 { 02326 // C11 6.5.1.1p3 "The controlling expression of a generic selection is 02327 // not evaluated." 02328 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 02329 ControllingExpr = ParseAssignmentExpression(); 02330 if (ControllingExpr.isInvalid()) { 02331 SkipUntil(tok::r_paren, StopAtSemi); 02332 return ExprError(); 02333 } 02334 } 02335 02336 if (ExpectAndConsume(tok::comma)) { 02337 SkipUntil(tok::r_paren, StopAtSemi); 02338 return ExprError(); 02339 } 02340 02341 SourceLocation DefaultLoc; 02342 TypeVector Types; 02343 ExprVector Exprs; 02344 do { 02345 ParsedType Ty; 02346 if (Tok.is(tok::kw_default)) { 02347 // C11 6.5.1.1p2 "A generic selection shall have no more than one default 02348 // generic association." 02349 if (!DefaultLoc.isInvalid()) { 02350 Diag(Tok, diag::err_duplicate_default_assoc); 02351 Diag(DefaultLoc, diag::note_previous_default_assoc); 02352 SkipUntil(tok::r_paren, StopAtSemi); 02353 return ExprError(); 02354 } 02355 DefaultLoc = ConsumeToken(); 02356 Ty = ParsedType(); 02357 } else { 02358 ColonProtectionRAIIObject X(*this); 02359 TypeResult TR = ParseTypeName(); 02360 if (TR.isInvalid()) { 02361 SkipUntil(tok::r_paren, StopAtSemi); 02362 return ExprError(); 02363 } 02364 Ty = TR.get(); 02365 } 02366 Types.push_back(Ty); 02367 02368 if (ExpectAndConsume(tok::colon)) { 02369 SkipUntil(tok::r_paren, StopAtSemi); 02370 return ExprError(); 02371 } 02372 02373 // FIXME: These expressions should be parsed in a potentially potentially 02374 // evaluated context. 02375 ExprResult ER(ParseAssignmentExpression()); 02376 if (ER.isInvalid()) { 02377 SkipUntil(tok::r_paren, StopAtSemi); 02378 return ExprError(); 02379 } 02380 Exprs.push_back(ER.get()); 02381 } while (TryConsumeToken(tok::comma)); 02382 02383 T.consumeClose(); 02384 if (T.getCloseLocation().isInvalid()) 02385 return ExprError(); 02386 02387 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, 02388 T.getCloseLocation(), 02389 ControllingExpr.get(), 02390 Types, Exprs); 02391 } 02392 02393 /// \brief Parse A C++1z fold-expression after the opening paren and optional 02394 /// left-hand-side expression. 02395 /// 02396 /// \verbatim 02397 /// fold-expression: 02398 /// ( cast-expression fold-operator ... ) 02399 /// ( ... fold-operator cast-expression ) 02400 /// ( cast-expression fold-operator ... fold-operator cast-expression ) 02401 ExprResult Parser::ParseFoldExpression(ExprResult LHS, 02402 BalancedDelimiterTracker &T) { 02403 if (LHS.isInvalid()) { 02404 T.skipToEnd(); 02405 return true; 02406 } 02407 02408 tok::TokenKind Kind = tok::unknown; 02409 SourceLocation FirstOpLoc; 02410 if (LHS.isUsable()) { 02411 Kind = Tok.getKind(); 02412 assert(isFoldOperator(Kind) && "missing fold-operator"); 02413 FirstOpLoc = ConsumeToken(); 02414 } 02415 02416 assert(Tok.is(tok::ellipsis) && "not a fold-expression"); 02417 SourceLocation EllipsisLoc = ConsumeToken(); 02418 02419 ExprResult RHS; 02420 if (Tok.isNot(tok::r_paren)) { 02421 if (!isFoldOperator(Tok.getKind())) 02422 return Diag(Tok.getLocation(), diag::err_expected_fold_operator); 02423 02424 if (Kind != tok::unknown && Tok.getKind() != Kind) 02425 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch) 02426 << SourceRange(FirstOpLoc); 02427 Kind = Tok.getKind(); 02428 ConsumeToken(); 02429 02430 RHS = ParseExpression(); 02431 if (RHS.isInvalid()) { 02432 T.skipToEnd(); 02433 return true; 02434 } 02435 } 02436 02437 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z 02438 ? diag::warn_cxx14_compat_fold_expression 02439 : diag::ext_fold_expression); 02440 02441 T.consumeClose(); 02442 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind, 02443 EllipsisLoc, RHS.get(), T.getCloseLocation()); 02444 } 02445 02446 /// ParseExpressionList - Used for C/C++ (argument-)expression-list. 02447 /// 02448 /// \verbatim 02449 /// argument-expression-list: 02450 /// assignment-expression 02451 /// argument-expression-list , assignment-expression 02452 /// 02453 /// [C++] expression-list: 02454 /// [C++] assignment-expression 02455 /// [C++] expression-list , assignment-expression 02456 /// 02457 /// [C++0x] expression-list: 02458 /// [C++0x] initializer-list 02459 /// 02460 /// [C++0x] initializer-list 02461 /// [C++0x] initializer-clause ...[opt] 02462 /// [C++0x] initializer-list , initializer-clause ...[opt] 02463 /// 02464 /// [C++0x] initializer-clause: 02465 /// [C++0x] assignment-expression 02466 /// [C++0x] braced-init-list 02467 /// \endverbatim 02468 bool Parser::ParseExpressionList(SmallVectorImpl<Expr*> &Exprs, 02469 SmallVectorImpl<SourceLocation> &CommaLocs, 02470 void (Sema::*Completer)(Scope *S, 02471 Expr *Data, 02472 ArrayRef<Expr *> Args), 02473 Expr *Data) { 02474 bool SawError = false; 02475 while (1) { 02476 if (Tok.is(tok::code_completion)) { 02477 if (Completer) 02478 (Actions.*Completer)(getCurScope(), Data, Exprs); 02479 else 02480 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); 02481 cutOffParsing(); 02482 return true; 02483 } 02484 02485 ExprResult Expr; 02486 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 02487 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 02488 Expr = ParseBraceInitializer(); 02489 } else 02490 Expr = ParseAssignmentExpression(); 02491 02492 if (Tok.is(tok::ellipsis)) 02493 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); 02494 if (Expr.isInvalid()) { 02495 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch); 02496 SawError = true; 02497 } else { 02498 Exprs.push_back(Expr.get()); 02499 } 02500 02501 if (Tok.isNot(tok::comma)) 02502 return SawError; 02503 // Move to the next argument, remember where the comma was. 02504 CommaLocs.push_back(ConsumeToken()); 02505 } 02506 } 02507 02508 /// ParseSimpleExpressionList - A simple comma-separated list of expressions, 02509 /// used for misc language extensions. 02510 /// 02511 /// \verbatim 02512 /// simple-expression-list: 02513 /// assignment-expression 02514 /// simple-expression-list , assignment-expression 02515 /// \endverbatim 02516 bool 02517 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, 02518 SmallVectorImpl<SourceLocation> &CommaLocs) { 02519 while (1) { 02520 ExprResult Expr = ParseAssignmentExpression(); 02521 if (Expr.isInvalid()) 02522 return true; 02523 02524 Exprs.push_back(Expr.get()); 02525 02526 if (Tok.isNot(tok::comma)) 02527 return false; 02528 02529 // Move to the next argument, remember where the comma was. 02530 CommaLocs.push_back(ConsumeToken()); 02531 } 02532 } 02533 02534 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 02535 /// 02536 /// \verbatim 02537 /// [clang] block-id: 02538 /// [clang] specifier-qualifier-list block-declarator 02539 /// \endverbatim 02540 void Parser::ParseBlockId(SourceLocation CaretLoc) { 02541 if (Tok.is(tok::code_completion)) { 02542 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); 02543 return cutOffParsing(); 02544 } 02545 02546 // Parse the specifier-qualifier-list piece. 02547 DeclSpec DS(AttrFactory); 02548 ParseSpecifierQualifierList(DS); 02549 02550 // Parse the block-declarator. 02551 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 02552 ParseDeclarator(DeclaratorInfo); 02553 02554 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 02555 DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation()); 02556 02557 MaybeParseGNUAttributes(DeclaratorInfo); 02558 02559 // Inform sema that we are starting a block. 02560 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope()); 02561 } 02562 02563 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 02564 /// like ^(int x){ return x+1; } 02565 /// 02566 /// \verbatim 02567 /// block-literal: 02568 /// [clang] '^' block-args[opt] compound-statement 02569 /// [clang] '^' block-id compound-statement 02570 /// [clang] block-args: 02571 /// [clang] '(' parameter-list ')' 02572 /// \endverbatim 02573 ExprResult Parser::ParseBlockLiteralExpression() { 02574 assert(Tok.is(tok::caret) && "block literal starts with ^"); 02575 SourceLocation CaretLoc = ConsumeToken(); 02576 02577 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 02578 "block literal parsing"); 02579 02580 // Enter a scope to hold everything within the block. This includes the 02581 // argument decls, decls within the compound expression, etc. This also 02582 // allows determining whether a variable reference inside the block is 02583 // within or outside of the block. 02584 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 02585 Scope::DeclScope); 02586 02587 // Inform sema that we are starting a block. 02588 Actions.ActOnBlockStart(CaretLoc, getCurScope()); 02589 02590 // Parse the return type if present. 02591 DeclSpec DS(AttrFactory); 02592 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 02593 // FIXME: Since the return type isn't actually parsed, it can't be used to 02594 // fill ParamInfo with an initial valid range, so do it manually. 02595 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 02596 02597 // If this block has arguments, parse them. There is no ambiguity here with 02598 // the expression case, because the expression case requires a parameter list. 02599 if (Tok.is(tok::l_paren)) { 02600 ParseParenDeclarator(ParamInfo); 02601 // Parse the pieces after the identifier as if we had "int(...)". 02602 // SetIdentifier sets the source range end, but in this case we're past 02603 // that location. 02604 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 02605 ParamInfo.SetIdentifier(nullptr, CaretLoc); 02606 ParamInfo.SetRangeEnd(Tmp); 02607 if (ParamInfo.isInvalidType()) { 02608 // If there was an error parsing the arguments, they may have 02609 // tried to use ^(x+y) which requires an argument list. Just 02610 // skip the whole block literal. 02611 Actions.ActOnBlockError(CaretLoc, getCurScope()); 02612 return ExprError(); 02613 } 02614 02615 MaybeParseGNUAttributes(ParamInfo); 02616 02617 // Inform sema that we are starting a block. 02618 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope()); 02619 } else if (!Tok.is(tok::l_brace)) { 02620 ParseBlockId(CaretLoc); 02621 } else { 02622 // Otherwise, pretend we saw (void). 02623 ParsedAttributes attrs(AttrFactory); 02624 SourceLocation NoLoc; 02625 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true, 02626 /*IsAmbiguous=*/false, 02627 /*RParenLoc=*/NoLoc, 02628 /*ArgInfo=*/nullptr, 02629 /*NumArgs=*/0, 02630 /*EllipsisLoc=*/NoLoc, 02631 /*RParenLoc=*/NoLoc, 02632 /*TypeQuals=*/0, 02633 /*RefQualifierIsLvalueRef=*/true, 02634 /*RefQualifierLoc=*/NoLoc, 02635 /*ConstQualifierLoc=*/NoLoc, 02636 /*VolatileQualifierLoc=*/NoLoc, 02637 /*RestrictQualifierLoc=*/NoLoc, 02638 /*MutableLoc=*/NoLoc, 02639 EST_None, 02640 /*ESpecLoc=*/NoLoc, 02641 /*Exceptions=*/nullptr, 02642 /*ExceptionRanges=*/nullptr, 02643 /*NumExceptions=*/0, 02644 /*NoexceptExpr=*/nullptr, 02645 /*ExceptionSpecTokens=*/nullptr, 02646 CaretLoc, CaretLoc, 02647 ParamInfo), 02648 attrs, CaretLoc); 02649 02650 MaybeParseGNUAttributes(ParamInfo); 02651 02652 // Inform sema that we are starting a block. 02653 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope()); 02654 } 02655 02656 02657 ExprResult Result(true); 02658 if (!Tok.is(tok::l_brace)) { 02659 // Saw something like: ^expr 02660 Diag(Tok, diag::err_expected_expression); 02661 Actions.ActOnBlockError(CaretLoc, getCurScope()); 02662 return ExprError(); 02663 } 02664 02665 StmtResult Stmt(ParseCompoundStatementBody()); 02666 BlockScope.Exit(); 02667 if (!Stmt.isInvalid()) 02668 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope()); 02669 else 02670 Actions.ActOnBlockError(CaretLoc, getCurScope()); 02671 return Result; 02672 } 02673 02674 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals. 02675 /// 02676 /// '__objc_yes' 02677 /// '__objc_no' 02678 ExprResult Parser::ParseObjCBoolLiteral() { 02679 tok::TokenKind Kind = Tok.getKind(); 02680 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind); 02681 }