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();
166 if (Tok.is(tok::kw_co_yield))
167 return ParseCoyieldExpression();
169 ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
170 /*isAddressOfOperand=*/false,
172 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
175 /// \brief Parse an assignment expression where part of an Objective-C message
176 /// send has already been parsed.
178 /// In this case \p LBracLoc indicates the location of the '[' of the message
179 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
180 /// the receiver of the message.
182 /// Since this handles full assignment-expression's, it handles postfix
183 /// expressions and other binary operators for these expressions as well.
185 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
186 SourceLocation SuperLoc,
187 ParsedType ReceiverType,
188 Expr *ReceiverExpr) {
190 = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
191 ReceiverType, ReceiverExpr);
192 R = ParsePostfixExpressionSuffix(R);
193 return ParseRHSOfBinaryExpression(R, prec::Assignment);
197 ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
198 // C++03 [basic.def.odr]p2:
199 // An expression is potentially evaluated unless it appears where an
200 // integral constant expression is required (see 5.19) [...].
201 // C++98 and C++11 have no such rule, but this is only a defect in C++98.
202 EnterExpressionEvaluationContext Unevaluated(Actions,
203 Sema::ConstantEvaluated);
205 ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
206 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
207 return Actions.ActOnConstantExpression(Res);
210 /// \brief Parse a constraint-expression.
213 /// constraint-expression: [Concepts TS temp.constr.decl p1]
214 /// logical-or-expression
216 ExprResult Parser::ParseConstraintExpression() {
217 // FIXME: this may erroneously consume a function-body as the braced
218 // initializer list of a compound literal
220 // FIXME: this may erroneously consume a parenthesized rvalue reference
221 // declarator as a parenthesized address-of-label expression
222 ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false));
223 ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
228 bool Parser::isNotExpressionStart() {
229 tok::TokenKind K = Tok.getKind();
230 if (K == tok::l_brace || K == tok::r_brace ||
231 K == tok::kw_for || K == tok::kw_while ||
232 K == tok::kw_if || K == tok::kw_else ||
233 K == tok::kw_goto || K == tok::kw_try)
235 // If this is a decl-specifier, we can't be at the start of an expression.
236 return isKnownToBeDeclarationSpecifier();
239 static bool isFoldOperator(prec::Level Level) {
240 return Level > prec::Unknown && Level != prec::Conditional;
242 static bool isFoldOperator(tok::TokenKind Kind) {
243 return isFoldOperator(getBinOpPrecedence(Kind, false, true));
246 /// \brief Parse a binary expression that starts with \p LHS and has a
247 /// precedence of at least \p MinPrec.
249 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
250 prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
251 GreaterThanIsOperator,
252 getLangOpts().CPlusPlus11);
253 SourceLocation ColonLoc;
256 // If this token has a lower precedence than we are allowed to parse (e.g.
257 // because we are called recursively, or because the token is not a binop),
259 if (NextTokPrec < MinPrec)
262 // Consume the operator, saving the operator token for error reporting.
266 // Bail out when encountering a comma followed by a token which can't
267 // possibly be the start of an expression. For instance:
268 // int f() { return 1, }
269 // We can't do this before consuming the comma, because
270 // isNotExpressionStart() looks at the token stream.
271 if (OpToken.is(tok::comma) && isNotExpressionStart()) {
277 // If the next token is an ellipsis, then this is a fold-expression. Leave
278 // it alone so we can handle it in the paren expression.
279 if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
280 // FIXME: We can't check this via lookahead before we consume the token
281 // because that tickles a lexer bug.
287 // Special case handling for the ternary operator.
288 ExprResult TernaryMiddle(true);
289 if (NextTokPrec == prec::Conditional) {
290 if (Tok.isNot(tok::colon)) {
291 // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
292 ColonProtectionRAIIObject X(*this);
294 // Handle this production specially:
295 // logical-OR-expression '?' expression ':' conditional-expression
296 // In particular, the RHS of the '?' is 'expression', not
297 // 'logical-OR-expression' as we might expect.
298 TernaryMiddle = ParseExpression();
299 if (TernaryMiddle.isInvalid()) {
300 Actions.CorrectDelayedTyposInExpr(LHS);
302 TernaryMiddle = nullptr;
305 // Special case handling of "X ? Y : Z" where Y is empty:
306 // logical-OR-expression '?' ':' conditional-expression [GNU]
307 TernaryMiddle = nullptr;
308 Diag(Tok, diag::ext_gnu_conditional_expr);
311 if (!TryConsumeToken(tok::colon, ColonLoc)) {
312 // Otherwise, we're missing a ':'. Assume that this was a typo that
313 // the user forgot. If we're not in a macro expansion, we can suggest
314 // a fixit hint. If there were two spaces before the current token,
315 // suggest inserting the colon in between them, otherwise insert ": ".
316 SourceLocation FILoc = Tok.getLocation();
317 const char *FIText = ": ";
318 const SourceManager &SM = PP.getSourceManager();
319 if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
320 assert(FILoc.isFileID());
321 bool IsInvalid = false;
322 const char *SourcePtr =
323 SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
324 if (!IsInvalid && *SourcePtr == ' ') {
326 SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
327 if (!IsInvalid && *SourcePtr == ' ') {
328 FILoc = FILoc.getLocWithOffset(-1);
334 Diag(Tok, diag::err_expected)
335 << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
336 Diag(OpToken, diag::note_matching) << tok::question;
337 ColonLoc = Tok.getLocation();
341 // Code completion for the right-hand side of an assignment expression
342 // goes through a special hook that takes the left-hand side into account.
343 if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
344 Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
349 // Parse another leaf here for the RHS of the operator.
350 // ParseCastExpression works here because all RHS expressions in C have it
351 // as a prefix, at least. However, in C++, an assignment-expression could
352 // be a throw-expression, which is not a valid cast-expression.
353 // Therefore we need some special-casing here.
354 // Also note that the third operand of the conditional operator is
355 // an assignment-expression in C++, and in C++11, we can have a
356 // braced-init-list on the RHS of an assignment. For better diagnostics,
357 // parse as if we were allowed braced-init-lists everywhere, and check that
358 // they only appear on the RHS of assignments later.
360 bool RHSIsInitList = false;
361 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
362 RHS = ParseBraceInitializer();
363 RHSIsInitList = true;
364 } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
365 RHS = ParseAssignmentExpression();
367 RHS = ParseCastExpression(false);
369 if (RHS.isInvalid()) {
370 // FIXME: Errors generated by the delayed typo correction should be
371 // printed before errors from parsing the RHS, not after.
372 Actions.CorrectDelayedTyposInExpr(LHS);
373 if (TernaryMiddle.isUsable())
374 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
378 // Remember the precedence of this operator and get the precedence of the
379 // operator immediately to the right of the RHS.
380 prec::Level ThisPrec = NextTokPrec;
381 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
382 getLangOpts().CPlusPlus11);
384 // Assignment and conditional expressions are right-associative.
385 bool isRightAssoc = ThisPrec == prec::Conditional ||
386 ThisPrec == prec::Assignment;
388 // Get the precedence of the operator to the right of the RHS. If it binds
389 // more tightly with RHS than we do, evaluate it completely first.
390 if (ThisPrec < NextTokPrec ||
391 (ThisPrec == NextTokPrec && isRightAssoc)) {
392 if (!RHS.isInvalid() && RHSIsInitList) {
393 Diag(Tok, diag::err_init_list_bin_op)
394 << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
397 // If this is left-associative, only parse things on the RHS that bind
398 // more tightly than the current operator. If it is left-associative, it
399 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
400 // A=(B=(C=D)), where each paren is a level of recursion here.
401 // The function takes ownership of the RHS.
402 RHS = ParseRHSOfBinaryExpression(RHS,
403 static_cast<prec::Level>(ThisPrec + !isRightAssoc));
404 RHSIsInitList = false;
406 if (RHS.isInvalid()) {
407 // FIXME: Errors generated by the delayed typo correction should be
408 // printed before errors from ParseRHSOfBinaryExpression, not after.
409 Actions.CorrectDelayedTyposInExpr(LHS);
410 if (TernaryMiddle.isUsable())
411 TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
415 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
416 getLangOpts().CPlusPlus11);
419 if (!RHS.isInvalid() && RHSIsInitList) {
420 if (ThisPrec == prec::Assignment) {
421 Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
422 << Actions.getExprRange(RHS.get());
424 Diag(OpToken, diag::err_init_list_bin_op)
425 << /*RHS*/1 << PP.getSpelling(OpToken)
426 << Actions.getExprRange(RHS.get());
431 if (!LHS.isInvalid()) {
432 // Combine the LHS and RHS into the LHS (e.g. build AST).
433 if (TernaryMiddle.isInvalid()) {
434 // If we're using '>>' as an operator within a template
435 // argument list (in C++98), suggest the addition of
436 // parentheses so that the code remains well-formed in C++0x.
437 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
438 SuggestParentheses(OpToken.getLocation(),
439 diag::warn_cxx11_right_shift_in_template_arg,
440 SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
441 Actions.getExprRange(RHS.get()).getEnd()));
443 LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
444 OpToken.getKind(), LHS.get(), RHS.get());
446 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
447 LHS.get(), TernaryMiddle.get(),
450 // Ensure potential typos in the RHS aren't left undiagnosed.
451 Actions.CorrectDelayedTyposInExpr(RHS);
455 /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
456 /// parse a unary-expression.
458 /// \p isAddressOfOperand exists because an id-expression that is the
459 /// operand of address-of gets special treatment due to member pointers.
461 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
462 bool isAddressOfOperand,
463 TypeCastState isTypeCast) {
465 ExprResult Res = ParseCastExpression(isUnaryExpression,
470 Diag(Tok, diag::err_expected_expression);
475 class CastExpressionIdValidator : public CorrectionCandidateCallback {
477 CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
478 : NextToken(Next), AllowNonTypes(AllowNonTypes) {
479 WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
482 bool ValidateCandidate(const TypoCorrection &candidate) override {
483 NamedDecl *ND = candidate.getCorrectionDecl();
485 return candidate.isKeyword();
487 if (isa<TypeDecl>(ND))
488 return WantTypeSpecifiers;
490 if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
493 if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
496 for (auto *C : candidate) {
497 NamedDecl *ND = C->getUnderlyingDecl();
498 if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
510 /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
511 /// a unary-expression.
513 /// \p isAddressOfOperand exists because an id-expression that is the operand
514 /// of address-of gets special treatment due to member pointers. NotCastExpr
515 /// is set to true if the token is not the start of a cast-expression, and no
516 /// diagnostic is emitted in this case.
519 /// cast-expression: [C99 6.5.4]
521 /// '(' type-name ')' cast-expression
523 /// unary-expression: [C99 6.5.3]
524 /// postfix-expression
525 /// '++' unary-expression
526 /// '--' unary-expression
527 /// [Coro] 'co_await' cast-expression
528 /// unary-operator cast-expression
529 /// 'sizeof' unary-expression
530 /// 'sizeof' '(' type-name ')'
531 /// [C++11] 'sizeof' '...' '(' identifier ')'
532 /// [GNU] '__alignof' unary-expression
533 /// [GNU] '__alignof' '(' type-name ')'
534 /// [C11] '_Alignof' '(' type-name ')'
535 /// [C++11] 'alignof' '(' type-id ')'
536 /// [GNU] '&&' identifier
537 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
538 /// [C++] new-expression
539 /// [C++] delete-expression
541 /// unary-operator: one of
542 /// '&' '*' '+' '-' '~' '!'
543 /// [GNU] '__extension__' '__real' '__imag'
545 /// primary-expression: [C99 6.5.1]
547 /// [C++] id-expression
550 /// [C++] boolean-literal [C++ 2.13.5]
551 /// [C++11] 'nullptr' [C++11 2.14.7]
552 /// [C++11] user-defined-literal
553 /// '(' expression ')'
554 /// [C11] generic-selection
555 /// '__func__' [C99 6.4.2.2]
556 /// [GNU] '__FUNCTION__'
557 /// [MS] '__FUNCDNAME__'
558 /// [MS] 'L__FUNCTION__'
559 /// [GNU] '__PRETTY_FUNCTION__'
560 /// [GNU] '(' compound-statement ')'
561 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
562 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
563 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
565 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
567 /// [OBJC] '[' objc-message-expr ']'
568 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
569 /// [OBJC] '\@protocol' '(' identifier ')'
570 /// [OBJC] '\@encode' '(' type-name ')'
571 /// [OBJC] objc-string-literal
572 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
573 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
574 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
575 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
576 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
577 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
578 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
579 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
580 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
581 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
582 /// [C++] 'this' [C++ 9.3.2]
583 /// [G++] unary-type-trait '(' type-id ')'
584 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
585 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
586 /// [clang] '^' block-literal
588 /// constant: [C99 6.4.4]
590 /// floating-constant
591 /// enumeration-constant -> identifier
592 /// character-constant
594 /// id-expression: [C++ 5.1]
598 /// unqualified-id: [C++ 5.1]
600 /// operator-function-id
601 /// conversion-function-id
605 /// new-expression: [C++ 5.3.4]
606 /// '::'[opt] 'new' new-placement[opt] new-type-id
607 /// new-initializer[opt]
608 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
609 /// new-initializer[opt]
611 /// delete-expression: [C++ 5.3.5]
612 /// '::'[opt] 'delete' cast-expression
613 /// '::'[opt] 'delete' '[' ']' cast-expression
615 /// [GNU/Embarcadero] unary-type-trait:
616 /// '__is_arithmetic'
617 /// '__is_floating_point'
619 /// '__is_lvalue_expr'
620 /// '__is_rvalue_expr'
621 /// '__is_complete_type'
626 /// '__is_lvalue_reference'
627 /// '__is_rvalue_reference'
628 /// '__is_fundamental'
633 /// '__is_member_object_pointer'
634 /// '__is_member_function_pointer'
635 /// '__is_member_pointer'
639 /// '__is_standard_layout'
643 /// [GNU] unary-type-trait:
644 /// '__has_nothrow_assign'
645 /// '__has_nothrow_copy'
646 /// '__has_nothrow_constructor'
647 /// '__has_trivial_assign' [TODO]
648 /// '__has_trivial_copy' [TODO]
649 /// '__has_trivial_constructor'
650 /// '__has_trivial_destructor'
651 /// '__has_virtual_destructor'
652 /// '__is_abstract' [TODO]
654 /// '__is_empty' [TODO]
658 /// '__is_polymorphic'
659 /// '__is_sealed' [MS]
663 /// [Clang] unary-type-trait:
664 /// '__trivially_copyable'
666 /// binary-type-trait:
667 /// [GNU] '__is_base_of'
668 /// [MS] '__is_convertible_to'
669 /// '__is_convertible'
672 /// [Embarcadero] array-type-trait:
676 /// [Embarcadero] expression-trait:
677 /// '__is_lvalue_expr'
678 /// '__is_rvalue_expr'
681 ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
682 bool isAddressOfOperand,
684 TypeCastState isTypeCast) {
686 tok::TokenKind SavedKind = Tok.getKind();
689 // This handles all of cast-expression, unary-expression, postfix-expression,
690 // and primary-expression. We handle them together like this for efficiency
691 // and to simplify handling of an expression starting with a '(' token: which
692 // may be one of a parenthesized expression, cast-expression, compound literal
693 // expression, or statement expression.
695 // If the parsed tokens consist of a primary-expression, the cases below
696 // break out of the switch; at the end we call ParsePostfixExpressionSuffix
697 // to handle the postfix expression suffixes. Cases that cannot be followed
698 // by postfix exprs should return without invoking
699 // ParsePostfixExpressionSuffix.
702 // If this expression is limited to being a unary-expression, the parent can
703 // not start a cast expression.
704 ParenParseOption ParenExprType =
705 (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral
708 SourceLocation RParenLoc;
709 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
710 isTypeCast == IsTypeCast, CastTy, RParenLoc);
712 switch (ParenExprType) {
713 case SimpleExpr: break; // Nothing else to do.
714 case CompoundStmt: break; // Nothing else to do.
715 case CompoundLiteral:
716 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
717 // postfix-expression exist, parse them now.
720 // We have parsed the cast-expression and no postfix-expr pieces are
728 // primary-expression
729 case tok::numeric_constant:
730 // constant: integer-constant
731 // constant: floating-constant
733 Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
739 return ParseCXXBoolLiteral();
741 case tok::kw___objc_yes:
742 case tok::kw___objc_no:
743 return ParseObjCBoolLiteral();
745 case tok::kw_nullptr:
746 Diag(Tok, diag::warn_cxx98_compat_nullptr);
747 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
749 case tok::annot_primary_expr:
750 assert(Res.get() == nullptr && "Stray primary-expression annotation?");
751 Res = getExprAnnotation(Tok);
755 case tok::kw___super:
756 case tok::kw_decltype:
757 // Annotate the token and tail recurse.
758 if (TryAnnotateTypeOrScopeToken())
760 assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
761 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
763 case tok::identifier: { // primary-expression: identifier
764 // unqualified-id: identifier
765 // constant: enumeration-constant
766 // Turn a potentially qualified name into a annot_typename or
767 // annot_cxxscope if it would be valid. This handles things like x::y, etc.
768 if (getLangOpts().CPlusPlus) {
769 // Avoid the unnecessary parse-time lookup in the common case
770 // where the syntax forbids a type.
771 const Token &Next = NextToken();
773 // If this identifier was reverted from a token ID, and the next token
774 // is a parenthesis, this is likely to be a use of a type trait. Check
776 if (Next.is(tok::l_paren) &&
777 Tok.is(tok::identifier) &&
778 Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
779 IdentifierInfo *II = Tok.getIdentifierInfo();
780 // Build up the mapping of revertible type traits, for future use.
781 if (RevertibleTypeTraits.empty()) {
782 #define RTT_JOIN(X,Y) X##Y
783 #define REVERTIBLE_TYPE_TRAIT(Name) \
784 RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \
785 = RTT_JOIN(tok::kw_,Name)
787 REVERTIBLE_TYPE_TRAIT(__is_abstract);
788 REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
789 REVERTIBLE_TYPE_TRAIT(__is_array);
790 REVERTIBLE_TYPE_TRAIT(__is_base_of);
791 REVERTIBLE_TYPE_TRAIT(__is_class);
792 REVERTIBLE_TYPE_TRAIT(__is_complete_type);
793 REVERTIBLE_TYPE_TRAIT(__is_compound);
794 REVERTIBLE_TYPE_TRAIT(__is_const);
795 REVERTIBLE_TYPE_TRAIT(__is_constructible);
796 REVERTIBLE_TYPE_TRAIT(__is_convertible);
797 REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
798 REVERTIBLE_TYPE_TRAIT(__is_destructible);
799 REVERTIBLE_TYPE_TRAIT(__is_empty);
800 REVERTIBLE_TYPE_TRAIT(__is_enum);
801 REVERTIBLE_TYPE_TRAIT(__is_floating_point);
802 REVERTIBLE_TYPE_TRAIT(__is_final);
803 REVERTIBLE_TYPE_TRAIT(__is_function);
804 REVERTIBLE_TYPE_TRAIT(__is_fundamental);
805 REVERTIBLE_TYPE_TRAIT(__is_integral);
806 REVERTIBLE_TYPE_TRAIT(__is_interface_class);
807 REVERTIBLE_TYPE_TRAIT(__is_literal);
808 REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
809 REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
810 REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
811 REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
812 REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
813 REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
814 REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
815 REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
816 REVERTIBLE_TYPE_TRAIT(__is_object);
817 REVERTIBLE_TYPE_TRAIT(__is_pod);
818 REVERTIBLE_TYPE_TRAIT(__is_pointer);
819 REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
820 REVERTIBLE_TYPE_TRAIT(__is_reference);
821 REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
822 REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
823 REVERTIBLE_TYPE_TRAIT(__is_same);
824 REVERTIBLE_TYPE_TRAIT(__is_scalar);
825 REVERTIBLE_TYPE_TRAIT(__is_sealed);
826 REVERTIBLE_TYPE_TRAIT(__is_signed);
827 REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
828 REVERTIBLE_TYPE_TRAIT(__is_trivial);
829 REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
830 REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
831 REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
832 REVERTIBLE_TYPE_TRAIT(__is_union);
833 REVERTIBLE_TYPE_TRAIT(__is_unsigned);
834 REVERTIBLE_TYPE_TRAIT(__is_void);
835 REVERTIBLE_TYPE_TRAIT(__is_volatile);
836 #undef REVERTIBLE_TYPE_TRAIT
840 // If we find that this is in fact the name of a type trait,
841 // update the token kind in place and parse again to treat it as
842 // the appropriate kind of type trait.
843 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
844 = RevertibleTypeTraits.find(II);
845 if (Known != RevertibleTypeTraits.end()) {
846 Tok.setKind(Known->second);
847 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
848 NotCastExpr, isTypeCast);
852 if ((!ColonIsSacred && Next.is(tok::colon)) ||
853 Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
855 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
856 if (TryAnnotateTypeOrScopeToken())
858 if (!Tok.is(tok::identifier))
859 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
863 // Consume the identifier so that we can see if it is followed by a '(' or
865 IdentifierInfo &II = *Tok.getIdentifierInfo();
866 SourceLocation ILoc = ConsumeToken();
868 // Support 'Class.property' and 'super.property' notation.
869 if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
870 (Actions.getTypeName(II, ILoc, getCurScope()) ||
871 // Allow the base to be 'super' if in an objc-method.
872 (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
875 // Allow either an identifier or the keyword 'class' (in C++).
876 if (Tok.isNot(tok::identifier) &&
877 !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
878 Diag(Tok, diag::err_expected_property_name);
881 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
882 SourceLocation PropertyLoc = ConsumeToken();
884 Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
889 // In an Objective-C method, if we have "super" followed by an identifier,
890 // the token sequence is ill-formed. However, if there's a ':' or ']' after
891 // that identifier, this is probably a message send with a missing open
892 // bracket. Treat it as such.
893 if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
894 getCurScope()->isInObjcMethodScope() &&
895 ((Tok.is(tok::identifier) &&
896 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
897 Tok.is(tok::code_completion))) {
898 Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
903 // If we have an Objective-C class name followed by an identifier
904 // and either ':' or ']', this is an Objective-C class message
905 // send that's missing the opening '['. Recovery
906 // appropriately. Also take this path if we're performing code
907 // completion after an Objective-C class name.
908 if (getLangOpts().ObjC1 &&
909 ((Tok.is(tok::identifier) && !InMessageExpression) ||
910 Tok.is(tok::code_completion))) {
911 const Token& Next = NextToken();
912 if (Tok.is(tok::code_completion) ||
913 Next.is(tok::colon) || Next.is(tok::r_square))
914 if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
915 if (Typ.get()->isObjCObjectOrInterfaceType()) {
916 // Fake up a Declarator to use with ActOnTypeName.
917 DeclSpec DS(AttrFactory);
918 DS.SetRangeStart(ILoc);
919 DS.SetRangeEnd(ILoc);
920 const char *PrevSpec = nullptr;
922 DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
923 Actions.getASTContext().getPrintingPolicy());
925 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
926 TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
931 Res = ParseObjCMessageExpressionBody(SourceLocation(),
938 // Make sure to pass down the right value for isAddressOfOperand.
939 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
940 isAddressOfOperand = false;
942 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
943 // need to know whether or not this identifier is a function designator or
946 CXXScopeSpec ScopeSpec;
947 SourceLocation TemplateKWLoc;
949 auto Validator = llvm::make_unique<CastExpressionIdValidator>(
950 Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast);
951 Validator->IsAddressOfOperand = isAddressOfOperand;
952 if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
953 Validator->WantExpressionKeywords = false;
954 Validator->WantRemainingKeywords = false;
956 Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren);
958 Name.setIdentifier(&II, ILoc);
959 Res = Actions.ActOnIdExpression(
960 getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
961 isAddressOfOperand, std::move(Validator),
962 /*IsInlineAsmIdentifier=*/false,
963 Tok.is(tok::r_paren) ? nullptr : &Replacement);
964 if (!Res.isInvalid() && !Res.get()) {
965 UnconsumeToken(Replacement);
966 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
967 NotCastExpr, isTypeCast);
971 case tok::char_constant: // constant: character-constant
972 case tok::wide_char_constant:
973 case tok::utf8_char_constant:
974 case tok::utf16_char_constant:
975 case tok::utf32_char_constant:
976 Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
979 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
980 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
981 case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
982 case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
983 case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
984 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
985 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
988 case tok::string_literal: // primary-expression: string-literal
989 case tok::wide_string_literal:
990 case tok::utf8_string_literal:
991 case tok::utf16_string_literal:
992 case tok::utf32_string_literal:
993 Res = ParseStringLiteralExpression(true);
995 case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
996 Res = ParseGenericSelectionExpression();
998 case tok::kw___builtin_va_arg:
999 case tok::kw___builtin_offsetof:
1000 case tok::kw___builtin_choose_expr:
1001 case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1002 case tok::kw___builtin_convertvector:
1003 return ParseBuiltinPrimaryExpression();
1004 case tok::kw___null:
1005 return Actions.ActOnGNUNullExpr(ConsumeToken());
1007 case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1008 case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1009 // C++ [expr.unary] has:
1010 // unary-expression:
1011 // ++ cast-expression
1012 // -- cast-expression
1013 SourceLocation SavedLoc = ConsumeToken();
1014 // One special case is implicitly handled here: if the preceding tokens are
1015 // an ambiguous cast expression, such as "(T())++", then we recurse to
1016 // determine whether the '++' is prefix or postfix.
1017 Res = ParseCastExpression(!getLangOpts().CPlusPlus,
1018 /*isAddressOfOperand*/false, NotCastExpr,
1020 if (!Res.isInvalid())
1021 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1024 case tok::amp: { // unary-expression: '&' cast-expression
1025 // Special treatment because of member pointers
1026 SourceLocation SavedLoc = ConsumeToken();
1027 Res = ParseCastExpression(false, true);
1028 if (!Res.isInvalid())
1029 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1033 case tok::star: // unary-expression: '*' cast-expression
1034 case tok::plus: // unary-expression: '+' cast-expression
1035 case tok::minus: // unary-expression: '-' cast-expression
1036 case tok::tilde: // unary-expression: '~' cast-expression
1037 case tok::exclaim: // unary-expression: '!' cast-expression
1038 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1039 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1040 SourceLocation SavedLoc = ConsumeToken();
1041 Res = ParseCastExpression(false);
1042 if (!Res.isInvalid())
1043 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1047 case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1048 SourceLocation CoawaitLoc = ConsumeToken();
1049 Res = ParseCastExpression(false);
1050 if (!Res.isInvalid())
1051 Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1055 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1056 // __extension__ silences extension warnings in the subexpression.
1057 ExtensionRAIIObject O(Diags); // Use RAII to do this.
1058 SourceLocation SavedLoc = ConsumeToken();
1059 Res = ParseCastExpression(false);
1060 if (!Res.isInvalid())
1061 Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1064 case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1065 if (!getLangOpts().C11)
1066 Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
1068 case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1069 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1070 // unary-expression: '__alignof' '(' type-name ')'
1071 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1072 // unary-expression: 'sizeof' '(' type-name ')'
1073 case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1074 // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1075 case tok::kw___builtin_omp_required_simd_align:
1076 return ParseUnaryExprOrTypeTraitExpression();
1077 case tok::ampamp: { // unary-expression: '&&' identifier
1078 SourceLocation AmpAmpLoc = ConsumeToken();
1079 if (Tok.isNot(tok::identifier))
1080 return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1082 if (getCurScope()->getFnParent() == nullptr)
1083 return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1085 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1086 LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1088 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1092 case tok::kw_const_cast:
1093 case tok::kw_dynamic_cast:
1094 case tok::kw_reinterpret_cast:
1095 case tok::kw_static_cast:
1096 Res = ParseCXXCasts();
1098 case tok::kw_typeid:
1099 Res = ParseCXXTypeid();
1101 case tok::kw___uuidof:
1102 Res = ParseCXXUuidof();
1105 Res = ParseCXXThis();
1108 case tok::annot_typename:
1109 if (isStartOfObjCClassMessageMissingOpenBracket()) {
1110 ParsedType Type = getTypeAnnotation(Tok);
1112 // Fake up a Declarator to use with ActOnTypeName.
1113 DeclSpec DS(AttrFactory);
1114 DS.SetRangeStart(Tok.getLocation());
1115 DS.SetRangeEnd(Tok.getLastLoc());
1117 const char *PrevSpec = nullptr;
1119 DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1120 PrevSpec, DiagID, Type,
1121 Actions.getASTContext().getPrintingPolicy());
1123 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1124 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1129 Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1135 case tok::annot_decltype:
1137 case tok::kw_wchar_t:
1138 case tok::kw_char16_t:
1139 case tok::kw_char32_t:
1144 case tok::kw___int64:
1145 case tok::kw___int128:
1146 case tok::kw_signed:
1147 case tok::kw_unsigned:
1150 case tok::kw_double:
1152 case tok::kw_typename:
1153 case tok::kw_typeof:
1154 case tok::kw___vector: {
1155 if (!getLangOpts().CPlusPlus) {
1156 Diag(Tok, diag::err_expected_expression);
1160 if (SavedKind == tok::kw_typename) {
1161 // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1162 // typename-specifier braced-init-list
1163 if (TryAnnotateTypeOrScopeToken())
1166 if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1167 // We are trying to parse a simple-type-specifier but might not get such
1168 // a token after error recovery.
1172 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1173 // simple-type-specifier braced-init-list
1175 DeclSpec DS(AttrFactory);
1177 ParseCXXSimpleTypeSpecifier(DS);
1178 if (Tok.isNot(tok::l_paren) &&
1179 (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1180 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1181 << DS.getSourceRange());
1183 if (Tok.is(tok::l_brace))
1184 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1186 Res = ParseCXXTypeConstructExpression(DS);
1190 case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1191 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1192 // (We can end up in this situation after tentative parsing.)
1193 if (TryAnnotateTypeOrScopeToken())
1195 if (!Tok.is(tok::annot_cxxscope))
1196 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1197 NotCastExpr, isTypeCast);
1199 Token Next = NextToken();
1200 if (Next.is(tok::annot_template_id)) {
1201 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1202 if (TemplateId->Kind == TNK_Type_template) {
1203 // We have a qualified template-id that we know refers to a
1204 // type, translate it into a type and continue parsing as a
1207 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1208 /*EnteringContext=*/false);
1209 AnnotateTemplateIdTokenAsType();
1210 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1211 NotCastExpr, isTypeCast);
1215 // Parse as an id-expression.
1216 Res = ParseCXXIdExpression(isAddressOfOperand);
1220 case tok::annot_template_id: { // [C++] template-id
1221 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1222 if (TemplateId->Kind == TNK_Type_template) {
1223 // We have a template-id that we know refers to a type,
1224 // translate it into a type and continue parsing as a cast
1226 AnnotateTemplateIdTokenAsType();
1227 return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1228 NotCastExpr, isTypeCast);
1231 // Fall through to treat the template-id as an id-expression.
1234 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1235 Res = ParseCXXIdExpression(isAddressOfOperand);
1238 case tok::coloncolon: {
1239 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1240 // annotates the token, tail recurse.
1241 if (TryAnnotateTypeOrScopeToken())
1243 if (!Tok.is(tok::coloncolon))
1244 return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1246 // ::new -> [C++] new-expression
1247 // ::delete -> [C++] delete-expression
1248 SourceLocation CCLoc = ConsumeToken();
1249 if (Tok.is(tok::kw_new))
1250 return ParseCXXNewExpression(true, CCLoc);
1251 if (Tok.is(tok::kw_delete))
1252 return ParseCXXDeleteExpression(true, CCLoc);
1254 // This is not a type name or scope specifier, it is an invalid expression.
1255 Diag(CCLoc, diag::err_expected_expression);
1259 case tok::kw_new: // [C++] new-expression
1260 return ParseCXXNewExpression(false, Tok.getLocation());
1262 case tok::kw_delete: // [C++] delete-expression
1263 return ParseCXXDeleteExpression(false, Tok.getLocation());
1265 case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1266 Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1267 SourceLocation KeyLoc = ConsumeToken();
1268 BalancedDelimiterTracker T(*this, tok::l_paren);
1270 if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1272 // C++11 [expr.unary.noexcept]p1:
1273 // The noexcept operator determines whether the evaluation of its operand,
1274 // which is an unevaluated operand, can throw an exception.
1275 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1276 ExprResult Result = ParseExpression();
1280 if (!Result.isInvalid())
1281 Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1282 Result.get(), T.getCloseLocation());
1286 #define TYPE_TRAIT(N,Spelling,K) \
1287 case tok::kw_##Spelling:
1288 #include "clang/Basic/TokenKinds.def"
1289 return ParseTypeTrait();
1291 case tok::kw___array_rank:
1292 case tok::kw___array_extent:
1293 return ParseArrayTypeTrait();
1295 case tok::kw___is_lvalue_expr:
1296 case tok::kw___is_rvalue_expr:
1297 return ParseExpressionTrait();
1300 SourceLocation AtLoc = ConsumeToken();
1301 return ParseObjCAtExpression(AtLoc);
1304 Res = ParseBlockLiteralExpression();
1306 case tok::code_completion: {
1307 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1312 if (getLangOpts().CPlusPlus11) {
1313 if (getLangOpts().ObjC1) {
1314 // C++11 lambda expressions and Objective-C message sends both start with a
1315 // square bracket. There are three possibilities here:
1316 // we have a valid lambda expression, we have an invalid lambda
1317 // expression, or we have something that doesn't appear to be a lambda.
1318 // If we're in the last case, we fall back to ParseObjCMessageExpression.
1319 Res = TryParseLambdaExpression();
1320 if (!Res.isInvalid() && !Res.get())
1321 Res = ParseObjCMessageExpression();
1324 Res = ParseLambdaExpression();
1327 if (getLangOpts().ObjC1) {
1328 Res = ParseObjCMessageExpression();
1337 // Check to see whether Res is a function designator only. If it is and we
1338 // are compiling for OpenCL, we need to return an error as this implies
1339 // that the address of the function is being taken, which is illegal in CL.
1341 // These can be followed by postfix-expr pieces.
1342 Res = ParsePostfixExpressionSuffix(Res);
1343 if (getLangOpts().OpenCL)
1344 if (Expr *PostfixExpr = Res.get()) {
1345 QualType Ty = PostfixExpr->getType();
1346 if (!Ty.isNull() && Ty->isFunctionType()) {
1347 Diag(PostfixExpr->getExprLoc(),
1348 diag::err_opencl_taking_function_address_parser);
1356 /// \brief Once the leading part of a postfix-expression is parsed, this
1357 /// method parses any suffixes that apply.
1360 /// postfix-expression: [C99 6.5.2]
1361 /// primary-expression
1362 /// postfix-expression '[' expression ']'
1363 /// postfix-expression '[' braced-init-list ']'
1364 /// postfix-expression '(' argument-expression-list[opt] ')'
1365 /// postfix-expression '.' identifier
1366 /// postfix-expression '->' identifier
1367 /// postfix-expression '++'
1368 /// postfix-expression '--'
1369 /// '(' type-name ')' '{' initializer-list '}'
1370 /// '(' type-name ')' '{' initializer-list ',' '}'
1372 /// argument-expression-list: [C99 6.5.2]
1373 /// argument-expression ...[opt]
1374 /// argument-expression-list ',' assignment-expression ...[opt]
1377 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1378 // Now that the primary-expression piece of the postfix-expression has been
1379 // parsed, see if there are any postfix-expression pieces here.
1382 switch (Tok.getKind()) {
1383 case tok::code_completion:
1384 if (InMessageExpression)
1387 Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1391 case tok::identifier:
1392 // If we see identifier: after an expression, and we're not already in a
1393 // message send, then this is probably a message send with a missing
1394 // opening bracket '['.
1395 if (getLangOpts().ObjC1 && !InMessageExpression &&
1396 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1397 LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1398 ParsedType(), LHS.get());
1402 // Fall through; this isn't a message send.
1404 default: // Not a postfix-expression suffix.
1406 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
1407 // If we have a array postfix expression that starts on a new line and
1408 // Objective-C is enabled, it is highly likely that the user forgot a
1409 // semicolon after the base expression and that the array postfix-expr is
1410 // actually another message send. In this case, do some look-ahead to see
1411 // if the contents of the square brackets are obviously not a valid
1412 // expression and recover by pretending there is no suffix.
1413 if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1414 isSimpleObjCMessageExpression())
1417 // Reject array indices starting with a lambda-expression. '[[' is
1418 // reserved for attributes.
1419 if (CheckProhibitedCXX11Attribute())
1422 BalancedDelimiterTracker T(*this, tok::l_square);
1424 Loc = T.getOpenLocation();
1425 ExprResult Idx, Length;
1426 SourceLocation ColonLoc;
1427 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1428 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1429 Idx = ParseBraceInitializer();
1430 } else if (getLangOpts().OpenMP) {
1431 ColonProtectionRAIIObject RAII(*this);
1432 // Parse [: or [ expr or [ expr :
1433 if (!Tok.is(tok::colon)) {
1435 Idx = ParseExpression();
1437 if (Tok.is(tok::colon)) {
1439 ColonLoc = ConsumeToken();
1440 if (Tok.isNot(tok::r_square))
1441 Length = ParseExpression();
1444 Idx = ParseExpression();
1446 SourceLocation RLoc = Tok.getLocation();
1448 if (!LHS.isInvalid() && !Idx.isInvalid() && !Length.isInvalid() &&
1449 Tok.is(tok::r_square)) {
1450 if (ColonLoc.isValid()) {
1451 LHS = Actions.ActOnOMPArraySectionExpr(LHS.get(), Loc, Idx.get(),
1452 ColonLoc, Length.get(), RLoc);
1454 LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
1458 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1459 (void)Actions.CorrectDelayedTyposInExpr(Idx);
1460 (void)Actions.CorrectDelayedTyposInExpr(Length);
1470 case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
1471 case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
1472 // '(' argument-expression-list[opt] ')'
1473 tok::TokenKind OpKind = Tok.getKind();
1474 InMessageExpressionRAIIObject InMessage(*this, false);
1476 Expr *ExecConfig = nullptr;
1478 BalancedDelimiterTracker PT(*this, tok::l_paren);
1480 if (OpKind == tok::lesslessless) {
1481 ExprVector ExecConfigExprs;
1482 CommaLocsTy ExecConfigCommaLocs;
1483 SourceLocation OpenLoc = ConsumeToken();
1485 if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1486 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1490 SourceLocation CloseLoc;
1491 if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
1492 } else if (LHS.isInvalid()) {
1493 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1495 // There was an error closing the brackets
1496 Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
1497 Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
1498 SkipUntil(tok::greatergreatergreater, StopAtSemi);
1502 if (!LHS.isInvalid()) {
1503 if (ExpectAndConsume(tok::l_paren))
1506 Loc = PrevTokLocation;
1509 if (!LHS.isInvalid()) {
1510 ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1514 if (ECResult.isInvalid())
1517 ExecConfig = ECResult.get();
1521 Loc = PT.getOpenLocation();
1524 ExprVector ArgExprs;
1525 CommaLocsTy CommaLocs;
1527 if (Tok.is(tok::code_completion)) {
1528 Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1533 if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1534 if (Tok.isNot(tok::r_paren)) {
1535 if (ParseExpressionList(ArgExprs, CommaLocs, [&] {
1536 Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs);
1538 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1540 } else if (LHS.isInvalid()) {
1541 for (auto &E : ArgExprs)
1542 Actions.CorrectDelayedTyposInExpr(E);
1548 if (LHS.isInvalid()) {
1549 SkipUntil(tok::r_paren, StopAtSemi);
1550 } else if (Tok.isNot(tok::r_paren)) {
1551 bool HadDelayedTypo = false;
1552 if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
1553 HadDelayedTypo = true;
1554 for (auto &E : ArgExprs)
1555 if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
1556 HadDelayedTypo = true;
1557 // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
1558 // instead of PT.consumeClose() to avoid emitting extra diagnostics for
1559 // the unmatched l_paren.
1561 SkipUntil(tok::r_paren, StopAtSemi);
1566 assert((ArgExprs.size() == 0 ||
1567 ArgExprs.size()-1 == CommaLocs.size())&&
1568 "Unexpected number of commas!");
1569 LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc,
1570 ArgExprs, Tok.getLocation(),
1579 // postfix-expression: p-e '->' template[opt] id-expression
1580 // postfix-expression: p-e '.' template[opt] id-expression
1581 tok::TokenKind OpKind = Tok.getKind();
1582 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
1585 ParsedType ObjectType;
1586 bool MayBePseudoDestructor = false;
1587 if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1588 Expr *Base = LHS.get();
1589 const Type* BaseType = Base->getType().getTypePtrOrNull();
1590 if (BaseType && Tok.is(tok::l_paren) &&
1591 (BaseType->isFunctionType() ||
1592 BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1593 Diag(OpLoc, diag::err_function_is_not_record)
1594 << OpKind << Base->getSourceRange()
1595 << FixItHint::CreateRemoval(OpLoc);
1596 return ParsePostfixExpressionSuffix(Base);
1599 LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1600 OpLoc, OpKind, ObjectType,
1601 MayBePseudoDestructor);
1602 if (LHS.isInvalid())
1605 ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1606 /*EnteringContext=*/false,
1607 &MayBePseudoDestructor);
1608 if (SS.isNotEmpty())
1609 ObjectType = ParsedType();
1612 if (Tok.is(tok::code_completion)) {
1613 // Code completion for a member access expression.
1614 Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1615 OpLoc, OpKind == tok::arrow);
1621 if (MayBePseudoDestructor && !LHS.isInvalid()) {
1622 LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
1627 // Either the action has told us that this cannot be a
1628 // pseudo-destructor expression (based on the type of base
1629 // expression), or we didn't see a '~' in the right place. We
1630 // can still parse a destructor name here, but in that case it
1631 // names a real destructor.
1632 // Allow explicit constructor calls in Microsoft mode.
1633 // FIXME: Add support for explicit call of template constructor.
1634 SourceLocation TemplateKWLoc;
1636 if (getLangOpts().ObjC2 && OpKind == tok::period &&
1637 Tok.is(tok::kw_class)) {
1639 // After a '.' in a member access expression, treat the keyword
1640 // 'class' as if it were an identifier.
1642 // This hack allows property access to the 'class' method because it is
1643 // such a common method name. For other C++ keywords that are
1644 // Objective-C method names, one must use the message send syntax.
1645 IdentifierInfo *Id = Tok.getIdentifierInfo();
1646 SourceLocation Loc = ConsumeToken();
1647 Name.setIdentifier(Id, Loc);
1648 } else if (ParseUnqualifiedId(SS,
1649 /*EnteringContext=*/false,
1650 /*AllowDestructorName=*/true,
1651 /*AllowConstructorName=*/
1652 getLangOpts().MicrosoftExt,
1653 ObjectType, TemplateKWLoc, Name)) {
1654 (void)Actions.CorrectDelayedTyposInExpr(LHS);
1658 if (!LHS.isInvalid())
1659 LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
1660 OpKind, SS, TemplateKWLoc, Name,
1661 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
1665 case tok::plusplus: // postfix-expression: postfix-expression '++'
1666 case tok::minusminus: // postfix-expression: postfix-expression '--'
1667 if (!LHS.isInvalid()) {
1668 LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1669 Tok.getKind(), LHS.get());
1677 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1678 /// vec_step and we are at the start of an expression or a parenthesized
1679 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1680 /// expression (isCastExpr == false) or the type (isCastExpr == true).
1683 /// unary-expression: [C99 6.5.3]
1684 /// 'sizeof' unary-expression
1685 /// 'sizeof' '(' type-name ')'
1686 /// [GNU] '__alignof' unary-expression
1687 /// [GNU] '__alignof' '(' type-name ')'
1688 /// [C11] '_Alignof' '(' type-name ')'
1689 /// [C++0x] 'alignof' '(' type-id ')'
1691 /// [GNU] typeof-specifier:
1692 /// typeof ( expressions )
1693 /// typeof ( type-name )
1694 /// [GNU/C++] typeof unary-expression
1696 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
1697 /// vec_step ( expressions )
1698 /// vec_step ( type-name )
1701 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1704 SourceRange &CastRange) {
1706 assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof,
1707 tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
1708 tok::kw___builtin_omp_required_simd_align) &&
1709 "Not a typeof/sizeof/alignof/vec_step expression!");
1713 // If the operand doesn't start with an '(', it must be an expression.
1714 if (Tok.isNot(tok::l_paren)) {
1715 // If construct allows a form without parenthesis, user may forget to put
1716 // pathenthesis around type name.
1717 if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1718 tok::kw__Alignof)) {
1719 if (isTypeIdUnambiguously()) {
1720 DeclSpec DS(AttrFactory);
1721 ParseSpecifierQualifierList(DS);
1722 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1723 ParseDeclarator(DeclaratorInfo);
1725 SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1726 SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1727 Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1729 << FixItHint::CreateInsertion(LParenLoc, "(")
1730 << FixItHint::CreateInsertion(RParenLoc, ")");
1737 if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1738 Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
1743 Operand = ParseCastExpression(true/*isUnaryExpression*/);
1745 // If it starts with a '(', we know that it is either a parenthesized
1746 // type-name, or it is a unary-expression that starts with a compound
1747 // literal, or starts with a primary-expression that is a parenthesized
1749 ParenParseOption ExprType = CastExpr;
1750 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1752 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1753 false, CastTy, RParenLoc);
1754 CastRange = SourceRange(LParenLoc, RParenLoc);
1756 // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1758 if (ExprType == CastExpr) {
1763 if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1764 // GNU typeof in C requires the expression to be parenthesized. Not so for
1765 // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1766 // the start of a unary-expression, but doesn't include any postfix
1767 // pieces. Parse these now if present.
1768 if (!Operand.isInvalid())
1769 Operand = ParsePostfixExpressionSuffix(Operand.get());
1773 // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1779 /// \brief Parse a sizeof or alignof expression.
1782 /// unary-expression: [C99 6.5.3]
1783 /// 'sizeof' unary-expression
1784 /// 'sizeof' '(' type-name ')'
1785 /// [C++11] 'sizeof' '...' '(' identifier ')'
1786 /// [GNU] '__alignof' unary-expression
1787 /// [GNU] '__alignof' '(' type-name ')'
1788 /// [C11] '_Alignof' '(' type-name ')'
1789 /// [C++11] 'alignof' '(' type-id ')'
1791 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1792 assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof,
1793 tok::kw__Alignof, tok::kw_vec_step,
1794 tok::kw___builtin_omp_required_simd_align) &&
1795 "Not a sizeof/alignof/vec_step expression!");
1799 // [C++11] 'sizeof' '...' '(' identifier ')'
1800 if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1801 SourceLocation EllipsisLoc = ConsumeToken();
1802 SourceLocation LParenLoc, RParenLoc;
1803 IdentifierInfo *Name = nullptr;
1804 SourceLocation NameLoc;
1805 if (Tok.is(tok::l_paren)) {
1806 BalancedDelimiterTracker T(*this, tok::l_paren);
1808 LParenLoc = T.getOpenLocation();
1809 if (Tok.is(tok::identifier)) {
1810 Name = Tok.getIdentifierInfo();
1811 NameLoc = ConsumeToken();
1813 RParenLoc = T.getCloseLocation();
1814 if (RParenLoc.isInvalid())
1815 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1817 Diag(Tok, diag::err_expected_parameter_pack);
1818 SkipUntil(tok::r_paren, StopAtSemi);
1820 } else if (Tok.is(tok::identifier)) {
1821 Name = Tok.getIdentifierInfo();
1822 NameLoc = ConsumeToken();
1823 LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1824 RParenLoc = PP.getLocForEndOfToken(NameLoc);
1825 Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1827 << FixItHint::CreateInsertion(LParenLoc, "(")
1828 << FixItHint::CreateInsertion(RParenLoc, ")");
1830 Diag(Tok, diag::err_sizeof_parameter_pack);
1836 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1837 Sema::ReuseLambdaContextDecl);
1839 return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1840 OpTok.getLocation(),
1845 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1846 Diag(OpTok, diag::warn_cxx98_compat_alignof);
1848 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1849 Sema::ReuseLambdaContextDecl);
1853 SourceRange CastRange;
1854 ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1859 UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1860 if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof))
1861 ExprKind = UETT_AlignOf;
1862 else if (OpTok.is(tok::kw_vec_step))
1863 ExprKind = UETT_VecStep;
1864 else if (OpTok.is(tok::kw___builtin_omp_required_simd_align))
1865 ExprKind = UETT_OpenMPRequiredSimdAlign;
1868 return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1871 CastTy.getAsOpaquePtr(),
1874 if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
1875 Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1877 // If we get here, the operand to the sizeof/alignof was an expresion.
1878 if (!Operand.isInvalid())
1879 Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1887 /// ParseBuiltinPrimaryExpression
1890 /// primary-expression: [C99 6.5.1]
1891 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1892 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1893 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1895 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1896 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
1898 /// [GNU] offsetof-member-designator:
1899 /// [GNU] identifier
1900 /// [GNU] offsetof-member-designator '.' identifier
1901 /// [GNU] offsetof-member-designator '[' expression ']'
1903 ExprResult Parser::ParseBuiltinPrimaryExpression() {
1905 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1907 tok::TokenKind T = Tok.getKind();
1908 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
1910 // All of these start with an open paren.
1911 if (Tok.isNot(tok::l_paren))
1912 return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
1915 BalancedDelimiterTracker PT(*this, tok::l_paren);
1921 default: llvm_unreachable("Not a builtin primary expression!");
1922 case tok::kw___builtin_va_arg: {
1923 ExprResult Expr(ParseAssignmentExpression());
1925 if (ExpectAndConsume(tok::comma)) {
1926 SkipUntil(tok::r_paren, StopAtSemi);
1930 TypeResult Ty = ParseTypeName();
1932 if (Tok.isNot(tok::r_paren)) {
1933 Diag(Tok, diag::err_expected) << tok::r_paren;
1937 if (Expr.isInvalid() || Ty.isInvalid())
1940 Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
1943 case tok::kw___builtin_offsetof: {
1944 SourceLocation TypeLoc = Tok.getLocation();
1945 TypeResult Ty = ParseTypeName();
1946 if (Ty.isInvalid()) {
1947 SkipUntil(tok::r_paren, StopAtSemi);
1951 if (ExpectAndConsume(tok::comma)) {
1952 SkipUntil(tok::r_paren, StopAtSemi);
1956 // We must have at least one identifier here.
1957 if (Tok.isNot(tok::identifier)) {
1958 Diag(Tok, diag::err_expected) << tok::identifier;
1959 SkipUntil(tok::r_paren, StopAtSemi);
1963 // Keep track of the various subcomponents we see.
1964 SmallVector<Sema::OffsetOfComponent, 4> Comps;
1966 Comps.push_back(Sema::OffsetOfComponent());
1967 Comps.back().isBrackets = false;
1968 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1969 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1971 // FIXME: This loop leaks the index expressions on error.
1973 if (Tok.is(tok::period)) {
1974 // offsetof-member-designator: offsetof-member-designator '.' identifier
1975 Comps.push_back(Sema::OffsetOfComponent());
1976 Comps.back().isBrackets = false;
1977 Comps.back().LocStart = ConsumeToken();
1979 if (Tok.isNot(tok::identifier)) {
1980 Diag(Tok, diag::err_expected) << tok::identifier;
1981 SkipUntil(tok::r_paren, StopAtSemi);
1984 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1985 Comps.back().LocEnd = ConsumeToken();
1987 } else if (Tok.is(tok::l_square)) {
1988 if (CheckProhibitedCXX11Attribute())
1991 // offsetof-member-designator: offsetof-member-design '[' expression ']'
1992 Comps.push_back(Sema::OffsetOfComponent());
1993 Comps.back().isBrackets = true;
1994 BalancedDelimiterTracker ST(*this, tok::l_square);
1996 Comps.back().LocStart = ST.getOpenLocation();
1997 Res = ParseExpression();
1998 if (Res.isInvalid()) {
1999 SkipUntil(tok::r_paren, StopAtSemi);
2002 Comps.back().U.E = Res.get();
2005 Comps.back().LocEnd = ST.getCloseLocation();
2007 if (Tok.isNot(tok::r_paren)) {
2010 } else if (Ty.isInvalid()) {
2014 Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2016 PT.getCloseLocation());
2023 case tok::kw___builtin_choose_expr: {
2024 ExprResult Cond(ParseAssignmentExpression());
2025 if (Cond.isInvalid()) {
2026 SkipUntil(tok::r_paren, StopAtSemi);
2029 if (ExpectAndConsume(tok::comma)) {
2030 SkipUntil(tok::r_paren, StopAtSemi);
2034 ExprResult Expr1(ParseAssignmentExpression());
2035 if (Expr1.isInvalid()) {
2036 SkipUntil(tok::r_paren, StopAtSemi);
2039 if (ExpectAndConsume(tok::comma)) {
2040 SkipUntil(tok::r_paren, StopAtSemi);
2044 ExprResult Expr2(ParseAssignmentExpression());
2045 if (Expr2.isInvalid()) {
2046 SkipUntil(tok::r_paren, StopAtSemi);
2049 if (Tok.isNot(tok::r_paren)) {
2050 Diag(Tok, diag::err_expected) << tok::r_paren;
2053 Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2054 Expr2.get(), ConsumeParen());
2057 case tok::kw___builtin_astype: {
2058 // The first argument is an expression to be converted, followed by a comma.
2059 ExprResult Expr(ParseAssignmentExpression());
2060 if (Expr.isInvalid()) {
2061 SkipUntil(tok::r_paren, StopAtSemi);
2065 if (ExpectAndConsume(tok::comma)) {
2066 SkipUntil(tok::r_paren, StopAtSemi);
2070 // Second argument is the type to bitcast to.
2071 TypeResult DestTy = ParseTypeName();
2072 if (DestTy.isInvalid())
2075 // Attempt to consume the r-paren.
2076 if (Tok.isNot(tok::r_paren)) {
2077 Diag(Tok, diag::err_expected) << tok::r_paren;
2078 SkipUntil(tok::r_paren, StopAtSemi);
2082 Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
2086 case tok::kw___builtin_convertvector: {
2087 // The first argument is an expression to be converted, followed by a comma.
2088 ExprResult Expr(ParseAssignmentExpression());
2089 if (Expr.isInvalid()) {
2090 SkipUntil(tok::r_paren, StopAtSemi);
2094 if (ExpectAndConsume(tok::comma)) {
2095 SkipUntil(tok::r_paren, StopAtSemi);
2099 // Second argument is the type to bitcast to.
2100 TypeResult DestTy = ParseTypeName();
2101 if (DestTy.isInvalid())
2104 // Attempt to consume the r-paren.
2105 if (Tok.isNot(tok::r_paren)) {
2106 Diag(Tok, diag::err_expected) << tok::r_paren;
2107 SkipUntil(tok::r_paren, StopAtSemi);
2111 Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
2117 if (Res.isInvalid())
2120 // These can be followed by postfix-expr pieces because they are
2121 // primary-expressions.
2122 return ParsePostfixExpressionSuffix(Res.get());
2125 /// ParseParenExpression - This parses the unit that starts with a '(' token,
2126 /// based on what is allowed by ExprType. The actual thing parsed is returned
2127 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2128 /// not the parsed cast-expression.
2131 /// primary-expression: [C99 6.5.1]
2132 /// '(' expression ')'
2133 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
2134 /// postfix-expression: [C99 6.5.2]
2135 /// '(' type-name ')' '{' initializer-list '}'
2136 /// '(' type-name ')' '{' initializer-list ',' '}'
2137 /// cast-expression: [C99 6.5.4]
2138 /// '(' type-name ')' cast-expression
2139 /// [ARC] bridged-cast-expression
2140 /// [ARC] bridged-cast-expression:
2141 /// (__bridge type-name) cast-expression
2142 /// (__bridge_transfer type-name) cast-expression
2143 /// (__bridge_retained type-name) cast-expression
2144 /// fold-expression: [C++1z]
2145 /// '(' cast-expression fold-operator '...' ')'
2146 /// '(' '...' fold-operator cast-expression ')'
2147 /// '(' cast-expression fold-operator '...'
2148 /// fold-operator cast-expression ')'
2151 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2152 bool isTypeCast, ParsedType &CastTy,
2153 SourceLocation &RParenLoc) {
2154 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2155 ColonProtectionRAIIObject ColonProtection(*this, false);
2156 BalancedDelimiterTracker T(*this, tok::l_paren);
2157 if (T.consumeOpen())
2159 SourceLocation OpenLoc = T.getOpenLocation();
2161 ExprResult Result(true);
2162 bool isAmbiguousTypeId;
2163 CastTy = ParsedType();
2165 if (Tok.is(tok::code_completion)) {
2166 Actions.CodeCompleteOrdinaryName(getCurScope(),
2167 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2168 : Sema::PCC_Expression);
2173 // Diagnose use of bridge casts in non-arc mode.
2174 bool BridgeCast = (getLangOpts().ObjC2 &&
2175 Tok.isOneOf(tok::kw___bridge,
2176 tok::kw___bridge_transfer,
2177 tok::kw___bridge_retained,
2178 tok::kw___bridge_retain));
2179 if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2180 if (!TryConsumeToken(tok::kw___bridge)) {
2181 StringRef BridgeCastName = Tok.getName();
2182 SourceLocation BridgeKeywordLoc = ConsumeToken();
2183 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2184 Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2186 << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2191 // None of these cases should fall through with an invalid Result
2192 // unless they've already reported an error.
2193 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2194 Diag(Tok, diag::ext_gnu_statement_expr);
2196 if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
2197 Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
2199 // Find the nearest non-record decl context. Variables declared in a
2200 // statement expression behave as if they were declared in the enclosing
2201 // function, block, or other code construct.
2202 DeclContext *CodeDC = Actions.CurContext;
2203 while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
2204 CodeDC = CodeDC->getParent();
2205 assert(CodeDC && !CodeDC->isFileContext() &&
2206 "statement expr not in code context");
2208 Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
2210 Actions.ActOnStartStmtExpr();
2212 StmtResult Stmt(ParseCompoundStatement(true));
2213 ExprType = CompoundStmt;
2215 // If the substmt parsed correctly, build the AST node.
2216 if (!Stmt.isInvalid()) {
2217 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation());
2219 Actions.ActOnStmtExprError();
2222 } else if (ExprType >= CompoundLiteral && BridgeCast) {
2223 tok::TokenKind tokenKind = Tok.getKind();
2224 SourceLocation BridgeKeywordLoc = ConsumeToken();
2226 // Parse an Objective-C ARC ownership cast expression.
2227 ObjCBridgeCastKind Kind;
2228 if (tokenKind == tok::kw___bridge)
2230 else if (tokenKind == tok::kw___bridge_transfer)
2231 Kind = OBC_BridgeTransfer;
2232 else if (tokenKind == tok::kw___bridge_retained)
2233 Kind = OBC_BridgeRetained;
2235 // As a hopefully temporary workaround, allow __bridge_retain as
2236 // a synonym for __bridge_retained, but only in system headers.
2237 assert(tokenKind == tok::kw___bridge_retain);
2238 Kind = OBC_BridgeRetained;
2239 if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2240 Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2241 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2242 "__bridge_retained");
2245 TypeResult Ty = ParseTypeName();
2247 ColonProtection.restore();
2248 RParenLoc = T.getCloseLocation();
2249 ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2251 if (Ty.isInvalid() || SubExpr.isInvalid())
2254 return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2255 BridgeKeywordLoc, Ty.get(),
2256 RParenLoc, SubExpr.get());
2257 } else if (ExprType >= CompoundLiteral &&
2258 isTypeIdInParens(isAmbiguousTypeId)) {
2260 // Otherwise, this is a compound literal expression or cast expression.
2262 // In C++, if the type-id is ambiguous we disambiguate based on context.
2263 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2264 // in which case we should treat it as type-id.
2265 // if stopIfCastExpr is false, we need to determine the context past the
2266 // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2267 if (isAmbiguousTypeId && !stopIfCastExpr) {
2268 ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
2270 RParenLoc = T.getCloseLocation();
2274 // Parse the type declarator.
2275 DeclSpec DS(AttrFactory);
2276 ParseSpecifierQualifierList(DS);
2277 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2278 ParseDeclarator(DeclaratorInfo);
2280 // If our type is followed by an identifier and either ':' or ']', then
2281 // this is probably an Objective-C message send where the leading '[' is
2282 // missing. Recover as if that were the case.
2283 if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2284 !InMessageExpression && getLangOpts().ObjC1 &&
2285 (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2288 InMessageExpressionRAIIObject InMessage(*this, false);
2289 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2291 Result = ParseObjCMessageExpressionBody(SourceLocation(),
2297 ColonProtection.restore();
2298 RParenLoc = T.getCloseLocation();
2299 if (Tok.is(tok::l_brace)) {
2300 ExprType = CompoundLiteral;
2303 InMessageExpressionRAIIObject InMessage(*this, false);
2304 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2306 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2309 if (ExprType == CastExpr) {
2310 // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2312 if (DeclaratorInfo.isInvalidType())
2315 // Note that this doesn't parse the subsequent cast-expression, it just
2316 // returns the parsed type to the callee.
2317 if (stopIfCastExpr) {
2320 InMessageExpressionRAIIObject InMessage(*this, false);
2321 Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2324 return ExprResult();
2327 // Reject the cast of super idiom in ObjC.
2328 if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2329 Tok.getIdentifierInfo() == Ident_super &&
2330 getCurScope()->isInObjcMethodScope() &&
2331 GetLookAheadToken(1).isNot(tok::period)) {
2332 Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2333 << SourceRange(OpenLoc, RParenLoc);
2337 // Parse the cast-expression that follows it next.
2338 // TODO: For cast expression with CastTy.
2339 Result = ParseCastExpression(/*isUnaryExpression=*/false,
2340 /*isAddressOfOperand=*/false,
2341 /*isTypeCast=*/IsTypeCast);
2342 if (!Result.isInvalid()) {
2343 Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2344 DeclaratorInfo, CastTy,
2345 RParenLoc, Result.get());
2350 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2353 } else if (Tok.is(tok::ellipsis) &&
2354 isFoldOperator(NextToken().getKind())) {
2355 return ParseFoldExpression(ExprResult(), T);
2356 } else if (isTypeCast) {
2357 // Parse the expression-list.
2358 InMessageExpressionRAIIObject InMessage(*this, false);
2360 ExprVector ArgExprs;
2361 CommaLocsTy CommaLocs;
2363 if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2364 // FIXME: If we ever support comma expressions as operands to
2365 // fold-expressions, we'll need to allow multiple ArgExprs here.
2366 if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) &&
2367 NextToken().is(tok::ellipsis))
2368 return ParseFoldExpression(Result, T);
2370 ExprType = SimpleExpr;
2371 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2375 InMessageExpressionRAIIObject InMessage(*this, false);
2377 Result = ParseExpression(MaybeTypeCast);
2378 if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) {
2379 // Correct typos in non-C++ code earlier so that implicit-cast-like
2380 // expressions are parsed correctly.
2381 Result = Actions.CorrectDelayedTyposInExpr(Result);
2383 ExprType = SimpleExpr;
2385 if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis))
2386 return ParseFoldExpression(Result, T);
2388 // Don't build a paren expression unless we actually match a ')'.
2389 if (!Result.isInvalid() && Tok.is(tok::r_paren))
2391 Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
2395 if (Result.isInvalid()) {
2396 SkipUntil(tok::r_paren, StopAtSemi);
2401 RParenLoc = T.getCloseLocation();
2405 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2406 /// and we are at the left brace.
2409 /// postfix-expression: [C99 6.5.2]
2410 /// '(' type-name ')' '{' initializer-list '}'
2411 /// '(' type-name ')' '{' initializer-list ',' '}'
2414 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2415 SourceLocation LParenLoc,
2416 SourceLocation RParenLoc) {
2417 assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2418 if (!getLangOpts().C99) // Compound literals don't exist in C90.
2419 Diag(LParenLoc, diag::ext_c99_compound_literal);
2420 ExprResult Result = ParseInitializer();
2421 if (!Result.isInvalid() && Ty)
2422 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
2426 /// ParseStringLiteralExpression - This handles the various token types that
2427 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
2428 /// translation phase #6].
2431 /// primary-expression: [C99 6.5.1]
2434 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2435 assert(isTokenStringLiteral() && "Not a string literal!");
2437 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
2438 // considered to be strings for concatenation purposes.
2439 SmallVector<Token, 4> StringToks;
2442 StringToks.push_back(Tok);
2443 ConsumeStringToken();
2444 } while (isTokenStringLiteral());
2446 // Pass the set of string tokens, ready for concatenation, to the actions.
2447 return Actions.ActOnStringLiteral(StringToks,
2448 AllowUserDefinedLiteral ? getCurScope()
2452 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
2456 /// generic-selection:
2457 /// _Generic ( assignment-expression , generic-assoc-list )
2458 /// generic-assoc-list:
2459 /// generic-association
2460 /// generic-assoc-list , generic-association
2461 /// generic-association:
2462 /// type-name : assignment-expression
2463 /// default : assignment-expression
2465 ExprResult Parser::ParseGenericSelectionExpression() {
2466 assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2467 SourceLocation KeyLoc = ConsumeToken();
2469 if (!getLangOpts().C11)
2470 Diag(KeyLoc, diag::ext_c11_generic_selection);
2472 BalancedDelimiterTracker T(*this, tok::l_paren);
2473 if (T.expectAndConsume())
2476 ExprResult ControllingExpr;
2478 // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2480 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2482 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
2483 if (ControllingExpr.isInvalid()) {
2484 SkipUntil(tok::r_paren, StopAtSemi);
2489 if (ExpectAndConsume(tok::comma)) {
2490 SkipUntil(tok::r_paren, StopAtSemi);
2494 SourceLocation DefaultLoc;
2499 if (Tok.is(tok::kw_default)) {
2500 // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2501 // generic association."
2502 if (!DefaultLoc.isInvalid()) {
2503 Diag(Tok, diag::err_duplicate_default_assoc);
2504 Diag(DefaultLoc, diag::note_previous_default_assoc);
2505 SkipUntil(tok::r_paren, StopAtSemi);
2508 DefaultLoc = ConsumeToken();
2511 ColonProtectionRAIIObject X(*this);
2512 TypeResult TR = ParseTypeName();
2513 if (TR.isInvalid()) {
2514 SkipUntil(tok::r_paren, StopAtSemi);
2519 Types.push_back(Ty);
2521 if (ExpectAndConsume(tok::colon)) {
2522 SkipUntil(tok::r_paren, StopAtSemi);
2526 // FIXME: These expressions should be parsed in a potentially potentially
2527 // evaluated context.
2529 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()));
2530 if (ER.isInvalid()) {
2531 SkipUntil(tok::r_paren, StopAtSemi);
2534 Exprs.push_back(ER.get());
2535 } while (TryConsumeToken(tok::comma));
2538 if (T.getCloseLocation().isInvalid())
2541 return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2542 T.getCloseLocation(),
2543 ControllingExpr.get(),
2547 /// \brief Parse A C++1z fold-expression after the opening paren and optional
2548 /// left-hand-side expression.
2551 /// fold-expression:
2552 /// ( cast-expression fold-operator ... )
2553 /// ( ... fold-operator cast-expression )
2554 /// ( cast-expression fold-operator ... fold-operator cast-expression )
2555 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
2556 BalancedDelimiterTracker &T) {
2557 if (LHS.isInvalid()) {
2562 tok::TokenKind Kind = tok::unknown;
2563 SourceLocation FirstOpLoc;
2564 if (LHS.isUsable()) {
2565 Kind = Tok.getKind();
2566 assert(isFoldOperator(Kind) && "missing fold-operator");
2567 FirstOpLoc = ConsumeToken();
2570 assert(Tok.is(tok::ellipsis) && "not a fold-expression");
2571 SourceLocation EllipsisLoc = ConsumeToken();
2574 if (Tok.isNot(tok::r_paren)) {
2575 if (!isFoldOperator(Tok.getKind()))
2576 return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
2578 if (Kind != tok::unknown && Tok.getKind() != Kind)
2579 Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
2580 << SourceRange(FirstOpLoc);
2581 Kind = Tok.getKind();
2584 RHS = ParseExpression();
2585 if (RHS.isInvalid()) {
2591 Diag(EllipsisLoc, getLangOpts().CPlusPlus1z
2592 ? diag::warn_cxx14_compat_fold_expression
2593 : diag::ext_fold_expression);
2596 return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind,
2597 EllipsisLoc, RHS.get(), T.getCloseLocation());
2600 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2603 /// argument-expression-list:
2604 /// assignment-expression
2605 /// argument-expression-list , assignment-expression
2607 /// [C++] expression-list:
2608 /// [C++] assignment-expression
2609 /// [C++] expression-list , assignment-expression
2611 /// [C++0x] expression-list:
2612 /// [C++0x] initializer-list
2614 /// [C++0x] initializer-list
2615 /// [C++0x] initializer-clause ...[opt]
2616 /// [C++0x] initializer-list , initializer-clause ...[opt]
2618 /// [C++0x] initializer-clause:
2619 /// [C++0x] assignment-expression
2620 /// [C++0x] braced-init-list
2622 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
2623 SmallVectorImpl<SourceLocation> &CommaLocs,
2624 std::function<void()> Completer) {
2625 bool SawError = false;
2627 if (Tok.is(tok::code_completion)) {
2631 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2637 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2638 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2639 Expr = ParseBraceInitializer();
2641 Expr = ParseAssignmentExpression();
2643 if (Tok.is(tok::ellipsis))
2644 Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2645 if (Expr.isInvalid()) {
2646 SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
2649 Exprs.push_back(Expr.get());
2652 if (Tok.isNot(tok::comma))
2654 // Move to the next argument, remember where the comma was.
2655 CommaLocs.push_back(ConsumeToken());
2658 // Ensure typos get diagnosed when errors were encountered while parsing the
2660 for (auto &E : Exprs) {
2661 ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E);
2662 if (Expr.isUsable()) E = Expr.get();
2668 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2669 /// used for misc language extensions.
2672 /// simple-expression-list:
2673 /// assignment-expression
2674 /// simple-expression-list , assignment-expression
2677 Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2678 SmallVectorImpl<SourceLocation> &CommaLocs) {
2680 ExprResult Expr = ParseAssignmentExpression();
2681 if (Expr.isInvalid())
2684 Exprs.push_back(Expr.get());
2686 if (Tok.isNot(tok::comma))
2689 // Move to the next argument, remember where the comma was.
2690 CommaLocs.push_back(ConsumeToken());
2694 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2697 /// [clang] block-id:
2698 /// [clang] specifier-qualifier-list block-declarator
2700 void Parser::ParseBlockId(SourceLocation CaretLoc) {
2701 if (Tok.is(tok::code_completion)) {
2702 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2703 return cutOffParsing();
2706 // Parse the specifier-qualifier-list piece.
2707 DeclSpec DS(AttrFactory);
2708 ParseSpecifierQualifierList(DS);
2710 // Parse the block-declarator.
2711 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2712 ParseDeclarator(DeclaratorInfo);
2714 MaybeParseGNUAttributes(DeclaratorInfo);
2716 // Inform sema that we are starting a block.
2717 Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2720 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2721 /// like ^(int x){ return x+1; }
2725 /// [clang] '^' block-args[opt] compound-statement
2726 /// [clang] '^' block-id compound-statement
2727 /// [clang] block-args:
2728 /// [clang] '(' parameter-list ')'
2730 ExprResult Parser::ParseBlockLiteralExpression() {
2731 assert(Tok.is(tok::caret) && "block literal starts with ^");
2732 SourceLocation CaretLoc = ConsumeToken();
2734 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2735 "block literal parsing");
2737 // Enter a scope to hold everything within the block. This includes the
2738 // argument decls, decls within the compound expression, etc. This also
2739 // allows determining whether a variable reference inside the block is
2740 // within or outside of the block.
2741 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2744 // Inform sema that we are starting a block.
2745 Actions.ActOnBlockStart(CaretLoc, getCurScope());
2747 // Parse the return type if present.
2748 DeclSpec DS(AttrFactory);
2749 Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2750 // FIXME: Since the return type isn't actually parsed, it can't be used to
2751 // fill ParamInfo with an initial valid range, so do it manually.
2752 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2754 // If this block has arguments, parse them. There is no ambiguity here with
2755 // the expression case, because the expression case requires a parameter list.
2756 if (Tok.is(tok::l_paren)) {
2757 ParseParenDeclarator(ParamInfo);
2758 // Parse the pieces after the identifier as if we had "int(...)".
2759 // SetIdentifier sets the source range end, but in this case we're past
2761 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2762 ParamInfo.SetIdentifier(nullptr, CaretLoc);
2763 ParamInfo.SetRangeEnd(Tmp);
2764 if (ParamInfo.isInvalidType()) {
2765 // If there was an error parsing the arguments, they may have
2766 // tried to use ^(x+y) which requires an argument list. Just
2767 // skip the whole block literal.
2768 Actions.ActOnBlockError(CaretLoc, getCurScope());
2772 MaybeParseGNUAttributes(ParamInfo);
2774 // Inform sema that we are starting a block.
2775 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2776 } else if (!Tok.is(tok::l_brace)) {
2777 ParseBlockId(CaretLoc);
2779 // Otherwise, pretend we saw (void).
2780 ParsedAttributes attrs(AttrFactory);
2781 SourceLocation NoLoc;
2782 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2783 /*IsAmbiguous=*/false,
2784 /*RParenLoc=*/NoLoc,
2785 /*ArgInfo=*/nullptr,
2787 /*EllipsisLoc=*/NoLoc,
2788 /*RParenLoc=*/NoLoc,
2790 /*RefQualifierIsLvalueRef=*/true,
2791 /*RefQualifierLoc=*/NoLoc,
2792 /*ConstQualifierLoc=*/NoLoc,
2793 /*VolatileQualifierLoc=*/NoLoc,
2794 /*RestrictQualifierLoc=*/NoLoc,
2795 /*MutableLoc=*/NoLoc,
2797 /*ESpecRange=*/SourceRange(),
2798 /*Exceptions=*/nullptr,
2799 /*ExceptionRanges=*/nullptr,
2800 /*NumExceptions=*/0,
2801 /*NoexceptExpr=*/nullptr,
2802 /*ExceptionSpecTokens=*/nullptr,
2807 MaybeParseGNUAttributes(ParamInfo);
2809 // Inform sema that we are starting a block.
2810 Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2814 ExprResult Result(true);
2815 if (!Tok.is(tok::l_brace)) {
2816 // Saw something like: ^expr
2817 Diag(Tok, diag::err_expected_expression);
2818 Actions.ActOnBlockError(CaretLoc, getCurScope());
2822 StmtResult Stmt(ParseCompoundStatementBody());
2824 if (!Stmt.isInvalid())
2825 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
2827 Actions.ActOnBlockError(CaretLoc, getCurScope());
2831 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2835 ExprResult Parser::ParseObjCBoolLiteral() {
2836 tok::TokenKind Kind = Tok.getKind();
2837 return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);