1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Provides the Expression parsing implementation.
13 /// Expressions in C99 basically consist of a bunch of binary operators with
14 /// unary operators and other random stuff at the leaves.
16 /// In the C99 grammar, these unary operators bind tightest and are represented
17 /// as the 'cast-expression' production. Everything else is either a binary
18 /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
19 /// handled by ParseCastExpression, the higher level pieces are handled by
20 /// ParseBinaryExpression.
22 //===----------------------------------------------------------------------===//
24 #include "clang/Parse/Parser.h"
25 #include "RAIIObjectsForParser.h"
26 #include "clang/AST/ASTContext.h"
27 #include "clang/Basic/PrettyStackTrace.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/ParsedTemplate.h"
30 #include "clang/Sema/Scope.h"
31 #include "clang/Sema/TypoCorrection.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/SmallVector.h"
34 using namespace clang;
36 /// \brief Simple precedence-based parser for binary/ternary operators.
38 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
39 /// production. C99 specifies that the LHS of an assignment operator should be
40 /// parsed as a unary-expression, but consistency dictates that it be a
41 /// conditional-expession. In practice, the important thing here is that the
42 /// LHS of an assignment has to be an l-value, which productions between
43 /// unary-expression and conditional-expression don't produce. Because we want
44 /// consistency, we parse the LHS as a conditional-expression, then check for
45 /// l-value-ness in semantic analysis stages.
48 /// pm-expression: [C++ 5.5]
50 /// pm-expression '.*' cast-expression
51 /// pm-expression '->*' cast-expression
53 /// multiplicative-expression: [C99 6.5.5]
54 /// Note: in C++, apply pm-expression instead of cast-expression
56 /// multiplicative-expression '*' cast-expression
57 /// multiplicative-expression '/' cast-expression
58 /// multiplicative-expression '%' cast-expression
60 /// additive-expression: [C99 6.5.6]
61 /// multiplicative-expression
62 /// additive-expression '+' multiplicative-expression
63 /// additive-expression '-' multiplicative-expression
65 /// shift-expression: [C99 6.5.7]
66 /// additive-expression
67 /// shift-expression '<<' additive-expression
68 /// shift-expression '>>' additive-expression
70 /// relational-expression: [C99 6.5.8]
72 /// relational-expression '<' shift-expression
73 /// relational-expression '>' shift-expression
74 /// relational-expression '<=' shift-expression
75 /// relational-expression '>=' shift-expression
77 /// equality-expression: [C99 6.5.9]
78 /// relational-expression
79 /// equality-expression '==' relational-expression
80 /// equality-expression '!=' relational-expression
82 /// AND-expression: [C99 6.5.10]
83 /// equality-expression
84 /// AND-expression '&' equality-expression
86 /// exclusive-OR-expression: [C99 6.5.11]
88 /// exclusive-OR-expression '^' AND-expression
90 /// inclusive-OR-expression: [C99 6.5.12]
91 /// exclusive-OR-expression
92 /// inclusive-OR-expression '|' exclusive-OR-expression
94 /// logical-AND-expression: [C99 6.5.13]
95 /// inclusive-OR-expression
96 /// logical-AND-expression '&&' inclusive-OR-expression
98 /// logical-OR-expression: [C99 6.5.14]
99 /// logical-AND-expression
100 /// logical-OR-expression '||' logical-AND-expression
102 /// conditional-expression: [C99 6.5.15]
103 /// logical-OR-expression
104 /// logical-OR-expression '?' expression ':' conditional-expression
105 /// [GNU] logical-OR-expression '?' ':' conditional-expression
106 /// [C++] the third operand is an assignment-expression
108 /// assignment-expression: [C99 6.5.16]
109 /// conditional-expression
110 /// unary-expression assignment-operator assignment-expression
111 /// [C++] throw-expression [C++ 15]
113 /// assignment-operator: one of
114 /// = *= /= %= += -= <<= >>= &= ^= |=
116 /// expression: [C99 6.5.17]
117 /// assignment-expression ...[opt]
118 /// expression ',' assignment-expression ...[opt]
120 ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
121 ExprResult LHS(ParseAssignmentExpression(isTypeCast));
122 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
125 /// This routine is called when the '@' is seen and consumed.
126 /// Current token is an Identifier and is not a 'try'. This
127 /// routine is necessary to disambiguate \@try-statement from,
128 /// for example, \@encode-expression.
131 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
132 ExprResult LHS(ParseObjCAtExpression(AtLoc));
133 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
136 /// This routine is called when a leading '__extension__' is seen and
137 /// consumed. This is necessary because the token gets consumed in the
138 /// process of disambiguating between an expression and a declaration.
140 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
141 ExprResult LHS(true);
143 // Silence extension warnings in the sub-expression
144 ExtensionRAIIObject O(Diags);
146 LHS = ParseCastExpression(false);
149 if (!LHS.isInvalid())
150 LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
153 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
156 /// \brief Parse an expr that doesn't include (top-level) commas.
157 ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
158 if (Tok.is(tok::code_completion)) {
159 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
164 if (Tok.is(tok::kw_throw))
165 return ParseThrowExpression();
167 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
168 /*isAddressOfOperand=*/false,
170 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
173 /// \brief Parse an assignment expression where part of an Objective-C message
174 /// send has already been parsed.
176 /// In this case \p LBracLoc indicates the location of the '[' of the message
177 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
178 /// the receiver of the message.
180 /// Since this handles full assignment-expression's, it handles postfix
181 /// expressions and other binary operators for these expressions as well.
183 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
184 SourceLocation SuperLoc,
185 ParsedType ReceiverType,
186 Expr *ReceiverExpr) {
188 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
189 ReceiverType, ReceiverExpr);
190 R = ParsePostfixExpressionSuffix(R);
191 return ParseRHSOfBinaryExpression(R, prec::Assignment);
195 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
196 // C++03 [basic.def.odr]p2:
197 // An expression is potentially evaluated unless it appears where an
198 // integral constant expression is required (see 5.19) [...].
199 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
200 EnterExpressionEvaluationContext Unevaluated(Actions,
201 Sema::ConstantEvaluated);
203 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
204 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
205 return Actions.ActOnConstantExpression(Res);
208 bool Parser::isNotExpressionStart() {
209 tok::TokenKind K = Tok.getKind();
210 if (K == tok::l_brace || K == tok::r_brace ||
211 K == tok::kw_for || K == tok::kw_while ||
212 K == tok::kw_if || K == tok::kw_else ||
213 K == tok::kw_goto || K == tok::kw_try)
215 // If this is a decl-specifier, we can't be at the start of an expression.
216 return isKnownToBeDeclarationSpecifier();
219 static bool isFoldOperator(prec::Level Level) {
220 return Level > prec::Unknown && Level != prec::Conditional;
222 static bool isFoldOperator(tok::TokenKind Kind) {
223 return isFoldOperator(getBinOpPrecedence(Kind, false, true));
226 /// \brief Parse a binary expression that starts with \p LHS and has a
227 /// precedence of at least \p MinPrec.
229 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
230 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
231 GreaterThanIsOperator,
232 getLangOpts().CPlusPlus11);
233 SourceLocation ColonLoc;
236 // If this token has a lower precedence than we are allowed to parse (e.g.
237 // because we are called recursively, or because the token is not a binop),
239 if (NextTokPrec < MinPrec)
242 // Consume the operator, saving the operator token for error reporting.
246 // Bail out when encountering a comma followed by a token which can't
247 // possibly be the start of an expression. For instance:
248 // int f() { return 1, }
249 // We can't do this before consuming the comma, because
250 // isNotExpressionStart() looks at the token stream.
251 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
257 // If the next token is an ellipsis, then this is a fold-expression. Leave
258 // it alone so we can handle it in the paren expression.
259 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
260 // FIXME: We can't check this via lookahead before we consume the token
261 // because that tickles a lexer bug.
267 // Special case handling for the ternary operator.
268 ExprResult TernaryMiddle(true);
269 if (NextTokPrec == prec::Conditional) {
270 if (Tok.isNot(tok::colon)) {
271 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
272 ColonProtectionRAIIObject X(*this);
274 // Handle this production specially:
275 // logical-OR-expression '?' expression ':' conditional-expression
276 // In particular, the RHS of the '?' is 'expression', not
277 // 'logical-OR-expression' as we might expect.
278 TernaryMiddle = ParseExpression();
279 if (TernaryMiddle.isInvalid()) {
280 Actions.CorrectDelayedTyposInExpr(LHS);
282 TernaryMiddle = nullptr;
285 // Special case handling of "X ? Y : Z" where Y is empty:
286 // logical-OR-expression '?' ':' conditional-expression [GNU]
287 TernaryMiddle = nullptr;
288 Diag(Tok, diag::ext_gnu_conditional_expr);
291 if (!TryConsumeToken(tok::colon, ColonLoc)) {
292 // Otherwise, we're missing a ':'. Assume that this was a typo that
293 // the user forgot. If we're not in a macro expansion, we can suggest
294 // a fixit hint. If there were two spaces before the current token,
295 // suggest inserting the colon in between them, otherwise insert ": ".
296 SourceLocation FILoc = Tok.getLocation();
297 const char *FIText = ": ";
298 const SourceManager &SM = PP.getSourceManager();
299 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
300 assert(FILoc.isFileID());
301 bool IsInvalid = false;
302 const char *SourcePtr =
303 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
304 if (!IsInvalid && *SourcePtr == ' ') {
306 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
307 if (!IsInvalid && *SourcePtr == ' ') {
308 FILoc = FILoc.getLocWithOffset(-1);
314 Diag(Tok, diag::err_expected)
315 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
316 Diag(OpToken, diag::note_matching) << tok::question;
317 ColonLoc = Tok.getLocation();
321 // Code completion for the right-hand side of an assignment expression
322 // goes through a special hook that takes the left-hand side into account.
323 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
324 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
329 // Parse another leaf here for the RHS of the operator.
330 // ParseCastExpression works here because all RHS expressions in C have it
331 // as a prefix, at least. However, in C++, an assignment-expression could
332 // be a throw-expression, which is not a valid cast-expression.
333 // Therefore we need some special-casing here.
334 // Also note that the third operand of the conditional operator is
335 // an assignment-expression in C++, and in C++11, we can have a
336 // braced-init-list on the RHS of an assignment. For better diagnostics,
337 // parse as if we were allowed braced-init-lists everywhere, and check that
338 // they only appear on the RHS of assignments later.
340 bool RHSIsInitList = false;
341 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
342 RHS = ParseBraceInitializer();
343 RHSIsInitList = true;
344 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
345 RHS = ParseAssignmentExpression();
347 RHS = ParseCastExpression(false);
349 if (RHS.isInvalid()) {
350 // FIXME: Errors generated by the delayed typo correction should be
351 // printed before errors from parsing the RHS, not after.
352 Actions.CorrectDelayedTyposInExpr(LHS);
353 if (TernaryMiddle.isUsable())
354 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
358 // Remember the precedence of this operator and get the precedence of the
359 // operator immediately to the right of the RHS.
360 prec::Level ThisPrec = NextTokPrec;
361 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
362 getLangOpts().CPlusPlus11);
364 // Assignment and conditional expressions are right-associative.
365 bool isRightAssoc = ThisPrec == prec::Conditional ||
366 ThisPrec == prec::Assignment;
368 // Get the precedence of the operator to the right of the RHS. If it binds
369 // more tightly with RHS than we do, evaluate it completely first.
370 if (ThisPrec < NextTokPrec ||
371 (ThisPrec == NextTokPrec && isRightAssoc)) {
372 if (!RHS.isInvalid() && RHSIsInitList) {
373 Diag(Tok, diag::err_init_list_bin_op)
374 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
377 // If this is left-associative, only parse things on the RHS that bind
378 // more tightly than the current operator. If it is left-associative, it
379 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
380 // A=(B=(C=D)), where each paren is a level of recursion here.
381 // The function takes ownership of the RHS.
382 RHS = ParseRHSOfBinaryExpression(RHS,
383 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
384 RHSIsInitList = false;
386 if (RHS.isInvalid()) {
387 // FIXME: Errors generated by the delayed typo correction should be
388 // printed before errors from ParseRHSOfBinaryExpression, not after.
389 Actions.CorrectDelayedTyposInExpr(LHS);
390 if (TernaryMiddle.isUsable())
391 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
395 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
396 getLangOpts().CPlusPlus11);
399 if (!RHS.isInvalid() && RHSIsInitList) {
400 if (ThisPrec == prec::Assignment) {
401 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
402 << Actions.getExprRange(RHS.get());
404 Diag(OpToken, diag::err_init_list_bin_op)
405 << /*RHS*/1 << PP.getSpelling(OpToken)
406 << Actions.getExprRange(RHS.get());
411 if (!LHS.isInvalid()) {
412 // Combine the LHS and RHS into the LHS (e.g. build AST).
413 if (TernaryMiddle.isInvalid()) {
414 // If we're using '>>' as an operator within a template
415 // argument list (in C++98), suggest the addition of
416 // parentheses so that the code remains well-formed in C++0x.
417 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
418 SuggestParentheses(OpToken.getLocation(),
419 diag::warn_cxx11_right_shift_in_template_arg,
420 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
421 Actions.getExprRange(RHS.get()).getEnd()));
423 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
424 OpToken.getKind(), LHS.get(), RHS.get());
426 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
427 LHS.get(), TernaryMiddle.get(),
430 // Ensure potential typos in the RHS aren't left undiagnosed.
431 Actions.CorrectDelayedTyposInExpr(RHS);
435 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
436 /// parse a unary-expression.
438 /// \p isAddressOfOperand exists because an id-expression that is the
439 /// operand of address-of gets special treatment due to member pointers.
441 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
442 bool isAddressOfOperand,
443 TypeCastState isTypeCast) {
445 ExprResult Res = ParseCastExpression(isUnaryExpression,
450 Diag(Tok, diag::err_expected_expression);
455 class CastExpressionIdValidator : public CorrectionCandidateCallback {
457 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
458 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
459 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
462 bool ValidateCandidate(const TypoCorrection &candidate) override {
463 NamedDecl *ND = candidate.getCorrectionDecl();
465 return candidate.isKeyword();
467 if (isa<TypeDecl>(ND))
468 return WantTypeSpecifiers;
470 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
473 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
476 for (auto *C : candidate) {
477 NamedDecl *ND = C->getUnderlyingDecl();
478 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
490 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
491 /// a unary-expression.
493 /// \p isAddressOfOperand exists because an id-expression that is the operand
494 /// of address-of gets special treatment due to member pointers. NotCastExpr
495 /// is set to true if the token is not the start of a cast-expression, and no
496 /// diagnostic is emitted in this case.
499 /// cast-expression: [C99 6.5.4]
501 /// '(' type-name ')' cast-expression
503 /// unary-expression: [C99 6.5.3]
504 /// postfix-expression
505 /// '++' unary-expression
506 /// '--' unary-expression
507 /// unary-operator cast-expression
508 /// 'sizeof' unary-expression
509 /// 'sizeof' '(' type-name ')'
510 /// [C++11] 'sizeof' '...' '(' identifier ')'
511 /// [GNU] '__alignof' unary-expression
512 /// [GNU] '__alignof' '(' type-name ')'
513 /// [C11] '_Alignof' '(' type-name ')'
514 /// [C++11] 'alignof' '(' type-id ')'
515 /// [GNU] '&&' identifier
516 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
517 /// [C++] new-expression
518 /// [C++] delete-expression
520 /// unary-operator: one of
521 /// '&' '*' '+' '-' '~' '!'
522 /// [GNU] '__extension__' '__real' '__imag'
524 /// primary-expression: [C99 6.5.1]
526 /// [C++] id-expression
529 /// [C++] boolean-literal [C++ 2.13.5]
530 /// [C++11] 'nullptr' [C++11 2.14.7]
531 /// [C++11] user-defined-literal
532 /// '(' expression ')'
533 /// [C11] generic-selection
534 /// '__func__' [C99 6.4.2.2]
535 /// [GNU] '__FUNCTION__'
536 /// [MS] '__FUNCDNAME__'
537 /// [MS] 'L__FUNCTION__'
538 /// [GNU] '__PRETTY_FUNCTION__'
539 /// [GNU] '(' compound-statement ')'
540 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
541 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
542 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
544 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
546 /// [OBJC] '[' objc-message-expr ']'
547 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
548 /// [OBJC] '\@protocol' '(' identifier ')'
549 /// [OBJC] '\@encode' '(' type-name ')'
550 /// [OBJC] objc-string-literal
551 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
552 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
553 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
554 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
555 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
556 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
557 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
558 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
559 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
560 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
561 /// [C++] 'this' [C++ 9.3.2]
562 /// [G++] unary-type-trait '(' type-id ')'
563 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
564 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
565 /// [clang] '^' block-literal
567 /// constant: [C99 6.4.4]
569 /// floating-constant
570 /// enumeration-constant -> identifier
571 /// character-constant
573 /// id-expression: [C++ 5.1]
577 /// unqualified-id: [C++ 5.1]
579 /// operator-function-id
580 /// conversion-function-id
584 /// new-expression: [C++ 5.3.4]
585 /// '::'[opt] 'new' new-placement[opt] new-type-id
586 /// new-initializer[opt]
587 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
588 /// new-initializer[opt]
590 /// delete-expression: [C++ 5.3.5]
591 /// '::'[opt] 'delete' cast-expression
592 /// '::'[opt] 'delete' '[' ']' cast-expression
594 /// [GNU/Embarcadero] unary-type-trait:
595 /// '__is_arithmetic'
596 /// '__is_floating_point'
598 /// '__is_lvalue_expr'
599 /// '__is_rvalue_expr'
600 /// '__is_complete_type'
605 /// '__is_lvalue_reference'
606 /// '__is_rvalue_reference'
607 /// '__is_fundamental'
612 /// '__is_member_object_pointer'
613 /// '__is_member_function_pointer'
614 /// '__is_member_pointer'
618 /// '__is_standard_layout'
622 /// [GNU] unary-type-trait:
623 /// '__has_nothrow_assign'
624 /// '__has_nothrow_copy'
625 /// '__has_nothrow_constructor'
626 /// '__has_trivial_assign' [TODO]
627 /// '__has_trivial_copy' [TODO]
628 /// '__has_trivial_constructor'
629 /// '__has_trivial_destructor'
630 /// '__has_virtual_destructor'
631 /// '__is_abstract' [TODO]
633 /// '__is_empty' [TODO]
637 /// '__is_polymorphic'
638 /// '__is_sealed' [MS]
642 /// [Clang] unary-type-trait:
643 /// '__trivially_copyable'
645 /// binary-type-trait:
646 /// [GNU] '__is_base_of'
647 /// [MS] '__is_convertible_to'
648 /// '__is_convertible'
651 /// [Embarcadero] array-type-trait:
655 /// [Embarcadero] expression-trait:
656 /// '__is_lvalue_expr'
657 /// '__is_rvalue_expr'
660 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
661 bool isAddressOfOperand,
663 TypeCastState isTypeCast) {
665 tok::TokenKind SavedKind = Tok.getKind();
668 // This handles all of cast-expression, unary-expression, postfix-expression,
669 // and primary-expression. We handle them together like this for efficiency
670 // and to simplify handling of an expression starting with a '(' token: which
671 // may be one of a parenthesized expression, cast-expression, compound literal
672 // expression, or statement expression.
674 // If the parsed tokens consist of a primary-expression, the cases below
675 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
676 // to handle the postfix expression suffixes. Cases that cannot be followed
677 // by postfix exprs should return without invoking
678 // ParsePostfixExpressionSuffix.
681 // If this expression is limited to being a unary-expression, the parent can
682 // not start a cast expression.
683 ParenParseOption ParenExprType =
684 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
687 SourceLocation RParenLoc;
688 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
689 isTypeCast == IsTypeCast, CastTy, RParenLoc);
691 switch (ParenExprType) {
692 case SimpleExpr: break; // Nothing else to do.
693 case CompoundStmt: break; // Nothing else to do.
694 case CompoundLiteral:
695 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
696 // postfix-expression exist, parse them now.
699 // We have parsed the cast-expression and no postfix-expr pieces are
707 // primary-expression
708 case tok::numeric_constant:
709 // constant: integer-constant
710 // constant: floating-constant
712 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
718 return ParseCXXBoolLiteral();
720 case tok::kw___objc_yes:
721 case tok::kw___objc_no:
722 return ParseObjCBoolLiteral();
724 case tok::kw_nullptr:
725 Diag(Tok, diag::warn_cxx98_compat_nullptr);
726 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
728 case tok::annot_primary_expr:
729 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
730 Res = getExprAnnotation(Tok);
734 case tok::kw___super:
735 case tok::kw_decltype:
736 // Annotate the token and tail recurse.
737 if (TryAnnotateTypeOrScopeToken())
739 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
740 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
742 case tok::identifier: { // primary-expression: identifier
743 // unqualified-id: identifier
744 // constant: enumeration-constant
745 // Turn a potentially qualified name into a annot_typename or
746 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
747 if (getLangOpts().CPlusPlus) {
748 // Avoid the unnecessary parse-time lookup in the common case
749 // where the syntax forbids a type.
750 const Token &Next = NextToken();
752 // If this identifier was reverted from a token ID, and the next token
753 // is a parenthesis, this is likely to be a use of a type trait. Check
755 if (Next.is(tok::l_paren) &&
756 Tok.is(tok::identifier) &&
757 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
758 IdentifierInfo *II = Tok.getIdentifierInfo();
759 // Build up the mapping of revertible type traits, for future use.
760 if (RevertibleTypeTraits.empty()) {
761 #define RTT_JOIN(X,Y) X##Y
762 #define REVERTIBLE_TYPE_TRAIT(Name) \
763 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
764 = RTT_JOIN(tok::kw_,Name)
766 REVERTIBLE_TYPE_TRAIT(__is_abstract);
767 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
768 REVERTIBLE_TYPE_TRAIT(__is_array);
769 REVERTIBLE_TYPE_TRAIT(__is_base_of);
770 REVERTIBLE_TYPE_TRAIT(__is_class);
771 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
772 REVERTIBLE_TYPE_TRAIT(__is_compound);
773 REVERTIBLE_TYPE_TRAIT(__is_const);
774 REVERTIBLE_TYPE_TRAIT(__is_constructible);
775 REVERTIBLE_TYPE_TRAIT(__is_convertible);
776 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
777 REVERTIBLE_TYPE_TRAIT(__is_destructible);
778 REVERTIBLE_TYPE_TRAIT(__is_empty);
779 REVERTIBLE_TYPE_TRAIT(__is_enum);
780 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
781 REVERTIBLE_TYPE_TRAIT(__is_final);
782 REVERTIBLE_TYPE_TRAIT(__is_function);
783 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
784 REVERTIBLE_TYPE_TRAIT(__is_integral);
785 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
786 REVERTIBLE_TYPE_TRAIT(__is_literal);
787 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
788 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
789 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
790 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
791 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
792 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
793 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
794 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
795 REVERTIBLE_TYPE_TRAIT(__is_object);
796 REVERTIBLE_TYPE_TRAIT(__is_pod);
797 REVERTIBLE_TYPE_TRAIT(__is_pointer);
798 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
799 REVERTIBLE_TYPE_TRAIT(__is_reference);
800 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
801 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
802 REVERTIBLE_TYPE_TRAIT(__is_same);
803 REVERTIBLE_TYPE_TRAIT(__is_scalar);
804 REVERTIBLE_TYPE_TRAIT(__is_sealed);
805 REVERTIBLE_TYPE_TRAIT(__is_signed);
806 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
807 REVERTIBLE_TYPE_TRAIT(__is_trivial);
808 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
809 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
810 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
811 REVERTIBLE_TYPE_TRAIT(__is_union);
812 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
813 REVERTIBLE_TYPE_TRAIT(__is_void);
814 REVERTIBLE_TYPE_TRAIT(__is_volatile);
815 #undef REVERTIBLE_TYPE_TRAIT
819 // If we find that this is in fact the name of a type trait,
820 // update the token kind in place and parse again to treat it as
821 // the appropriate kind of type trait.
822 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
823 = RevertibleTypeTraits.find(II);
824 if (Known != RevertibleTypeTraits.end()) {
825 Tok.setKind(Known->second);
826 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
827 NotCastExpr, isTypeCast);
831 if ((!ColonIsSacred && Next.is(tok::colon)) ||
832 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
834 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
835 if (TryAnnotateTypeOrScopeToken())
837 if (!Tok.is(tok::identifier))
838 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
842 // Consume the identifier so that we can see if it is followed by a '(' or
844 IdentifierInfo &II = *Tok.getIdentifierInfo();
845 SourceLocation ILoc = ConsumeToken();
847 // Support 'Class.property' and 'super.property' notation.
848 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
849 (Actions.getTypeName(II, ILoc, getCurScope()) ||
850 // Allow the base to be 'super' if in an objc-method.
851 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
854 // Allow either an identifier or the keyword 'class' (in C++).
855 if (Tok.isNot(tok::identifier) &&
856 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
857 Diag(Tok, diag::err_expected_property_name);
860 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
861 SourceLocation PropertyLoc = ConsumeToken();
863 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
868 // In an Objective-C method, if we have "super" followed by an identifier,
869 // the token sequence is ill-formed. However, if there's a ':' or ']' after
870 // that identifier, this is probably a message send with a missing open
871 // bracket. Treat it as such.
872 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
873 getCurScope()->isInObjcMethodScope() &&
874 ((Tok.is(tok::identifier) &&
875 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
876 Tok.is(tok::code_completion))) {
877 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
882 // If we have an Objective-C class name followed by an identifier
883 // and either ':' or ']', this is an Objective-C class message
884 // send that's missing the opening '['. Recovery
885 // appropriately. Also take this path if we're performing code
886 // completion after an Objective-C class name.
887 if (getLangOpts().ObjC1 &&
888 ((Tok.is(tok::identifier) && !InMessageExpression) ||
889 Tok.is(tok::code_completion))) {
890 const Token& Next = NextToken();
891 if (Tok.is(tok::code_completion) ||
892 Next.is(tok::colon) || Next.is(tok::r_square))
893 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
894 if (Typ.get()->isObjCObjectOrInterfaceType()) {
895 // Fake up a Declarator to use with ActOnTypeName.
896 DeclSpec DS(AttrFactory);
897 DS.SetRangeStart(ILoc);
898 DS.SetRangeEnd(ILoc);
899 const char *PrevSpec = nullptr;
901 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
902 Actions.getASTContext().getPrintingPolicy());
904 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
905 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
910 Res = ParseObjCMessageExpressionBody(SourceLocation(),
917 // Make sure to pass down the right value for isAddressOfOperand.
918 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
919 isAddressOfOperand = false;
921 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
922 // need to know whether or not this identifier is a function designator or
925 CXXScopeSpec ScopeSpec;
926 SourceLocation TemplateKWLoc;
928 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
929 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
930 Validator->IsAddressOfOperand = isAddressOfOperand;
931 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
932 Validator->WantExpressionKeywords = false;
933 Validator->WantRemainingKeywords = false;
935 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
937 Name.setIdentifier(&II, ILoc);
938 Res = Actions.ActOnIdExpression(
939 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
940 isAddressOfOperand, std::move(Validator),
941 /*IsInlineAsmIdentifier=*/false,
942 Tok.is(tok::r_paren) ? nullptr : &Replacement);
943 if (!Res.isInvalid() && !Res.get()) {
944 UnconsumeToken(Replacement);
945 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
946 NotCastExpr, isTypeCast);
950 case tok::char_constant: // constant: character-constant
951 case tok::wide_char_constant:
952 case tok::utf8_char_constant:
953 case tok::utf16_char_constant:
954 case tok::utf32_char_constant:
955 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
958 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
959 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
960 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
961 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
962 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
963 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
964 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
967 case tok::string_literal: // primary-expression: string-literal
968 case tok::wide_string_literal:
969 case tok::utf8_string_literal:
970 case tok::utf16_string_literal:
971 case tok::utf32_string_literal:
972 Res = ParseStringLiteralExpression(true);
974 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
975 Res = ParseGenericSelectionExpression();
977 case tok::kw___builtin_va_arg:
978 case tok::kw___builtin_offsetof:
979 case tok::kw___builtin_choose_expr:
980 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
981 case tok::kw___builtin_convertvector:
982 return ParseBuiltinPrimaryExpression();
984 return Actions.ActOnGNUNullExpr(ConsumeToken());
986 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
987 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
988 // C++ [expr.unary] has:
990 // ++ cast-expression
991 // -- cast-expression
992 SourceLocation SavedLoc = ConsumeToken();
993 // One special case is implicitly handled here: if the preceding tokens are
994 // an ambiguous cast expression, such as "(T())++", then we recurse to
995 // determine whether the '++' is prefix or postfix.
996 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
997 /*isAddressOfOperand*/false, NotCastExpr,
999 if (!Res.isInvalid())
1000 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1003 case tok::amp: { // unary-expression: '&' cast-expression
1004 // Special treatment because of member pointers
1005 SourceLocation SavedLoc = ConsumeToken();
1006 Res = ParseCastExpression(false, true);
1007 if (!Res.isInvalid())
1008 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1012 case tok::star: // unary-expression: '*' cast-expression
1013 case tok::plus: // unary-expression: '+' cast-expression
1014 case tok::minus: // unary-expression: '-' cast-expression
1015 case tok::tilde: // unary-expression: '~' cast-expression
1016 case tok::exclaim: // unary-expression: '!' cast-expression
1017 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1018 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1019 SourceLocation SavedLoc = ConsumeToken();
1020 Res = ParseCastExpression(false);
1021 if (!Res.isInvalid())
1022 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1026 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1027 // __extension__ silences extension warnings in the subexpression.
1028 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1029 SourceLocation SavedLoc = ConsumeToken();
1030 Res = ParseCastExpression(false);
1031 if (!Res.isInvalid())
1032 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1035 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1036 if (!getLangOpts().C11)
1037 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1039 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1040 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1041 // unary-expression: '__alignof' '(' type-name ')'
1042 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1043 // unary-expression: 'sizeof' '(' type-name ')'
1044 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1045 return ParseUnaryExprOrTypeTraitExpression();
1046 case tok::ampamp: { // unary-expression: '&&' identifier
1047 SourceLocation AmpAmpLoc = ConsumeToken();
1048 if (Tok.isNot(tok::identifier))
1049 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1051 if (getCurScope()->getFnParent() == nullptr)
1052 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1054 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1055 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1057 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1061 case tok::kw_const_cast:
1062 case tok::kw_dynamic_cast:
1063 case tok::kw_reinterpret_cast:
1064 case tok::kw_static_cast:
1065 Res = ParseCXXCasts();
1067 case tok::kw_typeid:
1068 Res = ParseCXXTypeid();
1070 case tok::kw___uuidof:
1071 Res = ParseCXXUuidof();
1074 Res = ParseCXXThis();
1077 case tok::annot_typename:
1078 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1079 ParsedType Type = getTypeAnnotation(Tok);
1081 // Fake up a Declarator to use with ActOnTypeName.
1082 DeclSpec DS(AttrFactory);
1083 DS.SetRangeStart(Tok.getLocation());
1084 DS.SetRangeEnd(Tok.getLastLoc());
1086 const char *PrevSpec = nullptr;
1088 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1089 PrevSpec, DiagID, Type,
1090 Actions.getASTContext().getPrintingPolicy());
1092 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1093 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1098 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1104 case tok::annot_decltype:
1106 case tok::kw_wchar_t:
1107 case tok::kw_char16_t:
1108 case tok::kw_char32_t:
1113 case tok::kw___int64:
1114 case tok::kw___int128:
1115 case tok::kw_signed:
1116 case tok::kw_unsigned:
1119 case tok::kw_double:
1121 case tok::kw_typename:
1122 case tok::kw_typeof:
1123 case tok::kw___vector: {
1124 if (!getLangOpts().CPlusPlus) {
1125 Diag(Tok, diag::err_expected_expression);
1129 if (SavedKind == tok::kw_typename) {
1130 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1131 // typename-specifier braced-init-list
1132 if (TryAnnotateTypeOrScopeToken())
1135 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1136 // We are trying to parse a simple-type-specifier but might not get such
1137 // a token after error recovery.
1141 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1142 // simple-type-specifier braced-init-list
1144 DeclSpec DS(AttrFactory);
1146 ParseCXXSimpleTypeSpecifier(DS);
1147 if (Tok.isNot(tok::l_paren) &&
1148 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1149 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1150 << DS.getSourceRange());
1152 if (Tok.is(tok::l_brace))
1153 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1155 Res = ParseCXXTypeConstructExpression(DS);
1159 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1160 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1161 // (We can end up in this situation after tentative parsing.)
1162 if (TryAnnotateTypeOrScopeToken())
1164 if (!Tok.is(tok::annot_cxxscope))
1165 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1166 NotCastExpr, isTypeCast);
1168 Token Next = NextToken();
1169 if (Next.is(tok::annot_template_id)) {
1170 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1171 if (TemplateId->Kind == TNK_Type_template) {
1172 // We have a qualified template-id that we know refers to a
1173 // type, translate it into a type and continue parsing as a
1176 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1177 /*EnteringContext=*/false);
1178 AnnotateTemplateIdTokenAsType();
1179 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1180 NotCastExpr, isTypeCast);
1184 // Parse as an id-expression.
1185 Res = ParseCXXIdExpression(isAddressOfOperand);
1189 case tok::annot_template_id: { // [C++] template-id
1190 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1191 if (TemplateId->Kind == TNK_Type_template) {
1192 // We have a template-id that we know refers to a type,
1193 // translate it into a type and continue parsing as a cast
1195 AnnotateTemplateIdTokenAsType();
1196 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1197 NotCastExpr, isTypeCast);
1200 // Fall through to treat the template-id as an id-expression.
1203 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1204 Res = ParseCXXIdExpression(isAddressOfOperand);
1207 case tok::coloncolon: {
1208 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1209 // annotates the token, tail recurse.
1210 if (TryAnnotateTypeOrScopeToken())
1212 if (!Tok.is(tok::coloncolon))
1213 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1215 // ::new -> [C++] new-expression
1216 // ::delete -> [C++] delete-expression
1217 SourceLocation CCLoc = ConsumeToken();
1218 if (Tok.is(tok::kw_new))
1219 return ParseCXXNewExpression(true, CCLoc);
1220 if (Tok.is(tok::kw_delete))
1221 return ParseCXXDeleteExpression(true, CCLoc);
1223 // This is not a type name or scope specifier, it is an invalid expression.
1224 Diag(CCLoc, diag::err_expected_expression);
1228 case tok::kw_new: // [C++] new-expression
1229 return ParseCXXNewExpression(false, Tok.getLocation());
1231 case tok::kw_delete: // [C++] delete-expression
1232 return ParseCXXDeleteExpression(false, Tok.getLocation());
1234 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1235 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1236 SourceLocation KeyLoc = ConsumeToken();
1237 BalancedDelimiterTracker T(*this, tok::l_paren);
1239 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1241 // C++11 [expr.unary.noexcept]p1:
1242 // The noexcept operator determines whether the evaluation of its operand,
1243 // which is an unevaluated operand, can throw an exception.
1244 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1245 ExprResult Result = ParseExpression();
1249 if (!Result.isInvalid())
1250 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1251 Result.get(), T.getCloseLocation());
1255 #define TYPE_TRAIT(N,Spelling,K) \
1256 case tok::kw_##Spelling:
1257 #include "clang/Basic/TokenKinds.def"
1258 return ParseTypeTrait();
1260 case tok::kw___array_rank:
1261 case tok::kw___array_extent:
1262 return ParseArrayTypeTrait();
1264 case tok::kw___is_lvalue_expr:
1265 case tok::kw___is_rvalue_expr:
1266 return ParseExpressionTrait();
1269 SourceLocation AtLoc = ConsumeToken();
1270 return ParseObjCAtExpression(AtLoc);
1273 Res = ParseBlockLiteralExpression();
1275 case tok::code_completion: {
1276 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1281 if (getLangOpts().CPlusPlus11) {
1282 if (getLangOpts().ObjC1) {
1283 // C++11 lambda expressions and Objective-C message sends both start with a
1284 // square bracket. There are three possibilities here:
1285 // we have a valid lambda expression, we have an invalid lambda
1286 // expression, or we have something that doesn't appear to be a lambda.
1287 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1288 Res = TryParseLambdaExpression();
1289 if (!Res.isInvalid() && !Res.get())
1290 Res = ParseObjCMessageExpression();
1293 Res = ParseLambdaExpression();
1296 if (getLangOpts().ObjC1) {
1297 Res = ParseObjCMessageExpression();
1306 // These can be followed by postfix-expr pieces.
1307 return ParsePostfixExpressionSuffix(Res);
1310 /// \brief Once the leading part of a postfix-expression is parsed, this
1311 /// method parses any suffixes that apply.
1314 /// postfix-expression: [C99 6.5.2]
1315 /// primary-expression
1316 /// postfix-expression '[' expression ']'
1317 /// postfix-expression '[' braced-init-list ']'
1318 /// postfix-expression '(' argument-expression-list[opt] ')'
1319 /// postfix-expression '.' identifier
1320 /// postfix-expression '->' identifier
1321 /// postfix-expression '++'
1322 /// postfix-expression '--'
1323 /// '(' type-name ')' '{' initializer-list '}'
1324 /// '(' type-name ')' '{' initializer-list ',' '}'
1326 /// argument-expression-list: [C99 6.5.2]
1327 /// argument-expression ...[opt]
1328 /// argument-expression-list ',' assignment-expression ...[opt]
1331 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1332 // Now that the primary-expression piece of the postfix-expression has been
1333 // parsed, see if there are any postfix-expression pieces here.
1336 switch (Tok.getKind()) {
1337 case tok::code_completion:
1338 if (InMessageExpression)
1341 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1345 case tok::identifier:
1346 // If we see identifier: after an expression, and we're not already in a
1347 // message send, then this is probably a message send with a missing
1348 // opening bracket '['.
1349 if (getLangOpts().ObjC1 && !InMessageExpression &&
1350 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1351 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1352 ParsedType(), LHS.get());
1356 // Fall through; this isn't a message send.
1358 default: // Not a postfix-expression suffix.
1360 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1361 // If we have a array postfix expression that starts on a new line and
1362 // Objective-C is enabled, it is highly likely that the user forgot a
1363 // semicolon after the base expression and that the array postfix-expr is
1364 // actually another message send. In this case, do some look-ahead to see
1365 // if the contents of the square brackets are obviously not a valid
1366 // expression and recover by pretending there is no suffix.
1367 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1368 isSimpleObjCMessageExpression())
1371 // Reject array indices starting with a lambda-expression. '[[' is
1372 // reserved for attributes.
1373 if (CheckProhibitedCXX11Attribute())
1376 BalancedDelimiterTracker T(*this, tok::l_square);
1378 Loc = T.getOpenLocation();
1380 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1381 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1382 Idx = ParseBraceInitializer();
1384 Idx = ParseExpression();
1386 SourceLocation RLoc = Tok.getLocation();
1388 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
1389 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1392 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1393 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1403 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1404 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1405 // '(' argument-expression-list[opt] ')'
1406 tok::TokenKind OpKind = Tok.getKind();
1407 InMessageExpressionRAIIObject InMessage(*this, false);
1409 Expr *ExecConfig = nullptr;
1411 BalancedDelimiterTracker PT(*this, tok::l_paren);
1413 if (OpKind == tok::lesslessless) {
1414 ExprVector ExecConfigExprs;
1415 CommaLocsTy ExecConfigCommaLocs;
1416 SourceLocation OpenLoc = ConsumeToken();
1418 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1419 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1423 SourceLocation CloseLoc;
1424 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1425 } else if (LHS.isInvalid()) {
1426 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1428 // There was an error closing the brackets
1429 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1430 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1431 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1435 if (!LHS.isInvalid()) {
1436 if (ExpectAndConsume(tok::l_paren))
1439 Loc = PrevTokLocation;
1442 if (!LHS.isInvalid()) {
1443 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1447 if (ECResult.isInvalid())
1450 ExecConfig = ECResult.get();
1454 Loc = PT.getOpenLocation();
1457 ExprVector ArgExprs;
1458 CommaLocsTy CommaLocs;
1460 if (Tok.is(tok::code_completion)) {
1461 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1466 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1467 if (Tok.isNot(tok::r_paren)) {
1468 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1469 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1471 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1473 } else if (LHS.isInvalid()) {
1474 for (auto &E : ArgExprs)
1475 Actions.CorrectDelayedTyposInExpr(E);
1481 if (LHS.isInvalid()) {
1482 SkipUntil(tok::r_paren, StopAtSemi);
1483 } else if (Tok.isNot(tok::r_paren)) {
1484 bool HadDelayedTypo = false;
1485 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1486 HadDelayedTypo = true;
1487 for (auto &E : ArgExprs)
1488 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1489 HadDelayedTypo = true;
1490 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1491 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1492 // the unmatched l_paren.
1494 SkipUntil(tok::r_paren, StopAtSemi);
1499 assert((ArgExprs.size() == 0 ||
1500 ArgExprs.size()-1 == CommaLocs.size())&&
1501 "Unexpected number of commas!");
1502 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1503 ArgExprs, Tok.getLocation(),
1512 // postfix-expression: p-e '->' template[opt] id-expression
1513 // postfix-expression: p-e '.' template[opt] id-expression
1514 tok::TokenKind OpKind = Tok.getKind();
1515 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1518 ParsedType ObjectType;
1519 bool MayBePseudoDestructor = false;
1520 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1521 Expr *Base = LHS.get();
1522 const Type* BaseType = Base->getType().getTypePtrOrNull();
1523 if (BaseType && Tok.is(tok::l_paren) &&
1524 (BaseType->isFunctionType() ||
1525 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1526 Diag(OpLoc, diag::err_function_is_not_record)
1527 << OpKind << Base->getSourceRange()
1528 << FixItHint::CreateRemoval(OpLoc);
1529 return ParsePostfixExpressionSuffix(Base);
1532 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1533 OpLoc, OpKind, ObjectType,
1534 MayBePseudoDestructor);
1535 if (LHS.isInvalid())
1538 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1539 /*EnteringContext=*/false,
1540 &MayBePseudoDestructor);
1541 if (SS.isNotEmpty())
1542 ObjectType = ParsedType();
1545 if (Tok.is(tok::code_completion)) {
1546 // Code completion for a member access expression.
1547 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1548 OpLoc, OpKind == tok::arrow);
1554 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1555 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1560 // Either the action has told us that this cannot be a
1561 // pseudo-destructor expression (based on the type of base
1562 // expression), or we didn't see a '~' in the right place. We
1563 // can still parse a destructor name here, but in that case it
1564 // names a real destructor.
1565 // Allow explicit constructor calls in Microsoft mode.
1566 // FIXME: Add support for explicit call of template constructor.
1567 SourceLocation TemplateKWLoc;
1569 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1570 Tok.is(tok::kw_class)) {
1572 // After a '.' in a member access expression, treat the keyword
1573 // 'class' as if it were an identifier.
1575 // This hack allows property access to the 'class' method because it is
1576 // such a common method name. For other C++ keywords that are
1577 // Objective-C method names, one must use the message send syntax.
1578 IdentifierInfo *Id = Tok.getIdentifierInfo();
1579 SourceLocation Loc = ConsumeToken();
1580 Name.setIdentifier(Id, Loc);
1581 } else if (ParseUnqualifiedId(SS,
1582 /*EnteringContext=*/false,
1583 /*AllowDestructorName=*/true,
1584 /*AllowConstructorName=*/
1585 getLangOpts().MicrosoftExt,
1586 ObjectType, TemplateKWLoc, Name)) {
1587 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1591 if (!LHS.isInvalid())
1592 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1593 OpKind, SS, TemplateKWLoc, Name,
1594 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1598 case tok::plusplus: // postfix-expression: postfix-expression '++'
1599 case tok::minusminus: // postfix-expression: postfix-expression '--'
1600 if (!LHS.isInvalid()) {
1601 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1602 Tok.getKind(), LHS.get());
1610 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1611 /// vec_step and we are at the start of an expression or a parenthesized
1612 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1613 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1616 /// unary-expression: [C99 6.5.3]
1617 /// 'sizeof' unary-expression
1618 /// 'sizeof' '(' type-name ')'
1619 /// [GNU] '__alignof' unary-expression
1620 /// [GNU] '__alignof' '(' type-name ')'
1621 /// [C11] '_Alignof' '(' type-name ')'
1622 /// [C++0x] 'alignof' '(' type-id ')'
1624 /// [GNU] typeof-specifier:
1625 /// typeof ( expressions )
1626 /// typeof ( type-name )
1627 /// [GNU/C++] typeof unary-expression
1629 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1630 /// vec_step ( expressions )
1631 /// vec_step ( type-name )
1634 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1637 SourceRange &CastRange) {
1639 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1640 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step) &&
1641 "Not a typeof/sizeof/alignof/vec_step expression!");
1645 // If the operand doesn't start with an '(', it must be an expression.
1646 if (Tok.isNot(tok::l_paren)) {
1647 // If construct allows a form without parenthesis, user may forget to put
1648 // pathenthesis around type name.
1649 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1650 tok::kw__Alignof)) {
1651 if (isTypeIdUnambiguously()) {
1652 DeclSpec DS(AttrFactory);
1653 ParseSpecifierQualifierList(DS);
1654 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1655 ParseDeclarator(DeclaratorInfo);
1657 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1658 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1659 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1661 << FixItHint::CreateInsertion(LParenLoc, "(")
1662 << FixItHint::CreateInsertion(RParenLoc, ")");
1669 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1670 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1675 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1677 // If it starts with a '(', we know that it is either a parenthesized
1678 // type-name, or it is a unary-expression that starts with a compound
1679 // literal, or starts with a primary-expression that is a parenthesized
1681 ParenParseOption ExprType = CastExpr;
1682 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1684 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1685 false, CastTy, RParenLoc);
1686 CastRange = SourceRange(LParenLoc, RParenLoc);
1688 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1690 if (ExprType == CastExpr) {
1695 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1696 // GNU typeof in C requires the expression to be parenthesized. Not so for
1697 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1698 // the start of a unary-expression, but doesn't include any postfix
1699 // pieces. Parse these now if present.
1700 if (!Operand.isInvalid())
1701 Operand = ParsePostfixExpressionSuffix(Operand.get());
1705 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1711 /// \brief Parse a sizeof or alignof expression.
1714 /// unary-expression: [C99 6.5.3]
1715 /// 'sizeof' unary-expression
1716 /// 'sizeof' '(' type-name ')'
1717 /// [C++11] 'sizeof' '...' '(' identifier ')'
1718 /// [GNU] '__alignof' unary-expression
1719 /// [GNU] '__alignof' '(' type-name ')'
1720 /// [C11] '_Alignof' '(' type-name ')'
1721 /// [C++11] 'alignof' '(' type-id ')'
1723 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1724 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1725 tok::kw__Alignof, tok::kw_vec_step) &&
1726 "Not a sizeof/alignof/vec_step expression!");
1730 // [C++11] 'sizeof' '...' '(' identifier ')'
1731 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1732 SourceLocation EllipsisLoc = ConsumeToken();
1733 SourceLocation LParenLoc, RParenLoc;
1734 IdentifierInfo *Name = nullptr;
1735 SourceLocation NameLoc;
1736 if (Tok.is(tok::l_paren)) {
1737 BalancedDelimiterTracker T(*this, tok::l_paren);
1739 LParenLoc = T.getOpenLocation();
1740 if (Tok.is(tok::identifier)) {
1741 Name = Tok.getIdentifierInfo();
1742 NameLoc = ConsumeToken();
1744 RParenLoc = T.getCloseLocation();
1745 if (RParenLoc.isInvalid())
1746 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1748 Diag(Tok, diag::err_expected_parameter_pack);
1749 SkipUntil(tok::r_paren, StopAtSemi);
1751 } else if (Tok.is(tok::identifier)) {
1752 Name = Tok.getIdentifierInfo();
1753 NameLoc = ConsumeToken();
1754 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1755 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1756 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1758 << FixItHint::CreateInsertion(LParenLoc, "(")
1759 << FixItHint::CreateInsertion(RParenLoc, ")");
1761 Diag(Tok, diag::err_sizeof_parameter_pack);
1767 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1768 Sema::ReuseLambdaContextDecl);
1770 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1771 OpTok.getLocation(),
1776 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1777 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1779 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1780 Sema::ReuseLambdaContextDecl);
1784 SourceRange CastRange;
1785 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1790 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1791 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1792 ExprKind = UETT_AlignOf;
1793 else if (OpTok.is(tok::kw_vec_step))
1794 ExprKind = UETT_VecStep;
1797 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1800 CastTy.getAsOpaquePtr(),
1803 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1804 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1806 // If we get here, the operand to the sizeof/alignof was an expresion.
1807 if (!Operand.isInvalid())
1808 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1816 /// ParseBuiltinPrimaryExpression
1819 /// primary-expression: [C99 6.5.1]
1820 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1821 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1822 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1824 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1825 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1827 /// [GNU] offsetof-member-designator:
1828 /// [GNU] identifier
1829 /// [GNU] offsetof-member-designator '.' identifier
1830 /// [GNU] offsetof-member-designator '[' expression ']'
1832 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1834 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1836 tok::TokenKind T = Tok.getKind();
1837 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1839 // All of these start with an open paren.
1840 if (Tok.isNot(tok::l_paren))
1841 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1844 BalancedDelimiterTracker PT(*this, tok::l_paren);
1850 default: llvm_unreachable("Not a builtin primary expression!");
1851 case tok::kw___builtin_va_arg: {
1852 ExprResult Expr(ParseAssignmentExpression());
1854 if (ExpectAndConsume(tok::comma)) {
1855 SkipUntil(tok::r_paren, StopAtSemi);
1859 TypeResult Ty = ParseTypeName();
1861 if (Tok.isNot(tok::r_paren)) {
1862 Diag(Tok, diag::err_expected) << tok::r_paren;
1866 if (Expr.isInvalid() || Ty.isInvalid())
1869 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1872 case tok::kw___builtin_offsetof: {
1873 SourceLocation TypeLoc = Tok.getLocation();
1874 TypeResult Ty = ParseTypeName();
1875 if (Ty.isInvalid()) {
1876 SkipUntil(tok::r_paren, StopAtSemi);
1880 if (ExpectAndConsume(tok::comma)) {
1881 SkipUntil(tok::r_paren, StopAtSemi);
1885 // We must have at least one identifier here.
1886 if (Tok.isNot(tok::identifier)) {
1887 Diag(Tok, diag::err_expected) << tok::identifier;
1888 SkipUntil(tok::r_paren, StopAtSemi);
1892 // Keep track of the various subcomponents we see.
1893 SmallVector<Sema::OffsetOfComponent, 4> Comps;
1895 Comps.push_back(Sema::OffsetOfComponent());
1896 Comps.back().isBrackets = false;
1897 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1898 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1900 // FIXME: This loop leaks the index expressions on error.
1902 if (Tok.is(tok::period)) {
1903 // offsetof-member-designator: offsetof-member-designator '.' identifier
1904 Comps.push_back(Sema::OffsetOfComponent());
1905 Comps.back().isBrackets = false;
1906 Comps.back().LocStart = ConsumeToken();
1908 if (Tok.isNot(tok::identifier)) {
1909 Diag(Tok, diag::err_expected) << tok::identifier;
1910 SkipUntil(tok::r_paren, StopAtSemi);
1913 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1914 Comps.back().LocEnd = ConsumeToken();
1916 } else if (Tok.is(tok::l_square)) {
1917 if (CheckProhibitedCXX11Attribute())
1920 // offsetof-member-designator: offsetof-member-design '[' expression ']'
1921 Comps.push_back(Sema::OffsetOfComponent());
1922 Comps.back().isBrackets = true;
1923 BalancedDelimiterTracker ST(*this, tok::l_square);
1925 Comps.back().LocStart = ST.getOpenLocation();
1926 Res = ParseExpression();
1927 if (Res.isInvalid()) {
1928 SkipUntil(tok::r_paren, StopAtSemi);
1931 Comps.back().U.E = Res.get();
1934 Comps.back().LocEnd = ST.getCloseLocation();
1936 if (Tok.isNot(tok::r_paren)) {
1939 } else if (Ty.isInvalid()) {
1943 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
1944 Ty.get(), &Comps[0], Comps.size(),
1945 PT.getCloseLocation());
1952 case tok::kw___builtin_choose_expr: {
1953 ExprResult Cond(ParseAssignmentExpression());
1954 if (Cond.isInvalid()) {
1955 SkipUntil(tok::r_paren, StopAtSemi);
1958 if (ExpectAndConsume(tok::comma)) {
1959 SkipUntil(tok::r_paren, StopAtSemi);
1963 ExprResult Expr1(ParseAssignmentExpression());
1964 if (Expr1.isInvalid()) {
1965 SkipUntil(tok::r_paren, StopAtSemi);
1968 if (ExpectAndConsume(tok::comma)) {
1969 SkipUntil(tok::r_paren, StopAtSemi);
1973 ExprResult Expr2(ParseAssignmentExpression());
1974 if (Expr2.isInvalid()) {
1975 SkipUntil(tok::r_paren, StopAtSemi);
1978 if (Tok.isNot(tok::r_paren)) {
1979 Diag(Tok, diag::err_expected) << tok::r_paren;
1982 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
1983 Expr2.get(), ConsumeParen());
1986 case tok::kw___builtin_astype: {
1987 // The first argument is an expression to be converted, followed by a comma.
1988 ExprResult Expr(ParseAssignmentExpression());
1989 if (Expr.isInvalid()) {
1990 SkipUntil(tok::r_paren, StopAtSemi);
1994 if (ExpectAndConsume(tok::comma)) {
1995 SkipUntil(tok::r_paren, StopAtSemi);
1999 // Second argument is the type to bitcast to.
2000 TypeResult DestTy = ParseTypeName();
2001 if (DestTy.isInvalid())
2004 // Attempt to consume the r-paren.
2005 if (Tok.isNot(tok::r_paren)) {
2006 Diag(Tok, diag::err_expected) << tok::r_paren;
2007 SkipUntil(tok::r_paren, StopAtSemi);
2011 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2015 case tok::kw___builtin_convertvector: {
2016 // The first argument is an expression to be converted, followed by a comma.
2017 ExprResult Expr(ParseAssignmentExpression());
2018 if (Expr.isInvalid()) {
2019 SkipUntil(tok::r_paren, StopAtSemi);
2023 if (ExpectAndConsume(tok::comma)) {
2024 SkipUntil(tok::r_paren, StopAtSemi);
2028 // Second argument is the type to bitcast to.
2029 TypeResult DestTy = ParseTypeName();
2030 if (DestTy.isInvalid())
2033 // Attempt to consume the r-paren.
2034 if (Tok.isNot(tok::r_paren)) {
2035 Diag(Tok, diag::err_expected) << tok::r_paren;
2036 SkipUntil(tok::r_paren, StopAtSemi);
2040 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2046 if (Res.isInvalid())
2049 // These can be followed by postfix-expr pieces because they are
2050 // primary-expressions.
2051 return ParsePostfixExpressionSuffix(Res.get());
2054 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2055 /// based on what is allowed by ExprType. The actual thing parsed is returned
2056 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2057 /// not the parsed cast-expression.
2060 /// primary-expression: [C99 6.5.1]
2061 /// '(' expression ')'
2062 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2063 /// postfix-expression: [C99 6.5.2]
2064 /// '(' type-name ')' '{' initializer-list '}'
2065 /// '(' type-name ')' '{' initializer-list ',' '}'
2066 /// cast-expression: [C99 6.5.4]
2067 /// '(' type-name ')' cast-expression
2068 /// [ARC] bridged-cast-expression
2069 /// [ARC] bridged-cast-expression:
2070 /// (__bridge type-name) cast-expression
2071 /// (__bridge_transfer type-name) cast-expression
2072 /// (__bridge_retained type-name) cast-expression
2073 /// fold-expression: [C++1z]
2074 /// '(' cast-expression fold-operator '...' ')'
2075 /// '(' '...' fold-operator cast-expression ')'
2076 /// '(' cast-expression fold-operator '...'
2077 /// fold-operator cast-expression ')'
2080 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2081 bool isTypeCast, ParsedType &CastTy,
2082 SourceLocation &RParenLoc) {
2083 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2084 ColonProtectionRAIIObject ColonProtection(*this, false);
2085 BalancedDelimiterTracker T(*this, tok::l_paren);
2086 if (T.consumeOpen())
2088 SourceLocation OpenLoc = T.getOpenLocation();
2090 ExprResult Result(true);
2091 bool isAmbiguousTypeId;
2092 CastTy = ParsedType();
2094 if (Tok.is(tok::code_completion)) {
2095 Actions.CodeCompleteOrdinaryName(getCurScope(),
2096 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2097 : Sema::PCC_Expression);
2102 // Diagnose use of bridge casts in non-arc mode.
2103 bool BridgeCast = (getLangOpts().ObjC2 &&
2104 Tok.isOneOf(tok::kw___bridge,
2105 tok::kw___bridge_transfer,
2106 tok::kw___bridge_retained,
2107 tok::kw___bridge_retain));
2108 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2109 if (!TryConsumeToken(tok::kw___bridge)) {
2110 StringRef BridgeCastName = Tok.getName();
2111 SourceLocation BridgeKeywordLoc = ConsumeToken();
2112 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2113 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2115 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2120 // None of these cases should fall through with an invalid Result
2121 // unless they've already reported an error.
2122 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2123 Diag(Tok, diag::ext_gnu_statement_expr);
2125 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2126 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2128 // Find the nearest non-record decl context. Variables declared in a
2129 // statement expression behave as if they were declared in the enclosing
2130 // function, block, or other code construct.
2131 DeclContext *CodeDC = Actions.CurContext;
2132 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2133 CodeDC = CodeDC->getParent();
2134 assert(CodeDC && !CodeDC->isFileContext() &&
2135 "statement expr not in code context");
2137 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2139 Actions.ActOnStartStmtExpr();
2141 StmtResult Stmt(ParseCompoundStatement(true));
2142 ExprType = CompoundStmt;
2144 // If the substmt parsed correctly, build the AST node.
2145 if (!Stmt.isInvalid()) {
2146 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2148 Actions.ActOnStmtExprError();
2151 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2152 tok::TokenKind tokenKind = Tok.getKind();
2153 SourceLocation BridgeKeywordLoc = ConsumeToken();
2155 // Parse an Objective-C ARC ownership cast expression.
2156 ObjCBridgeCastKind Kind;
2157 if (tokenKind == tok::kw___bridge)
2159 else if (tokenKind == tok::kw___bridge_transfer)
2160 Kind = OBC_BridgeTransfer;
2161 else if (tokenKind == tok::kw___bridge_retained)
2162 Kind = OBC_BridgeRetained;
2164 // As a hopefully temporary workaround, allow __bridge_retain as
2165 // a synonym for __bridge_retained, but only in system headers.
2166 assert(tokenKind == tok::kw___bridge_retain);
2167 Kind = OBC_BridgeRetained;
2168 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2169 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2170 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2171 "__bridge_retained");
2174 TypeResult Ty = ParseTypeName();
2176 ColonProtection.restore();
2177 RParenLoc = T.getCloseLocation();
2178 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2180 if (Ty.isInvalid() || SubExpr.isInvalid())
2183 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2184 BridgeKeywordLoc, Ty.get(),
2185 RParenLoc, SubExpr.get());
2186 } else if (ExprType >= CompoundLiteral &&
2187 isTypeIdInParens(isAmbiguousTypeId)) {
2189 // Otherwise, this is a compound literal expression or cast expression.
2191 // In C++, if the type-id is ambiguous we disambiguate based on context.
2192 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2193 // in which case we should treat it as type-id.
2194 // if stopIfCastExpr is false, we need to determine the context past the
2195 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2196 if (isAmbiguousTypeId && !stopIfCastExpr) {
2197 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2199 RParenLoc = T.getCloseLocation();
2203 // Parse the type declarator.
2204 DeclSpec DS(AttrFactory);
2205 ParseSpecifierQualifierList(DS);
2206 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2207 ParseDeclarator(DeclaratorInfo);
2209 // If our type is followed by an identifier and either ':' or ']', then
2210 // this is probably an Objective-C message send where the leading '[' is
2211 // missing. Recover as if that were the case.
2212 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2213 !InMessageExpression && getLangOpts().ObjC1 &&
2214 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2217 InMessageExpressionRAIIObject InMessage(*this, false);
2218 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2220 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2226 ColonProtection.restore();
2227 RParenLoc = T.getCloseLocation();
2228 if (Tok.is(tok::l_brace)) {
2229 ExprType = CompoundLiteral;
2232 InMessageExpressionRAIIObject InMessage(*this, false);
2233 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2235 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2238 if (ExprType == CastExpr) {
2239 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2241 if (DeclaratorInfo.isInvalidType())
2244 // Note that this doesn't parse the subsequent cast-expression, it just
2245 // returns the parsed type to the callee.
2246 if (stopIfCastExpr) {
2249 InMessageExpressionRAIIObject InMessage(*this, false);
2250 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2253 return ExprResult();
2256 // Reject the cast of super idiom in ObjC.
2257 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2258 Tok.getIdentifierInfo() == Ident_super &&
2259 getCurScope()->isInObjcMethodScope() &&
2260 GetLookAheadToken(1).isNot(tok::period)) {
2261 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2262 << SourceRange(OpenLoc, RParenLoc);
2266 // Parse the cast-expression that follows it next.
2267 // TODO: For cast expression with CastTy.
2268 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2269 /*isAddressOfOperand=*/false,
2270 /*isTypeCast=*/IsTypeCast);
2271 if (!Result.isInvalid()) {
2272 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2273 DeclaratorInfo, CastTy,
2274 RParenLoc, Result.get());
2279 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2282 } else if (Tok.is(tok::ellipsis) &&
2283 isFoldOperator(NextToken().getKind())) {
2284 return ParseFoldExpression(ExprResult(), T);
2285 } else if (isTypeCast) {
2286 // Parse the expression-list.
2287 InMessageExpressionRAIIObject InMessage(*this, false);
2289 ExprVector ArgExprs;
2290 CommaLocsTy CommaLocs;
2292 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2293 // FIXME: If we ever support comma expressions as operands to
2294 // fold-expressions, we'll need to allow multiple ArgExprs here.
2295 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2296 NextToken().is(tok::ellipsis))
2297 return ParseFoldExpression(Result, T);
2299 ExprType = SimpleExpr;
2300 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2304 InMessageExpressionRAIIObject InMessage(*this, false);
2306 Result = ParseExpression(MaybeTypeCast);
2307 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2308 // Correct typos in non-C++ code earlier so that implicit-cast-like
2309 // expressions are parsed correctly.
2310 Result = Actions.CorrectDelayedTyposInExpr(Result);
2312 ExprType = SimpleExpr;
2314 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2315 return ParseFoldExpression(Result, T);
2317 // Don't build a paren expression unless we actually match a ')'.
2318 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2320 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2324 if (Result.isInvalid()) {
2325 SkipUntil(tok::r_paren, StopAtSemi);
2330 RParenLoc = T.getCloseLocation();
2334 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2335 /// and we are at the left brace.
2338 /// postfix-expression: [C99 6.5.2]
2339 /// '(' type-name ')' '{' initializer-list '}'
2340 /// '(' type-name ')' '{' initializer-list ',' '}'
2343 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2344 SourceLocation LParenLoc,
2345 SourceLocation RParenLoc) {
2346 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2347 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2348 Diag(LParenLoc, diag::ext_c99_compound_literal);
2349 ExprResult Result = ParseInitializer();
2350 if (!Result.isInvalid() && Ty)
2351 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2355 /// ParseStringLiteralExpression - This handles the various token types that
2356 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2357 /// translation phase #6].
2360 /// primary-expression: [C99 6.5.1]
2363 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2364 assert(isTokenStringLiteral() && "Not a string literal!");
2366 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2367 // considered to be strings for concatenation purposes.
2368 SmallVector<Token, 4> StringToks;
2371 StringToks.push_back(Tok);
2372 ConsumeStringToken();
2373 } while (isTokenStringLiteral());
2375 // Pass the set of string tokens, ready for concatenation, to the actions.
2376 return Actions.ActOnStringLiteral(StringToks,
2377 AllowUserDefinedLiteral ? getCurScope()
2381 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2385 /// generic-selection:
2386 /// _Generic ( assignment-expression , generic-assoc-list )
2387 /// generic-assoc-list:
2388 /// generic-association
2389 /// generic-assoc-list , generic-association
2390 /// generic-association:
2391 /// type-name : assignment-expression
2392 /// default : assignment-expression
2394 ExprResult Parser::ParseGenericSelectionExpression() {
2395 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2396 SourceLocation KeyLoc = ConsumeToken();
2398 if (!getLangOpts().C11)
2399 Diag(KeyLoc, diag::ext_c11_generic_selection);
2401 BalancedDelimiterTracker T(*this, tok::l_paren);
2402 if (T.expectAndConsume())
2405 ExprResult ControllingExpr;
2407 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2409 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2411 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2412 if (ControllingExpr.isInvalid()) {
2413 SkipUntil(tok::r_paren, StopAtSemi);
2418 if (ExpectAndConsume(tok::comma)) {
2419 SkipUntil(tok::r_paren, StopAtSemi);
2423 SourceLocation DefaultLoc;
2428 if (Tok.is(tok::kw_default)) {
2429 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2430 // generic association."
2431 if (!DefaultLoc.isInvalid()) {
2432 Diag(Tok, diag::err_duplicate_default_assoc);
2433 Diag(DefaultLoc, diag::note_previous_default_assoc);
2434 SkipUntil(tok::r_paren, StopAtSemi);
2437 DefaultLoc = ConsumeToken();
2440 ColonProtectionRAIIObject X(*this);
2441 TypeResult TR = ParseTypeName();
2442 if (TR.isInvalid()) {
2443 SkipUntil(tok::r_paren, StopAtSemi);
2448 Types.push_back(Ty);
2450 if (ExpectAndConsume(tok::colon)) {
2451 SkipUntil(tok::r_paren, StopAtSemi);
2455 // FIXME: These expressions should be parsed in a potentially potentially
2456 // evaluated context.
2458 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2459 if (ER.isInvalid()) {
2460 SkipUntil(tok::r_paren, StopAtSemi);
2463 Exprs.push_back(ER.get());
2464 } while (TryConsumeToken(tok::comma));
2467 if (T.getCloseLocation().isInvalid())
2470 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2471 T.getCloseLocation(),
2472 ControllingExpr.get(),
2476 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2477 /// left-hand-side expression.
2480 /// fold-expression:
2481 /// ( cast-expression fold-operator ... )
2482 /// ( ... fold-operator cast-expression )
2483 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2484 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2485 BalancedDelimiterTracker &T) {
2486 if (LHS.isInvalid()) {
2491 tok::TokenKind Kind = tok::unknown;
2492 SourceLocation FirstOpLoc;
2493 if (LHS.isUsable()) {
2494 Kind = Tok.getKind();
2495 assert(isFoldOperator(Kind) && "missing fold-operator");
2496 FirstOpLoc = ConsumeToken();
2499 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2500 SourceLocation EllipsisLoc = ConsumeToken();
2503 if (Tok.isNot(tok::r_paren)) {
2504 if (!isFoldOperator(Tok.getKind()))
2505 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2507 if (Kind != tok::unknown && Tok.getKind() != Kind)
2508 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2509 << SourceRange(FirstOpLoc);
2510 Kind = Tok.getKind();
2513 RHS = ParseExpression();
2514 if (RHS.isInvalid()) {
2520 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2521 ? diag::warn_cxx14_compat_fold_expression
2522 : diag::ext_fold_expression);
2525 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2526 EllipsisLoc, RHS.get(), T.getCloseLocation());
2529 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2532 /// argument-expression-list:
2533 /// assignment-expression
2534 /// argument-expression-list , assignment-expression
2536 /// [C++] expression-list:
2537 /// [C++] assignment-expression
2538 /// [C++] expression-list , assignment-expression
2540 /// [C++0x] expression-list:
2541 /// [C++0x] initializer-list
2543 /// [C++0x] initializer-list
2544 /// [C++0x] initializer-clause ...[opt]
2545 /// [C++0x] initializer-list , initializer-clause ...[opt]
2547 /// [C++0x] initializer-clause:
2548 /// [C++0x] assignment-expression
2549 /// [C++0x] braced-init-list
2551 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2552 SmallVectorImpl<SourceLocation> &CommaLocs,
2553 std::function<void()> Completer) {
2554 bool SawError = false;
2556 if (Tok.is(tok::code_completion)) {
2560 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2566 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2567 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2568 Expr = ParseBraceInitializer();
2570 Expr = ParseAssignmentExpression();
2572 if (Tok.is(tok::ellipsis))
2573 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2574 if (Expr.isInvalid()) {
2575 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2578 Exprs.push_back(Expr.get());
2581 if (Tok.isNot(tok::comma))
2583 // Move to the next argument, remember where the comma was.
2584 CommaLocs.push_back(ConsumeToken());
2587 // Ensure typos get diagnosed when errors were encountered while parsing the
2589 for (auto &E : Exprs) {
2590 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2591 if (Expr.isUsable()) E = Expr.get();
2597 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2598 /// used for misc language extensions.
2601 /// simple-expression-list:
2602 /// assignment-expression
2603 /// simple-expression-list , assignment-expression
2606 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2607 SmallVectorImpl<SourceLocation> &CommaLocs) {
2609 ExprResult Expr = ParseAssignmentExpression();
2610 if (Expr.isInvalid())
2613 Exprs.push_back(Expr.get());
2615 if (Tok.isNot(tok::comma))
2618 // Move to the next argument, remember where the comma was.
2619 CommaLocs.push_back(ConsumeToken());
2623 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2626 /// [clang] block-id:
2627 /// [clang] specifier-qualifier-list block-declarator
2629 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2630 if (Tok.is(tok::code_completion)) {
2631 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2632 return cutOffParsing();
2635 // Parse the specifier-qualifier-list piece.
2636 DeclSpec DS(AttrFactory);
2637 ParseSpecifierQualifierList(DS);
2639 // Parse the block-declarator.
2640 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2641 ParseDeclarator(DeclaratorInfo);
2643 MaybeParseGNUAttributes(DeclaratorInfo);
2645 // Inform sema that we are starting a block.
2646 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2649 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2650 /// like ^(int x){ return x+1; }
2654 /// [clang] '^' block-args[opt] compound-statement
2655 /// [clang] '^' block-id compound-statement
2656 /// [clang] block-args:
2657 /// [clang] '(' parameter-list ')'
2659 ExprResult Parser::ParseBlockLiteralExpression() {
2660 assert(Tok.is(tok::caret) && "block literal starts with ^");
2661 SourceLocation CaretLoc = ConsumeToken();
2663 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2664 "block literal parsing");
2666 // Enter a scope to hold everything within the block. This includes the
2667 // argument decls, decls within the compound expression, etc. This also
2668 // allows determining whether a variable reference inside the block is
2669 // within or outside of the block.
2670 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2673 // Inform sema that we are starting a block.
2674 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2676 // Parse the return type if present.
2677 DeclSpec DS(AttrFactory);
2678 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2679 // FIXME: Since the return type isn't actually parsed, it can't be used to
2680 // fill ParamInfo with an initial valid range, so do it manually.
2681 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2683 // If this block has arguments, parse them. There is no ambiguity here with
2684 // the expression case, because the expression case requires a parameter list.
2685 if (Tok.is(tok::l_paren)) {
2686 ParseParenDeclarator(ParamInfo);
2687 // Parse the pieces after the identifier as if we had "int(...)".
2688 // SetIdentifier sets the source range end, but in this case we're past
2690 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2691 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2692 ParamInfo.SetRangeEnd(Tmp);
2693 if (ParamInfo.isInvalidType()) {
2694 // If there was an error parsing the arguments, they may have
2695 // tried to use ^(x+y) which requires an argument list. Just
2696 // skip the whole block literal.
2697 Actions.ActOnBlockError(CaretLoc, getCurScope());
2701 MaybeParseGNUAttributes(ParamInfo);
2703 // Inform sema that we are starting a block.
2704 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2705 } else if (!Tok.is(tok::l_brace)) {
2706 ParseBlockId(CaretLoc);
2708 // Otherwise, pretend we saw (void).
2709 ParsedAttributes attrs(AttrFactory);
2710 SourceLocation NoLoc;
2711 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2712 /*IsAmbiguous=*/false,
2713 /*RParenLoc=*/NoLoc,
2714 /*ArgInfo=*/nullptr,
2716 /*EllipsisLoc=*/NoLoc,
2717 /*RParenLoc=*/NoLoc,
2719 /*RefQualifierIsLvalueRef=*/true,
2720 /*RefQualifierLoc=*/NoLoc,
2721 /*ConstQualifierLoc=*/NoLoc,
2722 /*VolatileQualifierLoc=*/NoLoc,
2723 /*RestrictQualifierLoc=*/NoLoc,
2724 /*MutableLoc=*/NoLoc,
2727 /*Exceptions=*/nullptr,
2728 /*ExceptionRanges=*/nullptr,
2729 /*NumExceptions=*/0,
2730 /*NoexceptExpr=*/nullptr,
2731 /*ExceptionSpecTokens=*/nullptr,
2736 MaybeParseGNUAttributes(ParamInfo);
2738 // Inform sema that we are starting a block.
2739 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2743 ExprResult Result(true);
2744 if (!Tok.is(tok::l_brace)) {
2745 // Saw something like: ^expr
2746 Diag(Tok, diag::err_expected_expression);
2747 Actions.ActOnBlockError(CaretLoc, getCurScope());
2751 StmtResult Stmt(ParseCompoundStatementBody());
2753 if (!Stmt.isInvalid())
2754 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2756 Actions.ActOnBlockError(CaretLoc, getCurScope());
2760 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2764 ExprResult Parser::ParseObjCBoolLiteral() {
2765 tok::TokenKind Kind = Tok.getKind();
2766 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);