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