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 /// \brief Parse a constraint-expression.
211 /// constraint-expression: [Concepts TS temp.constr.decl p1]
212 /// logical-or-expression
214 ExprResult Parser::ParseConstraintExpression() {
215 // FIXME: this may erroneously consume a function-body as the braced
216 // initializer list of a compound literal
218 // FIXME: this may erroneously consume a parenthesized rvalue reference
219 // declarator as a parenthesized address-of-label expression
220 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
221 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
226 bool Parser::isNotExpressionStart() {
227 tok::TokenKind K = Tok.getKind();
228 if (K == tok::l_brace || K == tok::r_brace ||
229 K == tok::kw_for || K == tok::kw_while ||
230 K == tok::kw_if || K == tok::kw_else ||
231 K == tok::kw_goto || K == tok::kw_try)
233 // If this is a decl-specifier, we can't be at the start of an expression.
234 return isKnownToBeDeclarationSpecifier();
237 static bool isFoldOperator(prec::Level Level) {
238 return Level > prec::Unknown && Level != prec::Conditional;
240 static bool isFoldOperator(tok::TokenKind Kind) {
241 return isFoldOperator(getBinOpPrecedence(Kind, false, true));
244 /// \brief Parse a binary expression that starts with \p LHS and has a
245 /// precedence of at least \p MinPrec.
247 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
248 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
249 GreaterThanIsOperator,
250 getLangOpts().CPlusPlus11);
251 SourceLocation ColonLoc;
254 // If this token has a lower precedence than we are allowed to parse (e.g.
255 // because we are called recursively, or because the token is not a binop),
257 if (NextTokPrec < MinPrec)
260 // Consume the operator, saving the operator token for error reporting.
264 // Bail out when encountering a comma followed by a token which can't
265 // possibly be the start of an expression. For instance:
266 // int f() { return 1, }
267 // We can't do this before consuming the comma, because
268 // isNotExpressionStart() looks at the token stream.
269 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
275 // If the next token is an ellipsis, then this is a fold-expression. Leave
276 // it alone so we can handle it in the paren expression.
277 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
278 // FIXME: We can't check this via lookahead before we consume the token
279 // because that tickles a lexer bug.
285 // Special case handling for the ternary operator.
286 ExprResult TernaryMiddle(true);
287 if (NextTokPrec == prec::Conditional) {
288 if (Tok.isNot(tok::colon)) {
289 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
290 ColonProtectionRAIIObject X(*this);
292 // Handle this production specially:
293 // logical-OR-expression '?' expression ':' conditional-expression
294 // In particular, the RHS of the '?' is 'expression', not
295 // 'logical-OR-expression' as we might expect.
296 TernaryMiddle = ParseExpression();
297 if (TernaryMiddle.isInvalid()) {
298 Actions.CorrectDelayedTyposInExpr(LHS);
300 TernaryMiddle = nullptr;
303 // Special case handling of "X ? Y : Z" where Y is empty:
304 // logical-OR-expression '?' ':' conditional-expression [GNU]
305 TernaryMiddle = nullptr;
306 Diag(Tok, diag::ext_gnu_conditional_expr);
309 if (!TryConsumeToken(tok::colon, ColonLoc)) {
310 // Otherwise, we're missing a ':'. Assume that this was a typo that
311 // the user forgot. If we're not in a macro expansion, we can suggest
312 // a fixit hint. If there were two spaces before the current token,
313 // suggest inserting the colon in between them, otherwise insert ": ".
314 SourceLocation FILoc = Tok.getLocation();
315 const char *FIText = ": ";
316 const SourceManager &SM = PP.getSourceManager();
317 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
318 assert(FILoc.isFileID());
319 bool IsInvalid = false;
320 const char *SourcePtr =
321 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
322 if (!IsInvalid && *SourcePtr == ' ') {
324 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
325 if (!IsInvalid && *SourcePtr == ' ') {
326 FILoc = FILoc.getLocWithOffset(-1);
332 Diag(Tok, diag::err_expected)
333 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
334 Diag(OpToken, diag::note_matching) << tok::question;
335 ColonLoc = Tok.getLocation();
339 // Code completion for the right-hand side of an assignment expression
340 // goes through a special hook that takes the left-hand side into account.
341 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
342 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
347 // Parse another leaf here for the RHS of the operator.
348 // ParseCastExpression works here because all RHS expressions in C have it
349 // as a prefix, at least. However, in C++, an assignment-expression could
350 // be a throw-expression, which is not a valid cast-expression.
351 // Therefore we need some special-casing here.
352 // Also note that the third operand of the conditional operator is
353 // an assignment-expression in C++, and in C++11, we can have a
354 // braced-init-list on the RHS of an assignment. For better diagnostics,
355 // parse as if we were allowed braced-init-lists everywhere, and check that
356 // they only appear on the RHS of assignments later.
358 bool RHSIsInitList = false;
359 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
360 RHS = ParseBraceInitializer();
361 RHSIsInitList = true;
362 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
363 RHS = ParseAssignmentExpression();
365 RHS = ParseCastExpression(false);
367 if (RHS.isInvalid()) {
368 // FIXME: Errors generated by the delayed typo correction should be
369 // printed before errors from parsing the RHS, not after.
370 Actions.CorrectDelayedTyposInExpr(LHS);
371 if (TernaryMiddle.isUsable())
372 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
376 // Remember the precedence of this operator and get the precedence of the
377 // operator immediately to the right of the RHS.
378 prec::Level ThisPrec = NextTokPrec;
379 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
380 getLangOpts().CPlusPlus11);
382 // Assignment and conditional expressions are right-associative.
383 bool isRightAssoc = ThisPrec == prec::Conditional ||
384 ThisPrec == prec::Assignment;
386 // Get the precedence of the operator to the right of the RHS. If it binds
387 // more tightly with RHS than we do, evaluate it completely first.
388 if (ThisPrec < NextTokPrec ||
389 (ThisPrec == NextTokPrec && isRightAssoc)) {
390 if (!RHS.isInvalid() && RHSIsInitList) {
391 Diag(Tok, diag::err_init_list_bin_op)
392 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
395 // If this is left-associative, only parse things on the RHS that bind
396 // more tightly than the current operator. If it is left-associative, it
397 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
398 // A=(B=(C=D)), where each paren is a level of recursion here.
399 // The function takes ownership of the RHS.
400 RHS = ParseRHSOfBinaryExpression(RHS,
401 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
402 RHSIsInitList = false;
404 if (RHS.isInvalid()) {
405 // FIXME: Errors generated by the delayed typo correction should be
406 // printed before errors from ParseRHSOfBinaryExpression, not after.
407 Actions.CorrectDelayedTyposInExpr(LHS);
408 if (TernaryMiddle.isUsable())
409 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
413 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
414 getLangOpts().CPlusPlus11);
417 if (!RHS.isInvalid() && RHSIsInitList) {
418 if (ThisPrec == prec::Assignment) {
419 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
420 << Actions.getExprRange(RHS.get());
422 Diag(OpToken, diag::err_init_list_bin_op)
423 << /*RHS*/1 << PP.getSpelling(OpToken)
424 << Actions.getExprRange(RHS.get());
429 if (!LHS.isInvalid()) {
430 // Combine the LHS and RHS into the LHS (e.g. build AST).
431 if (TernaryMiddle.isInvalid()) {
432 // If we're using '>>' as an operator within a template
433 // argument list (in C++98), suggest the addition of
434 // parentheses so that the code remains well-formed in C++0x.
435 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
436 SuggestParentheses(OpToken.getLocation(),
437 diag::warn_cxx11_right_shift_in_template_arg,
438 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
439 Actions.getExprRange(RHS.get()).getEnd()));
441 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
442 OpToken.getKind(), LHS.get(), RHS.get());
444 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
445 LHS.get(), TernaryMiddle.get(),
448 // Ensure potential typos in the RHS aren't left undiagnosed.
449 Actions.CorrectDelayedTyposInExpr(RHS);
453 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
454 /// parse a unary-expression.
456 /// \p isAddressOfOperand exists because an id-expression that is the
457 /// operand of address-of gets special treatment due to member pointers.
459 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
460 bool isAddressOfOperand,
461 TypeCastState isTypeCast) {
463 ExprResult Res = ParseCastExpression(isUnaryExpression,
468 Diag(Tok, diag::err_expected_expression);
473 class CastExpressionIdValidator : public CorrectionCandidateCallback {
475 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
476 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
477 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
480 bool ValidateCandidate(const TypoCorrection &candidate) override {
481 NamedDecl *ND = candidate.getCorrectionDecl();
483 return candidate.isKeyword();
485 if (isa<TypeDecl>(ND))
486 return WantTypeSpecifiers;
488 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
491 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
494 for (auto *C : candidate) {
495 NamedDecl *ND = C->getUnderlyingDecl();
496 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
508 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
509 /// a unary-expression.
511 /// \p isAddressOfOperand exists because an id-expression that is the operand
512 /// of address-of gets special treatment due to member pointers. NotCastExpr
513 /// is set to true if the token is not the start of a cast-expression, and no
514 /// diagnostic is emitted in this case.
517 /// cast-expression: [C99 6.5.4]
519 /// '(' type-name ')' cast-expression
521 /// unary-expression: [C99 6.5.3]
522 /// postfix-expression
523 /// '++' unary-expression
524 /// '--' unary-expression
525 /// unary-operator cast-expression
526 /// 'sizeof' unary-expression
527 /// 'sizeof' '(' type-name ')'
528 /// [C++11] 'sizeof' '...' '(' identifier ')'
529 /// [GNU] '__alignof' unary-expression
530 /// [GNU] '__alignof' '(' type-name ')'
531 /// [C11] '_Alignof' '(' type-name ')'
532 /// [C++11] 'alignof' '(' type-id ')'
533 /// [GNU] '&&' identifier
534 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
535 /// [C++] new-expression
536 /// [C++] delete-expression
538 /// unary-operator: one of
539 /// '&' '*' '+' '-' '~' '!'
540 /// [GNU] '__extension__' '__real' '__imag'
542 /// primary-expression: [C99 6.5.1]
544 /// [C++] id-expression
547 /// [C++] boolean-literal [C++ 2.13.5]
548 /// [C++11] 'nullptr' [C++11 2.14.7]
549 /// [C++11] user-defined-literal
550 /// '(' expression ')'
551 /// [C11] generic-selection
552 /// '__func__' [C99 6.4.2.2]
553 /// [GNU] '__FUNCTION__'
554 /// [MS] '__FUNCDNAME__'
555 /// [MS] 'L__FUNCTION__'
556 /// [GNU] '__PRETTY_FUNCTION__'
557 /// [GNU] '(' compound-statement ')'
558 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
559 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
560 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
562 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
564 /// [OBJC] '[' objc-message-expr ']'
565 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
566 /// [OBJC] '\@protocol' '(' identifier ')'
567 /// [OBJC] '\@encode' '(' type-name ')'
568 /// [OBJC] objc-string-literal
569 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
570 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
571 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
572 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
573 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
574 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
575 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
576 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
577 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
578 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
579 /// [C++] 'this' [C++ 9.3.2]
580 /// [G++] unary-type-trait '(' type-id ')'
581 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
582 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
583 /// [clang] '^' block-literal
585 /// constant: [C99 6.4.4]
587 /// floating-constant
588 /// enumeration-constant -> identifier
589 /// character-constant
591 /// id-expression: [C++ 5.1]
595 /// unqualified-id: [C++ 5.1]
597 /// operator-function-id
598 /// conversion-function-id
602 /// new-expression: [C++ 5.3.4]
603 /// '::'[opt] 'new' new-placement[opt] new-type-id
604 /// new-initializer[opt]
605 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
606 /// new-initializer[opt]
608 /// delete-expression: [C++ 5.3.5]
609 /// '::'[opt] 'delete' cast-expression
610 /// '::'[opt] 'delete' '[' ']' cast-expression
612 /// [GNU/Embarcadero] unary-type-trait:
613 /// '__is_arithmetic'
614 /// '__is_floating_point'
616 /// '__is_lvalue_expr'
617 /// '__is_rvalue_expr'
618 /// '__is_complete_type'
623 /// '__is_lvalue_reference'
624 /// '__is_rvalue_reference'
625 /// '__is_fundamental'
630 /// '__is_member_object_pointer'
631 /// '__is_member_function_pointer'
632 /// '__is_member_pointer'
636 /// '__is_standard_layout'
640 /// [GNU] unary-type-trait:
641 /// '__has_nothrow_assign'
642 /// '__has_nothrow_copy'
643 /// '__has_nothrow_constructor'
644 /// '__has_trivial_assign' [TODO]
645 /// '__has_trivial_copy' [TODO]
646 /// '__has_trivial_constructor'
647 /// '__has_trivial_destructor'
648 /// '__has_virtual_destructor'
649 /// '__is_abstract' [TODO]
651 /// '__is_empty' [TODO]
655 /// '__is_polymorphic'
656 /// '__is_sealed' [MS]
660 /// [Clang] unary-type-trait:
661 /// '__trivially_copyable'
663 /// binary-type-trait:
664 /// [GNU] '__is_base_of'
665 /// [MS] '__is_convertible_to'
666 /// '__is_convertible'
669 /// [Embarcadero] array-type-trait:
673 /// [Embarcadero] expression-trait:
674 /// '__is_lvalue_expr'
675 /// '__is_rvalue_expr'
678 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
679 bool isAddressOfOperand,
681 TypeCastState isTypeCast) {
683 tok::TokenKind SavedKind = Tok.getKind();
686 // This handles all of cast-expression, unary-expression, postfix-expression,
687 // and primary-expression. We handle them together like this for efficiency
688 // and to simplify handling of an expression starting with a '(' token: which
689 // may be one of a parenthesized expression, cast-expression, compound literal
690 // expression, or statement expression.
692 // If the parsed tokens consist of a primary-expression, the cases below
693 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
694 // to handle the postfix expression suffixes. Cases that cannot be followed
695 // by postfix exprs should return without invoking
696 // ParsePostfixExpressionSuffix.
699 // If this expression is limited to being a unary-expression, the parent can
700 // not start a cast expression.
701 ParenParseOption ParenExprType =
702 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
705 SourceLocation RParenLoc;
706 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
707 isTypeCast == IsTypeCast, CastTy, RParenLoc);
709 switch (ParenExprType) {
710 case SimpleExpr: break; // Nothing else to do.
711 case CompoundStmt: break; // Nothing else to do.
712 case CompoundLiteral:
713 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
714 // postfix-expression exist, parse them now.
717 // We have parsed the cast-expression and no postfix-expr pieces are
725 // primary-expression
726 case tok::numeric_constant:
727 // constant: integer-constant
728 // constant: floating-constant
730 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
736 return ParseCXXBoolLiteral();
738 case tok::kw___objc_yes:
739 case tok::kw___objc_no:
740 return ParseObjCBoolLiteral();
742 case tok::kw_nullptr:
743 Diag(Tok, diag::warn_cxx98_compat_nullptr);
744 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
746 case tok::annot_primary_expr:
747 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
748 Res = getExprAnnotation(Tok);
752 case tok::kw___super:
753 case tok::kw_decltype:
754 // Annotate the token and tail recurse.
755 if (TryAnnotateTypeOrScopeToken())
757 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
758 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
760 case tok::identifier: { // primary-expression: identifier
761 // unqualified-id: identifier
762 // constant: enumeration-constant
763 // Turn a potentially qualified name into a annot_typename or
764 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
765 if (getLangOpts().CPlusPlus) {
766 // Avoid the unnecessary parse-time lookup in the common case
767 // where the syntax forbids a type.
768 const Token &Next = NextToken();
770 // If this identifier was reverted from a token ID, and the next token
771 // is a parenthesis, this is likely to be a use of a type trait. Check
773 if (Next.is(tok::l_paren) &&
774 Tok.is(tok::identifier) &&
775 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
776 IdentifierInfo *II = Tok.getIdentifierInfo();
777 // Build up the mapping of revertible type traits, for future use.
778 if (RevertibleTypeTraits.empty()) {
779 #define RTT_JOIN(X,Y) X##Y
780 #define REVERTIBLE_TYPE_TRAIT(Name) \
781 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
782 = RTT_JOIN(tok::kw_,Name)
784 REVERTIBLE_TYPE_TRAIT(__is_abstract);
785 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
786 REVERTIBLE_TYPE_TRAIT(__is_array);
787 REVERTIBLE_TYPE_TRAIT(__is_base_of);
788 REVERTIBLE_TYPE_TRAIT(__is_class);
789 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
790 REVERTIBLE_TYPE_TRAIT(__is_compound);
791 REVERTIBLE_TYPE_TRAIT(__is_const);
792 REVERTIBLE_TYPE_TRAIT(__is_constructible);
793 REVERTIBLE_TYPE_TRAIT(__is_convertible);
794 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
795 REVERTIBLE_TYPE_TRAIT(__is_destructible);
796 REVERTIBLE_TYPE_TRAIT(__is_empty);
797 REVERTIBLE_TYPE_TRAIT(__is_enum);
798 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
799 REVERTIBLE_TYPE_TRAIT(__is_final);
800 REVERTIBLE_TYPE_TRAIT(__is_function);
801 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
802 REVERTIBLE_TYPE_TRAIT(__is_integral);
803 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
804 REVERTIBLE_TYPE_TRAIT(__is_literal);
805 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
806 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
807 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
808 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
809 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
810 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
811 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
812 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
813 REVERTIBLE_TYPE_TRAIT(__is_object);
814 REVERTIBLE_TYPE_TRAIT(__is_pod);
815 REVERTIBLE_TYPE_TRAIT(__is_pointer);
816 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
817 REVERTIBLE_TYPE_TRAIT(__is_reference);
818 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
819 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
820 REVERTIBLE_TYPE_TRAIT(__is_same);
821 REVERTIBLE_TYPE_TRAIT(__is_scalar);
822 REVERTIBLE_TYPE_TRAIT(__is_sealed);
823 REVERTIBLE_TYPE_TRAIT(__is_signed);
824 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
825 REVERTIBLE_TYPE_TRAIT(__is_trivial);
826 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
827 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
828 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
829 REVERTIBLE_TYPE_TRAIT(__is_union);
830 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
831 REVERTIBLE_TYPE_TRAIT(__is_void);
832 REVERTIBLE_TYPE_TRAIT(__is_volatile);
833 #undef REVERTIBLE_TYPE_TRAIT
837 // If we find that this is in fact the name of a type trait,
838 // update the token kind in place and parse again to treat it as
839 // the appropriate kind of type trait.
840 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
841 = RevertibleTypeTraits.find(II);
842 if (Known != RevertibleTypeTraits.end()) {
843 Tok.setKind(Known->second);
844 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
845 NotCastExpr, isTypeCast);
849 if ((!ColonIsSacred && Next.is(tok::colon)) ||
850 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
852 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
853 if (TryAnnotateTypeOrScopeToken())
855 if (!Tok.is(tok::identifier))
856 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
860 // Consume the identifier so that we can see if it is followed by a '(' or
862 IdentifierInfo &II = *Tok.getIdentifierInfo();
863 SourceLocation ILoc = ConsumeToken();
865 // Support 'Class.property' and 'super.property' notation.
866 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
867 (Actions.getTypeName(II, ILoc, getCurScope()) ||
868 // Allow the base to be 'super' if in an objc-method.
869 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
872 // Allow either an identifier or the keyword 'class' (in C++).
873 if (Tok.isNot(tok::identifier) &&
874 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
875 Diag(Tok, diag::err_expected_property_name);
878 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
879 SourceLocation PropertyLoc = ConsumeToken();
881 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
886 // In an Objective-C method, if we have "super" followed by an identifier,
887 // the token sequence is ill-formed. However, if there's a ':' or ']' after
888 // that identifier, this is probably a message send with a missing open
889 // bracket. Treat it as such.
890 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
891 getCurScope()->isInObjcMethodScope() &&
892 ((Tok.is(tok::identifier) &&
893 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
894 Tok.is(tok::code_completion))) {
895 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
900 // If we have an Objective-C class name followed by an identifier
901 // and either ':' or ']', this is an Objective-C class message
902 // send that's missing the opening '['. Recovery
903 // appropriately. Also take this path if we're performing code
904 // completion after an Objective-C class name.
905 if (getLangOpts().ObjC1 &&
906 ((Tok.is(tok::identifier) && !InMessageExpression) ||
907 Tok.is(tok::code_completion))) {
908 const Token& Next = NextToken();
909 if (Tok.is(tok::code_completion) ||
910 Next.is(tok::colon) || Next.is(tok::r_square))
911 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
912 if (Typ.get()->isObjCObjectOrInterfaceType()) {
913 // Fake up a Declarator to use with ActOnTypeName.
914 DeclSpec DS(AttrFactory);
915 DS.SetRangeStart(ILoc);
916 DS.SetRangeEnd(ILoc);
917 const char *PrevSpec = nullptr;
919 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
920 Actions.getASTContext().getPrintingPolicy());
922 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
923 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
928 Res = ParseObjCMessageExpressionBody(SourceLocation(),
935 // Make sure to pass down the right value for isAddressOfOperand.
936 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
937 isAddressOfOperand = false;
939 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
940 // need to know whether or not this identifier is a function designator or
943 CXXScopeSpec ScopeSpec;
944 SourceLocation TemplateKWLoc;
946 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
947 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
948 Validator->IsAddressOfOperand = isAddressOfOperand;
949 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
950 Validator->WantExpressionKeywords = false;
951 Validator->WantRemainingKeywords = false;
953 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
955 Name.setIdentifier(&II, ILoc);
956 Res = Actions.ActOnIdExpression(
957 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
958 isAddressOfOperand, std::move(Validator),
959 /*IsInlineAsmIdentifier=*/false,
960 Tok.is(tok::r_paren) ? nullptr : &Replacement);
961 if (!Res.isInvalid() && !Res.get()) {
962 UnconsumeToken(Replacement);
963 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
964 NotCastExpr, isTypeCast);
968 case tok::char_constant: // constant: character-constant
969 case tok::wide_char_constant:
970 case tok::utf8_char_constant:
971 case tok::utf16_char_constant:
972 case tok::utf32_char_constant:
973 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
976 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
977 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
978 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
979 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
980 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
981 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
982 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
985 case tok::string_literal: // primary-expression: string-literal
986 case tok::wide_string_literal:
987 case tok::utf8_string_literal:
988 case tok::utf16_string_literal:
989 case tok::utf32_string_literal:
990 Res = ParseStringLiteralExpression(true);
992 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
993 Res = ParseGenericSelectionExpression();
995 case tok::kw___builtin_va_arg:
996 case tok::kw___builtin_offsetof:
997 case tok::kw___builtin_choose_expr:
998 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
999 case tok::kw___builtin_convertvector:
1000 return ParseBuiltinPrimaryExpression();
1001 case tok::kw___null:
1002 return Actions.ActOnGNUNullExpr(ConsumeToken());
1004 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1005 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1006 // C++ [expr.unary] has:
1007 // unary-expression:
1008 // ++ cast-expression
1009 // -- cast-expression
1010 SourceLocation SavedLoc = ConsumeToken();
1011 // One special case is implicitly handled here: if the preceding tokens are
1012 // an ambiguous cast expression, such as "(T())++", then we recurse to
1013 // determine whether the '++' is prefix or postfix.
1014 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1015 /*isAddressOfOperand*/false, NotCastExpr,
1017 if (!Res.isInvalid())
1018 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1021 case tok::amp: { // unary-expression: '&' cast-expression
1022 // Special treatment because of member pointers
1023 SourceLocation SavedLoc = ConsumeToken();
1024 Res = ParseCastExpression(false, true);
1025 if (!Res.isInvalid())
1026 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1030 case tok::star: // unary-expression: '*' cast-expression
1031 case tok::plus: // unary-expression: '+' cast-expression
1032 case tok::minus: // unary-expression: '-' cast-expression
1033 case tok::tilde: // unary-expression: '~' cast-expression
1034 case tok::exclaim: // unary-expression: '!' cast-expression
1035 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1036 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1037 SourceLocation SavedLoc = ConsumeToken();
1038 Res = ParseCastExpression(false);
1039 if (!Res.isInvalid())
1040 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1044 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1045 // __extension__ silences extension warnings in the subexpression.
1046 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1047 SourceLocation SavedLoc = ConsumeToken();
1048 Res = ParseCastExpression(false);
1049 if (!Res.isInvalid())
1050 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1053 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1054 if (!getLangOpts().C11)
1055 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1057 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1058 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1059 // unary-expression: '__alignof' '(' type-name ')'
1060 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1061 // unary-expression: 'sizeof' '(' type-name ')'
1062 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1063 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1064 case tok::kw___builtin_omp_required_simd_align:
1065 return ParseUnaryExprOrTypeTraitExpression();
1066 case tok::ampamp: { // unary-expression: '&&' identifier
1067 SourceLocation AmpAmpLoc = ConsumeToken();
1068 if (Tok.isNot(tok::identifier))
1069 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1071 if (getCurScope()->getFnParent() == nullptr)
1072 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1074 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1075 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1077 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1081 case tok::kw_const_cast:
1082 case tok::kw_dynamic_cast:
1083 case tok::kw_reinterpret_cast:
1084 case tok::kw_static_cast:
1085 Res = ParseCXXCasts();
1087 case tok::kw_typeid:
1088 Res = ParseCXXTypeid();
1090 case tok::kw___uuidof:
1091 Res = ParseCXXUuidof();
1094 Res = ParseCXXThis();
1097 case tok::annot_typename:
1098 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1099 ParsedType Type = getTypeAnnotation(Tok);
1101 // Fake up a Declarator to use with ActOnTypeName.
1102 DeclSpec DS(AttrFactory);
1103 DS.SetRangeStart(Tok.getLocation());
1104 DS.SetRangeEnd(Tok.getLastLoc());
1106 const char *PrevSpec = nullptr;
1108 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1109 PrevSpec, DiagID, Type,
1110 Actions.getASTContext().getPrintingPolicy());
1112 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1113 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1118 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1124 case tok::annot_decltype:
1126 case tok::kw_wchar_t:
1127 case tok::kw_char16_t:
1128 case tok::kw_char32_t:
1133 case tok::kw___int64:
1134 case tok::kw___int128:
1135 case tok::kw_signed:
1136 case tok::kw_unsigned:
1139 case tok::kw_double:
1141 case tok::kw_typename:
1142 case tok::kw_typeof:
1143 case tok::kw___vector: {
1144 if (!getLangOpts().CPlusPlus) {
1145 Diag(Tok, diag::err_expected_expression);
1149 if (SavedKind == tok::kw_typename) {
1150 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1151 // typename-specifier braced-init-list
1152 if (TryAnnotateTypeOrScopeToken())
1155 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1156 // We are trying to parse a simple-type-specifier but might not get such
1157 // a token after error recovery.
1161 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1162 // simple-type-specifier braced-init-list
1164 DeclSpec DS(AttrFactory);
1166 ParseCXXSimpleTypeSpecifier(DS);
1167 if (Tok.isNot(tok::l_paren) &&
1168 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1169 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1170 << DS.getSourceRange());
1172 if (Tok.is(tok::l_brace))
1173 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1175 Res = ParseCXXTypeConstructExpression(DS);
1179 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1180 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1181 // (We can end up in this situation after tentative parsing.)
1182 if (TryAnnotateTypeOrScopeToken())
1184 if (!Tok.is(tok::annot_cxxscope))
1185 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1186 NotCastExpr, isTypeCast);
1188 Token Next = NextToken();
1189 if (Next.is(tok::annot_template_id)) {
1190 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1191 if (TemplateId->Kind == TNK_Type_template) {
1192 // We have a qualified template-id that we know refers to a
1193 // type, translate it into a type and continue parsing as a
1196 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1197 /*EnteringContext=*/false);
1198 AnnotateTemplateIdTokenAsType();
1199 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1200 NotCastExpr, isTypeCast);
1204 // Parse as an id-expression.
1205 Res = ParseCXXIdExpression(isAddressOfOperand);
1209 case tok::annot_template_id: { // [C++] template-id
1210 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1211 if (TemplateId->Kind == TNK_Type_template) {
1212 // We have a template-id that we know refers to a type,
1213 // translate it into a type and continue parsing as a cast
1215 AnnotateTemplateIdTokenAsType();
1216 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1217 NotCastExpr, isTypeCast);
1220 // Fall through to treat the template-id as an id-expression.
1223 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1224 Res = ParseCXXIdExpression(isAddressOfOperand);
1227 case tok::coloncolon: {
1228 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1229 // annotates the token, tail recurse.
1230 if (TryAnnotateTypeOrScopeToken())
1232 if (!Tok.is(tok::coloncolon))
1233 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1235 // ::new -> [C++] new-expression
1236 // ::delete -> [C++] delete-expression
1237 SourceLocation CCLoc = ConsumeToken();
1238 if (Tok.is(tok::kw_new))
1239 return ParseCXXNewExpression(true, CCLoc);
1240 if (Tok.is(tok::kw_delete))
1241 return ParseCXXDeleteExpression(true, CCLoc);
1243 // This is not a type name or scope specifier, it is an invalid expression.
1244 Diag(CCLoc, diag::err_expected_expression);
1248 case tok::kw_new: // [C++] new-expression
1249 return ParseCXXNewExpression(false, Tok.getLocation());
1251 case tok::kw_delete: // [C++] delete-expression
1252 return ParseCXXDeleteExpression(false, Tok.getLocation());
1254 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1255 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1256 SourceLocation KeyLoc = ConsumeToken();
1257 BalancedDelimiterTracker T(*this, tok::l_paren);
1259 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1261 // C++11 [expr.unary.noexcept]p1:
1262 // The noexcept operator determines whether the evaluation of its operand,
1263 // which is an unevaluated operand, can throw an exception.
1264 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1265 ExprResult Result = ParseExpression();
1269 if (!Result.isInvalid())
1270 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1271 Result.get(), T.getCloseLocation());
1275 #define TYPE_TRAIT(N,Spelling,K) \
1276 case tok::kw_##Spelling:
1277 #include "clang/Basic/TokenKinds.def"
1278 return ParseTypeTrait();
1280 case tok::kw___array_rank:
1281 case tok::kw___array_extent:
1282 return ParseArrayTypeTrait();
1284 case tok::kw___is_lvalue_expr:
1285 case tok::kw___is_rvalue_expr:
1286 return ParseExpressionTrait();
1289 SourceLocation AtLoc = ConsumeToken();
1290 return ParseObjCAtExpression(AtLoc);
1293 Res = ParseBlockLiteralExpression();
1295 case tok::code_completion: {
1296 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1301 if (getLangOpts().CPlusPlus11) {
1302 if (getLangOpts().ObjC1) {
1303 // C++11 lambda expressions and Objective-C message sends both start with a
1304 // square bracket. There are three possibilities here:
1305 // we have a valid lambda expression, we have an invalid lambda
1306 // expression, or we have something that doesn't appear to be a lambda.
1307 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1308 Res = TryParseLambdaExpression();
1309 if (!Res.isInvalid() && !Res.get())
1310 Res = ParseObjCMessageExpression();
1313 Res = ParseLambdaExpression();
1316 if (getLangOpts().ObjC1) {
1317 Res = ParseObjCMessageExpression();
1326 // These can be followed by postfix-expr pieces.
1327 return ParsePostfixExpressionSuffix(Res);
1330 /// \brief Once the leading part of a postfix-expression is parsed, this
1331 /// method parses any suffixes that apply.
1334 /// postfix-expression: [C99 6.5.2]
1335 /// primary-expression
1336 /// postfix-expression '[' expression ']'
1337 /// postfix-expression '[' braced-init-list ']'
1338 /// postfix-expression '(' argument-expression-list[opt] ')'
1339 /// postfix-expression '.' identifier
1340 /// postfix-expression '->' identifier
1341 /// postfix-expression '++'
1342 /// postfix-expression '--'
1343 /// '(' type-name ')' '{' initializer-list '}'
1344 /// '(' type-name ')' '{' initializer-list ',' '}'
1346 /// argument-expression-list: [C99 6.5.2]
1347 /// argument-expression ...[opt]
1348 /// argument-expression-list ',' assignment-expression ...[opt]
1351 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1352 // Now that the primary-expression piece of the postfix-expression has been
1353 // parsed, see if there are any postfix-expression pieces here.
1356 switch (Tok.getKind()) {
1357 case tok::code_completion:
1358 if (InMessageExpression)
1361 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1365 case tok::identifier:
1366 // If we see identifier: after an expression, and we're not already in a
1367 // message send, then this is probably a message send with a missing
1368 // opening bracket '['.
1369 if (getLangOpts().ObjC1 && !InMessageExpression &&
1370 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1371 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1372 ParsedType(), LHS.get());
1376 // Fall through; this isn't a message send.
1378 default: // Not a postfix-expression suffix.
1380 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1381 // If we have a array postfix expression that starts on a new line and
1382 // Objective-C is enabled, it is highly likely that the user forgot a
1383 // semicolon after the base expression and that the array postfix-expr is
1384 // actually another message send. In this case, do some look-ahead to see
1385 // if the contents of the square brackets are obviously not a valid
1386 // expression and recover by pretending there is no suffix.
1387 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1388 isSimpleObjCMessageExpression())
1391 // Reject array indices starting with a lambda-expression. '[[' is
1392 // reserved for attributes.
1393 if (CheckProhibitedCXX11Attribute())
1396 BalancedDelimiterTracker T(*this, tok::l_square);
1398 Loc = T.getOpenLocation();
1400 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1401 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1402 Idx = ParseBraceInitializer();
1404 Idx = ParseExpression();
1406 SourceLocation RLoc = Tok.getLocation();
1408 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
1409 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1412 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1413 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1423 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1424 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1425 // '(' argument-expression-list[opt] ')'
1426 tok::TokenKind OpKind = Tok.getKind();
1427 InMessageExpressionRAIIObject InMessage(*this, false);
1429 Expr *ExecConfig = nullptr;
1431 BalancedDelimiterTracker PT(*this, tok::l_paren);
1433 if (OpKind == tok::lesslessless) {
1434 ExprVector ExecConfigExprs;
1435 CommaLocsTy ExecConfigCommaLocs;
1436 SourceLocation OpenLoc = ConsumeToken();
1438 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1439 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1443 SourceLocation CloseLoc;
1444 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1445 } else if (LHS.isInvalid()) {
1446 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1448 // There was an error closing the brackets
1449 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1450 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1451 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1455 if (!LHS.isInvalid()) {
1456 if (ExpectAndConsume(tok::l_paren))
1459 Loc = PrevTokLocation;
1462 if (!LHS.isInvalid()) {
1463 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1467 if (ECResult.isInvalid())
1470 ExecConfig = ECResult.get();
1474 Loc = PT.getOpenLocation();
1477 ExprVector ArgExprs;
1478 CommaLocsTy CommaLocs;
1480 if (Tok.is(tok::code_completion)) {
1481 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1486 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1487 if (Tok.isNot(tok::r_paren)) {
1488 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1489 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1491 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1493 } else if (LHS.isInvalid()) {
1494 for (auto &E : ArgExprs)
1495 Actions.CorrectDelayedTyposInExpr(E);
1501 if (LHS.isInvalid()) {
1502 SkipUntil(tok::r_paren, StopAtSemi);
1503 } else if (Tok.isNot(tok::r_paren)) {
1504 bool HadDelayedTypo = false;
1505 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1506 HadDelayedTypo = true;
1507 for (auto &E : ArgExprs)
1508 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1509 HadDelayedTypo = true;
1510 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1511 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1512 // the unmatched l_paren.
1514 SkipUntil(tok::r_paren, StopAtSemi);
1519 assert((ArgExprs.size() == 0 ||
1520 ArgExprs.size()-1 == CommaLocs.size())&&
1521 "Unexpected number of commas!");
1522 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1523 ArgExprs, Tok.getLocation(),
1532 // postfix-expression: p-e '->' template[opt] id-expression
1533 // postfix-expression: p-e '.' template[opt] id-expression
1534 tok::TokenKind OpKind = Tok.getKind();
1535 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1538 ParsedType ObjectType;
1539 bool MayBePseudoDestructor = false;
1540 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1541 Expr *Base = LHS.get();
1542 const Type* BaseType = Base->getType().getTypePtrOrNull();
1543 if (BaseType && Tok.is(tok::l_paren) &&
1544 (BaseType->isFunctionType() ||
1545 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1546 Diag(OpLoc, diag::err_function_is_not_record)
1547 << OpKind << Base->getSourceRange()
1548 << FixItHint::CreateRemoval(OpLoc);
1549 return ParsePostfixExpressionSuffix(Base);
1552 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1553 OpLoc, OpKind, ObjectType,
1554 MayBePseudoDestructor);
1555 if (LHS.isInvalid())
1558 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1559 /*EnteringContext=*/false,
1560 &MayBePseudoDestructor);
1561 if (SS.isNotEmpty())
1562 ObjectType = ParsedType();
1565 if (Tok.is(tok::code_completion)) {
1566 // Code completion for a member access expression.
1567 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1568 OpLoc, OpKind == tok::arrow);
1574 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1575 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1580 // Either the action has told us that this cannot be a
1581 // pseudo-destructor expression (based on the type of base
1582 // expression), or we didn't see a '~' in the right place. We
1583 // can still parse a destructor name here, but in that case it
1584 // names a real destructor.
1585 // Allow explicit constructor calls in Microsoft mode.
1586 // FIXME: Add support for explicit call of template constructor.
1587 SourceLocation TemplateKWLoc;
1589 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1590 Tok.is(tok::kw_class)) {
1592 // After a '.' in a member access expression, treat the keyword
1593 // 'class' as if it were an identifier.
1595 // This hack allows property access to the 'class' method because it is
1596 // such a common method name. For other C++ keywords that are
1597 // Objective-C method names, one must use the message send syntax.
1598 IdentifierInfo *Id = Tok.getIdentifierInfo();
1599 SourceLocation Loc = ConsumeToken();
1600 Name.setIdentifier(Id, Loc);
1601 } else if (ParseUnqualifiedId(SS,
1602 /*EnteringContext=*/false,
1603 /*AllowDestructorName=*/true,
1604 /*AllowConstructorName=*/
1605 getLangOpts().MicrosoftExt,
1606 ObjectType, TemplateKWLoc, Name)) {
1607 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1611 if (!LHS.isInvalid())
1612 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1613 OpKind, SS, TemplateKWLoc, Name,
1614 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1618 case tok::plusplus: // postfix-expression: postfix-expression '++'
1619 case tok::minusminus: // postfix-expression: postfix-expression '--'
1620 if (!LHS.isInvalid()) {
1621 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1622 Tok.getKind(), LHS.get());
1630 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1631 /// vec_step and we are at the start of an expression or a parenthesized
1632 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1633 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1636 /// unary-expression: [C99 6.5.3]
1637 /// 'sizeof' unary-expression
1638 /// 'sizeof' '(' type-name ')'
1639 /// [GNU] '__alignof' unary-expression
1640 /// [GNU] '__alignof' '(' type-name ')'
1641 /// [C11] '_Alignof' '(' type-name ')'
1642 /// [C++0x] 'alignof' '(' type-id ')'
1644 /// [GNU] typeof-specifier:
1645 /// typeof ( expressions )
1646 /// typeof ( type-name )
1647 /// [GNU/C++] typeof unary-expression
1649 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1650 /// vec_step ( expressions )
1651 /// vec_step ( type-name )
1654 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1657 SourceRange &CastRange) {
1659 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1660 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1661 tok::kw___builtin_omp_required_simd_align) &&
1662 "Not a typeof/sizeof/alignof/vec_step expression!");
1666 // If the operand doesn't start with an '(', it must be an expression.
1667 if (Tok.isNot(tok::l_paren)) {
1668 // If construct allows a form without parenthesis, user may forget to put
1669 // pathenthesis around type name.
1670 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1671 tok::kw__Alignof)) {
1672 if (isTypeIdUnambiguously()) {
1673 DeclSpec DS(AttrFactory);
1674 ParseSpecifierQualifierList(DS);
1675 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1676 ParseDeclarator(DeclaratorInfo);
1678 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1679 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1680 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1682 << FixItHint::CreateInsertion(LParenLoc, "(")
1683 << FixItHint::CreateInsertion(RParenLoc, ")");
1690 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1691 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1696 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1698 // If it starts with a '(', we know that it is either a parenthesized
1699 // type-name, or it is a unary-expression that starts with a compound
1700 // literal, or starts with a primary-expression that is a parenthesized
1702 ParenParseOption ExprType = CastExpr;
1703 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1705 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1706 false, CastTy, RParenLoc);
1707 CastRange = SourceRange(LParenLoc, RParenLoc);
1709 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1711 if (ExprType == CastExpr) {
1716 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1717 // GNU typeof in C requires the expression to be parenthesized. Not so for
1718 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1719 // the start of a unary-expression, but doesn't include any postfix
1720 // pieces. Parse these now if present.
1721 if (!Operand.isInvalid())
1722 Operand = ParsePostfixExpressionSuffix(Operand.get());
1726 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1732 /// \brief Parse a sizeof or alignof expression.
1735 /// unary-expression: [C99 6.5.3]
1736 /// 'sizeof' unary-expression
1737 /// 'sizeof' '(' type-name ')'
1738 /// [C++11] 'sizeof' '...' '(' identifier ')'
1739 /// [GNU] '__alignof' unary-expression
1740 /// [GNU] '__alignof' '(' type-name ')'
1741 /// [C11] '_Alignof' '(' type-name ')'
1742 /// [C++11] 'alignof' '(' type-id ')'
1744 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1745 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1746 tok::kw__Alignof, tok::kw_vec_step,
1747 tok::kw___builtin_omp_required_simd_align) &&
1748 "Not a sizeof/alignof/vec_step expression!");
1752 // [C++11] 'sizeof' '...' '(' identifier ')'
1753 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1754 SourceLocation EllipsisLoc = ConsumeToken();
1755 SourceLocation LParenLoc, RParenLoc;
1756 IdentifierInfo *Name = nullptr;
1757 SourceLocation NameLoc;
1758 if (Tok.is(tok::l_paren)) {
1759 BalancedDelimiterTracker T(*this, tok::l_paren);
1761 LParenLoc = T.getOpenLocation();
1762 if (Tok.is(tok::identifier)) {
1763 Name = Tok.getIdentifierInfo();
1764 NameLoc = ConsumeToken();
1766 RParenLoc = T.getCloseLocation();
1767 if (RParenLoc.isInvalid())
1768 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1770 Diag(Tok, diag::err_expected_parameter_pack);
1771 SkipUntil(tok::r_paren, StopAtSemi);
1773 } else if (Tok.is(tok::identifier)) {
1774 Name = Tok.getIdentifierInfo();
1775 NameLoc = ConsumeToken();
1776 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1777 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1778 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1780 << FixItHint::CreateInsertion(LParenLoc, "(")
1781 << FixItHint::CreateInsertion(RParenLoc, ")");
1783 Diag(Tok, diag::err_sizeof_parameter_pack);
1789 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1790 Sema::ReuseLambdaContextDecl);
1792 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1793 OpTok.getLocation(),
1798 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1799 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1801 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1802 Sema::ReuseLambdaContextDecl);
1806 SourceRange CastRange;
1807 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1812 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1813 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1814 ExprKind = UETT_AlignOf;
1815 else if (OpTok.is(tok::kw_vec_step))
1816 ExprKind = UETT_VecStep;
1817 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1818 ExprKind = UETT_OpenMPRequiredSimdAlign;
1821 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1824 CastTy.getAsOpaquePtr(),
1827 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1828 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1830 // If we get here, the operand to the sizeof/alignof was an expresion.
1831 if (!Operand.isInvalid())
1832 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1840 /// ParseBuiltinPrimaryExpression
1843 /// primary-expression: [C99 6.5.1]
1844 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1845 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1846 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1848 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1849 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1851 /// [GNU] offsetof-member-designator:
1852 /// [GNU] identifier
1853 /// [GNU] offsetof-member-designator '.' identifier
1854 /// [GNU] offsetof-member-designator '[' expression ']'
1856 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1858 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1860 tok::TokenKind T = Tok.getKind();
1861 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1863 // All of these start with an open paren.
1864 if (Tok.isNot(tok::l_paren))
1865 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1868 BalancedDelimiterTracker PT(*this, tok::l_paren);
1874 default: llvm_unreachable("Not a builtin primary expression!");
1875 case tok::kw___builtin_va_arg: {
1876 ExprResult Expr(ParseAssignmentExpression());
1878 if (ExpectAndConsume(tok::comma)) {
1879 SkipUntil(tok::r_paren, StopAtSemi);
1883 TypeResult Ty = ParseTypeName();
1885 if (Tok.isNot(tok::r_paren)) {
1886 Diag(Tok, diag::err_expected) << tok::r_paren;
1890 if (Expr.isInvalid() || Ty.isInvalid())
1893 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1896 case tok::kw___builtin_offsetof: {
1897 SourceLocation TypeLoc = Tok.getLocation();
1898 TypeResult Ty = ParseTypeName();
1899 if (Ty.isInvalid()) {
1900 SkipUntil(tok::r_paren, StopAtSemi);
1904 if (ExpectAndConsume(tok::comma)) {
1905 SkipUntil(tok::r_paren, StopAtSemi);
1909 // We must have at least one identifier here.
1910 if (Tok.isNot(tok::identifier)) {
1911 Diag(Tok, diag::err_expected) << tok::identifier;
1912 SkipUntil(tok::r_paren, StopAtSemi);
1916 // Keep track of the various subcomponents we see.
1917 SmallVector<Sema::OffsetOfComponent, 4> Comps;
1919 Comps.push_back(Sema::OffsetOfComponent());
1920 Comps.back().isBrackets = false;
1921 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1922 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1924 // FIXME: This loop leaks the index expressions on error.
1926 if (Tok.is(tok::period)) {
1927 // offsetof-member-designator: offsetof-member-designator '.' identifier
1928 Comps.push_back(Sema::OffsetOfComponent());
1929 Comps.back().isBrackets = false;
1930 Comps.back().LocStart = ConsumeToken();
1932 if (Tok.isNot(tok::identifier)) {
1933 Diag(Tok, diag::err_expected) << tok::identifier;
1934 SkipUntil(tok::r_paren, StopAtSemi);
1937 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1938 Comps.back().LocEnd = ConsumeToken();
1940 } else if (Tok.is(tok::l_square)) {
1941 if (CheckProhibitedCXX11Attribute())
1944 // offsetof-member-designator: offsetof-member-design '[' expression ']'
1945 Comps.push_back(Sema::OffsetOfComponent());
1946 Comps.back().isBrackets = true;
1947 BalancedDelimiterTracker ST(*this, tok::l_square);
1949 Comps.back().LocStart = ST.getOpenLocation();
1950 Res = ParseExpression();
1951 if (Res.isInvalid()) {
1952 SkipUntil(tok::r_paren, StopAtSemi);
1955 Comps.back().U.E = Res.get();
1958 Comps.back().LocEnd = ST.getCloseLocation();
1960 if (Tok.isNot(tok::r_paren)) {
1963 } else if (Ty.isInvalid()) {
1967 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
1968 Ty.get(), &Comps[0], Comps.size(),
1969 PT.getCloseLocation());
1976 case tok::kw___builtin_choose_expr: {
1977 ExprResult Cond(ParseAssignmentExpression());
1978 if (Cond.isInvalid()) {
1979 SkipUntil(tok::r_paren, StopAtSemi);
1982 if (ExpectAndConsume(tok::comma)) {
1983 SkipUntil(tok::r_paren, StopAtSemi);
1987 ExprResult Expr1(ParseAssignmentExpression());
1988 if (Expr1.isInvalid()) {
1989 SkipUntil(tok::r_paren, StopAtSemi);
1992 if (ExpectAndConsume(tok::comma)) {
1993 SkipUntil(tok::r_paren, StopAtSemi);
1997 ExprResult Expr2(ParseAssignmentExpression());
1998 if (Expr2.isInvalid()) {
1999 SkipUntil(tok::r_paren, StopAtSemi);
2002 if (Tok.isNot(tok::r_paren)) {
2003 Diag(Tok, diag::err_expected) << tok::r_paren;
2006 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2007 Expr2.get(), ConsumeParen());
2010 case tok::kw___builtin_astype: {
2011 // The first argument is an expression to be converted, followed by a comma.
2012 ExprResult Expr(ParseAssignmentExpression());
2013 if (Expr.isInvalid()) {
2014 SkipUntil(tok::r_paren, StopAtSemi);
2018 if (ExpectAndConsume(tok::comma)) {
2019 SkipUntil(tok::r_paren, StopAtSemi);
2023 // Second argument is the type to bitcast to.
2024 TypeResult DestTy = ParseTypeName();
2025 if (DestTy.isInvalid())
2028 // Attempt to consume the r-paren.
2029 if (Tok.isNot(tok::r_paren)) {
2030 Diag(Tok, diag::err_expected) << tok::r_paren;
2031 SkipUntil(tok::r_paren, StopAtSemi);
2035 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2039 case tok::kw___builtin_convertvector: {
2040 // The first argument is an expression to be converted, followed by a comma.
2041 ExprResult Expr(ParseAssignmentExpression());
2042 if (Expr.isInvalid()) {
2043 SkipUntil(tok::r_paren, StopAtSemi);
2047 if (ExpectAndConsume(tok::comma)) {
2048 SkipUntil(tok::r_paren, StopAtSemi);
2052 // Second argument is the type to bitcast to.
2053 TypeResult DestTy = ParseTypeName();
2054 if (DestTy.isInvalid())
2057 // Attempt to consume the r-paren.
2058 if (Tok.isNot(tok::r_paren)) {
2059 Diag(Tok, diag::err_expected) << tok::r_paren;
2060 SkipUntil(tok::r_paren, StopAtSemi);
2064 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2070 if (Res.isInvalid())
2073 // These can be followed by postfix-expr pieces because they are
2074 // primary-expressions.
2075 return ParsePostfixExpressionSuffix(Res.get());
2078 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2079 /// based on what is allowed by ExprType. The actual thing parsed is returned
2080 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2081 /// not the parsed cast-expression.
2084 /// primary-expression: [C99 6.5.1]
2085 /// '(' expression ')'
2086 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2087 /// postfix-expression: [C99 6.5.2]
2088 /// '(' type-name ')' '{' initializer-list '}'
2089 /// '(' type-name ')' '{' initializer-list ',' '}'
2090 /// cast-expression: [C99 6.5.4]
2091 /// '(' type-name ')' cast-expression
2092 /// [ARC] bridged-cast-expression
2093 /// [ARC] bridged-cast-expression:
2094 /// (__bridge type-name) cast-expression
2095 /// (__bridge_transfer type-name) cast-expression
2096 /// (__bridge_retained type-name) cast-expression
2097 /// fold-expression: [C++1z]
2098 /// '(' cast-expression fold-operator '...' ')'
2099 /// '(' '...' fold-operator cast-expression ')'
2100 /// '(' cast-expression fold-operator '...'
2101 /// fold-operator cast-expression ')'
2104 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2105 bool isTypeCast, ParsedType &CastTy,
2106 SourceLocation &RParenLoc) {
2107 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2108 ColonProtectionRAIIObject ColonProtection(*this, false);
2109 BalancedDelimiterTracker T(*this, tok::l_paren);
2110 if (T.consumeOpen())
2112 SourceLocation OpenLoc = T.getOpenLocation();
2114 ExprResult Result(true);
2115 bool isAmbiguousTypeId;
2116 CastTy = ParsedType();
2118 if (Tok.is(tok::code_completion)) {
2119 Actions.CodeCompleteOrdinaryName(getCurScope(),
2120 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2121 : Sema::PCC_Expression);
2126 // Diagnose use of bridge casts in non-arc mode.
2127 bool BridgeCast = (getLangOpts().ObjC2 &&
2128 Tok.isOneOf(tok::kw___bridge,
2129 tok::kw___bridge_transfer,
2130 tok::kw___bridge_retained,
2131 tok::kw___bridge_retain));
2132 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2133 if (!TryConsumeToken(tok::kw___bridge)) {
2134 StringRef BridgeCastName = Tok.getName();
2135 SourceLocation BridgeKeywordLoc = ConsumeToken();
2136 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2137 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2139 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2144 // None of these cases should fall through with an invalid Result
2145 // unless they've already reported an error.
2146 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2147 Diag(Tok, diag::ext_gnu_statement_expr);
2149 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2150 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2152 // Find the nearest non-record decl context. Variables declared in a
2153 // statement expression behave as if they were declared in the enclosing
2154 // function, block, or other code construct.
2155 DeclContext *CodeDC = Actions.CurContext;
2156 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2157 CodeDC = CodeDC->getParent();
2158 assert(CodeDC && !CodeDC->isFileContext() &&
2159 "statement expr not in code context");
2161 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2163 Actions.ActOnStartStmtExpr();
2165 StmtResult Stmt(ParseCompoundStatement(true));
2166 ExprType = CompoundStmt;
2168 // If the substmt parsed correctly, build the AST node.
2169 if (!Stmt.isInvalid()) {
2170 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2172 Actions.ActOnStmtExprError();
2175 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2176 tok::TokenKind tokenKind = Tok.getKind();
2177 SourceLocation BridgeKeywordLoc = ConsumeToken();
2179 // Parse an Objective-C ARC ownership cast expression.
2180 ObjCBridgeCastKind Kind;
2181 if (tokenKind == tok::kw___bridge)
2183 else if (tokenKind == tok::kw___bridge_transfer)
2184 Kind = OBC_BridgeTransfer;
2185 else if (tokenKind == tok::kw___bridge_retained)
2186 Kind = OBC_BridgeRetained;
2188 // As a hopefully temporary workaround, allow __bridge_retain as
2189 // a synonym for __bridge_retained, but only in system headers.
2190 assert(tokenKind == tok::kw___bridge_retain);
2191 Kind = OBC_BridgeRetained;
2192 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2193 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2194 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2195 "__bridge_retained");
2198 TypeResult Ty = ParseTypeName();
2200 ColonProtection.restore();
2201 RParenLoc = T.getCloseLocation();
2202 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2204 if (Ty.isInvalid() || SubExpr.isInvalid())
2207 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2208 BridgeKeywordLoc, Ty.get(),
2209 RParenLoc, SubExpr.get());
2210 } else if (ExprType >= CompoundLiteral &&
2211 isTypeIdInParens(isAmbiguousTypeId)) {
2213 // Otherwise, this is a compound literal expression or cast expression.
2215 // In C++, if the type-id is ambiguous we disambiguate based on context.
2216 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2217 // in which case we should treat it as type-id.
2218 // if stopIfCastExpr is false, we need to determine the context past the
2219 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2220 if (isAmbiguousTypeId && !stopIfCastExpr) {
2221 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2223 RParenLoc = T.getCloseLocation();
2227 // Parse the type declarator.
2228 DeclSpec DS(AttrFactory);
2229 ParseSpecifierQualifierList(DS);
2230 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2231 ParseDeclarator(DeclaratorInfo);
2233 // If our type is followed by an identifier and either ':' or ']', then
2234 // this is probably an Objective-C message send where the leading '[' is
2235 // missing. Recover as if that were the case.
2236 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2237 !InMessageExpression && getLangOpts().ObjC1 &&
2238 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2241 InMessageExpressionRAIIObject InMessage(*this, false);
2242 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2244 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2250 ColonProtection.restore();
2251 RParenLoc = T.getCloseLocation();
2252 if (Tok.is(tok::l_brace)) {
2253 ExprType = CompoundLiteral;
2256 InMessageExpressionRAIIObject InMessage(*this, false);
2257 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2259 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2262 if (ExprType == CastExpr) {
2263 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2265 if (DeclaratorInfo.isInvalidType())
2268 // Note that this doesn't parse the subsequent cast-expression, it just
2269 // returns the parsed type to the callee.
2270 if (stopIfCastExpr) {
2273 InMessageExpressionRAIIObject InMessage(*this, false);
2274 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2277 return ExprResult();
2280 // Reject the cast of super idiom in ObjC.
2281 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2282 Tok.getIdentifierInfo() == Ident_super &&
2283 getCurScope()->isInObjcMethodScope() &&
2284 GetLookAheadToken(1).isNot(tok::period)) {
2285 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2286 << SourceRange(OpenLoc, RParenLoc);
2290 // Parse the cast-expression that follows it next.
2291 // TODO: For cast expression with CastTy.
2292 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2293 /*isAddressOfOperand=*/false,
2294 /*isTypeCast=*/IsTypeCast);
2295 if (!Result.isInvalid()) {
2296 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2297 DeclaratorInfo, CastTy,
2298 RParenLoc, Result.get());
2303 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2306 } else if (Tok.is(tok::ellipsis) &&
2307 isFoldOperator(NextToken().getKind())) {
2308 return ParseFoldExpression(ExprResult(), T);
2309 } else if (isTypeCast) {
2310 // Parse the expression-list.
2311 InMessageExpressionRAIIObject InMessage(*this, false);
2313 ExprVector ArgExprs;
2314 CommaLocsTy CommaLocs;
2316 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2317 // FIXME: If we ever support comma expressions as operands to
2318 // fold-expressions, we'll need to allow multiple ArgExprs here.
2319 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2320 NextToken().is(tok::ellipsis))
2321 return ParseFoldExpression(Result, T);
2323 ExprType = SimpleExpr;
2324 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2328 InMessageExpressionRAIIObject InMessage(*this, false);
2330 Result = ParseExpression(MaybeTypeCast);
2331 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2332 // Correct typos in non-C++ code earlier so that implicit-cast-like
2333 // expressions are parsed correctly.
2334 Result = Actions.CorrectDelayedTyposInExpr(Result);
2336 ExprType = SimpleExpr;
2338 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2339 return ParseFoldExpression(Result, T);
2341 // Don't build a paren expression unless we actually match a ')'.
2342 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2344 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2348 if (Result.isInvalid()) {
2349 SkipUntil(tok::r_paren, StopAtSemi);
2354 RParenLoc = T.getCloseLocation();
2358 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2359 /// and we are at the left brace.
2362 /// postfix-expression: [C99 6.5.2]
2363 /// '(' type-name ')' '{' initializer-list '}'
2364 /// '(' type-name ')' '{' initializer-list ',' '}'
2367 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2368 SourceLocation LParenLoc,
2369 SourceLocation RParenLoc) {
2370 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2371 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2372 Diag(LParenLoc, diag::ext_c99_compound_literal);
2373 ExprResult Result = ParseInitializer();
2374 if (!Result.isInvalid() && Ty)
2375 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2379 /// ParseStringLiteralExpression - This handles the various token types that
2380 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2381 /// translation phase #6].
2384 /// primary-expression: [C99 6.5.1]
2387 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2388 assert(isTokenStringLiteral() && "Not a string literal!");
2390 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2391 // considered to be strings for concatenation purposes.
2392 SmallVector<Token, 4> StringToks;
2395 StringToks.push_back(Tok);
2396 ConsumeStringToken();
2397 } while (isTokenStringLiteral());
2399 // Pass the set of string tokens, ready for concatenation, to the actions.
2400 return Actions.ActOnStringLiteral(StringToks,
2401 AllowUserDefinedLiteral ? getCurScope()
2405 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2409 /// generic-selection:
2410 /// _Generic ( assignment-expression , generic-assoc-list )
2411 /// generic-assoc-list:
2412 /// generic-association
2413 /// generic-assoc-list , generic-association
2414 /// generic-association:
2415 /// type-name : assignment-expression
2416 /// default : assignment-expression
2418 ExprResult Parser::ParseGenericSelectionExpression() {
2419 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2420 SourceLocation KeyLoc = ConsumeToken();
2422 if (!getLangOpts().C11)
2423 Diag(KeyLoc, diag::ext_c11_generic_selection);
2425 BalancedDelimiterTracker T(*this, tok::l_paren);
2426 if (T.expectAndConsume())
2429 ExprResult ControllingExpr;
2431 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2433 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2435 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2436 if (ControllingExpr.isInvalid()) {
2437 SkipUntil(tok::r_paren, StopAtSemi);
2442 if (ExpectAndConsume(tok::comma)) {
2443 SkipUntil(tok::r_paren, StopAtSemi);
2447 SourceLocation DefaultLoc;
2452 if (Tok.is(tok::kw_default)) {
2453 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2454 // generic association."
2455 if (!DefaultLoc.isInvalid()) {
2456 Diag(Tok, diag::err_duplicate_default_assoc);
2457 Diag(DefaultLoc, diag::note_previous_default_assoc);
2458 SkipUntil(tok::r_paren, StopAtSemi);
2461 DefaultLoc = ConsumeToken();
2464 ColonProtectionRAIIObject X(*this);
2465 TypeResult TR = ParseTypeName();
2466 if (TR.isInvalid()) {
2467 SkipUntil(tok::r_paren, StopAtSemi);
2472 Types.push_back(Ty);
2474 if (ExpectAndConsume(tok::colon)) {
2475 SkipUntil(tok::r_paren, StopAtSemi);
2479 // FIXME: These expressions should be parsed in a potentially potentially
2480 // evaluated context.
2482 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2483 if (ER.isInvalid()) {
2484 SkipUntil(tok::r_paren, StopAtSemi);
2487 Exprs.push_back(ER.get());
2488 } while (TryConsumeToken(tok::comma));
2491 if (T.getCloseLocation().isInvalid())
2494 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2495 T.getCloseLocation(),
2496 ControllingExpr.get(),
2500 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2501 /// left-hand-side expression.
2504 /// fold-expression:
2505 /// ( cast-expression fold-operator ... )
2506 /// ( ... fold-operator cast-expression )
2507 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2508 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2509 BalancedDelimiterTracker &T) {
2510 if (LHS.isInvalid()) {
2515 tok::TokenKind Kind = tok::unknown;
2516 SourceLocation FirstOpLoc;
2517 if (LHS.isUsable()) {
2518 Kind = Tok.getKind();
2519 assert(isFoldOperator(Kind) && "missing fold-operator");
2520 FirstOpLoc = ConsumeToken();
2523 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2524 SourceLocation EllipsisLoc = ConsumeToken();
2527 if (Tok.isNot(tok::r_paren)) {
2528 if (!isFoldOperator(Tok.getKind()))
2529 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2531 if (Kind != tok::unknown && Tok.getKind() != Kind)
2532 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2533 << SourceRange(FirstOpLoc);
2534 Kind = Tok.getKind();
2537 RHS = ParseExpression();
2538 if (RHS.isInvalid()) {
2544 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2545 ? diag::warn_cxx14_compat_fold_expression
2546 : diag::ext_fold_expression);
2549 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2550 EllipsisLoc, RHS.get(), T.getCloseLocation());
2553 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2556 /// argument-expression-list:
2557 /// assignment-expression
2558 /// argument-expression-list , assignment-expression
2560 /// [C++] expression-list:
2561 /// [C++] assignment-expression
2562 /// [C++] expression-list , assignment-expression
2564 /// [C++0x] expression-list:
2565 /// [C++0x] initializer-list
2567 /// [C++0x] initializer-list
2568 /// [C++0x] initializer-clause ...[opt]
2569 /// [C++0x] initializer-list , initializer-clause ...[opt]
2571 /// [C++0x] initializer-clause:
2572 /// [C++0x] assignment-expression
2573 /// [C++0x] braced-init-list
2575 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2576 SmallVectorImpl<SourceLocation> &CommaLocs,
2577 std::function<void()> Completer) {
2578 bool SawError = false;
2580 if (Tok.is(tok::code_completion)) {
2584 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2590 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2591 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2592 Expr = ParseBraceInitializer();
2594 Expr = ParseAssignmentExpression();
2596 if (Tok.is(tok::ellipsis))
2597 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2598 if (Expr.isInvalid()) {
2599 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2602 Exprs.push_back(Expr.get());
2605 if (Tok.isNot(tok::comma))
2607 // Move to the next argument, remember where the comma was.
2608 CommaLocs.push_back(ConsumeToken());
2611 // Ensure typos get diagnosed when errors were encountered while parsing the
2613 for (auto &E : Exprs) {
2614 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2615 if (Expr.isUsable()) E = Expr.get();
2621 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2622 /// used for misc language extensions.
2625 /// simple-expression-list:
2626 /// assignment-expression
2627 /// simple-expression-list , assignment-expression
2630 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2631 SmallVectorImpl<SourceLocation> &CommaLocs) {
2633 ExprResult Expr = ParseAssignmentExpression();
2634 if (Expr.isInvalid())
2637 Exprs.push_back(Expr.get());
2639 if (Tok.isNot(tok::comma))
2642 // Move to the next argument, remember where the comma was.
2643 CommaLocs.push_back(ConsumeToken());
2647 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2650 /// [clang] block-id:
2651 /// [clang] specifier-qualifier-list block-declarator
2653 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2654 if (Tok.is(tok::code_completion)) {
2655 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2656 return cutOffParsing();
2659 // Parse the specifier-qualifier-list piece.
2660 DeclSpec DS(AttrFactory);
2661 ParseSpecifierQualifierList(DS);
2663 // Parse the block-declarator.
2664 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2665 ParseDeclarator(DeclaratorInfo);
2667 MaybeParseGNUAttributes(DeclaratorInfo);
2669 // Inform sema that we are starting a block.
2670 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2673 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2674 /// like ^(int x){ return x+1; }
2678 /// [clang] '^' block-args[opt] compound-statement
2679 /// [clang] '^' block-id compound-statement
2680 /// [clang] block-args:
2681 /// [clang] '(' parameter-list ')'
2683 ExprResult Parser::ParseBlockLiteralExpression() {
2684 assert(Tok.is(tok::caret) && "block literal starts with ^");
2685 SourceLocation CaretLoc = ConsumeToken();
2687 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2688 "block literal parsing");
2690 // Enter a scope to hold everything within the block. This includes the
2691 // argument decls, decls within the compound expression, etc. This also
2692 // allows determining whether a variable reference inside the block is
2693 // within or outside of the block.
2694 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2697 // Inform sema that we are starting a block.
2698 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2700 // Parse the return type if present.
2701 DeclSpec DS(AttrFactory);
2702 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2703 // FIXME: Since the return type isn't actually parsed, it can't be used to
2704 // fill ParamInfo with an initial valid range, so do it manually.
2705 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2707 // If this block has arguments, parse them. There is no ambiguity here with
2708 // the expression case, because the expression case requires a parameter list.
2709 if (Tok.is(tok::l_paren)) {
2710 ParseParenDeclarator(ParamInfo);
2711 // Parse the pieces after the identifier as if we had "int(...)".
2712 // SetIdentifier sets the source range end, but in this case we're past
2714 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2715 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2716 ParamInfo.SetRangeEnd(Tmp);
2717 if (ParamInfo.isInvalidType()) {
2718 // If there was an error parsing the arguments, they may have
2719 // tried to use ^(x+y) which requires an argument list. Just
2720 // skip the whole block literal.
2721 Actions.ActOnBlockError(CaretLoc, getCurScope());
2725 MaybeParseGNUAttributes(ParamInfo);
2727 // Inform sema that we are starting a block.
2728 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2729 } else if (!Tok.is(tok::l_brace)) {
2730 ParseBlockId(CaretLoc);
2732 // Otherwise, pretend we saw (void).
2733 ParsedAttributes attrs(AttrFactory);
2734 SourceLocation NoLoc;
2735 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2736 /*IsAmbiguous=*/false,
2737 /*RParenLoc=*/NoLoc,
2738 /*ArgInfo=*/nullptr,
2740 /*EllipsisLoc=*/NoLoc,
2741 /*RParenLoc=*/NoLoc,
2743 /*RefQualifierIsLvalueRef=*/true,
2744 /*RefQualifierLoc=*/NoLoc,
2745 /*ConstQualifierLoc=*/NoLoc,
2746 /*VolatileQualifierLoc=*/NoLoc,
2747 /*RestrictQualifierLoc=*/NoLoc,
2748 /*MutableLoc=*/NoLoc,
2751 /*Exceptions=*/nullptr,
2752 /*ExceptionRanges=*/nullptr,
2753 /*NumExceptions=*/0,
2754 /*NoexceptExpr=*/nullptr,
2755 /*ExceptionSpecTokens=*/nullptr,
2760 MaybeParseGNUAttributes(ParamInfo);
2762 // Inform sema that we are starting a block.
2763 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2767 ExprResult Result(true);
2768 if (!Tok.is(tok::l_brace)) {
2769 // Saw something like: ^expr
2770 Diag(Tok, diag::err_expected_expression);
2771 Actions.ActOnBlockError(CaretLoc, getCurScope());
2775 StmtResult Stmt(ParseCompoundStatementBody());
2777 if (!Stmt.isInvalid())
2778 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2780 Actions.ActOnBlockError(CaretLoc, getCurScope());
2784 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2788 ExprResult Parser::ParseObjCBoolLiteral() {
2789 tok::TokenKind Kind = Tok.getKind();
2790 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);